【发布时间】:2017-05-12 18:21:16
【问题描述】:
当前正在使用 AVPlayer 在视图中播放视频作为我的背景,但是当我返回主屏幕然后重新打开应用程序时,视频已暂停,我无法继续播放。当然关闭应用程序并重新打开会修复它,但当用户返回应用程序时,我真的需要它恢复。
我尝试在 AppDelegate 中使用 applicationDidBecomeActive,方法是创建一个链接到我的视图控制器的变量,然后调用 avPlayer.play()。然而,这会抛出一个错误,说 found nil。我还尝试在 applicationDidBecomeActive 中调用 viewDidLoad() ,这给了我一个 BAD INSTRUCTION 错误,即使代码在不从委托调用时完美运行。
任何帮助将不胜感激!
视图控制器:
import UIKit
import AVFoundation
class ViewController: UIViewController, CLLocationManagerDelegate {
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
var foregroundNotification: NSObjectProtocol!
//viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.viewDidLoad), name:NSNotification.Name.UIApplicationWillEnterForeground, object:UIApplication.shared)
//Rotate icon
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = 360.0
rotateAnimation.repeatCount = HUGE
rotateAnimation.duration = 450
checkInButton.layer.add(rotateAnimation, forKey: "myAnimationKey");
//Play background video
let theURL = Bundle.main.url(forResource:"city2", withExtension: "mp4")
avPlayer = AVPlayer(url: theURL!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayer.volume = 0
avPlayer.actionAtItemEnd = .none
//avPlayer.rate = 1
avPlayerLayer.frame = view.layer.bounds
view.backgroundColor = .clear
view.layer.insertSublayer(avPlayerLayer, at: 0)
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd(notification:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
}
func playerItemDidReachEnd(notification: Notification) {
let p: AVPlayerItem = notification.object as! AVPlayerItem
p.seek(to: kCMTimeZero)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
avPlayer.play()
paused = false
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
avPlayer.pause()
paused = true
}
}
代表:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var vc = ViewController()
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
vc.avPlayer.play()
vc.paused = false
}
【问题讨论】:
-
尝试在 ViewDidAppear 或 ViewWillAppear 函数中添加带有 NameWillEnterForeground 的 NotificationCenter。并创建一个将在 ViewController 中启动 avPlayer.play() 的函数。