swift2 Swift 2:调用可以抛出,但未标记为“try”,并且未处理错误

cwtwac6a  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(150)

我从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) {

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

nzk0hqpo

nzk0hqpo1#

这是因为不是所有的NSData都可以转换成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)
}
93ze6v8z

93ze6v8z2#

**您也可以使用类似的方法..**使用、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
        }

相关问题