在swift,iOS游乐场中读取文件
通过搜索许多(很多!)快速的游乐场问题来搜索这个代码,我仍然在苦苦挣扎。
Having searched through the many (many!) swift playground questions to even craft this code, I'm still struggling.
I已将文本文件放在包内容的 Resources
文件夹中,它在操场生成的运行临时文件中显示为别名(链接)( / var / folders / ...
)。
I've placed a text file in the Resources
folder of package contents, and it appears as an alias (link) in the running temp files generated by the playground (/var/folders/ ...
).
import UIKit
let bundle = NSBundle.mainBundle()
let myFilePath = bundle.pathForResource("dict1", ofType: "txt")
println(myFilePath) // <-- this is correct, there is a shortcut to the Resource file at this location
var error:NSError?
var content = String(contentsOfFile:myFilePath!, encoding:NSUTF8StringEncoding, error: &error)
println(content!) // <-- this is *NOT* the file contents [EDIT: see later note]
// Demonstrate there's no error
if let theError = error {
print("\(theError.localizedDescription)")
} else {
print("No error")
}
问题在于,内容
在游乐场输出中显示为一些apple \\\
,而不是预期的文件内容。
game \\\
how \ nswift \\ \\ antoken
The problem being, that content
is shown in the playground output as being Some "apple\ngame\nhow\nswift\ntoken"
, rather than the file contents as expected.
它正在查找文件,因为如果我更改文件名,则会出错。有关获取文件内容的任何建议吗?
It's finding the file, because if I change the filename, it errors. Any advice on getting the file contents?
Xcode 6.1
Xcode 6.1
编辑:
所以,实际的问题是我没想到要转义的游乐场输出(包括 println
)。结合疲劳和其他愚蠢行为使我相信存在问题,当时不存在。
So, the actual problem was that I wasn't expecting the playground output (including, println
) to be escaped. That, combined with fatigue and other stupidities led me to believe there was a problem, when none existed.
有趣的是,并非一切似乎都在游乐场中逃脱:
Interestingly, not everything seems to be escaped in playground:
println("foo\nbar") // Outputs "foo\nbar", escaped
println("\\n") // Outputs "\n", unescaped
您可以尝试创建一个用于打开和保存文件的类:
You can try creating a class for opening and saving your files:
更新: Xcode 7.2•Swift 2.1.1
class File {
class func open(path: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
if NSFileManager().fileExistsAtPath(path) {
do {
return try String(contentsOfFile: path, encoding: encoding)
} catch let error as NSError {
print(error.code)
return nil
}
}
return nil
}
class func save(path: String, _ content: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> Bool {
do {
try content.writeToFile(path, atomically: true, encoding: encoding)
return true
} catch let error as NSError {
print(error.code)
return false
}
}
}
用法:File.save
usage: File.save
let stringToSave:String = "Your text"
let didSave = File.save("\(NSHomeDirectory())/Desktop/file.txt", stringToSave)
if didSave { println("file saved") } else { println("error saving file") }
用法:File.open
usage: File.open
if let loadedData = File.open("\(NSHomeDirectory())/Desktop/file.txt") {
println(loadedData)
} else {
println("error reading file")
}
如果您更喜欢使用网址(正如我所做并由Apple推荐):
If you prefer working with URLs (as I do and recommended by Apple):
class Url {
class func open(url: NSURL) -> String? {
do {
return try String(contentsOfURL: url, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
print(error.code)
return nil
}
}
class func save(urL: NSURL, fileContent: String) -> Bool {
do {
try fileContent.writeToURL(urL, atomically: true, encoding: NSUTF8StringEncoding)
return true
} catch let error as NSError {
print(error.code)
return false
}
}
}