我有以下类,它异步发出 HTTP 发布请求以避免主 UI 线程上的问题:
@implementation DataFeeder
-(void) doLookup:(NSString *)inputValue
{
NSString *myRequestString = [NSString stringWithFormat:@"val=%@", inputValue];
NSMutableData *myRequestData = [ NSMutableData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
NSURL * myUrl = [NSURL URLWithString: @"http://mywebsite/results.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: myUrl];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: myRequestData];
[request setTimeoutInterval:10.0];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Show error message
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Use responseData
// Got all my response data here, so build up an object ready to send back
}
@end
我正在ViewController
使用以下代码行调用上述内容:
MyObject * myObj = [feeder doLookup:@"SomeStaticStringForNow"];
所以,这就是我的理解:
- 将
doLookup
在异步连接上执行请求。 - 当数据已完全加载时,它将调用
connectionDidFinishLoading
- 数据加载完成后,我将从响应数据构建一个对象,并将其发送回调用控制器
我怎样才能让调用控制器监听这个?我是否需要在 ViewController 中实现自己的回调方法来监听调用,然后停止微调器并根据内容更新 UI myObj
?
我希望有一个我忽略的非常简单的方法......
谢谢