为什么在停止应用程序并再次 运行 之后会触发先前的下载完成?

Why previous finish of download fires, after stop app and running again?

我使用两个数组跟踪下载,以跟踪我的下载并知道将它们保存在何处:

private var filesToDownload: NSMutableArray = []
private let startedDownloads: NSMutableArray = []

下载完成后,将它们从两个阵列中删除,并将下载的文件移动到永久位置。

    //is called once the download is complete
internal func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {

    print("download task", downloadTask.originalRequest!)
    print("download tasks", self.startedDownloads)
    // find matching manifestObject through finished downloadTask and use it to generate path

    let indexDownloadTask = self.startedDownloads.indexOfObjectIdenticalTo(downloadTask.originalRequest!)
    let listItem = self.filesToDownload.objectAtIndex(indexDownloadTask)

    // move file
    FileSystem.Instance().moveToRoot(location, relativeTo: listItem["file"] as! String)

    // remove downloadTask and matching item in filesToDownload to enshure the indexes of both arrays still matches
    self.startedDownloads.removeObjectAtIndex(indexDownloadTask)
    self.filesToDownload.removeObjectAtIndex(indexDownloadTask)

    print("Remaining Downloads1: ", self.startedDownloads.count)
    print("Remaining Downloads2: ", self.filesToDownload.count)

    // finished all downloads
    if self.startedDownloads.count == 0 {
        self.working = false
        self.cb(result: 0)
        print("Crazy shit, we finished downloading all files")
    }
}

现在 运行 我的应用程序会自动开始所有下载。如果我让他们完成一切都很好。但是,当我在下载过程中单击 Xcode 中的停止并再次单击 运行 时,它似乎继续 previous 下载并且会抛出边界,因为 previous 下载当然还没有在started downloads的数组中。

为什么之前的下载还在继续?

当使用模拟器并单击停止时,运行ning 会创建一个包含设备 "udid" 的新文件夹和一个新应用程序 "udid" 那么它是否像全新安装?还是继续?如果继续,它不应该使用相同的文件夹来继续相同的文件吗?

当下载完成后,我将它们从临时位置移动到永久位置,但由于它为 运行 上的新点击创建了一个新文件夹,所有尝试移动都将失败。我真的很困惑,这似乎毫无意义。

我从

开始
internal func download(url: NSURL) -> Void {
    self.working = true
    let session = self.getSession()
    let task = session.downloadTaskWithURL(url)
    self.startedDownloads.addObject(task.originalRequest!)
    task.resume()
}

并使用此配置

private let sessionConfig: NSURLSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.company.app.background")

如果您将应用程序设置为后台下载,那么即使应用程序终止,系统也会继续下载。对于从跳板启动的应用程序,系统将在下载完成后在后台重新启动您的应用程序。

文档告诉您,当您启动时,您应该重新创建下载会话对象并设置委托,然后您将收到下载完成消息。

如果您不希望在应用程序启动时交付上次 运行 开始的下载,那么您可能不希望后台下载。

每次任务完成时,您都应该从 appDelegate 中删除完成处理程序:

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {

        DispatchQueue.main.async{
            if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let completionHandler = appDelegate.backgroundTaskCompletionHandler{
                appDelegate.backgroundTaskCompletionHandler = nil
                completionHandler()
            }
        }

}