I'm now developing an iOS app using xcode(Swift). I want to import the data which is stored in a text file, and show the words from the text file on the screen. How can I import an existing text file into the project? Should I install anything? How can I read the text file and store the words in an array?
Asked
Active
Viewed 2,106 times
1 Answers
2
You can read a file easily in iOS. Follow these steps:
Step 1: Add a File into project
Step 2: Reading a file
EDIT
Swift:
let filePath = Bundle.main.path(forResource: "File", ofType: "txt");
let URL = NSURL.fileURL(withPath: filePath!)
do {
let string = try String.init(contentsOf: URL)
// use string here
print("read: " + string)
} catch {
print(error);
}
Objective-C:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
NSURL *url = [NSURL fileURLWithPath: filePath];
NSString *string = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
Thanks!

Shamim Hossain
- 1,690
- 12
- 21
-
Do you know the OP is clearly stating the language as Swift. Your answer is so suggestive, but never can be a _good answer_ when Swift code is given. – OOPer Jul 16 '18 at 05:05
-
@OOPer, I forgot to notice. Thank you so much. I updated answer. – Shamim Hossain Jul 16 '18 at 05:21