開篇說明
iOS 10 把 iMessage 變成了一個平台。所謂 iMessage App,就是嵌入在「信息」裡的小應用,既可以是簡單的表情包,也可以是帶完整自定義界面的複雜工具。
iMessage App 分兩大類:
· Sticker pack app:純表情包應用,一行代碼都不用寫,把圖片拖進去就行,靜態動態都支持。
· iMessage app:需要寫代碼的完整應用,能發送表情、文字、視頻、音頻。
這兩者既可以獨立上架,也可以作為某個普通 App 的擴展存在。
一、零代碼做一個表情包應用
先記住尺寸限制:
· Small:100 × 100 @3x(300 × 300 像素)
· Medium:136 × 136 @3x(378 × 378 像素)
· Large:206 × 206 @3x(618 × 618 像素)
其他硬性要求:單文件不超過 500KB;不能小於 300 × 300 像素;不能大於 618 × 618 像素;格式僅支持 PNG、APNG、JPEG、GIF。
1. 添加靜態表情
<1> 新建工程:Xcode → iOS → Sticker Pack Application


<2> 選中 Stickers.xcsstickers,再選右側 Sticker Pack 文件夾,把素材裡所有圖片一起拖進去。

<3> 運行看效果。

2. 添加動態表情
<1> 選中 Sticker Pack 文件夾,點擊左下角的「+」,選擇 New Sticker Sequence。

<2> 把逐幀圖片依次拖進 Frame 1、Frame 2……


<3> 幀速率可調:選中 Sticker Sequence,在右側屬性檢查器的 Sticker Sequence 分區裡設置 Frame Per Second。

<4> 運行確認。

至此,一個 Sticker pack app 就完成了,全程沒有寫一行代碼。
二、製作功能完整的 iMessage App
實踐中大致有三種組織方式:
· 直接在 MessagesAppViewController 裡加子視圖。最簡單,但界面一複雜就難維護。
· 用 MSStickerBrowserViewController 作為子控制器。如果只需要做表情選擇界面,這條路最輕鬆。
· 自定義一個完整的 ViewController 掛進去。此後開發體驗和普通 App 幾乎一致,但要特別留意「輸入框高度會隨之變化」這件事,務必使用自動布局。
Messages 框架的幾個基礎類:
· MessagesAppViewController:iMessage App 的入口,工程默認就繼承它。
· MSSticker:一枚表情,NSObject 的子類。
· MSStickerBrowserView:展示表情的視圖。
· MSStickerBrowserViewController:表情瀏覽控制器。
· MSStickerBrowserViewDataSource:表情數據源協議。
可以理解成 UITableViewCell、UITableView、UITableViewController、UITableViewDataSource 之間的那套關係。
1. 自定義貼紙布局
<1> 新建工程:Xcode → iOS → iMessage Application。之後的開發都在 MessageExtension 文件夾裡進行。

<2> 把圖片資源加入工程。
<3> 在 MessagesAppViewController 中加載數據,創建 MSStickerBrowserViewController 並實現數據源協議:
#import "MessagesViewController.h"
@interface MessagesViewController () <MSStickerBrowserViewDataSource>
@property (nonatomic, strong) NSMutableArray *stickersArray;
@end
@implementation MessagesViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self loadStickers];
[self createStickerBrowserViewController];
}
// 加載表情包數據
- (void)loadStickers {
NSMutableArray *mArray = [NSMutableArray array];
for (int i = 1; i < 11; i++) {
NSURL *url = [[NSBundle mainBundle] URLForResource:[NSString stringWithFormat:@"scoops%02d_sticker", i]
withExtension:@"png"];
MSSticker *sticker = [[MSSticker alloc] initWithContentsOfFileURL:url
localizedDescription:@""
error:nil];
[mArray addObject:sticker];
}
self.stickersArray = mArray;
}
// 必須以 MSStickerBrowserViewController 作為容器才能顯示貼紙
- (void)createStickerBrowserViewController {
MSStickerBrowserViewController *browserVc =
[[MSStickerBrowserViewController alloc] initWithStickerSize:MSStickerSizeSmall];
[self addChildViewController:browserVc];
[self.view addSubview:browserVc.view];
browserVc.stickerBrowserView.backgroundColor = [UIColor cyanColor];
browserVc.stickerBrowserView.dataSource = self;
browserVc.view.translatesAutoresizingMaskIntoConstraints = NO;
[self.view.topAnchor constraintEqualToAnchor:browserVc.view.topAnchor].active = YES;
[self.view.bottomAnchor constraintEqualToAnchor:browserVc.view.bottomAnchor].active = YES;
[self.view.leftAnchor constraintEqualToAnchor:browserVc.view.leftAnchor].active = YES;
[self.view.rightAnchor constraintEqualToAnchor:browserVc.view.rightAnchor].active = YES;
}
#pragma mark - MSStickerBrowserViewDataSource
- (NSInteger)numberOfStickersInStickerBrowserView:(MSStickerBrowserView *)stickerBrowserView {
return self.stickersArray.count;
}
- (MSSticker *)stickerBrowserView:(MSStickerBrowserView *)stickerBrowserView
stickerAtIndex:(NSInteger)index {
return self.stickersArray[index];
}
@end
2. 自定義 ViewController,發送圖片、音頻、視頻
兩種創建方式:直接新建 iMessage 應用;或者在已有普通 App 裡添加 iMessage 擴展。下面重點說後者。
<1> 先建一個普通工程,點「+」添加 iMessage Extension。



點 Finish,彈框選 Yes。生成的目錄結構與直接創建 iMessage App 時一致。

#import "MessagesViewController.h"
@implementation MessagesViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupButton];
}
#pragma mark - 按鈕創建
- (UIButton *)createButtonWithTitle:(NSString *)title action:(SEL)action {
UIButton *button = [[UIButton alloc] init];
[button setBackgroundColor:[self randomColor]];
button.translatesAutoresizingMaskIntoConstraints = NO;
[button setTitle:title forState:UIControlStateNormal];
[button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
return button;
}
- (UIColor *)randomColor {
CGFloat red = (CGFloat)random() / (CGFloat)RAND_MAX;
CGFloat green = (CGFloat)random() / (CGFloat)RAND_MAX;
CGFloat blue = (CGFloat)random() / (CGFloat)RAND_MAX;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}
- (void)setupButton {
UIButton *photoButton = [self createButtonWithTitle:@"圖片" action:@selector(sendPhoto)];
UIButton *musicButton = [self createButtonWithTitle:@"音樂" action:@selector(sendMusic)];
UIButton *videoButton = [self createButtonWithTitle:@"視頻" action:@selector(sendVideo)];
UIButton *stickerButton = [self createButtonWithTitle:@"貼紙" action:@selector(sendStick)];
UIButton *alterButton = [self createButtonWithTitle:@"自定義" action:@selector(sendAlter)];
[photoButton.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
[photoButton.rightAnchor constraintEqualToAnchor:musicButton.leftAnchor].active = YES;
[photoButton.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES;
[photoButton.heightAnchor constraintEqualToConstant:50].active = YES;
[musicButton.rightAnchor constraintEqualToAnchor:videoButton.leftAnchor].active = YES;
[musicButton.widthAnchor constraintEqualToAnchor:photoButton.widthAnchor].active = YES;
[musicButton.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES;
[musicButton.heightAnchor constraintEqualToConstant:50].active = YES;
[videoButton.rightAnchor constraintEqualToAnchor:stickerButton.leftAnchor].active = YES;
[videoButton.widthAnchor constraintEqualToAnchor:photoButton.widthAnchor].active = YES;
[videoButton.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES;
[videoButton.heightAnchor constraintEqualToConstant:50].active = YES;
[stickerButton.rightAnchor constraintEqualToAnchor:alterButton.leftAnchor].active = YES;
[stickerButton.widthAnchor constraintEqualToAnchor:photoButton.widthAnchor].active = YES;
[stickerButton.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES;
[stickerButton.heightAnchor constraintEqualToConstant:50].active = YES;
[alterButton.rightAnchor constraintEqualToAnchor:self.view.rightAnchor].active = YES;
[alterButton.widthAnchor constraintEqualToAnchor:photoButton.widthAnchor].active = YES;
[alterButton.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES;
[alterButton.heightAnchor constraintEqualToConstant:50].active = YES;
}
#pragma mark - 發送各類內容
// 通用:發送附件(圖片、音頻、視頻都走這裡)
- (void)sendMessageWithURL:(NSURL *)url {
[self requestPresentationStyle:MSMessagesAppPresentationStyleCompact];
[self.activeConversation insertAttachment:url
withAlternateFilename:nil
completionHandler:^(NSError * _Nullable error) {
if (error) { NSLog(@"%@", error); }
}];
}
- (void)sendPhoto {
NSURL *url = [[NSBundle mainBundle] URLForResource:@"image" withExtension:@"png"];
[self sendMessageWithURL:url];
}
- (void)sendMusic {
NSURL *url = [[NSBundle mainBundle] URLForResource:@"blank" withExtension:@"mp3"];
[self sendMessageWithURL:url];
}
- (void)sendVideo {
NSURL *url = [[NSBundle mainBundle] URLForResource:@"moments" withExtension:@"mp4"];
[self sendMessageWithURL:url];
}
// 發送貼紙
- (void)sendStick {
[self requestPresentationStyle:MSMessagesAppPresentationStyleCompact];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"sticker" withExtension:@"png"];
MSSticker *sticker = [[MSSticker alloc] initWithContentsOfFileURL:url
localizedDescription:@"localizedDescription"
error:nil];
[self.activeConversation insertSticker:sticker completionHandler:^(NSError * _Nullable error) {
if (error) { NSLog(@"%@", error); }
}];
}
// 發送自定義消息卡片
- (void)sendAlter {
[self requestPresentationStyle:MSMessagesAppPresentationStyleCompact];
MSMessageTemplateLayout *layout = [[MSMessageTemplateLayout alloc] init];
layout.image = [UIImage imageNamed:@"image"];
layout.imageTitle = @"老虎";
MSMessage *message = [[MSMessage alloc] init];
message.layout = layout;
[self.activeConversation insertMessage:message completionHandler:^(NSError * _Nullable error) {
if (error) { NSLog(@"%@", error); }
}];
}
@end
代碼要點
發送圖片與音視頻,靠的是 MSMessagesAppViewController 自帶的 activeConversation 屬性,調用 insertAttachment 並傳入文件 URL 即可:
NSURL *url = [[NSBundle mainBundle] URLForResource:@"image" withExtension:@"png"];
如果代碼裡取不到 URL,先確認文件是否真的被加進了 target——在文件右側檢查器裡勾選對應的 Target Membership,漏勾是最常見的原因。

發送貼紙同理,把 URL 換成 MSSticker 再插入即可,注意貼紙尺寸必須符合前面提到的規範。
自定義消息的關鍵是 MSMessage 的 layout 屬性,通過 MSMessageTemplateLayout 設置圖片與標題,就能在對話流裡呈現一張漂亮的卡片。