Closed. This question is opinion-based。它当前不接受答案。
                        
                    
                
            
        
            
        
                
                    
                
            
                
                    想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。
                
                    5年前关闭。
            
        

    

我当前在我的一个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]];
}


有了这段代码,我就可以等待服务器返回响应,并且可以继续进行下去。看来确实可以解决我的问题,但是不确定这是否是拨打电话的好方法。如果是这样,是否有一个良好的设计原则,在这里我可以保持代码通用并在整个应用程序中使用它。

谢谢

最佳答案

切勿阻塞主(UI)线程。也就是说,永远不要同步进行网络连接。

在整个请求加载期间,您的应用程序似乎已冻结-完全不响应触摸和系统事件,直到请求完成为止。

至少要显示一个加载模态,该模态在请求完成之前不会消失。更好的是,使其尽可能使用户可以在加载请求时正常交互应用程序。

从技术上讲,您在这里拥有的东西可能会起作用,但是对于实际应用而言,这是不可接受的。

关于iphone - 同步AFNetworking调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16577438/

10-12 00:19
查看更多