【发布时间】:2017-10-08 03:41:44
【问题描述】:
我在我的代码中使用http://www.omdbapi.com/?t=pulp+fiction IMDB api 来处理“低俗小说”。
应用程序中有一个搜索栏,我在这个搜索栏上写“低俗小说”然后输入。 我得到这个错误。
无法将“__NSDictionaryM”(0x1055952b0) 类型的值转换为 'NSString' (0x1023e3c60)。
ViewController.swift:
//
// ViewController.swift
// IMDB Api Project
//
// Created by gurkan on 5.05.2017.
// Copyright © 2017 gurkan. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var directorLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var actorsLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchForMovie(title: searchBar.text!)
searchBar.text = ""
}
func searchForMovie(title: String){
//http://www.omdbapi.com/?t=pulp+fiction
if let movie = title.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed){
let url = URL(string: "http://www.omdbapi.com/?t=\(movie)")
let session = URLSession.shared
let task = session.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
} else {
if data != nil {
do {
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
as! String //Error Line!
let jsonString = jsonResult.components(separatedBy: "")
let jsonDict = jsonString as! Dictionary<String,String>
DispatchQueue.main.async {
print(jsonDict)
}
} catch {
}
}
}
})
task.resume()
}
}
}
我该如何解决这个问题?
【问题讨论】:
-
您的 JSON 是字典,而不是字符串。
-
我像字典一样尝试过,但我之前遇到过错误。那么如何解决呢?全部代码是什么?
标签: ios json swift swift3 imdb