현재 AVPlayer를 사용하는보기에서 내 배경으로 비디오를 재생하고 있지만 홈 화면으로 돌아가서 응용 프로그램을 다시 열면 비디오가 일시 중지되고 다시 시작할 수 없습니다. 물론 앱을 닫고 다시 열면 해결되지만 사실 사용자가 앱을 다시 시작하면 다시 열어야합니다.
나는 내 viewcontroller에 링크 된 변수를 생성 한 다음 avPlayer.play()를 호출하여 AppDelegate에서 applicationDidBecomeActive를 사용하여 시도했다. 그러나이 다음 nil 발견 오류를 던졌습니다. 또한 applicationDidBecomeActive에서 viewDidLoad()를 호출 해 보았는데이 코드는 delegate에서 호출하지 않을 때 코드가 완벽하게 작동하더라도 잘못된 지시문 오류를 제공합니다.
도움이 될 것입니다.applicationDidBecomeActive가 실행되면 AVPlayer 비디오를 다시 시작 하시겠습니까?
의 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
}
시도를 재생 처리. ViewController에서 avPlayer.play()를 시작하는 함수를 만듭니다. –