我做了一些關於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塊中的代碼都沒有被調用。提前致謝!