Swift区域监听
2020-05-02 本文已影响0人
越天高
lazy var locationM: CLLocationManager = {
let locationM = CLLocationManager()
locationM.delegate = self
// 请求授权 配置key
if #available(iOS 8.0, *) {
locationM.requestAlwaysAuthorization()
if #available(iOS 9.0, *)
{
locationM.allowsBackgroundLocationUpdates = true
}
}
return locationM
}()
// 如果想要进行区域监听, 在ios8.0之后, 必须要请求用户的位置授权
// 区域监听
// 1. 创建区域
//监听状态前要判断,该区域是否可以被监听
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self)
{
// 1. 创建区域
//32.11612801,+118.80809973
let center = CLLocationCoordinate2DMake(32.11612801, 118.80809973)
var distance : CLLocationDistance = 100
// 2. 监听区域
// 使用前必须判定当前的监听区域半径是否大于最大可被监听的区域半径
if(distance > self.locationM.maximumRegionMonitoringDistance)
{
distance = self.locationM.maximumRegionMonitoringDistance;
}
let region = CLCircularRegion(center: center, radius: distance, identifier: "工作")
locationM.startMonitoring(for: region)
//监听某个区域的状态
}
- 监听代理
extension ViewController: CLLocationManagerDelegate {
/// 进入区域时调用
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion)
{
print("进入区域--" + region.identifier)
enterLabel.text = "进入区域"
}
// 离开区域时调用
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
print("离开区域--" + region.identifier)
enterLabel.text = "离开区域"
}
}
//监听区域的状态
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion)
{
//监听某区域的状态
if state == .inside
{
stateLabel.text = "进入状态区域"
}else if state == .outside
{
stateLabel.text = "离开状态区域"
}
}