John O'Reilly
11/26/2024, 12:06 PMDaniel Seither
11/26/2024, 12:42 PMMJegorovas
11/26/2024, 12:47 PMJohn O'Reilly
11/26/2024, 12:50 PMMJegorovas
11/26/2024, 1:07 PMclass BackgroundTransfersManager: NSObject {
private var backgroundSession: URLSession!
private override init() {
super.init()
let config = URLSessionConfiguration.background(withIdentifier: "com.company.app.background")
// see, if you need need these 3 parameters
config.sessionSendsLaunchEvents = true
config.isDiscretionary = false
config.httpCookieStorage = nil
backgroundSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
}
...
func upload() {
...
for fragment in fragments {
let url = URL(string: EndpointConstantsKt.FRAGMENT_CONTENT_STORE)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(fragment.keyId)", forHTTPHeaderField: "Content-Type")
let task = self.backgroundSession.uploadTask(with: request, fromFile: tempDirectory.appendingPathComponent(fragment.keyId))
task.resume()
}
...
// if you used `config.sessionSendsLaunchEvents = true`
// that means you needed for your app to be woken up from background to execute some logic after file was uploaded
var backgroundCompletionHandler: (() -> Void)?
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
DispatchQueue.main.async {
self.backgroundCompletionHandler?()
self.backgroundCompletionHandler = nil
}
}
}
// implement needed delegates
// to know when upload has completed you'll need `extension BackgroundTransfersManager: URLSessionDataDelegate` and
// `func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)`
// for progress you can use
// `func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)`
// if you used `config.sessionSendsLaunchEvents = true`
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
BackgroundTransfersManager.shared.backgroundCompletionHandler = completionHandler
}
}
John O'Reilly
11/26/2024, 1:13 PM