Code Snippets using the Native SDK for iOS

Product(s)
Video Cloud
Brightcove Player
Role(s)
Device SDK Developer
Task(s)
Develop with the Native SDKs
Topic(s)
Code Samples
SDK
iOS

In this topic, you will find a collection of code snippets which you may find useful as a reference while developing with the SDK. For more detailed solutions, see the iOS player samples.

Table of contents

Accessibility
Advertising
Analytics
Captions
Content security (DRM)
Cue points
Playback
Playlists
Styling

Custom controls for AirPlay

If you use the Brightcove PlayerUI controls, you are all set. AirPlay functionality works out-of-the-box, allowing users to stream video to high-definition displays with Apple TV.

If you are using custom controls, you can follow these steps:

  1. Learn about AirPlay in Apple's developer documentation for AirPlay.

  2. Use the playback controller’s allowsExternalPlayback property to set the AVPlayer’s allowsExternalPlayback property:

    _playbackController.allowsExternalPlayback = YES;
  3. Set up an AirPlay router control and handle its selection. For details, see Apple's AirPlay Overview document.

Customizing the closed captions button

The BCOVPlayerUI sample code shows you how to customize the Brightcove player when using the Native SDK for iOS. For more details, see the Customizing PlayerUI controls section of the Native SDK reference document.

To customize the closed captions button using the PlayerUI, follow these steps:

  1. Start with the Basic Video Playback App.

  2. Replace your values for the Policy Key, Account Id and Video Id. Select a video from your account that has text tracks.

  3. Set up the player view with a standard VOD layout:

    // Set up our player view. Create with a standard VOD layout.
    BCOVPUIPlayerView *playerView = [[BCOVPUIPlayerView alloc] initWithPlaybackController:self.playbackController options:nil controlsView:
    [BCOVPUIBasicControlView basicControlViewWithVODLayout] ];
  4. The closedCaptionButton is declared as a BCOVPUIButton, which is a subclass of UIButton and adds three additional methods for customization. Whenever you customize BCOVPlayerUI controls, you should use the Native Player APIs wherever they are available. Your customized code should look similar to this:

    // Customize the CC button.
    BCOVPUIButton *ccButton = playerView.controlsView.closedCaptionButton;
    ccButton.titleLabel.font = [UIFont systemFontOfSize:14.];
    ccButton.primaryTitle = @"CC";
    [ccButton showPrimaryTitle:YES];

Displaying FairPlay content on an external screen

When an external display is connected to an iOS device using an AV adapter and HDMI cable, the default behavior is to mirror the iOS screen. The exception to this is when you use FairPlay-protected video, which Apple prevents from mirroring (WWDC 2015, Session 502).

To display FairPlay-protected videos, set the AVPlayer properties exposed through the Brightcove Playback Controller to allow FairPlay video to play on an external display. The video plays in full screen mode. Here is an example of setting these properties:

playbackController.allowsExternalPlayback = YES;
playbackController.usesExternalPlaybackWhileExternalScreenIsActive = YES;

Google Analytics

If you use the Brightcove player and the catalog class, video analytics will be automatically collected and will appear in your Video Cloud Analytics module. For additional metrics, you can add Google Analytics to your app.

To integrate Google Analytics with your app, follow these steps:

  1. Review Google's document to Add Analytics to Your iOS App.
  2. Here is one way you could use Google Analytics to track video playback using Google's Firebase SDK:

    // This snippet shows one way to track video playback
    // using the Firebase SDK from Google Analytics with
    // the lifecycle event playback controller delegate method.
    - (void)playbackController:(id<BCOVPlaybackController>)controller playbackSession:(id<BCOVPlaybackSession>)session didReceiveLifecycleEvent:(BCOVPlaybackSessionLifecycleEvent *)lifecycleEvent
    {
    // Common parameters
    NSString *video_name = session.video.properties[kBCOVVideoPropertyKeyName];
    NSString *video_ID = session.video.properties[kBCOVVideoPropertyKeyId];
    
    // Session is ready to play
    if ([kBCOVPlaybackSessionLifecycleEventReady isEqualToString:lifecycleEvent.eventType])
    {
    	[FIRAnalytics logEventWithName:@"bcov_video_ready"
    											parameters:@{
    																	 @"bcov_video_name": video_name,
    																	 @"bcov_video_id": video_ID
    																	 }];
    }
    
    // Session encountered an error
    if ([kBCOVPlaybackSessionLifecycleEventError isEqualToString:lifecycleEvent.eventType])
    {
    	NSError *error = lifecycleEvent.properties[kBCOVPlaybackSessionEventKeyError];
    	int error_code = error.code;
    	[FIRAnalytics logEventWithName:@"bcov_video_playback_error"
    											parameters:@{
    																	 @"bcov_video_name": video_name,
    																	 @"bcov_video_id": video_ID,
    																	 @"bcov_video_error_code": @(error_code)
    																	 }];
    }
    
    // Session has completed
    if ([kBCOVPlaybackSessionLifecycleEventTerminate isEqualToString:lifecycleEvent.eventType])
    {
    	[FIRAnalytics logEventWithName:@"bcov_video_terminate"
    											parameters:@{
    																	 @"bcov_video_name": video_name,
    																	 @"bcov_video_id": video_ID
    																	 }];
    }
    }

 

Limiting the bitrate

You can't control which source (rendition) in the HLS manifest gets selected by the AVPlayer , but you can put a bitrate cap on playback. This prevents the player from using sources (renditions) with a bitrate over the specified bitrate.

Set the preferredPeakBitRate to the desired limit, in bits per second, of the network bandwidth consumption for the given AVPlayerItem .

Use one of the following declarations:

// Swift
var preferredPeakBitRate: Double
// Obj-C
@property(nonatomic) double preferredPeakBitRate

Looping a video

In some cases, you may want a video to automatically replay. To do this, you can get the "end of video" lifecycle event, seek to the beginning and play again.

This code assumes that you have set the delegate of the playbackController to the object with this method:

- (void)playbackController:(id<BCOVPlaybackController>)controller playbackSession:(id<BCOVPlaybackSession>)session didReceiveLifecycleEvent:(BCOVPlaybackSessionLifecycleEvent *)lifecycleEvent
{
if ([kBCOVPlaybackSessionLifecycleEventEnd isEqualToString:lifecycleEvent.eventType])
{
	[controller seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
	if (finished)
		{
			[controller play];
		}
}];
}
}

Managing videos in a playlist

One way to manage a playlist of videos is to store the video objects in a table. When the user selects a video from the table, the table row will contain the video object.

Here's an overview of how it works:

  1. Retrieve a playlist from your account.

    - (void)retrievePlaylist
    {
    [self.refreshControl beginRefreshing];
    
    // Retrieve a playlist through the BCOVPlaybackService
    BCOVPlaybackServiceRequestFactory *playbackServiceRequestFactory = [[BCOVPlaybackServiceRequestFactory alloc]         initWithAccountId:kDynamicDeliveryAccountID
    																policyKey:kDynamicDeliveryPolicyKey];
    BCOVPlaybackService *playbackService = [[BCOVPlaybackService alloc] initWithRequestFactory:playbackServiceRequestFactory];
    
    [playbackService findPlaylistWithReferenceID:kDynamicDeliveryPlaylistRefID
    																parameters:nil
    																completion:^(BCOVPlaylist *playlist, NSDictionary *jsonResponse, NSError *error)
    {
    	 [self.refreshControl endRefreshing];
    
    	 NSLog(@"JSON Response:\n%@", jsonResponse);
    
    	 if (playlist)
    	 {
    			 self.currentVideos = playlist.videos.mutableCopy;
    			 self.currentPlaylistTitle = playlist.properties[@"name"];
    			 self.currentPlaylistDescription = playlist.properties[@"description"];
    
    			 NSLog(@"Retrieved playlist containing %d videos", (int)self.currentVideos.count);
    
    			 [self usePlaylist:self.currentVideos];
    	 }
    	 else
    	 {
    			 NSLog(@"No playlist for ID %@ was found.", kDynamicDeliveryPlaylistRefID);
    	 }
    
    }];
    }
  2. Re-initialize the containers that store information related to the videos in the current playlist.

  3. When the table view is selected, the row's index is used to create a new videoDictionary. Next, ask the dictionary for the video. If the video is not null, then load the video in the playbackController.

    // Play the video in this row when selected
    - (IBAction)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
    {
    NSDictionary *videoDictionary = self.videosTableViewData[ (int)indexPath.row ];
    BCOVVideo *video = videoDictionary[@"video"];
    
    if (video != nil)
    {
    	[self.playbackController setVideos:@[ video ]];
    }
    }

To work with playlists, you can store the playlist in another object such as a table. Based on user interaction, you can navigate the object's indices and select the appropriate video.

Media progress values

During media playback, the values reported to the Player SDK progress delegate method may include an initial value of negative infinity and a final value of positive infinity. These values are used when processing pre-roll and post-roll ads.

If these values are not important to you or interfere with your own progress tracking, they can be easily ignored with a conditional statement like this:

- (void)playbackController:(id<BCOVPlaybackController>)controller playbackSession:(id<BCOVPlaybackSession>)session didProgressTo:(NSTimeInterval)progress
{
if (progress < 0.0 || progress >= INFINITY)
return;
// Your code here
}

OnceUX quartile events

When reading OnceUX VMAPS with the Brightcove OnceUX plugin, the quartile events must define valid offset values. In other words, the quartiles must contain offsets within their quartile impressions in order to be fired at that time.

Here are the observed events that are fired through the end of a pre-roll ad, when the quartile offsets are absent:

impression
companionCreativeView
creativeView
complete

Here are the observed events when valid offset values are used:

companionCreativeView
impression
creativeView
start
firstQuartile
midpoint
thirdQuartile
complete

OnceUX maintains an array of events to be fired during playback of ads, and that array is ordered by the event offsets. An event which does not possess a valid offset cannot be added to the array which means it cannot be fired during ad playback. The complete event is a special case which is handled without using the ordered event array.

Paging with the Playback API

When retrieving your Video Cloud content from the Playback API, you can implement paging for a playlist.

To page through a set of videos in a playlist, use the following request URL parameters:

  • limit - defines the number of videos to return from the Playback API
  • offset - sets the number of videos to skip in a playlist from the Playback API

This example returns 6 videos starting with the 10th video in the playlist:

NSDictionary *params =
@{
@"limit": @6,
@"offset": @9
};
[playbackService findPlaylistWithReferenceID:playlistRefID
parameters:params
completion:^(BCOVPlaylist *playlist, NSDictionary *jsonResponse, NSError *error)
{ ...

Programmatically adding cue points

Video Cloud customers can add cue points to a video using Video Cloud Studio as shown in the Adding Cue Points to Videos document.

You can also add cue points to your video programmatically. The code below adds quarterly interval cue points to the video returned from the Playback API:

// programmatically add cue points to a video
- (void)requestContentFromPlaybackService
{
[self.service findVideoWithVideoID:kViewControllerVideoID parameters:nil completion:^(BCOVVideo *video, NSDictionary *jsonResponse, NSError *error) {
if (video)
{
// Get the video duration from the properties dictionary
NSNumber *durationNumber = video.properties[@"duration"]; // milliseconds
float duration = durationNumber.floatValue / 1000.0; // convert to seconds
video = [video update:^(id<BCOVMutableVideo> mutableVideo)
{
// Add quarterly interval cue points of your own type
BCOVCuePoint *cp1 = [[BCOVCuePoint alloc] initWithType:@"your cue point type" position:CMTimeMake(duration * 250, 1000)];
BCOVCuePoint *cp2 = [[BCOVCuePoint alloc] initWithType:@"your cue point type" position:CMTimeMake(duration * 500, 1000)];
BCOVCuePoint *cp3 = [[BCOVCuePoint alloc] initWithType:@"your cue point type" position:CMTimeMake(duration * 750, 1000)];
BCOVCuePoint *cp4 = [[BCOVCuePoint alloc] initWithType:@"your cue point type" position:CMTimeMake(duration * 1000, 1000)];
// Create new cue point collection using existing cue points and new cue points
NSMutableArray *newCuePoints = [[NSMutableArray alloc] initWithArray:mutableVideo.cuePoints.array];
[newCuePoints addObject:cp1];
[newCuePoints addObject:cp2];
[newCuePoints addObject:cp3];
[newCuePoints addObject:cp4];
mutableVideo.cuePoints = [[BCOVCuePointCollection alloc] initWithArray:newCuePoints];
}];
[self.playbackController setVideos:@[ video ]];
}
else
{
NSLog(@"ViewController Debug - Error retrieving video: `%@`", error);
}
}];
}

Note that the value of your cue point type can be any string value that you want, as long as you are not using any of the iOS plugins. For details, see the BCOVCuePoint Protocol Reference document.

If you are using cue points with the IMA plugin, learn more about it in the VAST and VMAP/Server Side Ad Rules section of the IMA Plugin for the Native SDK for iOS notes. The IMA sample app shows you the value required for IMA ad cue points.

The code below listens for your cue points and displays a message:

// listen for cue points and display them
-(void)playbackController:(id<BCOVPlaybackController>)controller playbackSession:(id<BCOVPlaybackSession>)session didPassCuePoints:(NSDictionary *)cuePointInfo {
BCOVCuePointCollection *cpc = cuePointInfo[@"kBCOVPlaybackSessionEventKeyCuePoints"];
for (BCOVCuePoint *cp in cpc) {
if ([cp.type isEqualToString:@"your cue point type"])
{
NSLog(@"Found your cue point at %f", CMTimeGetSeconds(cp.position));
}
}
}

Setting the playback rate

To control the playback rate, you can set the rate property on the AVPlayer class exposed on the session. For a BCOVPlaybackSession , you could do something like this:

session.player.rate = 2;

Note the following:

  • For iOS6, a stream can only play at 2X if session.player.currentItem.canPlayFastForward returns YES.
  • For iOS7, you can play up to 2X always, but it won't go higher unless session.player.currentItem.canPlayFastForward returns Yes.

Setting VR Goggles mode for 360° videos

When playing a 360° video, users can select the Video 360 button on the control bar to switch to VR Goggles mode. You may also want to do this programmatically, before playback starts. You can do this by updating the BCOVPlaybackController protocol's viewProjection property as follows:

- (void)playbackController:(id<BCOVPlaybackController>)controller didAdvanceToPlaybackSession:(id<BCOVPlaybackSession>)session
{
BCOVVideo360ViewProjection *viewProjection = [self.playbackController.viewProjection copy];
[viewProjection setProjectionStyle:BCOVVideo360ProjectionStyleVRGoggles];
[self.playbackController setViewProjection:viewProjection];
}

VoiceOver support

Apple's VoiceOver app, which is integrated in iOS, allows visually impaired users to hear a description of everything that is on the screen.

The built-in playback controls for Brightcove Native SDK for iOS come with accessibility label text, but you can choose to customize these text values. The UIControl objects can be found in the following:

This example shows how to customize the accessibility values for the play button:

// After creating the BCOVPUIPlayerView, store it in a playerView property
// Then set the accessibilityLabel and accessibilityHint properties
self.playerView.controlsView.playbackButton.accessibilityLabel = @"Playback Button";
self.playerView.controlsView.playbackButton.accessibilityHint = @"Play or pause the video";

Changing the background color

When playing a video in portrait mode, you may notice a black border on top and below the player. The player view is the size of the screen, but the video only takes up a small part of the center of the player view. The visible portions around the video is the background of the player layer.

This is normal AVPlayer behavior. It shrinks your video to fit inside the player layer, and the rest is the player layer background.

You can change the player layer background with the following code:

(void)playbackController:(id<BCOVPlaybackController>)controller didAdvanceToPlaybackSession:(id<BCOVPlaybackSession>)session
{
session.playerLayer.backgroundColor = UIColor.whiteColor.CGColor;
}

Setting the background color to white should look like this:

Background color
Custom background color