Swift - Google NearBy Сообщения не работают - PullRequest
0 голосов
/ 05 апреля 2020

Я должен отправлять / получать сообщения через близлежащие сообщения Google, из документации я реализовал следующий код, но ничего не работает, может кто-нибудь сообщить мне, где я ошибаюсь.

 var nearbyPermission: GNSPermission!
    var messageMgr: GNSMessageManager?
    var publication: GNSPublication?
    var subscription: GNSSubscription?


    // MARK: Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        toggleNearbyPermission()

        // Set up the message view navigation buttons.
        nearbyPermission = GNSPermission(changedHandler: {[unowned self] granted in

            print(String(format: "%@ Nearby", granted ? "Deny" : "Allow"))
        })

        // Enable debug logging to help track down problems.
        GNSMessageManager.setDebugLoggingEnabled(true)

        // Create the message manager, which lets you publish messages and subscribe to messages
        // published by nearby devices.
        messageMgr = GNSMessageManager(apiKey: NEARBY_API,
                                       paramsBlock: {(params: GNSMessageManagerParams?) -> Void in
                                        guard let params = params else { return }

                                        // This is called when microphone permission is enabled or disabled by the user.
                                        params.microphonePermissionErrorHandler = { hasError in
                                            if (hasError) {
                                                print("Nearby works better if microphone use is allowed")
                                            }
                                        }
                                        // This is called when Bluetooth permission is enabled or disabled by the user.
                                        params.bluetoothPermissionErrorHandler = { hasError in
                                            if (hasError) {
                                                print("Nearby works better if Bluetooth use is allowed")
                                            }
                                        }
                                        // This is called when Bluetooth is powered on or off by the user.
                                        params.bluetoothPowerErrorHandler = { hasError in
                                            if (hasError) {
                                                print("Nearby works better if Bluetooth is turned on")
                                            }
                                        }
        })

    }

    @IBAction func startScanning(_ sender: Any) {
        // Show the name in the message view title and set up the Stop button.
        print("scanning")
        // Create a subscription that scans for nearby beacons.
        let stringFromData: ((Data?) -> String)? = { content in
            return String(data: content, encoding: .utf8)
            } as? ((Data?) -> String)

        let beaconScanStrategy = GNSBeaconStrategy(paramsBlock: { params in
            params?.allowInBackground = true
        })

        weak var weakSelf = self
        let messageFoundHandler:GNSMessageHandler = { message in
            let beaconString = stringFromData?(message?.content)
            //                weakSelf?.messageViewController.addMessage(beaconString)

            print(beaconString)

        }

        let messageLostHandler:GNSMessageHandler = { message in
            //weakSelf?.messageViewController.removeMessage(stringFromData?(message?.content))
        }

        subscription = messageMgr?.subscription(messageFoundHandler: messageFoundHandler, messageLostHandler: messageLostHandler, paramsBlock: { params in
            params?.deviceTypesToDiscover = .bleBeacon
            params?.beaconStrategy = beaconScanStrategy
        })
    }


    /// Starts sharing with a randomized name.
    func startSharingWithRandomName() {
        startSharing(withName: String(format:"Anonymous %d", arc4random() % 100))
    }

    /// Stops publishing/subscribing.
    func stopSharing() {
        publication = nil
        subscription = nil
    }

    func toggleNearbyPermission() {
        GNSPermission.setGranted(!GNSPermission.isGranted())
    }


    /// Starts publishing the specified name and scanning for nearby devices that are publishing
    /// their names.
    func startSharing(withName name: String) {
        if let messageMgr = self.messageMgr {
            // Show the name in the message view title and set up the Stop button.
            //        messageViewController.title = name
            print(name)

            // Publish the name to nearby devices.
            let pubMessage: GNSMessage = GNSMessage(content: name.data(using: .utf8,
                                                                       allowLossyConversion: true))
            publication = messageMgr.publication(with: pubMessage)

            // Subscribe to messages from nearby devices and display them in the message view.
            subscription = messageMgr.subscription(messageFoundHandler: {[unowned self] (message: GNSMessage?) -> Void in
                guard let message = message else { return }
                //          self.messageViewController.addMessage(String(data: message.content, encoding:.utf8))
                print(String(data: message.content, encoding:.utf8))

                }, messageLostHandler: {[unowned self](message: GNSMessage?) -> Void in
                    guard let message = message else { return }
                    //          self.messageViewController.removeMessage(String(data: message.content, encoding: .utf8))
                    print(String(data: message.content, encoding:.utf8))
            })
        }
    }

    @IBAction func startButtonClicked(_ sender: Any) {
        startSharingWithRandomName()
    }

    @IBAction func stopButtonClicked(_ sender: Any) {
        stopSharing()
    }
}

В UI У меня есть три кнопки: одна для подписки Bluetooth, чтобы прослушивать любое входящее сообщение, вторая - для отправки сообщения. Сейчас я просто распечатываю значение, но ничего не отображается.

...