在我的Swift
应用程序中,我正在检查用户的位置并将其发送到我的后端代码。我的Swift App在使用位置管理器时非常快地消耗电量
我该代码全部放在AppDelegate
,它看起来是这样的:用我的应用程序后
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()
}
}
现在:
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")!)
}
}
}
除此之外我还使用这两种方法一段时间以来,电池消耗非常快,而且整个手机也变得越来越热。我想改变这种行为并修复它,所以手机只发送一次位置(当它是fixed
),然后在位置发生重大变化时这样做。 你能给我一个提示,我怎么能从这里开始,为什么电池的排水速度如此之快?
没有任何东西耗尽电池,就像说'startUpdatingLocation'并将其保持打开状态。这显然是你在做什么(虽然你没有显示足够的代码来确定)。 – matt
@matt目前我在'applicationWillTerminate中也使用'locationManager.stopUpdatingLocation()locationManager = nil',但我想这还不够? – user3766930
我应该在哪一点停止更新位置? – user3766930