jane jane - 4 months ago 29
Objective-C Question

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;
}


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?

Answer

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);
}];