Skip to content

Instantly share code, notes, and snippets.

@JamesHopbourn
Forked from r3econ/gist:9953196
Created January 23, 2022 16:59
Show Gist options
  • Save JamesHopbourn/60935e5b6cf97794c788aa3e50bc3d95 to your computer and use it in GitHub Desktop.
Save JamesHopbourn/60935e5b6cf97794c788aa3e50bc3d95 to your computer and use it in GitHub Desktop.
Posting JSON file using NSURLSession.
// URL of the endpoint we're going to contact.
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/my.json"];
// Create a simple dictionary with numbers.
NSDictionary *dictionary = @{ @"numbers" : @[@1, @2, @3] };
// Convert the dictionary into JSON data.
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary
options:0
error:nil];
// Create a POST request with our JSON as a request body.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = JSONData;
// Create a task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
if (!error)
{
NSLog(@"Status code: %i", ((NSHTTPURLResponse *)response).statusCode);
}
else
{
NSLog(@"Error: %@", error.localizedDescription);
}
}];
// Start the task.
[task resume];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment