firebase Swift如何使用async/await in for

jk9hmnmh  于 2023-03-03  发布在  Swift
关注(0)|答案(1)|浏览(180)

我想知道如何使用异步/等待在由斯威夫特。

var data = [String]()
    func uploadImage(images: [UIImage]) async -> Array<String> {
        
        for image in images{
            
                 ImageUploader.uploadImages(image: image, type: .post) { imageUrl async in
                    await self.data.append(imageUrl)
                }
            
        }
        return data
    }
static func uploadImages(image: UIImage,type: UploadType,completion: @escaping(String) -> Void) async{
        guard let imageData = image.jpegData(compressionQuality: 0.5) else{return}
        let ref = type.filePath
        
        ref.putData(imageData,metadata: nil){ _, error in
            if let error = error{
                print("DEBUG: Failed to upload image\(error.localizedDescription)")
                return
            }
            
            print("Successfully uploaded image")
            
            ref.downloadURL{ url, _ in
                guard let imageUrl = url?.absoluteString else {return}
                completion(imageUrl)
            }
        }
    }

当我调用func uploadImage时,没有等待self.data.append(imageUrl)数据返回空数组。
我想让uploadImage等待append,那么字符串数组应该返回包含uploadImages的imageUrl的数组。
我该怎么更正呢。谢谢。

fykwrbwg

fykwrbwg1#

看起来自从我上次看API Firebase以来,它已经提供了自己的async/await方法。用于上传图像的是imageRef.putDataAsync(imageData)

///Uploads Data to the designated path in `FirebaseStorage`
static func upload(imageData: Data, path: String) async throws -> URL{
    let storageRef = storage.reference()
    let imageRef = storageRef.child(path)
    
    let metadata = try await imageRef.putDataAsync(imageData)
    return try await imageRef.downloadURL()
}

然后,您可以使用withThrowingTaskGroup同时上载,或者使用常规for循环1x1上载。

import UIKit
import FirebaseStorageSwift
import FirebaseStorage
struct ImageStorageService{
    static private let storage = Storage.storage()
    ///Uploads a multiple images as JPEGs and returns the URLs for the images
    ///Runs the uploads simultaneously
    static func uploadAsJPEG(images: [UIImage], path: String, compressionQuality: CGFloat = 1) async throws -> [URL]{
        return try await withThrowingTaskGroup(of: URL.self, body: { group in
            for image in images {
                group.addTask {
                    return try await uploadAsJPEG(image: image, path: path, compressionQuality: compressionQuality)
                }
            }
            var urls: [URL] = []
            for try await url in group{
                urls.append(url)
            }
            
            return urls
        })
    }
    
    ///Uploads a multiple images as JPEGs and returns the URLs for the images
    ///Runs the uploads one by one
    static func uploadAsJPEG1x1(images: [UIImage], path: String, compressionQuality: CGFloat = 1) async throws -> [URL]{
        var urls: [URL] = []
        for image in images {
            let url = try await uploadAsJPEG(image: image, path: path, compressionQuality: compressionQuality)
            urls.append(url)
        }
        return urls
    }
    ///Uploads a single image as a JPG and returns the URL for the image
    ///Runs the uploads simultaneously
    static func uploadAsJPEG(image: UIImage, path: String, compressionQuality: CGFloat = 1) async throws -> URL{
        guard let data = image.jpegData(compressionQuality: compressionQuality) else{
            throw ServiceError.unableToGetData
        }
        
        return try await upload(imageData: data, path: path)
    }
    ///Uploads Data to the designated path in `FirebaseStorage`
    static func upload(imageData: Data, path: String) async throws -> URL{
        let storageRef = storage.reference()
        let imageRef = storageRef.child(path)
        
        let metadata = try await imageRef.putDataAsync(imageData)
        return try await imageRef.downloadURL()
    }
    
    enum ServiceError: LocalizedError{
        case unableToGetData
    }
}

相关问题