当前正在使用AVPlayer在视图中播放视频作为我的背景,但当我返回到主屏幕,然后重新打开应用程序时,视频暂停,无法恢复。当然,关闭应用程序并重新打开可以修复它,但当用户返回应用程序时,我真的需要恢复它。
我尝试在AppDelegate中使用applicationDidBecomeActive,方法是创建一个链接到视图控制器的变量,然后调用avPlayer.play()。但是,这随后会抛出一个错误,指出found nil。我还尝试在applicationDidBecomeActive中调用viewDidLoad(),这会给我一个严重的指令错误,即使代码在没有从委托中调用它时也能很好地工作。
任何帮助都将不胜感激!
ViewController:
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
}发布于 2017-07-14 11:54:47
像这样设置一次通知。
NotificationCenter.default.addObserver(self, selector: #selector(appMovedToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)然后在这里播放你的音乐
func appMovedToForeground() {
//do you play stuff here
}https://stackoverflow.com/questions/43944226
复制相似问题