Swift 2:Call可以抛出,但没有标记为'尝试'并且不处理错误

时间:2016-04-01 22:23:17

标签: json swift swift2 itunes

我从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()
    }
}

我收到错误:""通话可以抛出,但没有标记为'尝试'并且没有处理错误""在这一行

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

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

2 个答案:

答案 0 :(得分:2)

那是因为并非所有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)
}

答案 1 :(得分:-2)

您也可以使用像这样的东西.. 使用,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
        }