如何使用 Swift 的 PHPickerController 在 firebase 上上传多张图片

How to upload multiple image on firebase using Swift's PHPickerController

因此在 Swift 中,您可以使用 UIImageViewController 轻松上传 image/video。我做了研究并遇到了 PHPickerController,我试图将其合并到我的代码中——原因是我想要选择多个 images/videos,一旦用户按下“按钮”,它就会将该批次推送到 firebase 云。我已经为此苦苦挣扎了一段时间。任何这样做的示例 swift 文件将不胜感激。

这对我有用。

注意:确保您从照片库中选择的图像不是 xCode 附带的默认图像。某些默认图像不起作用,因为它们没有文件位置。

SwiftUI 解决方案

这是调用 PHPickerViewController 的方式:

struct PHPicker: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> PHPickerViewController {
    var config = PHPickerConfiguration()
    config.selectionLimit = 5
    config.filter = PHPickerFilter.images
    
    let pickerViewController = PHPickerViewController(configuration: config)
    pickerViewController.delegate = context.coordinator
    return pickerViewController
}

func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {
}

class something: NSObject, PHPickerViewControllerDelegate {
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true)
        
        var fileName: Int = 5
        for result in results {
            
            // Get all the images that you selected from the PHPickerViewController
            result.itemProvider.loadObject(ofClass: UIImage.self) { object, error in
                // Check for errors
                if let error = error {
                    print("Sick error dawg \(error.localizedDescription)")
                } else {
                    // Convert the image into Data so we can upload to firebase
                    if let image = object as? UIImage {
                        let imageData = image.jpegData(compressionQuality: 1.0)
                        
                        // You NEED to make sure you somehow change the name of each picture that you upload which is why I am using the variable "count".
                        // If you do not change the filename for each picture you upload, it will try to upload the file to the same file and it will give you an error.
                        Storage.storage().reference().child("fileName").child("\(fileName)").putData(imageData!)
                        fileName += 1
                        print("Uploaded to firebase")
                    } else {
                        print("There was an error.")
                    }
                }
            }
        }
    }
}

func makeCoordinator() -> something {
    return something()
}

}

以下是我如何呈现 sheet:

struct PresentMyPicker: View {

@State var presentSheet: Bool = false

var body: some View {
    VStack {
        Button {
            presentSheet.toggle()
        } label: {
            Text("Click me")
        }
    }
    .sheet(isPresented: $presentSheet) {
        PHPicker()
    }
}

}

UIKit解决方案

这是我在点击按钮时显示 PHPickerViewController 的方式:

    func setupView() {
    var config = PHPickerConfiguration()
    config.selectionLimit = 5
    config.filter = PHPickerFilter.images
    
    let pickerViewController = PHPickerViewController(configuration: config)
    pickerViewController.delegate = self
    
    view.addSubview(button)
    button.addAction(UIAction() { _ in
        self.present(pickerViewController, animated: true)
    }, for: .touchUpInside)
}

这是我的委托函数,在您对要上传的选定图像单击“添加”后运行。

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    picker.dismiss(animated: true)
    
    var fileName: Int = 1
    for result in results {
        
        // Get all the images that you selected from the PHPickerViewController
        result.itemProvider.loadObject(ofClass: UIImage.self) { object, error in
            // Check for errors
            if let error = error {
                print("Sick error dawg \(error.localizedDescription)")
            } else {
                // Convert the image into Data so we can upload to firebase
                if let image = object as? UIImage {
                    let imageData = image.jpegData(compressionQuality: 1.0)
                    
                    // You NEED to make sure you somehow change the name of each picture that you upload which is why I am using the variable "fileName".
                    // If you do not change the filename for each picture you upload, it will try to upload all the selected images to the same file location and give you an error.
                    Storage.storage().reference().child("CollectionName").child("\(fileName)").putData(imageData!)
                    fileName += 1
                } else {
                    print("There was an error.")
                }
            }
        }
    }
}

此外,如果您想将视频上传到 firebase 并遇到问题,请查看此示例,我花了很长时间才弄明白。