【发布时间】:2020-01-08 06:41:51
【问题描述】:
我正在尝试将来自 YouTube 数据 API 的数据解析为 swift 字符串。因此,我使用 Alamofire 以及 SwiftyJSON。但是,SwiftyJSON 不解析任何内容,并且我收到一个错误 “Unexpectedly found nil while unwrapping an Optional value”。
我的 API 调用
YTDataService.fetchDetails(forVideo: videoId, parts: [VideoPart.statistics, VideoPart.contentDetails], onDone: {(details) in
// details is of Type JSON
let videoDuration = details["items"]["contentDetails"]["duration"].string! // not parsing
let videoViews = details["items"]["statistics"]["viewCount"].string! // not parsing
print(videoDuration, videoViews)
})
})
来自 YouTube 的 JSON 响应
{
"kind": "youtube#videoListResponse",
"etag": "\"8jEFfXBrqiSrcF6Ee7MQuz8XuAM/UwkUogFGo4AZoBzZtd5t6Tj8wk0\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"8jEFfXBrqiSrcF6Ee7MQuz8XuAM/qsX1KSuT5vhpp29lsFl_1l6uvWE\"",
"id": "Dkk9gvTmCXY",
"contentDetails": {
"duration": "PT3M31S",
"dimension": "2d",
"definition": "hd",
"caption": "true",
"licensedContent": true,
"projection": "rectangular"
},
"statistics": {
"viewCount": "129895203",
"likeCount": "3178074",
"dislikeCount": "266720",
"favoriteCount": "0",
"commentCount": "230345"
}
}
]
}
如您所见,我正确地尝试解析数据 - 但由于某种原因,SwiftyJSON 无法正确解析数据。
我们将不胜感激!
【问题讨论】:
-
items 是可以数组而不是字典。您不能直接从中获取 contentDetails。
-
天哪.... 肯定在这上面花了太多时间????将其发布为答案,我会将其标记为正确:) 谢谢@PGDev
-
添加了答案。试试看。
标签: ios json swift youtube-data-api swifty-json