Extra argument 'completionHandler' in call with NSURLSession.sharedSession() - ios

I'm new to swift, I am trying to make a weather app in IOS using swift,
When I the NSURLSession and NSURLSession.sharedSession(), I cant run the app its showing this Extra argument 'completionHandler' in call, What may the cause of this error?
my code:
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL, completionHandler:
{ (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void! in
println(response)
})
downloadTask.resume()

Use dataTaskWithRequest.
Here is a sample how i download image
var dowloadTask = session.dataTaskWithRequest(urlRequest, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
// data to image
let image = UIImage(data: data)
if image != nil {
// do some stuff
// preview
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = image
})
}
})
dowloadTask.resume()

let sharedSession = NSURLSession.sharedSession()
let url = NSURL(string: "")
let task = sharedSession.downloadTaskWithURL(url!, completionHandler: {(location: NSURL!, response: NSURLResponse!, error: NSError!) in
println("Task completed")
})
task.resume()

Related

App sudden crash loading url

I have the following function to load data. The function worked just fine till a couple of days ago. The app crashes trying to load any url, see code below and screenshot. Coding ios/swift just a few days a year, it pretty hard to figure out what's wrong...
class func loadDataFromURL(_ url: URL, completion:#escaping (_ data: Data?, _ error: NSError?) -> Void) {
let session = URLSession.shared
// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTask(with: url, completionHandler: { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
if let responseError = error {
completion(nil, responseError)
} else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode != 200 {
let statusError = NSError(domain:"com.xyz", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(nil, statusError)
} else {
completion(data, nil)
}
}
} as! (Data?, URLResponse?, Error?) -> Void)
loadDataTask.resume()
}
Use below code with latest Swift 3.0 syntax it works on Xcode 8.2:-
func loadDataFromURL(_ url: URL, completion:#escaping (_ data: Data?, _ error: NSError?) -> Void) {
let session = URLSession.shared
// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTask(with: url) { (data, response, error) in
if let responseError = error {
completion(nil, responseError as NSError?)
} else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode != 200 {
let statusError = NSError(domain:"com.xyz", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(nil, statusError)
} else {
completion(data, nil)
}
}
}
loadDataTask.resume()
}

SWIFT: session.dataTaskWithURL

I am trying to follow a tutorial on Swift, but the code does not work in Swift 3. Can anyone help update the code?
let url = NSURL(string: path)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!) {
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
print(">>>>> \(data)")
}
I have tried following the suggestions by the compiler, and have changed several of the keywords. The code now looks like this:
let url = NSURL(string: path)
let session = URLSession.shared
let task = session.dataTaskWithURL(url! as URL) {
(data: NSData?, response: URLResponse?, error: NSError?) -> Void in
print(">>>>> \(data)")
}
The error message is:
Cannot convert value of type '(NSData?, URLResponse?, NSError?) -> Void' to expected argument type '(Data?, URLResponse?, Error?) -> Void'
Source Tutorial: Build a simple weather App https://www.youtube.com/watch?v=AoYTuhWZFqM&list=PLoN_ejT35AEjBQ33-L8h2IwG11amXssGk#t=540.527064
let url = URL(string:path)
let session = URLSession.shared
let task = session.dataTask(with: url!) { (data:Data?, response:URLResponse?, error:Error?) in
print()
}

"Cannot convert value of type" error in Swift3

I've got the following error:
with Xcode-beta 5 and Swift. In beta 4 it works fine. Anybody who can help me?
extension UIImageView {
public func imageFromUrl(_ urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {
(response: URLResponse?, data: Data?, error: NSError?) -> Void in
self.image = UIImage(data: data!)
}
}
}
}
Read the error. Look as the type of your error parameter. You've declared it as NSError but the error message is telling you that it should be declared as Error, not NSError.
So you code should be:
extension UIImageView {
public func imageFromUrl(_ urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {
(response: URLResponse?, data: Data?, error: Error?) -> Void in
self.image = UIImage(data: data!)
}
}
}
}

Swift 1.2 to swift 2: Cannot convert value of type to expected argument type

I'm trying to create a NSURLSession task based on a tutorial I found online (https://www.raywenderlich.com/85528/user-accounts-ios-ruby-rails-swift#next_section) and I am getting the following error:
Cannot convert value of type '(NSData!, NSURLResponse!, NSError!) -> ()' to expected argument type '(NSData?, NSURLResponse?, NSError?) -> Void
at this block of code:
let task = session.dataTaskWithRequest(request) { (data: NSData!, response: NSURLResponse!, error: NSError!) in
The function where the issue belongs to can be found here
func sendRequest(request: NSURLRequest, completion:(NSData!, NSError!) -> Void) -> () {
// Create a NSURLSession task
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data: NSData!, response: NSURLResponse!, error: NSError!) in
if error != nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(data, error)
})
return
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
completion(data, nil)
} else {
var jsonerror:NSError?
if let errorDict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error:&jsonerror) as? NSDictionary {
let responseError : NSError = NSError(domain: "HTTPHelperError", code: httpResponse.statusCode, userInfo: errorDict as? [NSObject : AnyObject])
completion(data, responseError)
}
}
}
})
}
The full code block can be found here (https://codeshare.io/uJPcX) at line 68.
Change
data:NSData!, response: NSURLResponse!, error: NSError!
to
data: NSData?, response: NSURLResponse?, error: NSError?
when using data or response etc further down you may have to write is as data! to unwrap the variable, but be careful because if the variable is nil it will crash, so you must check that it is not nil first

Swift to Swift 2 and Cannot Invoke error. What is wrong?

I am using an API that provided the following code that is supposed to provide the song currently playing on the radio station.
func getSongs() {
let url = NSURL(string: "http://api.vicradio.org/songs/current")!
let request = NSMutableURLRequest(URL: url)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data: NSData!, response: NSURLResponse!, error: NSError!) in
if error != nil {
// Handle error...
return
}
println(error)
println(response)
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
task.resume()
}
This code was written for Swift 1 I believe. I'm getting an error that says:
Cannot invoke "dataTaskWithRequest" with an argument of list type "NSMutableURLRequest, (NSData!, NSURLResponse!, NSError!) -> _ "
I'm rather new to Swift, so maybe someone could explain how I could correct this error?
Change:
(data: NSData!, response: NSURLResponse!, error: NSError!)
to:
(data: NSData?, response: NSURLResponse?, error: NSError?)

Resources