Monday, 28 September 2015

how to use json response and request

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSURLConnectionDelegate>
{
    __weak IBOutlet UITextView *txtDisplay;
    NSMutableData *responseData;
}
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *actLoading;

- (IBAction)CallWSBtnClick:(UIButton *)sender;

@end
===========================
@implementation ViewController

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}



- (IBAction)CallWSBtnClick:(UIButton *)sender
{
    // Get Data
   
//    NSURL *aURL = [NSURL URLWithString:@"http://rest-service.guides.spring.io/greeting"];
//    NSURLRequest *aRequest = [NSURLRequest requestWithURL:aURL];
//    NSURLResponse *aResponse = nil;
//    NSError *aError = nil;

    // Synchronous Get Data
   

//    responseData = [[NSURLConnection sendSynchronousRequest:aRequest returningResponse:&aResponse error:&aError] mutableCopy];
//   
//    if (!aError)
//    {
//        txtDisplay.text = [NSString stringWithFormat:@"%@",[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]];
//    }
   
    // Asynchronous Get Data Without Block
   
    // *** Note : Don't Use This Method For InLine WebService Call(Like | Comment | Report Abuse) ***
   
//    NSData *responceData = [NSURLConnection sendSynchronousRequest:aRequest returningResponse:&aResponse error:&aError];
//    if (responceData.length>0 && aError == nil) {
//        txtDisplay.text = [NSString stringWithFormat:@"%@",[NSJSONSerialization JSONObjectWithData:responceData options:NSJSONReadingMutableContainers error:nil]];
//    }
    // Asynchronous Get Data With Block
   
    // *** Note : Must Use This Method For InLine WebService Call(Like | Comment | Report Abuse) ***
   
//    [NSURLConnection sendAsynchronousRequest:aRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
//    {
//        if (data.length > 0 && connectionError == nil)
//        {
//            txtDisplay.text = [NSString stringWithFormat:@"%@",[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
//        }
//    }];

   
    // Post Data
   
//    NSURL *aURL = [NSURL URLWithString:@"http://staging.indianic.com/lightning/public/web_service/client.php?method=skiplogin"];
//    NSString *strBody = @"post_data_string={\"device_id\":\"123\",\"device_type\":\"Android\",\"device_token\":\"8e310af31620ed310bfad3839c2f18130324a8c7f30739760ba60f56d8c93bae\"}";
//   
//    NSMutableURLRequest *aMutRequest = [[NSMutableURLRequest alloc]initWithURL:aURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
//    [aMutRequest setHTTPMethod:@"POST"];
//    [aMutRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [aMutRequest setHTTPBody:[NSData dataWithBytes:[strBody UTF8String] length:strlen([strBody UTF8String])]];
    //[NSURLConnection connectionWithRequest:aMutRequest delegate:self];
   
    NSURL *aURL = [NSURL URLWithString:@"http://www.izilunch.se/service/WebService/Service.svc/UpdateStatusOfpushNotification"];
   
    NSMutableDictionary *aDict = [[NSMutableDictionary alloc]init];
    [aDict setValue:@"8e310af31620ed310bfad3839c2f18130324a8c7f30739760ba60f56d8c93bae" forKey:@"deviceid"];
    [aDict setValue:@"0" forKey:@"status"];

    NSData *aData = [NSJSONSerialization dataWithJSONObject:aDict options:NSJSONWritingPrettyPrinted error:nil];
   
    NSMutableURLRequest *aMutRequest = [[NSMutableURLRequest alloc]initWithURL:aURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
    [aMutRequest setHTTPMethod:@"POST"];
    [aMutRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [aMutRequest setHTTPBody:aData];
    [aMutRequest setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[aData length]] forHTTPHeaderField:@"Content-Length"];
   
    [self.actLoading startAnimating];
   
//    [NSURLConnection connectionWithRequest:aMutRequest delegate:self];
   
    [NSURLConnection sendAsynchronousRequest:aMutRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         if (data.length > 0 && connectionError == nil)
         {
             txtDisplay.text = [NSString stringWithFormat:@"%@",[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
                [self.actLoading stopAnimating];
         }
     }];
   

}

#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to the instance variable you declared
    [responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse
{
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    [self.actLoading stopAnimating];
    txtDisplay.text = [NSString stringWithFormat:@"%@",[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]];
   
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // The request has failed for some reason!
    // Check the error var
}

@end