第三方应用和服务如何调用 VidHub API播放影片

概述

第三方应用和服务的开发者可以利用 VidHub 的视频播放功能,使用 URL 方案播放视频。还支持 x-callback,允许在操作完成后返回另一个应用。
可用平台:iPhone、iPad

使用示例

播放单个文件,完成后返回另一个应用程序

open-vidhub://x-callback-url/open?
on-success=some-app://x-callback-url/success&
on-failed=some-app://x-callback-url/failed&
url=http://localhost:8080/sample.mp4

播放添加了外部字幕的单个文件

open-vidhub://x-callback-url/open?
on-success=some-app://x-callback-url/success&
on-failed=some-app://x-callback-url/failed&
url=http://localhost:8080/sample.mp4&
sub=http://localhost:8080/sample.srt

URL编码

根据 x-callback-url 规范,所有查询字符串值都应是经过URL编码的。未编码的URL在某些情况下可能有效,但在使用具有多个参数的操作或具有多个键的URL时,您可能需要手动对URL进行编码。

未编码的URL

http://localhost:8080/Movies/movie.mkv

经过编码的URL

http%3A%2F%2Flocalhost%3A8080%2Fsample.mp4

第三方集成示例

第三方应用可以调用此方法将视频文件或字幕传递到VidHub播放

func openWithVidHub(url: URL, subUrl: URL? = nil) {
    let urlString = url.isFileURL ? url.path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) : url.absoluteString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    // Create with URLComponents
    var components = URLComponents()
    components.scheme = "open-vidhub"
    components.host = "x-callback-url"
    components.path = "/open"
    var queryItems: [URLQueryItem] = [URLQueryItem]()
    queryItems.append(URLQueryItem(name: "url", value: urlString))
    
    // subtitles, optional
    if let subUrl = subUrl, 
        let subUrlString = subUrl.isFileURL ? subUrl.path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) : subUrl.absoluteString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed){
      queryItems.append(URLQueryItem(name: "sub", value: subUrlString))
    }
    
    // Optionally, you can also add callback urls in queryItems
    queryItems.append(URLQueryItem(name: "on-success", value: "mySchema://x-callback-url/success".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)))
    queryItems.append(URLQueryItem(name: "on-failed", value: "mySchema://x-callback-url/failed".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)))
    
    components.queryItems = queryItems
    
    guard let vidHubURL = components.url else {
      return
    }

    debugPrint("Open with VidHub: \(vidHubURL.absoluteString)")

    UIApplication.shared.open(vidHubURL, options: [:], completionHandler: nil)
  } 

同时可以调用 scene(_:openURLContexts:) 来处理来自 VidHub 的回调方法

  func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else {
      return
    }
    // Process api call from VidHub
    // mySchema://x-callbacksw-url/success or mySchema://x-callback-url/failed
    if url.scheme == "mySchema" {
      if url.host == "x-callback-url" {
        if url.path == "/success" {
          // Handle success
          debugPrint("Success")
        } else if url.path == "/failed" {
          // Handle failed
          debugPrint("Failed")
        }
      }
    }    
  }