我正在将应用程序更新到 Swift 2.0,但是我遇到了 CLLocationManager
的问题。
我已经使用这段代码一段时间了,所以我有点困惑为什么它突然在 2.0 中成为一个问题。我正在使用一个全局变量(我知道是懒惰的),但除了声明它的类之外,它似乎无法在任何其他类中访问。我收到此错误:
Use of unresolved identifier '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)
}
}
大家有什么想法吗?
最佳答案
您可以实现 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)
}
}
关于ios - 无法访问不同类的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32800171/