【问题标题】:How to create a user profile image如何创建用户个人资料图像
【发布时间】:2019-12-06 16:49:42
【问题描述】:

当我的用户注册时,他的所有用户信息都会直接进入 Firebase 存储和数据库(例如:用户名和个人资料图片)。当我的用户注册时,用户名出现在他的个人资料上,但没有出现个人资料图片如何修复此代码以更改它? 我需要我的用户注册时使用的个人资料图片才能在他的个人资料屏幕上弹出

 import Firebase

class InteractivViewController: UIViewController {
    @IBOutlet weak var UsernameText: UILabel!

    @IBOutlet weak var ProfileImage: UIImageView!

    @IBOutlet weak var DisplayText: UILabel!

    var DatabaseRef: DatabaseReference!
    override func viewDidLoad() {
        super.viewDidLoad()

       DatabaseRef = Database.database().reference()

  if let userID = Auth.auth().currentUser?.uid {
        DatabaseRef.child("users").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
          // Get user value
          let dictionary = snapshot.value as? NSDictionary
         let username = dictionary?["username"] as? String ?? "username"
          if let profileImageUrl = dictionary?["photo"] as? String {

              func getProfileImage(uid: String, success: @escaping (UIImage?)->Void)
          {

              let storageRef = Storage.storage().reference().child("usersImages")
              storageRef.child("\(uid).jpg").getData(maxSize: 1024*1024) { (data, error) in
                  guard let data = data else {return}
                  DispatchQueue.main.async {
                      success(UIImage(data: data))

                  getProfileImage(uid: userID) { image in
                      self.ProfileImage.image = image
                   }
              }
          }
              }
            func upload(image: UIImage, to firebasePath: String, completion: @escaping (String?, Error?) -> Void) {
                //... creates data from the image...
                var data = NSData()
                //Compress the image by any percent
                data = image.jpegData(compressionQuality: 0.8)! as NSData
                //...sets the upload path
                let filePath = "\(Auth.auth().currentUser!.uid)0)" // path where you wanted to store img in storage
                print(filePath)
                let metaData = StorageMetadata()
                metaData.contentType = "image/jpg"

                let storageRef = Storage.storage().reference().child(filePath)
                storageRef.putData(data as Data, metadata: metaData){(metaData,error) in
                    if let error = error {
                        print(error.localizedDescription)
                        completion(nil, error)
                        return
                    } else {
                        storageRef.downloadURL(completion: { (url, error) in
                            //Returns the url string to the newly uploaded image so that we can set the user's photoURL database property to this string
                            Database.database().reference().child(firebasePath).setValue(url!.absoluteString)
                            completion(url!.absoluteString, nil)
                        })
                    }
                }

            let image = UIImage(named: "someImage")
            upload(image: image!, to: "Users/\(Auth.auth().currentUser!.uid)/photoUrls/0", completion: { urlString, error in
                Database.database().reference().child("Users/\(Auth.auth().currentUser!.uid)/photoUrls/0").setValue(urlString)
            },
                Database.database().reference().child("Users/\(Auth.auth().currentUser!.uid)/photoUrls/0").observeSingleEvent(of: .value) { (snapshot) in
                    let urlString = snapshot.value as! String
                    let task = URLSession.shared.dataTask(with: URL(string: urlString)!) {(data, response, error) in

                        if let image: UIImage = UIImage(data: data!) {
                            DispatchQueue.main.async {
                                //update the image
                                self.ProfileImage.image = image
                            }
                        }
                    }
                    task.resume()
                }
                   )}

            }


                                   self.UsernameText.text = username
                                       self.DisplayText.text = username


                                       return

                     }

【问题讨论】:

    标签: ios swift firebase user-interface firebase-realtime-database


    【解决方案1】:

    您必须使用从 firebase 检索到的 url 并使用他们的 Storage API 下载它

    let storage = Storage.storage()
    let storageRef = storage.reference()
    let ref = storage.reference(forURL: profileImageUrl)
    ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
       if let error = error {
         // Uh-oh, an error occurred!
      } else {
    
         self.ProfileImage = UIImage(data: data!)
        self.view.addSubview(self.ProfileImage)
        self.reloadInputViews()
      }
     }
    

    【讨论】:

      【解决方案2】:

      您需要将指向存储桶中引用的 url 存储在数据库中的用户对象中。这是我使用的函数,它采用 UIImageString 表示 Firebase 路径并返回上传图片的 URL:

      func upload(image: UIImage, to firebasePath: String, completion: @escaping (String?, Error?) -> Void) {
          //... creates data from the image...
          var data = NSData()
          //Compress the image by any percent
          data = UIImageJPEGRepresentation(image, 0.8)! as NSData
          //...sets the upload path
          let filePath = "\(Auth.auth().currentUser!.uid)0)" // path where you wanted to store img in storage
          print(filePath)
          let metaData = StorageMetadata()
          metaData.contentType = "image/jpg"
      
          let storageRef = Storage.storage().reference().child(filePath)
          storageRef.putData(data as Data, metadata: metaData){(metaData,error) in
              if let error = error {
                  print(error.localizedDescription)
                  completion(nil, error)
                  return
              } else {
                  storageRef.downloadURL(completion: { (url, error) in
                      //Returns the url string to the newly uploaded image so that we can set the user's photoURL database property to this string
                      Database.database().reference().child(firebasePath).setValue(url!.absoluteString)
                      completion(url!.absoluteString, nil)
                  })
              }
          }
      }
      

      要上传图片并更新数据库中的用户对象,您可以这样做:

      let image = UIImage(named: "someImage")
      upload(image: image, to: "Users/\(Auth.auth().currentUser!.uid)/photoUrls/0", completion: { urlString, error in
          Database.database().reference().child("Users/\(Auth.auth().currentUser!.uid)/photoUrls/0").setValue(urlString)
      }
      

      然后,您可以通过以下方式抓取图像:

      Database.database().reference().child("Users/\(Auth.auth().currentUser!.uid)/photoUrls/0").observeSingleEvent(of: .value) { (snapshot) in
          let urlString = snapshot.value as! String
          let task = URLSession.shared.dataTask(with: URL(string: urlString)!) {(data, response, error) in
      
              if let image: UIImage = UIImage(data: data!) {
                  DispatchQueue.main.async {
                      //update the image
                      self.ProfileImage.image = image
                  }
              }
          }
          task.resume()
      }
      

      【讨论】:

      • Database.database().reference().child("Users/(Auth.auth().currentUser.uid)/photoUrls/0").observeSingleEvent(of: .value) { (快照)在让 urlString = snapshot.value as! String let task = URLSession.shared.dataTask(with: URL(string: urlString)!) {(data, response, error) in if let image: UIImage = UIImage(data: data!) { DispatchQueue.main.async { / /更新图像 self.ProfileImage.image = image } } } task.resume() } ERROR
      • 调用中的额外参数
      • 我不在家,但这是用于已部署应用程序的代码,我们对此没有任何问题。它可能没有正确应用。有时间我看看能不能给你修改一下
      • 我真的很感激
      • 这是一个链接,解释了您如何错误地实施它。这是一个简单的 Swift 格式化的东西。 pastebin.com/zj2ugaLy
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多