Swift,Firebase:创建用户后实时数据库中没有数据

时间:2018-11-09 17:47:11

标签: swift firebase firebase-realtime-database

使用Xcode 10.1,Swift 4.2和Firebase ##

使用以下代码将数据上传到Firebase后,我看不到实时数据库中的数据:

static func createUser(username: String, email: String, password: String, imageData: Data, onSuccess: @escaping () -> Void, onError: @escaping (_ error: String?) -> Void) {

    Auth.auth().createUser(withEmail: email, password: password) { (data, error) in
        if let err = error {
            onError(err.localizedDescription)
            return
        }
        // User erfolgreich erstellt
        guard let uid = data?.user.uid else { return }
        self.uploadUserData(uid: uid, username: username, email: email, imageData: imageData, onSuccess: onSuccess)
    }
}

static func uploadUserData(uid: String, username: String, email: String, imageData: Data, onSuccess: @escaping () -> Void) {


    let storageRef = Storage.storage().reference().child("profile_image").child(uid)

    storageRef.putData(imageData, metadata: nil) { (metadata, error) in
        if error != nil {
            return
        }
    }

    storageRef.downloadURL(completion:  { (url, error) in
        if  error != nil {
            print(error!.localizedDescription)
            return
        }

        let profilImageURL = url?.absoluteString


        let ref = Database.database().reference().child("users").child(uid)
        ref.setValue(["username" : username, "email" : email, "profileImageURL": profilImageURL ?? "Kein Bild vorhanden"])

    })
     onSuccess()
}

firebase中的设置:

The settings in firebase

应该以正确的方式工作。我已经查看了Firebase文档,但没有找到更多信息。

1 个答案:

答案 0 :(得分:1)

该图像是否上传到Cloud Storage?如果可以,但是下载URL没有写入数据库,我猜是因为在生成下载URL之前没有上传数据。由于上载函数是异步的,因此应从闭包中调用downloadURL函数。

static func uploadUserData(uid: String, username: String, email: String, imageData: Data, onSuccess: @escaping () -> Void) {

    let storageRef = Storage.storage().reference().child("profile_image").child(uid)

    storageRef.putData(imageData, metadata: nil) { (metadata, error) in
        if error != nil {
            return
        }
        storageRef.downloadURL(completion:  { (url, error) in
        if  error != nil {
            print(error!.localizedDescription)
            return
        }
     onSuccess()
    }
}