.fileImporter(isPresented: $imported, allowedContentTypes: [.delimitedText], allowsMultipleSelection: false){ result in do { guardlet fileUrl: URL=try result.get().first else {return} if (CFURLStartAccessingSecurityScopedResource(fileUrl asCFURL)) { //不在这个if里就出错,唉 //理由:iOS的沙盒机制保护需要我们申请临时调用url的权限 guardlet data =String(data: tryData(contentsOf: fileUrl), encoding: .utf8) else { return } handleSSJdataCSV(data: data) //done accessing the url CFURLStopAccessingSecurityScopedResource(fileUrl asCFURL) } else { print("Permission error!") } } catch { // Handle failure. print ("error reading: \(error.localizedDescription)") } } //数据格式处理代码 funchandleSSJdataCSV(data : String){ var csvToStruct = [SSJdata]() //split the long string into an array of "rows " of sata. each row is a string //detect "/n" carriage return , then split var rows = data.components(separatedBy: "\n") let columnCount = rows.first?.components(separatedBy: ",").count //remove the header rows rows.removeFirst() //loop around each row and split into columns for row in rows{ let csvColumes = row.components(separatedBy: ",") if csvColumes.count == columnCount{ let genericStruct =SSJdata.init( raw: csvColumes) csvToStruct.append(genericStruct!) }
} print(csvToStruct) for singleRecord in csvToStruct{ print(singleRecord.recordType) } //done accessing the url }