问题
-(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;
}
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?
回答1:
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);
}];
回答2:
If you modify your NSDictionary
inside the block you need declare __block
attribute for your property like below
@property (nonatomic, strong) __block NSDictionary *dataFetched;
Look at 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.
来源:https://stackoverflow.com/questions/38691246/how-to-get-nsdictionary-from-nsurlsessiondatatask