应用程序处于后台ios时Geofence不工作
我正在尝试为我的应用程序执行地理围栏。当我的应用程序运行时,我模拟了位置。它收到了地理围栏,但当它在后台时,它不会收到任何地理围栏。(我遵循本教程学习地理围栏 但我使用谷歌地图显示地图(根据要求) 这是我的AppDelegate的代码应用程序处于后台ios时Geofence不工作,ios,swift,google-maps,geofencing,Ios,Swift,Google Maps,Geofencing,我正在尝试为我的应用程序执行地理围栏。当我的应用程序运行时,我模拟了位置。它收到了地理围栏,但当它在后台时,它不会收到任何地理围栏。(我遵循本教程学习地理围栏 但我使用谷歌地图显示地图(根据要求) 这是我的AppDelegate的代码 import GoogleMaps import GooglePlaces import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDel
import GoogleMaps
import GooglePlaces
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let locationManager = CLLocationManager()
private let BLE_UUID_NUS_SERVICE = CBUUID(string: "6E400001-B5A3-F393-E0A9-E50E24DCCA9E")//Nordic UART Service
private let BLE_UUID_NUS_RX_CHARACTERISTIC = CBUUID(string: "6E400002-B5A3-F393-E0A9-E50E24DCCA9E") //write
private let BLE_UUID_NUS_TX_CHARACTERISTIC = CBUUID(string: "6E400003-B5A3-F393-E0A9-E50E24DCCA9E") // notify
var centralManager:CBCentralManager? = nil
var currentLuminKeyIdentifire = ""
var lumnKeyPeripheral:CBPeripheral? = nil
var Rx_Write_Characteristic:CBCharacteristic? = nil
var Tx_Notify_Characteristic:CBCharacteristic? = nil
func应用程序(application:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.launchOptions键:任意]?)->Bool{
// location manager delegage
GMSServices.provideAPIKey(Constant.googleApiKey)
GMSPlacesClient.provideAPIKey(Constant.googleApiKey)
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
let options: UNAuthorizationOptions = [.badge, .sound, .alert]
UNUserNotificationCenter.current()
.requestAuthorization(options: options) { success, error in
if let error = error {
print("Error: \(error)")
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
print("AppDelegate Application applicationWillResignActive")}
func applicationDidEnterBackground(_ application: UIApplication) {
print("AppDelegate Application applicationDidEnterBackground ")
}
func applicationWillEnterForeground(_ application: UIApplication) {
print("AppDelegate Application applicationWillEnterForeground ")
}
func applicationDidBecomeActive(_ application: UIApplication) {
application.applicationIconBadgeNumber = 0
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
print("AppDelegate Application applicationDidBecomeActive ")
ReachabilityManager.shared.startMonitoring()
}
func applicationWillTerminate(_ application: UIApplication) {
print("AppDelegate Application applicationWillTerminate ")
}
func handleEvent(for region: CLRegion!) {
// currentLuminKeyIdentifire = region.identifier
//
// self.centralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey : NSNumber(value: true)])
//
// print("AppDelegate Geofence triggered! and \(currentLuminKeyIdentifire)")
if UIApplication.shared.applicationState == .active {
print("Active")
} else {
// Otherwise present a local notification
let notificationContent = UNMutableNotificationContent()
notificationContent.body = "Geo fence Triggred for lumin key"
notificationContent.sound = UNNotificationSound.default
notificationContent.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "location_change_geofence",
content: notificationContent,
trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error: \(error)")
}
}
}
}
}
}
}
扩展AppDelegate:CBPeripheralDelegate{
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
// toast(message: "In peripherals")
guard let services=peripheral.services else {return}
for service in services{
peripheral.discoverCharacteristics([BLE_UUID_NUS_RX_CHARACTERISTIC,
BLE_UUID_NUS_TX_CHARACTERISTIC], for: service)
// peripheral.discoverCharacteristics(nil, for: service)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service:
CBService, error: Error?) {
guard let characteristics = service.characteristics else { return }
for characteristic in characteristics {
print(characteristic)
// check if it contains write characteristic
if characteristic.properties.contains(.read) {
print("\(characteristic.uuid): properties contains .read")
// this does not contain any read charateristic
peripheral.readValue(for: characteristic)
}
if characteristic.properties.contains(.notify) {
print("\(characteristic.uuid): properties contains .notify")
// this also does not notify so this is un used
// peripheral.setNotifyValue(true, for: characteristic)
}
if characteristic.properties.contains(.write) {
Rx_Write_Characteristic = characteristic
BleCommandUtil.sendColorCommadToKey(color: UIColor.hexStringToUIColor(hex:AppUserDefaults.getselectedColorHex()) ,
lumnKeyPeripheral: lumnKeyPeripheral,
Rx_Write_Characteristic: self.Rx_Write_Characteristic!,
isRandomColor: AppUserDefaults.getRandomColorToggle(),
isPowerSave: AppUserDefaults.getPowerSaveToggle())
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
switch characteristic.uuid {
case BLE_UUID_NUS_TX_CHARACTERISTIC:
print(characteristic.value ?? "no value")
default:
print("AppDelegate Unhandled Characteristic UUID: \(characteristic.uuid)")
}
}
}
启动监控功能
func startMonitoring(geotification: Geotification) {
// 1
if !CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
self.toast(message: "Geofencing is not supported on this device!")
return
}
// 2
if CLLocationManager.authorizationStatus() != .authorizedAlways {
let message = "Your geotification is saved but will only be activated once you grant Geotify permission to access the device location."
self.toast(message: message)
}
// 3
let fenceRegion = region(with: geotification)
// 4
loacationManager.startMonitoring(for: fenceRegion)
}
我无法识别问题。我注意到,如果我运行已完成的示例代码并在iPhone上单击home按钮,则AppDelegate的func应用程序将终止(application:UIApplication),但当我运行我的应用程序时,它会调用。我做错了什么?如何解决此问题您是否已在项目设置的“功能”选项卡上启用“后台模式”,并选中“位置更新”复选框?如果没有,请执行此操作,然后您可以在后台模式下获取更新位置。我已解决问题,问题是info.list have uiapplicationexitsonsuspend=是。我删除了它,现在它工作正常。我检查了位置更新,但它仍然不工作
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
// toast(message: "In peripherals")
guard let services=peripheral.services else {return}
for service in services{
peripheral.discoverCharacteristics([BLE_UUID_NUS_RX_CHARACTERISTIC,
BLE_UUID_NUS_TX_CHARACTERISTIC], for: service)
// peripheral.discoverCharacteristics(nil, for: service)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service:
CBService, error: Error?) {
guard let characteristics = service.characteristics else { return }
for characteristic in characteristics {
print(characteristic)
// check if it contains write characteristic
if characteristic.properties.contains(.read) {
print("\(characteristic.uuid): properties contains .read")
// this does not contain any read charateristic
peripheral.readValue(for: characteristic)
}
if characteristic.properties.contains(.notify) {
print("\(characteristic.uuid): properties contains .notify")
// this also does not notify so this is un used
// peripheral.setNotifyValue(true, for: characteristic)
}
if characteristic.properties.contains(.write) {
Rx_Write_Characteristic = characteristic
BleCommandUtil.sendColorCommadToKey(color: UIColor.hexStringToUIColor(hex:AppUserDefaults.getselectedColorHex()) ,
lumnKeyPeripheral: lumnKeyPeripheral,
Rx_Write_Characteristic: self.Rx_Write_Characteristic!,
isRandomColor: AppUserDefaults.getRandomColorToggle(),
isPowerSave: AppUserDefaults.getPowerSaveToggle())
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
switch characteristic.uuid {
case BLE_UUID_NUS_TX_CHARACTERISTIC:
print(characteristic.value ?? "no value")
default:
print("AppDelegate Unhandled Characteristic UUID: \(characteristic.uuid)")
}
}
func startMonitoring(geotification: Geotification) {
// 1
if !CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
self.toast(message: "Geofencing is not supported on this device!")
return
}
// 2
if CLLocationManager.authorizationStatus() != .authorizedAlways {
let message = "Your geotification is saved but will only be activated once you grant Geotify permission to access the device location."
self.toast(message: message)
}
// 3
let fenceRegion = region(with: geotification)
// 4
loacationManager.startMonitoring(for: fenceRegion)
}