Swift 4.您能否建议返回应用程序后如何播放视频?

时间:2018-07-23 08:57:20

标签: ios swift avplayer

我在电话视图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:.
}

}

2 个答案:

答案 0 :(得分:2)

您可以将UIApplicationDidBecomeActive中的UIApplicationWillResignActive ViewController用作-

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

答案 1 :(得分:1)

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

在您的<template> <main> <a :href="item.link"></a> <img :src="item.image.url" alt=""> <footer> <h2>{{ item.title }}</h2> <div class="author">{{ item.creator }}</div> </footer> </main> <main v-if="index"> <a :href="item.link"></a> <img :src="item.image.url" alt=""> <footer> <h2>{{ item.title }}</h2> <div class="author">{{ item.creator }}</div> </footer> </main> <main v-if="index + 1" class="highligths2"> <a :href="item.link"></a> <img :src="item.image.url" alt=""> <footer> <h2>{{ item.title }}</h2> <div class="author">{{ item.creator }}</div> </footer> </main> </template> <script> export default { name: 'childcard', props: { item: { type: Object, required: true }, index: { type: Number // required: true } } }; </script> 类中。您可以添加将通知您的观察者,并且您可以执行任何操作

ViewController

当您的应用激活时,它将被调用。