IOS开发模块总结(二)后台运行程序(2)Task completion-UIBackgroundTaskIdentifier

本文介绍如何使用UIBackgroundTaskIdentifier在iOS应用中管理后台任务,包括开始和结束后台任务的方法,以及如何利用定时器监控剩余后台运行时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过UIBackgroundTaskIdentifier可以实现有限时间内在后台运行程序

程序进入后台时调用applicationDidEnterBackground函数,

首先判断设置是否支付后台运行

通过beginBackgroundTaskWithExpirationHandler 获取UIBackgroundTaskIdentifier

后就可以在后台获取一定的时间去指行我们的代码,可以通过

NSTimeInterval backgroundTimeRemanging = [[UIApplication sharedApplication] backgroundTimeRemaining];

NSLog(@"backgroundTimeRemanging = %.02f", backgroundTimeRemanging);

来查看后台可以执行的时间,注意,在beginBackgroundTaskWithExpirationHandler代码块中一定要

调用UIApplicationendBackgroundTask:方法来结束后台任务 如

[app endBackgroundTask:_bgTask];

这里的_bgTask是通过beginBackgroundTaskWithExpirationHandler得到的.要保持一致。

最后,当我们的应用回到前台,如果我们的后台任务还在执行中,我们需要确保我们在干掉它: 

- (void)applicationWillEnterForeground:(UIApplication *)application{ 

if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){ 

[self endBackgroundTask]; } 

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@property (nonatomic, strong) NSTimer * myTimer;
- (BOOL)isMutiltaskingSupported;
@end

// 判断当前设备是否支持 后台多任务
- (BOOL)isMutiltaskingSupported{
    BOOL result = NO;
    if ( [[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
        result = [[UIDevice currentDevice] isMultitaskingSupported];
    }
    return result;
}
// 定时器调用方法
- (void)timerMethod:(NSTimer *)paramSender{
    NSTimeInterval backgroundTimeRemanging = [[UIApplication sharedApplication] backgroundTimeRemaining];
    if ( backgroundTimeRemanging == DBL_MAX) {
        NSLog(@"Background Time Remaining = Undeterminded");
    }
    //--显示后台任务还剩余的时间
    NSLog(@"Background Timer Remaining = %.02f Seconds", backgroundTimeRemanging);
}
// 进入挂起状态时候,调用方法
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    if ( [self isMutiltaskingSupported] == NO) {
        NSLog(@"---> 不支持后台多任务");
        return;
    }
    
    self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundTask];
    }];<pre name="code" class="objc">    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                    target:self
                                                  selector:@selector(timerMethod:)
                                                  userInfo:nil
                                                   repeats:YES];
    

}
// 任务完成,处理释放对象
- (void)endBackgroundTask{
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    __weak AppDelegate *weakSelf = self;
    dispatch_async(mainQueue, ^{
        AppDelegate * strongSelf = weakSelf;
        if ( strongSelf != nil) {
            [strongSelf.myTimer invalidate];
            [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
            strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
        }
    });
}
- (void)applicationWillEnterForeground:(UIApplication *)application{ 
if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){ 
[self endBackgroundTask]; } 
} 






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值