Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where did setHTTPMethod, setURL and setHTTPBody go in swift?

Tags:

ios

swift

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.

like image 426
Gokhan Dilek Avatar asked Jun 08 '14 14:06

Gokhan Dilek


2 Answers

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
like image 107
BJ Homer Avatar answered Sep 19 '22 12:09

BJ Homer


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

like image 6
jaumard Avatar answered Sep 18 '22 12:09

jaumard