我做了一些关于beginBackgroundTaskWithExpirationHandler的研究,我不认为我正确理解它。我的印象是,如果我们的应用程序进入后台,那么我可以在其中包含一个长期任务,该任务将继续运行。因此,当您第一次运行我们的应用时,您可以从我们的服务器下载更多数据,为用户提供更多信息。由于这可能需要一段时间,我希望此任务在后台和睡眠模式下运行(如果可能)。beginBackgroundTaskWithExpirationHandler,从服务器下载数据
我没有beginBackgroundTaskWithExpirationHandler原来的功能,当用户点击下载时调用的样子:
-(void) HandleDownload:(NSNotification *)notification
{
DataManager *dmgr = [TestApp sharedDelegate].AppDataManager;
NSString *nextPacketName = [dmgr GetNextPacketName];
int totalNumberPackets = [dmgr GetRowCountForTable:@"Manifest"];
if (nextPacketName == nil)
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:DownloadReferenceSequenceNotification object:nil];
self.ProgressLabel.hidden = YES;
self.ProgressBar.hidden = YES;
}
else
{
self.ProgressLabel.hidden = NO;
self.ProgressLabel.text = [NSString stringWithFormat:@"Downloading %@", nextPacketName];
self.ProgressBar.hidden = NO;
self.ProgressBar.progress += 1./(totalNumberPackets);
WebServiceManager *wmgr = [WebServiceManager sharedInstance];
[wmgr GetPacket:nextPacketName]; // This function creates the NSURL and starts the request
}
}
此功能假定应用程序是在前台。我试图做有这个任务在后台是:
-(void) HandleDownload:(NSNotification *)notification
{
UIApplication *app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier taskID;
taskID = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Background task not completed");
[app endBackgroundTask:taskID];
DataManager *dmgr = [TestApp sharedDelegate].AppDataManager;
NSString *nextPacketName = [dmgr GetNextPacketName];
int totalNumberPackets = [dmgr GetRowCountForTable:@"Manifest"];
if (nextPacketName == nil)
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:DownloadReferenceSequenceNotification object:nil];
self.ProgressLabel.hidden = YES;
self.ProgressBar.hidden = YES;
}
else
{
self.ProgressLabel.hidden = NO;
self.ProgressLabel.text = [NSString stringWithFormat:@"Downloading %@", nextPacketName];
self.ProgressBar.hidden = NO;
self.ProgressBar.progress += 1./(totalNumberPackets);
WebServiceManager *wmgr = [WebServiceManager sharedInstance];
[wmgr GetPacket:nextPacketName]; // This function creates the NSURL and starts the request
}
NSLog(@"Time remaining: %f", app.backgroundTimeRemaining);
}];
if (taskID == UIBackgroundTaskInvalid) {
NSLog(@"Failed to create background task identifier");
}
}
我要对这个在试图总结我的长期运行的任务在beginBackgroundTaskWithExpirationHandler块的正确方法?它看起来不像我,因为expiratinHandler块中的代码都没有被调用。提前致谢!