Synchronous Request Handling:
responseData = [[NSMutableData data] retain]; |
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/json"]]; |
NSURLResponse *response = nil; |
NSData *newData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; |
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding]; |
NSDictionary *jsonObject = [responseString JSONValue]; |
NSLog(@"type : %@", [jsonObject objectForKey:@"Type"] ); |
Some explanations :
- response is the url response for the json call
- error is error returned by NSURLConnection
- newData is data returned by the server
Notice that you can cast the JSON deserialized data into a NSDictionnary or anNSMutuableArray.
Asynchronous Request Handling:
To make an Asynchronous call we’ll need to use NSURLConnection withinitWithRequest method, then we need to implement differents other methods to handle the finish of data loading, error handling etc.
responseData = [[NSMutableData data] retain]; |
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/json"]];//asynchronous call |
[[NSURLConnection alloc] initWithRequest:request delegate:self]; |
Implementing delegate methods :
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { |
[responseData setLength:0]; |
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { |
[responseData appendData:data]; |
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { |
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { |
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; |
NSDictionary *jsonObject = [responseString JSONValue]; |
NSLog(@"type : %@", [jsonObject objectForKey:@"Type"] ); |
No comments:
Post a Comment