I want to send my JSON to a URL (POST and GET).
NSMutableDictionary *JSONDict = [[NSMutableDictionary alloc] init];
[JSONDict setValue:"myValue" forKey:"myKey"];
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:nil];
My current request code isn’t working.
NSMutableURLRequest *requestData = [[NSMutableURLRequest alloc] init];
[requestData setURL:[NSURL URLWithString:@"http://fake.url/"];];
[requestData setHTTPMethod:@"POST"];
[requestData setValue:postLength forHTTPHeaderField:@"Content-Length"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[requestData setHTTPBody:postData];
Using ASIHTTPRequest is not a liable answer.
Sending
POSTandGETrequests in iOS is quite easy; and there’s no need for an additional framework.POSTRequest:We begin by creating our
POST‘sbody(ergo. what we’d like to send) as anNSString, and converting it toNSData.objective-c
Next up, we read the
postData‘slength, so we can pass it along in the request.Now that we have what we’d like to post, we can create an
NSMutableURLRequest, and include ourpostData.swift
And finally, we can send our request, and read the reply by creating a new
NSURLSession:objective-c
swift
GETRequest:With the
GETrequest it’s basically the same thing, only without theHTTPBodyandContent-Length.objective-c
swift
On a side note, you can add
Content-Type(and other data) by adding the following to ourNSMutableURLRequest. This might be required by the server when requesting, e.g, a json.objective-c
Response code can also be read using
[(NSHTTPURLResponse*)response statusCode].swift
Update:
sendSynchronousRequestis deprecated from ios9 and osx-elcapitan (10.11) and out.