我有一个显示
AVPlayerViewController
的按钮,我设法将图片添加到我的 AVPlayerViewController 中,这样我就可以最小化它,现在最小化后我想再次最大化它,但一旦我这样做,AVPlayerViewController
就会消失。我不打算使用故事板,并希望以编程方式执行此操作,因为将视图控制器嵌入导航控制器可以解决问题,但我不想遵循这种方法
我添加了
BackgroundMode
功能并勾选了 PIP
和 Appdelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.playback)
try audioSession.setActive(true, options: [])
} catch {
print("Setting category to AVAudioSessionCategoryPlayback failed.")
}
return true
}
在我的
ViewController
class ViewController: UIViewController,AVPlayerViewControllerDelegate {
var playerController : AVPlayerViewController!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btnClicked(_ sender: Any) {
if let videoURL = URL(string: "https://storage.googleapis.com/exoplayer-test-media-0/BigBuckBunny_320x180.mp4") {
let player = AVPlayer(url: videoURL)
playerController = AVPlayerViewController()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.didfinishPlaying(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
playerController.player = player
playerController.allowsPictureInPicturePlayback = true
playerController.delegate = self
playerController.player?.play()
self.present(playerController, animated: true, completion : nil)
}
}
}
只是为了创建一个简单的演示,我使用了
storyboard
,在我的真实应用程序中我不使用它
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController,AVPlayerViewControllerDelegate {
let playerController = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
playerController.delegate = self
}
@IBAction func btnClicked(_ sender: Any) {
if let videoURL = URL(string: "https://storage.googleapis.com/exoplayer-test-media-0/BigBuckBunny_320x180.mp4") {
let player = AVPlayer(url: videoURL)
playerController.player = player
playerController.allowsPictureInPicturePlayback = true
playerController.delegate = self
playerController.player?.play()
self.present(playerController, animated: true, completion : nil)
}
}
func playerViewController(_ playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) {
self.present(playerViewController, animated: true) {
completionHandler(true)
}
}
}
上面的代码无需
NavigationController
即可工作