Using URLSession and background fetch together with remote notifications using firebase

心已入冬 提交于 2019-12-02 05:16:24

A few observations:

  1. When your app is restarted by handleEventsForBackgroundURLSessionIdentifier, you have to not only save the completion handler, but you actually have to start the session, too. You appear to be doing the former, but not the latter.

    Also, you have to implement urlSessionDidFinishEvents(forBackgroundURLSession:) and call (and discard your reference to) that saved completion handler.

  2. You appear to be doing a data task. But if you want background operation, it has to be download or upload task. [You have edited question to make it a download task.]

  3. In userNotificationCenter(_:willPresent:completionHandler:), you don't ever call the completion handler that was passed to this method. So, when the 30 seconds (or whatever it is) expires, because you haven't called it, your app will be summarily terminated and all background requests will be canceled.

    So, willPresent should call its completion handler as soon it done starting the requests. Don't confuse this completion handler (that you're done handling the notification) with the separate completion handler that is provided later to urlSessionDidFinishEvents (that you're done handling the the background URLSession events).

  4. Your saved background session completion handler is not right. I'd suggest:

    var backgroundSessionCompletionHandler: (() -> Void)?
    

    When you save it, it is:

    backgroundSessionCompletionHandler = completionHandler   // note, no ()
    

    And when you call it in urlSessionDidFinishEvents, it is:

    DispatchQueue.main.async {
        self.backgroundSessionCompletionHandler?()
        self.backgroundSessionCompletionHandler = nil
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!