Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Tuesday, July 23, 2013

Creating an iOS Post Request

Creating a Post Request and Parsing a JSON Response in iOS / Xcode. 

Lets look at a simple example...

// The url to our server endpoint
NSString *url = @"http://www.mydomain.com/myserverendpoint";

// Like the post request I showed you before, I'm going to send the deviceId again, because that is generally useful for establishing 

UIDevice *device = [UIDevice currentDevice];
NSString *deviceRef = [device uniqueIdentifier];
    
NSString *post = [NSString stringWithFormat:@"device_ref=", deviceRef];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
[request setHTTPBody:postData];
   
NSURLResponse *response;
NSError *error;
    
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;

if (error) NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);





About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates