iOS 借助定位实现“保活”策略

疑惑

你是否有过类似的体验,当你刚刚来到一个商业区,命名没打开任何APP,手机就会收到push给你推荐周围的"吃喝玩乐",那他们又是怎么做到的呢?

##解密

其实,我们可以通过监听当位置变化,在用户无感知的情况下在后台悄悄拉齐我们的进行来处理特定的逻辑。

不是感觉很不可思议?不用着急,我们先复习一下iOS定位的相关原理------Core Location

由上图可以看出,系统每次检测到位置变化时,都会产生一个event,然后遍历所有App,查看每个App是否有权限并且是该event的观察者,如果符合条件,系统就会拉起该App的进程。

##试验

建一个空项目,在App启动的时候注册位置监听,并且在首次启动后给App后台访问用户位置的权限,代码如下:

复制代码
@interface AppDelegate ()<CLLocationManagerDelegate>
@property (nonatomic,strong) CLLocationManager  *locationManager;
@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    [_locationManager requestAlwaysAuthorization];
    [_locationManager setAllowsBackgroundLocationUpdates:true];
    [_locationManager startMonitoringSignificantLocationChanges];
    NSLog(@"test:=====didFinishLaunchingWithOptions");
    return YES;
}

注册监听,当用户位置变化时打印log:

复制代码
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
     CLLocation*location = locations[0];
     NSLog(@"test:纬度=========%f 经度===========%f",location.coordinate.latitude,location.coordinate.longitude);
}

准备工作已经就绪,现在开始试验:

1、启动App后同意相关协议,然后杀死App后台。

2、改变设备位置,如果使用模拟器可以开启模拟移动定位,我这里设置的是模拟drive。

3、打开控制台,过滤log如图:

我们可以发现,虽然进程已经被我们主动杀死,但是当位置变化时,系统会将我们的进程拉起,并且执行方法didFinishLaunchingWithOptions中的内容(log:test:=====didFinishLaunchingWithOptions),由于我们在didFinishLaunchingWithOptions方法中注册了位置变化监听,所以当位置发生变化时didUpdateLocations也会被执行到,认证了之前的猜想

##结论
当位置变化时,系统会拉起符合条件的App进程,并执行didFinishLaunchingWithOptions方法里面的内容,并且这种操作是在用户无感知的情况下完成的,我们可以通过这种方式实现后台App进程保活策略。

相关推荐
Cutecat_1 天前
视频字幕处理工具横向:提取模式 vs 编辑模式,该如何选择
android·前端·ios·语音识别
2601_961845421 天前
法考真题及答案解析|历年真题|资料已整理
linux·windows·ubuntu·macos·centos·gnu
大熊猫侯佩1 天前
WWDC26 SwiftUI 进化之路:砸碎黑盒,彻底迎来开发自由!
ios·swiftui·swift
游戏开发爱好者81 天前
iPhone真机调试有哪些方法?一次定位推送权限问题时整理出来的几种方案
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
Allen Su1 天前
【Mac 教程系列第 20 篇】macOS 鼠须管(Squirrel)皮肤大全(持续更新)
macos·rime·squirrel·rime 输入法皮肤大全
LinMin_Rik1 天前
Mac上获取私钥证书P12文件(也可以给win11的HbuilderX使用)
macos
音视频牛哥2 天前
macOS如何实现RTSP/RTMP低延迟播放? SmartMacPlayer技术实战探究
macos·大牛直播sdk·mac rtsp播放器·mac rtmp·mac rtmp播放器·mac平台播放rtsp·mac平台播放rtmp
大熊猫侯佩2 天前
WWDC26 最被忽视的王炸:告别“伪并发”陷阱,Swift 6.4 的 async defer
ios·swift·编程语言
一杯奶茶¥2 天前
苹果系统可引导镜像 macOS 原版可引导镜像
macos
BugShare2 天前
Mac 上原生开发的开源免费、尽享丝滑数据库工具
数据库·macos·开源