使用键值对在Swift中POST请求 [英] POST Request in Swift with key-value pairs
本文介绍了使用键值对在Swift中POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须发布帖子请求并在Swift中收到回复。我需要以键值对格式向请求添加值,然后我得到一个答案(0或1)。我不知道如何将Dictionary值添加到请求中。:
I have to make a post request and receive a response in Swift. I need to add values to the request in key-value pairs format and then I get an answer (0 or 1). I don't know how to add the Dictionary values to the request.:
var url = NSURL(string:"www.myurl.com")
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
var params = ["email":"\(txtEmail.text)", "passw":"\(txtPassword.text)"] as Dictionary
let data = //HOW CAN I LOAD THE DATA TO THE HTTPBODY REQUEST??
request.HTTPBody = data
var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)
提前致谢。
推荐答案
解决方案。感谢@Rob:
The solution. Thanks to @Rob :
func loginRequest(url:String, withParams params: [String: String?], postCompleted : (succeeded: Bool, msg: String) -> ()){
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
var bodyData = ""
for (key,value) in params{
if (value == nil){ continue }
let scapedKey = key.stringByAddingPercentEncodingWithAllowedCharacters(
.URLHostAllowedCharacterSet())!
let scapedValue = value!.stringByAddingPercentEncodingWithAllowedCharacters(
.URLHostAllowedCharacterSet())!
bodyData += "\(scapedKey)=\(scapedValue)&"
}
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
var task = session.dataTaskWithRequest(request,
completionHandler: {data, response, error -> Void in
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
postCompleted(succeeded: true, msg: dataString!)
})
task.resume()
}
然后,我调用函数和我可以知道用户是否正确:
Then, I call the function and I can know if the user is correct:
self.loginRequest("http:myurl.com",
withParams: ["email":"email","passw":"passw"])
{
(succeeded: Bool, msg: String) -> () in
if(succeeded) {
if msg == "0"
{
//Incorrect data...
}
else
{
//The login it's ok...
}
}
}
这篇关于使用键值对在Swift中POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文