您的位置:首页 > 其它

百度地图API后台持续定位、指南针改变位置问题

2016-08-26 14:25 1041 查看
最近的需要用到后台持续定位,项目中又是用的百度地图API,遇到点麻烦:

1、进入后台,手机静置,定位持续16分钟左右就停止了,但是还是无限后台效果;但如果一直运动,让定位持续更新,定位服务一直保持

其实是API中的自动暂停定位属性 默认是true,设置为false,就不会自动关闭了

_locService = BMKLocationService()
_locService!.delegate = self
// 允许后台定位 打开
_locService!.allowsBackgroundLocationUpdates    = true
// 自动暂停定位 关闭
_locService!.pausesLocationUpdatesAutomatically = false
//启动LocationService
_locService!.startUserLocationService()


记得设置Background Modes:



下面是AppDelegate中进入后台后的处理办法:

func applicationDidEnterBackground(application: UIApplication) {
print("进入后台---持续定位")

let application = UIApplication.sharedApplication()
// 设置后台后,600s内触发至少一次的方法
let shouldRestartLoc = application.setKeepAliveTimeout(600, handler: {
self.backgroundHandler()
})

if shouldRestartLoc {
print("backgrouding accepted")
}
else {
backgroundHandler()
}

}

func backgroundHandler() {
let application = UIApplication.sharedApplication()
bgTask = application.beginBackgroundTaskWithExpirationHandler {
if(self.bgTask != UIBackgroundTaskInvalid){
self.bgTask = UIBackgroundTaskInvalid;
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
while (true) {
// 发送通知,重开locationService定位服务
let noticeCenter = NSNotificationCenter.defaultCenter()
noticeCenter.postNotificationName("restartLocationService", object: self, userInfo: nil)
print("剩余时间:\(application.backgroundTimeRemaining)")
sleep(5)
}
}
}


在适当的地方注册通知,实现通知触发的方法即可,在方法中再次开始定位即可

// 注册通知
let notice = NSNotificationCenter.defaultCenter()
notice.addObserver(self, selector: #selector(restartLocationService), name: "restartLocationService", object: nil)
-----------------------------------------------------
// 重新定位
func restartLocationService() {
_locService!.startUserLocationService()
_locService!.allowsBackgroundLocationUpdates = true
_locService!.pausesLocationUpdatesAutomatically = false
}


2、地图图层上的指南针如何移动位置:

虽然API中明确了属性compassPosition来修改位置,但是如果不注意视图的load顺序,修改是无效的。所以注意:需要在mapViewDidFinishLoading之后,再去修改位置,才能生效。

func mapViewDidFinishLoading(mapView: BMKMapView!) {
_mapView!.compassPosition = CGPointMake(10,5) // 设置指南针位置
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息