Skip to content

Instantly share code, notes, and snippets.

@ipreencekmr
Created November 27, 2017 05:11
Show Gist options
  • Save ipreencekmr/6327336f9d865d052df7568568d79f60 to your computer and use it in GitHub Desktop.
Save ipreencekmr/6327336f9d865d052df7568568d79f60 to your computer and use it in GitHub Desktop.
//
// ViewController.m
// Session Demo
//
// Created by mCURA on 27/11/17.
// Copyright © 2017 Prince. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDataDelegate, NSURLSessionDelegate>
@property (nonatomic, strong) NSMutableData *receivedData;
@end
@implementation ViewController
NSTimeInterval reqTimeInterval = 300.0f;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.receivedData = [[NSMutableData alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSURLSession *)sessionForId:(NSString *)identity {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 4;
NSString *backgroundSessionIdentifier = [NSString stringWithFormat:@"backgroundPdfUploadIdentifier_%@",identity];
NSURLSessionConfiguration *backgroundSession = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:backgroundSessionIdentifier];
backgroundSession.networkServiceType = NSURLNetworkServiceTypeBackground;
backgroundSession.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
backgroundSession.timeoutIntervalForRequest = reqTimeInterval;
backgroundSession.timeoutIntervalForResource = (reqTimeInterval * 2);
if ([backgroundSession respondsToSelector:@selector(setWaitsForConnectivity:)]) {
[backgroundSession setWaitsForConnectivity:true];
}
NSURLSession *session = [NSURLSession sessionWithConfiguration:backgroundSession delegate:self delegateQueue:queue];
return session;
}
- (IBAction)startFetching:(id)sender {
NSString *urlString = [NSString stringWithFormat:@"http://services.groupkt.com/country/get/all"];
NSLog(@"url Req %@",urlString);
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setTimeoutInterval:reqTimeInterval];
NSURLSession *session = [self sessionForId:@"mySessionId"];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request];
NSLog(@"postDataTask %@ timeout %f",postDataTask,request.timeoutInterval);
[postDataTask resume];
}
#pragma mark- NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"response status code: %ld", (long)[httpResponse statusCode]);
self.receivedData = nil;
self.receivedData = [[NSMutableData alloc] init];
[self.receivedData setLength:0];
completionHandler(NSURLSessionResponseAllow);
}
#pragma mark- NSURLSessionDataDelegate
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
[self.receivedData appendData:data];
}
#pragma mark- NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
NSLog(@"RESPONSE --------------");
NSLog(@"session identifier %@",session.configuration.identifier);
if (error) {
// Handle error
NSLog(@"Error %@",error);
[self responseHandler:error];
}
else {
if ([session.configuration.identifier rangeOfString:@"backgroundPdfUploadIdentifier"].location != NSNotFound) {
NSDictionary *responseData = [NSJSONSerialization JSONObjectWithData:self.receivedData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"response of background session --- %@",responseData);
}
}
[session finishTasksAndInvalidate];
self.receivedData = nil;
}
- (void)responseHandler:(NSError *)error {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Message" message:error.localizedDescription preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}
});
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment