DEV'S

Protocol And Delegates With NSURLSession

ViewController.h
//
//  ViewController.h
//  WebSrvExample

#import <UIKit/UIKit.h>
#import "WebService.h"

@interface ViewController : UIViewController<WebServiceDelegate>

@property (strong, nonatomic) IBOutlet UILabel *locationInfo;
@property(nonatomic,retain) WebService *webService;

@end

ViewController.m

//
//  ViewController.m
//  WebSrvExample
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize locationInfo,webService;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //Sample URL http://devsonline.in/app/getallitems
    //Payload : username=deva&password=1234
    //Method : POST
    //If you have issues with Google’s Map Webservice URL, Use the above to handle result
    // Sample Response from the server
    /*
     {
     "result": "OK",
     "items": [
     {
     "item_id": "6",
     "item_user_name": "deva",
     "item_name": "Apple",
     "item_qty": "12",
     "item_price": "23",
     "item_log": "2015-11-17 22:16:51"
     },
     {
     "item_id": "27",
     "item_user_name": "deva",
     "item_name": "Mango",
     "item_qty": "211",
     "item_price": "23",
     "item_log": "2015-11-18 09:05:50"
     },
     {
     "item_id": "28",
     "item_user_name": "deva",
     "item_name": "Orange",
     "item_qty": "122",
     "item_price": "23",
     "item_log": "2015-11-18 09:34:41"
     }
     ]
     }
     */
    webService = [[WebService alloc]init];
    [webService setDelegate:self];
    [webService callWebServiceWithURLWithGET:@"https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=AIzaSyAAKb5lBsDLrS-JxQn9Z38G2bEpF69MuPE"];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - WebServiceDelegate Function

-(void)getResponseFromServer:(NSDictionary *)dict{

    NSArray *resultArray = [dict objectForKey:@"results"];
    
    for(int i = 0; i< [resultArray count]; i++){
        
        //NSLog(@"%@",[resultArray objectAtIndex:i]);
        
    }
    
    NSDictionary *resultObj = [resultArray objectAtIndex:0];
    
    NSLog(@"The location is %@",[resultObj objectForKey:@"formatted_address"]);
    
        [locationInfo setText:[resultObj objectForKey:@"formatted_address"]];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Location" message:[resultObj objectForKey:@"formatted_address"] preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            //handle events after pressing OK
            
            
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
            //handle events after pressing Cancel
            
            
        }];
        
        [alertController addAction:okAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    

}

@end

WebService.h

//
//  WebService.h
//  WebSrvExample
//

#import <Foundation/Foundation.h>

@class WebService;

@protocol WebServiceDelegate <NSObject>

-(void)getResponseFromServer:(NSDictionary *)dict;

@end

@interface WebService : NSObject

@property(nonatomic,retain) id <WebServiceDelegate> delegate;

-(void)callWebServiceWithURLWithPOST:(NSString *)wsurl payLoadTosend:(NSString *)payLoad;

-(void)callWebServiceWithURLWithGET:(NSString *)wsurl;

@end

WebService.m

//
//  WebService.m
//  WebSrvExample
//

#import "WebService.h"

@implementation WebService

@synthesize delegate;

-(void)callWebServiceWithURLWithPOST:(NSString *)wsurl  payLoadTosend:(NSString *)payLoad{
    
    NSURL *url = [NSURL URLWithString:wsurl];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:240];
    
    [request setHTTPMethod:@"POST"];
    
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSString *strLen = [NSString stringWithFormat:@"%ld",(long)payLoad.length];
    
    [request setValue:strLen forHTTPHeaderField:@"Content-Length"];
    NSData *dataToBeSent = [payLoad dataUsingEncoding:NSUTF8StringEncoding]; //encode as UTF-8
    
    
    [request setHTTPBody:dataToBeSent];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        
        if ([httpResponse statusCode] == 200){
        //Valid response received
            NSError *respError;
            NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&respError];
            dispatch_async(dispatch_get_main_queue(), ^(void){
                [delegate getResponseFromServer:responseDic];
            });
            
            
            
        }else{
        
        //Something went wrong
        }
        
        
    }];
    
    [task resume];
    

}

-(void)callWebServiceWithURLWithGET:(NSString *)wsurl{
    
    NSURL *url = [NSURL URLWithString:wsurl];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:240];
    
    [request setHTTPMethod:@"GET"];
    
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        
        if ([httpResponse statusCode] == 200){
            //Valid response received
            NSError *respError;
            NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&respError];
            dispatch_async(dispatch_get_main_queue(), ^(void){
                [delegate getResponseFromServer:responseDic];
            });
            
            
            
        }else{
            
            //Something went wrong
        }
        
        
    }];
    
    [task resume];
    
    
    
}

@end

iOS

2017-12-19 00:07:26
1) CoreData - UIDatePicker - Part2 - Final
2017-12-18 23:29:30
2) CoreData - UIDatePicker - Part1
2017-12-18 05:09:33
3) Shopping List App - Swift Part 2 - ActionSheet
2017-12-18 03:22:51
4) Shopping List App - Swift Part 1
2017-12-17 23:34:49
5) Swift - Introduction - WebService
2017-12-15 03:30:23
6) Shopping List IOS App - Part 2
2017-12-15 01:21:10
7) Shopping List IOS App - Part 1
2017-12-14 21:58:22
8) Shopping List IOS App - API Calls
2017-12-14 03:48:37
9) Delegate - Protocols - WebService
2017-12-13 04:28:23
10) NSMutableArray - NSMutableDictionary - TableViewController
2017-12-13 02:47:13
11) UITableViewController
2017-12-12 22:59:32
12) Segue Forward And Unwind
2016-02-27 03:20:22
13) GoogleMap Addon
2016-02-26 04:06:38
14) UILocalNotification With NSNotificationCenter
2016-02-25 03:51:07
15) CLLocationManager Example
2016-02-24 03:27:59
16) UIImagePickerController Using Camera And PhotoLibrary
2016-02-23 02:08:19
17) Multi Section UITableView - UIPickerView
2016-02-18 03:16:09
18) Hello World IOS App Using Swift
2016-02-17 03:10:24
19) Swift Programming Language - Playground
2016-02-15 02:06:55
20) TabBar Controller
2016-02-15 02:06:55
21) Understanding Auto Layout and Layout Constraints
2016-02-10 22:56:12
22) Shopping List App - Cloud - Part 3 - Final
2016-02-09 04:12:06
23) Shopping List App - Cloud - Part 2
2016-02-08 03:21:52
24) Shopping List App - Cloud - Part 1
2016-02-05 03:24:01
25) Protocol And Delegates With NSURLSession
2016-02-04 00:59:51
26) Webservice Using NSURLSession
2016-02-02 02:09:13
27) UIPickerView Addon - InputView And AccessoryView For UITextField
2016-02-02 02:07:12
28) Protocol And Delegates
2016-02-01 00:37:02
29) UIPickerView - Add Programmatically
2016-01-30 00:52:48
30) NSUserDefaults - UIAlertControler - Back Navigation Title Change
2016-01-29 02:01:06
31) CoreData - StudentsRecord App
2016-01-27 21:54:28
32) Manual Segue
2016-01-27 00:04:21
33) TableViewController Example
2016-01-25 02:08:16
34) NSArray And NSDictionary
2016-01-23 03:23:10
35) Reverse (Unwind) Segue
2016-01-22 00:56:28
36) ViewController - Segue - Messages
2014-12-22 05:29:28
37) WebService Example
2014-12-22 05:16:57
38) CoreData Example

© Vasudev.H / Email: tech3in@live.com