【发布时间】:2016-07-13 06:14:21
【问题描述】:
如何获取我的 iOS 设备的当前位置?
Apple 似乎对获取位置的方式进行了更改,但我找不到最新的帖子。我自己在下面回答了这个问题:
【问题讨论】:
标签: ios swift core-location
如何获取我的 iOS 设备的当前位置?
Apple 似乎对获取位置的方式进行了更改,但我找不到最新的帖子。我自己在下面回答了这个问题:
【问题讨论】:
标签: ios swift core-location
我找不到获取当前位置的最新解决方案,所以我就是这样做的。
我的来源是苹果关于位置跟踪和智能手表的示例代码,名为PotLocCoreLocationwithiPhoneandAppleWatch:https://github.com/robovm/apple-ios-samples/tree/master/PotLocCoreLocationwithiPhoneandAppleWatch
这是您必须在应用中执行的操作。
请注意,步骤 2-6 中的所有内容都在此要点中: https://gist.github.com/JonMercer/75b3f45cda16ee5d1e0955b2492f66dd
capabilities 选项卡(它是您输入捆绑标识符的 general 选项卡旁边的选项卡)。然后开启Background Mode并启用Location updates。 感谢@Rob 编辑: 并将NSLocationWhenInUseUsageDescription 添加到您的 plist。值可以是您喜欢的任何值在您的视图控制器中,扩展 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
【讨论】:
requestWhenInUseAuthorization 工作的必要 plist 设置的内容。此外,上述所有关于后台位置更新的内容仅适用于编写一个真正的导航应用程序,该应用程序将在应用程序处于后台时继续使用标准位置服务。如果您在应用程序运行时进行定位服务,则不需要所有这些背景信息。事实上,如果你的应用不是真正需要后台服务的导航应用,它很可能会被拒绝。