无法使用 AFNetworking 3.0 从异步块获得响应

Can't get response from async block using AFNetworking 3.0

我是 IOS 开发的新手,所以我可能只是缺少一些基础知识。已经为这个问题苦苦挣扎了2天。 所以,就在这里。 我的 API class:

中有一个数据任务
//request generation, putting url and dictionary into it

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if(!error)
    {
        self.jsonDictionary = responseObject;
        NSInteger HTTPStatusCode = [(NSHTTPURLResponse *)response statusCode];
        NSLog(@"RESPONSE DATA:  %@", self.jsonDictionary);
        self.didSendRequest = YES;
    }
    else
    {
        self.didSendRequest = NO;
        NSLog(@"ERROR:  %@", error);
    }
}];
[dataTask resume];

然后像这样检索 json 字典:

-(NSDictionary *)returnJSON{
if(self.didSendRequest) return self.jsonDictionary;
else NSLog(@"No dictionary dowloaded");
return self.jsonDictionary;}

然后,在其他 class 中,我将 url 和字典传递给数据任务方法,并得到如下响应:

-(NSDictionary*)userLogin : (NSString* )email : (NSString*) password {
dataTaskClass* aph = [[dataTaskClass alloc] init];

NSDictionary *userParams = [[NSDictionary alloc] initWithObjectsAndKeys:
                            email,@"email",
                            password,@"password",
                            nil];
[aph postRequest: @"myUrl"];
return dataTaskClass.returnJSON;}

最后我在我的视图控制器中调用它 class 像这样:

    //button click method here
response = [lh userLogin : userEmail : userPass];
            if (response) {//do some action}

所以,是的,如您所见,我调用了一个方法,该方法然后异步执行下载任务,然后我立即检查 return 值,当然是 "null" . 那么我如何将 return 值与 dataTask 同步,或者以任何其他方式检查它是否完成?

已经尝试了愚蠢的 "while loop" 和信号量方法,正如预期的那样,它们都挂在了主线程上。 尝试了一些带有通知的东西,但最终一无所获。

我很确定它有一个该死的简单解决方案,但无法实现。

很乐意提供任何帮助。

是的,您缺少一些基础知识。

您不能调用异步操作的方法并期望立即得到答复。解决方案是编写获取完成块的方法。然后在完成块中传递要执行的代码。该方法在结果可用之前立即调用 returns,但一旦下载任务完成,就会调用完成块代码。

我写了一个包含示例应用程序的 SO 答案,但它是用 Swift 编写的。如果您是 iOS 开发的新手并且正在 Objective-C 工作,您可能会发现很难理解。

如果您刚刚学习 iOS 开发,您应该认真考虑学习 Swift。 Apple 明确表示 Swift 是 iOS 发展的未来。学习 Objective-C 也很有用,但我建议您将注意力放在 Swift.