在Firebase中上传多张图片

时间:2019-06-13 08:28:08

标签: swift firebase

上传图片文件url时,仅上传最后一个

if 0 < imageData.count {
            var imagesCount:Int = 0
            var fileNumbers:Int = 0
            var temp:Int = 0
            for data in imageData {
                fileNumbers += 1
                let uploadTask = storageRef.child("\(fileNumbers).jpg").putData(data)
                uploadTask.observe(.success) { snapshot in
                    imagesCount += 1
                    storageRef.child("\(fileNumbers).jpg").downloadURL(completion: { url, error in
                        if error != nil {
                            print("error: \(error!)")
                        } else {
                            let downloadURL = url?.absoluteString
                            DatabaseReference.child("User").child(self.userID!).child("Puppy").child("Walk").child("WalkData").child("\(self.walkCache["dataInt"]!)").child("images").updateChildValues(["imageURL\(fileNumbers)":downloadURL!])
                            print("=============================")
                            print(fileNumbers)
                            print(downloadURL!)
                            print("=============================")
                        }
                    })
                    if self.imageData.count == imagesCount {
                        self.indicatorView.stopAnimating()
                        self.subIndicatoreView.stopAnimating()
                        FileManager.shared.clearTmpDirectory()
                        //self.view.removeFromSuperview()
                    }
                }

            }
        }

我的控制台

============================= 2

sameurl

============================= 2

sameurl

1 个答案:

答案 0 :(得分:0)

我编写了一个在Firebase存储中上传图片的功能,请使用此功能,您也可以多次调用它以并行上传多张图片。

public func uploadData(data: Data, serverFileName: String) {

        let storage = Storage.storage()
        let storageRef = storage.reference()
        // Create a reference to the file you want to upload
        var directory = "images/"

        let fileRef = storageRef.child(directory + serverFileName);

        // Upload the file to the path "images/rivers.jpg"
        let uploadTask = fileRef.putData(data, metadata: nil) { metadata, error in
            /*   guard let metadata = metadata else {
             // Uh-oh, an error occurred!
             print("Uh-oh, an error occurred! in metadata retreiving")

             return
             } */
            // Metadata contains file metadata such as size, content-type.
            //       let size = metadata.size
            // You can also access to download URL after upload.
            fileRef.downloadURL { (url, error) in
                guard let downloadURL = url else {
                    // Uh-oh, an error occurred!


                    return
                }

                // File Uploaded Successfully
                // file url is here downloadURL.absoluteString
            }
        }
    }