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:
I wouldn't use
Data
orURLResponse
as parameter names to thedataTask
closure. Those are names of data types. I would usedata
andresponse
(or don't even specifyresponse
because you're not using it), instead, to avoid confusion (for both you and the compiler).You have a lot of extraneous casts that only add noise to the code. E.g.
windows
is an array ofUIWindow
, so why bother doingas UIWindow
when you get the first item from that array.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")
You've got a couple of extraneous options that you can remove if you want. E.g.
.allowFragments
forJSONSerialization
is unnecessary (and probably undesirable). Or acompletion
ofnil
for yourUIAlertAction
andpresent
is unnecessary, too. Not a big deal, but it just adds noise to your code.As a matter of convention, we don't use
_
characters to separate words in a variable name. We use camelCase. So, for example, rather thancurrent_view
, we'd usecurrentView
. (Or, because that's a window, I'd actually usewindow
, which is even simpler.)There's no point in using
do
-try
-catch
pattern if you're not doing anything in thecatch
block. Why throw an error if you're not going to do anything when you catch it. Just usetry?
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
How to Check How Long Ago Was the App Last Opened
Why It Shows "Ld: Framework Not Found Bolts"
How to Access a Specific Field from Cloud Firestore Firebase in Swift
How to Record Video of Front and Back Camera At a Time in Ios
Scrolling Issue on Position Fixed Element on Ios
Check If There Is an Emoji Contained in a String
How to Get the Root Directory of My iOS App
Wkwebview Not Loading Webpage - Renders Blank Screen in Swift
How to Center Horizontally Uicollectionview Cells
How to Create a Custom Pop Up View With Swift
Iphone/Ipad: How to Make Uitextfield Readonly (But Not Disabled)
Uiimageview - How to Get the File Name of the Image Assigned
How to Load Image from Local Path iOS Swift (By Path)
Take Screenshots in the iOS Simulator
Detect Tap on a Button in Uitableviewcell for Uitableview Containing Multiple Sections
Ansible Regex_Findall Multiple Strings
Swift: How to Split Up a [String] Resulting in a [[String]] With a Given Subarray Size