如何在Firebase中保存网址之前摆脱“可选”一词?

时间:2018-08-22 15:18:42

标签: ios swift firebase

当前,我正在保存存储在Firebase数据库中的图像的url。但是我在URL之前得到了可选的词。如下面所示。

  

“可选(https:URL.HERE)”

以下是进行保存的代码块:

if let imageData = UIImageJPEGRepresentation(image, 0.8) {
    let metadata = storageRef //.child("poop/")

    let uploadTask = metadata.putData(imageData, metadata: nil) { (metadata, error) in
        guard let metadata = metadata else {
            // Uh-oh, an error occurred!
            return
        }

        // You can also access to download URL after upload.
        storageRef.downloadURL { (url, error) in
            guard let downloadURL = url else {
                // Uh-oh, an error occurred!
                return
            }
            let imgURL = url

            //database integration
            let ref = Database.database().reference()
            let usersRef = ref.child("usersPosts")

            let uid = Auth.auth().currentUser?.uid
            let newUserRef = usersRef.child(uid!)
            //creates a child for email and password (i think we shud store password so we can tell sumone what it is inmediatly, maybe)
            newUserRef.setValue(["Image": "\(imgURL)"])
        }

    }

    // For progress
    uploadTask.observe(.progress, handler: { (snapshot) in
        guard let progress = snapshot.progress else {
            return
        }

        let percentage = (Float(progress.completedUnitCount) / Float(progress.totalUnitCount))
        progressBlock(Double(percentage))
    })

} else {
    completionBlock(nil, "Image could not be converted to Data.")
}

1 个答案:

答案 0 :(得分:5)

您将获得Optional...,因为imgURL是可选的。 imgURL是可选的,因为您是从url分配的,这是可选的。

由于您已经在url语句中解包了guard,因此只需使用downloadURL而不是创建imgURL

删除:

let imgURL = url

imgURL代替downloadURL的使用,urlguard中正确解包的newUserRef.setValue(["Image": "\(downloadURL)"]) 的版本。

Popen