-->

Issues with A background URLSession with identifie

2019-06-10 03:15发布

问题:

I tried this code in my project to download large files in background and it works fine. I start downloading in UIViewController. If I go to another view and back to the UIViewController ,it stop reloading the progress bar.

I got the Issues with A background URLSession with identifier already exists!. I Want to create new session every time when UIViewController load. I want invalidate all background session when dismiss the view controller. I tried all possibilities to resolve this issue but don’t get succeed.

Click Here

回答1:

When you create a background session, you're doing two things:

  • Telling nsurlsessiond (a background daemon) to create a session.
  • Creating a local session in your app that is connected to that session.

The purpose of the identifier is to allow your app to reconnect to the external session (controlled by nsurlsessiond) if your app gets terminated by the operating system.

To my knowledge, it is not normally possible for your app to voluntarily dissociate its session from the background session. So when your app tries to create a session with the same identifier, suddenly there are two sessions that are both trying to talk to the same external session in nsurlsessiond, and things go very wrong. That's not a supported way to use the API.

The background session object must be kept alive the entire time that your app is running. Don't try to dispose of it and recreate it within a single launch. You should not ever create a session with the same ID unless your app gets relaunched.

Note, however, that if your app gets relaunched to handle background events (iOS only), when you call the completion handler provided by the event, your app's local session does get invalidated, and you need to create it if your app does anything after that. That's the only situation I'm aware of where a background session ever stops being associated with the background session in nsurlsessiond, and thus that's the only situation where you should ever create a session with the same ID twice in a single launch (once when you're asked to handle background events, and then potentially again when you get a didFinishLaunching call to indicate that the user foregrounded your app).