首页 > 解决方案 > 从 firebase 获取 UI 图像与在 .text 中获取 UI 标签有何不同,以及从图像获取中产生的潜在问题是什么?

问题描述

我已成功获取 UI 标签并显示它,但不确定如何获取图像。

我试图为图像复制粘贴相同的框架,但它说你不能使用字符串作为这种形式的图像:

let x = y?["PhotoPost"]

////Here is what I have for the label: 

public  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell

    let person: Userx = people[indexPath.row]

    cell.lblName.text = person.Education

    table.dataSource = self
    table.delegate = self

    return cell

}

databaseRef.observe(DataEventType.value,  with: {snapshot in

    if snapshot.childrenCount>0{


        self.people.removeAll()

        for people in snapshot.children.allObjects as! [DataSnapshot] {
            let peopleObject = people.value as? [String: AnyObject]
            let peopleEducation = peopleObject?["Education"]
            let peoplePhotoPosts = peopleObject?["PhotoPosts"]
            let peopl = Userx(Education: peopleEducation as! String?, PhotoPosts: peoplePhotoPosts as AnyObject)
                self.people.append(peopl)

        }
        self.table.reloadData()


    }

})

////这是我为图片摆姿势的初步代码

import SDWebImage.  

///installed in pod already

cell.imageView?.image = UIImage(named: "il_570xN.1325825023_m2nl")

    if let PhotoPosts = person.PhotoPosts {
        let url = URL(string: PhotoPosts)
        cell.imageView?.sd_setImage(with: url)
        URLSession.shared.dataTask(with: (url)!, completionHandler: {(data, response, error) in

        if error != nil {
            print(error as Any)
            return


        }

        DispatchQueue.main.async{
            cell.imageView?.image = UIImage(data: data!)
        }

    }).resume()

    }

    return cell

}

我也有 PhotoPosts 显然被设置为 Dictionary 而不是 String 的问题。我不确定它会在哪里设置为字典,因为在这个文件和它的类中,它都是字符串。

标签: iosswiftxcodefirebase

解决方案


1-这应该在viewDidLoad

table.dataSource = self
table.delegate = self

2-像投

let peopleObject = people.value as! [String: Any]
let peopleEducation = peopleObject?["Education"] as! String
let peoplePhotoPosts = peopleObject?["PhotoPosts"]  as! [String:Any]
print(peoplePhotoPosts)

3- 使用SDWebImage显示远程图像


这个

let databaseRef = Database.database().reference().child("people")

是一个通用 url,它将为您应用程序中的每个用户返回相同的内容,而不是您需要此数据库结构

> People
  > Uid
    >Education:""
    > so on

然后使用

let userID = Auth.auth().currentUser!.uid
databaseRef = Database.database().reference().child("people/\(userID)")

推荐阅读