防止dispatch_after()后台任务被执行 [英] Prevent dispatch_after() background task from being executed

查看:970
本文介绍了防止dispatch_after()后台任务被执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题。当我的应用程序进入后台我希望它在一段时间后执行一个功能。这是我做的:

This is my issue. When my application enters background I want it to perform a function after certain period of time. This is what I do:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    isRunningInBackground = YES;

    taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];

    int64_t delayInSeconds = 30;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
    {
        [self doSomething];
    });
}

- (void)doSomething
{
   NSLog(@"HELLO");
}

taskIdentifier 在myAppDelegate.h文件中声明如下:

taskIdentifier variable is declared in myAppDelegate.h file like this:

UIBackgroundTaskIdentifier taskIdentifier;

一切都按原样工作,我看到控制台打印HELLO刚好30秒后就没了。但是如果应用程序进入前台直到30秒结束,我不希望执行 doSomething 。所以我需要取消它。这是我怎么做:

Everything works as it supposed to, I see that console prints HELLO just right after 30 seconds are gone. But I don't want doSomething to be executed if the app enters foreground until 30 seconds are over. So I need to cancel it. This is how i do that:

- (void)applicationWillEnterForeground:(UIApplication *)application
{    
    isRunningInBackground = NO;
    [self stopBackgroundExecution];
}

- (void)stopBackgroundExecution
{
    [[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
    taskIdentifier = UIBackgroundTaskInvalid;
}

但是不幸的是它不会取消 doSomething ,仍然执行。我做错了什么?如何取消该功能?

But unfortunately it doesn't cancel doSomething, it is still performed. What am I doing wrong? How do I cancel that function?

推荐答案

为什么还要使用GCD?你可以使用 NSTimer ,并在你的应用程序返回到前端时将其无效。

Why even use GCD? You could just use an NSTimer and invalidate it when your app returns to the foregound.

这篇关于防止dispatch_after()后台任务被执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆