Swift获取当前位置

24 篇文章 0 订阅

首先在Info.plist文件中添加允许获取位置信息的键值对
这里写图片描述
使用系统类CLLocationManager获取位置信息,下面已经封装了一个类,调用getLocation方法即可直接获取到位置信息
github地址:https://github.com/ColdChains/LAXLocationManager

import Foundation
import UIKit
import CoreLocation

class LAXLocationManager:CLLocationManager, CLLocationManagerDelegate {

    private var successBlock: ((_ address: String) -> Void)?
    private var failBlock: ((_ error: String) -> Void)?

    override init() {
        super.init()
        self.delegate = self
        self.desiredAccuracy = kCLLocationAccuracyBest
    }

    convenience init(getLocation success: @escaping (_ address: String) -> Void, failed: @escaping (_ error: String) -> Void) {
        self.init()
        self.getLocation(success: success, failed: failed)
    }

    func getLocation(success: @escaping (_ address: String) -> Void, failed: @escaping (_ error: String) -> Void) {
        self.successBlock = success
        self.failBlock = failed

        self.requestWhenInUseAuthorization()
        self.startUpdatingLocation()
    }

    // CLLocationManagerDelegate
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if let location = locations.last {
            self.stopUpdatingLocation()
            let coor = location.coordinate
            let long = coor.longitude // 经度
            let lati = coor.latitude // 纬度
            print(long, lati)

            let geocoder = CLGeocoder.init()
            geocoder.reverseGeocodeLocation(location) { (placemarks, error) in

                if let name = placemarks?.first?.name {
                    self.successBlock?(name)
                } else {
                    self.failBlock?("抱歉,获取不到您的位置")
                }

            }
        }

    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        self.stopUpdatingLocation()
        var str = "未知错误"
        switch (error as NSError).code {
        case 0:
            str = "位置不可用"
            break
        case 1:
            str = "用户关闭"
            break
        default: break
        }
        print(str)
        self.failBlock?(str)
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值