Hello,
I have Swift code that lets me select and read a CSV file. I would like to be able to hard code the path to the CSV file as a string in the @IBAction function OpenPanel instead of calling getCSVPath. To do so I think may require encoding the file path string but am unsure how to accomplish this.
Below is my code.
Chris
import Cocoa
func getCSVPath() -> String {
let dialog = NSOpenPanel()
dialog.title = "Select a CVS file"
dialog.showsResizeIndicator = true
dialog.showsHiddenFiles = false
dialog.allowsMultipleSelection = false
dialog.canChooseDirectories = false
dialog.allowedFileTypes = ["csv"]
if (dialog.runModal() == NSApplication.ModalResponse.OK){
let result = dialog.url
if (result != nil) {
return result!.path
} else {
return "nofile"
}
} else {
return "cancel"
}
}
func parsedCSVLine (thePath : String) -> Array {
do {
let content = try String(contentsOfFile: thePath)
let parsedLines : [String] = content.components(separatedBy: "\n")
return parsedLines
}
catch {
let tempArray : [String] = ["error"]
return(tempArray)
}
}
func getDates (inputArray : Array ) -> Array {
var outputArray : [String] =
for i in 1..<inputArray.count - 1 {
let lineArray = inputArray[i].components(separatedBy: ",")
outputArray.append(lineArray[0])
}
return outputArray
} // end function
func getValues(inputArray : Array) -> Array{
var outputArray : [Double] =
for i in 1..<inputArray.count - 1 {
let lineArray = inputArray[i].components(separatedBy: ",")
outputArray.append(Double(lineArray[1])!)
}
return outputArray
} // end function
//func myArrayFunc(inputArray:Array) -> Array {}
//first.append(contentsOf: second)
class ViewController: NSViewController {
@IBOutlet weak var nameField: NSTextField!
@IBOutlet weak var helloLabel: NSTextField!
@IBAction func sayButtonClicked(_ sender: Any) {
}
@IBAction func OpenPanel(_ sender: Any) {
let path = getCSVPath()
let parsedArray : [String] = parsedCSVLine(thePath: path)
if parsedArray[0] == "error" {
print ("error")
return
}
// let dateArray : [String] = getDates(inputArray: parsedArray)
// let valueArray : [Double] = getValues(inputArray: parsedArray)
print(parsedArray)
} // end of func OpenPanel
@IBAction func readCSV(_ sender: Any) {
if let fileURL = Bundle.main.url(forResource: "Data", withExtension: "csv"){
if let content = try? String(contentsOf: fileURL){
let parsedCSV : [[String]] = content
.components(separatedBy: "\n")
.map({$0.components(separatedBy: ",")})
print(parsedCSV)
}
} // end of topmost if statement
} // end of func readCSV
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}