[英]Getting current location using CLLocationManager in Swift
如何获取我的iOS设备的当前位置?
苹果似乎已经对如何获取位置进行了更改,而我找不到最新的帖子。 我在下面亲自回答了这个问题:
我找不到获取当前位置的最新解决方案,所以这是我的操作方法。
我的消息来源是苹果关于位置跟踪和智能手表的示例代码,称为PotLocCoreLocationwithiPhoneandAppleWatch
和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.