Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Last active April 21, 2020 10:02
Show Gist options
  • Save alexpaul/0f512ead2ac6e79d5c734ea9a058bb68 to your computer and use it in GitHub Desktop.
Save alexpaul/0f512ead2ac6e79d5c734ea9a058bb68 to your computer and use it in GitHub Desktop.
Accessing manually uploaded media from Firebase Storage.

Accessing manually uploaded media from Firebase Storage.

Prerequisites

  • Firebase pods are installed
  • Firebase Storage is configured on your Firebase console.
  • Media has been uploaded to Firebase Storage.
  • You have already downloaded the Google-Info.plist file and added it to Xcode.
  • Firebase has been configured in the AppDelegate.
  • Firebase Authentication is configured or Firebase Storage read access is set to public i.e read: true;

StorageService.swift

import FirebaseStorage

class StorageService {
  private init() {}
  static let shared = StorageService()
  
  private let storageRef = Storage.storage().reference()
  
  public func fetchPhoto(filename: String, completion: @escaping (Result<URL, Error>) -> ()) {
    storageRef.child(filename).downloadURL { (url, error) in
      if let error = error {
        completion(.failure(error))
      } else if let url = url {
        completion(.success(url))
      }
    }
  }
}

ViewController.swift - Fetching an Image

"mobilePhotos/french-toast.jpeg" this would be the reference storage location in your Firebase Storage.

import UIKit
import Kingfisher 

StorageService.shared.fetchMedia(at: "mobilePhotos/french-toast.jpeg") { [weak self] result in
  switch result {
  case .failure(let error):
    print("failed to fetch URL with error: \(error)")
  case .success(let url):
    DispatchQueue.main.async {
      self?.imageview.kf.setImage(with: url)
    }
  }
}

ViewController.swift - Fetching a Video

"mobileVideos/cherry-blossom-1.mp4" - this would be the reference storage location in your Firebase Storage.

import UIKit
import AVKit 

StorageService.shared.fetchMedia(at: "mobileVideos/cherry-blossom-1.mp4") { [weak self] result in
    switch result {
    case .failure(let error):
      print("failed to fetch URL with error: \(error)")
    case .success(let url):
      DispatchQueue.main.async {
        let player = AVPlayer(url: url)
        let playerController = AVPlayerViewController()
        playerController.player = player
        self?.present(playerController, animated: true) {
          player.play()
        }
      }
    }
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment