2017-09-30 1 views
0

사용자가 로그인 할 수있는 앱을 개발 중입니다. 사용자 프로필 페이지에서 내 앱에 표시 할 이미지 프로필을 선택할 수 있습니다. 이 이미지는 Firebase 데이터베이스와 Firebase Storage에 저장됩니다. 사용자가 원하는 경우 현재 이미지 프로필을 삭제하도록 결정할 수 있습니다. 내가 할 수있는 방법을 찾을 수 없습니다. 어떻게 이미지를 Firebase Storage에서 삭제할 수 있습니까? 메타 데이터를 사용하여 저장소에 저장합니다. 내가 버튼 "사진 삭제"를 추가하면Firebase Storage에서 사진을 삭제하는 방법

// 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 Storage에서이 이미지를 검색하려면 어떻게해야합니까? 올바른 이미지를 찾지 못하고 삭제할 수 없으며 Firebase Storage에 폴더를 만드는 방법을 모르기 때문에 모든 사용자 이미지가 Storage의 동일한 섹션에 있으므로 이미지를 가져올 수 없습니다. 오른쪽 이미지 (imageUid).

+0

다음과 같은 이미지 폴더를 만들 수 있다고 생각합니다 :'Storage.storage(). reference(). child ("YourImagesFolder"). 자식 (imgUid) .putData (...' – 3stud1ant3

+0

무료 계정, Firebase Storage에 폴더가 생성되지 않아서 폴더를 만들 수 있습니다. –

답변

1

이미지를 삭제하려면 이미지의 경로를 다시 만들 수 있어야합니다. 이것은 이미지의 파일 이름을 아는 것을 의미합니다.

지금 이미지를 저장하면 각 UUID에 임의의 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 
     } 
    } 
} 
+0

고맙습니다. lder가 생성 되었습니까? Firebase 구독 만 가능할 수도 있습니다. –

+0

코드가 작동하지만 Firebase Storage의 각 사용자에 대한 폴더를 볼 수없는 이유는 무엇입니까? 생성 된 것 같지만 그것을 볼 수 없습니다. –

+0

@Giggs가 콘솔에 업데이트 할 시간을 줄 수 있습니까? 그들은 보여줘야한다. –

관련 문제