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:
- JSON parsing (I could parse XML, but why?! JSON is way better!)
- HTTP Request (you can use AFNetworking instead of what I've done above)
- Asynchronous HTTP requests (do not block main thread)
- GCD (the
dispatch_async
stuff)
- Delegates (in this case for UITextField)
Performance update
- when checking if the size is bigger than 3 chars, you can even only make HTTP request every 2/3 chars, let's say, only request if
length % 3
.
I suggest you read something about those