茶漬けの技術メモ

Golang, Rubyで趣味開発します。テックニュース書いたり。ガジェット触ったり。

【Swift】Firebaseを使ってチャットアプリを作る。1 〜画面を作る〜


これからFirebase を使って簡単なチャットアプリを作っていきます。
Swiftを触ったことがある方なら3時間もあれば作成できると思いますので、ぜひ試してみてください!

それでは実際に作って行きましょうー!!


Firebase って何?

その前に、Firebase とは何者なのか、

Firebaseは2011年にアメリカで始まったMBaasですが,2014年にGoogleに買収されたことで一気に知名度が上がりました。 Firebaseも他のMBaas同様,オンラインでサインアップするだけでサーバのセットアップやメンテナンスに煩わされることなく使い始めるこ> とができ,オンラインデータベースにデータを格納したり引き出したりすることができますが,他のMBaasにはない強力な機能も数多く有し> ています。

http://gihyo.jp/dev/serial/01/firebase/0001

つまり、Firebase とはGoogle が提供している、BaaS(Backend as a Service) の1つで、
バックエンドの開発をせずに、データベースや、通知機能などをアプリで開発することが可能になります。NIFTY Cloud mobile backendや、Kiiなとも有名ですね。


チャット画面を作る

チャット画面の実装にはJSQMessagesViewControllerを使います。
cocoapods でインストールし、ViewController を以下のように実装します。

ViewController.swift

import UIKit
import JSQMessagesViewController

class ViewController: JSQMessagesViewController {
    
    var messages: [JSQMessage] = [
         JSQMessage(senderId: "Tsuru", displayName: "tsuru", text: "こんにちは!"),
         JSQMessage(senderId: "Gami", displayName: "gami", text: "こんにちは!!")
     ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        senderDisplayName = "tsuru"
        senderId = "Tsuru"
    }
    
    override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
        return messages[indexPath.row]
    }
    
    // コメントの背景色の指定
    override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
        if messages[indexPath.row].senderId == senderId {
            return JSQMessagesBubbleImageFactory().outgoingMessagesBubbleImage(with: UIColor(red: 112/255, green: 192/255, blue:  75/255, alpha: 1))
        } else {
            return JSQMessagesBubbleImageFactory().incomingMessagesBubbleImage(with: UIColor(red: 229/255, green: 229/255, blue: 229/255, alpha: 1))
        }
    }
    
    // コメントの文字色の指定
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
        if messages[indexPath.row].senderId == senderId {
            cell.textView.textColor = UIColor.white
        } else {
            cell.textView.textColor = UIColor.darkGray
        }
        return cell
    }
    
    // メッセージの数
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return messages.count
    }
    
    // ユーザのアバターの設定
    override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
        return JSQMessagesAvatarImageFactory.avatarImage(
            withUserInitials: messages[indexPath.row].senderDisplayName,
            backgroundColor: UIColor.lightGray,
            textColor: UIColor.white,
            font: UIFont.systemFont(ofSize: 10),
            diameter: 30)
    }

}


これで実行すると、下画像のように表示されていると思います。


f:id:biwako_no_otyazuke:20161130001646p:plain:w400



チャット画面が表示されていますね。
次回は、Firebase を使ってメッセージを実際に送信し、動的に表示していこうと思います。

続きはこちら

【Swift】Firebaseを使ってチャットアプリを作る。2 〜Firebase をアプリに追加する〜 - 茶漬けの技術メモ