Skip to content

Instantly share code, notes, and snippets.

@javorosas
Last active September 29, 2015 00:56
Show Gist options
  • Save javorosas/974675aa4c6a2338117b to your computer and use it in GitHub Desktop.
Save javorosas/974675aa4c6a2338117b to your computer and use it in GitHub Desktop.
Send NSDictionary as JSON via POST using NSURLSession
// 1. Populate an NSDictionary with the data you want to send
NSDictionary *exampleData = @{
@"first": @"Javier",
@"last": @"Rosas",
@"address": @"742 Evergreen Terrace"
};
// 2. Serialize your data to JSON format and store it in an NSData object
NSErrpr *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:exampleData options:0 error:&error];
// 3. Set up the request
NSURL *myUrl = [NSURL URLWithString:@"https://mysite.com/v1/users"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myUrl];
// 4. Assign our data to the body of the request and set required headers
[request setHTTPBody:jsonData];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// 5. Initialize our NSURLSession object
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
// 6. Get the task and set what will happen at completion
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// 8. Handle the error
}
// 9. Do something with the response object
}];
// 7. Execute request asynchronously
[task resume];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment