问题
i want to put a .txt file in my Xcode Swift Iphone project. First, i simply drag&dropped it from my desktop to the Supporting Files Folder from the project. Isn't there a Folder like on Android "assets", so i can place my files anywhere i want?
The file in my example is called README.txt which has a bunch of lines and paragraphs.
Simple enough, now I want to print the content of the README.txt file to a view.
How do i do the read function and what path should I insert, if my file is in the project /SupportFiles/README.txt?
Thanks alot!
回答1:
let path = NSBundle.mainBundle().pathForResource("README", ofType: "txt")
textView.text = String(contentsOfFile: path,
encoding: NSUTF8StringEncoding,
error: nil)
Just drop the file anywhere into the project browser and make sure it is added to the right target.
Just to expand on the answer, you can also place them in a folder and use: + pathForResource:ofType:inDirectory:.
回答2:
I would recommend to use NSFileManager and drop your file anywhere in your project :
if let path = NSBundle.mainBundle().pathForResource(name, ofType: "txt"){
let fm = NSFileManager()
let exists = fm.fileExistsAtPath(path)
if(exists){
let c = fm.contentsAtPath(path)
let cString = NSString(data: c!, encoding: NSUTF8StringEncoding)
ret = cString as! String
}
}
回答3:
In Swift 3
guard let path = Bundle.main.path(forResource: "README", ofType: "txt") else {
return
}
textView.text = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
回答4:
Swift 4 (thanks to @Pierre-Yves Guillemet for original)
As long as the file is in your project (and has a .txt) this will work (in this example, I assume "MyFile.txt" is a file that is in my project):
static func LoadFileAsString() -> ()
{
if let path = Bundle.main.path(forResource: "MyFile", ofType: "txt")
{
let fm = FileManager()
let exists = fm.fileExists(atPath: path)
if(exists){
let content = fm.contents(atPath: path)
let contentAsString = String(data: content!, encoding: String.Encoding.utf8)
}
}
}
回答5:
If you define path's
type and put !
end of the line, you won't get any warning.
let path:String = NSBundle.mainBundle().pathForResource("README", ofType: "txt")!
textView.text = String(contentsOfFile: path,
encoding: NSUTF8StringEncoding,
error: nil)
回答6:
There's a Assets.xcassets
for images and files.
And here's how to read it from assets.
if let data = NSDataAsset(name: "AssetName")?.data {
textView.text = String(data: data, encoding: .utf8)
}
来源:https://stackoverflow.com/questions/27206176/where-to-place-a-txt-file-and-read-from-it-in-a-ios-project