-
使用NSNotification来监听进入后台和前台事件
.UIApplicationWillEnterForeground
.UIApplicationDidEnterBackground
-
长按home键不会响应
1.
中的两个通知事件,需要同时使用以下通知.UIApplicationWillResignActive
.UIApplicationDidBecomeActive
如果AVPlayer
的当前项在设备的显示屏上显示视频,则AVPlayer
当应用程序发送到后台时,的播放会自动暂停。有两种方法可以防止这种暂停:
- 禁用播放器项中的视频轨道(仅基于文件的内容)。参见清单1。
AVPlayerLayer
从与其关联的中删除AVPlayer
(将AVPlayerLayer
player
属性设置为nil)。参见清单2。
Listing 1 Disabling the video tracks in the player item.
import AVFoundation
let playerItem = <#Your player item#>
let tracks = playerItem.tracks
for playerItemTrack in tracks {
// Find the video tracks.
if playerItemTrack.assetTrack.hasMediaCharacteristic(AVMediaCharacteristicVisual) {
// Disable the track.
playerItemTrack.isEnabled = false
}
}
Listing 2 Remove/Restore the AVPlayerLayer
and its associated AVPlayer
.
import UIKit
import AVFoundation
...
// A `UIView` subclass that is backed by an `AVPlayerLayer` layer.
class PlayerView: UIView {
var player: AVPlayer? {
get {
return playerLayer.player
}
set {
playerLayer.player = newValue
}
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
override class var layerClass: AnyClass {
return AVPlayerLayer.self
}
}
...
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
@IBOutlet weak var playerView: PlayerView!
/*
Remove the AVPlayerLayer from its associated AVPlayer
once the app is in the background.
*/
func applicationDidEnterBackground(_ application: UIApplication) {
// Remove the player.
playerView.player = nil
}
// Restore the AVPlayer when the app is active again.
func applicationDidBecomeActive(_ application: UIApplication) {
// Restore the player.
playerView.player = <#Your player#>
}
}