我正在尝试将图像上传到Firebase存储。这是我到目前为止的内容:
fileprivate func uploadImageToFirebase(){
let storageRef = Storage.storage().reference()
guard let uploadData = imageToUpload?.pngData() else { return }
storageRef.putData(uploadData, metadata: nil) { (metadata, err) in
if err != nil {
print(err?.localizedDescription)
return
}
print(metadata)
}
}
uploadData不是nil,但是我的应用程序崩溃了。这就是我得到的:
reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1]'
我试图查找,但不明白为什么该应用程序崩溃以及如何修复。 我知道我要插入nil,但是我没有nil。
答案 0 :(得分:0)
我知道了,这就是我现在所拥有的:
fileprivate func uploadImageToFirebase(completion: @escaping((_ url: String?)->())){
let imageName = UUID().uuidString
let storageRef = Storage.storage().reference()
let imagesRef = storageRef.child(imageName)
guard let uploadData = imageToUpload?.jpegData(compressionQuality: 0.8) else { return }
let metaData = StorageMetadata()
metaData.contentType = "image/jpeg"
imagesRef.putData(uploadData, metadata: metaData) { (metadata, err) in
if err == nil && metadata != nil {
imagesRef.downloadURL(completion: { (url, err) in
guard let downloadUrl = url else { return }
let urlString = downloadUrl.absoluteString
completion(urlString)
})
}
completion(nil)
}
}
编辑:
问题中的代码存在问题,即没有为要上传的文件分配名称。换句话说
let storageRef = Storage.storage().reference()
是对存储本身的引用,但是当上传到存储时,需要这样的文件名
let storageRef = Storage.storage().reference()
let myFile = storageRef.child("my_cool_pic.jpg")
用途是
myFile.putData(uploadData, metadata: nil)...