[iOS 10] メッセージ拡張「iMessage Application」でメッセージアプリを作ってみたよ♪

<h2>はじめに</h2>
こんにちわ！asuです（＾＾/

9月リリースのiOS 10から、拡張機能（Extension）メッセージアプリが出ましたが、まだ使っていなかったので簡単なアプリを作ってみました。

<iframe width="560" height="315" src="https://www.youtube.com/embed/2OyguJo6X30" frameborder="0" allowfullscreen></iframe>

この拡張機能は、Messagesフレームワークを使い、「Sticker Pack Application」と「iMessage Application」の２種類があるうち、今回は「iMessage Application」を使いました。

<h2>プロジェクト作成</h2>
まず、上部メニューから、File -> New -> Projectと移動し、下図のiOSタブのiMessageからメッセージ拡張のプロジェクトを作成します。

<a href="http://asksun.net/blog/wp-content/uploads/2016/10/0000.png"><img src="http://asksun.net/blog/wp-content/uploads/2016/10/0000.png" alt="iOS10 iMessage" width="650" class="size-full wp-image-981" /></a>

ストーリーボードは、下図のようになっており、起動時のコントローラーは、MSMessagesAppViewControllerを継承したMessagesViewControllerになっています。

<a href="http://asksun.net/blog/wp-content/uploads/2016/10/00.png"><img src="http://asksun.net/blog/wp-content/uploads/2016/10/00.png" alt="iMessage" width="650"  class="size-full wp-image-977" /></a>

<h2>MessagesViewController</h2>
次に、MSMessagesAppViewControllerには、下図のようなコールバックメソッドが有り、このコールバックメソッドを実装することで、メッセージ拡張を作っていきます。
 
<pre class="lang:default decode:true " title="iMessage" >import UIKit
import Messages

class MessagesViewController: MSMessagesAppViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - Conversation Handling
    
    override func willBecomeActive(with conversation: MSConversation) {
        // Called when the extension is about to move from the inactive to active state.
        // This will happen when the extension is about to present UI.
        
        // Use this method to configure the extension and restore previously stored state.
    }
    
    override func didResignActive(with conversation: MSConversation) {
        // Called when the extension is about to move from the active to inactive state.
        // This will happen when the user dissmises the extension, changes to a different
        // conversation or quits Messages.
        
        // Use this method to release shared resources, save user data, invalidate timers,
        // and store enough state information to restore your extension to its current state
        // in case it is terminated later.
    }
   
    override func didReceive(_ message: MSMessage, conversation: MSConversation) {
        // Called when a message arrives that was generated by another instance of this
        // extension on a remote device.
        
        // Use this method to trigger UI updates in response to the message.
    }
    
    override func didStartSending(_ message: MSMessage, conversation: MSConversation) {
        // Called when the user taps the send button.
    }
    
    override func didCancelSending(_ message: MSMessage, conversation: MSConversation) {
        // Called when the user deletes the message without sending it.
    
        // Use this to clean up state related to the deleted message.
    }
    
    override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
        // Called before the extension transitions to a new presentation style.
    
        // Use this method to prepare for the change in presentation style.
    }
    
    override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
        // Called after the extension transitions to a new presentation style.
    
        // Use this method to finalize any behaviors associated with the change in presentation style.
    }

}
</pre> 

<h2>MSConversation</h2>
MSConversationクラスは、メッセージアプリでの会話を表現するクラスです。 このクラスを利用すると、現在選択中のメッセージや会話についての各種オブジェクトにアクセスできます。 
参考：　<a href="https://developer.apple.com/reference/messages/msconversation" title="MSConversation">API Reference MSConversation</a>

使用する画像は、Assets.xcassetsに、追加しておきます(iconも設定)。
<a href="http://asksun.net/blog/wp-content/uploads/2016/10/Screen-Shot-2016-10-28-at-3.04.15.png"><img src="http://asksun.net/blog/wp-content/uploads/2016/10/Screen-Shot-2016-10-28-at-3.04.15.png" alt="iOS10 iMessage" width="650" class="size-full wp-image-978" /></a>

ストーリーボードで、デフォルトで置かれていたHello Worldのラベルを削除し、代わりにUIButtonを置き、imageを設定し、ButtonのActionを記述します。

<a href="http://asksun.net/blog/wp-content/uploads/2016/10/000.png"><img src="http://asksun.net/blog/wp-content/uploads/2016/10/000.png" alt="iOS10 iMessage" width="650"  class="size-full wp-image-979" /></a>

MSConversationクラスのinsert(MSmessage)を使用して、画像やメッセージを含めたものを送信対象にします。MSMessageのレイアウトには、MSMessageTemplateLayoutを使用しています。

<pre class="lang:default decode:true " title="MSConversation" >    @IBAction func send(_ sender: AnyObject) {
        let message = MSMessage()
        let template = MSMessageTemplateLayout()
        template.image = UIImage(named: "2")
        template.caption = "Hello! I'm rabbit!"
        template.subcaption = "How are you?"
        message.layout = template
        self.activeConversation?.insert(message, completionHandler: { (error) in
            print("insearted! error:\(error)")
            
        })
        dismiss()
    }</pre> 

<h2>実行結果</h2>
上記を実行すると下記のようになりました。

<a href="http://asksun.net/blog/wp-content/uploads/2016/10/message1.png"><img src="http://asksun.net/blog/wp-content/uploads/2016/10/message1.png" alt="message" width="650"class="alignnone size-full wp-image-993" /></a>

<h2>さいごに</h2>
メッセージ機能が簡単に使えて、便利な機能を備えたアプリがどんどん出てきてますね、今後の展開が楽しみです（＾＾/

<h2>参考にさせていただいたリンク</h2>
<a href="https://developer.apple.com/imessage/" title="iMessage+Apps">iMessage + Apps</a>
<a href="https://developer.apple.com/reference/messages">API Reference Messages Framework </a>
<a href="https://developer.apple.com/videos/play/wwdc2016/204/">iMessage Apps and Stickers, Part 1 </a>
<a href="https://developer.apple.com/videos/play/wwdc2016/224/" title="iMessage Apps and Stickers, Part 2">iMessage Apps and Stickers, Part 2 </a>
<a href="SampleCode Ice Cream Builder: A simple Messages app extension" title="SampleCode Ice Cream Builder: A simple Messages app extension">SampleCode Ice Cream Builder: A simple Messages app extension</a>

<h3 class="zemanta-related-title" style="margin:0 0 10px 0;padding:0;clear:both;">Related articles across the web</h3><ul style="margin: 0; padding: 0; overflow: hidden;" class="zemanta-article-ul zemanta-article-ul-image"><li style="padding: 0; background: none; list-style: none; display: block; float: left; vertical-align: top; text-align: left; width: 104px; font-size:12px; margin: 0 5px 10px 0;" class="zemanta-article-ul-li-image zemanta-article-ul-li"><a target="_blank" href="http://www.phonearena.com/news/Inline-game-videos-5-cool-apps-that-demo-the-power-of-iMessage-integration-in-iOS-10_id85408" style="padding: 2px; display: block; text-decoration: none;"><img style="border-radius:3px; box-shadow:0 1px 4px rgba(0, 0, 0, 0.2);padding: 0; margin: 0; border: 0; display: block; width: 100px; max-width: 100%;" src="http://i.zemanta.com/374966172_150_150.jpg"></a><a target="_blank" href="http://www.phonearena.com/news/Inline-game-videos-5-cool-apps-that-demo-the-power-of-iMessage-integration-in-iOS-10_id85408" style="display: block; overflow:hidden; text-decoration: none; line-height: 12pt; height: 80px; padding: 5px 2px 0 2px;">Inline game videos? Cool apps that demo the power of iMessage integration in iOS 10</a></li><li style="padding: 0; background: none; list-style: none; display: block; float: left; vertical-align: top; text-align: left; width: 104px; font-size:12px; margin: 0 5px 10px 0;" class="zemanta-article-ul-li-image zemanta-article-ul-li"><a target="_blank" href="https://sc5.io/posts/ios-10-improves-conversational-capabilities/" style="padding: 2px; display: block; text-decoration: none;"><img style="border-radius:3px; box-shadow:0 1px 4px rgba(0, 0, 0, 0.2);padding: 0; margin: 0; border: 0; display: block; width: 100px; max-width: 100%;" src="http://i.zemanta.com/noimg_10_150_150.jpg"></a><a target="_blank" href="https://sc5.io/posts/ios-10-improves-conversational-capabilities/" style="display: block; overflow:hidden; text-decoration: none; line-height: 12pt; height: 80px; padding: 5px 2px 0 2px;">iOS 10 improves conversational capabilities</a></li><li style="padding: 0; background: none; list-style: none; display: block; float: left; vertical-align: top; text-align: left; width: 104px; font-size:12px; margin: 0 5px 10px 0;" class="zemanta-article-ul-li-image zemanta-article-ul-li"><a target="_blank" href="http://www.redmondpie.com/ios-10-messages-best-stickers-games-apps-for-imessage/" style="padding: 2px; display: block; text-decoration: none;"><img style="border-radius:3px; box-shadow:0 1px 4px rgba(0, 0, 0, 0.2);padding: 0; margin: 0; border: 0; display: block; width: 100px; max-width: 100%;" src="http://i.zemanta.com/374892411_150_150.jpg"></a><a target="_blank" href="http://www.redmondpie.com/ios-10-messages-best-stickers-games-apps-for-imessage/" style="display: block; overflow:hidden; text-decoration: none; line-height: 12pt; height: 80px; padding: 5px 2px 0 2px;">iOS 10 Messages: Best Stickers, Games, Apps For iMessage</a></li><li style="padding: 0; background: none; list-style: none; display: block; float: left; vertical-align: top; text-align: left; width: 104px; font-size:12px; margin: 0 5px 10px 0;" class="zemanta-article-ul-li-image zemanta-article-ul-li"><a target="_blank" href="http://www.iClarified.com/56838/apple-releases-xcode-8-with-swift-3-and-sdks-for-ios-10-watchos-3-tvos-10-and-macos-sierra" style="padding: 2px; display: block; text-decoration: none;"><img style="border-radius:3px; box-shadow:0 1px 4px rgba(0, 0, 0, 0.2);padding: 0; margin: 0; border: 0; display: block; width: 100px; max-width: 100%;" src="http://i.zemanta.com/374835180_150_150.jpg"></a><a target="_blank" href="http://www.iClarified.com/56838/apple-releases-xcode-8-with-swift-3-and-sdks-for-ios-10-watchos-3-tvos-10-and-macos-sierra" style="display: block; overflow:hidden; text-decoration: none; line-height: 12pt; height: 80px; padding: 5px 2px 0 2px;">Apple Releases Xcode 8 With Swift 3 and SDKs for iOS 10, watchOS 3, tvOS 10, and macOS Sierra</a></li><li style="padding: 0; background: none; list-style: none; display: block; float: left; vertical-align: top; text-align: left; width: 104px; font-size:12px; margin: 0 5px 10px 0;" class="zemanta-article-ul-li-image zemanta-article-ul-li"><a target="_blank" href="http://blog.vodafone.co.uk/2016/09/13/get-ios-10-today-heres-everything-need-know-apples-latest-software-update/" style="padding: 2px; display: block; text-decoration: none;"><img style="border-radius:3px; box-shadow:0 1px 4px rgba(0, 0, 0, 0.2);padding: 0; margin: 0; border: 0; display: block; width: 100px; max-width: 100%;" src="http://i.zemanta.com/374761295_150_150.jpg"></a><a target="_blank" href="http://blog.vodafone.co.uk/2016/09/13/get-ios-10-today-heres-everything-need-know-apples-latest-software-update/" style="display: block; overflow:hidden; text-decoration: none; line-height: 12pt; height: 80px; padding: 5px 2px 0 2px;">Get iOS 10 today! Here's everything you need to know about Apple's latest software update</a></li></ul><ul class="zemanta-article-ul" style="overflow:hidden;clear:both;"></ul>