Reputation: 170
I am little bit confused with code which i have used to post parameters to php webservice. Is this code creates post connection or just used get connection. because of maximum character limit (2048 max characters) of url i have to use post connection between iphone app and php file. Is this code works for long data like all latitudes and longitudes between two locations (later on will need to send it on server). I have searched a lot but i am still confused. Please help me guyz. Code:
let request = NSMutableURLRequest(URL: NSURL(string: CommonUtils.webservice_path)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let postString = "type=updateUserDetail&Fname=" + fName + "&Lname=" + lName + "&mobile=" + mobileNo + "&phoneCode=" + countryCode + "&user_id=" + iUserId_str!
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if(data==nil){
}else{
}
})
Upvotes: 1
Views: 71
Reputation: 5658
Yes that code create a post method
the code i have used is below
SWIFT 2.0
let post:NSString = "Pram1=\(ratingUp)"
NSLog("PostData: %@",post);
let url:NSURL = NSURL(string:"http://yoururltopost.com")! //change it to your url
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! //data is being encoded
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST" //setting method as post
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept") //set type of api
// request.setValue(apiKey, forHTTPHeaderField: "Authorization") // use if you are use Authorization
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if (error == nil && data != nil)
{
func parseJson()
{
// do whatever you want to do
}else{
// show error
let alertView:UIAlertView = UIAlertView()
alertView.title = "Rating Error"
alertView.message = "Please try after some time"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
dispatch_async(dispatch_get_main_queue(), parseJson)
}
}
task.resume()
Upvotes: 2
Reputation: 9923
There's 2 way for POST method, depends on the API, one is single URL and your request body is an dictionary (eg "type":"updateUserDetail",..), second is append your postString
to the URL with empty body, what u doing is put the string that suppose to append to URL to the request body and that probably wont work
Upvotes: 0