Skip to content

Commit 1329d94

Browse files
committed
Update LoopingPlayerProtocol.swift
1 parent 901ccbc commit 1329d94

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

Sources/swiftui-loop-videoplayer/protocol/player/LoopingPlayerProtocol.swift

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -164,25 +164,38 @@ internal extension LoopingPlayerProtocol {
164164
self.loop()
165165
}
166166

167+
// Set up state item status observer
168+
setupStateItemStatusObserver(newItem: newItem, callback: callback)
169+
170+
if autoPlay{
171+
player.play()
172+
}
173+
}
174+
175+
/// Sets up an observer for the status of the provided `AVPlayerItem`.
176+
///
177+
/// This method observes changes in the status of `newItem` and triggers the provided callback
178+
/// whenever the status changes to `.readyToPlay` or `.failed`. Once the callback is invoked,
179+
/// the observer is invalidated, ensuring that the callback is called only once.
180+
///
181+
/// - Parameters:
182+
/// - newItem: The `AVPlayerItem` whose status is to be observed.
183+
/// - callback: A closure that is called when the item's status changes to `.readyToPlay` or `.failed`.
184+
func setupStateItemStatusObserver(newItem: AVPlayerItem, callback: ((AVPlayerItem.Status) -> Void)?) {
167185
statusObserver?.invalidate()
168186

169-
170-
if let callback{
171-
statusObserver = newItem.observe(\.status, options: [.new, .old]) { [weak self] item, change in
172-
//.unknown: This state is essentially the default, indicating that the player item is new or has not yet attempted to load its assets.
187+
if let callback = callback {
188+
//.unknown: This state is essentially the default, indicating that the player item is new or has not yet attempted to load its assets.
189+
statusObserver = newItem.observe(\.status, options: [.new, .old]) { [weak self] item, _ in
173190
guard item.status == .readyToPlay || item.status == .failed else {
174191
return
175192
}
176193

177-
callback(item.status)
178-
self?.statusObserver?.invalidate()
179-
self?.statusObserver = nil
194+
callback(item.status)
195+
self?.statusObserver?.invalidate()
196+
self?.statusObserver = nil
180197
}
181198
}
182-
183-
if autoPlay{
184-
player.play()
185-
}
186199
}
187200

188201
/// Sets up observers on the player item and the player to track their status and error states.

0 commit comments

Comments
 (0)