我有一个管理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
?我想了解使用块进行异步开发的基本概念。
答案 0 :(得分: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
}];