2015-11-02 23 views
-1
func centerMapOnLocation(location: CLLocation) { 
    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 
     regionRadius * 2.0, regionRadius * 2.0) 
    MapOutlet.setRegion(coordinateRegion, animated: true) 
} 

上面這個函數在我的視圖控制器下面繼續運行,雖然我從來沒有編寫任何循環,有人可以幫助發現不正確的邏輯。這裏是視圖控制器爲什麼這個函數保持循環?

import UIKit 
import MapKit 
import CoreLocation 


class ViewControllerPublic: UIViewController, CLLocationManagerDelegate { 
let locationManager = CLLocationManager() 



let initialLocation = CLLocation(latitude: 3.632488, longitude: -117.898886) 
override func viewDidLoad() { 
    super.viewDidLoad() 
    centerMapOnLocation(initialLocation) 

    // Ask for Authorisation from the User. 
    self.locationManager.requestAlwaysAuthorization() 

    // For use in foreground 
    self.locationManager.requestWhenInUseAuthorization() 

    if CLLocationManager.locationServicesEnabled() { 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
     locationManager.startUpdatingLocation() 
    } 

} 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    let locValue:CLLocationCoordinate2D = manager.location!.coordinate 
    print("locations = \(locValue.latitude) \(locValue.longitude)") 
    let currentLocation = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude) 
    centerMapOnLocation(currentLocation) 
} 

let regionRadius: CLLocationDistance = 2300 
func centerMapOnLocation(location: CLLocation) { 
    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 
     regionRadius * 2.0, regionRadius * 2.0) 
    MapOutlet.setRegion(coordinateRegion, animated: true) 
} 

@IBOutlet weak var MapOutlet: MKMapView! 

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

}

+0

'didUpdateLocations'每個位置更新更新。並且您已經調用了該功能,這就是爲什麼它要求輕微的位置更改。 –

+0

你也可以公開一些允許用戶控制'setUserTrackingMode:animated:'設置的UI,MapView將爲你做所有事情 – Paulw11

回答

1

的你永遠不會失效CLLocation manager從而@Ashish Kakkad說休息,只要你得到哪怕是一丁點的位置更改功能是越來越再次調用。如果您不想要這種行爲,那麼在didUpdateLocations中獲得位置後,您需要執行locationManager.stopUpdatingLocation()。或者,如果您確實希望自己的應用在每次位置更改時更新地圖,則可能需要考慮更改所需的位置準確性。