iOS 后台运行程序

本文介绍如何在iOS应用进入后台时进行资源释放、保存用户数据等操作,并通过开始和结束后台任务的方法确保应用状态的正常保存。

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

@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskIdentifier;



- (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 ( !_screen_locked ) { [self logoutLog:1]; }


    // 标记一个长时间运行的后台任务将开始

    // 通过调试发现,iOS给了我们额外的10分钟(600s)来执行这个任务。

    @weakify(self);

    self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) {

        @strongify(self);

        // 当应用程序留给后台的时间快要到结束时(应用程序留给后台执行的时间是有限的), 这个Block块将被执行

        // 我们需要在次Block块中执行一些清理工作。

        // 如果清理工作失败了,那么将导致程序挂掉


        // 清理工作需要在主线程中用同步的方式来进行

        [self endBackgroundTask];

    }];


    [self submitAllLog];

}


- (void)endBackgroundTask {

    @weakify(self);

    dispatch_async(dispatch_get_main_queue(), ^(void) {

        @strongify(self);

        if (self != nil){

            // 停止定时器

            [self.backgroundTimer invalidate];


            // 每个对 beginBackgroundTaskWithExpirationHandler:方法的调用,必须要相应的调用 endBackgroundTask:方法。这样,来告诉应用程序你已经执行完成了。

            // 也就是说,我们向 iOS 要更多时间来完成一个任务,那么我们必须告诉 iOS 你什么时候能完成那个任务。

            // 也就是要告诉应用程序:好借好还嘛。

            // 标记指定的后台任务完成

            [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];

            // 销毁后台任务标识符

            self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;

        }

    });

}




参考文章:http://blog.youkuaiyun.com/pingchangtan367/article/details/26685477
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值