如何将一组(阵列)图像保存到Firebase云存储中?

时间:2018-08-16 18:56:30

标签: ios arrays swift firebase firebase-storage

我正在尝试将用户保存到云存储中的图像数组保存下来,然后在该人员个人资料下保存指向该图像的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)
}

1 个答案:

答案 0 :(得分:0)

我在firebase文档中找到了这个

// Add a new document with a generated id.
var ref: DocumentReference? = nil
ref = db.collection("cities").addDocument(data: [
"name": "Tokyo",
"country": "Japan"
]) { err in
if let err = err {
    print("Error adding document: \(err)")
} else {
    print("Document added with ID: \(ref!.documentID)")
}
}

希望这会对您有所帮助。 您可以在这里阅读有关内容:Click me