2015-04-28 49 views
0

我已經爲Swift中的CLLocation編寫了一個類。在視圖控制器代碼中,我希望能夠調用這個類。因此,這些類不是在視圖控制器代碼,試圖讓我的代碼可重用..CLLocation MVC原則的公共API

這裏是我迅速的CLLocation類代碼:

class LocationClass : NSObject, CLLocationManagerDelegate 
{ 
    var LocationManager : CLLocationManager = CLLocationManager() 

    override init() { 
     super.init() 
     self.LocationManager.delegate = self 
     self.LocationManager.requestAlwaysAuthorization() 
    } 

    func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { 
     println("didChangeAuthorizationStatus") 

     switch status { 
     case .NotDetermined: 
      println(".NotDetermined") 
      break 

     case .AuthorizedWhenInUse: 
      println(".Authorized") 
      LocationManager.startUpdatingLocation() 
      break 

     case .Denied: 
      println(".Denied") 
      break 

     default: 
      println("Unhandled authorization status") 
      break 

     } 

    } 

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { 

     let location = locations.last as! CLLocation 

     println(location.coordinate.latitude) 
     println(location.coordinate.longitude) 



    } 
} 

從視圖控制器的@IBOutlet內我想至少讓彈出窗口要求授權,並且我想返回didUpdateLocations,以便我可以在屏幕上放置經緯度。

我可以寫所有沒有MVC,但這是不好的做法..任何人都可以幫助我呢?感謝

回答

0

我增加了變量作爲一個實例變量(在視圖控制器類的頂部),這樣,它的工作:

class ViewController: UIViewController { 

    let LocManager = LocationClass() 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     var getlocation = LocationClass() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    @IBAction func LocButton(sender: UIButton) { 

     LocManager.findUserLocation() 



    } 
}