NSURLSession Sample Code

NSURLSession Sample Code

Written By: Debasis Das (28-Apr-2015)

In this article we will create a sample application that reads data from a web service using NSURLSession, NSURLSessionDelegate & NSURLRequest.

We have demonstrated 2 different approaches of getting data.

  1. Delegate Approach
  2. Call Back Approach
NSURLSession Sample Code

NSURLSession Sample Code

Below is the NSURLSession Sample Code 

The project is has the following

  • AppDelegate
  • NSWindowController
  • NSViewController that acts as a delegate for the NSURLSessionDelegate (this is used in approach 1)
  • Service Class that has method that triggers a NSURLRequest for web service call and provides data to a calling method (this is used in approach 2)
  • Constants file that has the web service URL

View Controller – Uses the Delegate Approach to get data from a web service

//  KSViewController.h
//  NSURLSession_KSSampleCode
//  Created by Debasis Das on 4/19/15.
//  Copyright (c) 2015 Knowstack. All rights reserved.

#import <Cocoa/Cocoa.h>
@interface KSViewController : NSViewController <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
@end
#import "KSViewController.h"
#import "KSService.h"
#import "KSConstants.h"

@interface KSViewController ()

@property (weak, nonatomic) IBOutlet NSProgressIndicator *progressIndicator;
@property (weak, nonatomic) IBOutlet NSTextField *progressIndicatorLabel;
@property (weak, nonatomic) IBOutlet NSTextField *dataURLTextField;
@property (assign) IBOutlet NSTextView *responseDataTextView;

@property (nonatomic,strong) NSURLSession *session;
@property (nonatomic,strong) NSURLSessionDataTask *finderTask;
@end

@implementation KSViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self hideProgressIndicator];
    [self.dataURLTextField setStringValue:EMPLOYEE_DATA_URL];
}

//The following method uses the Call Back/ Completion Block approach to retrieve data from a web service
-(IBAction)findDataFromWebService:(id)sender
{
    [self.responseDataTextView setString:@""];
    [self showProgressIndicator];
    [[KSService sharedInstance] fetchEmployeeDataWithCompletionBlock:^(NSArray *employeeArray, NSError *error) {
        if (!error) {
            NSLog(@"employeeArray %@",employeeArray);
            
            [self.responseDataTextView setString:[employeeArray description]];
            [self hideProgressIndicator];
        }
        else
        {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [NSApp presentError:error];
            }];
        }
    }];
}

#pragma mark Find Using NSURLSession Delegate Approach
- (NSURLSession *)createSession
{
    static NSURLSession *session = nil;
    session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                            delegate:self
                                       delegateQueue:[NSOperationQueue mainQueue]];
    return session;
}

//The below method used the delegate approach to get data from the same web service
-(IBAction)findDataUsingDelegate:(id)sender{
    [self.responseDataTextView setString:@""];
    [self showProgressIndicator];
    self.session = [self createSession];
    
    NSURL *dataURL = [NSURL URLWithString:EMPLOYEE_DATA_URL];
    NSURLRequest *request = [NSURLRequest requestWithURL:dataURL];
    self.finderTask = [self.session dataTaskWithRequest:request];
    [self.finderTask resume];
}

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data{
    NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    [self.responseDataTextView setString:[dataArray description]];
    [self hideProgressIndicator];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
 willCacheResponse:(NSCachedURLResponse *)proposedResponse
 completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler{
     NSLog(@"%s",__func__);
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error{
     NSLog(@"%s",__func__);
}

#pragma mark Progress Indicator
-(void)showProgressIndicator{
    [self.progressIndicator setHidden:NO];
    [self.progressIndicatorLabel setHidden:NO];
    [self.progressIndicator startAnimation:self];
}

-(void)hideProgressIndicator{
    [self.progressIndicator setHidden:YES];
    [self.progressIndicatorLabel setHidden:YES];
    [self.progressIndicator stopAnimation:self];
}
@end

KSService Class

//  KSService.h
//  NSURLSession_KSSampleCode
//  Copyright (c) 2015 Knowstack. All rights reserved.

#import <Foundation/Foundation.h>
@interface KSService : NSObject
+(KSService *)sharedInstance;
-(void) fetchEmployeeDataWithCompletionBlock:(void(^)(NSArray *employeeArray, NSError *error)) completionBlock;
@end
//  KSService.m
//  Copyright (c) 2015 Knowstack. All rights reserved.
#import "KSService.h"
#import "KSConstants.h"
@implementation KSService
+(KSService *) sharedInstance
{
    static KSService *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[KSService alloc] init];
    });
    return _sharedInstance;
}

-(void) fetchEmployeeDataWithCompletionBlock:(void(^)(NSArray *employeeArray, NSError *error)) completionBlock;
{
   NSLog(@"main thread? ANS - %@",[NSThread isMainThread]? @"YES":@"NO");
   NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    NSString *cachePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"/nsurlsessiondemo.cache"];

    NSURLCache *myCache = [[NSURLCache alloc] initWithMemoryCapacity: 16384
                                                        diskCapacity: 268435456
                                                            diskPath: cachePath];
    defaultConfigObject.URLCache = myCache;
    
    defaultConfigObject.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
    
    NSURLSession *delegateFreeSession = [NSURLSession sessionWithConfiguration: defaultConfigObject
                                                                      delegate: nil
                                                                 delegateQueue: [NSOperationQueue mainQueue]];
    
    NSURL *dataURL = [NSURL URLWithString:EMPLOYEE_DATA_URL];
    NSURLRequest *request = [NSURLRequest requestWithURL:dataURL];
    [[delegateFreeSession dataTaskWithRequest:request
                            completionHandler:^(NSData *data, NSURLResponse *response,
                                                NSError *error)
                            {
                                NSLog(@"Got response %@ with error %@.\n", response, error);
                                NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                completionBlock (dataArray, error);
                            }
      ]resume];
}
@end

The complete code can be found at https://github.com/knowstack/NSURLSession-Sample-Code.git

Posted in Cocoa, Objective C Tagged with: , , , , , ,
One comment on “NSURLSession Sample Code
  1. Imran Khan says:

    Good One Deb..

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news