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 preload to minimize the startup loading duration of playbacks. We recommend that you do not enable this feature for long videos.

  1. Create a player.
    Create an AliListPlayer object. The following sample code provides an example:
    self.listPlayer = [[AliListPlayer alloc] init];
    [listPlayer setTraceID:@"xxxxxx"];  // The trace ID is the unique identifier of the device used by 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. However, 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. Therefore, we recommend that you configure listeners as needed.

    You can configure multiple listeners for your player. We recommend that you configure the following important 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. This parameter is similar to the AliVcPlayerErrorModel parameter.
     */
    - (void)onError:(AliPlayer*)player errorModel:(AVPErrorModel *)errorModel {
        // Indicates that an error occurred and the playback stopped.
    }
    /**
     @brief The callback for player events.
     @param player The pointer for the player.
     @param eventType The event type of the player. This parameter is similar to the AVPEventType parameter.
     */
    -(void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
        switch (eventType) {
            case AVPEventPrepareDone: {
                // The completion of preparation.
            }
                break;
            case AVPEventAutoPlayStart:
                // The start of autoplay.
                break;
            case AVPEventFirstRenderedStart:
                // The display of the first frame.
                break;
            case AVPEventCompletion:
                // The completion of playback.
                break;
            case AVPEventLoadingStart:
                // The start of buffering.
                break;
            case AVPEventLoadingEnd:
                // The completion of buffering.
                break;
            case AVPEventSeekEnd:
                // The completion of seeking.
                break;
            case AVPEventLoopingStart:
                // The start of loop playback.
                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 progress bar.
    }
    /**
     @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. This parameter is similar to the AVPTrackInfo parameter.
     */
    - (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 subtitle.
    }
    /**
     @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 for indicating the completion of track switching.
     @param player The pointer for the player.
     @param info The information about the track after the switching is complete. This parameter is similar to the AVPTrackInfo parameter.
     */
    - (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info {
        // Notifies the bitrate after switching.
    }
    //...
  3. Set the number of videos that you want to preload.
    You can set the number of videos to be preloaded based on your business requirements. This way, the startup loading duration can be reduced. The following sample code provides an example:
    // Set 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 and UrlSource playback sources. UrlSource is used for URL-based playback, and VidSts is used for ID-based playback. The following sample code provides an example:
    • UrlSource: The streaming URL can be the URL of an audio or a video in ApsaraVideo VOD or on a third-party video-on-demand (VOD) platform. You can call the GetPlayInfo operation to obtain the streaming URL of an audio or a video in ApsaraVideo VOD. We recommend that you integrate a server operation SDK of ApsaraVideo VOD to obtain the URL. This way, you do not need to calculate the signature value. For more information, see GetPlayInfo in OpenAPI Explorer.
    • VidSts: To obtain the ID of an audio or a video, you can 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 a unique ID for multiple videos. You can set the uid parameter to a string.
  5. Configure the UI view.
    If the playback source contains video images, you must configure the UI view to display the video images in the player. The following sample code provides an example:
    self.listPlayer.playerView = self.simplePlayScrollView.playView;
  6. Play the content from a playback source.
    After you add one or more playback sources, call the moveTo method to play the content from the specified playback source. The following sample code provides an example:
    // Call the moveTo method in the following way for UrlSource playback sources:
    - (BOOL) moveTo:(NSString*)uid;
    // Call the moveTo method in the following way for VidSts playback sources. If you use VidSts playback sources, you must obtain the STS token and AccessKey pair in advance. For more information, see Create a 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 the moveToPrev method to play the previous video or call the moveToNext method to play the next video. The following sample code provides an example:

    // 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 or switch external subtitles in the SRT, SSA, or ASS3 format for videos. The following sample code provides an example:

  1. Create a view that displays the subtitle.
    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.
    [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 and software decodings

ApsaraVideo Player SDK for iOS supports hardware decoding based on the H.264 and H.265 standards. You can call the enableHardwareDecoder method to enable or disable the hardware decoding feature. By default, hardware decoding is enabled. If hardware decoding fails to be initialized, it is switched to software decoding to ensure normal playback. The following sample code provides an example:
// Enable hardware decoding. By default, hardware decoding is enabled.
self.player.enableHardwareDecoder = YES;
When hardware decoding is switched 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.
    }
}

Enable adaptive bitrate streaming

ApsaraVideo Player SDK for iOS supports adaptive bitrate streaming of Http-Live-Streaming (HLS) or DASH video streams. After the player is prepared by using the prepare method, you can call the getMediaInfo method to query the bitrate information, which is indicated by the TrackInfo parameter. The following sample code provides an example:
AVPMediaInfo *info = [self.player getMediaInfo];
NSArray<AVPTrackInfo*>* tracks = info.tracks;
Note You must package HLS 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 the bitrate. If you pass SELECT_AVPTRACK_TYPE_VIDEO_AUTO to the method, adaptive bitrate streaming is enabled. The following sample code provides an example:
// 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. The following sample code provides an example:
- (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 for you to capture snapshots of 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. Then, you can invoke the onCaptureScreen callback to obtain the bitmap. The following sample code provides an example:
// 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 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 duration. 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 use the VidPlayerConfigGen class 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. The following sample code provides an example:
// 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 contains the user agent information in its requests. The following sample code provides an example:
// 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];

Set the network timeout period and retries

ApsaraVideo Player SDK for iOS provides the AVPConfig class for you to set the network timeout period and retries. The following sample code provides an example:
// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Set the network timeout period. Unit: milliseconds.
config.networkTimeout = 5000;
// Set 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 maximum number of retries. A value of 0 indicates zero retry. The application determines the maximum 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 equals the value of the networkRetryCount parameter. The retry interval equals 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 of ApsaraVideo Player SDK for iOS to reload network packets or perform other operations as required.

Configure buffer and latency settings

Buffer control is important for a player. You can significantly shorten the startup loading duration and improve playback smoothness with proper configuration. ApsaraVideo Player SDK for iOS provides the AVPConfig class for you to configure buffer and latency settings. The following sample code provides an example:
// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Set the maximum latency. 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 is within 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;
// Set the peak buffer duration. Unit: milliseconds. The player starts to load data if the network condition is unstable. This parameter specifies the buffer duration beyond which the player stops loading data in this case. 
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 start of playback. 
config.startBufferDuration = 500;
// Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];
Notice 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.

Configure HTTP headers

ApsaraVideo Player SDK for iOS provides the AVPConfig class for you to add HTTP headers to requests. The following sample code provides an example:
// 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 the performance

Configure local caching

ApsaraVideo Player SDK for iOS allows you to cache videos during playback. This saves your traffic during loop playback. To set the play-and-cache feature, configure the AVPCacheConfig class before you call the prepare method. The following sample code provides an example:
AVPCacheConfig *config = [[AVPCacheConfig alloc] init];
// Enable the play-and-cache feature.
config.enable = YES;
// Specify the maximum duration of a single cached file. Files whose duration exceeds the maximum limit are not cached.
config.maxDuration = 100;
// Specify the cache directory. Specify it as required by your application.
config.path = @"please use your cache path here";
// Specify the maximum size of the cache directory. When the total size of cached files in the cache directory exceeds the maximum limit, the earliest cached files are overwritten.
config.maxSizeMB = 200;
// Configure the cache settings for the player.
[self.player setCacheConfig:config];
You can use cached files only after you call the setCacheConfig method. After a video is cached, the cached file is used in the following scenarios:
  • If the loop playback feature is enabled by using the Loop(true) method, the cached file is used when the player replays the video.
  • After you cache a video and create a player to play the video, the new player plays the video by using the cached video file.
    Note For ID-based playback, information such as the audio or video ID is required to find cached files. An online request must be sent to obtain the required information that determines which cached files are needed for ID-based playback.
The following table describes the methods that can be used to obtain the path of a cached file.
Method Description Parameter Return value
(NSString *) getCacheFilePath:(NSString *)URL Queries the path of a cached file based on the video URL. To obtain the path, make sure that you have called the setCacheConfig method. URL The absolute path of the cached file.
(NSString *) getCacheFilePath:(NSString *)vid format:(NSString *)format definition:(NSString *)definition Queries the path of a cached file based on the audio or video ID.
  • vid: the video ID.
  • format: the video format.
  • definition: the video definition.
  • previewTime: the preview duration.
The absolute path of the cached file.
The following information describes the limits on the play-and-cache feature:
  • If the player plays UrlSource streams by using the HLS protocol based on the URL in an M3U8 playlist, the player does not cache the video during the playback. For other supported formats, the player caches videos during playback as configured.
  • If you use VidAuth or VidSts sources for playback, the player caches videos during playback as configured.
  • A video is considered cached after the player reads all video data. Caching fails if the stop method is called or a callback is invoked by the onError method before the player reads all video data.
  • Seeking to a position inside the cached video does not affect the caching result. Seeking to a position outside the cached video may cause a caching failure.
  • An encrypted video cannot be cached if the verification information in the security file for encryption verification does not match the application information.
  • The callback invoked by the onPlayerEventInfo method returns the caching result.
-(void)onPlayerEvent:(AliPlayer*)player eventWithString:(AVPEventWithString)eventWithString description:(NSString *)description {
    if (eventWithString == EVENT_PLAYER_CACHE_SUCCESS) {
        // Indicate that the caching succeeds. 
    }else if (eventWithString == EVENT_PLAYER_CACHE_ERROR) {
        // Indicate that the caching fails. 
    }
}

Configure video preload

ApsaraVideo Player SDK for iOS supports video preload, which is an upgrade of the play-and-cache 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 following information describes the limits on the video preload feature:
  • You can preload only one MP4, MP3, FLV, or HLS file at a time.
  • You can preload only one file that is played based on the URL. You cannot preload VidAuth or VidSts sources.
  1. Enable the video preload feature.
    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.
    /**
     * 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. A value of true indicates that the video preload feature is enabled. A value of false indicates that the video preload feature is disabled. Default value: false. 
     * @param maxBufferMemoryKB: the maximum size of memory that can be occupied by a single video file to be cached. If the size of the video file exceeds the maximum limit, the video file is not cached. Unit: KB. 
     * @param localCacheDir: 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: the retention period after which the cached file expires. Unit: minutes. By default, the retention period for each cached file is 30 days. A cached file is deleted after the specified period. 
     @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 point in 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 point in 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 can create an additional name for the CaheUrlHashHandle block by using the typedef keyword.
     */
    
    // 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 the loading 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.
  2. Obtain an AliMediaLoader instance.

    The AliMediaLoader instance is a singleton object. 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.

Query the download speed

ApsaraVideo Player SDK for iOS allows you to query the download speed of specified videos. The callback invoked by the onCurrentDownloadSpeed method returns the download speed. The following sample code provides an example:
- (void)onCurrentDownloadSpeed:(AliPlayer *)player speed:(int64_t)speed {
    int speed_ = speed;
}

Configure networks

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 settings

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 normal download mode are not encrypted by Alibaba Cloud and can be played by third-party players.
  • Secure download: Videos that are downloaded in 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, once for all. The following sample code provides an example:
    NSString *encrptyFilePath = [[NSBundle mainBundle] pathForResource:@"encryptedApp" ofType:@"dat"];
    [AliPrivateService initKey:encrptyFilePath];
    Notice 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 completion of preparing 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;
        // In this example, download the content of the first track.
        [downloader selectTrack:[tracks objectAtIndex:0].trackIndex];
    }
  5. Update the download source and start the download.
    VidSts or VidAuth sources 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 downloader 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 iOS 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 Encrypt videos for playback.

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

API reference