问题描述
-(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文件可以访问它,但是当我尝试从其他.m文件中NSLog
dataFetched时,它将输出(空).无论如何,我可以在需要数据的其他.m文件中使数据可访问吗?
So I have tried putting the dataFetched as a global variable so I could access it around my .m file and make it accessible to other .m file but when I tried to NSLog
the dataFetched from other .m file it outputs (null). Is there anyway I could make the data accessible throughout my other .m files that needed the data?
推荐答案
您需要在您的方法中使用block,而不是返回NSDictionary
,因此请像这样更改代码.
You need to use block with your method, instead of returning NSDictionary
, So change your code like this.
首先像这样更改您的方法
First Change your method like this
-(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];
}
现在像这样调用您的方法
Now call your method like this
[self fetchFromUrl:urlStr withDictionary:^(NSDictionary *data) {
self.dataFetched = data;
NSLog(@"data %@",data);
}];
这篇关于如何从NSURLSessionDataTask获取NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!