I'm trying to run a beacon background detection in my app. I created a dedicated class for this and launch it in my ViewController:
override func viewDidLoad() {
super.viewDidLoad()
beaconSharedInstance
....
}
and here is the code of my class:
let beaconSharedInstance = iBeacon();
class iBeacon: NSObject, UIApplicationDelegate, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
var beaconRegion:CLBeaconRegion!
override init(){
super.init()
let uuidString = "FDA50693-A4E2-4FB1-AFCF-C6EB07640978"
let beaconIdentifier = "uby-06B524"
let beaconUUID:NSUUID = NSUUID(UUIDString: uuidString)!
beaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: beaconIdentifier)
locationManager = CLLocationManager()
locationManager.delegate = self
if(CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedAlways){
locationManager.requestAlwaysAuthorization()
}
locationManager.allowsBackgroundLocationUpdates = true
locationManager!.startRangingBeaconsInRegion(beaconRegion)
}
func locationManager(manager: CLLocationManager,
didRangeBeacons beacons: [CLBeacon],
inRegion region: CLBeaconRegion) {
print("didRangeBeacons");
if(beacons.count > 0) {
print("Discovered beacon \(beacons[0].rssi) dBM name: \(beacons[0].proximityUUID)")
}
}
}
this class is working perfectly in foreground, but as soon as my app is becoming inactive, I can see in the log files:
Ending background task
and the CLLocatioManager stops...
I set Location updates in the Background mode of my project as well as NSLocationAlwaysUsageDescription in my info.plist file but I still have the same behavior, my thread stops when app is inactive.
I also tried to launch my Thread like this:
let qualityOfServiceClass = DISPATCH_QUEUE_PRIORITY_DEFAULT
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
print("Running beacon detection in the background queue")
beaconSharedInstance
})
but in that case CLLocationManager never starts...any idea ?
The background task needs to have a loop, otherwise it will simply exit. Try:
dispatch_async(backgroundQueue, {
print("Running beacon detection in the background queue")
beaconSharedInstance
while(true) {
NSThread.sleepForTineInterval(1)
print("running...")
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.