Google 附近 API iOS 后台扫描

Google Nearby API on iOS background scanning

我已经在我的 Swift 应用程序中设置了附近 API,当该应用程序位于前台时我可以接收消息。按照文档中的 说明进行操作 我尝试在适当的位置包含 params.allowInBackground = true 但出现错误:

Value of type 'GNSBeaconStrategyParams' has no member 'allowInBackground'

所以,我不能这样做,我的 GNSSubscription 对象如下所示:

    subscription = messageManager.subscriptionWithMessageFoundHandler(
        messageFoundHandler, messageLostHandler: messageLostHandler,
        paramsBlock: { (params: GNSSubscriptionParams!) in
            params.deviceTypesToDiscover = .BLEBeacon
            params.permissionRequestHandler = { (permissionHandler: GNSPermissionHandler!) in
                // TODO: Show custom dialog here, and call permissionHandler after it is dismissed
                // show the dialogue
            }
            params.beaconStrategy = GNSBeaconStrategy(paramsBlock: { (params: GNSBeaconStrategyParams!) in
                    params.includeIBeacons = true
                    //params.allowInBackground = true //*** THIS DOESN'T WORK ***
                })
    })

我的消息处理程序如下所示:

    messageFoundHandler = {[unowned self](message: GNSMessage!) -> Void in
        print("Found handler:", message.type, "->", String(data: message.content!, encoding:NSUTF8StringEncoding)!)
        if UIApplication.sharedApplication().applicationState != .Active {
            let localNotification = UILocalNotification()
            localNotification.alertBody = "Message received" + String(data: message.content!, encoding:NSUTF8StringEncoding)!
            UIApplication.sharedApplication().presentLocalNotificationNow(localNotification)
        }
    }

    messageLostHandler = {(message: GNSMessage!) -> Void in
        print("Lost Handler:", message.type, "->", String(data: message.content, encoding:NSUTF8StringEncoding)!)
    }

通过此设置和范围内的 Eddystone 信标,我现在可以在后台收到通知!既然这是我想要的,我就应该高兴。但是,如果我将设备连接到 xcode 并在后台使用应用程序,我会开始看到这样的消息流(似乎大约每 5 秒一次):

2016-07-23 19:35:08.243 Hoc[1269:622746] Can't endBackgroundTask: no background task exists with identifier 2f3, or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.

我正在使用 NearbyMessages v0.10.0。如果有人能给我指出正确的方向,让后台扫描在 iOS 上可靠地工作,那就太好了。

这是由 Cocoapods 的问题引起的。尽管我使用 $ pod update 和类似的方法 remove/re-added 来自我的项目的 NearbyMessages cocoaPod,但出于某种原因我无法安装最新版本 (1.0.1) 的 Nearby SDK。解决方案是从 Github 手动下载规范并覆盖 ~/.cocoapods/repos/master.

中的文件

然后为了确保我安装了最新版本,我更改了我的 podfile 以包含 pod 'NearbyMessages', '~> 1.0.1',这有效。

现在我可以在 GNSBeaconStrategy 对象上设置适当的参数,并且 Eddystone 信标的后台扫描在 iOS 的后台工作。 :-)

希望对您有所帮助。