Archive for the ‘Uncategorized’ Category

5. iPhone Server Communication

Monday, September 14th, 2009

We can communicate in many ways with server. One way is using JSON, this is explained as below:

1. Starting Communication

[[[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:
[NSURL URLWithString:urlStr]] delegate:self startImmediately:YES] autorelease];
//urlStr is NSString ref

2. Start receiving data

- (void)connection:(NSURLConnection *)connection didReceiveResponse:
   (NSURLResponse *)response{
    [receivedData setLength:0];
}
//receivedData is NSMutableData ref

3. Get data in chunks

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [receivedData appendData:data];
}

4. After getting complete data

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    // json data retrival complete    (received data is NSMutableData)
    if(receivedData == nil || [receivedData length] == 0){
      //handle error in getting response, may be no network
        [self showAlertViewWithTitle:@"No network" andMessage:@"Could not open the
        page, because internet connection was not found." andTag:0];
        return;
    }

    NSString *responseBody = [[[NSString alloc] initWithData:receivedData
      encoding:NSUTF8StringEncoding] autorelease];
    ////NSLog(responseBody);
    NSError *jsonParsingError = [[[NSError alloc] init] autorelease];
    NSDictionary * jsonData = [NSDictionary dictionaryWithJSONData:
                                 [responseBody dataUsingEncoding:NSUTF8StringEncoding]
                                     error:&jsonParsingError];

    NSDictionary *serverError = [jsonData objectForKey:@"error"]==[NSNull null]?
                                   nil:[jsonData objectForKey:@"error"];

    if(serverError==nil || [serverError count]==0){
        // no error found else
        NSDictionary *response = [jsonData objectForKey:@"response"]==[NSNull null]?
                                   nil:[jsonData objectForKey:@"response"];
        NSArray *array = [response objectForKey:@"array"]==[NSNull null]?nil:
                              [response objectForKey:@"array"];
// I have left the code incomplete, its just for understanding

5. Check for null values
Never forget to check null values from JSON data as follows:

NSString *dataValue =  [[[array objectAtIndex:i] objectForKey:@"key"]==[NSNull null]?
                         @"0":[[array objectAtIndex:i] objectForKey:@"key"] intValue];

Please let me know if you require further explanation..