问题
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.
I've authenticated the user using Google Sign-In for iOS with the scope
"https://www.googleapis.com/auth/youtube.force-ssl"
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.
回答1:
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.
This is the example of a JSON body provided in the documentation for adding a comment:
{
"snippet": {
"channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
"topLevelComment": {
"snippet": {
"textOriginal": "This video is awesome!"
}
},
"videoId": "MILSirUni5E"
}
}
Let's build a parameters dictionary based on the above example, it is a nested dictionary:
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]
Then create your headers, your request and pass the parameters to the request
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.
来源:https://stackoverflow.com/questions/50412254/insert-a-comment-using-the-youtube-api-and-alamofire