如何更快地加载用户的个人资料照片(Firebase,swift)

时间:2017-11-28 09:54:48

标签: ios swift swift4

我在我的ProfileViewController的viewDidLoad中有这个

 self.user = Auth.auth().currentUser
      self.databaseRef.child("user_profiles").child(self.user!.uid).observeSingleEvent(of: .value) { (snapshot:DataSnapshot) in

          let snapshotValue = snapshot.value as? NSDictionary


        if(snapshotValue?["about"] != nil)
        {

        }

        if(snapshotValue?["profile_pic"] != nil)
        {
            let databaseProfilePic = snapshotValue!["profile_pic"]
                as! String

            let data = try? Data(contentsOf: URL(string: databaseProfilePic)!)

            self.setProfilePicture(imageView: self.profilePic,imageToSet: UIImage (data:(data!))!)
        }

还有这个功能

 internal func setProfilePicture(imageView:UIImageView,imageToSet:UIImage)
    {

        imageView.layer.cornerRadius = 22.5
        imageView.layer.borderColor = UIColor.white.cgColor
        imageView.layer.masksToBounds = true
        imageView.image = imageToSet

    }

加载经过身份验证的用户的个人资料照片。我唯一的问题是,每次我进入我的ProfileViewController,加载图片需要3-4秒,而我想在Instagram,whatsapp等,图像已经加载,所以没有这样烦人的等待时间。我该怎么办?

1 个答案:

答案 0 :(得分:1)

对于快速下载图片异步,您可以使用此library

您可以使用较少的代码行下载图像

if(snapshotValue?["profile_pic"] as? String != nil) {
   if let imgUrl = URL(string:snapshotValue?["profile_pic"] as! String) 
   {
       self.profilePic.kf.setImage(with: imgUrl)
       self.profilePic.layer.cornerRadius = min(self.profilePic.frame.height,self.profilePic.frame.width) / 2 //you can change the cornerRadius according to your need
       self.profilePic.layer.borderColor = UIColor.white.cgColor
       self.profilePic.layer.masksToBounds = true
   }
}

希望这会对你有所帮助

相关问题