download image from firebase storage in swift - swift

Have the image location as gs://olio-ae400.appspot.com/Listings/Food/-M3g8pZDGmApicUAQtOi/MainImage
I want to download from this firebase storage location to imageview.
Have used below code,but the unable to download image from url?
let storage = Storage.storage()
var reference: StorageReference!
reference = storage.reference(forURL: "gs://olio-ae400.appspot.com/Listings/Food/-M3g8pZDGmApicUAQtOi/MainImage")
reference.downloadURL { (url, error) in
print("image url is",url!)
let data = NSData(contentsOf: url!)
let image = UIImage(data: data! as Data)
self.img.image = image
}
Getting error at downloadURL line while retrieving the url for it in the response.
What is the correct way for it to download the image?

Install the pod firebaseUI.
import FirebaseUI
fetch the reference from the storage and set the reference to the imageview directly using SDwebimage as shown below.
let ref2 = Storage.storage().reference(forURL: "gs://hungry-aaf15.appspot.com/Listings/Food/-MV04bNvewyGPHMYUkK9/MainImage")
cell.img.sd_setImage(with: ref2)

Specify path and it's extension, then Use:
let path = "Listings/Food/-M3g8pZDGmApicUAQtOi/MainImage.jpg"
let reference = Storage.storage().reference(withPath: path)
reference.getData(maxSize: (1 * 1024 * 1024)) { (data, error) in
if let err = error {
print(err)
} else {
if let image = data {
let myImage: UIImage! = UIImage(data: image)
// Use Image
}
}
}

For Swift 5.6 and Xcode 13.4
I opened name "Images" folder in Firebase and uploaded my image which name "Corleone" in jpg format.
Firstly I fetch image data then assigned to imageView. Lastly, i downloaded image URL. You can use two method differently.
You can copy all what i wrote and past your project inside of viewDidload or buttonAction.
let storage = Storage.storage().reference().child("Images/Corleone.jpg")
storage.getData(maxSize: 1 * 1024 * 1024) { data, error in
if error != nil {
print(error?.localizedDescription ?? "errror")
}else{
let image = UIImage(data: data!)
self.imageView.image = image
storage.downloadURL { url, error in
if error != nil {
print(error?.localizedDescription ?? "error")
}else {
print(url ?? "url") //https://firebasestorage.googleapis.com/v0/b/epeycompare.appspot.com/o/Images%2FCorleone.jpg?alt=media&token=04c6369d-8036-4aef-8052-bac21c89eeda
}
}
}
}

Related

how to display image in collection view using mockapi? [duplicate]

In Swift 3, I am trying to capture an image from the internet, and have these lines of code:
var catPictureURL = NSURL(fileURLWithPath: "http://i.imgur.com/w5rkSIj.jpg")
var catPictureData = NSData(contentsOf: catPictureURL as URL) // nil
var catPicture = UIImage(data: catPictureData as! Data)
What am I doing wrong here?
There's a few things with your code as it stands:
You are using a lot of casting, which is not needed.
You are treating your URL as a local file URL, which is not the case.
You are never downloading the URL to be used by your image.
The first thing we are going to do is to declare your variable as let, as we are not going to modify it later.
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")! // We can force unwrap because we are 100% certain the constructor will not return nil in this case.
Then we need to download the contents of that URL. We can do this with the URLSession object. When the completion handler is called, we will have a UIImage downloaded from the web.
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
Finally you need to call resume on the download task, otherwise your task will never start:
downloadPicTask.resume().
All this code may look a bit intimidating at first, but the URLSession APIs are block based so they can work asynchronously - If you block your UI thread for a few seconds, the OS will kill your app.
Your full code should look like this:
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")!
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
let url = URL(string: "http://i.imgur.com/w5rkSIj.jpg")
let data = try? Data(contentsOf: url)
if let imageData = data {
let image = UIImage(data: imageData)
}
Swift
Good solution to extend native functionality by extensions
import UIKit
extension UIImage {
convenience init?(url: URL?) {
guard let url = url else { return nil }
do {
self.init(data: try Data(contentsOf: url))
} catch {
print("Cannot load image from url: \(url) with error: \(error)")
return nil
}
}
}
Usage
Convenience initializer is failable and accepts optional URL – approach is safe.
imageView.image = UIImage(url: URL(string: "some_url.png"))
You could also use Alamofire\AlmofireImage for that task:
https://github.com/Alamofire/AlamofireImage
The code should look something like that (Based on the first example on link above):
import AlamofireImage
Alamofire.request("http://i.imgur.com/w5rkSIj.jpg").responseImage { response in
if let catPicture = response.result.value {
print("image downloaded: \(image)")
}
}
While it is neat yet safe, you should consider if that worth the Pod overhead.
If you are going to use more images and would like to add also filter and transiations I would consider using AlamofireImage
Use this extension and download image faster.
extension UIImageView {
public func imageFromURL(urlString: String) {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
activityIndicator.startAnimating()
if self.image == nil{
self.addSubview(activityIndicator)
}
URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error ?? "No Error")
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
activityIndicator.removeFromSuperview()
self.image = image
})
}).resume()
}
}
Using Alamofire worked out for me on Swift 3:
Step 1:
Integrate using pods.
pod 'Alamofire', '~> 4.4'
pod 'AlamofireImage', '~> 3.3'
Step 2:
import AlamofireImage
import Alamofire
Step 3:
Alamofire.request("https://httpbin.org/image/png").responseImage { response in
if let image = response.result.value {
print("image downloaded: \(image)")
self.myImageview.image = image
}
}
The easiest way according to me will be using SDWebImage
Add this to your pod file
pod 'SDWebImage', '~> 4.0'
Run pod install
Now import SDWebImage
import SDWebImage
Now for setting image from url
imageView.sd_setImage(with: URL(string: "http://www.domain/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
It will show placeholder image but when image is downloaded it will show the image from url .Your app will never crash
This are the main feature of SDWebImage
Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC
To know more https://github.com/rs/SDWebImage
Use extension for UIImageView to Load URL Images.
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView {
func imageURLLoad(url: URL) {
DispatchQueue.global().async { [weak self] in
func setImage(image:UIImage?) {
DispatchQueue.main.async {
self?.image = image
}
}
let urlToString = url.absoluteString as NSString
if let cachedImage = imageCache.object(forKey: urlToString) {
setImage(image: cachedImage)
} else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
DispatchQueue.main.async {
imageCache.setObject(image, forKey: urlToString)
setImage(image: image)
}
}else {
setImage(image: nil)
}
}
}
}
We are able to fetch image directly without using Third Party SDK like 'AlamofireImage', 'Kingfisher' and 'SDWebImage'
Swift 5
DispatchQueue.global(qos: .background).async {
do{
let data = try Data.init(contentsOf: URL.init(string:"url")!)
DispatchQueue.main.async {
let image: UIImage? = UIImage(data: data)
yourImageView.image = image
}
}
catch let errorLog {
debugPrint(errorLog.localizedDescription)
}
}
let url = ("https://firebasestorage.googleapis.com/v0/b/qualityaudit-678a4.appspot.com/o/profile_images%2FBFA28EDD-9E15-4CC3-9AF8-496B91E74A11.png?alt=media&token=b4518b07-2147-48e5-93fb-3de2b768412d")
self.myactivityindecator.startAnimating()
let urlString = url
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url)
{
(data, response, error) in
if error != nil {
print("Failed fetching image:", error!)
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
print("error")
return
}
DispatchQueue.main.async {
let image = UIImage(data: data!)
let myimageview = UIImageView(image: image)
print(myimageview)
self.imgdata.image = myimageview.image
self.myactivityindecator.stopanimating()
}
}.resume()
I use AlamofireImage it works fine for me for Loading url within ImageView, which also has Placeholder option.
func setImage (){
let image = “https : //i.imgur.com/w5rkSIj.jpg”
if let url = URL (string: image)
{
//Placeholder Image which was in your Local(Assets)
let image = UIImage (named: “PlacehoderImageName”)
imageViewName.af_setImage (withURL: url, placeholderImage: image)
}
}
Note:- Dont forget to Add AlamofireImage in your Pod file as well as in Import Statment
Say Example,
pod 'AlamofireImage' within Your PodFile and in ViewController import AlamofireImage

How to get downloadURL of an existing image from firebase storage

I pushed an image to firebase storage and by using Resize Images Extension, I am able to get a resized image of the same image name plus _240x320. To be clear with you I get the downloadURL of the original image, but I am not understand why I cannot get the downloadURL of the resized image. Here is my code:
func storeImageInFirebase(){
let storeageRef = Storage.storage().reference()
let imageName = UUID().uuidString //+ ".jpg"
let imagesReference = storeageRef.child("images").child(imageName + ".jpg")
let imageData = self.imgView.image!.pngData()
let metaData = StorageMetadata()
var imageName2 = imageName //+ "_240x320.jpg"
let imagesReference2 = storeageRef.child("images").child(imageName2 + "_240x320.jpg")
metaData.contentType = "image/jpg"
imagesReference.putData(imageData!, metadata: metaData){ (metadate, error)
in
guard metadate != nil else{
print("Error: \(String(describing: error?.localizedDescription))")
return
}
// Fetch the download URL
imagesReference.downloadURL(completion: {(url, error)
in
if error != nil {
print("Faild to download url:", error!)
return
}else{
// show the url in real database
print("resized image url ..... \(url?.absoluteString)")
var theUsedURL = self.imgURL = (url?.absoluteString)!
self.sendDataToFirebase()
}
})
// Fetch the download URL
imagesReference2.downloadURL(completion: {(url, error)
in
if error != nil {
print("Faild to download url:", error!)
return
}else{
// show the url in real database
print("resized image url ..... \(url?.absoluteString)")
self.imgURL2 = (url?.absoluteString)!
self.sendDataToFirebase()
}
})
}
}
I wrote two image references, one for the original image and the other one for resized image. I am able to get the original image, but I have error faild to download url and the image does not exist for the resized image, where I can see in the Firebase Storage that the image there. I am trying to solve this from a weeks I will appreciate any help.

Load image to imageView from Firabse Storage Swift

I am trying to load an image to an imageView from firebase storage as expected.
I have the below function that is called in viewDidLoad but not sure why it's not working.
I copied the urlName.com directly from the image within Firebase storage.
func setProfileImage() {
let currentUserID = Auth.auth().currentUser!.uid
Storage.storage().reference(forURL: "gs://urlName.com").child("Folder/\(currentUserID).jpg").getData(maxSize: 1048576, completion: { (data, error) in
guard let imageData = data, error == nil else {
return
}
self.profileImage.image = UIImage(data: imageData)
})
}
This code doesn't throw an error but also doesn't load anything.
Any help much appreciated
Thanks
1- Allow Access for development mode, In Storage > Rules:
service firebase.storage {
match /b/yourapp.appspot.com/o {
match /{allPaths=**} {
// Allow access by all users
allow read, write;
}
}
}
Get the data:
let reference = Storage.storage().reference(withPath: "your_folder_path)/image.jpg")
reference.getData(maxSize: (1 * 1024 * 1024)) { (data, error) in
if let _error = error{
print(_error)
} else {
if let _data = data {
let myImage:UIImage! = UIImage(data: _data)
self.profileImage.image = myImage
}
}
}

How to cache an array of Images fetched from firebase Storage using SDWebImage in Swift 4?

I am fetching images from firebase storage in the form of data and I want to cache the images in my app using SDWebImage. Please guide me how to achieve it?
for x in images_list{
let storageRef = storage.child("images/\(x).jpg")
storageRef.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
if let error = error{
print(error.localizedDescription)
return
}
else{
imagesarray.append(UIImage(data: data!)!)
}
if let x = images_list.last{
cell.imageDemo.animationImages = imagesarray
cell.imageDemo.sd_setImage(with: storageRef) // Here I Want to cache the images of **imagesarray** that are being animated
cell.imageDemo.animationDuration = 2
cell.imageDemo.startAnimating()
}
}
}
you are downloading imageData directly from firebase in your question. Instead of using getData you will need to use downloadURL method. Like this:
for x in image_list {
let storageRef = storage.child("images/\(x).jpg")
//then instead of downloading data download the corresponding URL
storageRef.downloadURL { url, error in
if let error = error {
} else {
//make your imageArray to hold URL rather then images directly
imagesArray.append(url)
}
}
}
//////This is were you would use those url////////
let url = imageArray.first!
imageView.sd_setImage(with: url, completed: nil)
The most important part here is download url rather than image data. And whenever you set the image url to the imageView the SDWebImage library will cache it and display if already cached
Instead of getData method, I used downloadURL method and Cached the array of images.
var imagesarray = [URL]()
for x in images_list{
let storageRef = storage.child("images/\(x).jpg")
storageRef.downloadURL { (url, error) in
if let error = error{
print(error.localizedDescription)
}
else{
imagesarray.append(url!)
}
if let x = images_list.last{
cell.imageDemo.sd_setAnimationImages(with: imagesarray)
cell.imageDemo.animationDuration = 2
cell.imageDemo.startAnimating()
}
}
}

Swift: Display Image from URL

In Swift 3, I am trying to capture an image from the internet, and have these lines of code:
var catPictureURL = NSURL(fileURLWithPath: "http://i.imgur.com/w5rkSIj.jpg")
var catPictureData = NSData(contentsOf: catPictureURL as URL) // nil
var catPicture = UIImage(data: catPictureData as! Data)
What am I doing wrong here?
There's a few things with your code as it stands:
You are using a lot of casting, which is not needed.
You are treating your URL as a local file URL, which is not the case.
You are never downloading the URL to be used by your image.
The first thing we are going to do is to declare your variable as let, as we are not going to modify it later.
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")! // We can force unwrap because we are 100% certain the constructor will not return nil in this case.
Then we need to download the contents of that URL. We can do this with the URLSession object. When the completion handler is called, we will have a UIImage downloaded from the web.
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
Finally you need to call resume on the download task, otherwise your task will never start:
downloadPicTask.resume().
All this code may look a bit intimidating at first, but the URLSession APIs are block based so they can work asynchronously - If you block your UI thread for a few seconds, the OS will kill your app.
Your full code should look like this:
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")!
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
let url = URL(string: "http://i.imgur.com/w5rkSIj.jpg")
let data = try? Data(contentsOf: url)
if let imageData = data {
let image = UIImage(data: imageData)
}
Swift
Good solution to extend native functionality by extensions
import UIKit
extension UIImage {
convenience init?(url: URL?) {
guard let url = url else { return nil }
do {
self.init(data: try Data(contentsOf: url))
} catch {
print("Cannot load image from url: \(url) with error: \(error)")
return nil
}
}
}
Usage
Convenience initializer is failable and accepts optional URL – approach is safe.
imageView.image = UIImage(url: URL(string: "some_url.png"))
You could also use Alamofire\AlmofireImage for that task:
https://github.com/Alamofire/AlamofireImage
The code should look something like that (Based on the first example on link above):
import AlamofireImage
Alamofire.request("http://i.imgur.com/w5rkSIj.jpg").responseImage { response in
if let catPicture = response.result.value {
print("image downloaded: \(image)")
}
}
While it is neat yet safe, you should consider if that worth the Pod overhead.
If you are going to use more images and would like to add also filter and transiations I would consider using AlamofireImage
Use this extension and download image faster.
extension UIImageView {
public func imageFromURL(urlString: String) {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
activityIndicator.startAnimating()
if self.image == nil{
self.addSubview(activityIndicator)
}
URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error ?? "No Error")
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
activityIndicator.removeFromSuperview()
self.image = image
})
}).resume()
}
}
Using Alamofire worked out for me on Swift 3:
Step 1:
Integrate using pods.
pod 'Alamofire', '~> 4.4'
pod 'AlamofireImage', '~> 3.3'
Step 2:
import AlamofireImage
import Alamofire
Step 3:
Alamofire.request("https://httpbin.org/image/png").responseImage { response in
if let image = response.result.value {
print("image downloaded: \(image)")
self.myImageview.image = image
}
}
The easiest way according to me will be using SDWebImage
Add this to your pod file
pod 'SDWebImage', '~> 4.0'
Run pod install
Now import SDWebImage
import SDWebImage
Now for setting image from url
imageView.sd_setImage(with: URL(string: "http://www.domain/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
It will show placeholder image but when image is downloaded it will show the image from url .Your app will never crash
This are the main feature of SDWebImage
Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC
To know more https://github.com/rs/SDWebImage
Use extension for UIImageView to Load URL Images.
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView {
func imageURLLoad(url: URL) {
DispatchQueue.global().async { [weak self] in
func setImage(image:UIImage?) {
DispatchQueue.main.async {
self?.image = image
}
}
let urlToString = url.absoluteString as NSString
if let cachedImage = imageCache.object(forKey: urlToString) {
setImage(image: cachedImage)
} else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
DispatchQueue.main.async {
imageCache.setObject(image, forKey: urlToString)
setImage(image: image)
}
}else {
setImage(image: nil)
}
}
}
}
We are able to fetch image directly without using Third Party SDK like 'AlamofireImage', 'Kingfisher' and 'SDWebImage'
Swift 5
DispatchQueue.global(qos: .background).async {
do{
let data = try Data.init(contentsOf: URL.init(string:"url")!)
DispatchQueue.main.async {
let image: UIImage? = UIImage(data: data)
yourImageView.image = image
}
}
catch let errorLog {
debugPrint(errorLog.localizedDescription)
}
}
let url = ("https://firebasestorage.googleapis.com/v0/b/qualityaudit-678a4.appspot.com/o/profile_images%2FBFA28EDD-9E15-4CC3-9AF8-496B91E74A11.png?alt=media&token=b4518b07-2147-48e5-93fb-3de2b768412d")
self.myactivityindecator.startAnimating()
let urlString = url
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url)
{
(data, response, error) in
if error != nil {
print("Failed fetching image:", error!)
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
print("error")
return
}
DispatchQueue.main.async {
let image = UIImage(data: data!)
let myimageview = UIImageView(image: image)
print(myimageview)
self.imgdata.image = myimageview.image
self.myactivityindecator.stopanimating()
}
}.resume()
I use AlamofireImage it works fine for me for Loading url within ImageView, which also has Placeholder option.
func setImage (){
let image = “https : //i.imgur.com/w5rkSIj.jpg”
if let url = URL (string: image)
{
//Placeholder Image which was in your Local(Assets)
let image = UIImage (named: “PlacehoderImageName”)
imageViewName.af_setImage (withURL: url, placeholderImage: image)
}
}
Note:- Dont forget to Add AlamofireImage in your Pod file as well as in Import Statment
Say Example,
pod 'AlamofireImage' within Your PodFile and in ViewController import AlamofireImage