Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Created May 25, 2018 10:57
Show Gist options
  • Save alexpaul/2958c7fa792ed27add56634f8685c959 to your computer and use it in GitHub Desktop.
Save alexpaul/2958c7fa792ed27add56634f8685c959 to your computer and use it in GitHub Desktop.
This NetworkHelper is a wrapper that uses NSURLSession to make HTTP requests on behalf of an API network call.
//
// NetworkHelper.h
// Events
//
// Created by Alex Paul on 5/23/18.
// Copyright © 2018 Alex Paul. All rights reserved.
//
@interface NetworkHelper: NSObject
// class method is denoted by a + symbol
+ (instancetype)sharedManager;
// instance method is denoted by a - symbol
- (void)performRequestWithRequest:(NSURLRequest *)request completionHandler:(void(^)(NSError *error, NSData *data))completion;
@end
//
// NetworkHelper.m
// Events
//
// Created by Alex Paul on 5/23/18.
// Copyright © 2018 Alex Paul. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "NetworkHelper.h"
// class extension
@interface NetworkHelper ()
// private properties and methods
@property (nonatomic) NSURLSession *urlSession;
@end
@implementation NetworkHelper
// [NetworkHelper sharedManager], [NSFileManager sharedManager]
+ (instancetype)sharedManager {
static NetworkHelper *networkHelper;
static dispatch_once_t once_token;
// only run once!!!!!
dispatch_once(&once_token, ^{
networkHelper = [[NetworkHelper alloc] init];
});
return networkHelper;
}
- (instancetype)init {
self = [super init];
if (self) {
// initialize properties
_urlSession = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration];
}
return self;
}
// HTTP methods: GET, POST
- (void)performRequestWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSError *, NSData *))completion {
NSURLSessionDataTask *dataTask = [self.urlSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
completion(error, nil);
} else {
completion(nil, data);
}
}];
[dataTask resume]; // ALWAYS ADD resume() on the session task
// or state will be suspended and API call won't happen
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment