使用键值对在Swift中POST请求

时间:2014-11-29 15:10:32

标签: ios xcode post swift key-value

我必须发布帖子请求并在Swift中收到回复。我需要以键值对格式向请求添加值,然后我得到一个答案(0或1)。我不知道如何将Dictionary值添加到请求中。:

    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)

提前致谢。

2 个答案:

答案 0 :(得分:5)

解决方案。感谢@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()
}

然后,我调用该函数,我可以知道用户是否正确:

        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...
                }
            }
        }

答案 1 :(得分:1)

更新了Swift 4 +小改进的代码。基于@imj work。

/// Converts the dictionary to key values
func convertToParameters(_ params: [String: String?]) -> String {
    var paramList: [String] = []

    for (key, value) in params {
        guard let value = value else {
            continue
        }

        guard let scapedKey = key.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {
            print("Failed to convert key \(key)")
            continue
        }

        guard let scapedValue = value.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {
            print("Failed to convert value \(value)")
            continue
        }

        paramList.append("\(scapedKey)=\(scapedValue)")
    }

    return paramList.joined(separator: "&")
}