我是Swift的新手,我正在尝试将视频添加到视图中,然后在我的" stopScreenSaver"发送通知。除了我去删除视频图层(playerLayer.removeFromSuperlayer())时,一切似乎都运行良好。
任何指导都将不胜感激。我觉得我在这里缺少一些基本概念来添加和删除图层!
import UIKit
import AVFoundation
import QuartzCore
import CoreMedia
class ViewController: UIViewController {
let contentURL = NSBundle.mainBundle().URLForResource("testvideo", withExtension: "mp4")
var player = AVPlayer()
var playerLayer = AVPlayerLayer()
let screenSize : CGRect = UIScreen.mainScreen().bounds
override func viewDidLoad() {
super.viewDidLoad()
// Used for starting and stopping the videos related to the screen saver
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playScreenSaver:", name: "playScreenSaverID", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "stopScreenSaver:", name: "stopScreenSaverID", object: nil)
}
override func viewDidAppear(animated: Bool) {
// Player
player = AVPlayer(URL: contentURL!)
// Layer for display… Video plays at the full size of the iPad
playerLayer = AVPlayerLayer(player: player)
var view = UIView(frame: CGRectMake(0, 0, screenSize.width, screenSize.height))
self.view.layer.addSublayer(playerLayer)
playerLayer.frame = view.bounds
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func playScreenSaver(notification: NSNotification){
print("play")
dispatch_async(dispatch_get_main_queue()) {
self.view.layer.addSublayer(self.playerLayer!)
self.player!.play()
}
}
func stopScreenSaver(notification: NSNotification){
print("pause")
dispatch_async(dispatch_get_main_queue()) {
self.player!.pause()
self.playerLayer!.removeFromSuperlayer()
}
}
}
答案 0 :(得分:3)
使用调度修复了我遇到的问题。
dispatch_async(dispatch_get_main_queue()) {
self.player!.pause()
self.playerLayer!.removeFromSuperlayer()
}
答案 1 :(得分:0)
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
DispatchQueue.main.async {
self.player.currentItem?.removeObserver(self, forKeyPath: "duration", context: nil)
self.player!.pause()
self.playerLayer!.removeFromSuperlayer()
}
}
答案 2 :(得分:0)
尝试一下
{{1}}