方法在完成处理程序之前返回 [英] method returns before completionhandler

查看:81
本文介绍了方法在完成处理程序之前返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的项目开发networkUtil,我需要一个方法,该方法获取URL并使用NSURLSessionDataTask返回从该URL接收的JSON,以从服务器获取JSON.方法如下:

I am developing a networkUtil for my project, I need a method that gets a url and returns the JSON received from that url using NSURLSessionDataTask to get a JSON from server. the method is the following:

+ (NSDictionary*) getJsonDataFromURL:(NSString *)urlString{
    __block NSDictionary* jsonResponse;
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@", jsonResponse);
    }];

    [dataTask resume];

    return jsonResponse;
}

问题是我的方法中的 completionHandler 方法本身不同线程上运行,而在最后一行,jsonResponse是总是 nil

The problem is that the completionHandler inside my method and the method itself are run on different threads and in the last line the jsonResponse is always nil

如何使用从 urlString 返回的json设置 jsonResponse ?
此问题的最佳做法是什么?

How should I set jsonResponse with returned json from urlString?
What is the best practice for this issue?

推荐答案

在NSURLSession中运行的块正在不同的线程上运行-您的方法不会等待块完成.

Block that is running in NSURLSession is running on different thread - your method doesn't wait block to finish.

您在这里有两个选择

第一个.发送NSNotification

First one. Send NSNotification

+ (void) getJsonDataFromURL:(NSString *)urlString{
       NSURLSession *session = [NSURLSession sharedSession];
       NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
           NSDictionary* jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
           NSLog(@"%@", jsonResponse);

           [[NSNotificationCenter defaultCenter] postNotificationName:@"JSONResponse" object:nil userInfo:@{@"response" : jsonResponse}];
       }];

       [dataTask resume];
}

第二个.此实用程序方法的过去完成框

Second one. Past completion block to this utility method

+ (void) getJsonDataFromURL:(NSString *)urlString
            completionBlock:(void(^)(NSDictionary* response))completion {
       NSURLSession *session = [NSURLSession sharedSession];
       NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
           NSDictionary* jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
           NSLog(@"%@", jsonResponse);

           completion(jsonResponse);
       }];

       [dataTask resume];
}

这篇关于方法在完成处理程序之前返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆