Google附近的邮件:未收到任何邮件

时间:2018-11-27 21:30:03

标签: swift google-nearby

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

我再次检查了API密钥是否正确,并且还在Info.plist中添加了NSMicrophoneUsageDescriptionNSBluetoothPeripheralUsageDescription的权限。

在Google开发者控制台中启用了“附近消息” API,并且已将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))")
        })
    }

}

是否有人在设置此设置时遇到问题?

1 个答案:

答案 0 :(得分:0)

好吧,对于有相同问题的人,解决方案非常简单,几乎令人尴尬。必须将发布和订阅结果保存在类变量中:

    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))")
        })
    }