【发布时间】: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