本指南将向您介绍如何通过一个现有示例应用来创建支持 Cast 的 iOS 发送者应用。
如需按照本指南操作,请下载我们的投放示例,这是一个完整的 iOS 应用,可利用 IMA iOS SDK 为包含广告的视频实现投射功能。
前提条件
本指南以 Google Cast SDK 和 IMA SDK for iOS 的现有知识为基础。用户应熟悉以下内容:
本指南将介绍 Cast 示例与接收器进行通信时所使用的具体设置。未涵盖标准投放设置代码或常规 IMA 广告播放。如需详细了解如何实现接收器,请参阅我们的 HTML5 接收器指南。
发送消息
CastExample 的转换逻辑在 CastViewController.m
中实现。它使用 CastMessageChannel.h
中定义的投放通道在接收器和发送者之间路由消息。castVideo
函数会尝试加载内容网址,然后向接收方发送一条自定义消息,告知其使用同一广告代码请求广告,并跳转到发送者的当前时间戳。
CastViewController.m
- (IBAction)castVideo:(id)sender {
// Show alert if not connected.
if (!self.deviceManager ||
self.deviceManager.connectionState != GCKConnectionStateConnected) {
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"Not Connected"
message:@"Please connect to Cast device"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action =
[UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:nil];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
return;
}
[self.viewController pauseVideo];
NSString *contentUrl = self.viewController.kContentUrl;
GCKMediaMetadata *metadata = [[GCKMediaMetadata alloc] init];
GCKMediaInformation *mediaInformation =
[[GCKMediaInformation alloc] initWithContentID:contentUrl
streamType:GCKMediaStreamTypeBuffered
contentType:@"video/mp4"
metadata:metadata
streamDuration:0
customData:nil];
[self.mediaControlChannel loadMedia:mediaInformation
autoplay:NO
playPosition:0];
if (self.viewController.adIsVmap || !self.viewController.adHasStarted) {
[self sendMessage:[NSString
stringWithFormat:@"requestAd,%@,%f",
self.viewController.kAdTagUrl,
CMTimeGetSeconds(
self.viewController.contentPlayer
.currentTime)]];
} else {
[self sendMessage:[NSString
stringWithFormat:@"seek,%f",
CMTimeGetSeconds(
self.viewController.contentPlayer
.currentTime)]];
}
}
- (void)sendMessage:(NSString *)message {
NSLog(@"Sending message: %@", message);
[self.messageChannel sendTextMessage:message];
}
指定了两条消息:跳转,用于在没有广告的情况下在接收器上继续播放;以及 requestAd - 向接收器重新请求相同的广告代码。此示例中会用到广告播放列表和 VMAP,但您也可以自行定义投放时应发生的行为。这些消息以英文逗号分隔,其中第一个参数是消息名称,其余参数是广告代码和跳转时间。
接收消息
接收器会在投射视频发出时间更新通知时,以及停止投放的广告和内容开始播放时发出通知。系统会通过两条消息在发件人中进行处理:
onContentPauseRequested
onContentResumeRequested
这些消息采用逗号分隔,格式与上述 Seek 和 requestAd 消息类似。
- (void)onCastMessageReceived:(CastMessageChannel *)channel
withMessage:(NSString *)message {
// handle the delegate being called here
NSLog(@"Receiving message: %@", message);
NSArray *splitMessage = [message componentsSeparatedByString:@","];
NSString *event = splitMessage[0];
if ([event isEqualToString:@"onContentPauseRequested"]) {
self.castAdPlaying = true;
self.castContentTime =
CMTimeMakeWithSeconds([splitMessage[1] floatValue], 1);
} else if ([event isEqualToString:@"onContentResumeRequested"]) {
self.castAdPlaying = false;
}
}
变量 castAdPlaying
和 castContentTime
用于确定广告是否在投放设备上播放,并存储广告开始播放的时间。如果接收者停止投射,发送者会知道从何处恢复内容。
后续步骤
至此,您已经充分了解了 iOS 发送者应用如何与接收者互动。 如需试用,请创建接收器应用并注册接收器,以便接收来自发送者应用的 API 调用的应用 ID。