我正在尝试在我的应用程序中运行信标背景检测。我为此创建了一个专用类,并在我的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,但我仍然有相同的行为,当应用程序处于非活动状态时,我的线程会停止。
我还尝试这样启动我的Thread:
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从不starts...any的想法?
发布于 2016-08-24 04:44:26
后台任务需要有一个循环,否则它将直接退出。尝试:
dispatch_async(backgroundQueue, {
print("Running beacon detection in the background queue")
beaconSharedInstance
while(true) {
NSThread.sleepForTineInterval(1)
print("running...")
}
})https://stackoverflow.com/questions/39109919
复制相似问题