AFNetworking 2.0:AFHTTPRequestOperationManager异步方法调用

时间:2013-11-18 22:02:44

标签: ios objective-c afnetworking afnetworking-2

我使用AFNetworking 2.0进行应用程序的联网,我已经实现了一种方法来检查用户的登录信息

-(NSString *) loginWith : (NSString *) email andPassword :(NSString *) password
{
    __block NSString * result ;

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSDictionary *params = @{@"email": email, @"password": password};

    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    [manager POST:[kROOT_URL stringByAppendingString:@"auth/"] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSLog(@"JSON: %@", (NSDictionary*)responseObject);

        [[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:USER_KEY];
        [[NSUserDefaults standardUserDefaults] synchronize];

        result = [responseObject objectForKey:@"id"];
        NSLog(@"result :: %@",result);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSLog(@"Error: %@", error);

        result = nil;

    }];

    return result;
}

从其他视图控制器我调用此方法:

NSString * result = [self.user loginWith:emailCell.textField.text andPassword:passCell.textField.text];

NSLog(@"Result: %@",result);

问题是我得到“null”作为结果的对象,这是因为当执行NSlog时网络进程正在后台线程中进行,所以我如何更正实现,这样我才能得到结果在正确的时刻,取得后

谢谢

1 个答案:

答案 0 :(得分:4)

您应该在方法签名中添加“callback”块参数,并在请求完成时调用该块。

- (void)loginWith:(NSString *)email andPassword:(NSString *)password complete:(void(^)(id result, NSError *error))block {

    // ...

    [manager POST:[kROOT_URL stringByAppendingString:@"auth/"] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
    {

        // ...

        result = [responseObject objectForKey:@"id"];

        if (block) block(result, nil)

    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {

        if (block) block(nil, error)

    }];

}

调用方法时,传递回调块,您可以在其中读取结果值:

[self.user loginWith:emailCell.textField.text andPassword:passCell.textField.text complete:^(id result, NSError *error) {
     if (error)
         NSLog(@"Error: %@", error);
     else
         NSLog(@"Result: %@", result);
}];