2017-04-23 72 views
0

我有一个类来管理与AFNetworking的连接。如何在完成块中返回值

所以我想打电话给我之类的函数NSDictionary *dict = [ServerManager requestWithURL:@"https://someurl.com"];

而这在其他类中的函数:

- (NSDictionary *) requestWithURL:(NSString *)requestURL { 
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init]; 
    [manager GET:requestURL parameters:nil progress:nil 
     success:^(NSURLSessionDataTask *operation, id responseObject){ 

      return responseObject; 

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

    }]; 
} 

我知道这是不正确的做到这一点。那么我应该怎么做才能将responseObject退回NSDictionary *dict?我想获得块的异步开发的基本思想。

回答

3

由于网络请求完成长其启动后,处理结果的唯一途径是通过你的请求方法块...

// when request completes, invoke the passed block with the result or an error 
- (void)requestWithURL:(NSString *)requestURL completion:(void (^)(NSDictionary *, NSError *))completion { 
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init]; 
    [manager GET:requestURL parameters:nil progress:nil success:^(NSURLSessionDataTask *operation, id responseObject){ 
     if (completion) completion((NSDictionary*)responseObject, nil); 
    }, failure:^(NSURLSessionDataTask *operation, NSError *error) { 
     if (completion) completion(nil, error); 
    }]; 
} 

使其在ServerManager.h

公开
- (void)requestWithURL:(NSString *)requestURL completion:(void (^)(NSDictionary *, NSError *))completion; 

在其他地方,称之为:

[ServerManager requestWithURL:@"http://someurl.com" completion:^(NSDictionary *dictionary, NSError *error) { 
    // check error and use dictionary 
}]; 
相关问题