我试图将我的应用程序设置为在后台开始测距的方式,并在用户点击肩部按钮或主页按钮时获得通知(并非所有时间)并且我不会想要使用背景模式。
所以我用swift编写了这个代码,当我的应用程序在后台运行10秒钟时,它会起作用,当用户重新进入或退出区域时,不会重新启动,但我会回调大约180秒这意味着我的测距将工作3分钟,但它只在前10秒发送通知。
我在后台启动了一个任务,然后调用我的run函数来唤醒init函数。如果有人分享经验,我会很高兴。
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
BackgroundTask1.run(application:
application) { (BackgroundTask1_) in
}
运行和初始化函数:
class func run(application: UIApplication, handler: (BackgroundTask1) -> ()) {
let backgroundTask = BackgroundTask1(application: application)
backgroundTask.begin()
handler(backgroundTask)
}
func init_()
{
let uuidString = "43F2ACD1-5522-4E0D-9E3F-4A828EA12C24"
let beaconRegionIdentifier = "Hello"
let beaconUUID:UUID = UUID(uuidString:uuidString)!
beaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: beaconRegionIdentifier)
beaconRegion.notifyEntryStateOnDisplay = true
locationManager_ = CLLocationManager()
if (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.authorizedWhenInUse) {
locationManager_!.requestWhenInUseAuthorization()
}
locationManager_?.allowsBackgroundLocationUpdates = true
locationManager_!.delegate = self
locationManager_!.pausesLocationUpdatesAutomatically=false
locationManager_?.startRangingBeacons(in: beaconRegion)
}
这是通知代码:
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
print("sdljflkj")
if beacons.count == 0 {
return
}
let currentbeacon = beacons[0]
lastproximity = currentbeacon.proximity
if currentbeacon.proximity == CLProximity.immediate{
DispatchQueue.global(qos: .userInitiated).async {
let content = UNMutableNotificationContent()
content.title = "Forget Me Not"
content.body = "Are you forgetting something?"
content.sound = .default()
let request = UNNotificationRequest(identifier: "ForgetMeNot", content: content, trigger: nil)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
print("here1")
NotificationCenter.default.post(name: Notification.Name(rawValue: "iBeaconFoundReceivedNotification"), object: nil, userInfo: ["Major":currentbeacon.major, "minor": currentbeacon.minor])
}
}
}