我对用于将参数发布到php webservice的代码有点困惑。此代码是创建帖子连接还是仅使用get连接。因为url的最大字符限制(2048个最大字符)我必须使用iphone app和php文件之间的post连接。此代码是否适用于长数据,如两个位置之间的所有纬度和经度(稍后将需要在服务器上发送)。我搜索了很多,但我仍然感到困惑。请帮帮我。 代码:
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{
}
})
答案 0 :(得分:1)
是的,代码创建了一个post方法
我使用的代码在
之下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()
答案 1 :(得分:0)
POST方法有2种方式,取决于API,一种是单个URL,你的请求体是一个字典(例如" type":" updateUserDetail", ..),第二个是将您的postString
附加到带有空体的URL,您所做的是将假设附加到请求正文的URL的字符串放置并且可能无法正常工作