Swift 2 : 调用可以抛出,但是没有标记'try',错误没有被处理

Swift 2 : Call can throw, but it is not marked with 'try' and the error is not handled

我从 Swift 2 开始,我在尝试完成一个尝试使用 iTunes API 的功能时遇到此错误。

    func searchItunesFor(searchTerm: String) {
    let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)

    if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
        let urlPath = "http://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software"
        let url = NSURL(string: urlPath)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
            print("Task completed")
            if(error != nil) {
                print(error!.localizedDescription)
            }
            var err: NSError?
            if let jsonResult = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                if(err != nil) {
                    print("JSON Error \(err!.localizedDescription)")
                }
                if let results: NSArray = jsonResult["results"] as? NSArray {
                    dispatch_async(dispatch_get_main_queue(), {
                        self.tableData = results
                        self.appsTableView!.reloadData()
                    })
                }
            }
        })

        task.resume()
    }
}

我得到错误:“”调用可以抛出,但它没有用 'try' 标记并且错误没有被处理“”在这一行

if let jsonResult = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
            if(err != nil) {

这个问题的解决方案是什么? 谢谢

那是因为并非所有 NSData 都可以转换为 JSON 对象。将 JSON 解析部分替换为:

do {
    if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? NSDictionary {
        dispatch_async(dispatch_get_main_queue(), {
            self.tableData = results
            self.appsTableView!.reloadData()
        })
    }
} catch let jsonError as NSError {
    print(jsonError.localizedDescription)
}

你也可以这样使用.. 使用,ObjectMapper,SwiftyJSON,Alafir

        guard let jsonResponce = try? JSON(data: data) else {
            print("\n\n\n\n error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
            failure("error")
            return
        }