Swift 3 Urlsession.Shared() Ambiguous Reference to Member 'Datatask(With:Completionhandler:) Error (Bug)

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

The compiler is confused by the function signature. You can fix it like this:

let task = URLSession.shared.dataTask(with: request as URLRequest) {

But, note that we don't have to cast "request" as URLRequest in this signature if it was declared earlier as URLRequest instead of NSMutableURLRequest:

var request = URLRequest(url:myUrl!)

This is the automatic casting between NSMutableURLRequest and the new URLRequest that is failing and which forced us to do this casting here.

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

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.

Ambiguous reference to member 'dataTask(with:completionHandler:)' connect to server

The problem is almost certainly the return value of server.execute(). Maybe it's a NSURL or NSURLRequest rather than URL or URLRequest. Maybe it's an optional. Maybe it's something completely different. Bottom line, if the parameter to dataTask is not a non-optional URL or URLRequest, you can get the error you did. Without seeing what execute returns, we're just guessing, but it's the likely culprit.


A couple of unrelated observations:

  1. I wouldn't use Data or URLResponse as parameter names to the dataTask closure. Those are names of data types. I would use data and response (or don't even specify response because you're not using it), instead, to avoid confusion (for both you and the compiler).

  2. You have a lot of extraneous casts that only add noise to the code. E.g. windows is an array of UIWindow, so why bother doing as UIWindow when you get the first item from that array.

  3. You have a couple of optional chaining sequences that you later force unwrap. There's no point in doing that. Eliminate the optional chaining in that process. Thus, instead of storyboard? followed by ! later:

    let new_view = (self.storyboard?.instantiateViewController(withIdentifier: "tab_bar"))! as UIViewController

    You can just use storyboard!:

    let controller = self.storyboard!.instantiateViewController(withIdentifier: "tab_bar")
  4. You've got a couple of extraneous options that you can remove if you want. E.g. .allowFragments for JSONSerialization is unnecessary (and probably undesirable). Or a completion of nil for your UIAlertAction and present is unnecessary, too. Not a big deal, but it just adds noise to your code.

  5. As a matter of convention, we don't use _ characters to separate words in a variable name. We use camelCase. So, for example, rather than current_view, we'd use currentView. (Or, because that's a window, I'd actually use window, which is even simpler.)

  6. There's no point in using do-try-catch pattern if you're not doing anything in the catch block. Why throw an error if you're not going to do anything when you catch it. Just use try? if all you care about is whether it succeeded or not.

Thus, the code can be cleaned up a bit to something like:

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

guard let data = data,
let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
let result = json["result"] as? String else {
print("no result")
return
}

DispatchQueue.main.async {
if result == "0" {
let alert = UIAlertController(title: "Incorrect Username", message: "The username you entered doesn't appear to belong to an account. Please check your username and try again", preferredStyle: .alert)
let action = UIAlertAction(title: "Try Again", style: .default)
alert.addAction(action)
self.present(alert, animated: true)
} else {
UserDefaults.standard.set(result, forKey: "user_id")
let window = UIApplication.shared.windows[0]
let controller = self.storyboard!.instantiateViewController(withIdentifier: "tab_bar")
UIView.transition(from: window.rootViewController!.view, to: controller.view, duration: 0.65, options: .transitionFlipFromRight, completion: { _ in
window.rootViewController = controller
})
}
}
}
task.resume()

Now, I've replaced server.execute() with request because I don't know what execute is doing, but use whatever is appropriate (see the beginning of this answer).

Ambiguous reference to member 'dataTask(with:completionHandler:)'

try something like this

 guard let requestUrl = URL(string:yourUrlString) else { return }
let request = URLRequest(url:requestUrl)
let task = session.dataTask(with: request) {
(data, response, error) in
if error == nil {
//JSONSerialization
}
}

Ambiguous reference to member 'dataTask(with:completionHandler:)' error

The method expects native URLRequest, not NSMutableURLRequest.

var request = URLRequest(url: url!)

And a JSON dictionary in Swift 3+ is [String:Any] not [String:AnyObject]

ambigouous reference to member 'datatask(with:completionhandler:)'

The compiler is complaining because the function SwiftBuilder returns a String and there are multiple methods on URLSession named dataTask(with:completion:), but none of them take a String for the first argument.

If you need SwiftBuilder to continue to return a string for some other part of your code, then for here you'll need to convert that string to a URL.

Something like the following should work:

let session = URLSession(configuration: .default)

let imageUrlString = StringBuilder()
if let imageUrl = URL(string: imageUrlString) {
let downloadPicTask = session.dataTask(with: imageUrl) { (data, response, error) in
// The download has finished.

And so on... let me know if that makes sense.

migrating to Swift3 - Ambiguous reference to member 'dataTask(with:CompletionHandler:)'

The compiler wants native URLRequest rather than NSMutableURLRequest

var request = URLRequest(url: url)
// request.httpMethod = "GET" <- GET is the default
request.cachePolicy = .reloadIgnoringLocalCacheData // <- renamed enum case
request.timeoutInterval = 10


Related Topics



Leave a reply



Submit