LoginSignup
24
20

More than 5 years have passed since last update.

Rails 5 Action CableチャットアプリのiOSクライアント側を作る

Last updated at Posted at 2017-05-20

はじめに

iOSでリアルタイム通信がデモできるアプリを作りたいと思っていたところ。
RailsのAction Cableを使ったアプリケーションと通信する簡単なiOSアプリを作ってみました。

今回のRailsとiOSのコードはGithubに上げましたので、ご興味があれば動かしてみてください。
ariiyu/ActionCableSample: Action Cable Sample with Rails 5.1 and Swift 3.1

Action Cableとは

Ruby on Rails 5で導入された、WebSocketによる双方向通信とRailsを統合するための仕組みです。
Action Cable の概要 | Rails ガイド

Railsアプリケーション

※ruby 2.4.1、Rails 5.1.0
以下の記事を元に、Rails側の実装を行いました。
コードはほぼそのままです。

Rails 5 + ActionCableで作る!シンプルなチャットアプリ(DHH氏のデモ動画より) - Qiita

iOS側からのリクエストを許可

以下の記述を加えておきます。

config.environment/development.rb
config.action_cable.allowed_request_origins = ['ws://localhost:3000']

Swiftアプリ

Swift-ActionCableClientというライブラリを利用しました。
WebViewを使わずに、ネイティブのコードを書いてRailsのAction Cableアプリケーションとやりとりします。

接続

接続が成功したらonConnectedが呼ばれます。

var client: ActionCableClient!

self.client = ActionCableClient(url: URL(string: "ws://localhost:3000/cable")!)
client.connect()

client.onConnected = {
  print("Connected!")
}

client.onDisconnected = {(error: Error?) in
  print("Disconnected!")
}

チャンネル作成・購読

client.createでチャンネルを購読します。

self.roomChannel = self.client.create("RoomChannel")

メッセージ受信

メッセージを受信したらonReceiveが呼ばれます。

roomChannel.onReceive = { (JSON : Any?, error : Error?) in
  if let json = JSON {
    self.receivedBodyLabel.text = (json as! NSDictionary)["message"] as? String
  } 
}

roomChannel.onSubscribed = {
  print("Subscribed")
}

roomChannel.onUnsubscribed = {
  print("Unsubscribed")
}

roomChannel.onRejected = {
  print("Rejected")
}

アクション送信

if let error = roomChannel["speak"](["message": "hello: " + String(random)]) {
    print("Error: ", error)
} else {
    print("spoke message")
}

動作確認

$ rails s

Railsサーバーを起動してWebブラウザでhttp://localhost:3000にアクセスすると、チャット画面が表示されます。
iOSアプリをシミュレータで実行してmessageを送受信すると、それぞれの端末の画面の表示がリアルタイムに更新されることを確認します。

おわりに

Action Cableを使ったサーバーと通信するiOSクライアントアプリを作ってみました。
今回は単純なサンプルを作るのが目的でしたが、Rails側、iOS側ともにサクッと作れたように思います。

参考

24
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
20