简体   繁体   中英

How to fetch images by their uid's Swift Firebase?

I am trying to show all images that the current user posts. As you can see in the picture in a table view, every time the current user post an image it automatically creates a unique id for the image under the current user information.

截图

In this images, You will see that when the users post an image it create a node called media for the image with their children.

截图

Here's my code:

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


    FIRDatabase.database().reference().child("users").child(FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: { (snapshot) in
    // check if user has photo
    if snapshot.hasChild("media") != nil{
        print("found it")

     //set image locatin
    let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\("media")"


    FIRStorage.storage().reference().child(filePath).data(withMaxSize: 10*1024*1024, completion: { (data, error) in

    let userPhoto = UIImage(data: data!)
    cell.Myimages.image = userPhoto

    })

    }
    else {
        print("nil")
        }
        })

        return cell


    }}

The media in your users node is stored as a NSDictionary, not as a String. You will have to loop through the media node to get the paths of all your files. You can do something like

//Create reference to media directly instead
FIRDatabase.database().reference().child("users").child(FIRAuth.auth()!.currentUser!.uid).child("media").observeSingleEvent(of: .value, with: { (snapshot) in
  if let media = snapshot.value as? NSDictionary {

    //Loop thorugh all the entries in your media node to get all the media paths
    for (_, value) in media {
      FIRStorage.storage().reference().child("media").child(value as! String)

      //get the file now that you have the reference
    }
  }
})

如果您想将图像添加到特定的ID,然后将图像上传到Firebase存储,则以绝对字符串形式获取image.downloadurl,并将此值添加到对象的“ image”键中,然后将该对象发布到Firebase数据库中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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