2
我想在我的应用程序中自动填充UITextFiled。在用户输入某个字母时,它会调用Web服务并在UIpPickerView中显示响应,以便搜索城市。当我们输入任何字母时,会显示一些城市名称。任何人都可以知道如何去做?请帮帮我。如何在iPhone中使用异步Web服务调用自动完成TextField?
我想在我的应用程序中自动填充UITextFiled。在用户输入某个字母时,它会调用Web服务并在UIpPickerView中显示响应,以便搜索城市。当我们输入任何字母时,会显示一些城市名称。任何人都可以知道如何去做?请帮帮我。如何在iPhone中使用异步Web服务调用自动完成TextField?
从服务器获取数据不同步,你可以使用NSURLConnection
和NSURLConnectionDelegate
方法
在接口文件:
@interface ViewController : UIViewController<NSURLConnectionDelegate, UITextFieldDelegate> {
NSMutableData *mutableData;
}
-(void)getDataUsingText:(NSString *)text;
@end
在实现文件:
@implementation ViewController
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *value =[textField.text stringByReplacingCharactersInRange:range withString:string];
[self getDataUsingText:value];
return YES;
}
-(void)getDataUsingText:(NSString *)text;
{
NSString *urlString = [NSString stringWithFormat:@"http://...."];
NSURL *url =[NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
mutableData = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *dataString = [[NSString alloc] initWithData:mutableData encoding:NSUTF8StringEncoding];
NSLog(@"your data from server: %@", dataString);
// Here you got the data from server asynchronously.
// Here you can parse the string and reload the picker view using [picker reloadAllComponents];
}
@end
必须委托设为文本字段,您必须使用NSURLConnectionDelegate
方法中的数据实现选取器。而this是加载选取器视图的教程。
非常感谢.. :)我得到了你的解决方案...... :) – python 2012-08-14 03:35:39