Skip to content

Instantly share code, notes, and snippets.

@ftp27
Created October 23, 2019 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftp27/8f28449c4f60f564d576c5a7cbdd7475 to your computer and use it in GitHub Desktop.
Save ftp27/8f28449c4f60f564d576c5a7cbdd7475 to your computer and use it in GitHub Desktop.
import Foundation
func getData(_ urlString: String) -> Data? {
guard let url = URL(string: urlString) else { return nil }
return try? Data(contentsOf: url)
}
struct Result {
var comments: Int
var words: Int
var characters: Int
var nextPage: String?
mutating func append(_ new: Result) {
comments += new.comments
words += new.words
characters += new.characters
nextPage = new.nextPage
}
}
func parse(data: Data?) -> Result? {
guard let data = data else { return nil }
guard let root = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return nil }
let next = root["nextPageToken"] as? String
guard let items = root["items"] as? [[String: Any]] else { return nil }
let comments = items.compactMap { (dict) -> String? in
guard let snippet = dict["snippet"] as? [String: Any] else { return nil }
guard let topLevelComment = snippet["topLevelComment"] as? [String: Any] else { return nil }
guard let snippet2 = topLevelComment["snippet"] as? [String: Any] else { return nil }
return snippet2["textDisplay"] as? String
}
var words = 0
var symbols = 0
for comment in comments {
words += comment.split(separator: " ").count
symbols += comment.count
}
return Result(comments: comments.count, words: words, characters: symbols, nextPage: next)
}
func collect() -> Result? {
let key = ""
let maxResults = 100
let textFormat = "plainText"
let videoId = ""
let part = "snippet"
let url = "https://www.googleapis.com/youtube/v3/commentThreads" +
"?key=\(key)" +
"&textFormat=\(textFormat)" +
"&maxResults=\(maxResults)" +
"&videoId=\(videoId)" +
"&part=\(part)"
guard var result = parse(data: getData(url)) else { return nil }
while result.nextPage != nil {
guard let new = parse(data: getData(url + "&pageToken=\(result.nextPage!)")) else { break }
result.append(new)
}
return result
}
print(collect())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment