hanumanDev
hanumanDev

Reputation: 6614

How to search from a UISearchBar using a URL

I'm trying to search directly from the UISearchBar. I'm having problems with this and was wondering if there are any tutorials that cover this or if someone could help. here's my code:

-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    if ([searchText length] == 0) {
        [displayItems removeAllObjects];

    } else {
        [displayItems removeAllObjects];

        NSString *url=[NSString stringWithFormat:@"http://xml.customweather.com/xml?client=clinique_test&client_password=f@c3$toF&product=search&search=%@",searchBar.text];
        NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];

        }
    }

    // reload the table data
    [self.tableView reloadData];
} 

Upvotes: 2

Views: 2980

Answers (2)

Paras Joshi
Paras Joshi

Reputation: 20541

Here from your code you use URLConnection with every character change in UISearchBar so it will not work perfect for you.

NOTE

Here you want to get data from web-server then here send request for that after you enter whole string in textfield of UISearchBar .. like in searchBarSearchButtonClicked method.

//RootViewController.m
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {

   [self searchTableView];
   [searchTableView reloadData];
}

- (void) searchTableView {

    NSString *url = [NSString stringWithFormat:@"http://xml.customweather.com/xml?client=clinique_test&client_password=f@c3$toF&product=search&search=%@",searchBar.text];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
}

Upvotes: 0

laxonline
laxonline

Reputation: 2653

try this

 - (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];
}

Connection delegate methods

#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];

}

Upvotes: 3

Related Questions