swift 地图定位(六)区域监听

喻选
2023-12-01
import UIKit
import CoreLocation

class ViewController: UIViewController {

    lazy var locationM: CLLocationManager = {
        let locationM = CLLocationManager()
        locationM.delegate = self
        if #available(iOS 8.0, *) {//info.plist add: Privacy - Location Always Usage Description
            locationM.requestAlwaysAuthorization()
        }
        return locationM
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 1. 创建区域
        let center = CLLocationCoordinate2DMake(31.785834, 121.406417)
        let distance: CLLocationDistance = 1000
        let region  = CLCircularRegion(center: center, radius: distance, identifier: "targetcloud")
        // 2. 监听区域
        locationM.startMonitoring(for: region)
    }
}

extension ViewController: CLLocationManagerDelegate {
    // 进入区域时调用
    func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
        print(">进入区域" + region.identifier)
    }
    
    // 离开区域时调用
    func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
         print("离开区域<" + region.identifier)
    }
}


加入判断

import UIKit
import CoreLocation

class ViewController: UIViewController {

    @IBOutlet weak var noticeLabel: UILabel!
    
    lazy var locationM: CLLocationManager = {
        let locationM = CLLocationManager()
        locationM.delegate = self
        if #available(iOS 8.0, *) {
            locationM.requestAlwaysAuthorization()
        }
        return locationM
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self){//加判断
            let center = CLLocationCoordinate2DMake(31.785834, 121.406417)
            var distance: CLLocationDistance = 1000
            if distance > locationM.maximumRegionMonitoringDistance {
                distance = locationM.maximumRegionMonitoringDistance
            }
            let region  = CLCircularRegion(center: center, radius: distance, identifier: "targetcloud")
            locationM.startMonitoring(for: region)
            locationM.requestState(for: region)
        }
    }
}

extension ViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
        print(">进入区域" + region.identifier)
    }
    
    func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
        print("离开区域<" + region.identifier)
    }
    
    func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
        if region.identifier == "targetcloud" {
            if state == .inside {
              noticeLabel.text = "welcome!"
            }else if state == .outside {
              noticeLabel.text = "欢迎下次再来!"
            }
        }
    }
}



 类似资料: