如何从 AVPlayer iOS 中的 url 检测视频不存在状态

How to detect Video does not exist state from url in AVPlayer iOS

我正在 AVPlayer 中播放来自 url 的视频。它工作正常。但是,很少有视频一直在加载而不是播放器,我在浏览器中检查了它们,它们显示 视频不存在

因此,如何检测视频不存在状态以及如何显示警报以供最终用户理解。

override func viewDidLoad() {
        
        super.viewDidLoad()
        self.setupAVAudioSession()
        
    }

  func playVideo(){
        
        if let str = videoUrl{
            
            if let videoURL:URL = URL(string: str) {
                
                player = AVPlayer(url: videoURL)
                player?.rate = 1 //auto play
                let playerFrame = CGRect(x: 0, y: 0, width: 200, height: 210)
                let playerViewController = AVPlayerViewController()
                playerViewController.delegate = self
                playerViewController.player = player
                playerViewController.view.frame = playerFrame
                playerViewController.showsPlaybackControls = true
                addChild(playerViewController)
                videoPlayerView.addSubview(playerViewController.view)
            }
        }
    }

 func setupAVAudioSession(){
        
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
        }
        catch {
            print("Setting category to AVAudioSessionCategoryPlayback failed.")
        }
    }

func playerViewController(_ playerViewController: AVPlayerViewController, willBeginFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator){
}

func playerViewController(_ playerViewController: AVPlayerViewController, willEndFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator){
    playerViewController.dismiss(animated: true)
}

有什么建议吗?

我还没有从移动端得到任何修复,所以,我们已经从后端修复了这个。

您可以在开始播放之前发送 HEAD 请求来检查您的视频 url 是否存在,例如:

var request = URLRequest(url: url)
request.httpMethod = "HEAD"
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) { data, response, error in
    guard error == nil,
        let r = response as? HTTPURLResponse,
        r.statusCode == 200
    else {
        print("url is not valid")
        return
    }
    
    print("url is valid")
}
task.resume()