Tuesday, December 13, 2016

How to do Web Service in iOS - Web Service Sample example


Import ApiCall Model object class in ViewController.h

Call delegate APIDelegate in ViewController.h to define the APICall delegate methods in our ViewController View


//=== 


#import <UIKit/UIKit.h>
#import "ViewController.h"
#import "APICall.h"
@interface ViewController ()<APIDelegate>
{
    UILabel * lbl;
}

@end


//=== "ViewController.M"


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    APICall * api= [[APICall alloc] init];
    
    api.del = self;
    
    [api makeAPICallWithMethodName:@"greeting" methodTyep:@"GET" body:nil];
}

-(void)serviceSuccess:(NSData *)data methodName:(NSString *)method
{
    NSLog(@"Data : %@",data);
    NSError *error;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    
    NSLog(@"%@", jsonDict);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        lbl.text = [jsonDict objectForKey:@"id"];
    });
}
-(void)serviceError:(NSError *)error methodName:(NSString *)method{


}


//=== All the Magic is in APICall.h model objects to call the service calls


#import <Foundation/Foundation.h>
#define BASEURL @"http://rest-service.guides.spring.io/"
@protocol APIDelegate
@optional
-(void)serviceSuccess:(NSData *)data methodName:(NSString *)method;
-(void)serviceError:(NSError *)error methodName:(NSString *)method;
@end

@interface APICall : NSObject
{

}
@property (strong,nonatomic) id<APIDelegate> del;
-(void)makeAPICallWithMethodName:(NSString *)methodName methodTyep:(NSString *)methodType body:(NSData *)body;
@end

//=== APICAll.M


#import "APICall.h"

@implementation APICall

-(NSMutableURLRequest *)prepareRequestWithMethodName:(NSString *)methodName methodType:(NSString *)methodType body:(NSData *)bodyData
{
    NSDictionary *headers = @{ @"cache-control": @"no-cache",
                               @"postman-token": @"b559e00e-c5a5-e96e-63ea-40907d757a39",@"AUTHTOKEN":@"djajkdhakj" };
    
    NSString * urlString = [NSString stringWithFormat:@"%@%@",BASEURL,methodName];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:10.0];
    [request setHTTPMethod:methodType];
    [request setAllHTTPHeaderFields:headers];
    if ([methodType isEqualToString:@"PUT"] || [methodType isEqualToString:@"POST"]) {
        [request setHTTPBody:bodyData];
    }
    return request;
}


-(void)conncectWithServerRequest:(NSURLRequest *)request methodName:(NSString *)method
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    if (error) {
                                                        NSLog(@"%@", error);
                                                        [self.del serviceError:error methodName:method];
                                                    } else {
                                                        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                        NSLog(@"%@", httpResponse);
                                                        [self.del serviceSuccess:data methodName:method];
                                                    }
                                                }];
    [dataTask resume];
}

-(void)makeAPICallWithMethodName:(NSString *)methodName methodTyep:(NSString *)methodType body:(NSData *)body
{
    NSMutableURLRequest * request = [self prepareRequestWithMethodName:methodName methodType:methodType body:body];
    [self conncectWithServerRequest:request methodName:methodName];
}
@end