我需要实现例如每5分钟在后台检测一次iBeacons
的工具,为此,我想使用新的Apple框架BackgroundTask
这是我实现操作子类的方式
import CoreLocation
class BeaconsRecord: AsyncOperation {
private let locationmanager: CLLocationmanager
private let clBeaconIdentityConstraint: CLBeaconIdentityConstraint
var beacons = [CLBeacon]()
init (locationmanager: CLLocationmanager,uuid: UUID) {
self.locationmanager = locationmanager
self.clBeaconIdentityConstraint = CLBeaconIdentityConstraint(uuid: uuid)
super.init()
}
override func main() {
locationmanager.delegate = self
locationmanager.startRangingBeacons(satisfying: clBeaconIdentityConstraint)
}
}
extension BeaconsRecord: CLLocationmanagerDelegate {
func locationmanager(_ manager: CLLocationmanager,didRangeBeacons beacons: [CLBeacon],in region: CLBeaconRegion) {
self.locationmanager.stopRangingBeacons(satisfying: clBeaconIdentityConstraint)
self.beacons = beacons
self.state = .Finished
}
}
如果我从前景使用它,它可以完美工作,那么我尝试从后台使用它,如wwdc演示中所示,它不起作用。 我想念吗? 我的appdelegate实施
@UIApplicationmain AppDelegate类:UIResponder,UIApplicationDelegate {
var window: UIWindow?
var locationmanager : CLLocationmanager?
let uuid = UUID(uuidString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")!
lazy var detectBeaconsQueue : OperationQueue = {
var queue = OperationQueue()
queue.name = "detectBeaconsQueue"
queue.maxConcurrentOperationCount = 1
return queue
}()
func application(_ application: UIApplication,didFinishlaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
locationmanager = CLLocationmanager()
locationmanager?.requestAlwaysAuthorization()
registerBackgroundTaks()
registerLocalNotification()
return true
}
//MARK: Register BackGround Tasks
func registerBackgroundTaks() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "xxx.xxxxxx.xxxxxxxxxxx",using: nil) { task in
self.scheduleLocalNotification()
self.handleAppRefresh(task: task as! BGAppRefreshTask)
}
}
func applicationDidEnterBackground(_ application: UIApplication) {
cancelAllPendingBGTask()
scheduleAppRefresh()
}
}
扩展名AppDelegate {
func cancelAllPendingBGTask() {
BGTaskScheduler.shared.cancelAllTaskRequests()
}
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: ""xxx.xxxxxx.xxxxxxxxxxx"")
// Fetch no earlier than 1 minutes from now
request.earliestBeginDate = Date(timeIntervalSinceNow: 1 * 60)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh: \(error)")
}
}
func handleAppRefresh(task: BGAppRefreshTask) {
// Schedule a new refresh task
scheduleAppRefresh()
let operation = BeaconsRecord(locationmanager: locationmanager!,uuid: uuid)
task.expirationHandler = {
operation.cancel()
}
operation.completionBlock = {
task.setTaskCompleted(success: !operation.isCancelled)
}
detectBeaconsQueue.addOperation(operation)
}
}