I have FirstViewController
with button to move in SecondTableViewController
. In SecondTableViewController
I have cell and if I click on cell downloading starts.
Problem: If I move in SecondTableViewController
from FirstViewController
to start downloading and return in FirstViewController
and after move in SecondTableViewController
I get this:
A background URLSession with identifier com.example.DownloadTaskExample.background already exists!
And I can not download my files. How to fix it?
my code in SecondTableViewController
:
var backgroundSession: URLSession!
var index = 0
override func viewDidLoad() {
super.viewDidLoad()
let sessionConfig = URLSessionConfiguration.background(withIdentifier: "com.example.DownloadTaskExample.background")
backgroundSession = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: OperationQueue())
}
code for download files:
let url = URL(string: "link")!
let downloadTaskLocal = ViewController.backgroundSession.downloadTask(with: url)
downloadTaskLocal.resume()
New code:
class Networking {
static let shared = Networking()
var backgroundSession = URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "com.example.DownloadTaskExample.background"), delegate: URLSession() as? URLSessionDelegate, delegateQueue: OperationQueue())
}
class ViewController: UITableViewController, URLSessionDownloadDelegate {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let url = URL(string: "link")!
let downloadTaskLocal = Networking.shared.backgroundSession.downloadTask(with: url)
downloadTaskLocal.resume()
}
}
UPD
class BackgroundSession: NSObject {
static let shared = BackgroundSession()
static let identifier = "com.example.DownloadTaskExample.background"
var session: URLSession!
private override init() {
super.init()
let configuration = URLSessionConfiguration.background(withIdentifier: BackgroundSession.identifier)
session = URLSession(configuration: configuration, delegate: self as? URLSessionDelegate, delegateQueue: OperationQueue())
}
}
class ViewController: UITableViewController, URLSessionDownloadDelegate{
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let url = URL(string: "http:link\(indexPath.row + 1)")!
let downloadTaskLocal = BackgroundSession.shared.session.downloadTask(with: url)
downloadTaskLocal.resume()
}
}