iOS 定位

iOS 8以后使用Core Location进行定位

  1. iOS 8以后再使用Core Location前需要调用下面两个方法其中之一

    • 始终允许访问位置信息 requestAlwaysAuthorization()
    • 使用应用程序期间允许访问位置数据 requestWhenInUseAuthorization()
  2. 在Info.plist中添加两个String类型的NSLocationAlwaysUsageDescription和NSLocationWhenInUseUsageDescription

CLLocationManager

let manager = CLLocationManager()
// 始终访问位置信息
manager.requestAlwaysAuthorization()
// 在App使用期间访问位置信息
// manager.requestWhenInUseAuthorization()
manager.delegate = self

manager.distanceFilter = 10.0 // 最少移动多少距离才更新一次
manager.desiredAccuracy = kCLLocationAccuracyKilometer // 定位精度

manager.startUpdatingLocation() // 开始定位
复制代码

获取位置信息

获取位置信息通过CLLocationManagerDelegate的协议方法来进行更新,一般会使用locationManager(manager:didUpdateLocations:)

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let currentLocation: CLLocation = locations.last {
      print("Current latitude: \(currentLocation.coordinate.latitude), longitude:\(currentLocation.coordinate.longitude)")

      // 解码出相关信息
      let clGeocoder = CLGeocoder()
      clGeocoder.reverseGeocodeLocation(currentLocation, completionHandler: { (placemarks, error) in
        if let mark = placemarks?.first {
          if let dic = mark.addressDictionary {
            let city = dic["City"] as? String
            let state = dic["State"] as? String
            self.locationLabel.text = state! + city!
          }
        }
      })
    }
    manager.stopUpdatingLocation()
  }
复制代码

转载于:https://juejin.im/post/5a30df636fb9a0450e761c2e

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值