草庐IT

swift - URLSession downloadTask 在后台运行时的行为?

coder 2023-09-15 原文

我有一个应用程序需要下载一个可能相当大的文件(可能大到 20 MB)。我一直在阅读 URLSession downloadTasks 以及当应用程序进入后台或被 iOS 终止时它们如何工作。我希望继续下载,根据我的阅读,这是可能的。我找到了一篇博文 here详细讨论了这个主题。

根据我所读到的内容,我首先创建了一个如下所示的下载管理器类:

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.")
        }
    }
}

我还在我的 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)")
            }
        }
    }

最后,我像这样开始测试下载:

    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()

当我运行这段代码并开始下载时,我看到委托(delegate)方法被调用,但我也看到一条消息:

A background URLSession with identifier com.example.testapp.background already exists!

认为这是因为 application:handleEventsForBackgroundURLSession:completionHandler:

中的以下调用而发生的
let session = DownloadManager.shared.session

我的 DownloadManager 类中 session 属性的 getter(我直接从前面引用的博客文章中获取)总是尝试使用后台配置创建一个新的 URLSession。据我了解,如果我的应用程序已终止,那么这将是“重新连接”到原始 URLSession 的适当行为。但由于可能应用程序没有被终止,而是只是进入后台,当调用 application:handleEventsForBackgroundURLSession:completionHandler: 时,我应该引用 URLSession 的现有实例。至少我认为这就是问题所在。谁能为我澄清这种行为?谢谢!

最佳答案

您的问题是每次引用 session 变量时都在创建一个新 session :

var session : URLSession {
        get {
            let config = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).background")
            return URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
        }
    }

相反,将 session 保留为实例变量,然后获取它:

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
}

当我在 Playground 上执行此操作时,它表明重复调用给出了相同的 session ,并且没有错误:

session 不存在于进程中,它是操作系统的一部分。每次访问写入的 session 变量时,您都会增加引用计数,这会导致错误。

关于swift - URLSession downloadTask 在后台运行时的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46939142/

有关swift - URLSession downloadTask 在后台运行时的行为?的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  3. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

  4. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  5. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  6. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  7. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  8. ruby-on-rails - 无法让 rspec、spork 和调试器正常运行 - 2

    GivenIamadumbprogrammerandIamusingrspecandIamusingsporkandIwanttodebug...mmm...let'ssaaay,aspecforPhone.那么,我应该把“require'ruby-debug'”行放在哪里,以便在phone_spec.rb的特定点停止处理?(我所要求的只是一个大而粗的箭头,即使是一个有挑战性的程序员也能看到:-3)我已经尝试了很多位置,除非我没有正确测试它们,否则会发生一些奇怪的事情:在spec_helper.rb中的以下位置:require'rubygems'require'spork'

  9. ruby-on-rails - before_filter 运行多个方法 - 2

    是否有可能:before_filter:authenticate_user!||:authenticate_admin! 最佳答案 before_filter:do_authenticationdefdo_authenticationauthenticate_user!||authenticate_admin!end 关于ruby-on-rails-before_filter运行多个方法,我们在StackOverflow上找到一个类似的问题: https://

  10. Vscode+Cmake配置并运行opencv环境(Windows和Ubuntu大同小异) - 2

    之前在培训新生的时候,windows环境下配置opencv环境一直教的都是网上主流的vsstudio配置属性表,但是这个似乎对新生来说难度略高(虽然个人觉得完全是他们自己的问题),加之暑假之后对cmake实在是爱不释手,且这样配置确实十分简单(其实都不需要配置),故斗胆妄言vscode下配置CV之法。其实极为简单,图比较多所以很长。如果你看此文还配不好,你应该思考一下是不是自己的问题。闲话少说,直接开始。0.CMkae简介有的人到大二了都不知道cmake是什么,我不说是谁。CMake是一个开源免费并且跨平台的构建工具,可以用简单的语句来描述所有平台的编译过程。它能够根据当前所在平台输出对应的m

随机推荐