iOS Background downloads when the app is not active

后端 未结 8 1475
日久生厌
日久生厌 2020-11-27 13:28

When my app is initially downloaded, the user needs to download a large file something like 200MB (upper limit). I definitely can\'t expect the user to keep the app open til

8条回答
  •  余生分开走
    2020-11-27 13:32

    In one of my apps, I was loading huge amount of data. I definitely can't expect the user to keep the app in foreground until the data is downloaded. I just use following code to get the data downloading while app is in background. Its working properly :-)
    Please go through following steps:

    1) use following line in header file of ViewController

       @property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;
    

    synthesis it in .m file.

    2) in ViewDidLoad assign UIBackgroundTaskIdentifier like:

       self.backgroundTask = UIBackgroundTaskInvalid;
    

    3) Use following line of code, here I am just keeping on getDataFromServer method inside beginBackgroundTaskWithExpirationHandler: block.

            self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    
            [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
            self.backgroundTask = UIBackgroundTaskInvalid;
        }];
    
        /* Here your downloading Code, let say getDataFromServer method */
    
        [self getDataFromServer]; // Its dummy method
    
        /* Your downloading Code End Here */
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
            [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
            self.backgroundTask = UIBackgroundTaskInvalid;
        });
    

    4) If you want to check time remaining to download data in background, include following line in applicationDidEnterBackground:(UIApplication *)application delegate method of AppDelegate:

          NSLog(@"Background time remaining = %.1f seconds", [UIApplication sharedApplication].backgroundTimeRemaining);
    

提交回复
热议问题