我試圖在地圖視圖上顯示和跟蹤位置。我得到的錯誤:在地圖視圖上使用軌道位置時出現可變錯誤
Use of local Variable 'locationManager' before declaration
的錯誤是對的LocationManager的所有行:
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
我已經ViewDidLoad
之前聲明var locationManager = CLLocationManager()
。
我有我的變數在錯誤的地方嗎?
import UIKit
import MapKit
import CoreLocation
class InfoViewController: UIViewController,UIGestureRecognizerDelegate, CLLocationManagerDelegate {
// Outlets
@IBOutlet weak var infoImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var categoryLabel: UILabel!
@IBAction func urlButton(sender: UIButton) {
}
@IBOutlet weak var mapView: MKMapView!
// Variables
var gesture: UISwipeGestureRecognizer!
var store: Store!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Background image
self.infoImageView.image = UIImage(data: store.photo)
// Set label text
self.nameLabel.text = store.name
// Set category text
var categoryText = String()
for category in store.storeCategories {
if !categoryText.isEmpty {
categoryText += ", "
}
categoryText += category.name
}
categoryLabel.text = categoryText
if (CLLocationManager.locationServicesEnabled())
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations.last as! CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
}
// Gesture recoginizer
gesture = UISwipeGestureRecognizer(target: self, action: "dismissView")
self.gesture.direction = UISwipeGestureRecognizerDirection.Up
self.view.addGestureRecognizer(self.gesture)
}
func dismissView() {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
哪條線出現該錯誤?將有助於顯示整個文件,以便我們可以看到'locationManager'的聲明位置。 – NickEntin
謝謝@NickEntin我得到所有位置管理器變量的錯誤。我更新了原始問題中的代碼。你可以看一下嗎? – amym