1 Reply
      Latest reply: Jan 13, 2017 1:27 PM by eskimo RSS
      theclayton Level 1 Level 1 (0 points)

        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() {
                let config = URLSessionConfiguration.background(withIdentifier: "com.flaresoftware.scroller.bgsession")
                backgroundSession = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
            @IBAction func addButtonPressed(_ sender: Any) {
            func startDownload() {
                let url = URL(string: "http://example.com/file.xml")
                downloadTask = backgroundSession.downloadTask(with: url!)
            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.

        • Re: Action Extension Background Session Download Task
          eskimo Apple Staff Apple Staff (7,190 points)

          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"