美股記帳 App / Part 5. 導入 .csv 檔
Published in
6 min readApr 2, 2022
懶得手動輸入交易嗎?害怕不小心把交易輸入錯誤嗎?
現在只要從券商那裡下載交易明細,按照指示簡單修改一下,就可以直接導入.csv 檔,將交易加進 App 喔
安裝 CHCSVParser
- 首先,先下載下面 github 裡的檔案,並把 .h 和 .m 的檔案拉進 xcode 的 project 裡
- 因為檔案是 objective-c 語言,所以加進去的時候會問你要不要加個 bridge,選擇要,並加入下面程式
#import "CHCSVParser.h"
從手機裡選擇檔案
- 使用 UIDocumentPickerViewController 來選曲檔案
@IBAction func importFile(_ sender: Any) {
let supportedFile : [UTType] = [UTType.data]
let DocumentPickerController = UIDocumentPickerViewController(forOpeningContentTypes: supportedFile, asCopy: true)
DocumentPickerController.delegate = self
DocumentPickerController.allowsMultipleSelection = false
present(DocumentPickerController, animated: true, completion: nil)
}
讀取 .csv 檔
- 先建一個 讀取 csv 的 struct,並依 header 設定 init
struct importFile : Codable{
var dateString : String
var description : String
init(raw:[String]) {
dateString = raw[0]
description = raw[1]
}
}
- 讀取 csv 檔裡的資料並檔入前面建的 struct
- 在讀檔錯誤的時候,跳出警告並告知 csv 檔裡的哪一行出現錯誤,方便使用者修改
- 在讀檔正確的時候,也跳出提示使用者
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
print("file was selected")
var correctFormat = true let rows = NSArray(contentsOfCSVURL: url, options:CHCSVParserOptions.sanitizesFields)!
for (index, rowContent) in rows.enumerated(){
if index != 0, let rowString = rowContent as? [String]{
let importFileStruct = stockTracker.importFile.init(raw:rowString)
}else{
correctFormat = false
let alertController = UIAlertController(title: "Warning!!!", message: "The format of imported .csv file may be wrong.(error in line : \(index) of the imported file). Please follow the instruction below", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
break
}
}
}
if correctFormat{
let alertController = UIAlertController(title: "Message", message: "Import the File Successfully!!! Please check them in Transaction Report.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
present(alertController, animated: true, completion: nil)
}else {
print("the format of imported file is incorrect")
}
}
}
詳情可以參考下面的 youtube 教學,教的很詳細喔!!