I have a single method that should deal with downloading images. It seems to be working completely correctly, outside of the fact that the Data returned from Firebase Storage is 0 bytes. Why is this?
func useDatabaseToDownloadPicture () {
if let userId = FIRAuth.auth()?.currentUser?.uid {
// Get a reference to the storage service using the default Firebase App
let storage = FIRStorage.storage()
let firebaseImages = FIRStorage.storage().reference().child("Images")
let userPhotoLocation = firebaseImages.child("Users").child(userId).child("profilePicture.jpg")
let myRef = FIRStorage.storage().reference()
let firebaseProfilePicLocation = firebase.child("Users").child(userId).child("Images").child("profilePicture").child("downloadURL")
firebaseProfilePicLocation.observe(.value, with: { (snapshot) in
print(" Profile Picture Databse Snapshot -> \n \(snapshot) ")
// Get download URL from snapshot
if let downloadURL = snapshot.value as? String {
print(" downloadURL converted to String ")
// Create a storage reference from the URL
let storageRef = storage.reference(forURL: downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) -> Void in
print("Downloading Data . . . Data String -> \(String(describing: data))")
print("Downloading Data . . . Data Literal -> \(data)")
// Create a UIImage, add it to profile picture
if data != nil {
print("Data is not nil!")
if let image = UIImage(data: data!) {
print("Image Created")
} else {
print("Image Could Not create!! check data...")
let url = URL(string: downloadURL)
let urlData = try? Data(contentsOf: url!)
if let img = UIImage(data: urlData!) {
print("Image 2 Created")
} else {
print("Image 2 Failed")
}
}
let pic = UIImage(data: data!)
self.profilePicture.image = pic
} else {
print(" ❌ Data is nil ")
}
}
} else if let downloadURL = snapshot.value as? URL {
print(" downloadURL converted to URL! ")
// Create a storage reference from the URL
let storageRef = storage.reference(forURL: downloadURL.absoluteString)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) -> Void in
// Create a UIImage, add it to profile picture
if data != nil {
let pic = UIImage(data: data!)
self.profilePicture.image = pic
} else {
print(" ❌ Data is nil")
}
}
} else {
// . . . Do nothing, all ways failed
}
})
}
}
The result printed is:
downloadURL converted to String
Downloading Data . . . Data String -> Optional(0 bytes)
Downloading Data . . . Data Literal -> Optional(0 bytes)
Image Could Not create!! check data...
Image 2 Failed
To me, it seems that the problem is less the data coming in properly, but it seems as it the problem is the data being 0 bytes. Why is that the case?
Thank you!!