如何在Swift 3,URLRequest上使用httpMethod = POST?

时间:2016-11-22 11:22:47

标签: ios json swift httprequest

我使用json方法工作GET,但是当我通过添加将其转换为POST时;

  request.httpMethod = "POST"

给了我;

  

无法分配属性:' httpMethod'是一个get-only属性Error

我的代码如下可以修复它?如何将其转换为POST

 @discardableResult
    open func  getLoginMethod(_ method: String, parameters: String, completionHandler: @escaping (_ login: [Login]?, _ error: Error?) -> Void) -> URLSessionTask! {
        let session = URLSession.shared
        guard let url = NSURL(string: parameters) else {
            completionHandler(nil, myErrors.InvalidUrlError)
            return nil
        }
        let request = NSURLRequest(url: url as URL)

        let task = session.dataTask(with: request as URLRequest) { data, response, error in
            if error != nil {
                completionHandler(nil, myErrors.getError)
            } else {
                do {
                    let login = try self.getLogin(jsonData: data! as NSData)
                    completionHandler(login, nil)
                } catch {
                    completionHandler(nil, error)
                }
            }
        }
        task.resume()

        return task
    }

我的调用代码下面是get方法我parameters中的变量,POST方法我需要做哪些更改?

  AWLoader.show(blurStyle: .dark, shape: .Circle)

        DispatchQueue.global(qos: .background).async {
            myApp.sharedInstance().getLoginMethod("", parameters: "http://bla.com/Post?Phone=\(self.phone.text)") {login, error in
                if error != nil {
                    DispatchQueue.main.async {
                        //  self.showAlert()

                        print(error!)

                        AWLoader.hide()
                    }
                } else {
                    DispatchQueue.main.async {
                        self.getlogin = login!
                        //    self.collectionView.reloadData()
                        //       AWLoader.hide()

                        //  self.loginButton.alpha = 0
                        print(self.getlogin)


                        AWLoader.hide()
                    }
                }
            }


        }

由于

1 个答案:

答案 0 :(得分:3)

您需要使用NSMutableURLRequest才能修改httpMethod。使用NSURLRequest不会。

示例:

let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"

但更好的是,你应该使用URLRequest struct:

var request = URLRequest(url: url)
request.httpMethod = "POST"

您的重构代码以及其他改进:

@discardableResult
open func getLoginMethod(_ method: String, parameters: String,
                     session: URLSession = .shared,
                     completionHandler: @escaping (_ login: [Login]?, _ error: Error?) -> Void) -> URLSessionTask! {

    guard let url = URL(string: parameters) else {
        completionHandler(nil, myErrors.InvalidUrlError)
        return nil
    }
    var request = URLRequest(url: url)
    request.httpMethod = method
    let task = session.dataTask(with: request) { data, _, _ in
        guard let responseData = data else {
            completionHandler(nil, myErrors.getError)
            return
        }
        do {
            let login = try self.getLogin(jsonData: data as NSData)
            completionHandler(login, nil)
        } catch {
            completionHandler(nil, error)
        }
    }
    task.resume()

    return task
}

编辑: 回答你的第二部分问题。这取决于您的API期望的数据格式 - 无论是multipart/form-data还是json格式,都取决于。 但一般来说,假设您使用的是我提到的URLRequest结构,您应该使用序列化程序将其转换为Data并使用它:

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = <your parameters converted to Data>

通常,您的API会向Content-Type添加正确的URLRequest标头:

request.setValue("application/json", forHTTPHeaderField: "Content-Type")