[英]Swift 2 Beacon scan in background
我正在嘗試在我的應用程序中運行信標背景檢測。 我為此創建了一個專用類,並在ViewController中啟動它:
override func viewDidLoad() {
super.viewDidLoad()
beaconSharedInstance
....
}
這是我班上的代碼:
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)")
}
}
}
該類在前台運行良好,但是一旦我的應用程序變為非活動狀態,就可以在日志文件中看到:
Ending background task
然后CLLocatioManager停止...
我在項目的背景模式下設置了位置更新,並在info.plist文件中設置了NSLocationAlwaysUsageDescription,但是我仍然有相同的行為,當應用程序處於非活動狀態時,線程停止了。
我也試圖像這樣啟動我的線程:
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
})
但是在那種情況下,CLLocationManager永遠不會啟動...知道嗎?
后台任務需要循環,否則它將退出。 嘗試:
dispatch_async(backgroundQueue, {
print("Running beacon detection in the background queue")
beaconSharedInstance
while(true) {
NSThread.sleepForTineInterval(1)
print("running...")
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.