user3818576 user3818576 - 16 days ago 5
iOS Question

How to get data from blocks using NSURLSession?

I have problem with this block. I trying to get the data inside the block of

NSURLSession
.

here's my code

-(NSDictionary *) RetrieveData{

NSURLSession * session = [NSURLSession sharedSession];
NSURL * url = [NSURL URLWithString: self.getURL];
dataList =[[NSDictionary alloc] init];

NSURLSessionDataTask * dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

self.json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

}];
return self.dataList;
[dataTask resume];

}


Is it possible to get the data inside the blocks of
NSURLSession
?

Answer
-(void)getJsonResponse:(NSString *)urlStr success:(void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:urlStr];   

    // Asynchronously API is hit here
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {            
                                                NSLog(@"%@",data);
                                                if (error)
                                                    failure(error);
                                                else {                                               
                                                    NSDictionary *json  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                                    NSLog(@"%@",json);
                                                    success(json);                                               
                                                }
                                            }];
    [dataTask resume];    // Executed First
}

call this:

[self getJsonResponse:@"Enter your url here" success:^(NSDictionary *responseDict) {   
        NSLog(@"%@",responseDict);
    } failure:^(NSError *error) {
        // error handling here ... 
}];