WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

How do you save/export a CSV files to an extrenal flash drive?

Forums > iOS

Hello,

How do you save/export a CSV files to an extrenal flash drive? I know you're susposed to use UIDocumentPickerViewController, but I am confused how to do that with the code I have below. An pointer or direction would be appreciated!

Thank you,

Cameron

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func generateCSVFile(_ sender: Any) {

        let sFileName = "test.csv"

        let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String

        let documentURL = URL(fileURLWithPath: documentDirectoryPath).appendingPathComponent(sFileName)

        let output = OutputStream.toMemory()

        let csvWriter = CHCSVWriter(outputStream: output, encoding: String.Encoding.utf8.rawValue, delimiter: ",".utf16.first!)

        // HEADER
        csvWriter?.writeField("ASSET_ID")
        csvWriter?.writeField("COMPANY_NAME")

        csvWriter?.finishLine()

        var arrOfEmployeeData = [[String]]()

        arrOfEmployeeData.append(["1", "Company 1"])
        arrOfEmployeeData.append(["2", "Company 2"])
        arrOfEmployeeData.append(["3", "Company 3"])

        for(elements) in arrOfEmployeeData.enumerated()
        {
            csvWriter?.writeField(elements.element[0]) // ID
            csvWriter?.writeField(elements.element[1]) // Name
            csvWriter?.writeField(elements.element[2]) // Age
            csvWriter?.writeField(elements.element[3]) // Designation

            csvWriter?.finishLine()

        }

        csvWriter?.closeStream()

        let buffer = (output.property(forKey: .dataWrittenToMemoryStreamKey) as? Data)!

        do{
            try buffer.write(to: documentURL)
        }
        catch{
        }
    }

}

1      

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.