Storing/Downloading/Deleting images or videos Using Firebase Cloud Storage - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

8 Oct 2017

Storing/Downloading/Deleting images or videos Using Firebase Cloud Storage

Cloud Storage for Firebase is a powerful, simple, and cost-effective object storage service built for Google scale. Firebase SDK adds Google security to file uploads and downloads for your Firebase apps, either if connectivity is slow or fast.

Storing/Downloading images or videos Using Firebase Cloud Storage


If the network connection is poor, the client is able to retry the operation right where it left off, saving your users time and bandwidth. Everything will be done asynchronously in background threads, so that UI won't hang.

We can store images, videos, files, audio in cloud storage by using Firebase SDK. For accessing those files we can use same Google cloud storage.

Uploads and downloads are robust, meaning they restart where they stopped, saving your users time and bandwidth.

Google provides strong security, so that only authenticated users can upload or download files.

Before getting in to Sample Project, Integrate your project with Firebase.

Add the following dependency to podfile:
pod 'Firebase/Storage'

Run pod install and open the created .xcworkspace file.

Configure Firebase Storage Rules:

The Firebase Storage provides a set rules so that files can structure according to the rules.

By default, only authenticated users can access to the Firebase Storage for uploading & downloading files.

There are different authenticated methods choose any one of them.

Using Facebook Login
Using Email & Password
Anonymous Login

In this project we are going to start without setting up Authentication, you can configure your rules for public access.

Go to Firebase console -> Storage -> Rules

Add the following rule and publish:
// Anyone can read or write to the bucket, even non-users of your app.
// Because it is shared with Google App Engine, this will also make
// files uploaded via GAE public.
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}


 Firebase console -> Storage -> Rules


Set up Firebase Storage To iOS Project :

We need to initialize Firebase.

First import the Firebase SDK in AppDelegate.swift file:
import Firebase

Then, in the application:didFinishLaunchingWithOptions: method, initialize the FirebaseApp object:
// Use Firebase library to configure APIs
FirebaseApp.configure()

Open ViewController.swift file add the following code inside viewDidLoad() method:
let storage = Storage.storage()

Create a Reference To upload, download, or delete:

References are created using the FirebaseStorage service and calling its reference method.
// Create a storage reference from our storage service
let storageRef = storage.reference()

You can create a reference to a location lower in the tree, say 'images/car.jpg', by using the child method on an existing reference.
var carRef = storageRef.child("images/car.jpg")

Uploading To Cloud Storage :

For uploading a file firstly we need a reference, we can use the one which created earlier.

We can upload files to storage using two ways:

1. Upload from data in memory
2. Upload from a URL representing a file on device

Here we will show using memory.

Before doing that drag one image to the project and name its as 'car.jpg'.

Add the following method and call in viewDidLoad() method:
func uploadImageToStorage() {
    let storage = Storage.storage()
    var storageRef = storage.reference()
    
    if let image = UIImage(named: "car.jpg") {
        let data = UIImagePNGRepresentation(image)
        print("data \(String(describing: data))")
        
        
        // Create the file metadata
        let metadata = StorageMetadata()
        metadata.contentType = "image/jpeg"
        
        storageRef = storageRef.child("images/car.jpg")
        
        let uploadTask = storageRef.putData(data!, metadata: metadata)
        
        // Listen for state changes, errors, and completion of the upload.
        uploadTask.observe(.resume) { snapshot in
            // Upload resumed, also fires when the upload starts
        }
        
        uploadTask.observe(.pause) { snapshot in
            // Upload paused
        }
        
        uploadTask.observe(.progress) { snapshot in
            // Upload reported progress
            let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
                / Double(snapshot.progress!.totalUnitCount)
            
            print("Upload Percentage == \(percentComplete)")
        }
        
        uploadTask.observe(.success) { snapshot in
            // Upload completed successfully
            print("Upload completed successfully")
        }
        
        uploadTask.observe(.failure) { snapshot in
            if let error = snapshot.error as? NSError {
                switch (StorageErrorCode(rawValue: error.code)!) {
                case .objectNotFound:
                    // File doesn't exist
                    break
                case .unauthorized:
                    // User doesn't have permission to access file
                    break
                case .cancelled:
                    // User canceled the upload
                    break
                    
                    /* ... */
                    
                case .unknown:
                    // Unknown error occurred, inspect the server response
                    break
                default:
                    // A separate error occurred. This is a good place to retry the upload.
                    break
                }
            }
        }
    }
}

Above method will give percentage of upload done,failures causes, pause, resume and success observer.

Build and Run,if everything is correct then we will see 'Upload completed successfully' message in the console.

Then open Firebase console check inside storage -> images -> car.jpg should be there like below:

 storage -> images -> car.jpg


Downloading Image From Cloud Storage:

Now we will download the car image what we uploaded before.

Add the following code and call in viewDidLoad() method:
func downloadImageFromStorage() {
    let storage = Storage.storage()
    var storageRef = storage.reference()
    
    // Create a reference to the file we want to download
    storageRef = storageRef.child("images/car.jpg")
    
    // Start the download (in this case writing to a file)
    let downloadTask = storageRef.getData(maxSize: 5 * 1024 * 1024) { data, error in
        if let error = error {
            // Uh-oh, an error occurred!
        } else {
            // Data for "images/island.jpg" is returned
            let image = UIImage(data: data!)
            
            print("image succesfully downloaded \(image!)")
        }
    }
    
    
    // Observe changes in status
    downloadTask.observe(.resume) { snapshot in
        // Download resumed, also fires when the download starts
    }
    
    downloadTask.observe(.pause) { snapshot in
        // Download paused
    }
    
    downloadTask.observe(.progress) { snapshot in
        // Download reported progress
        let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
            / Double(snapshot.progress!.totalUnitCount)
    }
    
    downloadTask.observe(.success) { snapshot in
        // Download completed successfully
    }
    
    // Errors only occur in the "Failure" case
    downloadTask.observe(.failure) { snapshot in
        guard let errorCode = (snapshot.error as? NSError)?.code else {
            return
        }
        guard let error = StorageErrorCode(rawValue: errorCode) else {
            return
        }
        switch (error) {
        case .objectNotFound:
            // File doesn't exist
            break
        case .unauthorized:
            // User doesn't have permission to access file
            break
        case .cancelled:
            // User cancelled the download
            break
            
            /* ... */
            
        case .unknown:
            // Unknown error occurred, inspect the server response
            break
        default:
            // Another error occurred. This is a good place to retry the download.
            break
        }
    }
}

Above method will give percentage of download done,failures causes, pause, resume and success observer.

Build and Run,if everything is correct then we will see 'image successfully downloaded with file' message in the console.


Deleting Image From Firebase Storage:

We will delete the car image from Firebase storage.

Add the following code and call in viewDidLoad() method:
func deletingImageFromStorage(){
    let storage = Storage.storage()
    var storageRef = storage.reference()
    
    // Create a reference to the file we want to download
    storageRef = storageRef.child("images/car.jpg")
    
    storageRef.delete { error in
        if let error = error {
            // Uh-oh, an error occurred!
        } else {
            print("File deleted successfully")
        }
    }
    
}

Build and Run,if everything is correct then we will see 'File deleted successfully' message in the console.

Open the Firebase console and check whether image deleted or not.

8 comments:

  1. Thank you very much, this worked out-of-the-box perfectly in my Swift 5.3 app, exactly what I wanted help with as a new IOS developer. Great Job and thanks again!

    ReplyDelete
  2. I visit your blog regularly and recommend it to all of those who wanted to enhance their knowledge with ease. The style of writing is excellent and also the content is top-notch. Thanks for that shrewdness you provide the readers! YouTube Vanced apk

    ReplyDelete
  3. I really loved reading your blog. It was very well authored and easy to undertand. Unlike additional blogs I have read which are really not tht good. I also found your posts very interesting. In fact after reading, I had to go show it to my friend and he ejoyed it as well! get more info about tape storage

    ReplyDelete
  4. This article was written by a real thinking writer without a doubt. I agree many of the with the solid points made by the writer. I’ll be back day in and day for further new updates. tape storage singapore

    ReplyDelete
  5. I read a article under the same title some time ago, but this articles quality is much, much better. How you do this.. singapore tape storage

    ReplyDelete
  6. Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. singapore best tape storage

    ReplyDelete
  7. Love to read it,Waiting For More new Update and I Already Read your Recent Post its Great Thanks. buy tape storage online

    ReplyDelete
  8. Most of our customers ar asking for "Storage units near ME" and that is what we offer! Safe, Local and Cheap Storage. storage near me Aberdeen

    ReplyDelete

Post Top Ad