techium

このブログは何かに追われないと頑張れない人たちが週一更新をノルマに技術情報を発信するブログです。もし何か調査して欲しい内容がありましたら、@kobashinG or @muchiki0226 までいただけますと気が向いたら調査するかもしれません。

Nearby Messages APIを使ってみた iOS API使用方法

前回は、iOSのプロジェクトの設定とGoogleDeveloperConsoleの設定について説明した blog.techium.jp

今回は実際のAPIの使用方法について解説する

MessageManagerの初期化

Nearyby Messageのpublishとsubscribeを管理するクラスである、GNSMessageManagerを生成する

let kMyAPIKey = "ここに取得したAPIキーをいれる"


var messageMgr: GNSMessageManager?
messageMgr = GNSMessageManager(APIKey: kMyAPIKey)

デバッグログの有効化

Nearby Messageを使用する上での問題を解決するために、デバッグログをコンソールに出力すると良いだろう

GNSMessageManager.setDebugLoggingEnabled(true)

ユーザー設定の監視

ユーザーがマイクパーミッションを拒否、またはBluetoothパーミッションを拒否、BluetoothをオフにするとNearby Messagesは正しく動作しない
アプリでは上記のような場合、メッセージを表示しユーザーに通知する必要がある。
具体的には以下のようにハンドリングを行う

        messageMgr = GNSMessageManager(APIKey: kMyAPIKey,
                                       paramsBlock: {(params: GNSMessageManagerParams!) -> Void in
                                        // 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")
                                            }
                                        }
        })

Nearby Permissionの監視

近くのデバイスを検出するにはユーザーの許可を得る必要がある
これはNearby Permission Stateにて確認する
初回のpublishまたは、subscribe要求時にダイアログが表示される
f:id:forestsoftjpdev:20160712230648p:plain f:id:forestsoftjpdev:20160712230624p:plain ユーザーが許可したかどうかの情報はNSUserDefaultsに保存される 以下のコードで許可状態の監視が行える

           nearbyPermission = GNSPermission(changedHandler: {[unowned self] granted in
      //grantedの値がtrueであれば、許可された
            })

また、以下のようにすると許可状態を反転することができる

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

ただし、許可状態にするには、必ずユーザーの操作が必要になり、自動で許可状態にできない

メッセージの配信

メッセージの配信は以下のように行う
配信を停止する時は、GNSPublicationオブジェクトを解放する

var publication: GNSPublication?

    func publishMessage(message:String) {
        let pubMessage: GNSMessage = GNSMessage(content: message.dataUsingEncoding(NSUTF8StringEncoding,
            allowLossyConversion: true))
        publication = self.messageMgr!.publicationWithMessage(pubMessage)
    }

    func unpublishMessage(){
        publication = nil
    }

メッセージの受信

メッセージの受信は以下のように行う
メッセージ受信を停止する時はGNSSubscriptionオブジェクトを解放する

   var subscription: GNSSubscription?

    func subscribeMessage(){
        // Subscribe to messages from nearby devices and display them in the message view.
        subscription = self.messageMgr!.subscriptionWithMessageFoundHandler({[unowned self] (message: GNSMessage!) -> Void in
            // 受信したメッセージの処理
            }, messageLostHandler: {[unowned self](message: GNSMessage!) -> Void in
            //  ロストしたメッセージの処理
            })
    }
    
    func unsubscribeMessage(){
        self.subscription = nil
    }