You need to enable JavaScript to run this app. SwiftUI 修复视频结束监听报错及实现播放完成后返回首页的方法
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI 修复视频结束监听报错及实现播放完成后返回首页的方法

原代码报错原因梳理
  • 语法上下文非法:将通知注册代码直接写在struct的属性初始化区域,不属于可执行代码的合法上下文,编译直接报语法错误
  • 类型约束不匹配:ContentViewC是SwiftUI的struct值类型,不满足NotificationCenter要求observer必须是引用类型(AnyObject)的约束,传self会直接触发类型不匹配报错
  • 监听逻辑漏洞:注册通知时将object参数传为nil,会全局接收所有AVPlayerItem的播放结束事件,极易引发逻辑错乱
  • 生命周期不匹配:没有在视图销毁时移除通知监听,会引发野指针类崩溃
修复实现

1. 合规的播放结束监听写法

放弃需要搭配@objc selector的传统通知写法,改用block式通知监听,把注册、移除逻辑和视图的onAppear/onDisappear生命周期绑定,精准匹配当前播放项。

关键注意:注册通知时必须把player.currentItem传入object参数,不要传nil,否则会收到全局的AVPlayer结束通知,出现逻辑串台问题。

2. 播放结束自动返回HomeView的导航逻辑

SwiftUI中不需要手动操作底层UINavigationController的返回方法,只要把原来无状态绑定的NavigationLink改成isActive绑定模式,通过绑定变量控制导航状态即可:

  • 在Home主页定义@State状态变量,用来控制视频播放页的展示/隐藏
  • 把状态变量绑定到NavigationLink的isActive参数,同时把这个绑定变量透传给视频播放页
  • 视频播放结束的回调里,把绑定的状态变量设为false,系统会自动触发导航返回动作,回到Home主页
修正后可直接运行的代码

Home主页(原ContentView)

struct ContentView: View {
    // 新增:绑定视频播放页的导航展示状态
    @State private var showVideoPlayer = false
    private let width: CGFloat = 400
    private let height: CGFloat = 400
    private let txtWidth: CGFloat = 300
    private let txtHeight: CGFloat = 100
    
    var body: some View {
        NavigationView {
            ZStack {
                Image("app_bg3")
                    .resizable()
                    .edgesIgnoringSafeArea(.all)
                VStack {
                    ZStack {
                        // 改造原有无状态NavigationLink为isActive绑定模式
                        NavigationLink(
                            destination: ContentViewC(isActive: $showVideoPlayer),
                            isActive: $showVideoPlayer
                        ) {
                            HStack(alignment: .bottom) {
                                Spacer()
                                VStack  {
                                    VStack {
                                        Image("OneCirclePlayBtn")
                                            .resizable()
                                            .aspectRatio(contentMode: .fill)
                                            .frame(width: width, height: height)
                                        Text("The")
                                            .font(Font.custom("Nunito-Regular", size: 43))
                                            .font(.largeTitle)
                                            .fontWeight(.bold)
                                            .foregroundColor(Color(.white))
                                            .frame(width: txtWidth, height: txtHeight, alignment: .center)
                                        Text("Voice")
                                            .font(Font.custom("Nunito-Regular", size: 43))
                                            .font(.largeTitle)
                                            .fontWeight(.bold)
                                            .foregroundColor(Color(.white))
                                            .frame(width: txtWidth, height: txtHeight, alignment: .center)
                                            .offset(y: -50)
                                    }
                                }
                                Spacer()
                            }
                        }
                    }.offset(y: 100)
                    
                    HStack(spacing: 350) {
                        NavigationLink(destination: ContentViewA()) {
                            VStack {
                                VStack {
                                    Image("TwoCirclePlayBtn")
                                        .resizable()
                                        .aspectRatio(contentMode: .fill)
                                        .frame(width: width, height: height)
                                    Text("The Cast")
                                        .font(Font.custom("Nunito-Regular", size: 33))
                                        .font(.largeTitle)
                                        .fontWeight(.bold)
                                        .foregroundColor(Color(.white))
                                        .frame(width: txtWidth, height: txtHeight, alignment: .center)
                                }
                            }
                        }
                        
                        NavigationLink(destination: ContentViewB()) {
                            VStack {
                                VStack {
                                    Image("ThreeCirclePlayBtn")
                                        .resizable()
                                        .aspectRatio(contentMode: .fill)
                                        .frame(width: width, height: height, alignment: .center)
                                    Text("The Artist")
                                        .font(Font.custom("Nunito-Regular", size: 33))
                                        .font(.largeTitle)
                                        .fontWeight(.bold)
                                        .foregroundColor(Color(.white))
                                        .frame(width: txtWidth, height: txtHeight, alignment: .center)
                                }
                            }
                        }
                    }.offset(y: -150)
                }
            }
            .navigationViewStyle(StackNavigationViewStyle())
            .accentColor(.white)
            .statusBar(hidden: true)
            .background(StatusBarHideHelperView())
        }
    }
}

// 保留原有状态栏隐藏辅助类
class StatusBarHideHelper: UIViewController {
    override var prefersStatusBarHidden: Bool { true }
}

struct StatusBarHideHelperView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> UIViewController {
        StatusBarHideHelper()
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}

视频播放页(原ContentViewC)

struct ContentViewC: View {
    // 接收从主页透传的导航绑定状态
    @Binding var isActive: Bool
    private let player = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "videoToPlay", ofType: "mp4")!))
    
    var body: some View {
        VStack {
            AVPlayerControllerRepresented(player: player)
                .edgesIgnoringSafeArea(.all)
                .onAppear {
                    // 注册播放结束通知,精准监听当前播放项
                    NotificationCenter.default.addObserver(
                        forName: .AVPlayerItemDidPlayToEndTime,
                        object: player.currentItem,
                        queue: .main
                    ) { _ in
                        print("视频播放完成")
                        // 把绑定状态设为false,自动触发返回动作
                        isActive = false
                    }
                    player.play()
                }
                .onDisappear {
                    // 移除通知监听,避免内存泄漏
                    NotificationCenter.default.removeObserver(
                        self,
                        name: .AVPlayerItemDidPlayToEndTime,
                        object: player.currentItem
                    )
                    player.pause()
                    player.seek(to: .zero)
                }
        }
        .background(Color(.black))
        .edgesIgnoringSafeArea(.all)
    }
}

内容的提问来源于stack exchange,提问作者devlo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.06 00:06:10