【问题标题】:How to upload an array of images in Firebase Storage using iOS Swift如何使用 iOS Swift 在 Firebase 存储中上传一组图像
【发布时间】:2020-07-25 00:51:07
【问题描述】:

我想按用户上传一组图片 这是我将单个图像上传到 Firebase 存储时的代码,请参阅代码:1。但是当我上传图像数组时遇到问题。参考代码:2

代码:1

func uploadImage(image:UIImage,userId:String,completion:@escaping(_ status:Bool,_ response:String)->Void){
        // if status is true then downloadurl will be in response
        // Data in memory
        guard let data = image.jpegData(compressionQuality: 0.2) else{
            completion(false,"Unable to get data from image")
            return
        }
        // Create a reference to the file you want to upload
        let riversRef = firebaseStorage.reference().child("images/\(userId).jpg")
        // Upload the file to the path "images/rivers.jpg"
        let _ = riversRef.putData(data, metadata: nil) { (metadata, error) in
            guard let _ = metadata else{
                // Uh-oh, an error occurred!
                completion(false,error!.localizedDescription)
                return
            }
            // You can also access to download URL after upload.
            riversRef.downloadURL { (url, error) in
                guard let downloadURL = url else{
                    // Uh-oh, an error occurred!
                    completion(false,error!.localizedDescription)
                    return
                }
                completion(true,downloadURL.absoluteString)
            }
        }
    }

代码:2

func uploadPostImages(image:[UIImage],userId:String,completion:@escaping(_ status:Bool,_ response:String)->Void){
        let photoDictionary = ["postImages": PostArray.sharedInstance.photosArray as NSArray]
         // Create a reference to the file you want to upload
         let riversRef = firebaseStorage.reference().child("postImages/\(userId).jpg")
         // Upload the file to the path "images/rivers.jpg"
         let _ = riversRef.putData(photoDictionary, metadata: nil) { (metadata, error) in
             guard let _ = metadata else{
                 // Uh-oh, an error occurred!
                 completion(false,error!.localizedDescription)
                 return
             }
             // You can also access to download URL after upload.
             riversRef.downloadURL { (url, error) in
                 guard let downloadURL = url else{
                     // Uh-oh, an error occurred!
                     completion(false,error!.localizedDescription)
                     return
                 }
                 completion(true,downloadURL.absoluteString)
             }
         }
     }

我在代码中收到此错误:2

Cannot convert value of type '[String : NSArray]' to expected argument type 'Data'

谁能帮帮我??

【问题讨论】:

  • 代码很混乱。 var photoDictionary 包含一个键:字符串的值对,然后是某种类型的数组 let photoDictionary = ["postImages": PostArray.sharedInstance.photosArray as NSArray] 然后你想把它上传到存储中吗? riversRef.putData(photoDictionary?您需要上传某种数据,而不是字典,请查看您的第一个示例guard let data = image.jpegData。换句话说,代码 2 不能按原样工作。为什么不遍历包含图像的数组并将每个图像传递给第一个示例中的代码,相应地更改名称?

标签: ios swift firebase firebase-storage


【解决方案1】:

据我所知,这样的事情应该可行。抱歉,我不在 IDE 中。如果这不起作用,请发表评论,我会仔细看看。

func uploadImages(
images:[UIImage],
userId:String,
completion:@escaping(_ status:Bool,_ response:String)->Void)
{
        images.enumerated().forEach { (index, image) in 
        guard let data = image.jpegData(compressionQuality: 0.2) else{
            completion(false,"Unable to get data from image")
            return
        }
        // Create a reference to the file you want to upload
        let riversRef = firebaseStorage.reference().child("images/\(userId)\(index).jpg")
        // Upload the file to the path "images/rivers.jpg"
        let _ = riversRef.putData(data, metadata: nil) { (metadata, error) in
            guard let _ = metadata else{
                // Uh-oh, an error occurred!
                completion(false,error!.localizedDescription)
                return
            }
            // You can also access to download URL after upload.
            riversRef.downloadURL { (url, error) in
                guard let downloadURL = url else{
                    // Uh-oh, an error occurred!
                    completion(false,error!.localizedDescription)
                    return
                }
                completion(true,downloadURL.absoluteString)
            }
         }
       }
    }

【讨论】:

  • 工作正常,但这是多次上传数据。我一次上传 5 张图片,所以我希望它以数组的形式上传 5 张图片,或者在单个实例中上传一些东西。屏幕截图在链接sendspace.com/file/i9sjc7提前谢谢
  • 您发送给我的屏幕截图来自 Firestore.firestore(),但是图像如何上传到 Storage.storage()?我得看看你是如何将数据写入 Firestore 的。
  • 我是这样写的,请检查链接中的屏幕截图sendspace.com/file/rqdvsp 如果你想让我把代码发给你,我可以发给你
  • 你有 GitHub 仓库吗?把链接发给我。
  • 检查您的邮件,我邀请您在 github 作为我的 repo 的合作者创建您的分支并推送您的分支中的更改
【解决方案2】:

此代码将上传一组图像

func uploadImages(images:[UIImage], userId:String, completion:@escaping(_ status:Bool, _ response:String)->Void){
    
    guard images.count <= 5 && !images.isEmpty else {return}
    
    convertImagesToData(images: images).enumerated().forEach { (index, image) in
        
        let riversRef = firebaseStorage.reference().child("userAdPostImages/\(userId)\(index).jpg")
        
        let _ = riversRef.putData(image, metadata: nil, completion: { (_ , error) in
            
            if let error = error {
                completion(true, error.localizedDescription)
                return
            }
            
            riversRef.downloadURL(completion: {(url, error) in
                
                if let error = error{
                    completion(true,error.localizedDescription)
                    return
                }
                
                guard let downloadURL = url else {return}
                completion(false,downloadURL.absoluteString)
            })
        })
    }
}

这会将您的帖子添加到 Firebase,包括数组图像

    func addPost() {
    hud.show()
    dispatchGroup.enter()
    let user = Auth.auth().currentUser
    if let user = user {
        self.userId = user.uid
    }
    let location = self.locationTextfield.text ?? ""
    let type = self.selectedType ?? ""
    let description = self.descriptionTextView.text ?? ""
    let adImages = self.adImages
    let userId = self.userId ?? ""
    let price = priceTextfield.text ?? ""
    let userName = self.userName ?? ""
    let userProfileImage = self.userProfileImage ?? ""
    let userphoneNumber = self.phoneNumber ?? ""

    ServerManager.sharedDelegate.uploadImages(images: adImages, userId: userId) { (isError, urlString) in
        
        guard !isError else {
            DispatchQueue.main.async {
                hud.hide()
            }
            return
        }
        
        self.imagePaths.append(urlString)
        print("This is the image path saved \(self.imagePaths)!!!!")
        
        if self.imagePaths.count == adImages.count {
            self.dispatchGroup.leave()
        }
    }
    dispatchGroup.notify(queue: .global(qos: .background), execute: {
        ServerManager.sharedDelegate.addPost(UserProfileImage: userProfileImage, UserName: userName, phoneNumber: userphoneNumber, adImages: self.imagePaths, Price: price, location: location, type: type, Description: description) { _ , message in
            
            DispatchQueue.main.async {
                hud.hide()
                self.vc?.view.makeToast(message)
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    self.vc?.dismiss(animated: true, completion: nil)
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
                }
                
            }
            return
        }
    })
}

感谢@MichaelWells 的帮助,很抱歉延迟发布答案

【讨论】:

    【解决方案3】:

    您可以对字典进行编码,然后将其存储为数据:

    let data = JSONEncoder().encode(photoDictionary)
    

    【讨论】:

      猜你喜欢
      • 2019-01-30
      • 2016-11-08
      • 2018-12-01
      • 2020-04-26
      • 2016-12-30
      • 1970-01-01
      • 2020-07-05
      • 2017-09-25
      • 2020-08-28
      相关资源
      最近更新 更多