Blog

Swift Firebase Storage 実装忘備録

FireStorage 保存処理

doneボタンが押されたタイミングでFirbaseStrageへ保存

Point_1 画像のリサイズが必要。カメラは最近4Mとか平気で容量があるので、リサイズをかませる

Point_2 Firebaseには urlのpathを保存する

       @IBAction func doneButtonTapped(_ sender:Any) {
        
        if isMember(of: DiaryCreateController.self) {
            checkPointsAndDatesThenUploadPhoto()
            return
        }
        //trailing closure for image_url
        uploadPhoto() { imgRef in self.saveDiary(photoRef: imgRef) }
    }

    private func uploadPhoto(callback: @escaping ((String?)->Void)) {

//リサイズが必要
        guard  let diaryImage = diaryImage.image, diaryImage != defaultImg else { callback(nil); return }
        let size = diaryImage.size
        let ratio = size.width / size.height
        let w = CGFloat(150)
        let h = w / ratio
        guard  let resizeImage = diaryImage.resize(size: .init(width: w, height: h)) else { return }
        
//compressionQualityだけでは間に合わない 300KBを超える
        guard let imgData = resizeImage.jpegData(compressionQuality:0.5) else {
            callback(nil)
            return
        }
        let fileName = NSUUID().uuidString
        let storageRef = Storage.storage().reference().child("diaryImages").child(fileName)

        storageRef.putData(imgData, metadata: nil) { (metadata, error) in

            if let error = error {
                print("upload error: \(error)")
                callback(nil)
                return
            }

            callback(metadata?.path)
        }
    }

checkPointsAndDatesThenUploadPhotoはこちら

こちらはシングルトンのチェックくらいしか実装していません。

他のコードが混ざっているのはご了承ください

private func checkPointsAndDatesThenUploadPhoto() {
        var checkPoint = false
        var checkDate = false
        let dpg = DispatchGroup()
        
        dpg.enter()
        checkPoints { (point, err) in
            defer { dpg.leave() }
            if let err = err { print(err) }
            guard let point = point else { return }
            User.loggedIn?.points += point
            User.loggedIn?.save()
            checkPoint = true
        }
        
        // Firebase search
        dpg.enter()
        checkDates {
            defer { dpg.leave() }
            checkDate = $0
        }
        
        dpg.notify(queue: .main) {
            guard checkPoint, checkDate else { return }
            self.uploadPhoto() { imgRef in self.saveDiary(photoRef: imgRef) }
        }
    }

FireStorageからの削除処理


func deleteDiary(){
        guard let id = diary?.documentId else { return}
        
        //First delete image from firestrage
        if let fileName = diary?.photo {
            print("delete item: \(fileName), from diary: \(id)")

// ここがPoint 保存時とPathが違う
            let storageRef = Storage.storage().reference().child(fileName)
            // Delete the file
            storageRef.delete() { error in
                if let err = error{
                    debugPrint(err)
                }
            }
        }
        
        //Second delete from firebase
        userREF.collection(DIARY_REF).document(id).delete()  { error in
            
            if let err = error{
                print("error delete :\(err)")
                let alert = UIAlertController(title: "Error in Delete", message: "OK", preferredStyle: .alert)
                let action = UIAlertAction(title: "Dismiss", style: .default, handler: nil)
                alert.addAction(action)
                self.present(alert, animated: true, completion: nil)
            }
        }
        navigationController?.popToRootViewController(animated: true)
    }

質問や、アプリの要望等ありましたら、教えていただけますか?

こちらからご連絡、お願いいたします。

コネクト facebook page