如何创建用户个人资料图像

Posted

技术标签:

【中文标题】如何创建用户个人资料图像【英文标题】: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

                     

【问题讨论】:

【参考方案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

以上是关于如何创建用户个人资料图像的主要内容,如果未能解决你的问题,请参考以下文章

如何通过应用程序中的表单为用户创建个人资料?我正在使用 laravel 8

快速从 imageView.image 创建 jpeg 图像

我应该如何使用 Laravel 提供图像?

如果用户未在 api 调用中上传个人资料图片,如何更新用户数据

使用 usermanager 编辑用户个人资料图像

如何:在注册/创建时设置 Firebase 用户的个人资料信息? (颤动网络)