我正在尝试使用CLLocationManager获取用户位置。由于某种原因,从不调用locationManager:didUpdateLocations。 Bellow是视图控制器的代码。
注意:我已经在info.plist中添加了必要的密钥,并在模拟器中启用了位置服务。
控制台输出为:"允许的位置"
任何想法我做错了什么?
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager:CLLocationManager = CLLocationManager()
var location_seenError: Bool = false
var location_fixAchieved: B
ool = false
var location_status: NSString = "Not Started"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
location_seenError = false;
location_fixAchieved = false;
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}
// Location Manager Delegate stuff
// If failed
func locationManager(manager: CLLocationManager, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
NSLog("locationManager:didFailWithError")
if (error) {
if (location_seenError == false) {
location_seenError = true
NSLog("Location Error")
}
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]!) {
NSLog("locationManager:didUpdateLocations")
if (location_fixAchieved == false) {
location_fixAchieved = true
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as CLLocation
var coord = locationObj.coordinate
NSLog("lat: \(coord.latitude)")
NSLog("lon: \(coord.longitude)")
}
}
// authorization status
func locationManager(manager: CLLocationManager,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
switch status {
case CLAuthorizationStatus.Restricted:
location_status = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
location_status = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
location_status = "Status not determined"
default:
location_status = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if (shouldIAllow == true) {
NSLog("Location to Allowed")
// Start location services
manager.startMonitoringSignificantLocationChanges()
locationManager.startMonitoringSignificantLocationChanges()
} else {
NSLog("Denied access: \(location_status)")
}
}
}
答案 0 :(得分:0)
模拟器没有GPS功能。但是,您可以使用调试器窗口底部的GPS图标模拟GPS位置。选择其中一个位置后,您应该获得位置更新,以便调用locationmanager.didUpdateLocations
。
您可以通过向项目中添加带有mappoint的GPX文件,将自己的位置添加到列表中。