Swift - AVPlayer 加载失败,出现错误 域=NSURLError域代码=-999 "cancelled"



我尝试从url字符串播放视频。但我在题目上犯了一些错误。

我在下面尝试这个代码。videoPath是一个url字符串。

let videoURL = URL(string: videoPath)
let player = AVPlayer(url: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}

以下是错误日志:

加载失败,出现错误Domain=NSURLErrorDomain Code=-999"cancelled"UserInfo={NSErrorFailingURLStringKey=http://b…a.mp4,NSErrorFailingURLKey=http://b。。。a.mp4,_NSURLError相关URLSession任务ErrorKey=("LocalDataTask<841B2FFA-479B-4E5A-9BD3-D9207EAA0D32>。<2>"(,_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask<841B2FFA-479B-4E5A-9BD3-D9207EAA0D32><2> ,NSLocalizedDescription=已取消}[-999]

我设置了info.plist--

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>www.example.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>

注意:问题出现在10分钟以上的视频中。这是正常的吗?

您是否试图在viewDidLoad中显示AVPlayerViewController?如果是这样的话,您可以在视图控制器的视图添加到窗口层次结构后尝试呈现它,例如viewDidAppear。请记住,当您导航回控制器时,将调用viewDidAppear,并且将再次触发模式演示。

URL是否需要设置cookie?我也遇到了丢失饼干的问题。您可以尝试在匿名窗口中打开url进行检查。如果它仍然运行良好,那么也许你可以通过-进行调试

使用URL创建AVURLAsset对象,例如-
AVURLAsset(url: <URL>, options:[]),并将resourceLoader委托设置为self。类似urlAsset?.resourceLoader.setDelegate(self, queue: .main)并实现功能

func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
return true
}
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForRenewalOfRequestedResource renewalRequest: AVAssetResourceRenewalRequest) -> Bool {
return true
}
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) {
}
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForResponseTo authenticationChallenge: URLAuthenticationChallenge) -> Bool {
return true
}
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel authenticationChallenge: URLAuthenticationChallenge) {
}

但如果它确实需要cookie-在AVURLAsset对象中设置它们,例如 let asset = AVURLAsset(url: videoURL, options: ["AVURLAssetHTTPHeaderFieldsKey": ["Cookie": "<YOUR TOKEN>"]])

原因可能是视频中的元数据错误。看看我回答的这个线程:AVPlayer HLS直播IOS

转码后的视频需要具有profile baseline才能在AVPlayer中播放。查看ffmpeg转码命令了解详细信息:

https://gist.github.com/chungnguyen/d88e73e3cc8788878f5ffb8c232b4729

NSErrorFailingURLKey=http://b。。。a.mp4不管你有什么ATS,前缀为"http"的url总是失败。请访问我在这里的答案

最新更新