Google的附近消息:没有收到任何消息

Google's nearby messages: not receiving any messages

我正在试用 Google 的附近消息 API,它似乎很容易使用,但由于某些原因无法按预期工作。我怀疑这个问题是微不足道的,但我一直无法解决这个问题。

我仔细检查了 API 键是否正确,我还在 Info.plist.[=14= 中添加了 NSMicrophoneUsageDescriptionNSBluetoothPeripheralUsageDescription 的权限]

附近的消息 API 在 Google 的开发人员控制台中启用,并且 API 键已设置为仅限于应用程序的包标识符。如果删除此限制,它也不会起作用。

class ViewController: UIViewController {

    private var messageManager: GNSMessageManager?

    override func viewDidLoad() {
        super.viewDidLoad()

        GNSMessageManager.setDebugLoggingEnabled(true)

        messageManager = GNSMessageManager(apiKey: "<my-api-key>", paramsBlock: { (params: GNSMessageManagerParams?) -> Void in
            guard let params = params else { return }

            params.microphonePermissionErrorHandler = { hasError in
                if hasError {
                    print("Nearby works better if microphone use is allowed")
                }
            }
            params.bluetoothPermissionErrorHandler = { hasError in
                if hasError {
                    print("Nearby works better if Bluetooth use is allowed")
                }
            }
            params.bluetoothPowerErrorHandler = { hasError in
                if hasError {
                    print("Nearby works better if Bluetooth is turned on")
                }
            }
        })

        // publish
        messageManager?.publication(with: GNSMessage(content: "Hello".data(using: .utf8)))

        // subscribe
        messageManager?.subscription(messageFoundHandler: { message in
            print("message received: \(String(describing: message))")
        }, messageLostHandler: { message in
            print("message lost: \(String(describing: message))")
        })
    }

}

其他人在设置时遇到问题吗?

好的,对于遇到同样问题的人来说,解决方案非常简单而且几乎令人尴尬。有必要将发布和订阅结果保存在一个class变量中:

    private var publication: GNSPublication?
    private var subscription: GNSSubscription?

    override func viewDidLoad() {
        super.viewDidLoad()

        messageManager = GNSMessageManager(apiKey: "<my-api-key>")

        // publish
        publication = messageManager?.publication(with: GNSMessage(content: "Hello".data(using: .utf8)))

        // subscribe
        subscription = messageManager?.subscription(messageFoundHandler: { message in
            print("message received: \(String(describing: message))")
        }, messageLostHandler: { message in
            print("message lost: \(String(describing: message))")
        })
    }