iOS开发 - 百度地图后台持续定位

之前有做一个定位的项目,类似嘀嘀打车那样。 需要后台持续定位。

这里选择了百度地图,不过在后台持续定位方面, 之前只是简单的设置如下:


不过经测试发现, 这样设置完,在后台运行大概30分钟,又会被crash掉。 重新打开应用则自动恢复定位。


当然,这不是我们想要的效果,所以折腾了下,实现了后台持续定位。

总的来说,就是利用进入后台后我们可操控的10分钟,来完成一些事情。

为达到持续定位,每10分钟。自动重新开启定位。这样就解决问题了。


具体如下:


AppDelegate.h

@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier bgTask;

AppDelegate.m

- (void)backgroundHandler
{
    NSLog(@"### -->backgroundinghandler");
    
    UIApplication* app = [UIApplication sharedApplication];
    
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
        
    }];
    
    // Start the long-running task
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        // 您想做的事情,
        // 比如我这里是发送广播, 重新激活定位
        // 取得ios系统唯一的全局的广播站 通知中心
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        //设置广播内容
        NSDictionary *dict = [[NSDictionary alloc]init];
        //将内容封装到广播中 给ios系统发送广播
        // LocationTheme频道
        [nc postNotificationName:@"LocationTheme" object:self userInfo:dict];

    });
    
}

- (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.
    
    BOOL backgroundAccepted = [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{ [self backgroundHandler]; }];
    
    if (backgroundAccepted)
        
    {
        NSLog(@"backgrounding accepted");
    }

    [self backgroundHandler];
}



然后在开启定位的位置,成为广播接收者,并且重新激活定位

//初始化BMKLocationService
    myLocService = [[BMKLocationService alloc]init];
    myLocService.delegate = self;
    //启动LocationService
    [myLocService startUserLocationService];

NSNotificationCenter *nc2 = [NSNotificationCenter defaultCenter];
    
    // 成为听众一旦有广播就来调用self recvBcast:函数
    [nc2 addObserver:self selector:@selector(activeLocation:) name:@"LocationTheme" object:nil];

- (void) activeLocation:(NSNotification *)notify
{
    [myLocService stopUserLocationService];
    //初始化BMKLocationService
    myLocService = [[BMKLocationService alloc]init];
    myLocService.delegate = self;
    //启动LocationService
    [myLocService startUserLocationService];
}


当然,上面的方式,可能方法比较渣,代码也写的比较乱。

只是提供一种解决办法而已。


评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Colin丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值