Objective-C:如何从POST方法返回响应?

时间:2014-11-16 04:43:21

标签: ios objective-c ios7 afnetworking

我有POST方法,看起来像

+ (id) post {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    id response = nil;
    [manager POST:@"https://mapp.com/oauth/register"
       parameters:@{@"email" : @"e", @"memberExternalId" : @"m"}
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              response =  responseObject;
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                // (todo) alert on failure
                NSLog(@"Error: %@", error);
            }];
    return response;
}

我想抽象这个方法以便我可以重用它,所以我创建了id response

但是当我分配

response =  responseObject;

我收到编译错误

Variable is declared outside the block and is not assignable  

enter image description here 问题

如何保留response以便我以后可以退回。

1 个答案:

答案 0 :(得分:4)

您正在调用使用完成块模式的异步方法,因此您应该这样做。所以

  • 将返回类型更改为void;

  • 将阻止参数添加到您的方法中;

  • POST完成版块中,如果有提供的话,请致电completionHandler;

因此:

+ (void) postWithCompletionHandler:(void (^)(id responseObject, NSError *error))completionHandler {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    // these lines not needed
    //
    // [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

    [manager POST:@"https://mapp.com/oauth/register"
       parameters:@{@"email" : @"e", @"memberExternalId" : @"m"}
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              if (completionHandler) {
                  completionHandler(responseObject, nil);
              }
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              if (completionHandler) {
                  completionHandler(nil, error);
              }
          }];
}

因此,您可以这样称呼它:

[MyClass postWithCompletionHandler:^(id responseObject, NSError *error) {
    if (!responseObject) {
        NSLog(@"failed: %@", error);
        return;
    }

    // use the `responseObject` here
}];

// Note, because the above is asynchronous, don't try to use `responseObject` here.
// You can only use it inside the above `completionHandler` block.

顺便说一下,您可能不希望为每个请求实例化一个新的AFHTTPRequestOperationManager。所以,我个人(a)将AFHTTPRequestOperationManager作为本课程的财产; (b)将操作管理器的实例化移动到该类的一些初始化方法中; (c)使这个"执行请求"方法实例方法,而不是类方法。它在这里并不那么重要,但是当您考虑将来发布许多请求的功能时,在整个地方实例化新的请求操作管理器是低效的。