我正在尝试通过
从.txt文件中获取一些内容let ruterQuery = loadR(filename: "content.txt")
func loadR( filename: String ) -> String {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
print(data)
return "done"
}
但是,当我打印数据时,它只显示“ 2045个字节”,如何获取文件的实际内容?
这是content.txt,用于api网址,作为要返回哪些字段的“查询”。因此,该网址为“ https://api.myapi.com/planner?query=” + content.txt
"{\n\tplaces(\n\t\tids:[\"ABC:StopPlace:8329\", \"ABC:StopPlace:0808\"]\n\t) {\n\t\tname\n\t\tid\n\t\testimatedCalls(timeRange: 72100, numberOfDepartures: 20) {\n\n\t\t\trealtime\n\t\t\trealtimeState\n\t\t\texpectedDepartureTime\n\t\t\tpredictionInaccurate\n\t\t\tdestinationDisplay {\n\t\t\t\tfrontText\n\t\t\t}\n\t\t\tquay {\n\t\t\t\tid\n\t\t\t}\n\n\t\t\tsituations {\n\t\t\t\tid\n\t\t\t\tlines {\n\t\t\t\t\tid\n\t\t\t\t}\n\t\t\t\tsummary {\n\t\t\t\t\tvalue\n\t\t\t\t\tlanguage\n\t\t\t\t}\n\t\t\t\tstopPlaces {\n\t\t\t\t\tid\n\t\t\t\t}\n\t\t\t\tdescription {\n\t\t\t\t\tvalue\n\t\t\t\t\tlanguage\n\t\t\t\t}\n\t\t\t\tvalidityPeriod {\n\t\t\t\t\tstartTime\n\t\t\t\t\tendTime\n\t\t\t\t}\n\t\t\t\tseverity\n\t\t\t\tsituationNumber\n\t\t\t}\n\n\t\t\tserviceJourney {\n\t\t\t\tid\n\t\t\t\tpublicCode\n\t\t\t\tprivateCode\n\t\t\t\tserviceAlteration\n\t\t\t\ttransportSubmode\n\t\t\t\tdirectionType\n\n\t\t\t\tnotices {\n\t\t\t\t\tid\n\t\t\t\t\ttext\n\t\t\t\t\tpublicCode\n\t\t\t\t}\n\n\t\t\t\tjourneyPattern {\n\t\t\t\t\tid\n\t\t\t\t\tline{\n\t\t\t\t\t\tid\n\t\t\t\t\t\tname\n\t\t\t\t\t\tpublicCode\n\t\t\t\t\t\ttransportMode\n\t\t\t\t\t\ttransportSubmode\n\t\t\t\t\t\tpresentation {\n\t\t\t\t\t\t\ttextColour\n\t\t\t\t\t\t\tcolour\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsituations {\n\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\tdescription {\n\t\t\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t\tlanguage\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvalidityPeriod {\n\t\t\t\t\t\t\t\tstartTime\n\t\t\t\t\t\t\t\tendTime\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsituations {\n\t\t\t\t\tid\n\t\t\t\t\tlines {\n\t\t\t\t\t\tid\n\t\t\t\t\t}\n\t\t\t\t\tsummary {\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\tlanguage\n\t\t\t\t\t}\n\t\t\t\t\tstopPlaces {\n\t\t\t\t\t\tid\n\t\t\t\t\t}\n\t\t\t\t\tdescription {\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\tlanguage\n\t\t\t\t\t}\n\t\t\t\t\tvalidityPeriod {\n\t\t\t\t\t\tstartTime\n\t\t\t\t\t\tendTime\n\t\t\t\t\t}\n\t\t\t\t\tseverity\n\t\t\t\t\tsituationNumber\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n}\n"
答案 0 :(得分:3)
文件的内容是JSON,而不仅仅是文本。
您将获得字符串表示形式
func loadR(filename: String ) -> String {
let url = Bundle.main.url(forResource: filename, withExtension: "txt")!
let data = try! Data(contentsOf: url)
let string = String(data: data, encoding: .utf8)!
print(string)
return string
}
如果代码崩溃,则说明您犯了一个设计错误。由于捆绑包中的文件在运行时不可变,因此代码不得崩溃。
另一种不好的做法是所有不必要的空格字符。与人类不同,该设备并不关心prettyPrinting