我正在使用 YouTube API 从 channel 获取视频,我想获取标题:
let url = URL(string: "https://www.googleapis.com/youtube/v3/search?key=**********&channelId=UCFNHx0ppCqm4EgPzEcOc29Q&part=snippet,id&order=date&maxResults=50")
let task = URLSession.shared.dataTask(with: url!) { (data, reponse, error) in
if error != nil {
print("ERROR")
}else{
if let content = data {
do{
if let myJsonArray = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any] {
if let itemsJson = myJsonArray["items"] as? [[String:Any]] {
//var i:Int = 0
for i in 0 ..< itemsJson.count {
print("-----------------------------")
let snippetDict = itemsJson[i]["snippet"] as! Dictionary<NSObject, AnyObject>
print(snippetDict["title"] as String) //NOT WORKING
}
}
}
}catch{
print("ERROR 2")
}
}
}
}
task.resume()
但是当我将所有标题打印为 print(snippetDict["title"] as String)
时,Xcode 说:
ambiguous reference to member 'subscript'`.
如何获取视频的标题?
谢谢!
最佳答案
尝试使用 String
作为您的 key (而不是 NSObject
):
let snippetDict = itemsJson[i]["snippet"] as! [String: AnyObject]
我怀疑冲突是由这两个引起的Dictionary
下标(当使用 String
作为键时):
subscript(key: NSObject) -> Value?
subscript(key: _Hashable) -> Value?
不过,如果您的字典是基于字符串的,那么您应该使用String
键入它。反正 key :)
顺便说一句,[Key: Value]
只是语法糖更长的Dictionary<Key, Value>
明确的类型名称。
关于ios - 使用 YouTube API 获取 YouTube 视频的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43984138/