我正在将我的应用程序更新为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)
}
}
有人有想法么?
最佳答案
您可以实现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/