一、环境
要实现画中画 ios系统必须是 iOS14+
本文开发环境
xcode14.2
二、权限配置
- 在项目导航器中单击项目,然后单击Signing & Capabilities。
- 单击
+ Capabilit
- 搜索
Background Modes
,然后双击将其添加为功能。 - 在新添加的
Background Modes
部分,选中Audio, AirPlay, and Picture in Picture
复选框。
三、实例
import Foundation
import SwiftUI
import AVKit
struct VideoPlayerView: UIViewControllerRepresentable {var videoURL: URL?// 创建UIViewControllerfunc makeUIViewController(context: Context) -> AVPlayerViewController {let controller = AVPlayerViewController()controller.player = AVPlayer(url: videoURL!)controller.allowsPictureInPicturePlayback = truecontroller.delegate = context.coordinatorreturn controller}// 更新UIViewControllerfunc updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {uiViewController.player = AVPlayer(url: videoURL!)uiViewController.allowsPictureInPicturePlayback = trueuiViewController.showsPlaybackControls = true // 显示控制层if #available(iOS 14.2, *) {//进入后台时是否自动打开
// uiViewController.canStartPictureInPictureAutomaticallyFromInline = true} else {// Fallback on earlier versions}}func makeCoordinator() -> Coordinator {Coordinator(self)}class Coordinator: NSObject, AVPlayerViewControllerDelegate {var playerView: VideoPlayerViewinit(_ playerView: VideoPlayerView) {self.playerView = playerView}func playerViewController(_ playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) {// 在这里,你可以决定在退出画中画模式后是否保持在当前视图。// 这个例子中我们选择保持在当前视图。completionHandler(true)}}
}struct playView: View {var body: some View {VStack {VideoPlayerView(videoURL: URL(string: "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8")!).frame(height: 400)}
// .onAppear {
// player.play()
// }
// .onDisappear {
// player.pause()
// }}
}
注意:画中画只能在真机上运行,xcode上的模拟器没有画中画功能