【发布时间】:2018-04-07 16:00:13
【问题描述】:
我有问题。我在 Swift 中有这段代码,但是当我在 tableview 中滚动时它非常滞后,我不知道问题是什么......?? 它下载的图像数据每个大约 20mb(我认为)..
谢谢!
func downloadJsonWithTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 200)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData)
}).resume()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.nameLabel.text = nameArray[indexPath.row]
cell.dobLabel.text = dobArray[indexPath.row]
let imgURL = NSURL(string: imgURLArray[indexPath.row])
if imgURL != nil {
let data = NSData(contentsOf: (imgURL as? URL)!)
cell.imgView.image = UIImage(data: data as! Data)
}
return cell
}
///for showing next detailed screen with the downloaded info
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
vc.imageString = imgURLArray[indexPath.row]
vc.imageString2 = imgURL2Array[indexPath.row]
vc.imageString3 = imgURL3Array[indexPath.row]
vc.imageString4 = imgURL4Array[indexPath.row]
vc.imageString5 = imgURL5Array[indexPath.row]
vc.imageString6 = imgURL6Array[indexPath.row]
vc.nameString = nameArray[indexPath.row]
vc.dobString = dobArray[indexPath.row]
vc.txtString = txtArray[indexPath.row]
vc.contactString = contactArray[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
【问题讨论】:
-
可能与每个20mb有关
-
旁注 - 不要在 Swift 中使用
NSURL或NSData。永远,永远不要使用NSData(contentsOf:)来加载远程数据。 -
@rmaddy 谢谢!我对此很陌生,但我应该改用什么?
-
您必须始终异步加载远程数据。通常这是通过 URLSession 完成的。但是对于带有缓存的远程表格视图图像,SDWebImage 似乎是一个流行的实用程序。
标签: ios json swift uitableview