如何将以下代码从Swift 2转换为Swift 5?

时间:2019-05-02 20:53:44

标签: swift swift2 swift5

我相信下面的代码是用Swift 2编写的。如何将语法转换为最新的Swift(5)?

使用Xcode进行转换时,它会出现类似以下错误:

  

通话中额外的参数“ usingEncoding”

  

无法调用非函数类型“ URLSession”的值

原始(需要帮助转换):

let request = NSMutableURLRequest(URL: NSURL(string: "http://www.sample.com/sample.php")!)
        request.HTTPMethod = "POST"

        let postString = "a=\(customerLabel!)"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil {
                print("error=\(error)")
                return
            }

            print("response = \(response)")

            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")
        }
        task.resume()
    }

这是我的尝试,但有错误:

let request = NSMutableURLRequest(url: URL(string: "http://www.sample.com/sample.php")!)
request.httpMethod = "POST"
let postString = "a=\(customerLabel!)"
request.HTTPBody = postString.data(usingEncoding: NSUTF8StringEncoding)

let task = URLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if error != nil {
        print("error=\(error)")
        return
    }

    print("response = \(response)")

    let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    print("responseString = \(responseString)")
}
task.resume()

1 个答案:

答案 0 :(得分:2)

  1. 请勿使用NSMutableURLRequest。使用URLRequest
  2. 不要使用NSString,请使用String
  3. 查看URLSession文档,发现您需要shared,而不是sharedInstance()
  4. data(using .utf8)
  5. 许多其他修复程序。

这是您的固定代码,可以在完成处理程序中更好地处理可选内容:

var request = URLRequest(url: URL(string: "http://www.sample.com/sample.php")!)
request.httpMethod = "POST"
let postString = "a=\(customerLabel!)"
request.httpBody = postString.data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("error=\(error)")
        return
    }

    print("response = \(response)")

    if let data = data, let responseString = String(data: data, encoding: .utf8) {
        print("responseString = \(responseString)")
    }
}
task.resume()