在我的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时),然后在位置发生重大变化时发送。
你能给我一个提示,我怎么能从这里开始,为什么电池消耗这么快?

最佳答案

至于电池耗尽,运行仪器,看看是什么在消耗CPU。我猜不是位置经理。
就只知道重大变化而言,苹果有一个用于此的API。
startMonitoringSignificantLocationChanges()
注意:当设备移动500时,应用程序可能会收到通知
距离上次通知的米或更多。不应该期望
每五分钟通知一次以上。如果
设备能够从网络中检索数据,位置管理器
更有可能及时发送通知。

关于ios - 使用定位管理器时,我的Swift应用会很快耗尽电池电量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42632381/

10-11 22:46
查看更多