Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place a .txt file and read from it in a IOS project

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!

like image 376
Felix Me Avatar asked Nov 29 '14 19:11

Felix Me


People also ask

How do I open a .txt file in iOS?

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.

How do I add a text file to Xcode project?

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.

Where are txt files stored?

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.


2 Answers

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:.

like image 153
Mundi Avatar answered Sep 20 '22 19:09

Mundi


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     } } 
like image 42
GPY Avatar answered Sep 20 '22 19:09

GPY