美文网首页
Swift — 系统定位CoreLocation获取权限,经纬度

Swift — 系统定位CoreLocation获取权限,经纬度

作者: 土豆骑士 | 来源:发表于2020-11-09 21:21 被阅读0次

环境:iOS,Xcode 12.1 ,Swift5.3.
PS: import CoreLocation
PS: LocationManager需要全局设置,否则获取权限的弹窗会闪现消失。
PS: info.list里面添加权限。

  • Privacy - Location When In Use Usage Description => Please allow "APP name" to use your location
  • Privacy - Location Always and When In Use Usage Description => Please allow "APP name" to use your location
    //MARK: - 定位测试
   ///PS: LocationManager需要全局设置,否则获取权限的弹窗会闪现消失

    var manager: LocationManager!
    @IBAction func testLocation(_ sender: Any) {
        
        if CLLocationManager.locationServicesEnabled() {
            print("设备有定位服务")
            
            manager = LocationManager.shared
            
            manager.getAuthHandle = { [weak self] (success) in
                print("获取权限:\(success)")
            }
            
            if manager.hasLocationPermission() {

                manager.requestLocation()
                manager.getLocationHandle = { (success,latitude, longitude) in
                    
                    print("获得location \(success), latitude:\(latitude)  longitude:\(longitude)")
                }
            } else {
                manager.requestLocationAuthorizaiton()

            }
        } else {
            print("设备没有定位服务")
            
            let alter = UIAlertController(title: "Location is Disabled", message: "To use location, go to your settings\nApp > Privacy > Location Services", preferredStyle: .alert)
            
            let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
            alter.addAction(action)
           
            present(alter, animated: true, completion: nil)
        }
    }

LocationManager 封装

import UIKit
import CoreLocation

class LocationManager: NSObject {
    
    static let shared = LocationManager()
    
    var getLocationHandle: ((_ success: Bool, _ latitude: Double, _ longitude: Double) -> Void)?
    
    var getAuthHandle: ((_ success: Bool) -> Void)?
    
    private var locationManager: CLLocationManager!
    
    override init() {
        super.init()
        locationManager = CLLocationManager()
        //设置了精度最差的 3公里内 kCLLocationAccuracyThreeKilometers
        locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        locationManager.delegate = self
        
    }
    /// 设备是否开启了定位服务
    func hasLocationService() -> Bool {
        
        return CLLocationManager.locationServicesEnabled()
        
    }
    /// APP是否有定位权限
    func hasLocationPermission() -> Bool {
        
        switch locationPermission() {
        case .notDetermined, .restricted, .denied:
            return false
        case .authorizedWhenInUse, .authorizedAlways:
            return true
        default:
            break
        }
        return false
    }
    
    /// 定位的权限
    func locationPermission() -> CLAuthorizationStatus {
        if #available(iOS 14.0, *) {
            let status: CLAuthorizationStatus = locationManager.authorizationStatus
            print("location authorizationStatus is \(status.rawValue)")
            return status
        } else {
            let status = CLLocationManager.authorizationStatus()
            print("location authorizationStatus is \(status.rawValue)")
            return status
        }
    }
    
    
    //MARK: - 获取权限,在代理‘didChangeAuthorization’中拿到结果
    func requestLocationAuthorizaiton() {
        locationManager.requestWhenInUseAuthorization()
        
    }
    //MARK: - 获取位置
    func requestLocation() {
        locationManager.requestLocation()
    }
    
}

extension LocationManager: CLLocationManagerDelegate {
   //MARK: - ios 14.0 之前,获取权限结果的方法
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        handleChangedAuthorization()
    }
    
    //MARK: - ios 14.0,获取权限结果的方法
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        handleChangedAuthorization()
    }
    
    private func handleChangedAuthorization() {
        if let block = getAuthHandle, locationPermission() != .notDetermined {
            if hasLocationPermission() {
                block(true)
            } else {
                block(false)
            }
        }
    }
    //MARK: - 获取定位后的经纬度
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let loction = locations.last {
            
            print("latitude: \(loction.coordinate.latitude)   longitude:\(loction.coordinate.longitude)")
            
            if let block = getLocationHandle {
                block(true, loction.coordinate.latitude, loction.coordinate.longitude)
            }
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        
        if let block = getLocationHandle {
            block(false, 0, 0)
        }
        print("get location failed. error:\(error.localizedDescription)")
    }
}

相关文章

网友评论

      本文标题:Swift — 系统定位CoreLocation获取权限,经纬度

      本文链接:https://www.haomeiwen.com/subject/ntmrbktx.html