Search code examples
swiftswift3nsurlsessionxcode8

URLSession issue


I'm converting my project to Swift 3.

I have this code in Swift 2.2 :

lazy var downloadsSession: NSURLSession = {
    let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("bgSessionConfiguration")
    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

    return session
}()

And the code is converted to Swift 3:

lazy var downloadsSession: URLSession = {
    let configuration = URLSessionConfiguration.background(withIdentifier: "bgSessionConfiguration")
    let session = URLSession(session: configuration, downloadTask: self, didFinishDownloadingToURL: nil)

    return session
}()

But such error is:

"cannot convert value of type URLSessionConfiguration to expected argument type URLSession"

URLSession have not any method to get URLSessionConfiguration!

Update: Here is picture of swift3 auto correction when used of this function:

let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

enter image description here

How do I fix this code?


Solution

  • The initializer you are looking for URLSession is like init(configuration:delegate:delegateQueue:). So change your initialization of session like this.

    let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)