2014-09-28 106 views
0

我有一個應用程序需要使用AFNetworking,我遇到了異步操作的問題。我知道這裏有很多類似的問題,但我還沒有找到我的問題的答案。等待AFNetworking操作登錄

應用程序調用的登錄方法 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

這種方法看起來是這樣的:

- (void)loginWithUsername:(NSString *)username password:(NSString *)password { 
    url = [NSURL URLWithString:@"Users/Login/" relativeToURL:baseURL]; 
    NSDictionary *parameters = @{UsernameParameter: username, PasswordParameter: password}; 
    [requestManager GET:url.absoluteString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { 
     user = [[User alloc] initWithServerResponse:responseObject]; 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(error.description); 
    }]; 
} 

響應包含一對夫婦的授權令牌所必需的所有其他呼叫遠程API的。問題在於,在收到登錄響應並執行成功或失敗塊之前,其他操作正在執行。因此,當應用程序試圖再次調用API時,該應用程序崩潰(或者,如果我檢查無用戶,則不執行任何操作)。在繼續之前確保接收登錄響應的最佳方法是什麼?

謝謝。

回答

0

在用戶的登錄呼叫之後(在該塊中)做另一個遠程API的調用。
例如

NSDictionary *parameters = @{UsernameParameter: username, PasswordParameter: password}; 
[requestManager GET:url.absoluteString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    user = [[User alloc] initWithServerResponse:responseObject]; 
    ///insert another remote api here. 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(error.description); 

    ///warnning for error. 
}]; 
+0

我決定在我看到您的建議之前再試一次。這似乎有伎倆。第一次嘗試時它沒有工作,所以我第一次肯定有錯誤。謝謝。 – 2014-09-28 04:43:20