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!
Tap the file attachment button in the email message to open and read the plain text file. Alternatively, touch and hold the attachment to choose an installed app that can handle the file. Tap "Quick Look" to read the contents of the text file on the iPhone's screen.
To add a text file to the project, right-click on the project folder in the project view in the left pane and select the option New Item... In the dialog that appears, select the Other category and the Empty file option. Name the file numbers. txt.
This file is located in data/data/your.package.name/files/ folder. You can see this file with DDMS File Explorer on emulator or rooted device.
if let path = Bundle.main.path(forResource: "README", ofType: "txt") { do { textView.text = try String(contentsOfFile: path, encoding: .utf8) } catch let error { // Handle error here } }
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:.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With