如何获取 iOS 设备的当前位置?
苹果似乎对获取位置的方式进行了更改,但我找不到最新的帖子。我自己回答了这个问题:
最佳答案
我找不到获取当前位置的最新解决方案,因此我是这样做的。
我的来源是苹果关于位置跟踪和智能 watch 的示例代码,名为PotLocCoreLocationwithiPhoneandAppleWatch
:https://github.com/robovm/apple-ios-samples/tree/master/PotLocCoreLocationwithiPhoneandAppleWatch
这是您必须在应用中执行的操作。
请注意,步骤 2-6 中的所有内容均在以下要点中: https://gist.github.com/JonMercer/75b3f45cda16ee5d1e0955b2492f66dd
- 在 xcode 的项目设置中,点击
capability
选项卡(它是general
选项卡旁边的选项卡,您可以在其中输入包标识符)。然后开启后台模式
并启用位置更新
。 编辑感谢@Rob:并将NSLocationWhenInUseUsageDescription
添加到您的plist中。该值可以是您喜欢的任何值 在 View Controller 内,扩展
CLLocationManagerDelegate
class YourClass: UIViewController, CLLocationManagerDelegate {
实现这两个函数
/** Increases that location count by the number of locations received by the manager. Updates the batch count with the added locations. */ func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //use the "locations" variable here } /// Log any errors to the console. func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Error occured: \(error.localizedDescription).") }
创建一个
let manager = CLLocationManager()
变量- 在
viewDidLoad()
上设置以下内容:manager.requestWhenInUseAuthorization()
、manager.allowsBackgroundLocationUpdates = true
和manager。 startUpdatingLocation()
- 要停止跟踪,请执行以下操作:
manager.stopUpdatingLocation()
和manager.allowsBackgroundLocationUpdates = false
关于ios - 在 Swift 中使用 CLLocationManager 获取当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38343891/