Created
October 23, 2019 23:13
-
-
Save ftp27/8f28449c4f60f564d576c5a7cbdd7475 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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