gpt4 book ai didi

ios - 如何使用swift在firebase上上传多张图片?

转载 作者:搜寻专家 更新时间:2023-11-01 05:51:59 24 4
gpt4 key购买 nike

我只想使用 swift 在 firebase 上上传多张图片。我现在正在上传一张图片,但无法上传多张图片。这是我的代码

let photoIdString = NSUUID().uuidString
let storageRef = Storage.storage().reference(forURL: Config.STORAGE_ROOF_REF).child("posts").child(photoIdString)
storageRef.putData(imageData, metadata: nil,completion: {(metadata,error) in

if error != nil {
return
}
let photoUrl = metadata?.downloadURL()?.absoluteString
let ref = Database.database().reference()
let postReference = ref.child("posts")
let newPostId = postReference.childByAutoId().key
let newPostReference = postReference.child(newPostId)
newPostReference.setValue(["photoUrl":photoUrl,"caption":self.textView.text!])

最佳答案

目前没有直接的批量上传/下载文件的API。我们不能使用循环,因为所有任务都是异步执行的。我们可以做的是使用递归函数。

核心逻辑

let images = [image1, image2, image3, image4]
func uploadImage(forIndex index: Int) {
if index < images.count {
/// Perform uploading
/// After successfully uploading call this method again by increment the **index = index + 1**
return;
}

/// All images have been uploaded successfully
}

完整代码示例

<强>1。我为文件上传创建了一个自定义类

import UIKit
import Firebase

class FirFile: NSObject {

/// Singleton instance
static let shared: FirFile = FirFile()

/// Path
let kFirFileStorageRef = Storage.storage().reference().child("Files")

/// Current uploading task
var currentUploadTask: StorageUploadTask?

func upload(data: Data,
withName fileName: String,
block: @escaping (_ url: String?) -> Void) {

// Create a reference to the file you want to upload
let fileRef = kFirFileStorageRef.child(fileName)

/// Start uploading
upload(data: data, withName: fileName, atPath: fileRef) { (url) in
block(url)
}
}

func upload(data: Data,
withName fileName: String,
atPath path:StorageReference,
block: @escaping (_ url: String?) -> Void) {

// Upload the file to the path
self.currentUploadTask = path.putData(data, metadata: nil) { (metaData, error) in
let url = metaData?.downloadURL()?.absoluteString
block(url)
}
}

func cancel() {
self.currentUploadTask?.cancel()
}
}

<强>2。在这里我们如何使用它

首先为 main 函数创建一个完成 block ,它将让您知道何时所有图像都将成功上传。

/// This is your images array
let images = [image1, image2, image3, image4]

/// Here is the completion block
typealias FileCompletionBlock = () -> Void
var block: FileCompletionBlock?

下面是两个函数,第一个是初始函数,它将开始上传,第二个是递归函数,如果有下一张图片可供上传,它将自行调用。

func startUploading(completion: @escaping FileCompletionBlock) {
if images.count == 0 {
completion()
return;
}

block = completion
uploadImage(forIndex: 0)
}

func uploadImage(forIndex index:Int) {

if index < images.count {
/// Perform uploading
let data = UIImagePNGRepresentation(images[index])!
let fileName = String(format: "%@.png", "yourUniqueFileName")

FirFile.shared.upload(data: data, withName: fileName, block: { (url) in
/// After successfully uploading call this method again by increment the **index = index + 1**
print(url ?? "Couldn't not upload. You can either check the error or just skip this.")
self.uploadImage(forIndex: index + 1)
})
return;
}

if block != nil {
block!()
}
}

最后是带有完成 block 的 main 函数

startUploading {
/// All the images have been uploaded successfully.
}

为新的 Firebase 编辑“上传”功能:

唯一不同的是获取下载地址的方式。这是 new Firebase doc同样。

func upload(data: Data,
withName fileName: String,
atPath path:StorageReference,
block: @escaping (_ url: String?) -> Void) {

// Upload the file to the path
self.currentUploadTask = path.putData(data, metadata: nil) { (metaData, error) in
guard let metadata = metadata else {
    // Uh-oh, an error occurred!
block(nil)
    return
  }
  // Metadata contains file metadata such as size, content-type.
  // let size = metadata.size
  // You can also access to download URL after upload.
  path.downloadURL { (url, error) in
    guard let downloadURL = url else {
      // Uh-oh, an error occurred!
block(nil)
return
    }
block(url)
  }
}
}

关于ios - 如何使用swift在firebase上上传多张图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49934195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com