I'd like to maniplate the following curl request into swift(or objective-c).
curl -X POST \ -d "login_id=mylogin_id" \
-d "api_key=myapi_key" \
https://~~~~~/v2/authenticate/api
The following is what I wrote.
func authentication(){
var loginID = "mylogin_id"
var apiKey = "myapi_key"
var post:NSString = "login_id=\(loginID)&api_key=\(apiKey)"
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string:"https://~~~~~/v2/authenticate/api")!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
}
If the login is successful a token will be returned, however, I cannot get it.
{"auth_token": "ea6d13c7bc50feb46cf978d137bc01a2"}
I referred this link. Thank you for your kindness.
////// ※Update Jan4th PM2:30
I have rewritten the code from "var request~~" as following, then get "Error", therefore it looks like this code returns urlData as nil.
If you will find how to solve problem, please help me.
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
//request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
//request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if (urlData != nil){
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
let res = response as NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300){
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
}
}else{
NSLog("Error");
}