如何从 NSURLSessionDataTask 获取 NSDictionary

How to get NSDictionary from NSURLSessionDataTask

-(NSDictionary *)fetchFromUrl:(NSString *)url{
    NSURLRequest *request = [NSURLRequest  requestWithURL:[NSURL URLWithString:url]];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {
                                  dataFetched = [NSJSONSerialization JSONObjectWithData:data
                                                                                           options:0
                                                                                             error:NULL];

                              }];
    [task resume];
    NSLog(@"dataFetched, %@", dataFetched);

    return dataFetched;
}

所以我尝试将 dataFetched 作为一个全局变量,这样我就可以在我的 .m 文件周围访问它并使其可供其他 .m 文件访问,但是当我尝试 NSLog 从其他 . m 文件输出 (null)。无论如何,我可以让需要数据的其他 .m 文件中的数据可访问吗?

如果您在块内修改 NSDictionary,您需要为 属性 声明 __block 属性,如下所示

@property (nonatomic, strong) __block NSDictionary *dataFetched;

看看doc

Use __block Variables to Share Storage If you need to be able to change the value of a captured variable from within a block, you can use the __block storage type modifier on the original variable declaration. This means that the variable lives in storage that is shared between the lexical scope of the original variable and any blocks declared within that scope.

您需要在您的方法中使用块,而不是返回 NSDictionary,因此请像这样更改您的代码。

首先像这样改变你的方法

-(void)fetchFromUrl:(NSString *)url withDictionary:(void (^)(NSDictionary* data))dictionary{ 
    NSURLRequest *request = [NSURLRequest  requestWithURL:[NSURL URLWithString:url]];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error) {
                                      NSDictionary *dicData = [NSJSONSerialization JSONObjectWithData:data
                                                                                    options:0
                                                                                      error:NULL];
                                      dictionary(dicData);
                                  }];
    [task resume];          
}

现在像这样调用你的方法

[self fetchFromUrl:urlStr withDictionary:^(NSDictionary *data) {
    self.dataFetched = data;
    NSLog(@"data %@",data);
}];