在地图视图上使用轨迹位置时出现可变错误

Posted

技术标签:

【中文标题】在地图视图上使用轨迹位置时出现可变错误【英文标题】:Variable error when using track location on a map view 【发布时间】:2015-08-23 05:05:04 【问题描述】:

我正在尝试在地图视图上显示和跟踪位置。我收到错误:

声明前使用局部变量'locationManager'

错误出现在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 我收到所有位置管理器变量的错误。我更新了原始问题中的代码。可以看看吗? 【参考方案1】:

您必须在块外声明 locationManager,在这种情况下,您尝试在 if-block 内声明它,这将使其成为局部变量。在 if-block. 工作示例代码之外声明该作业的变量:

var locationManager = CLLocationManager()

override func viewDidLoad() 

如您所见,我已将变量声明在与viewDidLoad() 方法相同的级别,使其范围更大。

然后,在你的 if 块中你可以这样做:

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()

请注意,我删除了 locationManager = CLLocationManager() 的第一行,因为它已经实例化了。

另外,locationManager 的函数不能在 viewDidLoad 方法中。

此外,我不明白为什么您的if-block 包装了该方法。

【讨论】:

谢谢。现在对我来说很有意义,因为我不应该在视图中调用 func locationManager 确实加载了。感谢您帮助我理解。地图运行良好 :) @amym 老兄,你会回答吗?【参考方案2】:

正如 Hassan 所说,您需要做的就是将 locationManager(...) 函数声明移出 if 块。要意识到的重要一点是,在 Swift 中,您可以像传递变量一样传递对函数的引用。因此,locationManager(...) 函数的声明(简称为 locationManager)会覆盖变量的声明。

您的代码现在应该如下所示:

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()
        

        // 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)
    

    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)
    


此外,当您将此对象设置为委托时,它希望该方法可以从类中直接访问。同样,在 Swift 中,就作用域而言,方法就像变量一样。因此,当您在另一个方法中声明它时,无法从类中访问它。直接在类下声明,调用delegate.locationManager(...)即可访问。

【讨论】:

感谢您的详细解释。帮助我解决了这个问题。现在效果很好。感谢您的帮助:) 很高兴我能帮上忙 :)

以上是关于在地图视图上使用轨迹位置时出现可变错误的主要内容,如果未能解决你的问题,请参考以下文章

尝试显示谷歌地图时出现“偏移宽度”错误[重复]

为啥函数调用在 swiftui 中返回不可变值时出现错误?

在剃刀视图上递增时出现编译错误

将结构插入地图时出现分段错误

尝试在视图中使用模型时出现 MVC 错误

尝试从 sharedPreferences 检索地图时出现颤振错误