2017-04-23 68 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 
}]; 
相關問題