I am new to ios programming, need to implement something like a google search box i.e., autofill text field. My scenario is as follow 1.when user type in text field 2.background call to webservice for data(request data= text field data).
for example:- if user type "abc" in text field request data for web service call should be "abc" and web service gives response on that. Now next time user type "d" i.e textfield contains "abcd" service response must consider the appended text.(something like google search field) 3.web service call should be Asynchronous. 4.response should be displayed in drop down list.
Is it possible in ios??? Any tutorial or example would be appreciated. Thanks in advance.
I will assume you are talking about a Restful webservice and NOT SOAP, for the love of god!
Yes, of course it is possible. You can follow this approach, I could use an HTTP lib such as AFNetworking to make the request but for the sake of simplicity I'm just init'ing the NSData with the contents of URL on background and updating UI on main thread using GCD.
Set your UITextField delegate to the ViewController you are working on viewDidLoad:
method
textField.delegate = self;
override the UITextField
delegate method textField:shouldChangeCharactersInRange:replacementString:
with:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// To increase performance I advise you to only make the http request on a string bigger than 3,4 chars, and only invoke it
if( textField.text.length + string.length - range.length > 3) // lets say 3 chars mininum
{
// call an asynchronous HTTP request
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL * url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http:/example.com/search?q=%@", textField.text]];
NSData * results = [NSData dataWithContentsOfURL:url];
NSArray * parsedResults = [NSJSONSerialization JSONObjectWithData: results options: NSJSONReadingMutableContainers error: nil];
// TODO: with this NSData, you can parse your values - XML/JSON
dispatch_sync(dispatch_get_main_queue(), ^{
// TODO: And update your UI on the main thread
// let's say you update an array with the results and reload your UITableView
self.resultsArrayForTable = parsedResults;
[tableView reloadData];
});
});
}
return YES; // this is the default return, means "Yes, you can append that char that you are writing
// you can limit the field size here by returning NO when a limit is reached
}
As you can see there are a list of concepts that you need to get used to:
dispatch_async
stuff)Performance update
length % 3
.I suggest you read something about those
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With