繁体   English   中英

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

[英]Getting current location using CLLocationManager in Swift

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

苹果似乎已经对如何获取位置进行了更改,而我找不到最新的帖子。 我在下面亲自回答了这个问题:

我找不到获取当前位置的最新解决方案,所以这是我的操作方法。

我的消息来源是苹果关于位置跟踪和智能手表的示例代码,称为PotLocCoreLocationwithiPhoneandAppleWatchPotLocCoreLocationwithiPhoneandAppleWatchhttps : //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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM