gpt4 book ai didi

swift - AvFoundation框架,AvPlayer暂停方法导致应用程序最小化后崩溃

转载 作者:行者123 更新时间:2023-11-30 10:36:38 28 4
gpt4 key购买 nike

我使用 UIView 组件和 AVFoundation 框架在后台显示 mp4 视频文件。

但是应用程序用户最小化应用程序后会出现错误。因为如您所见,player.pause() 方法会导致崩溃。这是错误: fatal error :隐式解包可选值时意外发现 nil

    import UIKit
import AVFoundation
import AVKit

class ViewController: UIViewController {

private var player: AVPlayer!

@IBOutlet weak var videoUiViewOutlet: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
}

private func setupView()
{
let path = URL(fileURLWithPath: Bundle.main.path(forResource: "clouds", ofType: "mp4")!)
let player = AVPlayer(url: path)
let newLayer = AVPlayerLayer(player: player)
newLayer.frame = self.videoUiViewOutlet.frame
self.videoUiViewOutlet.layer.addSublayer(newLayer)
newLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill

player.play()

player.actionAtItemEnd = AVPlayer.ActionAtItemEnd.none

NotificationCenter.default.addObserver(self, selector: #selector(self.videoDidPlayToEnd(notification:)),
name: NSNotification.Name(rawValue: "AVPlayerItemDidPlayToEndTimeNotification"), object: player.currentItem)

NotificationCenter.default.addObserver(self, selector: #selector(enteredBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(enteredForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}

@objc func videoDidPlayToEnd(notification: Notification)
{
let player: AVPlayerItem = notification.object as! AVPlayerItem
player.seek(to: .zero, completionHandler: nil)
}

@objc func enteredBackground() {
print("scope: enteredBackground")
player.pause()
}

@objc func enteredForeground() {
print("scope: enteredForeground")
player.play()
}
}

如何解决这个问题?应用程序最小化后,视频应暂停。应用程序最大化后,视频应继续播放。

最佳答案

问题是因为您尚未将值分配给类 ViewControllerplayer 属性,即

private var player: AVPlayer!

由于它是一个强制解包可选,因此它的默认值是nil。在 enteredBackground() 方法中使用它会导致运行时异常

解决方案:

setupView()方法中,替换

let player = AVPlayer(url: path)

self.player = AVPlayer(url: path)

关于swift - AvFoundation框架,AvPlayer暂停方法导致应用程序最小化后崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57849349/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com