I am trying to implement HTTP requests.
Here is the objective C implementation
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
I started by writing:
let request = NSMutableURLRequest()
request .setValue(postLength, forHTTPHeaderField: "Content-Lenght")
request .setValue(application/json, forHTTPHeaderField: Accept)
1.The json request is giving me an error.
2.I cannot convert the setURL and SetHTTPBody from objective C to swift. I could not find the option for these.
Any help would be appreciated. Thank you.
They have become properties. Most setter methods with a single argument have become properties.
The problem with your json line is you did not have quotes around "Accept."
let request = NSMutableURLRequest()
request.url = url
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField:"Content-Length")
request.setValue("application/json", forHTTPHeaderField:"Accept")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
request.postBody = postData
Here is how i do it in swift :
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With