2017-08-09 31 views
2

我在同一UIViewController中使用CLLocationManagerMKMapView。 我只想在重要位置發生變化時調用API。didUpdateLocations每當viewWillAppear調用重要位置時調用

import UIKit 
import CoreLocation 
import MapKit 


class ViewController: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate { 

@IBOutlet weak var mapView: MKMapView! 

var locationManager = CLLocationManager() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    self.locationManager.requestAlwaysAuthorization() 
    self.locationManager.delegate = self 
    self.locationManager.startMonitoringSignificantLocationChanges() 
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation 
    self.locationManager.distanceFilter = 500 
    mapView.showsUserLocation = true 
} 

override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(true) 
} 


override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     print("locations \(locations)") 
} 

} 

在這方面,主要的問題是,每當我做應用前景和背景didUpdateLocations被調用。我希望只在重要位置發生變化時纔會調用它,而不是每次調用viewWillAppear時。

我發現它是因爲MKMapView,didUpdateLocations被調用。

+0

爲什麼如果你只需要重要的位置更新,你有'self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation'?您是否在地圖視圖中顯示用戶位置? – Paulw11

+0

@ Paulw11 - 是的,我在MapView中顯示用戶位置 – Cintu

+0

這將導致地圖請求用戶位置更新,該位置更新正在傳遞給您的委託。您可以保留先前位置的記錄,並檢查位置更新中的距離;只有在距離大於某個閾值時更新服務器 – Paulw11

回答

1

您可以手動檢查上次保存位置的距離。嘗試這個。

var lastLocation: CLLocation? 
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

    if let lastLocation = lastLocation, let newLocation = locations.last { 
     if (lastLocation.distance(from: newLocation) < manager.distanceFilter) { 
      return 
     } 
    } 

    print("locations \(locations)") 
    lastLocation = locations.last 
} 
0

您可以保存最後的位置,並檢查裏面didUpdateLocations方法,如果不一樣採取適當的行動。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

    let location : CLLocation = locations.last! 

    if location.coordinate.latitude != lastLat && location.coordinate.longitude != lastLon{ 
     // take action 
    } 
} 
相關問題