尝试这个
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSString *trimDot = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([trimDot isEqualToString:@"."]) {
return YES;
}
if(connection){
[connection cancel];
}
NSString *appendStr;
if([text length] == 0)
{
NSRange rangemak = NSMakeRange(0, [searchbar.text length]-1);
appendStr = [searchbar.text substringWithRange:rangemak];
}
else
{
appendStr = [NSString stringWithFormat:@"%@%@",searchbar.text,text];
}
[self performSelector:@selector(callSearchWebService:) withObject:appendStr];
[activityindicator startAnimating];
return YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
[self performSelector:@selector(callSearchWebService:) withObject:searchBar.text];
searchBar.showsCancelButton=NO;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self performSelector:@selector(callSearchWebService:) withObject:searchBar.text];
[searchBar resignFirstResponder];
}
-(void)callSearchWebService:(NSString*)searchStr
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
NSString *str =@"";
if ([searchStr length] != 0 ) str = searchStr;
NSString *url = [NSString stringWithFormat:@"%@/%d/%d/%@/",ListoutForSearcing_server,minRecords,maxRecords,str];
[request setURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// Create Connection.
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
JsonResponseData = [NSMutableData data] ;
NSLog( @"Data will be received from URL: %@", request.URL );
}
else
{// The download could not be made.
NSLog( @"Data could not be received from: %@", request.URL );
}
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
HUD.delegate = self;
HUD.labelText = @"Loading";
[HUD show:YES];
}
连接委托方法
#pragma mark Connection delegate methods.
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[JsonResponseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[JsonResponseData appendData:data];
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error
{
UIAlertView *alertError=[[UIAlertView alloc]initWithTitle:@"Message" message:@"Network Problem." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alertError show];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
receivedString = [[NSString alloc] initWithData:JsonResponseData
encoding:NSASCIIStringEncoding];
RecievedDataDict=[[NSMutableDictionary alloc]init];
}