我目前在我的一个iPhone应用程序中使用AFNetworking。它真的是一个进行异步调用的方便的库。然而,在我的应用程序中,我遇到了需要从服务器获取数据才能向前移动的情况。所以我想用这种方式等待回复。
MyAFNetworkClient *httpClient = [MyAFNetworkClient sharedClient];
NSURLRequest *request = [httpClient requestWithMethod:@"GET" path:path parameters:nil];
__block int status = 0;
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:JSON];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
@throw error.userInfo;
status = 2;
NSLog(@"Error... Status Code 2");
}];
[httpClient enqueueHTTPRequestOperation:operation];
[httpClient.operationQueue waitUntilAllOperationsAreFinished];
while (status == 0)
{
// run runloop so that async dispatch can be handled on main thread AFTER the operation has
// been marked as finished (even though the call backs haven't finished yet).
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate date]];
}有了这段代码,我就能够等待从服务器返回的响应,并能够继续进行下去。这似乎真的解决了我的问题,但是,我不确定这是不是一个打电话的好方法。如果是这样,有没有一个好的设计原则,让我可以保持代码的通用性,并在我的应用程序中使用它。
谢谢
发布于 2013-05-24 00:08:33
永远不要阻塞主(UI)线程。这就是说,永远不要同步地做网络。
在请求加载的整个过程中,您的应用程序似乎已经冻结-完全不响应触摸和系统事件,直到请求完成。
至少,显示一个在请求完成之前不会被忽略的加载模式。更好的是,如果可能的话,让用户可以在请求加载时正常地与应用程序交互。
从技术上讲,您所拥有的可能是可行的,但是对于实际的应用程序来说,这是不可接受的。
发布于 2013-05-26 07:47:04
对于遇到与您进行异步调用相同的情况并希望等待数据返回到主线程以执行其他操作的所有人来说,这可能会有一些帮助
场景:
用户身份验证:用户输入用户名、密码并尝试登录。
Solution:向他们展示加载模式,告诉他们幕后正在发生的事情,一旦你得到响应,你就可以继续主线程,如下所示。
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
// perform next steps....
});
}感谢@matt关于在这种情况下需要做什么的提示。
https://stackoverflow.com/questions/16577438
复制相似问题