Пытаюсь реализовать возможно добавления нескольких фото в массив который потом будет загружен в Fierebase

Создаю пустой массив и вызываю ImagePicker из которого хочу брать несколько фото и передавать их в массив, все добавленные фото будут выводиться во View и далее массив будет загружен на сервер. В данный момент я смог выполнить лишь для одной фотографии.

struct CreateWochnungPostView: View {


@Binding var showCreatePost: Bool
@State var showActionSheet = false
@State var showImagePicker = false
@State private var showAlert = false
@State var imagePost: [UIImage?] = []
@State var uiImage: UIImage? = nil

  var body: some View {
    ZStack {
        Color.white.edgesIgnoringSafeArea(.all)
        ScrollView(.vertical, showsIndicators: false) {

            //MARK: TOP
            HStack(alignment: .center) {
                Text("Wochnung")
                    .font(.system(size: 20, weight: .semibold, design: .serif))
                    .foregroundColor(Color(#colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)))
                    .padding(15)
                    .modifier(NeumorphicStyleTextButton(bgColor: Color(#colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9529411765, alpha: 1))))
                Spacer()
                VStack {
                    Button(action: {
                        self.showCreatePost = false
                    }) {
                        Image(systemName: "xmark")
                            .font(.system(size: 16, weight: .medium))
                            .foregroundColor(.gray)
                    }
                }
                .frame(width: 44, height: 44)
                .modifier(NeumorphicStyleTextButton(bgColor: Color(#colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9529411765, alpha: 1))))
            }
            .padding([.leading, .trailing], 10)

            //MARK: IMAGE
            VStack {
                Spacer()
                HStack {

                    //Uploading image
                    if (self.uiImage == nil) {
                        Image(systemName: "camera.circle")
                            .foregroundColor(Color.gray)
                            .frame(width: 100, height: 100)
                            .modifier(NeumorphicStyleTextButton(bgColor: Color(#colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9529411765, alpha: 1))))
                            .padding(20)
                            .onTapGesture {
                                self.showImagePicker = true
                        }
                    } else {
                        // Image(systemName: "camera")
                        Image(uiImage: uiImage!)
                            .resizable()
                            .frame(width: 100, height: 100)
                            .modifier(NeumorphicStyleTextButton(bgColor: Color(#colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9529411765, alpha: 1))))
                            .padding(20)
                            .onTapGesture {
                                self.showAction = true
                        }
                    }
                }

                .sheet(isPresented: $showImagePicker, onDismiss: {
                    self.showImagePicker = false
                }, content: {
                    ImagePickerView(isShown: self.$showImagePicker, uiImage: self.$uiImage)
                })
                    .actionSheet(isPresented: $showAction) {
                        sheet
                }

                Spacer()
                HStack(spacing: 40) {

                    Button(action: {
                        self.showImagePicker = true
                    }) {
                        Image(systemName: "tray.and.arrow.down")
                            .foregroundColor(Color(#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)))
                            .frame(width: 44, height: 44)
                            .modifier(NeumorphicStyleTextButton(bgColor: Color(#colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9529411765, alpha: 1))))
                    }


                    Button(action: {
                        self.showImagePicker = true
                    }) {
                        Image(systemName: "square.grid.3x2")
                            .foregroundColor(Color(#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)))
                            .frame(width: 44, height: 44)
                            .modifier(NeumorphicStyleTextButton(bgColor: Color(#colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9529411765, alpha: 1))))
                    }

                    Button(action: {
                        self.showImagePicker = true
                    }) {
                        Image(systemName: "rectangle.grid.1x2")
                            .foregroundColor(Color(#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)))
                            .frame(width: 44, height: 44)
                            .modifier(NeumorphicStyleTextButton(bgColor: Color(#colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9529411765, alpha: 1))))
                    }

                }

                VStack {
                    TextField("Stadt", text: self.$stadt)
                        .modifier(TextFieldFormStyleModifier())
                    TextField("Adresse", text: self.$adresse)
                        .modifier(TextFieldFormStyleModifier())
                    TextField("MieteZzgl", text: self.$mieteZzgl)
                        .modifier(TextFieldFormStyleModifier())
                    TextField("MieteInkl", text: self.$mieteInkl)
                        .modifier(TextFieldFormStyleModifier())
                    TextField("Nebenkosten", text: self.$nebenkosten)
                        .modifier(TextFieldFormStyleModifier())
                    TextField("Kaution", text: self.$kaution)
                        .modifier(TextFieldFormStyleModifier())
                    TextField("Zimmer", text: self.$zimmer)
                        .modifier(TextFieldFormStyleModifier())
                    TextField("Wochenflache", text: self.$wochenflache)
                        .modifier(TextFieldFormStyleModifier())
                    TextField("Etage", text: self.$etage)
                        .modifier(TextFieldFormStyleModifier())

                }
                .padding(.horizontal, 10)
                .padding(5)
                //MARK: BUTTON POST CREATE
                HStack {
                    Button(action: {
                        if self.fieldsComplited() == false {
                            self.showAlert = true
                        } else if self.fieldsComplited() == true {
                            self.uploadPostToFirebase()
                        }
                    }) {
                        Text("SENDEN")
                            .font(.system(size: 18, weight: .semibold, design: .rounded))
                            .foregroundColor(!self.fieldsComplited() == false ? Color.blue : Color.gray)
                            .frame(width: 120, height: 20)
                            .padding(15)
                            .modifier(NeumorphicStyleTextButton(bgColor: Color(#colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9529411765, alpha: 1))))
                    }
                    .alert(isPresented: self.$showAlert) { Alert(title: Text("Achtung!"), message: Text("Nicht alle Formularfelder sind ausgefullt!"), dismissButton: .cancel(Text("OK"))
                        )}
                }
                .padding(.top, 40)
                .padding(.bottom, 10)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
        .onTapGesture {
            self.hideKeyboard()
        }
    }
}
var sheet: ActionSheet {
    ActionSheet(
        title: Text("Внимение"),
        message: Text("Хотите изменить выбранную фотографию?"),
        buttons: [
            .default(Text("Изменить"), action: {
                self.showAction = false
                self.showImagePicker = true
            }),
            .cancel(Text("Закрыть"), action: {
                self.showAction = false
            }),
            .destructive(Text("Удалить"), action: {
                self.showAction = false
                 self.uiImage = nil

        })
    ])
}

//MARK: ADD IMAGE


//MARK: Проверка заполнения формы
private func fieldsComplited() -> Bool {
    return
        self.stadt != ""
            &&
            self.adresse != ""
            &&
            self.mieteZzgl != ""
            &&
            self.mieteInkl != ""
            &&
            self.kaution != ""
}

//MARK: UPLOAD POST / IMAGE
private func uploadPostToFirebase() {
    let save = CreateWochnung()
    save.id = UUID().uuidString
    save.stadte = stadt
    save.adresse = adresse
    save.mieteZzgl = Double(mieteZzgl)
    //if save.imagePost.count > 0 {
    print("*** UPLOAD START ***")
    uploadImages(images: [uiImage], itemId: save.id) { ( imageLinkArray ) in
        save.imagePost = imageLinkArray
        saveWochnungToFirestore(save)
        print("*** UPLOAD END ***")
        self.showCreatePost = false
    }

    // }
}

}

--------------ImagePickerView-------------

import Foundation import SwiftUI

struct ImagePickerView: UIViewControllerRepresentable {

@Binding var isShown: Bool
@Binding var uiImage: UIImage?

// var sourceType:UIImagePickerController.SourceType = .camera

class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @Binding var isShown: Bool
    @Binding var uiImage: UIImage?

    init(isShown: Binding<Bool>, uiImage: Binding<UIImage?>) {
        _isShown = isShown
        _uiImage = uiImage
    }

    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let imagePicked = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        uiImage = imagePicked
        isShown = false
    }



    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        isShown = false
    }

}

func makeCoordinator() -> Coordinator {
    return Coordinator(isShown: $isShown, uiImage: $uiImage)
}

func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePickerView>) -> UIImagePickerController {
    let picker = UIImagePickerController()
    //picker.sourceType = sourceType
    picker.delegate = context.coordinator
    return picker
}

func updateUIViewController(_ uiViewController: UIImagePickerController,
                            context: UIViewControllerRepresentableContext<ImagePickerView>) {

}

}


Ответы (1 шт):

Автор решения: schmidt9

С помощью UIImagePickerController выбрать несколько фото не получится, можно воспользоваться каким-либо сторонним решением, вот например список

→ Ссылка