【问题标题】:ImageView must be used from main thread onlyImageView 只能在主线程中使用
【发布时间】:2018-12-31 10:12:48
【问题描述】:

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

【问题讨论】:

    标签: ios swift firebase uiimageview uiimage


    【解决方案1】:

    你在全局而不是主队列中做,所以改变这个

    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 
    }
    

    【讨论】:

    • 它只是返回空白图像
    • 然后你的网址有问题,复制一个互联网图片网址,硬编码,然后检查
    • 网址有问题,感谢您为我提供的所有帮助
    【解决方案2】:

    试试这个方法

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多