基于AFNetworking响应的返回值

时间:2014-02-08 16:14:42

标签: objective-c cocoa

我正在尝试创建一个函数,该函数将根据AFNetworking POST请求的响应返回一个值。

但是,我无法找到一种方法,因为该函数是异步的,因此在实际接收响应之前返回该值。

int didLogin;

__block NSString *response;

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

    NSDictionary *parameters = @{@"username":username, @"password":password};

    [manager POST:loginUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        //json "response" object from server response
        response = [responseObject objectForKey:@"response"];

        NSLog(@"Response: %@", response);

        [HUD hide:YES];
        [HUD removeFromSuperViewOnHide];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [HUD hide:YES];
        [HUD removeFromSuperViewOnHide];

        NSLog(@"Login Error: %@", error);
    }];

    if ([response compare:@"1"] == NSOrderedSame || [response compare:@"2"] == NSOrderedSame)
    {
        //successful login/1-new device/2-existing device
        didLogin = 1;
    }
    else if ([response compare:@"0"] == NSOrderedSame)
    {
        //unsuccessful login/invalid password
        didLogin = 0;
    }
    else{
        //unsuccessful login
        didLogin = 2;
    }

此时它将返回didLogin。

有没有办法让这项工作,或者我是否需要使用同步请求?

1 个答案:

答案 0 :(得分:2)

您的方法应该将回调块作为参数,然后在异步过程完成时应该使用didLogin调用该块。您需要接受在整个代码中尝试执行的异步特性。