API reference

Updated at:

AliPlayerKit provides a rich set of APIs for controlling player behavior. This document details the main APIs for AliPlayerKit on iOS.

Note

AliPlayerKit includes detailed code comments for all core APIs, such as classes and methods. In Xcode, you can view these comments with Quick Help (Option + Click) to accelerate development. This also makes the APIs more friendly to AI programming tools.

Core class overview

Class name

Type

Responsibility

Lifecycle

AliPlayerKit

Global entry point

SDK initialization, global configuration, factory/preloader management

App lifecycle

AliPlayerView

View container

Player view management, slot system host

Same as UIView

AliPlayerController

Playback controller

Playback control, state management, strategy coordination

Manually released by `destroy`

AliPlayerModel

Data model

Encapsulates video source and playback parameters

Value object, no independent lifecycle

PlayerStateStore

State store

Read-only access to the player's current state

Follows the Controller

PlayerViewState

View state

Read-only access to UI layer state (fullscreen, control bar visibility)

Follows AliPlayerView

SlotManager

Slot manager

Slot registration, visibility control, element-level management

Follows AliPlayerView

StrategyManager

Strategy manager

Strategy registration, start, stop, and reset

Follows the Controller

StrategyRegistry

Strategy registry

Global default strategy factory management (singleton)

App lifecycle

LogHub

Log center

Log output and observer management (singleton)

App lifecycle

LocaleManager

Localization management

Multilingual support and Provider injection (singleton)

App lifecycle

AliPlayerKit (Global APIs)

AliPlayerKit is a global settings class for SDK initialization and configuration. You cannot instantiate this class. All its methods are class methods.

Initialization methods

Method

Parameter

Return value

Description

+ (void)setup

-

void

Initializes the SDK. `dispatch_once` ensures idempotency. Call this method when the app starts.

+ (BOOL)isInitialized

-

BOOL

Checks if the SDK is initialized.

+ (void)setOnGlobalInitBlock:

OnGlobalInitBlock block

void

Sets a custom configuration callback after global initialization is complete. Call this method before `setup`.

Status query and version information

Method

Parameter

Return value

Description

+ (NSString *)getPlayerKitVersion

-

NSString *

Gets the PlayerKit version number.

+ (NSString *)getSdkVersion

-

NSString *

Gets the underlying AliPlayer SDK version number.

Debug configurations

Method

Parameter

Return value

Description

+ (void)setDebugModeEnabled:

BOOL enabled

void

Enables or disables debug mode.

+ (BOOL)isDebugModeEnabled

-

BOOL

Checks if debug mode is enabled.

+ (void)setLogPanelEnabled:

BOOL enabled

void

Enables or disables the log panel. This feature is for debugging only.

+ (BOOL)isLogPanelEnabled

-

BOOL

Checks if the log panel is enabled.

Log configurations

Method

Parameter

Return value

Description

+ (void)setLogLevel:

LogLevel level

void

Sets the log level. Logs below this level are ignored. The default level is Info.

+ (LogLevel)logLevel

-

LogLevel

Gets the current log level.

+ (void)enableConsoleLog:

BOOL enable

void

Enables or disables console log output.

+ (BOOL)isConsoleLogEnabled

-

BOOL

Checks if console log output is enabled.

Player factory

Method

Parameter

Description

+ (void)setPlayerFactory:

id<PlayerFactory> factory

Sets a custom player factory. Pass `nil` to restore the default factory.

+ (id<PlayerFactory>)playerFactory

-

Gets the current player factory.

Preloading

Method

Parameter

Description

+ (void)setPreloader:

id<PlayerPreloader> preloader

Sets a custom preloader. Pass `nil` to restore the default preloader.

+ (id<PlayerPreloader>)preloader

-

Gets the current preloader.

Cache management

Method

Description

+ (void)clearCaches

Clears the local media cache of the player. Call this method after `setup`.

Internationalization

Method

Parameter

Description

+ (void)setLanguageCode:

NSString * languageCode

Manually specifies the language. Supported languages are `zh-Hans` and `en`.

+ (void)setLocaleProvider:

id<LocaleProvider> provider

Injects a custom localization provider. This has the highest priority.

+ (void)resetLocaleToSystemLanguage

-

Resets the language to follow the system language.

+ (NSString *)currentLanguageCode

-

Gets the current language code.

AliPlayerView (View APIs)

AliPlayerView is the player's view container. It manages controller binding and the slot system. The rendering view is created and managed by the internal PlayerSurfaceSlot.

Properties

Property

Type

Description

controller

AliPlayerController *

The associated player controller.

viewState

PlayerViewState *

The UI state that is retained across videos, such as fullscreen and control bar visibility.

slotManager

SlotManager *

The slot manager. You can pre-configure it before attaching.

fullscreenTransition

id<FullscreenTransition>

The implementation of the fullscreen transition animation. By default, an independent window rotation solution is used.

onBackPressed

void (^)(void)

The callback for the back button event.

Note

The `onBackPressed` callback is triggered in non-fullscreen mode. In fullscreen mode, the player automatically handles the back operation by exiting fullscreen. If this callback is not set, the player attempts a default navigation behavior, such as `pop` or `dismiss`, through the responder chain.

Controller binding

Method

Parameter

Description

- (void)attach:

AliPlayerController * controller

Binds the controller and activates the slot system.

- (void)detach

-

Detaches the controller without destroying it.

When to call:

  • attach:: The component is attached after the controller calls configure:. The slot system is then automatically built based on the slotManager configuration.

  • detach: Call this method when the view is about to be destroyed or when you need to bind a different controller.

AliPlayerController (Controller APIs)

AliPlayerController is the playback controller. It serves as a unified entry point for playback operations and encapsulates the logic for player creation, configuration, and control.

Properties

Property

Type

Description

playerModel

AliPlayerModel *

The current playback configuration model.

playerState

PlayerState

The current player state.

currentPosition

NSInteger

The current playback position in milliseconds.

duration

NSInteger

The total duration of the video in milliseconds.

stateStore

PlayerStateStore *

The state store.

strategyManager

StrategyManager *

The strategy manager.

lifecycleStrategy

id<PlayerLifecycleStrategy>

The current lifecycle strategy.

autoLifecycleManagement

BOOL

Specifies whether to automatically manage the foreground and background lifecycle. Default: YES.

controlsVisibilityLocked

BOOL

The lock flag for control bar visibility.

Note

When controlsVisibilityLocked is set to YES, the setControlsVisible:NO request is ignored, and the control bar remains visible. This is used for interactive scenarios, such as dragging the progress bar, where the control bar must always be displayed.

Constructors

Method

Parameter

Description

- (instancetype)init

-

Creates a controller with the default lifecycle strategy.

- (instancetype)initWithLifecycleStrategy:

id<PlayerLifecycleStrategy> strategy

Creates a controller with a custom lifecycle strategy.

Configuration and playback control

Method

Parameter

Description

- (void)configure:

AliPlayerModel * model

Configures the player and prepares for playback.

- (void)play

-

Starts or resumes playback.

- (void)pause

-

Pauses playback.

- (void)toggle

-

Toggles between play and pause.

- (void)replay

-

Restarts playback from the beginning.

- (void)stop

-

Stops playback.

- (void)seekTo:

NSInteger position (milliseconds)

Seeks to a specific position.

- (void)setRate:

float rate

Sets the playback speed. 1.0 is normal speed.

- (void)setLoop:

BOOL loop

Sets whether to loop playback.

- (void)setMuted:

BOOL muted

Sets whether to mute the audio.

- (void)setMirrorMode:

MirrorMode mirrorMode

Sets the mirror mode.

- (void)setScaleMode:

ScaleMode scaleMode

Sets the scaling mode.

- (void)setRotateMode:

RotateMode rotateMode

Sets the rotation angle.

- (void)selectTrack:

TrackQuality * quality

Switches the video quality.

- (void)snapshot

-

Takes a snapshot of the current video frame.

UI control

Method

Parameter

Return value

Description

- (void)setControlsVisible:

BOOL visible

void

Sets the visibility of the control bar.

- (void)setFullscreen:

BOOL fullscreen

void

Sets fullscreen mode with animation.

- (void)setFullscreen:animated:

BOOL fullscreen, BOOL animated

void

Sets fullscreen mode with optional animation.

Lifecycle methods

Method

Parameter

Return value

Description

- (void)onResume

-

void

Resumes playback. Call this when returning from the background.

- (void)onPause

-

void

Pauses playback. Call this when entering the background.

- (void)destroy

-

void

Destroys the player and releases all resources.

Notification delegates

Method

Parameter

Return value

Description

- (void)addNotificationDelegate:

id<PlayerNotificationDelegate> delegate

void

Adds a notification delegate. It is held by a weak reference.

- (void)removeNotificationDelegate:

id<PlayerNotificationDelegate> delegate

void

Removes a notification delegate.

AliPlayerModel (Model APIs)

AliPlayerModel is the player configuration model. It encapsulates all the configuration information required for playback.

Properties

Property

Type

Default value

Description

videoSource

VideoSource *

-

The video data source. This is required.

sceneType

SceneType

SceneTypeVOD

The playback scenario type.

coverUrl

NSString *

nil

The thumbnail URL.

videoTitle

NSString *

nil

The video title.

autoPlay

BOOL

YES

Specifies whether to enable autoplay.

traceId

NSString *

nil

The tracking identifier for playback quality monitoring.

startTime

NSInteger

0

The start position in milliseconds.

hardwareDecode

BOOL

YES

Specifies whether to enable hardware decoding.

allowScreenSleep

BOOL

NO

Specifies whether to allow the screen to sleep.

disableScreenshot

BOOL

NO

Specifies whether to disable screenshots and screen recording.

onPlayerConfigBlock

void (^)(id<MediaPlayer>)

nil

The instance-level custom configuration callback.

Creation methods

Method

Parameter

Return value

Description

- (instancetype)initWithVideoSource:

VideoSource * videoSource

AliPlayerModel *

Creates a model from a video source. This is the designated initializer.

Notification system

AliPlayerKit uses a Dispatcher + Delegate pattern for event communication between components. Each AliPlayerController has an independent Dispatcher instance, which prevents events from different player instances from interfering with each other. All callbacks are dispatched on the main thread.

PlayerNotificationDelegate (Player notification delegate)

A protocol for player state change callbacks. All methods are @optional.

Playback state

Method

Parameter

Description

- playerDidChangeState:

PlayerState state

The player state changes.

- playerDidPreparedWithDuration:

NSInteger duration (milliseconds)

The player is prepared and ready for playback.

- playerDidRenderFirstFrame

-

The first frame is rendered.

- playerDidCompletion

-

Playback is complete.

Playback progress

Method

Parameter

Description

- playerDidUpdateCurrentPosition:duration:bufferedPosition:

position, duration, bufferedPosition (milliseconds)

Reports the playback progress at regular intervals.

Errors and snapshots

Method

Parameter

Description

- playerDidEncounterError:

NSError * error

A playback error occurred.

- playerDidCompleteSnapshot:

UIImage *

A snapshot is taken.

Video information

Method

Parameter

Description

- playerDidChangeVideoWidth:height:

NSInteger width, height

The video dimensions change.

UI state

Method

Parameter

Description

- playerDidChangeFullscreen:

BOOL isFullscreen

The fullscreen state changes.

- playerDidChangeControlsVisible:

BOOL visible

The visibility of the control bar changes.

Loading state

Method

Parameter

Description

- playerDidLoadingBegin

-

Buffering starts.

- playerDidLoadingEnd

-

Buffering ends.

- playerDidUpdateLoadingProgress:

float progress (0-100)

The buffering progress is updated.

Display mode

Method

Parameter

Description

- playerDidChangeMirrorMode:

MirrorMode mirrorMode

The mirror mode changes.

- playerDidChangeScaleMode:

ScaleMode scaleMode

The scaling mode changes.

- playerDidChangeRotateMode:

RotateMode rotateMode

The rotation mode changes.

Track

Method

Parameter

Description

- playerDidTrackReady:

NSArray<TrackQuality *> * tracks

Information about available tracks is ready.

- playerDidTrackChanged:

TrackQuality * quality

The track is switched.

GestureNotificationDelegate (Gesture notification delegate)

A protocol for gesture interaction event callbacks. All methods are @optional. Events are multicast by GestureNotificationDispatcher.

Single tap

Method

Parameter

Description

- gestureDidSingleTap

-

A single tap gesture is triggered. This is typically used to toggle the visibility of the control bar.

Long press (playback speed)

Method

Parameter

Description

- gestureDidBeginLongPress

-

A long press begins. This activates fast-forward playback.

- gestureDidEndLongPress

-

A long press ends. This restores normal playback speed.

Brightness (left vertical drag)

Method

Parameter

Description

- gestureDidUpdateBrightnessWithPercent:

CGFloat currentPercent (0.0 to 1.0)

The brightness is being adjusted.

- gestureDidEndBrightnessAdjust

-

The brightness adjustment ends.

Volume (right vertical drag)

Method

Parameter

Description

- gestureDidUpdateVolumeWithPercent:

CGFloat currentPercent (0.0 to 1.0)

The volume is being adjusted.

- gestureDidEndVolumeAdjust

-

The volume adjustment ends.

SlotActionNotificationDelegate (Slot action notification delegate)

A notification protocol for action events between slots. It is used to decouple direct method calls between slots. All methods are @optional and are dispatched asynchronously to the main thread.

Method

Parameter

Description

- slotDidRequestToggleSettingMenu

-

Requests to toggle the visibility of the settings menu. This is usually triggered by `TopBarSlot`.

- slotDidRequestShowSpeedPanel

-

Requests to show the playback speed selection panel. This is usually triggered by `BottomBarSlot`.

- slotDidRequestShowQualityPanel

-

Requests to show the video quality selection panel. This is usually triggered by `BottomBarSlot`.

Player protocols

AliPlayerKit defines the core capabilities and behavioral constraints of the player through protocols.

MediaPlayer (Player protocol)

This protocol defines the core operation interface for the player. You can create an instance using PlayerFactory.

Properties

Property

Type

Description

playerId

NSString *

The unique identifier of the player.

state

PlayerState

The current playback state.

currentPosition

NSInteger

The current position in milliseconds.

duration

NSInteger

The total duration in milliseconds.

speed

float

The current playback speed.

loop

BOOL

Specifies whether to loop playback.

muted

BOOL

Specifies whether the audio is muted.

mirrorMode

MirrorMode

The current mirror mode.

scaleMode

ScaleMode

The current scaling mode.

rotateMode

RotateMode

The current rotation angle.

stateStore

PlayerStateStore *

The state store.

Playback control

Method

Parameter

Description

- setDataSource:

AliPlayerModel * model

Sets the video data source.

- prepare

-

Asynchronously prepares player resources.

- start

-

Starts playback.

- pause

-

Pauses playback.

- toggle

-

Toggles between play and pause.

- replay

-

Restarts playback from the beginning.

- seekTo:

NSInteger position (milliseconds)

Seeks to a specific position.

- stop

-

Stop.

- destroy

-

Destroys the player and releases resources.

Playback settings

Method

Parameter

Description

- setSpeed:

float speed

Sets the playback speed (0.5 to 2.0).

- setLoop:

BOOL loop

Sets loop playback.

- setMuted:

BOOL muted

Mutes the audio.

- setMirrorMode:

MirrorMode mode

Sets the mirror mode.

- setScaleMode:

ScaleMode mode

Sets the scaling mode.

- setRotateMode:

RotateMode mode

Sets the rotation angle.

- selectTrack:

TrackQuality * quality

Switches the video quality.

- snapshot

-

Takes a snapshot of the current frame.

PlayerLifecycleStrategy (Lifecycle strategy protocol)

This protocol defines the acquisition and recycling behavior of player instances.

Methods

Method

Parameter

Return value

Description

- setupWithFactory:

id<PlayerFactory> factory

void

Injects the player factory. This must be called first.

- acquirePlayer

-

id<MediaPlayer>

Gets a player instance.

- recyclePlayer:force:

player, BOOL force

void

Recycles a player instance.

- clear

-

void

Releases all cached instances.

- preloadWithCount: (@optional)

NSInteger count

void

Preloads a specified number of instances into the pool.

- acquirePlayerWithUniqueId: (@optional)

NSString * uniqueId

id<MediaPlayer>

Gets a player by ID. This is specific to the IdScoped strategy.

- recyclePlayer:uniqueId:force: (@optional)

player, uniqueId, force

void

Recycles a player by ID. This is specific to the IdScoped strategy.

Built-in strategy implementations

Strategy class

Behavior

Scenarios

DefaultLifecycleStrategy

Creates a new instance each time and destroys it upon recycling.

Normal video playback.

SingletonLifecycleStrategy

Global unique instance (sharedInstance singleton)

List playback, memory-sensitive scenarios.

ReusePoolLifecycleStrategy

LIFO reuse pool.

Short video lists.

IdScopedPoolLifecycleStrategy

ID binding + LRU eviction.

Video preloading.

FullscreenTransition (Fullscreen transition protocol)

This protocol defines the transition behavior for entering and exiting fullscreen mode.

Method / Property

Parameter

Description

- enterFullscreenWithPlayerView:animated:completion:

playerView, animated, completion

Enters fullscreen.

- exitFullscreenWithPlayerView:animated:completion:

playerView, animated, completion

Exits fullscreen.

isInFullscreen (readonly)

-

Specifies whether the player is in fullscreen mode.

The default implementation DefaultFullscreenTransition uses an independent Window rotation solution. You can inject a custom implementation via playerView.fullscreenTransition.

Slot system

The slot system provides a composable and replaceable UI layer management mechanism.

SlotProtocol (Slot protocol)

You can define the slot lifecycle callback.

Method

Parameter

Description

- onAttach:

id<SlotHost> host

The slot is attached to the host.

- onDetach

-

The slot is detached from the host.

- onBindData:

AliPlayerModel * model

Playback data is bound.

- onUnbindData

-

Playback data is unbound.

BaseSlot (Base slot class)

The abstract base class for all built-in slots (a UIView subclass) implements the SlotProtocol protocol and provides common capabilities.

Properties

Property

Type

Description

host

id<SlotHost>

The host to which the slot is attached.

slotType

SlotType

The slot type identifier. It is injected by SlotHostLayout.

safeAreaEdges

SlotSafeAreaEdge

The safe area edges to avoid. Default: All.

deferContentCreation

BOOL

The switch for deferred content creation.

contentReady

BOOL

Specifies whether the content is ready.

touchPassthrough

BOOL

The switch for touch passthrough. Default: YES.

Methods

Method

Type

Description

- setupContentView

-

Subclasses override this method to add custom UI elements.

- show / - hide

-

Shows or hides the slot.

- showWithAnimation: / - hideWithAnimation:

BOOL animated

Shows or hides the slot with an animation.

- isShowing

-

Indicates whether it is currently visible.

- dismiss

-

Correctly removes the slot through the host.

- onRegisterElements

-

Subclasses override this method to declare the bitmask of default visible elements.

- isElementVisible:

NSUInteger element

Queries the final visibility of a specific element.

- currentSceneType

-

Safely reads the current scene type.

- ensureContentReady

-

Ensures that deferred content is ready.

SlotManager (Slot manager)

The SlotManager is the unified management entry point for the slot system. You can retrieve it using AliPlayerView.slotManager.

Registration methods

Method

Parameter

Description

- registerSlotType:provider:

type, SlotProvider block

Registers or replaces a slot provider.

- unregisterSlotType:

SlotType type

Unregisters a slot provider.

- isRegistered:

SlotType type

Check if it is registered.

- registerCustomSlotType:provider:

CustomSlotType * type, provider

Registers a custom slot.

- unregisterCustomSlotType:

CustomSlotType * type

Unregisters a custom slot.

Slot visibility

Method

Parameter

Description

- hideSlot:

SlotType type

Hides an entire slot.

- showSlot:

SlotType type

Shows a hidden slot.

- isSlotHidden:

SlotType type

Checks if a slot is hidden.

Element-level visibility

Method

Parameter

Description

- hideElements:forSlot:

NSUInteger mask, SlotType type

Hides specific elements within a slot using a bitmask.

- showElements:forSlot:

NSUInteger mask, SlotType type

Shows previously hidden elements.

- setHiddenElementMask:forSlot:

NSUInteger mask, SlotType type

Replaces the hidden element mask. This overwrites the existing mask.

- setAllHiddenElementMasks:

NSDictionary * config

Sets all hidden elements in a batch.

- clearAllElementMasks

-

Clears all element visibility configurations.

Runtime access

Method

Parameter

Return value

Description

- slotViewForType:

SlotType type

UIView<SlotProtocol> *

Gets the attached slot view.

- rebuildSlots

-

void

Rebuilds all slots.

- clearAll

-

void

Resets to the initial state.

SlotType (Slot type constants)

Constant

Value

Description

SlotTypePlayerSurface

10

Player rendering view layer (bottommost).

SlotTypeGestureControl

20

Gesture recognition and control layer.

SlotTypeLandscapeHint

30

Landscape hint layer.

SlotTypeCover

40

Video thumbnail layer.

SlotTypeCenterDisplay

50

Center display layer (playback speed, brightness, volume).

SlotTypePlayState

60

Playback state indicator layer (loading, error, complete).

SlotTypeLogPanel

70

Log panel layer.

SlotTypeTopBar

80

Top navigation bar layer.

SlotTypeBottomBar

90

Bottom control bar layer.

SlotTypeSettingMenu

100

Settings menu layer.

SlotTypeOptionPanel

110

Option panel layer (playback speed, quality).

CustomSlotType (Custom slot type)

This is used to insert custom slots between built-in slots. The built-in SlotType enumeration values are arranged at intervals of 10 (10, 20, ..., 110), and CustomSlotType uses the order field to specify the insertion position.

Property / Method

Description

key

A unique identifier used for registration, lookup, and equality checks.

order

The sort value that determines the slot's position on the Z-axis. A smaller value means it is placed lower.

+ typeWithKey:order:

Creates a custom slot type instance.

// Insert a custom slot between TopBar (80) and BottomBar (90)
CustomSlotType *type = [CustomSlotType typeWithKey:@"myCustomSlot" order:85];
[playerView.slotManager registerCustomSlotType:type provider:^UIView<SlotProtocol> *(UIView *parentView) {
    return [[MyCustomSlotView alloc] initWithFrame:parentView.bounds];
}];

SlotElements (Slot element bitmasks)

You can use the hideElements:forSlot: and showElements:forSlot: methods of SlotManager to implement fine-grained visibility control for individual UI elements in a slot.

Top Bar Element (TopBarElement)

Constant

Bit

Description

TopBarElementBack

1 << 0

Back button.

TopBarElementTitle

1 << 1

Title text.

TopBarElementDownload

1 << 2

Download button.

TopBarElementSnapshot

1 << 3

Snapshot button.

TopBarElementSettings

1 << 4

Settings button.

BottomBarElement (Bottom bar elements)

Constant

Bit

Description

BottomBarElementPlay

1 << 0

Play/Pause button.

BottomBarElementProgress

1 << 1

Progress bar.

BottomBarElementRefresh

1 << 2

Refresh button.

BottomBarElementSpeed

1 << 3

Playback speed button. Visible in landscape layout only.

SettingMenuElement (Settings menu elements)

Constant

Bit

Description

SettingMenuElementSpeed

1 << 0

Playback speed option.

SettingMenuElementTrackInfo

1 << 1

Quality information.

SettingMenuElementLoop

1 << 2

Loop playback.

SettingMenuElementMute

1 << 3

Mute.

SettingMenuElementMirrorMode

1 << 4

Mirror mode.

SettingMenuElementRotateMode

1 << 5

Rotation mode.

SettingMenuElementScaleMode

1 << 6

Scaling mode.

SettingMenuElementSubtitle

1 << 7

Caption.

CenterDisplayElement (Center display layer elements)

Constant

Bit

Description

CenterDisplayElementVolume

1 << 0

Volume indicator.

CenterDisplayElementBrightness

1 << 1

Brightness indicator.

CenterDisplayElementSpeed

1 << 2

Playback speed indicator.

GestureElement (Gesture control elements)

Note

These constants control the enabling and disabling of gesture interactions, not the visibility of UI elements. When a gesture bit is set to hidden, the corresponding gesture is disabled.

Constant

Bit

Description

GestureElementSingleTap

1 << 0

Single tap gesture.

GestureElementDoubleTap

1 << 1

Double-tap gesture.

GestureElementLongPress

1 << 2

Long press gesture.

GestureElementHorizontalDrag

1 << 3

Horizontal drag (progress).

GestureElementLeftVerticalDrag

1 << 4

Left vertical drag (brightness).

GestureElementRightVerticalDrag

1 << 5

Right vertical drag (volume).

PlayStateElement (Playback state layer elements)

Constant

Bit

Description

PlayStateElementErrorMessage

1 << 0

Error message.

PlayStateElementLoadingMessage

1 << 1

Loading message.

State store

PlayerStateStore

PlayerStateStore holds a read-only snapshot of the current playback state. You can retrieve it through AliPlayerController.stateStore.

Property

Type

Default value

Description

playState

PlayerState

PlayerStateIdle

The current playback state.

duration

NSInteger

0

The total duration in milliseconds.

currentPosition

NSInteger

0

The current position in milliseconds.

bufferedPosition

NSInteger

0

The buffered position in milliseconds.

speed

float

1.0

The current playback speed.

loop

BOOL

NO

Specifies whether to loop playback.

muted

BOOL

NO

Specifies whether the audio is muted.

mirrorMode

MirrorMode

MirrorModeNone

The mirror mode.

scaleMode

ScaleMode

ScaleModeCenterCrop

The scaling mode.

rotateMode

RotateMode

RotateModeDegree0

The rotation angle.

videoWidth

NSInteger

0

The original width of the video.

videoHeight

NSInteger

0

The original height of the video.

trackQualityList

NSArray<TrackQuality *> *

nil

The list of available video qualities.

selectedTrackQuality

TrackQuality *

nil

The currently selected video quality.

PlayerViewState

PlayerViewState holds persistent state related to the UI layer. You can retrieve it through AliPlayerView.viewState. This state is retained across video switches, and state updates include automatic deduplication.

Property / Method

Type

Default value

Description

fullscreen

BOOL (readonly)

NO

Specifies whether the player is in fullscreen mode.

controlsVisible

BOOL (readonly)

NO

Specifies whether the control bar is visible.

- reset

-

-

Resets all states to their default values.

- updateFullscreen:

BOOL fullscreen

-

Updates the fullscreen state.

- updateControlsVisible:

BOOL controlsVisible

-

Updates the visibility of the control bar.

Video source

VideoSource (Video source model)

Property

Type

Description

sourceType

VideoSourceType

The video source type.

uniqueId

NSString *

The unique identifier. Returns `vid` for VidAuth/VidSts, and `url` for URL.

url

NSString *

The video URL. Valid for the URL type.

vid

NSString *

The video ID. Valid for VidAuth/VidSts.

playAuth

NSString *

The playback credential. Valid for VidAuth.

accessKeyId

NSString *

The STS AccessKeyId.

accessKeySecret

NSString *

The STS AccessKeySecret.

securityToken

NSString *

The STS SecurityToken.

region

NSString *

The region ID.

Factory methods

Method

Parameter

Return value

Description

+ vidAuthSourceWithVid:playAuth:

vid, playAuth

VideoSource *

Creates a VidAuth video source. This is recommended.

+ vidStsSourceWithVid:accessKeyId:accessKeySecret:securityToken:region:

vid, keyId, secret, token, region

VideoSource *

Creates a VidSts video source.

+ urlSourceWithUrl:

url

VideoSource *

Creates a URL video source.

- (BOOL)isValid

-

BOOL

Validates the configuration.

VideoSourceType (Video source type)

Constant

Value

Description

VideoSourceTypeVidAuth

0

VID + PlayAuth playback credential. This is recommended.

VideoSourceTypeVidSts

1

VID + STS temporary credential.

VideoSourceTypeUrl

2

Direct URL playback.

Strategy system

The strategy system provides a pluggable mechanism for extending playback behavior. Strategy names must be globally unique.

StrategyProtocol (Strategy protocol)

This protocol defines the lifecycle contract for a strategy. Strategy names must be globally unique.

Method

Parameter

Description

- strategyName (@required)

-

The unique identifier name of the strategy.

- strategyDidStart: (@required)

StrategyContext * context

The strategy starts and binds to the player context.

- strategyDidStop (@required)

-

The strategy stops and unbinds from the context.

- strategyDidReset: (@required)

StrategyContext * context

The strategy is reset. This is called when the video source is switched.

StrategyContext (Strategy context)

The read-only player environment context is provided to the strategy and is created and passed in by StrategyManager when the strategy starts.

Property

Type

Description

controller

AliPlayerController *

The associated player controller.

playerModel

AliPlayerModel *

The current playback configuration model.

stateStore

PlayerStateStore *

The player state store.

Important

This object is no longer valid after strategyDidStop, and you should not continue to use it.

BaseStrategy (Base strategy class)

An abstract base class for strategies that implements StrategyProtocol and PlayerNotificationDelegate to automatically handle the subscription and unsubscription of player events.

Property / Method

Description

context (readonly, nullable)

The current strategy context. It is valid only between `start` and `stop`.

- resetInternalState

A hook method for subclasses to reset their internal state, such as clearing counters or timers.

Lifecycle flow: strategyDidStart: → Save context → Register notification agent → strategyDidReset: → Update context → Call resetInternalState → strategyDidStop → Unregister notification agent → Clear context.

Note

Child classes must override the strategyName method. If you override strategyDidStart:, strategyDidStop, or strategyDidReset:, you must call super.

StrategyManager (Strategy manager)

Each AliPlayerController has a StrategyManager instance. Strategies are executed in the order of registration, and the lifecycle calls for each strategy are isolated using @try/@catch.

Methods

Method

Parameter

Description

- registerStrategy:

id<StrategyProtocol> strategy

Registers a strategy. If a strategy with the same name exists, it is stopped and replaced.

- unregisterStrategyWithName:

NSString * name

Unregisters a strategy by name.

- strategyWithName:

NSString * name

Finds a strategy by name.

- startWithController:playerModel:

controller, playerModel

Starts all registered strategies.

- resetWithPlayerModel:

AliPlayerModel * playerModel

Resets all strategies. This is used when the video source is switched.

- stop

-

Stops all strategies.

- destroy

-

Stops and removes all strategies.

Properties

Property

Type

Description

strategyCount

NSUInteger

The number of currently registered strategies.

started

BOOL

Indicates whether the manager is running.

StrategyRegistry (Global strategy registry)

The global strategy registry is a singleton that maintains a group of strategy factory Blocks. Whenever a new AliPlayerController is created, all registered factories are instantiated and injected into the controller's StrategyManager using applyToManager:.

Method

Parameter

Description

+ sharedRegistry

-

Gets the global registry singleton.

- addGlobalStrategyFactory:

StrategyFactory factory

Adds a global strategy factory.

- clearGlobalStrategies

-

Removes all global strategy factories, including built-in ones.

- applyToManager:

StrategyManager * manager

Instantiates all global strategies and registers them with the specified manager.

- resetToDefault

-

Restores the default built-in strategy configuration.

Note

Built-in strategies (FirstFrameStrategy, StutterDetectStrategy, and TrafficProtectionStrategy) are automatically registered on first access.

Built-in strategies

FirstFrameStrategy (Time-to-first-frame monitoring)

Measures the time from when the player starts preparing to when the first frame is rendered. It is divided into a preparing phase (Preparing to Prepared) and a rendering phase (Prepared to FirstFrameRendered).

Property

Type

Description

delegate

id<FirstFrameStrategyDelegate> (weak)

Callback delegate

FirstFrameStrategyDelegate callback:

Method

Parameter

Description

- firstFrameStrategy:didRenderFirstFrameWithPrepareTime:renderTime:totalTime:

strategy, prepareTimeMs, renderTimeMs, totalTimeMs

The first frame is rendered.

StutterDetectStrategy (Stuttering detection)

Detects stuttering by listening for Loading events. Loading before the first frame is rendered is not counted.

Property

Type

Description

stutterCount

NSInteger

The number of stutters in the current session.

totalStutterDurationMs

NSInteger

The total duration of stuttering in the current session, in milliseconds.

stutterThresholdMs

NSInteger

The stuttering threshold in milliseconds. Default: 0.

delegate

id<StutterDetectStrategyDelegate>

The callback delegate.

- initWithThreshold:

NSInteger

Creates a stutter detection strategy with a specified threshold.

StutterDetectStrategyDelegate callback:

Method

Parameter

Description

- stutterDetectStrategy:didStutter:

strategy, durationMs

A stutter is detected.

- stutterDetectStrategy:didAnalyzeSession:validPlayDuration:totalStutterDuration:stutterCount:

strategy, stayDurationMs, validPlayDurationMs, totalStutterDurationMs, stutterCount

The playback session analysis is complete.

TrafficProtectionStrategy (Traffic protection)

Monitors network status changes and detects playback on cellular networks. It only performs detection and logging and does not automatically pause playback.

Property

Type

Description

isOnCellularNetwork

BOOL

Specifies whether the device is currently on a cellular network.

delegate

id<TrafficProtectionStrategyDelegate>

The callback delegate.

TrafficProtectionStrategyDelegate callback:

Method

Parameter

Description

- trafficProtectionStrategyDidDetectCellularNetwork:

strategy

Playback on a cellular network is detected.

- trafficProtectionStrategyDidDetectWifiNetwork:

strategy

The network is switched back to Wi-Fi.

Log system

The log system provides a unified mechanism for log output and observer registration.

LogHub (Log center)

The log management center (singleton) that unifies log output and observer registration. It uses a hybrid threading model: console output is performed synchronously on the calling thread, while observer notifications are dispatched asynchronously to a background serial queue.

Properties

Property

Type

Default value

Description

logEnabled

BOOL

YES

Specifies whether to enable log output.

logLevel

LogLevel

LogLevelInfo

The minimum log output level.

consoleLogEnabled

BOOL

YES

Specifies whether to enable console (NSLog) output.

Observer management

Method

Parameter

Description

+ sharedHub

-

Gets the shared LogHub singleton.

- addObserver:

id<LogObserver> observer

Adds a log observer. It is held by a strong reference.

- removeObserver:

id<LogObserver> observer

Removes a log observer.

Log output

Method

Parameter

Description

- v:msg:

tag, message

Outputs a Verbose level log.

- d:msg:

tag, message

Outputs a Debug level log.

- i:msg:

tag, message

Outputs an Info level log.

- w:msg:

tag, message

Outputs a Warn level log.

- e:msg:

tag, message

Outputs an Error level log.

- e:msg:error:

tag, message, error (nullable)

Outputs an Error level log with an associated error object.

- log:tag:msg:

level, tag, message

Outputs a log at the specified level.

Utility methods

Method

Parameter

Return value

Description

+ levelToString:

LogLevel level

NSString *

Converts a log level to an abbreviated string (V/D/I/W/E/N).

+ stringToLevel:

NSString * levelName

LogLevel

Converts a level name string back to an enumeration value.

LogObserver (Log observer protocol)

Implement this protocol to receive all log output callbacks for custom log handling, such as writing to a file or reporting to a server.

Method

Parameter

Description

- onLog: (@required)

LogInfo * logInfo

The log output callback. It is executed on a subthread.

LogInfo (Log information model)

The data model for a single log entry.

Property

Type

Description

level

LogLevel

The log level.

tag

NSString *

The log tag.

message

NSString *

The log message.

timestamp

NSDate *

The timestamp.

threadName

NSString *

The thread name.

fileName

NSString *

The source file name.

line

NSInteger

The source code line number.

error

NSError *

The associated error object.

- formattedString

-

Gets the formatted log string.

Preloading system

The preloading system encapsulates the global preloading feature of the player SDK. You can retrieve it through `[AliPlayerKit preloader]`.

PlayerPreloader (Preloading protocol)

This protocol encapsulates the global preloading feature of the player SDK. You can retrieve it through [AliPlayerKit preloader].

Method

Parameter

Return value

Description

- addTask:delegate:

task, delegate

NSString * (task ID)

Adds a preloading task.

- cancelTask:

NSString * taskId

void

Cancels a specific task.

- pauseTask:

NSString * taskId

void

Pauses a specific task.

- resumeTask:

NSString * taskId

void

Resumes a specific task.

- cancelAll

-

void

Cancels all preloading tasks.

PlayerPreloadTask (Preloading task)

Property

Type

Description

videoSource

VideoSource *

The video data source.

preloadConfig

PlayerPreloadConfig *

The preloading configuration.

- initWithVideoSource:preloadConfig:

videoSource, preloadConfig

Creates a preloading task.

PlayerPreloadConfig (Preloading configuration)

Property

Type

Default value

Description

preloadDuration

NSInteger

3000

The preloading duration in milliseconds.

loadStartPositionMs

NSInteger

0

The preloading start position in milliseconds.

defaultQuality

NSString *

@"AUTO"

The default quality identifier.

defaultResolution

NSInteger

0

The default resolution. 0 means no limit.

defaultBandWidth

NSInteger

0

The default bitrate. 0 means no limit.

networkTimeout

NSInteger

0

The network timeout in milliseconds. 0 uses the SDK default.

networkRetryCount

NSInteger

0

The number of network retries. 0 uses the SDK default.

referrer

NSString * (nullable)

nil

Referrer information.

customHeaders

NSArray<NSString *> *

nil

Custom request headers.

Creation methods

Method

Parameter

Description

- init

-

Creates a configuration with default settings.

- initWithPreloadDuration:defaultQuality:

preloadDuration, defaultQuality

Creates a configuration with a specified preloading duration and default quality.

PreloadDelegate (Preloading delegate)

This protocol receives status events for preloading tasks. All methods are @required.

Note

Callbacks may be triggered on a background thread. You must dispatch them to the main thread for processing.

Method

Parameter

Description

- preloadTaskDidComplete:source:

taskId, source

The preloading task is complete.

- preloadTaskDidFail:source:error:

taskId, source, error

The preloading task failed.

- preloadTaskDidCancel:source:

taskId, source

The preloading task was canceled.

Localization system

The localization system manages multilingual support for PlayerKit. It supports three modes: following the system language automatically, specifying a language manually, or using custom providers.

LocaleManager (Localization manager)

The localization manager (singleton) that manages multilingual support for PlayerKit.

Resolution Chain: Custom Provider (if injected) → Bundle for the manually specified language (Manual mode) → SDK Bundle that follows the system language → Returns the key itself as a fallback.

Properties

Property

Type

Description

currentLanguageCode

NSString *

The current language code.

localeMode

LocaleMode

The current language mode.

localeProvider

id<LocaleProvider>

The currently injected custom provider.

Methods

Method

Parameter

Description

+ sharedManager

-

Gets the singleton instance.

- setLanguageCode:

NSString * languageCode

Sets the language manually. This switches to Manual mode.

- setLocaleProvider:

id<LocaleProvider> provider

Injects a custom provider. It is held by a weak reference. Pass `nil` to remove it.

- resetToSystemLanguage

-

Resets the language to follow the system language.

- localizedStringForKey:

NSString * key

Queries a localized string.

LocaleMode (Language mode)

Constant

Value

Description

LocaleModeSystem

0

Follows the system language. This is the default.

LocaleModeManual

1

Manually specifies the language code.

LocaleProvider (Localization provider protocol)

The host app can implement this protocol to provide custom translations for PlayerKit.

Method

Parameter

Return value

Description

- localizedStringForKey: (@optional)

NSString * key

NSString * (nullable)

Returns a localized string for a specified key. Returning `nil` means the SDK will handle it as a fallback.

LocaleDidChangeNotification (Language change notification)

When the language mode or language code changes, a LocaleDidChangeNotification notification is sent on the main thread. The userInfo dictionary contains the new language code under the LocaleLanguageCodeKey key.

Key enumerations and constants

Core enumeration types used in AliPlayerKit.

PlayerState (Player state)

Constant

Value

Description

PlayerStateIdle

0

Idle. Initialized but no resource is loaded.

PlayerStatePreparing

1

Preparing. Asynchronously loading resources.

PlayerStatePrepared

2

Prepared. Ready to start playback.

PlayerStatePlaying

3

Playing.

PlayerStatePaused

4

Paused.

PlayerStateCompleted

5

Completed.

PlayerStateStopped

6

Stopped.

PlayerStateError

7

Error state.

SceneType (Scenario type)

Constant

Value

Description

SceneTypeVOD

0

Video-on-demand scenario

SceneTypeLive

1

Live streaming scenario.

SceneTypeVideoList

2

Video list or short video stream scenario.

SceneTypeRestricted

3

Restricted playback scenario.

SceneTypeMinimal

4

Minimalist playback page scenario.

ScaleMode (Scaling mode)

Constant

Value

Description

ScaleModeFitXY

0

Stretches to fill the view.

ScaleModeFitCenter

1

Scales proportionally to fit the view. This may leave black bars.

ScaleModeCenterCrop

2

Scales proportionally and crops to fill.

MirrorMode (Mirror mode)

Constant

Value

Description

MirrorModeNone

0

No mirroring.

MirrorModeHorizontal

1

Horizontal mirroring.

MirrorModeVertical

2

Vertical mirroring.

RotateMode (Rotation mode)

Constant

Value

Description

RotateModeDegree0

0

0 degrees.

RotateModeDegree90

90

90 degrees.

RotateModeDegree180

180

180 degrees.

RotateModeDegree270

270

270 degrees.

LogLevel (Log level)

Constant

Value

Description

LogLevelVerbose

0

The most detailed debug information.

LogLevelDebug

1

Debug level.

LogLevelInfo

2

Info level. This is the default.

LogLevelWarn

3

Warning level.

LogLevelError

4

Error level.

LogLevelNone

100

Disables all logs.

TrackType (Track type)

Constant

Value

Description

TrackTypeUnknown

0

Unknown.

TrackTypeVideo

1

Video track.

TrackTypeAudio

2

Audio track.

TrackTypeSubtitle

3

Caption track.

TrackTypeVOD

4

VOD track.