POST Request in Swift with key-value pairs

假如想象 提交于 2019-12-19 04:23:44

问题


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)

Thanks in advance.


回答1:


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



回答2:


Updated the code for Swift 4 + small improvements. Based on @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: "&")
}


来源:https://stackoverflow.com/questions/27203708/post-request-in-swift-with-key-value-pairs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!