私の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()
}
}
:私はまた、これらの2つの方法を使用していることに加えて
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