我正在尝试从NSDictionary调用数据,但收到错误。
这是我收到的错误:
Cannot subscript a value of type '[NSDictionary]' with an index of type 'String'
我不确定在将NSEictionary通过密钥后从NSDictionary检索密钥的正确方法。我正在使用JSONSerialization将api json设置为字典。问题是,当我不使用tableview或collection view的indexpath时,如何从NSDictionary检索数据?
这是Apple文档中显示的示例:
let value = dictionary["helloString"]
这是我的prepareForSegue代码:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailsSegue" {
if let details = segue.destination as? DetailsView {
if let film = sender as? [NSDictionary]? {
details.films = film
}
}
}
}
这是我的详细信息查看代码:
import UIKit
import AFNetworking
class DetailsView: UIViewController {
let homepage = FilmsViewController()
var films: [NSDictionary]?
var videos: [NSDictionary]?
@IBOutlet var detailsImage: UIImageView!
@IBOutlet var detailsTitle: UILabel!
@IBOutlet var releaseDate: UILabel!
@IBOutlet var overview: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
detailsTitle.text = films?["title"] as? NSString
loadFilms()
}
}
我也尝试过:
detailsTitle.text = films?["results]["title"] as? NSString
在另一个ViewController上的CollectionView中,它的工作方式为:
film = films?[indexPath.row]
title = film?["title"]
正在通过此代码和AFNetworking解析NSDictionary:
////////Parse Film API//////////////////
func loadFilms() {
let apiKey = "97a0d64910120cbeae9df9cb675ad235"
let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)&language=en-US&page=1")
let request = URLRequest(
url: url! as URL,
cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData,
timeoutInterval: 10 )
let session = URLSession (
configuration: URLSessionConfiguration.default,
delegate: nil,
delegateQueue: OperationQueue.main
)
let task = session.dataTask(with: request, completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let resposeDictionary = try! JSONSerialization.jsonObject(with: data, options:[]) as? NSDictionary {
self.films = resposeDictionary["results"] as? [NSDictionary]
print("response: \(resposeDictionary)")
}
}
})
task.resume()
}
//////////End Parse Film API///////////////////
这是JSON。我正在尝试访问密钥:
{
"id": 335983,
"results": [
{
"id": "5a7c6a35c3a3680f7f01053a",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "dzxFdtWmjto",
"name": "VENOM - Official Teaser Trailer (HD)",
"site": "YouTube",
"size": 1080,
"type": "Teaser"
},
{
"id": "5a7cd5389251414b22019912",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "MDR3bfmzV8c",
"name": "VENOM - Teaser Trailer - In Cinemas October 4",
"site": "YouTube",
"size": 1080,
"type": "Teaser"
},
答案 0 :(得分:0)
因为视频是一系列词典。首先,您必须使用for或foreach循环解析数组,然后才能访问键值对。并且不要使用NSDictionary,而是尝试使用Dictionary或[String:Any]用法。示例如下
var videos: [Dictionary<String,Any>] = [
["key":"val1"],
["key":"val2"],
["key":"val3"]
]
videos.forEach { (dict) in
print(dict["key"] ?? "")
}
答案 1 :(得分:0)
在您的示例中,您具有视频词典数组。您要访问播放视频按钮。为此,可以对现有代码进行一些更改。
假设您必须使用一些呈现视频列表的列表UI组件。在每个列表项中都有播放按钮。您需要给标签打按钮,它可以是该项目列表的索引,如果您使用的是TableView,则可以将indepath.row用作按钮的标签。
此后,您需要对播放按钮的操作进行以下更改
@IBAction func playVideo(_ sender: UIButton) {
let video = videos![sender.tag]
let movieId = video["key"]
let video = AVPlayer(url: "https://www.youtube.com/watch?v=\(movieId)"
let videoPlayer = AVPlayerViewController()
videoPlayer.player = video
present(videoPlayer, animated: true, completion: {
video.play()
})
}
我也试图在评论中解释同一件事。
答案 2 :(得分:0)
我对此的最终答案是将所有内容从NSDictionary转换为快速的4 Codable数据结构