swift - iBeacon background ranging -
i'm trying set application way start ranging in background , notification when user hit shoulder button or home button(not time) , don't want using background mode.
so coded in swift, works when app working in background 10 seconds , ranging won't restarted when user re-enter or exit region callback 180 seconds means ranging work 3 minutes send notification in first 10 seconds.
i started task in background , call run function wake init function. i'll happy if shares experience.
func applicationdidenterbackground(_ application: uiapplication) { // use method release shared resources, save user data, invalidate timers, , store enough application state information restore application current state in case terminated later. // if application supports background execution, method called instead of applicationwillterminate: when user quits. backgroundtask1.run(application: application) { (backgroundtask1_) in }
run , init functions:
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) }
this notificaion's code:
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 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]) } } }
Comments
Post a Comment