Skip to content

Instantly share code, notes, and snippets.

@r3econ
Created April 3, 2014 12:09
Show Gist options
  • Save r3econ/9953196 to your computer and use it in GitHub Desktop.
Save r3econ/9953196 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];
@prajakta27
Copy link

prajakta27 commented Jan 22, 2017

its giving nsinternalinconsistencyexception exception and app getting crashed, my code is,

{
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if (dic != nil) {
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
request.HTTPBody = JSONData;
}

request.HTTPMethod = @"POST";
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                              
{
    if (!error)
    {
        NSLog(@"Status code: %li", (long)((NSHTTPURLResponse *)response).statusCode);
    }
    else
    {
       NSLog(@"Error: %@", error.localizedDescription);
    }
    
}];
[task resume];

}

tell me correction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment