Skip to content

Commit bf98bd7

Browse files
authored
Merge pull request #301 from duca14036/master
Ability to play video in background
2 parents a31a256 + f58401b commit bf98bd7

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

Source/BMPlayerLayerView.swift

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -271,12 +271,12 @@ open class BMPlayerLayerView: UIView {
271271
playerItem = AVPlayerItem(asset: urlAsset!)
272272
player = AVPlayer(playerItem: playerItem!)
273273
player!.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
274-
playerLayer?.removeFromSuperlayer()
275-
playerLayer = AVPlayerLayer(player: player)
276-
playerLayer!.videoGravity = videoGravity
277-
layer.addSublayer(playerLayer!)
274+
self.connectPlayerLayer()
278275
setNeedsLayout()
279276
layoutIfNeeded()
277+
278+
NotificationCenter.default.addObserver(self, selector: #selector(self.connectPlayerLayer), name: UIApplication.willEnterForegroundNotification, object: nil)
279+
NotificationCenter.default.addObserver(self, selector: #selector(self.disconnectPlayerLayer), name: UIApplication.didEnterBackgroundNotification, object: nil)
280280
}
281281

282282
func setupTimer() {
@@ -444,5 +444,18 @@ open class BMPlayerLayerView: UIView {
444444
}
445445
}
446446
}
447+
448+
@objc fileprivate func connectPlayerLayer() {
449+
playerLayer?.removeFromSuperlayer()
450+
playerLayer = AVPlayerLayer(player: player)
451+
playerLayer!.videoGravity = videoGravity
452+
453+
layer.addSublayer(playerLayer!)
454+
}
455+
456+
@objc fileprivate func disconnectPlayerLayer() {
457+
playerLayer?.removeFromSuperlayer()
458+
playerLayer = nil
459+
}
447460
}
448461

0 commit comments

Comments
 (0)