Search code examples
iosswiftuidocumentpickerviewcontroller

How to get data from a CSV in swift when using UIDocumentPickerViewController


I cannot find a way to import data from a CSV file. I want the data to be loading into an array.

I have tried Googling this but nothing I find seems to work for my case

This is my UIDocumentPickerViewController.

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    let urlst = "\(urls)"

    if urlst.fileExtension() == "csv]" || urlst.fileExtension() == "csv" {
        // Start Import Action From CSV File
    } else {
        let alert = UIAlertController(title: "An Error Occured!", message: "The file you were trying to inport is not supported.  Only csv is support.", preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "Ok", style: .default , handler: nil))

        alert.addAction(UIAlertAction(title: "Try Again", style: .default , handler: { (UIAlertAction) in
            self.toImport()
        }))

        self.present(alert, animated: true, completion: nil)
    }
}

My expected result is to get the csv file that the user selected using the UIDocumentPickerViewController and then importing it into an array or more then one. But I cannot find a way to make this work.


Solution

  • I finally found the solution to my problem. Here is the code:

    let path = url.path
            let importer = CSVImporter<exportDataImport>(path: path)
            importer.startImportingRecords { recordValues -> exportDataImport in
                return exportDataImport(name: recordValues[0], pricePer: recordValues[2], amount: recordValues[1], isComplte: recordValues[4], Qty: recordValues[3])
                }.onFinish { importedRecords in
    
                var tempArray = [exportDataImport]()
                for record in importedRecords {
                    tempArray.append(record)
                }
    
                if tempArray.count > 0 {
                    tempArray.removeFirst(1)
                    self.importArray = tempArray
                    self.startImport()
                }
            }