Swift 4.请问返回app后如何播放视频?

Swift 4. Could you suggest how to play video after returning to the app?

我在 phone 视图 AVPlayer 上有一个视频,但如果按下主页按钮,应用程序会崩溃——视频会自动停止,如果再次打开应用程序——应用程序会暂停。使用 AppDelegate applicationWillEnterForeground,我要求查看并尝试继续播放视频,但它继续暂停。在其他视图中转换并返回后 - 视频继续播放。 能否请教一下返回应用后如何播放视频?

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

var player: AVPlayer?
override func viewDidLoad() {
    super.viewDidLoad()

    playVideo()
}

public func test()
{
    print("1111")
    if player?.timeControlStatus == .playing
    {
        print("playing") // not print
    }
    else if player?.timeControlStatus == .paused
    {
        player?.play()
        print("paused") // not print
    }
}

private func playVideo()
{
    let file1 : String = "portable.mp4";

    let file = file1.components(separatedBy: ".")
    guard let path = Bundle.main.path(forResource: file[0], ofType:file[1]) else {
        debugPrint( "\(file.joined(separator: ".")) not found")
        return
    }
    player = nil
    player = AVPlayer(url: URL(fileURLWithPath: path))
    player?.actionAtItemEnd = .none
    player?.isMuted = false
    player?.volume = 0.2

    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    playerLayer.zPosition = -1

    playerLayer.frame = view.frame

    view.layer.addSublayer(playerLayer)

    player?.play()
    print("222")

    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: .main) { _ in
        self.player?.seek(to: kCMTimeZero)
        self.player?.play()
    }
}
}

AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
    // Override point for customization after application launch.
    IQKeyboardManager.shared.enable = true
    IQKeyboardManager.shared.enableAutoToolbar = false
    return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.

}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    print("000")
    let ll: ViewController = ViewController()
    ll.test()
}

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.


}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}

您可以在 ViewController 中使用 UIApplicationDidBecomeActive UIApplicationWillResignActive 作为 -

NotificationCenter.default.addObserver(self, selector: #selector(appBecomeActive), name: .UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appResignActive), name: .UIApplicationWillResignActive, object: nil)

@objc func appBecomeActive() {
   player.play()//Play video
}

@objc func appResignActive() {
    player.pause()//pause video
}

https://developer.apple.com/documentation/uikit/uiapplication/1622953-didbecomeactivenotification

您可以在 AppDelgate 方法中创建新实例,但这不是实现它的好方法。

在你的 ViewController class 中。您可以添加将通知您的观察者,您可以执行任何操作

NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationDidBecomeActive, object: nil, queue: .main) {[weak self] (noti) in
    guard let strongSelf = self  else {return }

   // DO here whatever you want 
}  

它会在您的应用激活时调用。