在我的Swift
应用程序中,我检查用户的位置并将其发送到我的后端代码。
我的代码全部放在AppDelegate
中,它看起来像这样:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
NotificationCenter.default.addObserver(self, selector:
#selector(AppDelegate.notificationConfirmationSent),
name: NSNotification.Name(rawValue: locationUpdKey), object: nil)
initLocationManager()
return true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location = locations.last
let coord = location.coordinate
longitude = coord.longitude
latitude = coord.latitude
NotificationCenter.default.post(name: Notification.Name(rawValue: locationUpdKey), object: self)
location_fixed = true;
}
func notificationConfirmationSent()
{
if(defaults.object(forKey: "uniqueId") != nil) {
let currentTime = Date().timeIntervalSince1970
if (currentTime - timeInterval > 30) {
print("SENDING DATA TO WEBSERVICE FROM NOTIFICATION")
timeInterval = currentTime
sendCurrentUserPositionToWebService(self.longitude, latitude: self.latitude, uniqueId: defaults.string(forKey: "uniqueId")!)
}
}
}
除此之外,我还使用这两种方法:
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
print("NotDetermined")
case .restricted:
print("Restricted")
case .denied:
print("Denied")
case .authorizedAlways:
print("AuthorizedAlways")
case .authorizedWhenInUse:
print("AuthorizedWhenInUse")
locationManager.distanceFilter = 200
locationManager.startUpdatingLocation()
}
}
func initLocationManager() {
print("init location manager app delegate")
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
//locationManager.startMonitoringSignificantLocationChanges()
locationManager.distanceFilter = 200
locationManager.startUpdatingLocation()
} else {
locationManager.requestWhenInUseAuthorization()
}
}
现在,在使用我的应用程序一段时间后,电池耗电非常快,整个手机也变热了。我想更改此行为并进行修复,因此手机只会发送一次该位置(当它fixed
时),然后在该位置发生重大变化时发送。
你能给我一个提示,我怎么能从这里开始,为什么电池的排水速度如此之快?
答案 0 :(得分:0)
就电池耗尽而言,运行仪器并查看耗费CPU的电量。我的猜测是,它不是位置经理。
只要知道重大变化,Apple就有一个API。
startMonitoringSignificantLocationChanges()
注意只要设备移动500,应用就会收到通知 距其先前通知的米或更多。不应该期待 通知频率高于每五分钟一次。如果 设备能够从网络中检索位置管理器的数据 更有可能及时发送通知。
答案 1 :(得分:0)
一般的想法是你可以调用startMonitoringSignificantLocationChanges,你现在设置location_fixed = true。您还需要停止位置更新,因此您的代码可能如下所示:
location_fixed = true
manager.stopUpdatingLocations()
manager.startMonitoringSignificantLocationChanges()