2015-02-09 36 views
3

我在使用CLLocationDelegate獲取位置時遇到問題。 我創建了UIView的新子類,並且運行良好,但是當我創建NSObject的子類時,CLLocationDelegate沒有被調用。我可以找到問題所在。 這裏是我的代碼:Swift,NSObject中的CLLocationManagerDelegate不起作用

import UIKit 
import CoreLocation 

class LocationData: NSObject, CLLocationManagerDelegate { 

var locationManager : CLLocationManager = CLLocationManager() 

override init() { 
    super.init() 
    if self.locationManager.respondsToSelector(Selector("requestAlwaysAuthorization")) { 
     self.locationManager.requestWhenInUseAuthorization() 
    } 
    self.locationManager.delegate = self 
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest 
    self.locationManager.distanceFilter = 50 
    self.locationManager.startUpdatingLocation() 
    println("init LocationData") 
} 

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { 
    println(error.description) 
    } 

    func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) { 
    println("updated") 
    } 
} 

謝謝!

+0

你看過http://stackoverflow.com/questions/24062509/location-services-not-working-in-ios-8? – Anna 2015-03-19 13:00:19

回答

0

你的代碼很好!但是,實例化類的時候,你需要做的是這樣的:

import UIKit 

class ViewController: UIViewController { 

let LocationData: LocationData = LocationData() //<- here is the secret to works!!! 

override func viewDidLoad() { 
     super.viewDidLoad() 
} 

我也建議你改變你的init到這樣的事情:

override init() { 
    super.init() 

    let authorizationStatus: CLAuthorizationStatus = CLLocationManager.authorizationStatus() 

    if authorizationStatus == .notDetermined { 
     locationManager.requestWhenInUseAuthorization() 
    } 

    self.locationManager.delegate = self 
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest 
    self.locationManager.distanceFilter = 50 
    self.locationManager.startUpdatingLocation() 
    print("init LocationData") 
} 

而且不要忘了在添加NSLocationWhenInUseUsageDescriptioninfo.plist項目。