在Swift 4中无法获取用户的当前位置
在Swift 4中无法获取用户的当前位置
位置信息没有被打印到控制台。我之前使用过这段代码,但自从更新到Xcode 10后,用户的当前位置没有打印到控制台。\n代码如下:\nvar locationManager: CLLocationManager!\noverride func viewWillAppear(_ animated: Bool) {\n super.viewWillAppear(animated)\n determineMyCurrentLocation()\n}\nfunc determineMyCurrentLocation() {\n locationManager = CLLocationManager()\n locationManager.delegate = self\n locationManager.desiredAccuracy = kCLLocationAccuracyBest\n locationManager.requestAlwaysAuthorization()\n if CLLocationManager.locationServicesEnabled() {\n locationManager.startUpdatingLocation()\n }\n}\nfunc locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {\n let userLocation: CLLocation = locations[0] as CLLocation\n print(\"用户纬度 = \\(userLocation.coordinate.latitude)\")\n print(\"用户经度 = \\(userLocation.coordinate.longitude)\")\n}\nfunc locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {\n print(\"错误 \\(error)\")\n}\n
\nInfo.plist:\n![enter image description here](https://i.stack.imgur.com/94hkf.png)
在Swift 4中,如果无法获取用户的当前位置,可能是以下原因导致的:
原因:
1. 缺少必要的导入,需要导入MapKit和CoreLocation。
2. 没有正确实现MKMapViewDelegate和CLLocationManagerDelegate协议。
3. 缺少CLLocationManager对象的初始化和位置变量的声明。
4. 在ViewDidLoad方法中没有调用determineMyCurrentLocation()方法。
5. 缺少determineMyCurrentLocation()方法的实现,以及CLLocationManager的代理方法。
解决方法:
1. 在代码中添加以下导入语句:
import MapKit
import CoreLocation
2. 在类的声明中添加协议:
class YourViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
// ...
}
3. 声明CLLocationManager对象和经纬度变量:
var locationManager = CLLocationManager()
var latitude: Double = 0.0
var longitude: Double = 0.0
4. 在ViewDidLoad方法中调用determineMyCurrentLocation()方法:
override func viewDidLoad() {
super.viewDidLoad()
determineMyCurrentLocation()
}
5. 实现determineMyCurrentLocation()方法和CLLocationManager的代理方法:
func determineMyCurrentLocation() {
if CLLocationManager.locationServicesEnabled() {
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
let authorizationStatus = CLLocationManager.authorizationStatus()
if authorizationStatus == .authorizedWhenInUse || authorizationStatus == .authorizedAlways {
self.locationManager.startUpdatingLocation()
} else if locationManager.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization)) {
self.locationManager.requestAlwaysAuthorization()
} else {
self.locationManager.startUpdatingLocation()
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error while requesting new coordinates")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.latitude = locations[0].coordinate.latitude
self.longitude = locations[0].coordinate.longitude
}
6. 在Info.plist文件中添加以下键值对:
Privacy - Location Usage Description Privacy - Location Always and When In Use Usage Description Privacy - Location When In Use Usage Description Privacy - Location Always Usage Description
通过以上步骤,就可以在Swift 4中成功获取用户的当前位置了。
问题出现的原因是没有导入CoreLocation库。
解决方法是:
1. 导入CoreLocation库。
2. 将变量locationManager的声明方式从var改为let,并在声明时初始化它。
3. 在类的顶部声明一个userLocation的变量,并将其初始化为CLLocation()。
4. 在locationManager的didUpdateLocations方法中,获取最新的位置信息,并使用userLocation.distance(from: newLocation)方法计算与上一次位置的距离。如果距离超过100m,则更新userLocation的值为newLocation。
5. 打印出用户的纬度和经度。
整理后的文章如下:
在使用Swift 4开发中,如果无法获取用户的当前位置,可能是因为没有导入CoreLocation库。解决方法是:
1. 首先确保已经导入了CoreLocation库。
2. 将变量locationManager的声明方式从var改为let,并在声明时初始化它。
3. 在类的顶部声明一个userLocation的变量,并将其初始化为CLLocation()。
4. 在locationManager的didUpdateLocations方法中,获取最新的位置信息,并使用userLocation.distance(from: newLocation)方法计算与上一次位置的距离。如果距离超过100m,则更新userLocation的值为newLocation。
5. 最后,打印出用户的纬度和经度。
代码示例如下:
import CoreLocation
let locationManager = CLLocationManager()
var userLocation = CLLocation()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:[CLLocation]){
let newLocation = locations[0]
let distance = userLocation.distance(from: newLocation)
// using this to update my location every 100m
if distance > 100 {
userLocation = newLocation
}
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
}
通过以上的操作,就可以成功获取用户的当前位置了。
问题出现的原因是Info.plist文件配置不正确。需要同时配置三个键:
- NSLocationAlwaysAndWhenInUseUsageDescription
- NSLocationWhenInUseUsageDescription
- NSLocationAlwaysUsageDescription
解决方法是在Info.plist文件中配置这三个键,并为其设置相应的字符串值,解释应用程序如何使用位置数据。在iOS 11及以上的版本中,可以省略"Always"键,但是必须同时配置"When In Use"和"Always and When In Use"键,即使只请求"Always"权限。
在Xcode控制台中,运行时会显示以下错误提示信息:
"The app's Info.plist must contain both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription keys with string values explaining to the user how the app uses this data."
虽然只请求"Always"权限,但是仍然需要配置这三个键。在Xcode 10中会出现这个问题,但是实际上这与Xcode版本无关,而是与iOS版本相关。