8

I have a swift 2.3 project I just updated to swift 3.0 and the following code broke.

    let task = URLSession.shared.dataTask(with: request, completionHandler: {
        data, response, error in

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

        print("response = \(response)")

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

I am unaware how to fix it

1 Answers1

18

You can get that error if the request is a NSURLRequest rather than a URLRequest.

let url = URL(string: urlString)!
let request = URLRequest(url: url)

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

    print("response = \(response)")

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

Or, if you're mutating the URLRequest, use var:

let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = ...

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

    print("response = \(response)")

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

Also, note, I've replaced NSString with String.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • This all works for me with single url `https:....` strings but when `request` is an array from json objects `session.dataTask(with: avArray)` I get a `Ambiguous reference to member 'dataTask(with:completionHandler:)'` from Xcode. How do I refactor for an array? – Edison Mar 27 '19 at 08:56
  • Iterate through them, e.g. `for string in avArray { ... }` and perform the request inside the loop. – Rob Mar 27 '19 at 15:09
  • I'm already enumerating. Please have a look. https://stackoverflow.com/questions/55387104/nserrorfailingurlstringkey – Edison Mar 27 '19 at 22:15
  • @tymac - Yep, that problem is not related to the enumeration and the initiation of the requests. It’s something else (either authentication issue or some WatchKit specific issue). – Rob Mar 27 '19 at 22:55