如何从Firebase存储中删除照片

时间:2017-09-30 13:11:05

标签: ios firebase swift3 xcode8 firebase-storage

我在用户可以登录时开发应用,在用户个人资料页面中,用户可以选择要在我的应用中显示的图片资料。此图片上传到Firebase数据库并存储在Firebase存储中。 我希望用户可以决定删除他当前的图像配置文件。 我无法找到方法,如何从Firebase存储中删除他的图片,我使用元数据将其存储在存储中。

这是我在Firebase存储和Firebase数据库中上传图片的代码:

// Create a path in order to save the photo in Firebase Database
func setUser(img: String) {
    var userUid = Auth.auth().currentUser?.uid
    let userData = ["nickname": Auth.auth().currentUser?.displayName, "userImg": img]

    KeychainWrapper.standard.set(userUid!, forKey: "uid")
    let location =                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Database.database().reference().child("users").child(userUid!).child("pseudo")
    location.setValue(userData)
    dismiss(animated: true, completion: nil)
}

// Upload and put image profile in the Firebase Storage
func uploadImg() {
    name = Auth.auth().currentUser?.displayName
    userUid = Auth.auth().currentUser?.uid

    guard let img = userImagePicker.image, imageSelected == true else {
        print("Image needs to be selected")
        return
    }

    if let imgData = UIImageJPEGRepresentation(img, 0.2) {
        let imgUid = NSUUID().uuidString
        let metadata = StorageMetadata()
        metadata.contentType = "image/jpeg"

        Storage.storage().reference().child(imgUid).putData(imgData, metadata: metadata) { (metadata, error) in
            if error != nil {
                print("Didn't upload image in Firebase Storage")
                self.isUploaded = false
            } else {
                print("Uploaded in Firebase Storage")
                self.isUploaded = true
                let downloadURL = metadata?.downloadURL()?.absoluteString
                if let url = downloadURL {
                    self.setUser(img: url)
                    self.downloadPhoto(user: self.name)
                }
            }
        }
    }
}

// The alert Controller (user can choose to take a photo with Camera or choose an image in his library then I use UIImagePickerController in order to display the image on a UIImageView)
@IBAction func actionButton(_ sender: Any) {
let attributedString = NSAttributedString(string: "User photo", attributes: [
    NSFontAttributeName : UIFont.boldSystemFont(ofSize: 15),
    NSForegroundColorAttributeName : UIColor.black
    ])

let alertController = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
alertController.message = nil
alertController.setValue(attributedString, forKey: "attributedTitle")
alertController.addAction(UIAlertAction(title: "Take photo", style: .default, handler: self.takePhoto))
alertController.addAction(UIAlertAction(title: "Choose in Library", style: .default, handler: self.libraryPhoto))
alertController.addAction(UIAlertAction(title: "Show current photo", style: .default, handler: self.showPhoto))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}

如果我添加按钮"删除照片"?如何删除此图像?如何在Firebase存储中检索此图像?我无法找到正确的图片并将其删除,而且我真的不知道如何在Firebase存储中创建文件夹,因此所有用户图片都位于存储的同一部分,我可以& #39; t检索正确的图像(imageUid)。

1 个答案:

答案 0 :(得分:2)

要删除图像,您需要能够重新创建图像的路径。这意味着知道图像的文件名。

当您保存图像时,您需要为每个图像分配一个随机的UUID并放在存储桶的根目录中,这从组织的角度来看并不是很有用。我会为每个用户创建一个文件夹并将图像存储为有用的内容(如profilePic.jpg),如下所示:

func uploadImg() {
    name = Auth.auth().currentUser?.displayName
    userUid = Auth.auth().currentUser?.uid

    guard let img = userImagePicker.image, imageSelected == true else {
        print("Image needs to be selected")
        return
    }

    if let imgData = UIImageJPEGRepresentation(img, 0.2) {
        let metadata = StorageMetadata()
        metadata.contentType = "image/jpeg"

        // create reference to image location
        let profilePicRef = Storage.storage().reference().child("\(userUid!)/profilePic.jpg")
        // upload image
        profilePicRef.putData(imgData, metadata: metadata) { (metadata, error) in
            if error != nil {
                print("Didn't upload image in Firebase Storage")
                self.isUploaded = false
            } else {
                print("Uploaded in Firebase Storage")
                self.isUploaded = true
                let downloadURL = metadata?.downloadURL()?.absoluteString
                if let url = downloadURL {
                    self.setUser(img: url)
                    self.downloadPhoto(user: self.name)
                }
            }
        }
    }
}

现在我们可以轻松找到个人资料图片,我们可以轻松删除它:

func deleteProfilePic() {
    guard let userUid = Auth.auth().currentUser.uid else {
        return
    }
    let pictureRef = Storage.storage().reference().child("\(userUid)/profilePic.jpg")
    pictureRef.delete { error in
        if let error = error {
            // Uh-oh, an error occurred!
        } else {
            // File deleted successfully
        }
    }
}