This topic describes the advanced features of ApsaraVideo Player SDK for iOS and provides the sample code.

Configure playback

Enable list playback for short videos

ApsaraVideo Player SDK for iOS provides a full-fledged list playback feature for short videos. The SDK uses solutions such as preloading to minimize the startup time of short videos. We recommend that you do not enable this feature for long videos.

  1. Create a player.
    Create an AliListPlayer object. Sample code:
    self.listPlayer = [[AliListPlayer alloc] init];
    [listPlayer setTraceID:@"xxxxxx"];  // TraceID indicates the unique identifier of the device or the user. In most cases, the value is the International Mobile Equipment Identity (IMEI) or the Identifier for Advertisers (IDFA) of the device.
  2. Optional:Configure listeners.
    Listeners are optional when you create a short video list player. If you do not configure listeners, you cannot receive notifications of events related to the player, such as the failure and progress of the playback. We recommend that you configure listeners.

    You can configure multiple listeners for your player. We recommend that you configure the following listeners: onPlayerEvent and onError.

    /**
     @brief The callback for an invalid delegate.
     @param player The pointer for the player.
     @param errorModel The description of player errors. For more information, see AliVcPlayerErrorModel.
     */
    - (void)onError:(AliPlayer*)player errorModel:(AVPErrorModel *)errorModel {
        // Indicates that an error occurred and the playback is stopped.
    }
    /**
     @brief The callback for player events.
     @param player The pointer for the player.
     @param eventType The type of the player event. For more information, see AVPEventType.
     */
    -(void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
        switch (eventType) {
            case AVPEventPrepareDone: {
                // The preparation is complete.
            }
                break;
            case AVPEventAutoPlayStart:
                // The autoplay starts.
                break;
            case AVPEventFirstRenderedStart:
                // The first frame appears.
                break;
            case AVPEventCompletion:
                // The playback is complete.
                break;
            case AVPEventLoadingStart:
                // The buffering starts.
                break;
            case AVPEventLoadingEnd:
                // The buffering is complete.
                break;
            case AVPEventSeekEnd:
                // The seeking is complete.
                break;
            case AVPEventLoopingStart:
                // The loop playback starts.
                break;
            default:
                break;
        }
    }
    /**
     @brief The callback for the current playback position.
     @param player The pointer for the player.
     @param position The current playback position.
     */
    - (void)onCurrentPositionUpdate:(AliPlayer*)player position:(int64_t)position {
        // Updates the playback progress.
    }
    /**
     @brief The callback for the buffer position.
     @param player The pointer for the player.
     @ param position The current buffer position.
     */
    - (void)onBufferedPositionUpdate:(AliPlayer*)player position:(int64_t)position {
        // Updates the buffer progress.
    }
    /**
     @ brief The callback for obtaining the track information.
     @param player The pointer for the player.
     @param info track The array of track information. For more information, see AVPTrackInfo.
     */
    - (void)onTrackReady:(AliPlayer*)player info:(NSArray<AVPTrackInfo*>*)info {
        // Obtains the information about different bitrates.
    }
    /**
     @brief The callback for displaying the subtitle.
     @param player The pointer for the player.
     @param index The index number for the subtitle.
     @param subtitle The string of the subtitle.
     */
    - (void)onSubtitleShow:(AliPlayer*)player index:(int)index subtitle:(NSString *)subtitle {
        // Obtains the subtitle for display.
    }
    /**
     @brief The callback for hiding the subtitle.
     @param player The pointer for the player.
     @param index The index number for the subtitle.
     */
    - (void)onSubtitleHide:(AliPlayer*)player index:(int)index {
        // Hides the subtitles.
    }
    /**
     @brief The callback for snapshot capture.
     @param player The pointer for the player.
     @param image The image.
     */
    - (void)onCaptureScreen:(AliPlayer *)player image:(UIImage *)image {
        // Previews and saves the snapshot.
    }
    /**
     @brief The callback that indicates that the track is switched.
     @param player The pointer for the player.
     @param info The information about the switching after the switching is complete. For more information, see AVPTrackInfo.
     */
    - (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info {
        // Notifies the result of track switching.
    }
    //...
  3. Specify the number of videos that you want to preload.
    You can specify the number of videos that you want to preload based on your business requirements. This reduces the startup time. Sample code:
    // Specify the number of videos that you want to preload. The total number of loaded videos is equal to one plus twice the specified number. 
    self.listplyer.preloadCount = 2;
  4. Add or remove multiple playback sources.
    List playback supports the VidSts playback source and UrlSource playback source. Url indicates the playback URL. vid indicates the audio or video ID. Sample code:
    • Url: The playback URL can be the URL of an audio file or video file in ApsaraVideo VOD or on a third-party video-on-demand (VOD) platform. You can call the GetPlayInfo operation to obtain the playback URL of an audio file or video file in ApsaraVideo VOD. We recommend that you use a server SDK to obtain media playback URLs in ApsaraVideo VOD. This frees you from complex signature calculations. For more information about the GetPlayInfo operation, see OpenAPI Explorer.
    • Vid: The audio or video ID. To obtain the ID, log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video in the left-side navigation pane. Alternatively, you can call the SearchMedia operation.
    // Add a VidSts playback source.
    [self.listPlayer addVidSource:videoId uid:UUIDString];
    // Add a UrlSource playback source.
    [self.listPlayer addUrlSource:URL uid:UUIDString];
    // Remove a playback source.
    [self.listPlayer removeSource:UUIDString];
    Note
    • VidAuth and VidMps are not supported for list playback.
    • The uid parameter specifies the unique ID of a video. You can use the unique ID to identify videos. Videos with the same unique ID are considered the same. If the player plays a video that is not the one you specified, check whether you specify the same ID for multiple videos. You can set the unique ID to any string that you prefer.
  5. Configure the user interface (UI) view.
    If the playback source contains video images, you must configure the UI view to display the video images in the player. Sample code:
    self.listPlayer.playerView = self.simplePlayScrollView.playView;
  6. Play the video source.
    After you add one or more playback sources, call the moveTo method to play the content from the specified playback source. Sample code:
    // Call moveTo in the following way for UrlSource playback sources:
    - (BOOL) moveTo:(NSString*)uid;
    // Call moveTo in the following way for VidSts playback sources. If you want to use VidSts playback sources, you must obtain the STS token and AccessKey pair in advance. For more information, see Create a RAM role and grant temporary access permissions to the role by using STS. 
    - (BOOL) moveTo:(NSString*)uid accId:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;
  7. Play the previous or next video in the list.
    You can call moveToPrev to play the previous video or call moveToNext to play the next video. Sample code:

    // Play the next video. 
    - (BOOL) moveToNext;
    // Play the previous video. 
    - (BOOL) moveToPre;

    // Play the next video. 
    - (BOOL) moveToNext:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;
    // Play the previous video. 
    - (BOOL) moveToPre:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;

Configure external subtitles

ApsaraVideo Player SDK for iOS allows you to add, turn on, and turn off external subtitles that are in the SubRip Subtitle (SRT) format, SubStation Alpha (SSA) format, Advanced SubStation Alpha (ASS) format, or Web Video Text Track (WebVTT) format. Sample code:

  1. Create a view that displays the subtitles.
    You must create different views for subtitles in different formats.
    // Initialize the custom subTitleLabel view.
    UILabel *subTitleLabel = [[UILabel alloc] initWithFrame:frame];
    // Add the subTitleLabel view to a custom superview, which is the parent view of the custom user interface.
    [superView addSubview:subTitleLabel];
  2. Configure listeners for subtitles.
    // Listens to the callback for adding an external subtitle.
    - (void)onSubtitleExtAdded:(AliPlayer*)player trackIndex:(int)trackIndex URL:(NSString *)URL {}
    // Listens to the callback for obtaining subtitle header information.
    - (void)onSubtitleHeader:(AliPlayer *)player trackIndex:(int)trackIndex Header:(NSString *)header {}
    // Listens to the callback for displaying the subtitle.
    - (void)onSubtitleShow:(AliPlayer*)player trackIndex:(int)trackIndex subtitleID:(long)subtitleID subtitle:(NSString *)subtitle {
        subTitleLabel.text = subtitle;
        subTitleLabel.tag = subtitleID;
    }
    // Listens to the callback for hiding the subtitle.
    - (void)onSubtitleHide:(AliPlayer*)player trackIndex:(int)trackIndex subtitleID:(long)subtitleID {
        [subTitleLabel removeFromSuperview];
    }
  3. Add subtitles.
    [self.player addExtSubtitle:URL];
  4. Switch subtitles.
    [self.player selectExtSubtitle:trackIndex enable:YES];

Enable audio-only playback

You can disable the display of video images to enable audio-only playback. Before you call the prepare method, configure the PlayerConfig class.
AVPConfig *config = [self.player getConfig];
config.disableVideo = YES;
[self.player setConfig:config];

Switch between hardware decoding and software decoding

ApsaraVideo Player SDK for iOS supports hardware decoding based on the H.264 standard and H.265 standard. You can call enableHardwareDecoder to enable or disable the hardware decoding feature. By default, hardware decoding is enabled. If hardware decoding fails to be initialized, software decoding is automatically used to ensure video playback. Sample code:
// Enable hardware decoding. By default, hardware decoding is enabled.
self.player.enableHardwareDecoder = YES;
If you switch hardware decoding to software decoding, a callback is invoked by the onPlayerEvent method. The following sample code provides an example:
-(void)onPlayerEvent:(AliPlayer*)player eventWithString:(AVPEventWithString)eventWithString description:(NSString *)description {
    if (eventWithString == EVENT_SWITCH_TO_SOFTWARE_DECODER) {
        // Switch to software decoding.
    }
}

Adaptive bitrate streaming

ApsaraVideo Player SDK for iOS supports adaptive bitrate streaming of HTTP Live Streaming (HLS) video streams and Dynamic Adaptive Streaming over HTTP (DASH) video streams. After the prepare method is called, call getMediaInfo to obtain the bitrate information that is indicated by TrackInfo. Sample code:
AVPMediaInfo *info = [self.player getMediaInfo];
NSArray<AVPTrackInfo*>* tracks = info.tracks;
Note You must package HLS video streams and DASH video streams by using a multi-bitrate transcoding template group. To use the template group, log on to the ApsaraVideo VOD console and choose Configuration Management > Media Processing > Transcoding Template Groups in the left-side navigation pane. For more information, see Configure video packaging templates.
During the playback, you can call the selectTrack method to switch to the required bitrate. If you specify SELECT_AVPTRACK_TYPE_VIDEO_AUTO in the method, adaptive bitrate streaming is enabled. Sample code:
// Switch the bitrate.
[self.player selectTrack:track.trackIndex];
// Enable adaptive bitrate streaming.
[self.player selectTrack:SELECT_AVPTRACK_TYPE_VIDEO_AUTO];
The callback invoked by the onTrackChanged method returns the switching result. Sample code:
- (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info {
    if (info.trackType == AVPTRACK_TYPE_VIDEO) {
        // video changed
    }
    // etc
}

Capture snapshots

ApsaraVideo Player SDK for iOS provides the snapshot method to allow you to capture snapshots from videos. When you capture a snapshot, the player saves the source data of the video image to be captured and converts the source data to a bitmap. After the snapshot is captured, you can invoke the onCaptureScreen callback to obtain the bitmap. Sample code:
// Configure the callback for snapshot capture.
- (void)onCaptureScreen:(AliPlayer *)player image:(UIImage *)image {
    // Process the snapshot.
}
// Capture a snapshot of the current video image.
aliyunVodPlayer.snapshot();
Note A snapshot does not contain the UI.

Configure video preview

ApsaraVideo Player SDK for iOS integrates specific configurations of ApsaraVideo VOD to support previews of videos. Only VidSts sources and VidAuth sources can be previewed. We recommend that you preview only VidAuth sources in ApsaraVideo VOD. For more information about how to configure and use the preview feature, see Configure the preview feature.

After you enable the preview feature, you can call the setPreviewTime method in the VidPlayerConfigGen class to specify the preview period. The following sample code provides an example. In this example, VidSts is used.
AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
....
VidPlayerConfigGenerator* vp = [[VidPlayerConfigGenerator alloc] init];
[vp setPreviewTime:20];// Set the preview duration to 20s.
source.playConfig = [vp generatePlayerConfig];// Configure the settings for the player.
...
After you specify the preview duration, ApsaraVideo Player SDK for iOS allows you to preview a video for the specified duration instead of the whole video.
Note You can call the VidPlayerConfigGen method to set the request parameters that are supported by the server. For more information, see Request parameters.

Set the referer

ApsaraVideo Player SDK for iOS provides the AVPConfig class for you to set the request referer. You can use the referer together with a referer whitelist or blacklist configured in the ApsaraVideo VOD console to implement access control. Sample code:
// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Set the referer.
config.referer = referer;
.... // Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];

Specify the user agent

ApsaraVideo Player SDK for iOS provides the AVPConfig class for you to specify the request user agent. After you specify the user agent, the player includes the user agent information in the requests. Sample code:
// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Specify the user agent.
config.userAgent = userAgent;
.... // Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];

Specify the network timeout period and number of retries

ApsaraVideo Player SDK for iOS provides the AVPConfig class to allow you to specify the network timeout period and the number of retries. Sample code:
// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Set the network timeout period. Unit: milliseconds.
config.networkTimeout = 5000;
// Specify the maximum number of retries upon a network timeout. The retry interval equals the timeout period specified by the NetworkTimeout parameter. The NetworkRetryCount parameter specifies the number of retries. A value of 0 indicates zero retry. The application determines the number of retries. Default value: 2.
config.networkRetryCount = 2;
.... // Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];
Note
  • If you set the networkRetryCount parameter to a value other than 0, the player retries playback when the player starts to load data due to a network error. The maximum number of retries is equal to the value of the networkRetryCount parameter. The retry interval is equal to the value of the networkTimeout parameter.
  • If loading persists after the maximum number of retries is reached, a callback is invoked by the onError method. In this case, the AVPErrorModel.code method returns ERROR_LOADING_TIMEOUT.
  • If you set the networkRetryCount parameter to 0, a callback is invoked by the onPlayerEvent method when a network timeout occurs. In this case, the eventWithString method returns EVENT_PLAYER_NETWORK_RETRY. To resolve the issue, you can call the reload method provided by ApsaraVideo Player SDK for iOS to reload network packets or perform other operations based on your business requirements.

Control the buffer and latency

Buffer control is important for a player. You can reduce the startup loading duration and improve playback smoothness by using proper configurations. ApsaraVideo Player SDK for iOS provides the AVPConfig class to allow you to configure buffer settings and latency settings. Sample code:
// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Set the maximum latency. Note: This parameter is valid only for live streaming. If the latency exceeds the maximum limit, ApsaraVideo Player SDK synchronizes frames to ensure that the latency does not exceed the limit. 
config.maxDelayTime = 5000;
// Set the maximum buffer duration. Unit: milliseconds. This parameter specifies the maximum buffer duration for the player to load data at a time. 
config.maxBufferDuration = 50000;
// Specify the peak buffer duration. Unit: milliseconds. This parameter specifies the peak buffer duration. After the peak buffer duration elapses, the player stops loading data if the network conditions are poor. 
config.highBufferDuration = 3000;
// Set the startup loading duration. Unit: milliseconds. A smaller value indicates a shorter startup loading duration. In this case, the player starts to load data sooner after the playback starts. 
config.startBufferDuration = 500;
// Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];
Important
  • Make sure that the value of the startBufferDuration parameter is not greater than the value of the highBufferDuration parameter. Make sure that the value of the highBufferDuration parameter is not greater than the value of the maxBufferDuration parameter.
  • When mMaxBufferDuration is greater than 5 minutes, the peak buffer duration is set to 5 minutes to prevent memory exceptions caused by excessive buffer size. When mMaxBufferDuration is greater than 50,000 ms (50 seconds), you can enable large cache to reduce the memory usage and improve playback performance. For more information, see Configure large cache.

Configure HTTP headers

ApsaraVideo Player SDK for iOS provides the AVPConfig class for you to add HTTP headers to requests. Sample code:
// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Define a header.
NSMutableArray *httpHeaders = [[NSMutableArray alloc] init];
// Configure a host when you use Alibaba Cloud HTTPDNS. 
[httpHeaders addObject:@"Host:example.com"];
// Configure the header.
config.httpHeaders = httpHeaders;
.... // Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];

Configure picture-in-picture (PiP)

Note
  • You can use the PiP feature only when you use ApsaraVideo Player V5.4.9.0 or later on devices that run iOS 15 or later.
  • You can call specific API operations to enable and disable the PiP feature and specify whether to play videos in a floating window when the application is switched to the backend.
After the PiP feature is enabled, the video is played in a floating window when the application is switched to the backend. When the application is switched to the frontend, the video is played in the application window. You can call the setPictureInPictureEnable operation to enable and disable the PiP feature. Before you enable the PiP feature, make sure that the player is prepared. AVPEventPrepareDone indicates that the player is prepared. Sample code:
- (void)onPlayerEvent:(AliPlayer *)player eventType:(AVPEventType)eventType {
    switch (eventType) {
        case AVPEventPrepareDone:
        {
            [self.player setPictureInPictureEnable:YES];
        }
            break;
        default:
            break;
    }
}

Configure the performance

Configure local caching

ApsaraVideo Player SDK for iOS allows you to cache videos during playback. This reduces the startup loading time, accelerates the seeking process, reduces playback latency, and saves your traffic during loop playback.

Enable local caching

By default, the video preload feature is disabled. To use this feature, you must manually enable it. You can call the enableLocalCache method in the AliPlayerGlobalSettings class. Sample code:
/**
 * Enable video preload. After this feature is enabled, a media file is cached on your device. 
 * @param enable: specifies whether to enable the video preload feature. Valid values: true and false. true indicates that the video preload feature is enabled and false indicates that the video preload feature is disabled. Default value: false. 
 * @param maxBufferMemoryKB -This parameter is deprecated in the new version. 
 * @param localCacheDir: Required. The directory of the cached file, which is an absolute path. 
 */
[AliPlayerGlobalSettings enableLocalCache:true maxBufferMemoryKB:1024 localCacheDir:@""];

/**
 @brief Configure settings for clearing cached files. 
 @param expireMin -This parameter is deprecated in the new version. 
 @param maxCapacityMB: the maximum size of cached data. Unit: MB. By default, the maximum size of cached data is 20 GB. If the specified maximum size is exceeded, the system deletes cached files based on the time when the file is cached until the size of the cached data is less than or equal to the specified maximum size. During this process, the system preferentially deletes the earliest files that are cached. 
 @param freeStorageMB: the minimum idle space of the disk. Unit: MB. Default value: 0. If the idle space of the disk is less than the specified minimum space, the system deletes cached files based on the time when the file is cached until the idle space of the disk is greater than or equal to the specified minimum space. During this process, the system preferentially deletes the earliest files that are cached. 
 */
[AliPlayerGlobalSettings setCacheFileClearConfig:0 maxCapacityMB:0 freeStorageMB:0];

/**
 * Obtain the callback for the URL hash value of the video file and use it as the unique ID of the URL. 
 */

// You must run the function block and set the function pointer to setCacheUrlHashCallback.
static NSString *CaheUrlHashHandle(NSString *url) {
    return @"xxx";
}

[AliPlayerGlobalSettings setCacheUrlHashCallback:&CaheUrlHashHandle];
Note
  • If the streaming URL of a video file contains authentication parameters, the values of the authentication parameters change during local caching and playback of the video file. You can calculate the MD5 hash value after you remove the authentication parameters. For example, http://****.mp4?aaa is the streaming URL of a video file and contains authentication parameters. In this case, the URL http://****.mp4 is used to calculate the MD5 hash value when the video file is loaded.
  • If your server supports both HTTP and HTTPS protocols and a video file can be specified by using two URLs with the same elements but different protocols, you can remove the protocol header of the URLs or use the URL with the HTTP protocol to calculate the MD5 hash value. Examples:
    • If the streaming URLs of a video file are https://****.mp4 and http://****.mp4, the MD5 hash value is calculated by using ****.mp4 when the video file is loaded.
    • If the streaming URL of the video file is https://****.mp4, the MD5 hash value is calculated by using the URL http://****.mp4 when the video file is loaded.

Enable or disable local caching for a single URL

You can disable local caching for a single URL in player config. Sample code:
// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Configure whether to enable local caching for the playback URL. Default value: true. When local caching is enabled in AliPlayerGlobalSettings and the value of this parameter is true, the local caching for the URL takes effect. If the value of this parameter is false, the local caching for the URL is disabled. 
config.enableLocalCache = false;
.... // Configure other settings.

// Configure the settings for the player.
[self.player setConfig:config];

Configure large cache

You can set the maximum buffer duration of data to cache video in the memory during playback, which improves the playback performance and experience. If the maximum buffer duration is set too large, the buffer consumes excessive memory. You can use the large cache feature to cache videos in files, which reduces memory usage and improves player performance.

When mMaxBufferDuration is greater than 50,000 ms, you can enable local caching to automatically trigger large cache. Procedure:

  1. Enable the global local caching feature.
    By default, the video preload feature is disabled. To use this feature, you must enable it. You can call the enableLocalCache method in the AliPlayerGlobalSettings class. For more information about the sample code, see the Enable local caching section in Configure local caching.
  2. Enable local caching for a URL.
    For more information about the sample code, see the Enable or disable local caching for a single URL section in Configure local caching.

Configure video preload

ApsaraVideo Player SDK for iOS supports video preload, which is an upgrade of the local caching feature. The video preload feature allows you to specify the maximum size of memory that can be occupied by cached videos. This helps reduce the startup loading duration.

The video preload feature has the following limits:
  • You can preload only one MP4, MP3, FLV, or HLS file at a time.
  • You can preload only videos that are played based on URLs. You cannot preload videos that use VidAuth or VidSts for playback.
Note By default, network resource scheduling is enabled when you use ApsaraVideo Player SDK for iOS to preload videos. This ensures the quality of the video that is being played. If network resource scheduling is enabled, the preload request is sent only after the buffered content of the video that is being played reaches a specific limit. You can disable network resource scheduling if you want to manage the real-time preload requests. Sample code:
[AliPlayerGlobalSettings enableNetworkBalance: false];
  1. Enable the local caching feature. For more information, see Configure local caching.
  2. Obtain an AliMediaLoader instance.

    The AliMediaLoader instance is a singleton. You can create only one AliMediaLoader instance regardless of the times for which you obtain the instance.

    [AliMediaLoader shareInstance];
  3. Configure the AliMediaLoader instance.
    // Configure listeners and start to load video files. 
    // url: the URL of the video file.  duration: the loading duration. Unit: milliseconds. 
    [[AliMediaLoader shareInstance] load:obj.url duration:1000];
    // Configure a callback delegate.
    [[AliMediaLoader shareInstance] setAliMediaLoaderStatusDelegate:self];
    
    @protocol AliMediaLoaderStatusDelegate <NSObject>
    @optional
    
    /**
     @brief The callback that is invoked when an error occurs.
     @ param url The URL.
     @param code The error code.
     @ param msg The error description.
     */
    - (void)onError:(NSString *)url code:(int64_t)code msg:(NSString *)msg;
    
    /**
     @ brief The callback that is invoked when the loading is complete.
     @ param url The URL.
     */
    - (void)onCompleted:(NSString *)url;
    
    /**
     @ brief The callback that is invoked when the loading is canceled.
     @ param url The URL.
     */
    - (void)onCanceled:(NSString *)url;
    
    @end
  4. Optional:Delete the loaded video files.
    You can delete the loaded video files to reduce occupied space. ApsaraVideo Player SDK for iOS does not provide a method to delete the loaded video files. You must delete the video files in the corresponding directory in your application.

Obtain the download speed

ApsaraVideo Player SDK for iOS allows you to obtain the download speed of specified videos. You can obtain the download speed from the callback of the onCurrentDownloadSpeed method. Sample code:
- (void)onCurrentDownloadSpeed:(AliPlayer *)player speed:(int64_t)speed {
    int speed_ = speed;
}

Configure the network

Enable HTTP/2

ApsaraVideo Player SDK for iOS supports HTTP/2. You can enable HTTP/2 to realize multiplexing of requests. This prevents head-of-line (HOL) blocking and therefore improves playback performance. The following sample code provides an example:
[AliPlayerGlobalSettings setUseHttp2:true];

Configure video download

Note Resumable download is supported.
ApsaraVideo Player SDK for iOS allows you to download videos from VidSts and VidAuth sources in ApsaraVideo VOD. You can download videos in secure download mode or normal download mode. To configure the download settings, log on to the ApsaraVideo VOD and choose Configuration Management > CDN Configuration > Download in the left-side navigation pane.
  • Normal download: Videos that are downloaded in the normal download mode are not encrypted by Alibaba Cloud and can be played by third-party players.
  • Secure download: Videos that are downloaded in the secure download mode are encrypted by Alibaba Cloud. You cannot use third-party players to play the downloaded videos. You can use only ApsaraVideo Player to play them.
  1. Create and configure a downloader.
    Create a download object. The following sample code provides an example:
    AliMediaDownloader *downloader = [[AliMediaDownloader alloc] init];
    [downloader setSaveDirectory:self.downLoadPath];
    [downloader setDelegate:self];
    ApsaraVideo Player SDK for iOS allows you to download videos that are encrypted by using Alibaba Cloud proprietary cryptography. For security reasons, you must configure a security file for encryption verification in the SDK. We recommend that you configure the security file in your application. The following sample code provides an example:
    NSString *encrptyFilePath = [[NSBundle mainBundle] pathForResource:@"encryptedApp" ofType:@"dat"];
    [AliPrivateService initKey:encrptyFilePath];
    Important If you download a video in secure download mode and the information in the security file for encryption verification does not match the application information, the video download fails.
  2. Configure listeners.
    The download object provides multiple listeners. The following sample code provides an example:
    -(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info {
        // Listens to the preparation of the content to be downloaded.
    }
    -(void)onError:(AliMediaDownloader *)downloader errorModel:(AVPErrorModel *)errorModel {
        // Listens to a download error.
    }
    -(void)onDownloadingProgress:(AliMediaDownloader *)downloader percentage:(int)percent {
        // Listens to the percentage of the download progress.
    }
    -(void)onProcessingProgress:(AliMediaDownloader *)downloader percentage:(int)percent {
        // Listens to the percentage of the processing progress.
    }
    -(void)onCompletion:(AliMediaDownloader *)downloader {
        // Listens to a successful download.
    }
  3. Prepare the download source.
    You can call the prepare method to prepare a download source. AVPVidStsSource and AVPVidAuthSource are supported. The following code uses AVPVidStsSource as an example:
    // Add the VidSts download source.
    AVPVidStsSource* stsSource = [[AVPVidStsSource alloc] init];
    stsSource.vid = source.vid;// The video ID.
    stsSource.region = DEFAULT_SERVER.region;// The access region.
    stsSource.securityToken = DEFAULT_SERVER.securityToken;// The security token.
    stsSource.accessKeySecret = DEFAULT_SERVER.accessKeySecret;// The temporary AccessKey secret.
    stsSource.accessKeyId = DEFAULT_SERVER.accessKeyId;// The temporary AccessKey ID.
    // Prepare the download source.
    [downloader prepareWithVid:stsSource];
  4. Select the content to be downloaded from the prepared download source.
    After the download source is prepared, a callback is invoked by the onPrepared method. Select a track to be downloaded:
    -(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info {
        NSArray<AVPTrackInfo*>* tracks = info.tracks;
        // Download the information about tracks, such as the first track.
        [downloader selectTrack:[tracks objectAtIndex:0].trackIndex];
    }
  5. Update the download source and start the download.
    VidSts or VidAuth may expire before the download. Therefore, we recommend that you update the download source before you start the download. The following sample code provides an example:
    // Update the download source.
    [downloader updateWithVid:vidSource]
    // Start the download.
    [downloader start];
  6. Release the download object after the download succeeds or fails.
    After the download succeeds, call the destroy method to release the downloader.
    [self.downloader destroy];
    self.downloader = nil;

Play encrypted videos

ApsaraVideo Player SDK for Android allows you to play on-demand videos encrypted based on HLS encryption, Alibaba Cloud proprietary cryptography, or digital rights management (DRM) encryption. The SDK allows you to play live streams encrypted only based on DRM encryption. For more information, see Play an encrypted video.

Configure Native RTS SDK

You can integrate ApsaraVideo Player SDK for iOS with Native RTS SDK to use the Real-Time Streaming (RTS) feature. For more information, see Native RTS SDK for iOS.

References