ios - ImageView 只能在主线程中使用

标签 ios swift firebase uiimageview uiimage

我从我的 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 
}

关于ios - ImageView 只能在主线程中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51487600/

相关文章:

ios - 为什么使用 UI GraphicsContext 裁剪图像时会出现白边?

ios - 自定义 iOS 应用启动画面

swift - 如何修复深层 if-else 嵌套

swift - 使用委托(delegate)方法在两个类之间发送数据

android - 应用程序关闭时 Firebase 作业调度程序未执行

ios - 在 dealloc 之后检查回调中的对象

ios - MPMoviePlayerController 旋转

swift - 为什么我不能快速删除 NSUserDefaults 键?

ios - 使用 firebase 和 Objective C 不接收推送通知

android - 通过随机键检索子值-Firebase