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.
}
}
CLLocation manager
就像@Ashish Kakkad所说的那样,您永远不会使它无效,只要您进行了最细微的位置更改,您的函数就会再次被调用。如果您不希望出现这种情况,那么在找到位置后,didUpdateLocations
您需要执行locationManager.stopUpdatingLocation()
。或者,如果您确实希望应用程序每次位置更改时都更新地图,则可能需要考虑更改所需的位置精度。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句