Notification system
The Notification System is the inter-component communication infrastructure of AliPlayerKit. It uses a Notification Dispatcher and Delegate protocol pattern to dispatch information, such as internal player state changes, gesture interactions, and slot operations, to all observers. This pattern completely decouples the player controller, UI slots, and policies.
Concepts
What is the notification system?
The Notification System is the multicast notification dispatch mechanism within PlayerKit. Each Dispatcher manages a group of weakly referenced observers. It defines callback interfaces through a corresponding Delegate protocol. Observers only need to implement the methods they are interested in to receive notifications.
Core features:
Multicast dispatch: Each Dispatcher supports registering multiple observers. Notifications are broadcast to all registered observers.
Weak reference management: Observers are stored as weak references using
NSHashTable. They are automatically cleaned up after the object is released.Instance-level isolation: Each
AliPlayerControllerholds an independent Dispatcher instance. Notifications from different player instances do not interfere with each other.Exception isolation: Each observer call is wrapped in a
@try/@catchblock. An exception in one observer does not affect other observers.
Problems solved
Problem | Solution with the notification system |
High coupling due to direct dependencies between components | Communication through Delegate protocols removes direct references between components. |
Disordered notifications with multiple player instances | Each controller holds an independent Dispatcher instance, providing natural isolation. |
Mixing of UI and business logic | Downward dispatch of state notifications separates responsibilities. |
Subscriber leaks | Weak references managed by |
Core architecture
The PlayerKit notification system consists of three groups of Dispatcher and Delegate protocols:
┌───────────────────────────────────────────────────────────────────┐
│ AliPlayerController │
│ │
│ ┌─────────────────────────────────┐ │
│ │ PlayerNotificationDispatcher │──▶ PlayerNotificationDelegate │
│ └─────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────┐ │
│ │ GestureNotificationDispatcher │──▶ GestureNotificationDelegate│
│ └─────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────┐ │
│ │ SlotActionNotificationDispatcher│──▶ SlotActionNotificationDele.│
│ └─────────────────────────────────┘ │
└───────────────────────────────────────────────────────────────────┘
│ │ │
▼ ▼ ▼
[Observer A] [Observer B] [Observer C]
(Slot/Strategy) (Slot/Strategy) (Slot/Strategy)Dispatcher | Delegate protocol | Responsibility | Access method |
|
| Core player notifications: state, progress, errors, snapshots, full screen, control bar, loading, display mode, and tracks. | Through the controller's |
|
| Gesture notifications: single tap, long press, brightness slide, and volume slide. | Injected into built-in slots by |
|
| Slot action notifications: settings menu, playback speed panel, and quality panel. | Injected into built-in slots by |
AliPlayerController only exposes the registration entry point for PlayerNotificationDelegate (addNotificationDelegate: / removeNotificationDelegate:). GestureNotificationDispatcher and SlotActionNotificationDispatcher are part of the internal communication mechanism for slots. They are automatically injected by SlotHostLayout during slot construction and are not exposed externally.
The three Dispatcher groups
PlayerNotificationDispatcher
The core player notification dispatcher. It is responsible for dispatching information, such as player state changes, progress updates, and error notifications, to all observers.
Core properties and methods:
Interface | Description |
| The unique identifier of the player that is the source of the notification ( |
| Adds an observer that conforms to |
| Removes the specified observer (has no effect if not registered). |
| Removes all observers. |
| Dispatches a notification block to all observers. |
| Dispatches only to observers that implement the specified selector (selector filtering). |
| Returns the number of current active observers. |
Convenience dispatch methods (called internally by the controller):
Method | Trigger scenario |
| Player state changes. |
| Preparation is complete. |
| First frame is rendered. |
| Playback is complete. |
| Progress is updated. |
| An error occurs. |
| Snapshot is complete. |
| Video dimensions change. |
| Full-screen state changes. |
| Buffering starts. |
| Buffering ends. |
| Buffering progress is updated. |
| Mirror mode changes. |
| Scaling mode changes. |
| Rotation mode changes. |
| Track information is ready. |
| Track switching is complete. |
PlayerNotificationDelegate defines 18 @optional callback methods, but the Dispatcher provides 17 convenience dispatch methods. The playerDidChangeControlsVisible: notification is dispatched by GestureControlSlot using the generic notifyObservers:withBlock: method, instead of a dedicated convenience method.
GestureNotificationDispatcher
The gesture notification dispatcher. It is created and held by GestureControlSlot. After a gesture is recognized, it dispatches semantic information about the gesture to all observers.
Core methods:
Interface | Description |
| Adds an observer that conforms to |
| Removes the specified observer. |
| Removes all observers. |
| Dispatches a notification block to all observers. |
| Returns the number of current active observers. |
Features:
Callback parameters focus on the data required for display, such as brightness or volume percentage, rather than the raw coordinate information of the gesture.
Injected by
SlotHostLayoutinto slots that need to respond to gestures, such asTopBarSlot,BottomBarSlot, andCenterDisplaySlot, during slot construction.
SlotActionNotificationDispatcher
The slot action notification dispatcher. It is created and managed by SlotHostLayout. It is used to decouple direct method calls between slots, such as when TopBarSlot or BottomBarSlot triggers SettingMenuSlot.
Core methods:
Interface | Description |
| Adds an observer that conforms to |
| Removes the specified observer. |
| Removes all observers. |
| Asynchronously dispatches a notification block to all observers. |
| Returns the number of current active observers. |
Features: Unlike other Dispatchers, SlotActionNotificationDispatcher always dispatches notifications asynchronously using dispatch_async(dispatch_get_main_queue(), ...). This avoids UI freezes that can be caused by performing heavy UI operations synchronously within the button event handling chain.
Usage
Register through the controller (recommended)
AliPlayerController provides convenience methods to register PlayerNotificationDelegate observers. This is the most common way to subscribe:
@interface MyViewController () <PlayerNotificationDelegate>
@property (nonatomic, strong) AliPlayerController *controller;
@end
@implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.controller = [[AliPlayerController alloc] init];
// Register as a notification observer
[self.controller addNotificationDelegate:self];
// Configure and attach the player...
[self.controller configure:model];
[self.playerView attach:self.controller];
}
- (void)dealloc {
// Explicitly remove the observer.
[self.controller removeNotificationDelegate:self];
[self.controller destroy];
}
#pragma mark - PlayerNotificationDelegate
- (void)playerDidChangeState:(PlayerState)state {
// Update the play/pause button state
}
- (void)playerDidUpdateCurrentPosition:(NSInteger)position
duration:(NSInteger)duration
bufferedPosition:(NSInteger)bufferedPosition {
// Update the progress bar
}
- (void)playerDidEncounterError:(NSError *)error {
// Display an error message
}
@endController registration entry points:
Method | Description |
| Adds an observer that conforms to the |
| Removes a previously added notification observer. |
Observers are stored as weak references using NSHashTable. They are automatically removed from the list when the observer object is released. However, you should explicitly call removeNotificationDelegate: in your observer's dealloc method to ensure prompt cleanup.
Internal slot communication (advanced)
GestureNotificationDispatcher and SlotActionNotificationDispatcher are part of the internal communication mechanism for slots. They are provided to built-in slots by SlotHostLayout through property injection during slot construction.
If a custom slot needs to receive gesture or slot action notifications, declare the corresponding Dispatcher property. SlotHostLayout will inject it for use:
@interface MyCustomSlot : UIView <SlotProtocol, GestureNotificationDelegate, SlotActionNotificationDelegate>
@property (nonatomic, weak, nullable) GestureNotificationDispatcher *gestureDispatcher;
@property (nonatomic, weak, nullable) SlotActionNotificationDispatcher *slotActionDispatcher;
@end
@implementation MyCustomSlot
- (void)setGestureDispatcher:(GestureNotificationDispatcher *)gestureDispatcher {
if (_gestureDispatcher) {
[_gestureDispatcher removeObserver:self];
}
_gestureDispatcher = gestureDispatcher;
if (_gestureDispatcher) {
[_gestureDispatcher addObserver:self];
}
}
- (void)setSlotActionDispatcher:(SlotActionNotificationDispatcher *)slotActionDispatcher {
if (_slotActionDispatcher) {
[_slotActionDispatcher removeObserver:self];
}
_slotActionDispatcher = slotActionDispatcher;
if (_slotActionDispatcher) {
[_slotActionDispatcher addObserver:self];
}
}
#pragma mark - GestureNotificationDelegate
- (void)gestureDidSingleTap {
// Toggle control bar visibility on single tap
}
- (void)gestureDidUpdateVolumeWithPercent:(CGFloat)currentPercent {
// Display the volume adjustment UI
}
#pragma mark - SlotActionNotificationDelegate
- (void)slotDidRequestToggleSettingMenu {
// Respond to the request to toggle the settings menu
}
@endGestureNotificationDispatcher is created and held by GestureControlSlot (a readonly property). SlotActionNotificationDispatcher is created and held by SlotHostLayout. The Dispatcher properties of a slot are declared as weak and are automatically injected by SlotHostLayout when rebuildSlots is called.
Complete code example
The following example shows how a complete playback page subscribes to player notifications:
@interface PlayerPageViewController () <PlayerNotificationDelegate>
@property (nonatomic, strong) AliPlayerView *playerView;
@property (nonatomic, strong) AliPlayerController *controller;
@end
@implementation PlayerPageViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.playerView = [[AliPlayerView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.playerView];
self.controller = [[AliPlayerController alloc] init];
// Register as a notification observer
[self.controller addNotificationDelegate:self];
VideoSource *source = [VideoSource vidAuthSourceWithVid:@"vid" playAuth:@"auth"];
AliPlayerModel *model = [[AliPlayerModel alloc] initWithVideoSource:source];
[self.controller configure:model];
[self.playerView attach:self.controller];
}
- (void)dealloc {
[self.controller removeNotificationDelegate:self];
[self.controller destroy];
}
#pragma mark - PlayerNotificationDelegate
- (void)playerDidChangeState:(PlayerState)state {
NSLog(@"Player state changed: %ld", (long)state);
}
- (void)playerDidPreparedWithDuration:(NSInteger)duration {
NSLog(@"Preparation complete, total duration: %ld ms", (long)duration);
}
- (void)playerDidRenderFirstFrame {
// Hide the thumbnail
}
- (void)playerDidCompletion {
// Show the replay button
}
- (void)playerDidUpdateCurrentPosition:(NSInteger)position
duration:(NSInteger)duration
bufferedPosition:(NSInteger)bufferedPosition {
// Update the progress bar
}
- (void)playerDidChangeFullscreen:(BOOL)isFullscreen {
// Update the layout for full-screen/non-full-screen mode
}
- (void)playerDidChangeControlsVisible:(BOOL)visible {
// Sync control bar visibility
}
- (void)playerDidEncounterError:(NSError *)error {
NSLog(@"Playback error: %@", error.localizedDescription);
}
@endThe PlayerKitUsages/UsageNotificationSystem module provides a complete example of how to use the notification system. It shows how to register a PlayerNotificationDelegate observer and receive real-time notifications for player state changes, progress updates, and more.
List of notifications
PlayerNotificationDelegate (18 @optional methods)
Playback state notifications
Method | Triggered when | Parameter description |
| The player state transitions. |
|
| The player finishes preparation. |
|
| The first frame of the video is rendered. | — |
| Playback reaches the end of the media. | — |
Playback progress notifications
Method | Triggered when | Parameter description |
| Called periodically during playback. |
|
Error notifications
Method | Triggered when | Parameter description |
| A playback error occurs. |
|
Snapshot notifications
Method | Triggered when | Parameter description |
| A snapshot is completed. |
|
Video dimension notifications
Method | Triggered when | Parameter description |
| The video dimensions change. |
|
Full-screen and control bar notifications
Method | Triggered when | Parameter description |
| The full-screen transition is complete. |
|
| The visibility of the control bar changes. |
|
The playerDidChangeControlsVisible: notification is triggered by a single-tap gesture in GestureControlSlot or by the auto-hide timer. All control bars that need to synchronize their visibility should implement this method. This prevents state inconsistencies that can result from independent toggling.
Loading notifications
Method | Triggered when | Parameter description |
| Network stuttering occurs or the buffer is insufficient. | — |
| There is enough buffered data to resume playback. | — |
| The buffering progress changes. |
|
Display mode notifications
Method | Triggered when | Parameter description |
| The mirror mode changes. |
|
| The scaling mode changes. |
|
| The rotation mode changes. |
|
Track notifications
Method | Triggered when | Parameter description |
| The available track information is ready. |
|
| Track switching is complete. |
|
GestureNotificationDelegate (7 @optional methods)
Method | Triggered when | Parameter description |
| A single-tap gesture is triggered. | — |
| A long-press gesture starts (playback speed is activated). | — |
| A long-press gesture ends (playback speed is restored). | — |
| A vertical drag on the left side is updated. |
|
| A vertical drag on the left side ends. | — |
| A vertical drag on the right side is updated. |
|
| A vertical drag on the right side ends. | — |
SlotActionNotificationDelegate (3 @optional methods)
Method | Triggered when | Parameter description |
| The Settings button in | — |
| The Playback Speed button in | — |
| The Quality button in | — |
All notifications from SlotActionNotificationDelegate are dispatched asynchronously using dispatch_async(dispatch_get_main_queue(), ...). This ensures they execute in the next run loop and avoids UI issues caused by synchronous execution within the button event handling chain.
Instance-level isolation mechanism
Design principle
In scenarios with multiple player instances, such as vertical scrolling in short videos or Picture-in-Picture (PiP), notifications from different players must not interfere with each other. PlayerKit achieves notification isolation at the instance level rather than through global filtering.
Isolation method
Each AliPlayerController holds an independent PlayerNotificationDispatcher instance. After an observer registers with a controller's Dispatcher, it only receives notifications from that controller:
┌── AliPlayerController (A) ──┐ ┌── AliPlayerController (B) ──┐
│ PlayerNotificationDispatcher │ │ PlayerNotificationDispatcher │
│ ├── Observer 1 │ │ ├── Observer 3 │
│ └── Observer 2 │ │ └── Observer 4 │
└───────────────────────────────┘ └───────────────────────────────┘
Observers 1 and 2 only receive notifications from Controller A
Observers 3 and 4 only receive notifications from Controller BKey design points:
No need for a global EventBus or to manually check the
playerIdin callbacks.The
PlayerNotificationDispatcher.playerIdproperty is used to inform observers of the source identifier of a notification, not for filtering.Registration provides isolation, and unregistering disconnects the observer.
// Notifications from controllerA are only dispatched to observers registered with A
[controllerA addNotificationDelegate:slotA]; // slotA only receives notifications from A
[controllerB addNotificationDelegate:slotB]; // slotB only receives notifications from BDeveloping custom observers
Implement the Delegate protocol
Implement the required Delegate protocol. You only need to implement the methods you are interested in, as all methods are @optional:
@interface MyAnalyticsObserver : NSObject <PlayerNotificationDelegate>
@end
@implementation MyAnalyticsObserver
- (void)playerDidChangeState:(PlayerState)state {
[self trackStateChange:state];
}
- (void)playerDidEncounterError:(NSError *)error {
[self reportError:error];
}
- (void)playerDidCompletion {
[self trackPlaybackComplete];
}
@endRegister and unregister
// Create the observer
MyAnalyticsObserver *observer = [[MyAnalyticsObserver alloc] init];
// Register: Use the controller's convenience entry point
[controller addNotificationDelegate:observer];
// Unregister: Explicitly remove
[controller removeNotificationDelegate:observer];Although the NSHashTable weak reference automatically cleans up after the observer is released, you should explicitly call removeNotificationDelegate: to ensure prompt cleanup. This avoids receiving unexpected notifications in the brief time window before the observer is released.
Thread safety mechanism
Feature | Description |
Observer storage | Stored as weak references using |
List access | Protected by a serial dispatch queue ( |
Callback thread | Notifications are always dispatched on the main thread. For |
Exception isolation | Each observer call is wrapped in a |
Duplicate additions | Adding the same observer multiple times has no effect. |
Safe for no-ops | Removing an unregistered observer has no effect. |
Dispatch flow:
PlayerNotificationDispatcher / GestureNotificationDispatcher:
dispatch method call
→ Get a snapshot of observers within the serial queue (thread-safe)
→ Call observer callbacks one by one on the main thread
→ Wrap each call in @try/@catch (exception isolation)
SlotActionNotificationDispatcher:
notifyObservers: call
→ Get a snapshot of observers within the serial queue (thread-safe)
→ Dispatch asynchronously with dispatch_async(dispatch_get_main_queue(), ...)
→ Call observer callbacks one by one in the next run loop
→ Wrap each call in @try/@catch (exception isolation)API quick reference
Dispatcher class
Class | Key methods | Description |
|
| Player notification dispatcher. Includes a |
|
| Gesture notification dispatcher. |
|
| Slot action notification dispatcher (asynchronous dispatch). |
Delegate protocols
Protocol | Number of methods | Scope of responsibility |
| 18 | Playback state, progress, errors, snapshots, full screen, control bar, loading, display mode, and tracks. |
| 7 | Single tap, long press, brightness adjustment, and volume adjustment. |
| 3 | Settings menu toggle, playback speed panel, and quality panel. |
Controller protocol
Method | Description |
| Registers a |
| Removes a |
Common Dispatcher methods
Method | Description |
| Adds an observer (weak reference, adding duplicates has no effect). |
| Removes the specified observer (has no effect if not registered). |
| Clears all observers. |
| Dispatches a notification block to all observers. |
| Returns the number of current active observers. |
PlayerNotificationDispatcher-specific methods
Method | Description |
| Dispatches only to observers that implement the specified selector (selector filtering). |
17 convenience methods, such as | Conveniently monitor player status, progress, errors, screenshots, full screen, loading, display mode, and tracks. |