如何读取csv文件swiftUI

yiytaume  于 2022-12-06  发布在  Swift
关注(0)|答案(1)|浏览(302)

我目前正在尝试读入CSV文件,但遇到了一些问题:(
下面是我的CSV阅读器函数

import SwiftUI

extension String{
    //Get the filename from a String
    func fileName ( ) -> String{
        return URL (fileURLWithPath: self).deletingPathExtension().lastPathComponent
    }
    //Get the file extension from a String
    func fileExtension() -> String{
        return URL (fileURLWithPath: self).pathExtension
    }
    
}

func readCSV (inputFile: String, separator: String) -> [String]{
    //Split the file name
    let fileExtension = inputFile.fileExtension()
    let fileName = inputFile.fileName()
    //Get the file URL
    let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let inputFileURL = fileURL[0].appendingPathComponent(fileName).appendingPathExtension(fileExtension)
    //Get Data
    do{
        let savedData = try String(contentsOf: inputFileURL)
        return savedData.components(separatedBy: separator)
    } catch{
        return ["Error file cant be found"]
    }
}

然后在视图中,我尝试将其显示为

struct Test: View{
    
    var data = readCSV(inputFile: "capitals.csv", separator: ",")
    
    var body: some View{
        VStack{
            Text(data[0])
            
        }
}

当我运行应用程序时,我得到的都是“找不到错误文件”
My CSV file
如何在视图中显示数据请
多谢

bxgwgixi

bxgwgixi1#

capitals.csv文件从Finder拖放到您的Xcode项目中,您可以在左侧面板中看到项目的文件夹/文件。然后使用下面的示例代码读取csv数据,并将其显示在List中(国家/地区,首都),对我来说效果很好:

struct ContentView: View {
    // [Country:Capital]
    @State var capitals: [String:String] = [:]
    
    var body: some View {
        VStack {
            List(Array(capitals.keys), id: \.self) { country in
                VStack {
                    Text(country)
                    Text(capitals[country] ?? "no data")
                }
            }
        }
        .onAppear {
            capitals = readCSV(inputFile: "capitals.csv")
        }
    }
    
    func readCSV(inputFile: String) -> [String:String] {
        if let filepath = Bundle.main.path(forResource: inputFile, ofType: nil) {
            do {
                let fileContent = try String(contentsOfFile: filepath)
                let lines = fileContent.components(separatedBy: "\n")
                var results: [String:String] = [:]
                lines.dropFirst().forEach { line in
                    let data = line.components(separatedBy: ",")
                    if data.count == 2 {
                        results[data[0]] = data[1]
                    }
                }
                return results
            } catch {
                print("error: \(error)") // to do deal with errors
            }
        } else {
            print("\(inputFile) could not be found")
        }
        return [:]
    }
  
}

相关问题