Action Extension Background Session Download Task

How can you download a file from the web to a shared container while using an action extension?


class ActionViewController: UIViewController, URLSessionDownloadDelegate {

    var downloadTask: URLSessionDownloadTask!
    var backgroundSession: URLSession!

    override func viewDidLoad() {
        super.viewDidLoad()

        let config = URLSessionConfiguration.background(withIdentifier: "com.flaresoftware.scroller.bgsession")
        backgroundSession = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
    }
    @IBAction func addButtonPressed(_ sender: Any) {
        startDownload()
    }
    func startDownload() {
        let url = URL(string: "http://example.com/file.xml")
        downloadTask = backgroundSession.downloadTask(with: url!)
        downloadTask.resume()
    }
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        let fileManager = FileManager.default
        let groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.flaresoftware.scroller")
        let destPath = NSURL(fileURLWithPath: (groupURL?.path)!).appendingPathComponent("file.xml")
    
        do {
            try fileManager.moveItem(at: location, to: destPath!)
            print("App group: \(groupURL?.path)")
        } catch {
            print("\n Save to shared container error \n")
        }
    }
    @IBAction func done() {
        self.extensionContext!.completeRequest(returningItems: self.extensionContext!.inputItems, completionHandler: nil)
    }


I've been experimenting with this code, it works fine in my container app but doesn't work in the extension.

Replies

You don’t seem to be setting the

sharedContainerIdentifier
property of the configuration.

Doing background networking from an extension is quite tricky. You can find a long discussion of this on the old DevForums.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

I could use the help from this long discussion you mention but the link isn't working anymore - is there some other way of accessing it?

I could use the help from this long discussion you mention but the link isn't working anymore

Indeed. That specific post died with the old DevForums. Fortunately, I kept a copy, and reposted it here.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
  • The link in the post is dead, but is accessible (at the time of this comment) here.

Add a Comment