AVPlayer Swift: How do I hide controls and disable

2019-09-09 06:49发布

问题:

since this is my first post, just a few words about me: Usually I design stuff (UI primarily) but I really wanted to take a leap into programming to understand you guys better. So I decided build a small app to get going.

So I've been trying to figure this out for hours now – this is my first app project ever so I apologise for my newbyness.

All I want to do is to hide the controls of AVPlayer and disable landscape view but I just can't figure out where to put showsPlaybackControls = false.

import UIKit
import AVKit
import AVFoundation


class ViewController: UIViewController {


    private var firstAppear = true

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if firstAppear {
            do {
                try playVideo()
                firstAppear = false
            } catch AppError.InvalidResource(let name, let type) {
                debugPrint("Could not find resource \(name).\(type)")
            } catch {
                debugPrint("Generic error")
            }

        }
    }

    private func playVideo() throws {
        guard let path = NSBundle.mainBundle().pathForResource("video", ofType:"mp4") else {
            throw AppError.InvalidResource("video", "m4v")
        }
        let player = AVPlayer(URL: NSURL(fileURLWithPath: path))
        let playerController = AVPlayerViewController()
        playerController.player = player
        self.presentViewController(playerController, animated: false) {
            player.play()
        }
    }
}

enum AppError : ErrorType {
    case InvalidResource(String, String)
}

回答1:

showsPlaybackControls is a property of AVPlayerViewController, so you can set it after you create it:

playerController.showsPlaybackControls = false

If you want to allow only landscape, you can subclass AVPlayerViewController, override supportedInterfaceOrientations and return only landscape, then use that class instead of AVPlayerViewController.

UPDATE

As mentioned in the comments, if you go to the documentation for AVPlayerViewController you'll find a warning that says:

Do not subclass AVPlayerViewController. Overriding this class’s methods is unsupported and results in undefined behavior.

They probably don't want you to override playback-related methods that could interfere with the behavior, and I would say that overriding only supportedInterfaceOrientations is safe.

However, if you want an alternative solution, you can create your own view controller class that overrides supportedInterfaceOrientations to return landscape only, and place the AVPlayerViewController inside that view controller.



标签: ios xcode swift