iOS终止状态下Swift检测iBeacon信号并推送通知方案咨询
iOS终止状态下用Swift实现iBeacon进入检测与通知推送
先搞定基础配置
这些是实现功能的核心前提,缺一不可:
- Xcode项目开启后台模式:进入
Capabilities,勾选Background Modes下的Location updates和Uses Bluetooth LE accessories - 申请永久定位权限:必须用
Always权限,When In Use权限在App终止后完全失效 - 配置Info.plist:添加
NSLocationAlwaysAndWhenInUseUsageDescription和NSLocationWhenInUseUsageDescription两个键,分别填写向用户申请权限的说明文本
代码实现步骤
1. 封装Core Location管理器
写一个单例类专门处理iBeacon监测逻辑:
import CoreLocation import UserNotifications class BeaconMonitorManager: NSObject, CLLocationManagerDelegate { static let shared = BeaconMonitorManager() private let locationManager = CLLocationManager() // 替换成你的iBeacon UUID和自定义标识 private let targetBeaconUUID = UUID(uuidString: "YOUR_BEACON_UUID")! private let beaconRegionId = "com.yourcompany.yourapp.beacon" override init() { super.init() locationManager.delegate = self // 允许后台定位更新,禁止自动暂停 locationManager.allowsBackgroundLocationUpdates = true locationManager.pausesLocationUpdatesAutomatically = false // 请求永久定位权限 locationManager.requestAlwaysAuthorization() } // 启动iBeacon区域监测 func startMonitoring() { // 先检查设备支持情况和权限 guard CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) else { print("当前设备不支持iBeacon监测") return } guard CLLocationManager.authorizationStatus() == .authorizedAlways else { print("还没拿到永久定位权限,先去申请") return } // 创建监测区域,只监听进入事件 let beaconRegion = CLBeaconRegion(uuid: targetBeaconUUID, identifier: beaconRegionId) beaconRegion.notifyOnEntry = true beaconRegion.notifyOnExit = false // 屏幕点亮时也会触发状态检查,避免漏检 beaconRegion.notifyEntryStateOnDisplay = true locationManager.startMonitoring(for: beaconRegion) // 主动请求一次区域状态,确保App终止重启时能检测当前是否在区域内 locationManager.requestState(for: beaconRegion) } }
2. 处理区域进入事件并推送通知
实现代理方法,捕捉进入事件并发送本地通知:
extension BeaconMonitorManager { // 进入Beacon区域时触发 func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { guard region is CLBeaconRegion else { return } sendEntryNotification() } // App终止重启时,检查当前是否在区域内 func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) { guard region is CLBeaconRegion else { return } if state == .inside { sendEntryNotification() } } // 发送本地通知 private func sendEntryNotification() { let notificationContent = UNMutableNotificationContent() notificationContent.title = "检测到目标Beacon" notificationContent.body = "你已经进入了指定的Beacon信号范围" notificationContent.sound = UNNotificationSound.default let request = UNNotificationRequest(identifier: "beacon_entry_alert", content: notificationContent, trigger: nil) UNUserNotificationCenter.current().add(request) { error in if let error = error { print("通知推送失败:\(error.localizedDescription)") } } } }
3. App启动时初始化监测
在App启动入口方法里启动监测,同时请求通知权限:
// 以AppDelegate为例 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 请求通知权限 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, _ in if granted { print("通知权限已获取") } } // 启动Beacon监测 BeaconMonitorManager.shared.startMonitoring() return true }
重点注意事项
- 权限是核心:必须拿到
authorizedAlways权限,否则App终止后系统不会触发任何定位相关事件 - 设备设置:用户必须开启蓝牙和系统定位服务,否则无法检测iBeacon
- 测试要求:只能用真机测试,模拟器不支持iBeacon;App终止后,系统触发事件可能有几秒到几十秒的延迟,耐心等待
- 通知权限:一定要提前请求用户允许通知,不然就算检测到Beacon也推不出通知
内容的提问来源于stack exchange,提问作者Shehzad Raheem
相关产品推荐
相关产品推荐

