ios - 在 Swift 中使用 CLLocationManager 获取当前位置

标签 ios swift core-location

如何获取 iOS 设备的当前位置?

苹果似乎对获取位置的方式进行了更改,但我找不到最新的帖子。我自己回答了这个问题:

最佳答案

我找不到获取当前位置的最新解决方案,因此我是这样做的。

我的来源是苹果关于位置跟踪和智能 watch 的示例代码,名为PotLocCoreLocationwithiPhoneandAppleWatch:https://github.com/robovm/apple-ios-samples/tree/master/PotLocCoreLocationwithiPhoneandAppleWatch

这是您必须在应用中执行的操作。

请注意,步骤 2-6 中的所有内容均在以下要点中: https://gist.github.com/JonMercer/75b3f45cda16ee5d1e0955b2492f66dd

  1. 在 xcode 的项目设置中,点击 capability 选项卡(它是 general 选项卡旁边的选项卡,您可以在其中输入包标识符)。然后开启后台模式并启用位置更新编辑感谢@Rob:并将NSLocationWhenInUseUsageDescription添加到您的plist中。该值可以是您喜欢的任何值
  2. 在 View Controller 内,扩展CLLocationManagerDelegate

    class YourClass: UIViewController, CLLocationManagerDelegate {
    
  3. 实现这两个函数

    /**
    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).")
    }
    
  4. 创建一个 let manager = CLLocationManager() 变量

  5. viewDidLoad() 上设置以下内容:manager.requestWhenInUseAuthorization()manager.allowsBackgroundLocationUpdates = truemanager。 startUpdatingLocation()
  6. 要停止跟踪,请执行以下操作:manager.stopUpdatingLocation()manager.allowsBackgroundLocationUpdates = false

关于ios - 在 Swift 中使用 CLLocationManager 获取当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38343891/

相关文章:

ios - 无法使用分段控件显示 UICollectionView

ios - 将两个坐标点转换为东西向和南北向的距离

swift - 您将如何在 Swift 中切换 kCL 错误?

ios - 将 UIButton 放置在与 UITabBar 相同的空间中(隐藏时)

iPhone - 应用程序在后台运行时更改应用程序设置

ios - 从方法内部获取函数数据(包括简单代码)

ios - 更新永远快速重复的 SKAction 的参数

ios - Facebook 登录集成到 Parse.com 应用程序

ios - 如何将代码执行移至主队列

ios - 现在像谷歌一样获取用户位置