试图创建一个处理AFNetworking的功能

时间:2014-07-15 14:51:07

标签: ios objective-c methods afnetworking

我正在尝试创建一个函数,我将调用它来处理AFNetworking JSON解析。

这是我的代码:

- (int)startParseWithParameters:(NSDictionary*)incomingParameters andUrlAdress:(NSString*)urlAdress;
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    NSDictionary *parameters = incomingParameters;
    [manager POST:urlAdress parameters:parameters success:^

     (AFHTTPRequestOperation *operation, id responseObject)
     {
         NSString *recivedErr = responseObject[@"error"];
         _errValue = [recivedErr intValue];

        NSLog(@"JSON: %d", _errValue);
     }

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

    return _errValue; 
}

我希望函数返回0或1,然后我会知道是否有错误。 现在它总是返回0.

当我尝试在成功块中返回时,我收到编译器错误。

什么可能导致这个问题?

1 个答案:

答案 0 :(得分:0)

成功块被处理为异步,所以你应该只调用块中的方法:

- (void)startParseWithParameters:(NSDictionary*)incomingParameters andUrlAdress:(NSString*)urlAdress {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    NSDictionary *parameters = incomingParameters;
    __weak typeof(self) weakSelf = self;
    [manager POST:urlAdress parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {


         NSString *recivedErr = responseObject[@"error"];
        [weakSelf didReceiveResponse:[recivedErr integerValue];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
    }];
}

-(void)didReceiveResponse:(NSInteger)status {
}