Note that there are some explanatory texts on larger screens.

plurals
  1. POiOS - How to attach a JSON Object to web request? (NOT using NSURLConnection)
    text
    copied!<p>I am trying to send some web requests to back-end API I have setup on my web server. However, to make things universal I would like to send an entire JSON object to the back-end, and do all my filtering of data there to determine what the request is for, what arguments to pass, etc.</p> <p>I will be making many requests from one class to different services, so I don't want to use NSURLConnection as it gets messy having to filter through all the results in the completion handler to determine which request was originally being fetched.</p> <p>I like how NSURLConnection allows you to attach a JSON object like this, but I want to know how to do it with a different method (say [NSData dataWithContentsOfURL:])</p> <pre><code>NSMutableDictionary *postObject = [[NSMutableDictionary alloc] init]; [postObject setValue:@"login" forKey:@"request"]; [postObject setValue:inputUsername.text forKey:@"userName"]; [postObject setValue:inputPassword.text forKey:@"password"]; NSData *postData = [NSJSONSerialization dataWithJSONObject:postObject options:0 error:NULL]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"WEB_URL"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; [request setTimeoutInterval:20]; </code></pre> <p>Any suggestions?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload