Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode Error Ambiguous reference to member 'dataTask(with:completionHandler:)' [duplicate]

Tags:

xcode

swift3

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

like image 999
Jacob Blacksten Avatar asked Nov 21 '16 20:11

Jacob Blacksten


1 Answers

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.

like image 98
Rob Avatar answered Nov 17 '22 16:11

Rob