我在选择collectionViewCell时尝试加载AVPlayer,这是didSelectItem
中的代码:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let item = items?[indexPath.item] {
showPlayer(item: item)
}
}
func showPlayer(item: Item) {
let playerLauncher = PlayerLauncher()
playerLauncher.showVideoPlayer()
let playerView = PlayerView()
playerView.item = item
playerView.setupPlayerView()
}
这是我的PlayerLauncher文件:
class PlayerView: UIView {
var item: Item? {
didSet {
if let id = item?.itemId {
itemId = id
}
}
}
var itemId = String()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(white: 0.3, alpha: 1)
}
var player: AVPlayer?
func setupPlayerView() {
let baseurl = "http://xample.com/play.m3u?id="
let urlString = "\(baseurl)\(itemId)"
print(urlString)
if let url = URL(string: urlString) {
player = AVPlayer(url: url)
let playerLayer = AVPlayerLayer(player: player)
self.layer.addSublayer(playerLayer)
playerLayer.frame = self.frame
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
} catch let err {
print(err)
return
}
player?.play()
player?.addObserver(self, forKeyPath: "currentItem.status", options: .new, context: nil)
}
}
}
class PlayerLauncher: NSObject {
func showVideoPlayer() {
print("Showing the player...")
if let keyWindow = UIApplication.shared.keyWindow {
let view = UIView(frame: keyWindow.frame)
view.backgroundColor = UIColor.white
view.frame = CGRect(x: keyWindow.frame.width - 10, y: keyWindow.frame.height - 10, width: 10, height: 10)
let playerFrame = CGRect(x: 0, y: 0, width: keyWindow.frame.width, height: keyWindow.frame.height)
let playerView = PlayerView(frame: playerFrame)
view.addSubview(playerView)
keyWindow.addSubview(view)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
view.frame = keyWindow.frame
}, completion: { (completedAnimation) in
//later...
})
}
}
}
所以每当我选择项目时,播放器开始加载,控制台打印URL(因为我在那里添加了print语句),这就是它打印的内容:
http://xample.com/play.m3u?id=12345
(lldb)
然后它崩溃并在AppDelegate中显示Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
错误。我该如何解决?
感谢。
更新
我稍微更改了didSelectItem
func。这是代码:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let item = items?[indexPath.item] {
showPlayer(item: item)
}
}
func showPlayer(item: Item) {
let playerLauncher = PlayerLauncher()
playerLauncher.showPlayer(item: item)
}
我将init
中的PlayerView
方法更改为:
var item: Item? {
didSet {
if let id = item?.itemId {
itemId = id
}
}
}
init(frame: CGRect, item: Item) {
super.init(frame: frame)
self.item = item
setupPlayerView()
setupContainerView()
backgroundColor = UIColor(white: 0.3, alpha: 1)
}
PlayerLauncher
中所需的更改:
let playerView = PlayerView(frame: playerFrame, item: item)
view.addSubview(playerView)
我在let playerView
行停了一下,我可以看到项目ID在那里传递。但它没有传递给PlayerView
类中的urlString。因此,ID仍为" "
。