ios - 异步加载图像到自定义 UITableViewCell 部分工作

标签 ios swift firebase tableview uitableview

我的图像不会加载到 ImageView 中,直到您将单元格从表格上滚动并重新打开,或者转到另一个 View 并返回到该 View (重绘单元格)。

如何让它们正确加载?

/////////

我的 viewDidLoad 里面有这个:

    tableView.delegate = self
    tableView.dataSource = self

    DispatchQueue.global(qos: .background).async {
        self.getBusinesses()

        DispatchQueue.main.async {

            self.tableView.reloadData()


        }
    }

我在 viewDidLoad 中调用的 .getBusinesses 函数中调用函数下载图像:

func getBusinesses() -> Array<Business> {

    var businessList = Array<Business>()
    //let id  = 1
    let url = URL(string: "**example**")!
    let data = try? Data(contentsOf: url as URL)
    var isnil = false

    if data == nil{
        isnil = true
    }
    print("is nill is \(isnil)")


    if(data == nil){
        print("network error")
        businessList = []
        return businessList
    }
    else{
        values = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
    }

    let json = JSON(values)

    var i = 0;
    for (key, values) in json {

        var businessReceived = json[key]
        let newBusiness = Business(id: "18", forename: "", surname: "", email: "", password: "", business: true, level: 1, messageGroups: [], problems: [])

        newBusiness.name = businessReceived["name"].stringValue
        newBusiness.description = businessReceived["description"].stringValue
        newBusiness.rating = Int(businessReceived["rating"].doubleValue)
        newBusiness.category = businessReceived["category"].intValue
        newBusiness.distance =  Double(arc4random_uniform(198) + 1)
        newBusiness.image_url  = businessReceived["image"].stringValue
        newBusiness.url  = businessReceived["url"].stringValue
        newBusiness.phone  = businessReceived["phone"].stringValue
        newBusiness.postcode  = businessReceived["postcode"].stringValue
        newBusiness.email = businessReceived["email"].stringValue
        newBusiness.id = businessReceived["user_id"].stringValue

        if(newBusiness.image_url  == ""){
            newBusiness.getImage()

        }
        else{
            newBusiness.image = #imageLiteral(resourceName: "NoImage")
        }


        if(businessReceived["report"].intValue !=  1){
            businessList.append(newBusiness)

        }
    }

    businesses = businessList

    print(businesses.count)
    holdBusinesses = businessList
    return businessList

}

在业务对象中,我有这种方法从 url 下载图像并将其存储在业务对象的图像属性中:

 func getImage(){

    if(self.image_url != ""){

        print("runs imageeee")
        var storage = FIRStorage.storage()

        // This is equivalent to creating the full reference
        let storagePath = "http://firebasestorage.googleapis.com\(self.image_url)"
        var storageRef = storage.reference(forURL: storagePath)




        // Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
        storageRef.data(withMaxSize: 30 * 1024 * 1024) { data, error in
            if let error = error {
                // Uh-oh, an error occurred!
            } else {
                // Data for "images/island.jpg" is returned
                self.image = UIImage(data: data!)!
                print("returned image")
            }
        }


    }
    else{

        self.image = #imageLiteral(resourceName: "NoImage")

    }

}

然后我将它输出到这里的 TableView 中:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell  = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for : indexPath) as! BusinessesViewCell


            cell.businessImage.image = businesses[(indexPath as NSIndexPath).row].image


            //.............  

     return cell
}

最佳答案

            self.image = UIImage(data: data!)!

应该变成

    DispatchQueue.main.async {
         self.image = UIImage(data: data!)!
    }

内部

    storageRef.data(withMaxSize: 30 * 1024 * 1024) { data, error in

编辑:我最初的想法是下载逻辑在单元格内,现在我知道不是了。

你要么每次到达时都需要在 tableView 上调用 reloadData()

         self.image = UIImage(data: data!)!

或者更好的是找出你刚刚更新的索引,然后调用

  tableView.reloadRows:[IndexPath]

关于ios - 异步加载图像到自定义 UITableViewCell 部分工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43680633/

相关文章:

ios - 是否可以在 Firebase 中使用电子邮件和电话号码进行身份验证?

java - 如何使用 RETROFIT 库发布原始 JSON 对象

javascript - Firebase:如何将表单数据提交到不同的集合?

ios - 仪器停止在 iPhone 应用程序上工作

ios - 设置 map 中心和缩放以适合所有坐标

swift - 如何基于类中的其他属性创建变量属性

ios - 您通常使用类或结构来定义实用程序功能列表吗?

swift - 是否可以将 NSData(从 NSKeyedArchiver 获得)保存为 NSString,然后作为 NSData 读回?

ios - 如何选择 UITextField 中的所有文本?

ios - CoreStore 重新获取谓词 NSFetchRequest 问题