Last active
December 14, 2015 11:38
-
-
Save lamprosg/5080784 to your computer and use it in GitHub Desktop.
(iOS) Parsing JSON - iOS 5+
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -(void)parseJSONFromURL:(NSString *)jsonURL { | |
| //Prepare URL request to get the user timeline | |
| NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:jsonURL]]; | |
| /*******************Sychronous Call Request**************/ | |
| //Perform request | |
| NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; | |
| /********************************************************/ | |
| /*******************Asychronous Call Request*************/ | |
| NSURL *URL = [NSURL URLWithString:jsonURL]; | |
| NSURLRequest *Request = [NSURLRequest requestWithURL:URL]; | |
| //Using Grand Central Dispatch | |
| dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul); | |
| dispatch_async(queue, ^{ | |
| NSURLResponse *response = nil; | |
| NSError *error = nil; | |
| NSData *receivedData = [NSURLConnection sendSynchronousRequest:Request | |
| returningResponse:&response | |
| error:&error]; | |
| }); | |
| /******************************* | |
| USE THIS IF YOU WANT TO BE RUN ON MAIN THREAD | |
| You're not allowed to perform user interface updates in the background queue, | |
| so use the dispatch_get_main_queue to let that background queue dispatch the user interface updates back | |
| to the main queue, once the main queue is available | |
| dispatch_async(dispatch_get_main_queue(), ^{ | |
| }); | |
| *******************************/ | |
| //OR | |
| //Without Grand Central Dispatch | |
| responseData = [[NSMutableData data] retain]; | |
| NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/json"]];//asynchronous call | |
| //If you plan to check for cookies | |
| NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHttpCookieStorage]; | |
| [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways]; | |
| [request setHTTPShouldHandleCookies:YES]; | |
| NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; | |
| //It might need this if it doesn't work | |
| [connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; | |
| [connection start]; | |
| #pragma mark - Delegate methods | |
| //MUST COMFORM THE NSURLConnectionDelegate protocol | |
| - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { | |
| // cast the response to NSHTTPURLResponse (if needed) so we can look for 404 etc | |
| NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; | |
| /*******************/ | |
| //If you want to check for the cookie | |
| //Ex. to see if he is logged in or something | |
| if (httpResponse != nil) { | |
| NSArray* cookies = [NSHTTPCookie | |
| cookiesWithResponseHeaderFields:[response allHeaderFields] | |
| forURL:[NSURL URLWithString:@""]]; | |
| if ([cookies count] > 0) { | |
| NSLog(@"cookies from the http POST %@", authToken); | |
| } | |
| } | |
| //Store the cookie | |
| [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:[NSURL URLWithString:@""] mainDocumentURL:nil]; | |
| // Now we can print all of the cookies we have: | |
| for (NSHTTPCookie *cookie in cookies) | |
| NSLog(@"Name: %@ : Value: %@, Expires: %@", cookie.name, cookie.value, cookie.expiresDate); | |
| /*****/ | |
| You can store only 1 cookie if you want to store one | |
| [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:thecookie]; | |
| /*****/ | |
| /*******************/ | |
| //Check http://www.w3.org/Protocols/HTTP/HTRESP.html for status codes | |
| if ([httpResponse statusCode] >= 400) { | |
| // do error handling here | |
| } | |
| } | |
| - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { | |
| [responseData appendData:data]; | |
| } | |
| - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { | |
| NSLog(@"%@", error); | |
| } | |
| - (void)connectionDidFinishLoading:(NSURLConnection *)connection { | |
| NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; | |
| [responseData release]; | |
| NSDictionary *jsonObject = [responseString JSONValue]; | |
| NSLog(@"type : %@", [jsonObject objectForKey:@"Type"] ); | |
| //OR | |
| //A model class containing properties with the same name as the keys in the json object | |
| Record *record = [[Record alloc] init]; | |
| //jsonObject is a NSDictionary. Set the corresponding values to our model class | |
| [record setValuesForKeysWithDictionary:jsonObject]; | |
| //Which means | |
| //record.keyValue = [jsonObject objectForkey: @"keyValue"]; | |
| //keyValue is a @property of Record class | |
| [connection release]; | |
| } | |
| /********************************************************/ | |
| //Parse the retrieved json | |
| NSError *jsonParsingError = nil; | |
| id *json_object = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&jsonParsingError]; | |
| //The json_object is either a NSArray or a NSDictionary depending on the structure of the original JSON document | |
| if ( [jsonObject isKindOfClass:[NSArray class]] ) | |
| { | |
| //json_object is a NSArray object | |
| } | |
| else | |
| { | |
| //json_object is a NSDictionary object | |
| for(NSDictionary *jsonObject in json_object) | |
| { | |
| NSLog(@"Item: %@", item); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*********************************************************/ | |
| //Here are some POST method examples | |
| //PHP will hndle them with $_POST['']; | |
| //1. Send an image | |
| NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed@"localimage.png"]); | |
| NSMutableURLRequest *request = [[NSMutableURLRequest alloc] | |
| initWithURL:[NSURL URLWithString:@"http://www.cimgf.com/testpostimage.php"]]; // Not a real URL. | |
| [request setHTTPMethod:@"POST"]; | |
| //Sets the specified HTTP header field. | |
| [request setValue:@"image/png" forHTTPHeaderField:@"Content-type"]; | |
| [request setValue:[NSString stringWithFormat:@"%d", [imageData length]] forHTTPHeaderField:@"Content-length"]; | |
| [request setHTTPBody:imageData]; | |
| NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; | |
| //It might need this if it doesn't work | |
| [connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; | |
| [connection start]; | |
| //2. Some values | |
| NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: | |
| [NSURL URLWithString:@"http://www.cimgf.com/test/testform.php"]]; | |
| [request setHTTPMethod:@"POST"]; | |
| NSString *postString = @"go=1&name=Bad%20Bad%20Bug&description=This%20bug%20is%20really%20really%20super%20bad."; | |
| //Sets the specified HTTP header field. | |
| [request setValue:[NSString stringWithFormat:@"%d", [postString length]] forHTTPHeaderField:@"Content-length"]; | |
| [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; | |
| NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; | |
| //It might need this if it doesn't work | |
| [connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; | |
| [connection start]; | |
| //3. Send an XML string | |
| NSMutableURLRequest *request = [[NSMutableURLRequest alloc] | |
| initWithURL:[NSURL | |
| URLWithString:@"http://www.cimgf.com/testpost.php"]]; | |
| [request setHTTPMethod:@"POST"]; | |
| [request setValue:@"text/xml" forHTTPHeaderField:@"Content-type"]; | |
| NSString *xmlString = @"<data><item>Item 1</item><item>Item 2</item></data>"; | |
| [request setValue:[NSString stringWithFormat:@"%d", [xmlString length]] forHTTPHeaderField:@"Content-length"]; | |
| [request setHTTPBody:[xmlString dataUsingEncoding:NSUTF8StringEncoding]]; | |
| NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; | |
| //It might need this if it doesn't work | |
| [connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; | |
| [connection start]; | |
| #pragma mark - NSURLConnection delegate methods | |
| //MUST COMFORM THE NSURLConnectionDelegate protocol | |
| -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ | |
| // cast the response to NSHTTPURLResponse so we can look for 404 etc | |
| NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; | |
| //Check http://www.w3.org/Protocols/HTTP/HTRESP.html | |
| if ([httpResponse statusCode] >= 400) { | |
| // do error handling here | |
| } | |
| } | |
| -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ | |
| } | |
| -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ | |
| } | |
| -(void)connectionDidFinishLoading:(NSURLConnection *)connection{ | |
| } | |
| /*************************************************************************/ | |
| //NOW TO JSON | |
| -(NSString*)serializeJSON { | |
| //First json object | |
| //{ "username" : "obj1" , "surname" : "obj2" , "name" : "obj3" } | |
| NSMutableDictionary* mineDictionary = [[NSMutableDictionary alloc] init]; | |
| [mineDictionary setObject:@"obj1" forKey:@"username"]; | |
| [mineDictionary setObject:@"obj2" forKey:@"surname"]; | |
| [mineDictionary setObject:@"obj3" forKey:@"name"]; | |
| //Second json object | |
| //{ "username" : "obj3" , "surname" : "obj4" , "name" : "obj5" } | |
| NSMutableDictionary* yourDictionary = [[NSMutableDictionary alloc] init]; | |
| [yourDictionary setObject:@"obj3" forKey:@"username"]; | |
| [yourDictionary setObject:@"obj4" forKey:@"surname"]; | |
| [yourDictionary setObject:@"obj5" forKey:@"name"]; | |
| //Our json array containing both objects | |
| NSMutableArray* jsonArray = [[NSMutableArray alloc] init]; | |
| [jsonArray addObject:mineDictionary]; | |
| [jsonArray addObject:yourDictionary]; | |
| NSData* nsdata = [NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONReadingMutableContainers error:nil]; | |
| NSString* jsonString =[[NSString alloc] initWithData:nsdata encoding:NSUTF8StringEncoding]; | |
| return jsonString; | |
| } | |
| //SEND THE JSON | |
| NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: | |
| [NSURL URLWithString:@"something.php"]]; | |
| [request setHTTPMethod:@"POST"]; | |
| NSString *json = [self serializeJSON]; | |
| //Sets the specified HTTP header field. | |
| [request setValue:[NSString stringWithFormat:@"%d", [json length]] forHTTPHeaderField:@"Content-length"]; | |
| [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; | |
| [request setHTTPBody:json]; | |
| NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; | |
| //It might need this if it doesn't work | |
| [connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; | |
| [connection start]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Get JSON object from an input stream | |
| NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://url_that_returns_json_stream"]]; | |
| NSInputStream *stream = [[NSInputStream alloc] initWithData:data]; | |
| [stream open]; | |
| if (stream) | |
| { | |
| NSError *parseError = nil; | |
| id jsonObject = [NSJSONSerialization JSONObjectWithStream:stream options:NSJSONReadingAllowFragments error:&parseError]; | |
| if ([jsonObject respondsToSelector:@selector(objectForKey:)]) | |
| { | |
| for (NSDictionary *dict in [jsonObject objectForKey:@"results"]) | |
| { | |
| NSLog(@"Tweet: %@", [tweet objectForKey:@"text"]); | |
| } | |
| } | |
| } | |
| else | |
| { | |
| NSLog(@"Failed to open stream."); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //http://www.raywenderlich.com/30445/afnetworking-crash-course | |
| //https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking | |
| #import "AFHTTPClient.h" | |
| #import "AFHTTPRequestOperation.h" | |
| AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://yourServerAddress.com/"]]; | |
| //Accept headers (for cookies) | |
| [httpClient setDefaultHeader:@"Accept" value:@"application/json"]; | |
| [httpClient setParameterEncoding:AFFormURLParameterEncoding]; | |
| //GET REQUEST | |
| NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" | |
| path:@"http://yourServerAddress.com/example?name=foo" | |
| parameters:nil]; | |
| [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]]; | |
| AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request | |
| success:^(AFHTTPRequestOperation *operation, id responseObject) | |
| { | |
| //-- This block gets invoked when the operation is successful | |
| } | |
| failure:^(AFHTTPRequestOperation *operation, NSError *error) | |
| { | |
| //-- This block gets invoked when the operation fails | |
| }]; | |
| //OR | |
| NSString *pathStr = @"/example?name=foo"; | |
| [httpClient getPath:pathStr parameters:paramaters | |
| success:^(AFHTTPRequestOperation *operation, id responseObject) | |
| { | |
| //Get the cookie if you need to validate the user | |
| NSString *cookie = [[((NSHTTPURLResponse *)[operation response]) allHeaderFields] objectForKey:@"Set-Cookie"]; | |
| //If you first login, save the cookie for future requests. | |
| [httpClient setDefaultHeader:@"cookie" value:cookie]; | |
| //To remove it just put @"" to the value | |
| //OR | |
| /***************************************/ | |
| //VALIDATE USER WITH COOKIE | |
| if (cookie != nil) | |
| { | |
| //Get the cookie you have saved prevously and check if they are the same | |
| NSString *savedCookie = [httpClient defaultValueForHeader:@"cookie"]; | |
| if (savedCookie != nil && ![savedCookie isEqualToString:cookie]) | |
| { | |
| //they are the same, user is authenticated | |
| } | |
| } | |
| /***************************************/ | |
| //Get the response | |
| NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; | |
| } | |
| failure:^(AFHTTPRequestOperation *operation, NSError *error) | |
| { | |
| NSLog(@"Error: %@", error.localizedDescription); | |
| }]; | |
| //-- The following codes allow you to track the download progress (if required) | |
| [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) | |
| { | |
| //-- This block gets invoked periodically as the download progress | |
| NSLog(@"bytesRead: %i; totalBytesRead: %lld; totalexpected: %lld", bytesRead, totalBytesRead, totalBytesExpectedToRead); | |
| }]; | |
| //-- end of the download progress tracking code | |
| [httpClient enqueueHTTPRequestOperation:operation]; | |
| /****************************/ | |
| //POST REQUEST | |
| AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://yourServerAddress.com/"]]; | |
| //-- the content of the POST request is passed in as an NSDictionary | |
| //-- in this example, there are two keys with an object each | |
| NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys: | |
| object1, @"KEY_NAME_1", | |
| object2, @"KEY_NAME_2", | |
| nil]; | |
| [httpClient postPath:@"/postExample/" parameters:parameters | |
| success:^(AFHTTPRequestOperation *operation, id responseObject) | |
| { | |
| NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; | |
| NSLog(@"Request Successful, response '%@'", responseStr); | |
| } | |
| failure:^(AFHTTPRequestOperation *operation, NSError *error) | |
| { | |
| NSLog(@"Error: %@", error.localizedDescription); | |
| }]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment