如何从Firebase存储中获取imageUrl并将其存储在Xcode 10 Swift 4.2中的Firebase数据库中

时间:2018-10-11 06:55:35

标签: swift xcode firebase xcode10 swift4.2

这是我正在使用的代码

@objc func handleSignUp() {
        guard let email = emailTextField.text, email.characters.count > 0 else { return }
        guard let username = usernameTextField.text, username.characters.count > 0 else { return }
        guard let password = passwordTextField.text, password.characters.count > 0 else { return }

    Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
         if let err = error {
            print("Failed to create user:", err)
            return
        }
        print("Successfully created user:", user?.user.uid)
        //            guard let image = self.plusPhotoButton.imageView?.image else { return }
        //            guard let uploadData = UIImageJPEGRepresentation(image, 0.3) else { return }
        guard let uploadData = self.plusPhotoButton.imageView?.image?.jpegData(compressionQuality: 0.3) else{return}

        let filename = NSUUID().uuidString
        Storage.storage().reference().child("profile_images").child(filename).putData(uploadData, metadata: nil, completion: { (metadata, err) in
             if let err = err {
                print("Failed to upload profile image:", err)
                return
            }

//此代码不适用于swift4.2   // guard let profileImageUrl =元数据?.downloadURL()?. absoluteString else {return}

            func getDownloadURL(from path: String, completion: @escaping (URL?, Error?) -> Void) {
                let storageReference = Storage.storage().reference(forURL: "gs://instagramfirebase-60be5.appspot.com")

                let storageRef = storageReference.child(path).downloadURL(completion: completion)
            }
            print("Successfully uploaded profile image")//,profileImageUrl

            guard let uid = user?.user.uid else { return }
            let dictionaryValues = ["username": username] as [String : Any]//, "profileImageUrl": profileImageUrl
            let values = [uid: dictionaryValues]

            Database.database().reference().child("users").updateChildValues(values, withCompletionBlock: { (err, ref) in

                if let err = err {
                    print("Failed to save user info into db:", err)
                    return
                }

                print("Successfully saved user info to db")
            })
        })
    })
}

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

通过在图片上传的结尾处使用以下代码,您可以轻松获得下载网址:

storageRef.downloadURL(completion: { (url, error) in
    if let err = error{
       // error happened - implement code to handle it
       print(err)
    } else {
       // no error happened; so just continue with your code
       print(url?.absoluteString) // this is the actual download url - the absolute string
    }

请注意:请不要单独存储downloadURL,因为Firebase可以更改downloadURL的令牌,建议您始终保留完整的存储路径。

希望我能提供帮助。