ios - Firebase 不将 URL 返回给 Swift

标签 ios iphone swift firebase firebase-realtime-database

我正在开发一款社交媒体应用。我已经创建了个人资料页面。我将它连接到我的 Firebase 数据库。但我希望从数据库中加载个人资料图片。

在我的数据库中有一个个人资料图片 url(这是 firebase 存储 url),我想从数据库中获取它并在个人资料图片上表示图像。

我还创建了 3 个操作请求。当用户单击可用的照片 3 选项时。

从图库中选择新照片

使用相机拍摄新照片

显示照片

因此我也希望我的图像被传递到另一个 View

这是一些代码:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    profilePic.layer.cornerRadius = profilePic.frame.size.width/2
    profilePic.clipsToBounds = true
    getImages()

}


func getImages(){
    if FIRAuth.auth()?.currentUser?.uid==nil{
        self.performSegue(withIdentifier: "logOutSegue", sender: self)
    } else {
        let uid = FIRAuth.auth()?.currentUser?.uid
        databaseRef.child("Users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
            if let dict = snapshot.value as? NSDictionary{
                let ImageUrl = dict["Profpic"] as? String
                print(ImageUrl)
                let url = URL(string: ImageUrl!)
                print(url)
                URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
                        if error != nil{
                            print(error?.localizedDescription)
                            return
                        }
                        DispatchQueue.main.async {
                            self.profilePic?.image = UIImage(data: data!)
                        }
                }).resume()
            }
        })
    }
}


@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    self.profilePic.image = image
    picker.dismiss(animated: true, completion: nil)
}


func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}



@IBAction func changePic(_ sender: Any) {

    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self

    let actionSheet = UIAlertController(title: "Foto Kaynağı", message: "Bir kaynak seçin", preferredStyle: .actionSheet)

    actionSheet.addAction(UIAlertAction(title: "Kameranla yeni bir fotoğraf çek", style: .default, handler: { (action:UIAlertAction) in

        if UIImagePickerController.isSourceTypeAvailable(.camera){
            imagePickerController.sourceType = .camera
            self.present(imagePickerController, animated: true, completion: nil)
        }
        else {
            print("Camera not available")
        }
    }))

    actionSheet.addAction(UIAlertAction(title: "Galeriden yeni bir fotoğraf seç", style: .default, handler: { (action:UIAlertAction) in
        imagePickerController.sourceType = .photoLibrary
        self.present(imagePickerController, animated: true, completion: nil)
    }))

    actionSheet.addAction(UIAlertAction(title: "Fotoğrafı Göster", style: .default, handler: { (action:UIAlertAction) in
        self.performSegue(withIdentifier: "showProfilePic", sender: self)
    }))

    actionSheet.addAction(UIAlertAction(title: "Geri Dön", style: .cancel, handler: nil))
    self.present(actionSheet, animated: true,completion: nil)

}



@IBAction func saveClicked(_ sender: Any) {
    let imageName = NSUUID().uuidString
    let storedImage = storageRef.child("Profile Pictures").child(imageName)
    if let uploadData = UIImagePNGRepresentation(self.profilePic.image!){
        storedImage.put(uploadData, metadata: nil, completion: { (metadata, error) in
            if error != nil {
                print(error?.localizedDescription)
                return
            }
            storedImage.downloadURL(completion: { (url, error) in
                if error != nil {
                    print(error?.localizedDescription)
                    return
                }
                if let urlText = url?.absoluteString{
                    self.databaseRef.child("Users").child((FIRAuth.auth()?.currentUser?.uid)!).updateChildValues(["ProfPic" : urlText], withCompletionBlock: { (error, ref) in
                        if error != nil{
                            print(error?.localizedDescription)
                            return
                        }
                    })
                }
            })
        })
    }
}

最佳答案

这是一个例子。我使用字典获取 URL,然后通过 sd_setImage 命令将 UIImageView 设置为图像。

注意:使用 Firebase 时,您不必使用 URLSessionDispatchQueue

if let dictionary = snapshot.value as? [String: AnyObject] {
       self.usernameLbl.text = dictionary["userName"] as? String
       self.genderLbl.text = dictionary["gender"] as? String
       self.ageLbl.text = dictionary["age"] as? String
       self.bioLbl.text = dictionary["bio"] as? String
       self.weightLbl.text = dictionary["weight"] as? String
       self.heightLbl.text = dictionary["name"] as? String

       let stringURL = NSURL(string: dictionary["profileImg"] as! String)
       self.profileImg.sd_setImage(with: stringURL as URL?)

            }

关于ios - Firebase 不将 URL 返回给 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47964276/

相关文章:

ios - 如何使用代码在模拟器上模拟不良的互联网连接

ios - xcode 4.5 iOS Storyboard 和 UITableView delegate 混淆

ios - 分析被禁用。事件未记录

ios - 在片段着色器中计算纹理坐标(iOS/OpenGL ES 2.0)

arrays - Swift 3 - 使类可迭代

uitableview - 将 UITableView 滚动到下一个 TableView 然后停止 - SWIFT iOS8

iphone - 我想知道如何创建动态 TableView

iphone - 创建一个调整纵向和横向渲染大小的 iPhone 网站

iphone - 找出谁下载了 iPhone 应用程序

ios - 符合协议(protocol)的 UIView 子类的 Swift 数组