当我运行程序时,无论其中的代码是否在一秒钟内完成,后台任务似乎都会运行20秒左右。这是我的viewdidload:
- (void)viewDidLoad
{
[super viewDidLoad];
self.yesButton.layer.cornerRadius = 20;
self.yesButton.layer.borderColor=[UIColor blackColor].CGColor;
self.yesButton.layer.borderWidth= 2.0f;
self.noButton.layer.cornerRadius = 20;
self.noButton.layer.borderColor=[UIColor blackColor].CGColor;
self.noButton.layer.borderWidth= 2.0f;
self.invalidISBNImage.hidden = true;
self.noInternetImage.hidden = true;
[self.yesButton setEnabled:NO];
[self.noButton setEnabled:NO];
if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
{
if([[UIDevice currentDevice] isMultitaskingSupported])
{
UIApplication *application = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if([self canReachInternet])
{
NSString *siteUrl = [NSString stringWithFormat:@"http://www.isbnsearch.org/isbn/%@", isbnSelling];
NSURL *url = [NSURL URLWithString:siteUrl];
NSString *webDataString = [NSString stringWithContentsOfURL:url];
if(webDataString == nil || [isbnSelling isEqualToString:@""])
{
NSLog(@"ISBN not recognized.");
invalidISBN = true;
self.invalidISBNImage.hidden = false;
}
else
{
// This is where I parse some html
}
}
else
{
NSLog(@"Failed to establish a connection to the internet.");
noInternetConnection = true;
self.noInternetImage.hidden = false;
}
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
self.titleLabel.text = title;
self.authorLabel.text = author;
self.editionLabel.text = edition;
self.publisherLabel.text = publisher;
self.datePublishedLabel.text = datePublished;
self.bindingLabel.text = binding;
self.loadingImage.hidden = true;
if(!invalidISBN && !noInternetConnection)
{
[self.yesButton setEnabled:YES];
[self.noButton setEnabled:YES];
}
});
}
}
}
例如,当满足以下条件时: if(webDataString == nil || [isbnSelling isEqualToString:@“”])
此行不能立即生效: self.invalidISBNImage.hidden = false; 我想要的时候。它发生在20秒之后......我认为程序的流程几乎会立即结束后台任务,但即使它在一秒内到达这个部分,它似乎也会运行后台任务还有20秒。是否有一行代码可以完全退出后台任务?