在學習獲取用戶位置的過程中,我下載了這個代碼https://github.com/irfanlone/CLLocationManager-Singleton-Swift。在使用它在Xcode8.3.3 Swift 3上運行後,我無法在調試控制檯中獲得任何輸出。事實上,我甚至無法得到這個位置認證dlalog顯示。我懷疑來自單身人士的數據沒有傳遞給視圖控制器,但我不能罰款的解決方案,你能看到什麼是錯的?謝謝。
爲夫特3校正後的代碼是: //單元素: 進口MapKit
協議LocationUpdateProtocol { FUNC locationDidUpdateToLocation(_位置:CLLocation) }
讓kLocationDidChangeNotification = 「LocationDidChangeNotification」
class UserLocationManager:NSObject,CLLocationManagerDelegate {
static let SharedManager = UserLocationManager()
fileprivate var locationManager = CLLocationManager()
var currentLocation : CLLocation?
var delegate : LocationUpdateProtocol!
fileprivate override init() {
super.init()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters
locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
}
// MARK: - CLLocationManagerDelegate
func locationManager(manager: CLLocationManager,didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
currentLocation = newLocation
let userInfo : NSDictionary = ["location" : currentLocation!]
DispatchQueue.main.async() {() -> Void in
self.delegate.locationDidUpdateToLocation(self.currentLocation!)
NotificationCenter.default.post(name: Notification.Name(kLocationDidChangeNotification), object: self, userInfo: userInfo as [NSObject : AnyObject])
}
}
}
//所述的ViewController 進口的UIKit 進口CoreLocation
類的ViewController:UIViewController中,LocationUpdateProtocol {
var currentLocation : CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.locationUpdateNotification(_:)), name: NSNotification.Name(rawValue: kLocationDidChangeNotification), object: nil)
let LocationMgr = UserLocationManager.SharedManager
LocationMgr.delegate = self
}
// MARK: - Notifications
func locationUpdateNotification(_ notification: Notification) {
let userinfo = notification.userInfo
self.currentLocation = userinfo!["location"] as! CLLocation
print("Latitude : \(self.currentLocation.coordinate.latitude)")
print("Longitude : \(self.currentLocation.coordinate.longitude)")
}
// MARK: - LocationUpdateProtocol
func locationDidUpdateToLocation(_ location: CLLocation) {
currentLocation = location
print("Latitude : \(self.currentLocation.coordinate.latitude)")
print("Longitude : \(self.currentLocation.coordinate.longitude)")
}
}
'的LocationManager:didUpdateToLocation:fromLocation'是委託方法。位置管理器使用此方法通知您的對象該位置已更新爲新值 - 您需要實施此方法才能使用該值執行某些操作。 – quellish 2014-07-16 20:20:46