当前,我有一个应用程序,当用户拍照时,它会自动保存在存储中,然后将URL保存到存储中。但是,每当我添加新图像时,它只会将旧图像更改为新图像。我想添加新的。最终目标是使用户能够将自己拍摄的图像数组保存到自己的帐户下。
下面是我保存用户拍摄图像的代码:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let userPickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// let imageToUse = PhotoArray()
// let data = UIImagePNGRepresentation(userPickedImage) //here convert to data
PhotoArray.sharedInstance.photosArray.append(userPickedImage) //append converted data in array
// do {
// try realm.write {
// realm.add(imageToUse)
// }
// } catch {
// print(“error adding image to array\(error)“)
// }
imageView.image = userPickedImage
//-----------------------------//
//Create a reference to the image
let imageRef = Storage.storage().reference().child("image.jpg")
// Get image data
if let uploadData = UIImagePNGRepresentation(userPickedImage) {
// Upload image to Firebase Cloud Storage
imageRef.putData(uploadData, metadata: nil) { (metadata, error) in
guard error == nil else {
// Handle error
return
}
// Get full image url
imageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
// Handle error
return
}
// Save url to database
Firestore.firestore().collection("images").document("myImage").setData(["imageUrl" : downloadURL.absoluteString])
}
}
}
//-----------------------------//
}
// print(PhotoArray().photosArray.count)
imagePicker.dismiss(animated: true, completion: nil)
}
答案 0 :(得分:0)
您无法将图像保存到Firebase Cloud Firestore。您可以通过访问Google并搜索Firebase Cloud Storage文档来尝试使用Firebase Cloud Storage。
答案 1 :(得分:0)
这是我如何使用Firebase存储保存多个图像的一小段代码。我两次调用了uploadProfileImage()并在存储路径中设置了NSUUID()。uuidString,因此基本上在每个实例上都调用了该函数,调用时间几乎没有什么不同,并且不会被覆盖:)
@IBAction func saveImages(_ sender: Any) {
self.uploadProfileImage(frontImage!) { url in
if url != nil {
print("success")
} else {
print("failed!")
}
}
self.uploadProfileImage(backImage!) { url in
if url != nil {
print("success")
} else {
print("failed!")
}
}
dismiss(animated: false, completion: nil)
}
func uploadProfileImage(_ image:UIImage, completion: @escaping ((_ url:URL?)->())) {
guard let uid = Auth.auth().currentUser?.uid else { return }
let imageTime = NSUUID().uuidString
let storageRef = Storage.storage().reference().child("users/\(uid)/\(imageTime)")
let imageData = image.jpegData(compressionQuality: 0.75)
let metaData = StorageMetadata()
metaData.contentType = "image/jpg"
storageRef.putData(imageData!, metadata: metaData) { metaData, error in
if error == nil, metaData != nil {
storageRef.downloadURL{ url, error in
completion(url)
}
}
else {
completion(nil)
}
}
}