【问题标题】:Taking an image from photo library and uploading to Firebase从照片库中获取图片并上传到 Firebase
【发布时间】:2020-10-06 06:49:05
【问题描述】:

我正在尝试将我的照片库中的内容(最近拍摄的照片保存在库中)并上传到 Firebase 存储。

下面的代码是图像的保存并将其添加到库中:

// MARK: - Save image

@IBAction func savePhoto(_ sender: Any) {
    UIImageWriteToSavedPhotosAlbum(licensePhoto.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}


//MARK: - Add image to Library

func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        // we got back an error!
        let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    } else {
        let alert = UIAlertController(title: "Saved!", message: "Image saved successfully", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

我已经尝试了以下代码,只是给我一个错误:

致命错误:注册后解包 Optional 值时意外发现 nil!:

代码:

    // . . .  upload license photo to firebase
    

    var data = NSData()
    data = UIImageJPEGRepresentation(licensePhoto.image!, 0.8)! as NSData
    // set upload path
    let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\("userPhoto")"
    let metaData = FIRStorageMetadata()
    metaData.contentType = "image/jpg"
    DataService.Instance.storageRef.child(filePath).put(data as Data, metadata: metaData){(metaData,error) in
        if let error = error {
            print(error.localizedDescription)
            return
        }else{
            //store downloadURL
            let downloadURL = metaData!.downloadURL()!.absoluteString
            //store downloadURL at database
            DataService.Instance.dbRef.child("users").child(FIRAuth.auth()!.currentUser!.uid).updateChildValues(["userPhoto": downloadURL])
        }
        
    }
}

【问题讨论】:

  • 请将您的代码作为文本而不是图像包含在内,否则复制和修改它会更加困难。
  • 对不起,我会编辑它。谢谢

标签: swift3 ios10 firebase-storage


【解决方案1】:

我找到了答案:

  // . . .  upload license photo to firebase

    let storage = FIRStorage.storage().reference()
    let tempImgRef = storage.child("tmpDir/tmpImage.jpg")

    var data: NSData = NSData()
    data = UIImageJPEGRepresentation(licensePhoto.image!, 0.8)! as NSData

    let metaData = FIRStorageMetadata()
    metaData.contentType = "image/jpeg"

    tempImgRef.put(data as Data, metadata: metaData, completion: { (metaData, error) in
        if error == nil {
            print("success")

        } else {
            print(error?.localizedDescription as Any)
        }
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-06
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2016-05-16
    • 1970-01-01
    • 2016-12-27
    相关资源
    最近更新 更多