Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 666
user3818576 Avatar asked Oct 03 '14 07:10

user3818576


1 Answers

-(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 ... 
}];
like image 176
neo D1 Avatar answered Sep 28 '22 12:09

neo D1