Firebase에서 사진 사용자 계정을 다운로드하려고합니다. 문제점을 설명합니다 : 사용자의 프로필 페이지에는 자신의 프로필 아바타에 대한 현재 이미지를 보여주는 버튼이 있습니다. 버튼 배경에 이미지가 없습니다. 처음 버튼을 클릭하면 사진에서 이미지를 선택할 수 있습니다. 라이브러리에 저장하거나 (알람 컨트롤러로) 장치 카메라로 사진을 찍으면이 이미지 또는 사진이 Firebase Storage에 업로드되고 새 사진이 버튼 배경에 나타납니다.Firebase Storage에서 사진을 다운로드하고 현재 사용자의 마지막 사진을 바꾸는 방법
그러나 사용자가 현재 사진을 변경하려면 버튼을 다시 탭하여 사진을 찍지만 사진을 찍은 후에는 버튼 배경이 변경되지 않고 사용자가 사진을 변경한다는 의미입니다. 현재 페이지의 사진은 변경 사항을 업데이트하지 않지만 다른보기로 이동하여 사진 변경보기로 돌아 오면 방금 선택한 사용자의 사진이 버튼 배경에 있습니다. 따라서 다운로드는 좋지만 사용자가 다른보기로 이동하지 않은 경우 즉시 작동 할 수 있습니다. 설명하기가 조금 어렵습니다. 여기
// Variables I need
@IBOutlet weak var photoProfil: UIButton!
var name: String!
var userUid: String!
@IBOutlet var userImagePicker: UIImageView!
var imagePicker: UIImagePickerController!
var imageSelected = false
var isUploaded: Bool = false
var refDatabase: DatabaseReference!
var photovide: UIImage = UIImage(named:"profilvide")!
// Take a photo with the camera (first choice)
func takePhoto(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = UIImagePickerControllerSourceType.camera // Source Camera
self.present(imagePicker, animated: false, completion: nil)
} else { // If camera doesn't work
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary // Source Library
self.present(imagePicker, animated: false, completion: nil)
}
}
// Choose an image from the library
func libraryPhoto(sender: AnyObject) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.photoLibrary
image.allowsEditing = false
self.present(image, animated: true)
}
// Take this image and shows it on the View Controller
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
// I want to upload the photo to storage and save it in the database
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
photoProfil.setImage(image, for: .normal) // Button showing the user photo
userImagePicker.image = image
imageSelected = true
uploadImg()
} else {
print("Error...")
}
imagePicker.dismiss(animated: true, completion: nil)
self.dismiss(animated: true, completion: nil)
}
// The alert Controller
@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)
}
// Create a path in order to save the photo in Firebase
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 in the Firebase Storage
func uploadImg() {
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("Did not upload img")
self.isUploaded = false
} else {
print("uploaded")
self.isUploaded = true
let downloadURL = metadata?.downloadURL()?.absoluteString
if let url = downloadURL {
self.setUser(img: url)
}
}
}
}
}
후 다운로드 다운로드 방법 및 쇼 사진에 대한 코드입니다 :
여기 내 업로드 방법에 대한 내 코드의
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
// For download photo from Firebase
name = Auth.auth().currentUser?.displayName
userUid = Auth.auth().currentUser?.uid
refDatabase = Database.database().reference().child("users").child(userUid!)
refDatabase.child("pseudo").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild("userImg") {
self.isUploaded = true
print("True userImg exists")
self.downloadPhoto(user: self.name)
} else {
self.isUploaded = false
self.userImagePicker = UIImageView(image: self.photovide)
self.photoProfil.setImage(self.photovide, for: .normal)
print("isUploaded2 = false")
print("false userImg doesn't exist")
print("Aucune photo n'a été uploadée dans la base de données")
}
})
}
override func viewWillAppear(_ animated: Bool) {
self.userImagePicker.image = nil
guard let username = Auth.auth().currentUser?.displayName else { return }
self.navigationItem.title = username
refDatabase = Database.database().reference().child("users").child(userUid!)
refDatabase.child("pseudo").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild("userImg") {
self.isUploaded = true
print("isUploaded2 = true")
print("true userImg exists")
self.downloadPhoto(user: self.name)
} else {
self.isUploaded = false
self.userImagePicker = UIImageView(image: self.photovide)
self.photoProfil.setImage(self.photovide, for: .normal)
print("False userImg doesn't exist")
}
})
}
func downloadPhoto(user: String) {
self.name = user
let recipientData = Database.database().reference().child("users").child(userUid!).child("pseudo")
recipientData.observeSingleEvent(of: .value, with: { (snapshot) in
let data = snapshot.value as! Dictionary<String, AnyObject>
let nickname = data["nickname"]
let userImg = data["userImg"]
let ref = Storage.storage().reference(forURL: userImg! as! String)
ref.getData(maxSize: 1000000, completion: { (data, error) in
if error != nil {
print("Could not load image")
} else {
if let imgData = data {
if let img = UIImage(data: imgData) {
self.userImagePicker.image = img
self.photoProfil.setImage(img, for: .normal)
}
}
}
})
})
userImagePicker.reloadInputViews()
}
func dismissFullscreenImage(_ sender: UITapGestureRecognizer) {
self.navigationController?.isNavigationBarHidden = false
self.tabBarController?.tabBar.isHidden = false
sender.view?.removeFromSuperview()
}
// Try to do the same with the viewDidLoad() method for download but can't work
override func viewDidAppear(_ animated: Bool) {
refDatabase = Database.database().reference().child("users").child(userUid!)
refDatabase.child("pseudo").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild("userImg") {
self.isUploaded = true
print("True userImg exists")
self.downloadPhoto(user: self.name)
} else {
self.isUploaded = false
self.userImagePicker = UIImageView(image: self.photovide)
self.photoProfil.setImage(self.photovide, for: .normal)
print("False userImg doesn't exist")
}
})
}
'didFinishPickingMediaWithInfo' 메소드 안에'photoProfil.setImage (image : for : .normal)'앞에'print (image)'를 추가하면 어떻게됩니까? 그래서 우리는이 메소드가 호출되고 있음을 확신 할 수있다. – 3stud1ant3
Ok 나는 프린트 (이미지)를 추가했으나 아무 것도 나타나지 않아 print ("image")로 대체하고 콘솔에 프린트한다. –
' if let' statement? – 3stud1ant3