Reputation:
I have added a text file to Xcode, now I want to make a string with it. How do I load it and put it into a string?
NewsStory1.txt
is the file, and I'm using Obj-C.
Upvotes: 37
Views: 28261
Reputation: 40621
NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
See Apple's iOS API documentation for NSString, specifically the section "Creating and Initializing a String from a File"
Upvotes: 76
Reputation: 793
Another simpler way with Objective-C:
NSError *error = nil;
NSString *string = [[NSString alloc] initWithContentsOfFile: @"<paht/to/file>"
enconding:NSUTF8StringEncoding
error: &error];
Upvotes: -1
Reputation: 2231
In Swift 4 this can be done like this:
let path = Bundle.main.path(forResource: "test_data", ofType: "txt")
if let path = path {
do {
let content = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
print(content)
} catch let error as NSError {
print("Error occured: \(error.localizedDescription)")
}
} else {
print("Path not available")
}
Upvotes: 1
Reputation: 5208
In swift
let path = NSBundle.mainBundle().pathForResource("home", ofType: "html")
do {
let content = try String(contentsOfFile:path!, encoding: NSUTF8StringEncoding)} catch _ as NSError {}
Upvotes: 5
Reputation: 11217
Very Simple
Just create a method as follows
- (void)customStringFromFile
{
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *stringContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"\n Result = %@",stringContent);
}
Upvotes: 3