【问题标题】:Getting current location using CLLocationManager in Swift在 Swift 中使用 CLLocationManager 获取当前位置
【发布时间】:2016-07-13 06:14:21
【问题描述】:

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

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

【问题讨论】:

    标签: ios swift core-location


    【解决方案1】:

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

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

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

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

    1. 在 xcode 的项目设置中,单击 capabilities 选项卡(它是您输入捆绑标识符的 general 选项卡旁边的选项卡)。然后开启Background Mode并启用Location updates感谢@Rob 编辑: 并将NSLocationWhenInUseUsageDescription 添加到您的 plist。值可以是您喜欢的任何值
    2. 在您的视图控制器中,扩展 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

    【讨论】:

    • 我可能会建议添加一些有关requestWhenInUseAuthorization 工作的必要 plist 设置的内容。此外,上述所有关于后台位置更新的内容仅适用于编写一个真正的导航应用程序,该应用程序将在应用程序处于后台时继续使用标准位置服务。如果您在应用程序运行时进行定位服务,则不需要所有这些背景信息。事实上,如果你的应用不是真正需要后台服务的导航应用,它很可能会被拒绝。
    猜你喜欢
    • 1970-01-01
    • 2014-08-06
    • 2017-07-03
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 2011-09-10
    • 2019-09-02
    相关资源
    最近更新 更多