I am confused with the background download using URLSession. Reading the blogs on the Internet, I have got many kinds of using background download and I don't know which one is the corrent way and now I have some doubt.
Precodition: schedule one task at a time.
1. Invoke the completionHandler or be killed.
I know that if I want to download files one by one, I should hold the completionHandler myself and invoke it whenever all my tasks are added and finished, or the app will be killed. However sometimes my app will be killed once simply one of my tasks is finished. Because I don't know the exact time when I will invoke the completion handler because of the network status and the amount of tasks, nor do the OS knows these. So how the OS thinks that my app does not invoke the handler and should be killed and kills it? I don't know why my app will be killed so fast.
2. Where to add a new task.
Till now, I add new task when my current task is finished in the delegate method:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location;
I have read some article that some developers add new task in:
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
But I think that adding task in the latter is more complex because if the current task is finished while the app is in foreground, this method will not be called so the new tasks will not be added. So which one the the right way? Or should I add task in both of the methods above?
3. No response if not run by xcode
Bellow occur in foreground. Sometimes, I run my app from the home screen and try downloading files, but I can't receive any response. So I try to debug it and run it with xcode, It begins to download normally and I can receive data now... If I stop it and reopen it from the home screen, it fails to receive data again... I don't know when this will occur but this indeed occur. I know that low power and network status will affect it but both of these seem not bad...
Could anyone helps ?? I want to know what is the right way to download with URLSession...