2017-04-25 89 views

回答

2

嵌入YouTube現場直播到您的iOS應用程序中使用下列內容:

@IBOutlet weak var LiveStreamViewer: UIWebView! 
    let channelID = "[channelID]" 

    func loadLiveStream { 
     guard 
      let youtubeURL = URL(string: "https://www.youtube.com/embed? 
       live=1&channel=\(channelID)") 
      else { return } 
     LiveStreamViewer.loadRequest(URLRequest(url: youtubeURL)) 
    } 

然而,使用這種會彈出如果您實際上並未進行流式傳輸,並且有人試圖播放視頻,則WebView中會出現錯誤。要計劃添加類似於以下功能的東西:

let googleAPI = "[youtubeAPIKey]" 


    func checkLive() { 
     let liveChannel = URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=\(channelID)&type=video&eventType=live&key=\(googleAPI)") 
     URLSession.shared.dataTask(with:liveChannel!, completionHandler: {(data, response, error) in 
      guard let data = data, error == nil else { return } 

      do { 
       let parsedData = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any] 
       let pageInfo = parsedData["pageInfo"] as! [String:Any] 

       print(pageInfo) 

       let currentState = pageInfo["totalResults"] as! Int 
       print(currentState) 

       if currentState == 0 { 
        print("No Stream Right Now") 
        self.LiveStreamViewer.isHidden = true 
        //DO SOMETHING TO LET THEM KNOW YOU ARENT STREAMING 
       } else { 
        print("Streaming") 
        self.LiveStreamViewer.isHidden = false 
        self.loadLiveStream() 
       } 

      } catch let error as NSError { 
       print(error) 
      } 
     }).resume() 
    } 
+0

這是否需要用戶登錄他的YouTube帳戶? – bhakti123

相關問題