swift 2.0中使用NSJSONSerialization需要处理异常,否则会报错。具体的使用方式如下:
func loadDataSource() { let url = NSURL(string: APIURL) let request = NSURLRequest(URL: url!) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response, data, error) -> Void in
if error != nil { print(error) return } do { if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
if let newsArray = json["item"] as? NSArray { var newsItems = [NewsItem]() for item in newsArray { let newsItem = NewsItem() newsItem.id = item["id"] as? String newsItem.title = item["title"] as? String newsItem.thumb = item["thumb"] as? String newsItems.append(newsItem) } //在主线程中更新数据 dispatch_async(dispatch_get_main_queue(), { () -> Void in self.dataSource = newsItems self.tableView.reloadData() })
} } } catch let error as NSError { print("error:\(error)") } catch { //默认错误 print("解析数据出现异常") }
} } |
官网参考: