无法从不同的类访问变量

时间:2015-09-26 17:51:48

标签: ios swift global cllocationmanager

我正在将我的应用更新为Swift 2.0,但是我遇到了CLLocationManager的问题。

我已经使用了这段代码了一段时间,所以我有点疑惑为什么它突然成为2.0中的一个问题。我正在使用一个全局变量(懒惰,我知道),但它似乎不能在其声明的其他类中访问。我收到此错误:

  

使用未解析的标识符' locationManager'

这是我在课堂上的代码,我宣布locationManager

var locationManager = CLLocationManager()

class InitalViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate {
        if #available(iOS 8.0, *) {
        locationManager.requestAlwaysAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()

        if CLLocationManager.locationServicesEnabled() {
            //Requests location use from user for maps
            locationManager.requestWhenInUseAuthorization()
        }
    }
}

这是另一个类中的代码:

@IBAction func centerOnLocation(sender: AnyObject) {
    if locationManager.location != nil {
        let locationCamera = MKMapCamera()
        locationCamera.heading = parkPassed.orientation!
        locationCamera.altitude = 600
        locationCamera.centerCoordinate.latitude = locationManager.location.coordinate.latitude
        locationCamera.centerCoordinate.longitude = locationManager.location.coordinate.longitude

        mapView.setCamera(locationCamera, animated: true)
    }
}

有人有什么想法吗?

2 个答案:

答案 0 :(得分:0)

全局变量的默认访问级别现在是internal,与同一模块中所有源文件的内部一样。如果centerOnLocation位于其他模块中,则需要将public修饰符添加到全局定义中:

public var locationManager = CLLocationManager() 

答案 1 :(得分:0)

您可以实现CLLocationManager的扩展,以将实例用作单例。

extension CLLocationManager{

  class var sharedManager : CLLocationManager {
    struct Singleton {
      static let instance = CLLocationManager()
    }
    return Singleton.instance
  }
}

然后你可以访问任何类中的单身人士

@IBAction func centerOnLocation(sender: AnyObject) {
    let locationManager = CLLocationManager.sharedManager
    if locationManager.location != nil {
        let locationCamera = MKMapCamera()
        locationCamera.heading = parkPassed.orientation!
        locationCamera.altitude = 600
        locationCamera.centerCoordinate.latitude = locationManager.location.coordinate.latitude
        locationCamera.centerCoordinate.longitude = locationManager.location.coordinate.longitude

        mapView.setCamera(locationCamera, animated: true)
    }
}
相关问题