我是swift 2的初学者,我没有发现问题。错误在这一行:
let jsonDictionary try NSJSONSerialization.JSONObjectWithData = (data!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary
func searchItunesFor(searchTerm: String) {
let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let urlPath: String = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software"
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(url, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
do {
if let ipString = NSString(data:data!, encoding:NSUTF8StringEncoding){
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary
let results: NSArray = jsonDictionary["results"] as NSArray
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.appsTableView?.reloadData()
})
}
}catch{
print("Bad ")
}
}).resume()
答案 0 :(得分:0)
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
答案 1 :(得分:0)
我希望这可以帮助一些人,即使它有点晚了:
此处的问题是您尝试将JsonObject
转换为Dictionary
而不是NSDictionary
。
因此,您只需在代码中将Dictionary
替换为NSDictionary
即可。这应该照顾错误。
Swift 2
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
Swift 3
let jsonDictionary = try JSONSerialization.JSONObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
答案 2 :(得分:0)
在Swift 3中为我工作的是定义字典键值类型。
if let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary<String, String>{
// something happens here
}
注意该行末尾的NSDictionary<String, String>
。
如果您的对象看起来像这样,当然:
{
"someProp" : "some value",
"someOtherProp" : "some other value"
}
如果您不知道自己获得的价值,可能是任何对象使用NSDictionary<String, Any>