Pages

Friday, February 1, 2013

xCode and JSON Connection in iOS 6.0

I Tried with ASIHttpRequest but found that it will not work in iOS 6.0 because ARC is not supported in ASIHttpRequest. And googled a lot for the POST method connection to PHP. So finally i found the NSMutableURLRequest method for safe and reliable. So here is the method to call a simple Login Feature.

1. First Declare NSMutableData as follow


@interface LoginViewController ()
@property (nonatomic, strong) NSMutableData *responseData;
@end


2. Now initiate this Data in viewDidLoad as follow

self.responseData = [NSMutableData data];

3. Send you User id and password to JSON by following method



-(void)connectForCredential:(NSString *)userId andPassword:(NSString *)userPassword
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.urlname.com/login"]];
    NSString *postString = [NSString stringWithFormat:@"username=%@&password=%@",userId, userPassword];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
                                                                 delegate:self];
    if (connection) {
    }
    else {}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    printf("Data Failure");
}

// Following function will show you the result mainly
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    printf("connectionDidFinishLoading");
    printf("\nSucceeded! Received %d bytes of data\n",[self.responseData length]);
    
    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    
    // show all values
    for(id key in res) {
        
        id value = [res objectForKey:key];
        
        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;
        
        NSLog(@"\nkey: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
    }
    
    // extract specific value...
    NSArray *results = [res objectForKey:@"results"];
    
    for (NSDictionary *result in results) {
        NSString *icon = [result objectForKey:@"icon"];
        printf("icon: %@", icon);
    }
    
}