2015-09-26 57 views
0

我正在將我的應用程序更新爲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) 
    } 
} 

人有什麼想法?

回答

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) 
    } 
} 
0

全局默認訪問級別現在爲internal,如同一個模塊中所有源文件的內部一樣。如果centerOnLocation是在不同的模塊,您需要將public改性劑添加到您的全球性的定義:

public var locationManager = CLLocationManager() 
+0

,但我仍然得到同樣的錯誤很遺憾。 – user3746428