繁体   English   中英

ImageView 只能在主线程中使用

[英]ImageView must be used from main thread only

我从我的 firebase 数据库中获取一个 url 来下载图像,并且在主线程中的 cell.articleImage.image = UIImage(data: data) 上收到此错误,它没有崩溃,但不会返回图像,有谁知道会出什么问题?

override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        DispatchQueue.global().async {
            let v = UIView(frame: .zero)
        }

    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell") as? articlesCell else {
            return UITableViewCell()}

        let article = articleArray[indexPath.row]

        let url = URL(string: article.imageURL)!
        DispatchQueue.global().async {
            do{
                let data = try Data(contentsOf: url)
                DispatchQueue.global().sync {
                    cell.articleImage.image = UIImage(data: data)
                }
            } catch {

            }
        }



       // cell.articleImage.sd_setImage(with: url, placeholderImage: UIImage(named: "issaimage"))
        cell.configureCell(title: article.ArticleTitle, author: article.author, date: article.date)

        return cell
    }

你在全局而不是主队列中执行此操作,因此请更改此设置

DispatchQueue.global().sync {
      cell.articleImage.image = UIImage(data: data)
}

DispatchQueue.main.sync {
       cell.articleImage.image = UIImage(data: data)
}

//

同样, SDWebImage是最好的,因为这种方法每次滚动都会下载图像

//

也在你的viewDidLoad

DispatchQueue.global().async { // should be in main queue 
   let v = UIView(frame: .zero)  // whatever UI is here 
}

试试这个方法

func openImageGallery() {
    DispatchQueue.main.async {
        self.picker.delegate = self
        self.picker.allowsEditing = true
        self.picker.sourceType = .photoLibrary
        self.present(self.picker, animated: true, completion: nil)
    }
    
}

暂无
暂无

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

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