ios - 快速加载图片时整个应用程序滞后
问题描述
您好,当我从服务器加载图片时,我的应用程序滞后。如果没有大量延迟,我无法滚动或转到下一个视图控制器。我试图用 DispatchQueue 方法来做这件事,DispatchQueue.main.async
我OperationQueue,main.addQueue
只能等待。在左侧,我可以看到最后一个视图控制器。
这是我的代码
func fetchData(uiView: UIView) {
let urlString = URL(string: "https://mydomain/assats/php/Random.php")!
let task = URLSession.shared.dataTask(with: urlString) { (data, response, error) in
guard let data = data, error == nil else {
debugPrint("Fehler beim Laden von \(urlString)", String(describing: error))
return
}
let JSONData = try? JSONDecoder().decode([Pics].self, from: data)
OperationQueue.main.addOperation {
let currentWidthScroll: Int = (100 / 1) - (100 / 1) + (1 * 0) + (1 * 0) + 0
let currentHighScroll: Int = (100 / 1) - (100 / 1) + (1 * 100) + (1 * 5) + 21
let screensize: CGRect = UIScreen.main.bounds
let screenWidth = screensize.width
let screenHeight = screensize.height
var scrollView = UIScrollView()
scrollView = UIScrollView(frame: CGRect(x: CGFloat(currentWidthScroll), y: CGFloat(currentHighScroll), width: screenWidth, height: screenHeight))
self.view.addSubview(scrollView)
if JSONData == nil {
let alert = UIAlertController(title: "Error", message: "You can't see much here because you don't Follow anybody", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
else {
for x in 0..<JSONData!.count {
OperationQueue.main.addOperation {
print(x)
let currentWidth: Int = (100 / 1) - (100 / 1) + (x * 0) + (x * 0) + 10
let currentHigh: Int = (100 / 1) - (100 / 1) + (x * 500) + (x * 5) + 80
let stackView = UIStackView(frame: CGRect(x: CGFloat(currentWidth), y: CGFloat(currentHigh), width: 350, height: 500))
stackView.alignment = .fill
stackView.distribution = .fillEqually
stackView.axis = .vertical
scrollView.contentSize = CGSize(width: 0, height: currentHigh + 650)
scrollView.addSubview(stackView)
let urlKey = "http://instapy.ddns.net/User/\(JSONData![x].Benutzername)/Posts/Photos/\(JSONData![x].Pic)"
let imgView = UIImageView(frame: CGRect(x: CGFloat(currentWidth), y: CGFloat(currentHigh), width: 350, height: 500))
imgView.image = UIImage(named: urlKey)
imgView.contentMode = .scaleAspectFit
stackView.addArrangedSubview(imgView)
if let url = URL(string: urlKey) {
do{
let data = try Data(contentsOf: url)
imgView.image = UIImage(data: data)
}catch let err {
print("Error: \(err.localizedDescription)")
}
}
}
}
}
}
};task.resume()
}
我在 viewDidLoad() 中加载函数
解决方案
问题就在这里
let data = try Data(contentsOf: url)
上面的行不应该在主队列中,因为它会阻止它,我想你需要一个 tableView 而不是 scrollView + stackView 并最好通过SDWebImage加载带有它们的 url 的图像
推荐阅读
- html - 具有最大列数的 CSS Grid 具有动态子项
- node.js - 打字稿覆盖 .env 文件设置
- ruby-on-rails - 无法将未经许可的参数转换为哈希
- node.js - api 调用受到另一个 api 调用验证的影响
- http - okhttp 发送错误 HTTP 消息,多个请求标头?
- python - 如何在python中将XML文件转换为PDF
- scala - scala spark job在失败时给出了奇怪的异常
- android - Android中RecyclerView的Textview AutoSizing
- tableau-api - Tableau 动态地图标签
- c++ - 如何正确设置高电压触发抓取?