简体   繁体   English

Swift Json Tableview落后

[英]Swift Json Tableview laggy

I have a problem. 我有个问题。 I have this code in Swift but when i scrolling in the tableview its very laggy and i dont know what the problem is..?? 我在Swift中有这段代码,但是当我在tableview中滚动时,它非常缓慢,我不知道问题出在什么地方。 Its downloading image data that is like 20mb each (i think).. 它的下载图像数据每个大约20mb(我认为)。

Thanks! 谢谢!

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)
}

The problem because of this line 由于这条线的问题

 let data = NSData(contentsOf: (imgURL as? URL)!)

it blocks the main thread , you have to run it in other queue , beside it re downloads the image every scroll ( no cache ) so it's better to use SDWebImage 它阻塞了主线程,您必须在其他队列中运行它,此外,它每次滚动时都会重新下载图像(没有缓存),因此最好使用SDWebImage

cell.imgView.sd_setImage(with: URL(string: "http://www.example.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))

This will always lag. 这将始终滞后。 Your requesting image in main thread. 您在主线程中的请求图像。

Try to use SDWebCache Library : https://github.com/rs/SDWebImage . 尝试使用SDWebCache库: https : //github.com/rs/SDWebImage

1 : It will cachce intially image and will avoid multiple HTTP requests. 1:它将最初缓存图像,并避免多个HTTP请求。

2 : Works in background so will not affect the main thread. 2:在后台运行,因此不会影响主线程。

Use method imageview.sd_imageFromUrl(URL(....)!) 使用方法imageview.sd_imageFromUrl(URL(....)!)

It's very clear. 很清楚 You asking the Image data from main thread. 您从主线程询问图像数据。 Whenever you perform timeconsuming operation on the Main Thread, then the App will be laggy. 每当您在主线程上执行耗时的操作时,该应用程序就会变得迟钝。

let data = NSData(contentsOf: (imgURL as? URL)!)

The best solution that worked for me so far is using AlamofireImage or Kingfisher. 到目前为止,对我来说最好的解决方案是使用AlamofireImage或Kingfisher。 That needs you to learn about adding library into your project. 这需要您学习有关将库添加到项目中的知识。 Try to use Cocoapods for convenience. 为了方便起见,请尝试使用可可豆。

I assume you were able to use Cocoapods here. 我认为您可以在这里使用Cocoapods。

In case you want to caching support, Kingfisher comes first. 如果您想缓存支持,Kingfisher排在第一位。 Caching means you will need to make Request to server only for the first time or if something changed. 缓存意味着您仅需要在第一次或发生更改时才向服务器发出请求。 It will save your resources etc. All you need to do is importing Kingfisher module in ViewController then it automatically extend UIImageView capability with Kingfisher extension kf 它将节省您的资源,等等。您要做的就是在ViewController中导入Kingfisher模块,然后使用Kingfisher扩展kf自动扩展UIImageView功能。

Here is the sample code 这是示例代码

//ViewController.swift
import Kingfisher

// Your cellForRowAt
...
if let url = URL(string: imgURLArray[indexPath.row]) {
    cell.imgView.kf.setImage(with: url)
}
...

Kingfisher will perform caching strategy under the hood so you can focus on the app. Kingfisher将在后台执行缓存策略,因此您可以专注于该应用程序。

In order to put default image which will be very usefull to inform user about the image, (user expects there is something in blank white box -- UIImageView while image is nil -- in their screen isn't?) Kingfisher helps you with placeholder 为了放置默认图像,这对于通知用户有关图像的信息非常有用(用户希望空白的白框中有一些东西-UIImageView而图像为零时不在屏幕上吗?)Kingfisher可以帮助您使用placeholder

let defaultImage = UIImage(named: "default_img")!
cell.imgView.kf.setImage(with: url, placeholder: defaultImage)

Get the complete insight about Kingfisher here Kingfisher's Github Page 在此处获得有关翠鸟的完整见解翠鸟的Github页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM