如何在完成块中 return 值
How to return value in completion block
我有 class 管理与 AFNetworking 的连接。
所以我想调用我的函数 NSDictionary *dict = [ServerManager requestWithURL:@"https://someurl.com"];
这就是另一个函数 class:
- (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) {
}];
}
我知道这样做是不正确的。那么returnresponseObject
回到NSDictionary *dict
怎么办呢?我想了解使用块进行异步开发的基本概念。
由于网络请求在启动后很长时间内完成,处理结果的唯一方法是将块传递给您的请求方法...
// 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);
}];
}
public 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
}];
我有 class 管理与 AFNetworking 的连接。
所以我想调用我的函数 NSDictionary *dict = [ServerManager requestWithURL:@"https://someurl.com"];
这就是另一个函数 class:
- (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) {
}];
}
我知道这样做是不正确的。那么returnresponseObject
回到NSDictionary *dict
怎么办呢?我想了解使用块进行异步开发的基本概念。
由于网络请求在启动后很长时间内完成,处理结果的唯一方法是将块传递给您的请求方法...
// 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);
}];
}
public 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
}];