我知道这个问题可能是重复的。但我试图在权益溢出中找出这个解决方案。不幸的是,我没有找到正确的答案。这是我所做的。
我试图使用alamofire访问Youtube数据。 在我看来DidLoad
let API_KEY = "**************"
let UPLOADS_PLAYLIST_ID = "PLqQMDoH89jqEoHMTsxxyMz1Hym_pOViq6"
let CHANNEL_ID = "UCcMUpFCaFhlyjZyy9d9LeRA"
let parameters = ["part":"snippet","channelId":CHANNEL_ID,"playListId":UPLOADS_PLAYLIST_ID,"key":API_KEY]
Alamofire.request("https://www.googleapis.com/youtube/v3/playlists", parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if let JSON = response.result.value{
for video in JSON["item"] as! NSArray {
print(video)
}
}
}
它给我错误类型"任何"没有下标成员
我也在尝试另一种方式,但这也给了我错误
Alamofire.request("https://www.googleapis.com/youtube/v3/playlists",
parameters: parameters, encoding: URLEncoding.default, headers:
nil).responseJSON { (response) in
switch(response.result) {
case .success(_):
if let JSON = response.result.value as! [[String : Any]]!{
for video in JSON["item"] as! NSArray {
print(video)
}
}
break
case .failure(_):
print("There is an error")
break
}
}
它给出了一个错误,并告诉不能用字符串类型的索引下标类型"[[字符串:任何]]"的值
在这里发布:if let JSON = response.result.value as! [[String : Any]]!
第一:如果您使用可选的链接(if let
(,请不要使用强制转换(as!
和[[String : Any]]!
(。
其次,您的 JSON 不是Dictionary
,而是Dictionaries
的Array
。
请尝试:if let JSON = response.result.value as? [String : Any]
另外,当您尝试时
if let JSON = response.result.value{
for video in JSON["item"] as! NSArray {
print(video)
}
}
您不会将变量JSON
强制转换为Dictionary
,而只是检查JSON
是否不为零。
您不能在任何变量类型上重新转换,您可以使用 [String:[String:Any]] 进行转换