- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
}
The above delegate method is called repeatedly so that the below delegate method is not called and app is hanged because of that.
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error
{
}
Methods used to create NSURLSessionDataTask
-(void)fetchDataAboveiOS7:(NSMutableURLRequest*)request :(void(^)(NSURLResponse *response, NSData *data, NSError *error))completionHandler
{
__block NSURLSessionDataTask *task;
task = [[self getSessionConfiguration] dataTaskWithRequest:request];
__block NSMutableArray *networkError;
if (!networkError) {
networkError = [[NSMutableArray alloc]init];
}
[task setTaskDescription:[request allHTTPHeaderFields][kTempId]];
[task resume];
}
-(NSURLSession *)getSessionConfiguration {
if (self.session) {
return self.session;
}
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.timeoutIntervalForRequest = kRequestTimeOut;
config.allowsCellularAccess = YES;
config.HTTPMaximumConnectionsPerHost = kMaximumConnectionPerHost;
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
return self.session;
}
Additional Code which used for creating NSURLRequest and this object is sent to fetchDataAboveiOS7
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:_url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:timeOutInterval];
/*method*/
[request setHTTPMethod:method];
if (self.sessionCookie != nil) {
[request setValue:self.sessionCookie forHTTPHeaderField:kCookie];
}
NSMutableDictionary *headerDict = [[NSMutableDictionary alloc] init];
[headerDict setValue:@"application/json;charset=UTF-8" forKey:@"Accept"];
[headerDict setValue:@"application/json;charset=UTF-8" forKey:@"Content-Type"];
for (NSString *key in [headerDict allKeys])
{
[request addValue:[headerDict valueForKey:key] forHTTPHeaderField:key];
}
if (bodyDict)
{
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:bodyDict
options:kNilOptions error:&error]];
}
[self fetchDataAboveiOS7:request :^(NSURLResponse *response, NSData *data, NSError *error) {
}];