ios - AFNetworking 异步任务 iOS 的返回值

标签 ios objective-c afnetworking

我最近询问了 AFNetwirking GET 查询的 nil 值。 Here is the question

我有一个答案

+ (void)getRequestFromUrl:(NSString *)requestUrl withCompletion:((void (^)(NSString *result))completion 
{
    NSString * completeRequestUrl = [NSString stringWithFormat:@"%@%@", BASE_URL, requestUrl];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:completeRequestUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *results = [NSString stringWithFormat:@"%@", responseObject];
        if (completion)
            completion(results);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSString *results = [NSString stringWithFormat:@"Error"];
        if (completion)
            completion(results);
    }];
}

[YourClass getRequestFromUrl:@"http://www.example.com" withCompletion:^(NSString *results){
    NSLog(@"Results: %@", results);
}

现在我有另一个问题:在 MyClass 中我有一个名为 getAllPlaces 的方法。

+ (void) getAllPlaces {
    NSString * placesUrl = [NSString stringWithFormat: @"/url"];
    NSMutableArray *places = [[NSMutableArray alloc] init];
    [RestfulActions getRequestFromUrl:cafesUrl withCompletion:^(id placesInJSONFormat) {
        NSArray *results = placesInJSONFormat;
        for (NSDictionary *tempPlaceDictionary in results) {
            Place *place = [[Place alloc] init];
            for (NSString *key in tempPlaceDictionary) {
                if ([place respondsToSelector:NSSelectorFromString(key)]) {
                    [place setValue:[tempPlaceDictionary valueForKey:key] forKey:key];
                }
            }
            [places addObject:place];
        }

}];

有效,但我想返回非空值(NSArray 位置)。现在它再次引发了关于异步任务的问题。我应该怎么办? 我想从另一个类访问 NSArray *places = [MyClass getAllPlaces] 我希望得到一个正确的答案。谢谢,阿尔乔姆。

最佳答案

您不能从该 block 返回值,因为它是异步的,并且在其他任务正在进行时继续运行。

处理此问题的正确方法是从 block 内调用处理此数据的方法并将数组传递给它。

关于ios - AFNetworking 异步任务 iOS 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20070571/

相关文章:

html - 如何使用 AFNetworking 获取重定向的 URL?

ios - 实例化 ViewController 并将其从 Swift 中的字符串转换为类

ios - 异步获取 Swift Xcode

ios - 检测页面何时按下 tabBar 项

ios - Afnetworking post 请求的代码提取

ios - iPhone 设备不连接到应用程序中的本地服务器

ios - swift ,让我知道了这个 : interfaceOrientation was deprecated in iOS 8. 0

ios - Swift segue 标识符始终为零,Storyboard ID 不起作用

iphone - 为 UITextView 设置多种数据检测器类型

ios - 通过 Obj-c 查询 REST API 时出现 Azure DocumentDB 间歇性 401 错误