Skip to content

Instantly share code, notes, and snippets.

@ipreencekmr
Created December 4, 2017 07:10
Show Gist options
  • Save ipreencekmr/40f5042942c9415324fdcb6fa84ccf59 to your computer and use it in GitHub Desktop.
Save ipreencekmr/40f5042942c9415324fdcb6fa84ccf59 to your computer and use it in GitHub Desktop.
//
// ViewController.h
// Session Demo
//
// Created by Prince on 27/11/17.
// Copyright © 2017 Prince. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
//
// ViewController.m
// Session Demo
//
// Created by Prince 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 = 20.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);
//do not work for background session
if ([backgroundSession respondsToSelector:@selector(setWaitsForConnectivity:)]) {
[backgroundSession setWaitsForConnectivity:true];
}
NSURLSession *session = [NSURLSession sessionWithConfiguration:backgroundSession delegate:self delegateQueue:queue];
return session;
}
- (NSString *)currentTime {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"hh:mm:ss"];
NSString *timeStr = [df stringFromDate:[NSDate date]];
return timeStr;
}
- (IBAction)startFetching:(id)sender {
NSLog(@"start Time %@",[self currentTime]);
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];
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];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
willBeginDelayedRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLSessionDelayedRequestDisposition disposition, NSURLRequest * _Nullable newRequest))completionHandler {
NSLog(@"continue delayed request -------------------");
completionHandler(NSURLSessionDelayedRequestContinueLoading,nil);
}
//won't work for background session
- (void)URLSession:(NSURLSession *)session taskIsWaitingForConnectivity:(NSURLSessionTask *)task {
NSLog(@"waits for connectivity delegate ------------");
}
#pragma mark- NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
NSLog(@"RESPONSE --------------");
NSLog(@"session identifier %@",session.configuration.identifier);
NSLog(@"response Time %@",[self currentTime]);
if (error) {
// Handle error
NSLog(@"Error %@",error);
[self responseHandler:error success:nil];
}
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);
[self responseHandler:nil success:[[responseData valueForKeyPath:@"RestResponse.messages"] firstObject]];
}
}
[session finishTasksAndInvalidate];
self.receivedData = nil;
}
- (void)responseHandler:(NSError *)error
success:(NSString *)message {
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];
}else {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Message" message:message 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