現在、iPhone アプリの 1 つで 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]];
}
このコードにより、サーバーからの応答を待ち、先に進むことができます。それは本当に私の問題を解決したように見えましたが、これが呼び出しを行う良い方法であるかどうかはわかりません. もしそうなら、コードを共通に保ち、アプリケーション全体で使用できる優れた設計原則はありますか?
ありがとうございました