UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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{
        }
    }

}

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.