Skip to content

Instantly share code, notes, and snippets.

@mspvirajpatel
Last active September 22, 2017 09:33
Show Gist options
  • Save mspvirajpatel/2b4e1839cd76ca287f696769d5cfe364 to your computer and use it in GitHub Desktop.
Save mspvirajpatel/2b4e1839cd76ca287f696769d5cfe364 to your computer and use it in GitHub Desktop.
API Call Manager Class Objective C
#import <Foundation/Foundation.h>
typedef NS_OPTIONS(NSInteger, APITask){
Login = 0,
Register = 1
};
@interface APIManager : NSObject
+(id)shared;
-(void)getRequest:(NSString *)url param:(NSDictionary *)Parameter type:(APITask *)Type internet:(void (^)(BOOL isOn)) Internet success:(void (^)(id response, id error))success failure:(void (^)(NSError *error))failure;
-(void)postRequest:(NSString *)url param:(NSDictionary *)Parameter type:(APITask *)Type completion:(void (^)(id response, id error))completion;
-(void)imageUploadWithPostRequest:(NSString *)url param:(NSDictionary *)Parameter imagePaths:(NSArray *)Images type:(APITask *)Type completion:(void (^)(id response, id error))completion;
-(NSString*)getURLStringFromDictionary:(NSDictionary*)dictionary;
-(NSData *)createBodyWithBoundary:(NSString *)boundary
parameters:(NSDictionary *)parameters
paths:(NSArray *)paths
fieldName:(NSString *)fieldName;
@end
#import "APIManager.h"
@import MobileCoreServices;
@implementation APIManager
+(id)shared{
static APIManager *sharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedManager = [[self alloc] init];
});
return sharedManager;
}
-(void)getRequest:(NSString *)url param:(NSDictionary *)Parameter type:(APITask *)Type internet:(void (^)(BOOL isOn)) Internet success:(void (^)(id response, id error))success failure:(void (^)(NSError *error))failure
{
[AppUtility isNetworkAvailableWithBlock:^(BOOL wasSuccessful) {
if(wasSuccessful){
Internet(wasSuccessful);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"GET"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"Request reply: %@", requestReply);
NSLog(@"RESPONSE: %@",response);
NSLog(@"DATA: %@",data);
if (!error) {
// Success
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
// Error Parsing JSON
failure(error);
} else {
// Success Parsing JSON
// Log NSDictionary response:
NSLog(@"%@",jsonResponse);
success(jsonResponse,nil);
}
} else {
//Web server is returning an error
}
} else {
// Fail
NSLog(@"error : %@", error.description);
failure(error);
}
}] resume];
}
else
{
Internet(wasSuccessful);
}
}];
}
-(void)postRequest:(NSString *)url param:(NSDictionary *)Parameter type:(APITask *)Type internet:(void (^)(BOOL isOn)) Internet success:(void (^)(id response, id error))success failure:(void (^)(NSError *error))failure
{
[AppUtility isNetworkAvailableWithBlock:^(BOOL wasSuccessful) {
if(wasSuccessful){
Internet(wasSuccessful);
NSString *post = [self getURLStringFromDictionary:Parameter];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
request.timeoutInterval = 60.0f;
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"Request reply: %@", requestReply);
NSLog(@"RESPONSE: %@",response);
NSLog(@"DATA: %@",data);
if (!error) {
// Success
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
// Error Parsing JSON
failure(error);
} else {
// Success Parsing JSON
// Log NSDictionary response:
success(jsonResponse,nil);
NSLog(@"%@",jsonResponse);
}
} else {
//Web server is returning an error
}
} else {
// Fail
NSLog(@"error : %@", error.description);
failure(error);
}
}] resume];
}
else
{
Internet(wasSuccessful);
}
}];
}
-(void)imageUploadWithPostRequest:(NSString *)url param:(NSDictionary *)Parameter imagePaths:(NSArray *)Images type:(APITask *)Type internet:(void (^)(BOOL isOn)) Internet success:(void (^)(id response, id error))success failure:(void (^)(NSError *error))failure
{
[AppUtility isNetworkAvailableWithBlock:^(BOOL wasSuccessful) {
if(wasSuccessful){
Internet(wasSuccessful);
NSString *boundary = [self generateBoundaryString];
// configure the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
// set content type
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
// create body
NSData *httpBody = [self createBodyWithBoundary:boundary parameters:Parameter paths:Images fieldName:@"fileName"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
// use sharedSession or create your own
NSURLSessionTask *task = [session uploadTaskWithRequest:request fromData:httpBody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"error = %@", error);
return;
}
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result = %@", result);
NSLog(@"RESPONSE: %@",response);
if (!error) {
// Success
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
// Error Parsing JSON
failure(error);
} else {
// Success Parsing JSON
// Log NSDictionary response:
success(jsonResponse,nil);
NSLog(@"%@",jsonResponse);
}
} else {
//Web server is returning an error
}
} else {
// Fail
NSLog(@"error : %@", error.description);
failure(error);
}
}];
[task resume];
}
else
{
Internet(wasSuccessful);
}
}];
}
-(NSString*)getURLStringFromDictionary:(NSDictionary*)dictionary{
NSMutableArray *urlStringWithDetailsArray = [NSMutableArray array];
[dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
[urlStringWithDetailsArray addObject:[NSString stringWithFormat:@"%@=%@", key, [obj stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding]]];
}];
NSString *finalString = [urlStringWithDetailsArray componentsJoinedByString:@"&"];
return finalString;
}
- (NSData *)createBodyWithBoundary:(NSString *)boundary
parameters:(NSDictionary *)parameters
paths:(NSArray *)paths
fieldName:(NSString *)fieldName {
NSMutableData *httpBody = [NSMutableData data];
// add params (all params are strings)
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *parameterKey, NSString *parameterValue, BOOL *stop) {
[httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", parameterKey] dataUsingEncoding:NSUTF8StringEncoding]];
[httpBody appendData:[[NSString stringWithFormat:@"%@\r\n", parameterValue] dataUsingEncoding:NSUTF8StringEncoding]];
}];
// add image data
for (NSString *path in paths) {
NSString *filename = [path lastPathComponent];
NSData *data = [NSData dataWithContentsOfFile:path];
NSString *mimetype = [self mimeTypeForPath:path];
[httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fieldName, filename] dataUsingEncoding:NSUTF8StringEncoding]];
[httpBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", mimetype] dataUsingEncoding:NSUTF8StringEncoding]];
[httpBody appendData:data];
[httpBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
[httpBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
return httpBody;
}
- (NSString *)mimeTypeForPath:(NSString *)path {
// get a mime type for an extension using MobileCoreServices.framework
CFStringRef extension = (__bridge CFStringRef)[path pathExtension];
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
assert(UTI != NULL);
NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType));
assert(mimetype != NULL);
CFRelease(UTI);
return mimetype;
}
- (NSString *)generateBoundaryString {
return [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];
}
@end
@mspvirajpatel
Copy link
Author

How to Use Get Request

[[APIManager shared] getRequest:finalString param:nil type:nil internet:^(BOOL isOn) {
        
    } success:^(id response, id error) {
        
    } failure:^(NSError *error) {
        
    }];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment