2017-03-06 7 views
1

Swift 애플리케이션에서 사용자의 위치를 ​​확인하고이를 내 백엔드 코드로 보냅니다.내 Swift 앱이 위치 관리자를 사용하는 동안 배터리를 매우 빠르게 소모합니다.

이에 대한 나의 코드는 모든 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 일 때) 위치를 변경하면 큰 변화가 발생합니다. 여기에서 어떻게 진행하면 좋을지, 정확히 배터리가 너무 빨리 소모되는 이유를 알려주세요.

+0

'startUpdatingLocation'을 말하고 그대로 놔두는 것 외에는 배터리가 소모되지 않습니다. 그리고 그것은 분명히 당신이하고있는 것입니다 (당신이 확실히 알 수있는 충분한 코드를 보여주지는 못했지만). – matt

+0

@matt 현재'applicationWillTerminate에서 locationManager.stopUpdatingLocation() locationManager = nil'을 사용하고 있습니다 만, 충분하지 않다고 생각하십니까? – user3766930

+0

다른 지점에서 위치 업데이트를 중지해야합니까? – user3766930

답변

0

배터리가 소모되는 한 계측기를 실행하고 CPU 사용량을 확인하십시오. 내 생각 엔 위치 관리자가 아닌 것 같습니다.

중요한 변경 사항에 대해서만 알고있는 한, Apple은이를위한 API를 가지고 있습니다. 장치가 이전 통지에서 500 미터 이상을 이동하면서

startMonitoringSignificantLocationChanges()

노트 앱은 즉시 알림을 기대할 수 있습니다. 5 분마다 한 번 이상 개의 알림이 발생하면 안됩니다. 기기가 네트워크에서 데이터를 검색 할 수있는 경우 위치 관리자 이 알림을 적시에 전송할 가능성이 훨씬 큽니다.

0

일반적으로 location_fixed = true로 설정 한 startMonitoringSignificantLocationChanges를 호출하는 것이 일반적입니다. 위치 업데이트를 중지하면 코드가 다음과 같이 표시됩니다.