使用YouTube API和Alamofire插入评论

问题描述:

感谢您抽出宝贵的时间阅读本文档.我对如何使用YouTube API插入评论感到困惑.我对使用API​​还是很陌生,因此在他们的文档.

Thanks for taking the time to read this. I'm confused on how to insert a comment using the YouTube API. I'm fairly new to using APIs, so I don't quite get what they are saying to do in their documentation.

我已使用 iOS的Google登录进行身份验证具有范围

"https://www.googleapis.com/auth/youtube.force-ssl"

,用于插入评论.但是现在,我必须实际插入注释,并且(如我所说)我不知道该怎么做,因为我必须在请求正文中提供资源.我正在使用Alamofire进行请求,并使用Swift 4作为我的语言.如果有人可以帮助我,我将不胜感激.

which is required to insert a comment. But now, I have to actually insert the comment and (like I've said) I don't understand how to do that because I have to provide a resource in the request body. I'm using Alamofire for the request and Swift 4 as my language. I would highly appreciate it if someone could help me.

正如我在另一篇文章中看到的( Google API-无效的凭据),您知道如何发出经过身份验证的Alamofire请求.现在,您需要构建适当的参数字典来满足API要求.我查看了YouTube数据API指南.

As I saw in your other post (Google API - Invalid Credentials) you know how to make an authenticated Alamofire request. Now you need to build a proper parameters dictionary to meet the API requirements. I looked into the Youtube Data API guide.

这是文档中提供的用于添加注释的JSON正文的示例:

{
  "snippet": {
   "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
   "topLevelComment": {
    "snippet": {
      "textOriginal": "This video is awesome!"
    }
   },
   "videoId": "MILSirUni5E"
  }
 }

让我们根据以上示例构建参数字典,它是一个嵌套字典:

let commentParams: Parameters = ["textOriginal": "This video is awesome!"]
let snippetParams: Parameters = ["snippet": commentParams]
let topLevelSnippet: Parameters = [
        "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
        "topLevelComment": snippetParams,
        "videoId": "MILSirUni5E"]

let allParams: Parameters = ["snippet": topLevelSnippet]

然后创建标题,您的请求并将参数传递给请求

let headers: HTTPHeaders = ["Authorization": "Bearer \(token)"]
// As API requires "part" is added as url parameter
let path = "https://www.googleapis.com/youtube/v3/commentThreads?part=snippet"
let request = Alamofire.request(path, method: HTTPMethod.post, parameters: allParams, encoding: JSONEncoding.default, headers: headers)

您应该检查哪些参数是强制性的,哪些不是必需的,但其想法是根据其要求构建适当的参数字典.

You should check which parameters are mandatory and which ones are not, but the idea is to build a proper parameters dictionary based on their requirements.