我无法通过cllocationDelegate获得我的位置。
我创建了uiview的新子类并且工作得很好,但是当我创建nsObject的子类时,没有调用clLocationDelegate。我能找到问题所在。
这是我的代码:
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")
}
}
谢谢!
最佳答案
你的代码很好!但是在实例化类时,您需要这样做:
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")
}
别忘了在
NSLocationWhenInUseUsageDescription
项目中添加info.plist
。