How to download or retrieve image from firebase storage in SwiftUI or Swift 5
For swift 5, you can use this :
let Ref = Storage.storage().reference(forURL: yourUrl)
Ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
if error != nil {
print("Error: Image could not download!")
} else {
yourImageView.image = UIImage(data: data!)
}
}
Hope it helps...
Retrieve photos from firebase storage SWIFT
- First, you need to fix your model so it can help you. Add the bucket name to the model like this:
Struct Labels {
let firstLabel: String
let secondLabel: String
let photoKey: String // This will store the bucket name for this `Labels`
}
- Now in your
getDatabaseRecords
change:
let newEntry = Labels(firstLabel: data["firstLabel"] as! String,
secondLabel: data["secondLabel"] as! String),
photoKey: data["photoKey"] as! String) // Added Line
- Then in
cellForRow
:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewTest.dequeueReusableCell(withIdentifier: "CountryTableViewCell", for: indexPath) as! CountryTableViewCell
let label = labels[indexPath.row]
let storageRef = Storage.storage().reference()
let photoRef = storageRef.child(label.photoKey)
cell.labelTest.text = label.firstLabel
cell.labelLaba.text = label.secondLabel
cell.imageView.sd_setImage(with: photoRef) // Assuming the image view in your cell is named this
return cell
}
- Last, make sure your document structure matches the new
Labels
Model in the firebase console, and you have images as well in the root of your storage that match with all thephotoKey
s. Btw,Labels
is not a very good model name, I just went with it for consistency
Retrieve an image from Firebase to an UIimage swift5
There's a number of ways to go about this but a brief description of the issue first:
The return statement within the closure will execute way before that image is downloaded - Firebase functions are asynchronous and code has to be crafted in a way that allows for time to download and get data from the internet. So - don't try to return data from asynchronous functions.
Here's the code re-written with a completion handler. That handler will be called only after the image is fully downloaded.
func getImageEvent (imagePath: String, completion: @escaping(UIImage) -> Void) {
var myImage : UIImageView?
let storageRef = Storage.storage().reference(withPath: imagePath)
storageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
print(error.localizedDescription)
return
}
if let data = data {
if let myImage = UIImage(data: data) {
completion(myImage)
}
}
}
}
and the key is how to call that function. Note this code awaits the data (UIImage) to be passed back to it within it's closure and lets you know that getting the image was complete.
self.getImageEvent(imagePath: "9U4BoXgBgTTgbbJCz0zy/eventMainImage.jpg", completion: { theImage in
print("got the image!")
})
You should add additional error checking in case the image was not downloaded or myImage was nil. Passing back an error message along with the nil myImage would be one option, or making the object passed back as an optional and then checking for nil within self.downloadImageAtPath
would be another.
Retrieve image from firebase storage to show on tableView (Swift)
Just change the below methods
func downloadPost(){
let userPostRef = self.databaseRef.child("posts")
userPostRef.queryOrderedByChild("time").observeEventType(.ChildAdded, withBlock: {(snapshot) in
if let postAdd = snapshot.value as? NSDictionary {
print("\(snapshot.value)")
let url = snapshot.value?["postPhoto"] as! String
let userPhotoUrl = snapshot.value?["userPhoto"] as! String
var myPost = Post(data: postAdd) //variable change to "var" because going to modify
let url2 = NSURL(string: url) //postPhoto URL
let data = NSData(contentsOfURL: url2!) // this URL convert into Data
if data != nil { //Some time Data value will be nil so we need to validate such things
myPost.postPhoto = UIImage(data: data!)
}
let url3 = NSURL(string: userPhotoUrl) //userPhoto URL
let data2 = NSData(contentsOfURL: url3!) //Convert into data
if data2 != nil { //check the data
myPost.userPhoto = UIImage(data: data2!) //store in image
}
self.posts.insert(myPost, atIndex: 0) // then add the "myPost" Variable
print(self.posts.count)
}
self.tableView.reloadData() // finally going to load the collection of data in tableview
})
}
its take loading time much. because converting the image and store it in the mainqueue.
another ways is store the URL and access the URL on the tableview display. can apply the async loading in the imageview.
Related Topics
Programmatically Screenshot | Swift 3, Macos
Swiftui Hierarchical Picker With Dynamic Data Crashes
Open Uidatepicker Programmatically in iOS 14
Filter Array of [Anyobject] in Swift
Build Error When Trying to Override an Initializer in Xcode 6.3 Beta 3
Xcode 9 and Xcode 10 Giving Different Results, Even with Same Swift Version
How to Return Value from Async Block in Swift
Use Resources in Unit Tests with Swift Package Manager
Swiftui Create Image Slider with Dots as Indicators
How to Configure Contextmenu Buttons For Delete and Disabled in Swiftui
Firebase Snapshot.Key Not Returning Actual Key
Cllocationcoordinate2D Can't Be Instantiated
How to Include .Swift File from Other .Swift File in an Immediate Mode
How to Create a View-Based Nstableview Purely in Code