How can I translate the following code from Swift 2 to Swift 5?

195 Views Asked by At

I believe the following code below is written in Swift 2. How can the syntax be converted to the latest Swift (5)?

When using Xcode for conversion, it leaves me with errors like:

Extra argument 'usingEncoding' in call

and

Cannot call value of non-function type 'URLSession'

Original (Need Help Converting):

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()
    }

This was my attempt but it has errors:

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

There are 1 best solutions below

0
rmaddy On BEST ANSWER
  1. Don't use NSMutableURLRequest. Use URLRequest.
  2. Don't use NSString, use String.
  3. Look at the URLSession documentation and see that you need shared, not sharedInstance().
  4. data(using .utf8).
  5. Lots of other fixes.

Here's your fixed code with better handling of optionals in the completion handler:

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()