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..
Hello from Russia!
Can I quote a post in your blog with the link to you?
@Polprav – Hello Polprav, Greetings. Sure you can post… Let me know if you have doubts…
Cool code – straight and to the point. Very useful. Thanks!
Would you know of further JSON wrappers? Something that will take JSON and return an object?
Thanks again,
Oded.
Thanks Oded,
and this is the best JSON Wrapper -https://github.com/TouchCode/TouchJSON.