I've tried the following:
func setupAssetDownload() {
// Create new background session configuration.
let configuration = URLSessionConfiguration.background(withIdentifier: "123124123152")
// Create a new AVAssetDownloadURLSession with background configuration, delegate, and queue
let downloadSession = AVAssetDownloadURLSession(configuration: configuration,
assetDownloadDelegate: self,
delegateQueue: OperationQueue.main)
let url = URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8")// HLS Asset URL
let asset = AVURLAsset(url: url!)
// Create new AVAssetDownloadTask for the desired asset
let downloadTask = downloadSession.makeAssetDownloadTask(asset: asset,
assetTitle: "assetTitle",
assetArtworkData: nil,
options: nil)
// Start task and begin download
print(downloadTask.debugDescription)
downloadTask?.resume()
}
and implemented
func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {
print("didFinishDownloadingTo \(location.relativePath)")
playOfflineAsset()
}
but the delegate method didFinishDownloadingTo is never called.
Also added didCompleteWithError delegate with no success.
My class is conforming to AVAssetDownloadDelegate.
AVAssetDownloadURLSession always work with real device only..So in your case its seems like you are tried on simulator.
Please go with Real device
Related
I was implementing an upload task using URLSession Uploadtask with the below code:
lazy var urlSession = URLSession(
configuration: .background(withIdentifier: "com.test.xxxxx"),
delegate: self,
delegateQueue: .main
)
var uploadTask = URLSessionUploadTask()
/// Calling uploadtask using 'fileURL' of the asset
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "PUT"
uploadTask = urlSession.uploadTask(with: request, fromFile: fileURL)
uploadTask.resume()
And uploading works as expected, my concern is if I want to use resume data whenever user removes the app from multitask window or any error happens in between uploading a file, how can i achieve it using below delegate method, this delegate method is firing for me, but we don't have any methods to use resume data like func downloadTask(withResumeData resumeData: Data) -> URLSessionDownloadTask for upload task or is it not possible for upload task, please guide me on this. Thank you.
func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
// Here comes when background upload failed with errors
// Such as app closed from the tray ,switched off ,crash occured, etc.
// Then, handle with resumeData
os_log("Download error: %#", type: .error, String(describing: error))
} else {
// Here comes when background upload completed with no error
os_log("Task finished: %#", type: .info, task)
}
}
Edit: I can't see anything related to resume data for upload task in Apple doc also.
I'm using a Series 6 emulator on watchOS7 and I'm trying to upload some JSON data to a remote server using an URLSession background task. However the delegate functions are not being called so I cannot clean up any local data from the upload and handle any errors. I got the original idea from my implementation from this WWDC video WWDC Video. I've looked at many posts on the Internet but nothing I've tried seems to work. Here is my code:
UploadSession class
class UploadSession: NSObject, Identifiable, URLSessionDelegate {
var backgroundTasks = [WKURLSessionRefreshBackgroundTask]()
private lazy var urlSession: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "my.app.watchextension")
config.sessionSendsLaunchEvents = true
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()
func enqueueBackgroundTask(idToken: String, uploadData: Data, url: URL) throws {
//build the JSON object we want to send in this post request
let tempDir = FileManager.default.temporaryDirectory
let localURL = tempDir.appendingPathComponent("throwaway")
try? uploadData.write(to: localURL)
//set up the URLRequest
var request = URLRequest(url: url)
request.httpMethod = K.Upload.httpPost
request.setValue(K.Upload.jsonContent, forHTTPHeaderField: K.Upload.contentType)
request.setValue("\(K.Upload.bearer)\(idToken)", forHTTPHeaderField: K.Upload.authorization)
request.timeoutInterval = K.Upload.httpUploadTimeout
//keep a reference to this class
BackgroundURLSessions.shared.sessions["my.app.watchextension"] = self
//create the upload task and kick it off
let task = urlSession.uploadTask(with: request, fromFile: localURL)
task.earliestBeginDate = Date().advanced(by: 120)//when setting this to zero the upload runs straight away.
task.resume()
}
func addBackgroundRefreshTask(_ task: WKURLSessionRefreshBackgroundTask) {
backgroundTasks.append(task)
}
//gets called when the task background task completes
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
//PROBLEM. This delegate method is never called
if let sessionId = session.configuration.identifier {
//TODO delete any local data copies
//set the session to nil so the system doesn't try to execute it again
BackgroundURLSessions.shared.sessions[sessionId] = nil
}
for task in backgroundTasks {
task.setTaskCompletedWithSnapshot(false)
}
}
//gets called if the background task throws an error
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
//PROBLEM. This delegate method is never called
}
}
BackgroundURLSessions class
class BackgroundURLSessions: NSObject {
static let shared: BackgroundURLSessions = BackgroundURLSessions()
var sessions = [String: UploadSession]()
override private init() {
super.init()
}
}
Extension Delegate class
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
if let session = BackgroundURLSessions.shared.sessions[urlSessionTask.sessionIdentifier] {
session.addBackgroundRefreshTask(urlSessionTask)
} else {
urlSessionTask.setTaskCompletedWithSnapshot(false)
}
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}
Any help really appreciated as I'm really struggling to get this work and it's a vital part of the application. Thanks.
I'm relatively new to swift and I'm having issues trying to call a function in a view controller from a delegate I have defined. How can I call the function in my view controller from this delegate? This is a mixed project consisting of mostly Objective-C code with only one Swift controller. The function is inside of the Swift controller. Below is the delegate class:
class DelegateToHandle302:NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: #escaping (URLRequest?) -> Void) {
//convert to https
let http = request.url!
var comps = URLComponents(url: http, resolvingAgainstBaseURL: false)!
comps.scheme = "https"
let httpsUrl = comps.url!
ViewControllerFunction(url: httpsUrl)
}
I get an error Use of unresolved identifier 'ViewControllerFunction'. I've tried creating an instance of the view controller but don't think that's the correct way to do it as this view controller also has an audio player (it also didn't work).
Here is where I call the delegate from a function inside the view controller:
let urlString = "https://urlthatredirects.com"
let config = URLSessionConfiguration.default
let url = URL(string: urlString)
//set delegate value equal to SessionDelegate to handle 302 redirect
let delegate = DelegateToHandle302()
//establish url session
let session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil)
//set task with url
let dataTask = session.dataTask(with: url!)
//init call
dataTask.resume()
I'm following part of an example on how to get the final URL from a redirection (https://gist.github.com/mgersty/b565ba4c9e9422637f15f52a5317f07e). My view controllers "header" is:
#objc class AudioPlayerController: UIViewController{........}
I hope I've provided enough info to allow anyone to assist me in figuring out what I'm doing wrong. The only thing I need to do is call that function and pass the redirection URL to it.
I'm a bit confused about what you're trying to do, and why you're trying to call a delegate method back into the VC rather than using the completion handler; but I think you've got your delegate pattern back-to-front. I'm assuming the idea is:
the view controller instiagtes the URL session
the url sessions passes of the result of the URLSession to the DelegateToHandle302 to process
DelegateToHandle302 then tries to run a method back in the view controller that launched it.
If this is the case you actually need the VC to be the delegate of the DelegateToHandle302 class, not the other way around.
So within your view controller
let handlerFor302 = DelegateToHandle302()
handlerFor302.delegate = self.
let session = URLSession(configuration: config, delegate: handlerFor302, delegateQueue: nil
//etc... as before
Create a protocol for the delegate to adopt, which defines the desired function
protocol URLProcessor {
func ViewControllerFunction(url: URL)
}
The adopt the protocol in your view controller and implement the method
extension MyViewController: URLProcessor {
func ViewControllerFunction(url: URL) { .... do whatever ...}
and then use the delegate with the protocol method in your DelegateToHandle302
class DelegateToHandle302:NSObject, URLSessionTaskDelegate {
weak var delegate: URLProcessor?
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: #escaping (URLRequest?) -> Void) {
//Process the output
delegate?.ViewControllerFunction(url: httpsUrl)
}
I have an app that needs to download a file which may be rather large (perhaps as large as 20 MB). I've been reading up on URLSession downloadTasks and how they work when the app goes to the background or is terminated by iOS. I'd like for the download to continue and from what I've read, that's possible. I found a blog post here that discusses this topic in some detail.
Based on what I've read, I first created a download manager class that looks like this:
class DownloadManager : NSObject, URLSessionDownloadDelegate, URLSessionTaskDelegate {
static var shared = DownloadManager()
var backgroundSessionCompletionHandler: (() -> Void)?
var session : URLSession {
get {
let config = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).background")
return URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
}
}
private override init() {
}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
DispatchQueue.main.async {
if let completionHandler = self.backgroundSessionCompletionHandler {
self.backgroundSessionCompletionHandler = nil
completionHandler()
}
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
if let sessionId = session.configuration.identifier {
log.info("Download task finished for session ID: \(sessionId), task ID: \(downloadTask.taskIdentifier); file was downloaded to \(location)")
do {
// just for testing purposes
try FileManager.default.removeItem(at: location)
print("Deleted downloaded file from \(location)")
} catch {
print(error)
}
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if totalBytesExpectedToWrite > 0 {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
let progressPercentage = progress * 100
print("Download with task identifier: \(downloadTask.taskIdentifier) is \(progressPercentage)% complete...")
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
print("Task failed with error: \(error)")
} else {
print("Task completed successfully.")
}
}
}
I also add this method in my AppDelegate:
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: #escaping () -> Void) {
DownloadManager.shared.backgroundSessionCompletionHandler = completionHandler
// if the app gets terminated, I need to reconstruct the URLSessionConfiguration and the URLSession in order to "re-connect" to the previous URLSession instance and process the completed download tasks
// for now, I'm just putting the app in the background (not terminating it) so I've commented out the lines below
//let config = URLSessionConfiguration.background(withIdentifier: identifier)
//let session = URLSession(configuration: config, delegate: DownloadManager.shared, delegateQueue: OperationQueue.main)
// since my app hasn't been terminated, my existing URLSession should still be around and doesn't need to be re-created
let session = DownloadManager.shared.session
session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) -> Void in
// downloadTasks = [URLSessionDownloadTask]
print("There are \(downloadTasks.count) download tasks associated with this session.")
for downloadTask in downloadTasks {
print("downloadTask.taskIdentifier = \(downloadTask.taskIdentifier)")
}
}
}
Finally, I start my test download like this:
let session = DownloadManager.shared.session
// this is a 100MB PDF file that I'm using for testing
let testUrl = URL(string: "https://scholar.princeton.edu/sites/default/files/oversize_pdf_test_0.pdf")!
let task = session.downloadTask(with: testUrl)
// I think I'll ultimately need to persist the session ID, task ID and a file path for use in the delegate methods once the download has completed
task.resume()
When I run this code and start my download, I see the delegate methods being called but I also see a message that says:
A background URLSession with identifier com.example.testapp.background already exists!
I think this is happening because of the following call in application:handleEventsForBackgroundURLSession:completionHandler:
let session = DownloadManager.shared.session
The getter for the session property in my DownloadManager class (which I took directly from the blog post cited previously) is always trying to create a new URLSession using the background configuration. As I understand it, if my app had been terminated, then this would be the appropriate behavior to "reconnect" to the original URLSession. But since may app is not being terminated but rather just going to the background, when the call to application:handleEventsForBackgroundURLSession:completionHandler: happens, I should be referencing the existing instance of URLSession. At least I think that's what the problem is. Can anyone clarify this behavior for me? Thanks!
Your problem is that you are creating a new session every time you reference the session variable:
var session : URLSession {
get {
let config = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).background")
return URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
}
}
Instead, keep the session as an instance variable, and just get it:
class DownloadManager:NSObject {
static var shared = DownloadManager()
var delegate = DownloadManagerSessionDelegate()
var session:URLSession
let config = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).background")
override init() {
session = URLSession(configuration: config, delegate: delegate, delegateQueue: OperationQueue())
super.init()
}
}
class DownloadManagerSessionDelegate: NSObject, URLSessionDelegate {
// implement here
}
When I do this in a playground, it shows that repeated calls give the same session, and no error:
The session doesn't live in-process, it's part of the OS. You're incrementing reference count every time you access your session variable as written, which causes the error.
Most of my programming experience is in Shell and Python. I'm fairly new to Swift, like "3 days ago" new. I just can't figure out why didFinishDownloadtingTo is not called when my downloadTask completes. Here's my AppDelegate.swift file:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, URLSessionDelegate, URLSessionDownloadDelegate {
#IBOutlet weak var window: NSWindow!
#IBOutlet var progressind: NSProgressIndicator!
#IBOutlet var outputtext: NSTextField!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
let requestURL: URL = URL(string: "https://www.apple.com")!
let urlRequest: URLRequest = URLRequest(url: requestURL as URL)
let session = URLSession.shared
let downloads = session.downloadTask(with: urlRequest)
print("starting download...")
downloads.resume()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
print("download finished!")
}
}
I'm using Swift 3, and I just cannot find enough documentation on it to figure this out on my own.
I went a little crazy declaring classes trying to figure out why it wasn't working right, so I'm sure there are also some errors there.
It appears to download the file successfully. I've tried with several URLs. The "Disk" and "Network" sections of the debug menu appear consistent with downloading a file of the size at every URL I've tested with.
The thing is that when you use NSURLSession(URLSession in Swift 3) you have to choose if you want to use a delegate or a completion handler, in case of use both, only the completion handler gets called. In your case the delegate is not set so you can't see the call to the delegate methods. Instead you should specify the delegate using the another initializer of NSURLSession like in the following code:
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, URLSessionDelegate, URLSessionDownloadDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
let requestURL: URL = URL(string: "https://www.apple.com")!
let urlRequest: URLRequest = URLRequest(url: requestURL as URL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
let downloads = session.downloadTask(with: urlRequest)
print("starting download...")
downloads.resume()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
print("download finished!")
}
}
And then you should see the delegate method called properly.
I hope this help you
The key lies in the word "delegate". It's like the dog in the night-time in the Sherlock Holmes story. The dog did nothing in the night. The word "delegate" never appears in your code!
But it needs to. didFinishDownloadingTo is a delegate method. You can only receive this method if you are the delegate of the NSURLSession. You need to set self as its delegate. The runtime doesn't magically read your mind and know that you intend this object as the delegate; you have to tell it.