SwiftUI filter array via searchBar

眉间皱痕 提交于 2020-01-06 06:06:37

问题


I been suggested in order to perform a search on array in different thread (to avoid the block of my view) the use of a @state var but I keep getting this error..

Argument passed to call that takes no arguments...

I simplify my code in a new project and still gave me error..looks for some tips..

this my contentView

import SwiftUI

struct ContentView: View {
    @ObservedObject var dm: DataManager
    @State private var searchTerm : String = ""
    @State var filteredAirports: [AirportModel] = []


    init() {
           dm.filter(valoreSearhed: searchTerm, arrayTosearh: dm.airportVector) {
               self.filteredAirports = $0
           }
       }

    var body: some View {
        VStack {
             SearchBar(text: $searchTerm)
            List{
                ForEach(filteredAirports){ item in
                    Text(item.aptICAO)
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(dm: DataManager())  // Argument passed to call that takes no arguments
    }
}

I have tried to remove the preview but he give more waning .. probably that init should be position in another place?

here below a function in my DataManager class for the filter

 func filter (valoreSearhed: String, arrayTosearh: [AirportModel],  closure: @escaping exit)  {
        DispatchQueue.global().async {
            let aeroportoFiltrato  = arrayTosearh.filter { $0.aptICAO.localizedCaseInsensitiveContains(valoreSearhed) }
            closure(aeroportoFiltrato)
        }
    }

I put here my DataManager class in case... but I guess the problem is not here..

class DataManager: ObservableObject {
    let objectWillChange = PassthroughSubject<Void,Never>()
    static let shared = DataManager()

    @Published var airportVector : [AirportModel] = []{
    didSet {
        objectWillChange.send()
    }}

    typealias AirportVector = [AirportModel]
    typealias completition = () -> ()
    typealias exit = ((_ airport: [AirportModel]) -> ())
    init() {

        debugPrint("APRO")
        self.caricaDati()

        self.openfilejson(fileName: "apt") {
            debugPrint("FINISH LOAD")
        }

        self.caricaDati()



    }
    var filePath : String = ""

    func caricaDati() {
        // creiamo il percorso al file
        filePath = cartellaDocuments() + "/airport.plist"

        // usiamo NSFileManager per sapere se esiste un file a quel percorso
        if FileManager.default.fileExists(atPath: filePath) {

            // se c'è de-archiviamo il file di testo nell'array
            // serve il blocco do try catch
            do {
                // proviamo a caricare il file dal percorso creato in precedenza
                let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
                // creiamo il decoder
                let decoder = PropertyListDecoder()
                // proviamo a decodificare il file nell'array
                airportVector = try decoder.decode(AirportVector.self, from: data)
            } catch {
                // se non ce la fa scriviamo in console l'errore
                debugPrint(error.localizedDescription)
            }

            // adesso abbiamo i dati e possiamo far andare l'App

            // *** ATTENZIONE***
            // funziona solo se il Model è conforme a Codable
            // *** ********* ***
        }
    }

    func salva() {
        // creiamo l'encoder
        let encoder = PropertyListEncoder()
        encoder.outputFormat = .xml // impostiamo l'output corretto
        // serve il blocco do try catch
        do {
            // proviamo a codificare l'array
            let data = try encoder.encode(airportVector)
            // proviamo a salvare l'array codificato nel file
            try data.write(to: URL(fileURLWithPath: filePath))
        } catch {
            // se non ce la fa scriviamo in console l'errore
            debugPrint(error.localizedDescription)
        }

        // *** ATTENZIONE***
        // funziona solo se il Model è conforme a Codable
        // *** ********* ***
    }

    func cartellaDocuments() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        //print(paths[0])
        return paths[0]
    }

    func openfilejson (fileName : String, completition: completition) {
          if let path = Bundle.main.path(forResource: fileName, ofType: "json") {
              do {
                  let fileUrl = URL(fileURLWithPath: path)
                  let datafile = try Data(contentsOf: fileUrl,options: .mappedIfSafe)
                  let json = JSON(data:datafile)

                  for (key,_) in json {

                      let airport = AirportModel(aptICAO: "")

                      airport.aptICAO = json[key]["icao"].stringValue

                      airportVector.append(airport)
                    debugPrint(airport.aptICAO)
                  }

              } catch {
                   print("ERRORE OPEN FILE AEROPORTI")
              }

          }
           salva()
          completition()
      }


    func filter (valoreSearhed: String, arrayTosearh: [AirportModel],  closure: @escaping exit)  {
        DispatchQueue.global().async {
            let aeroportoFiltrato  = arrayTosearh.filter { $0.aptICAO.localizedCaseInsensitiveContains(valoreSearhed) }
            closure(aeroportoFiltrato)
        }
    }
}

and my model

import Foundation

class AirportModel: Identifiable , Codable {
    var id : UUID = UUID()
    var aptICAO : String

init(aptICAO: String) {
    self.aptICAO = aptICAO
}
}

thanks in advance for the help.. honestly I can't understand why that warning.

来源:https://stackoverflow.com/questions/59600719/swiftui-filter-array-via-searchbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!