怠慢プログラマーの備忘録

怠慢でナマケモノなプログラマーの備忘録です。

【Swift】Firebase Cloud Storageで画像を取得する

Firebase Cloud Storageを利用してFirebaseに登録した画像を読み込む処理を実装した際のメモです。

firebase.google.com

UIImage+ext.swift

import Firebase
import FirebaseStorage

extension UIImage {
    // Firebase URLからUIImage取得
    static func contentOfFIRStorage(path: String, callback: @escaping (UIImage?) -> Void) {
        let storage = Storage.storage()
        let host = "gs://..../"
        storage.reference(forURL: host).child(path)
            .getData(maxSize: 1024 * 1024 * 10) { (data: Data?, error: Error?) in
            if error != nil {
                callback(nil)
                return
            }
            if let imageData = data {
                let image = UIImage(data: imageData)
                callback(image)
            }
        }
    }
    
    func resizeUIImageRatio(ratio: CGFloat) -> UIImage! {
        
        // 指定された画像の大きさのコンテキストを用意.
        UIGraphicsBeginImageContextWithOptions(CGSize(width: ratio, height: ratio - 50), false, 0.0)
        //UIGraphicsBeginImageContext(CGSize(width: ratio, height: ratio - 50))
        
        // コンテキストに自身に設定された画像を描画する.
        self.draw(in: CGRect(x: 0, y: 0, width: ratio, height: ratio - 50))
        
        // コンテキストからUIImageを作る.
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // コンテキストを閉じる.
        UIGraphicsEndImageContext()
        
        return newImage
    }
}

host名はコンソールの”gs〜”の箇所に表示されています。 f:id:ka0in:20171230213855p:plain

Extensionを追加したら、使用する側は下記の通りになります。

 UIImage.contentOfFIRStorage(path: "category/img01.jpg") { image in
                cell.image = image?.resizeUIImageRatio(ratio: cellSize)
            }

Callbackが受け取れるので、Image情報取得できた際に処理が走るような仕組みになっています。

詳解 Swift 第4版

詳解 Swift 第4版