iOS像足迹App那样自动启动,长时间iOS后台保活

1,519 阅读2分钟

zhuanlan.zhihu.com/p/44317140 足迹App的使用方法,这个App可以完全无感的、不用打开App自动记录用户去到哪里,在哪里停留了。 想要做到这个功能需要让App自动在某个时刻被唤醒,以及长时间保活。

先说保活

image.png iOS13.0+的设备,支持多场景,共有上图中的Unattached、Foreground Inactive、Foreground Active、Forground Inactive、Background、Suspended 6种状态。

Unattached:多个场景的情况,如果创建的场景不是当前显示的场景,那么场景处于Unattached状态;

Foreground Inactive:应用启动后,显示启动图的过程中,处于Foreground Inactive状态;

Forground Active:应用启动后,显示出来我们设置的rootViewController之后,场景处于Forground Active;

Foreground Inactive:应用启动后,场景处于显示状态,数据加载完毕,且用户和App没有交互过程中,处于Forground Inactive状态;

Background:用户点击Home键、或者是切换App后、锁屏后,应用进入Background状态;

Suspended:进入Background后,应用的代码不执行后,应用进入Suspended状态;(代码是否在运行,可以在应用中写定时器,定时输出内容,从Xcode控制台,或Mac端控制台查看是否有输出内容来判断)

截屏2023-10-14 上午10.22.11.png

首先需要把后台模式的这个开关打开,然后使用beginBackgroundTaskWithName开始一段短的后台任务,但是网上很多方案到这里就结束了,这样只会运行一小会儿,想要更长的运行还需要别的办法。

    
    self.backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:kBgTaskName expirationHandler:^{
       if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
           [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
           self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
       }
    }];
}

我的SDK能做到无上限的运行,直到电池电量耗尽。感兴趣的可以私聊我了解。

Demo

应用启动之后每隔一秒更新BadgeCount,通过观察小红点数字可以直观看到应用被后台自动拉起,存活了多久

    static** NSInteger count = 0;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    _badgeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(_badgeTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_badgeTimer, ^{
        [[UNUserNotificationCenter currentNotificationCenter] setBadgeCount:count++
                                                      withCompletionHandler:nil];
    });

    dispatch_resume(_badgeTimer);

录屏效果可以看 alive-demo.mov www.aliyundrive.com/s/eYWVifUuz… 点击链接保存,或者复制本段内容,打开「阿里云盘」APP ,无需下载极速在线查看,视频原画倍速播放。

可以看到现在运行了557秒接近十分钟了。 Screenshot 2023-10-14 at 13.37.04.png