Reputation: 4750
i am new to xcode and objective c.
firstly i have created a file in documents directory and it is created and now what i need is how can i read the data from that file like whether the file is containing a particular string or not
How can i get that
Upvotes: 7
Views: 2117
Reputation: 132
You can read data from file in documents folder in following way:
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/<pathofFile>"];
NSString *fileContent = [[NSString alloc] initWithContentOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
Now, you can use NSString methods for searching substring in the fileContent.
Upvotes: 0
Reputation: 13364
the same way as you write you can retrieve the data , lets assume you want to get an image from your documents folder then see this code -
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]];
NSString *fileName = [stringPath stringByAppendingFormat:@"/image.jpg"];
//fileName is your image path and image.jpg is your image name which is saved in documents folder...
NSData *retrieveData = [NSData dataWithContentsOfFile:fileName];
UIImage *newImage = [UIImage imageWithData: retrieveData];
in this case instead of
[data writeToFile:fileName atomically:YES];
you have to write
NSData *retrieveData = [NSData dataWithContentsOfFile:fileName];
line. And you can get all kind of data.
Thank You!!
Upvotes: 0
Reputation: 5314
Following method will get the contents of the file to a string.
+ (id)stringWithContentsOfFile:(NSString *)path
usedEncoding:(NSStringEncoding *)enc
error:(NSError **)error
You can then find out if the returned string contains specified substring by:
NSRange textRange;
textRange =[string rangeOfString:@"ohai"];
if(textRange.location != NSNotFound) {
//String contains substring "ohai"
}
Hope this helps.
Upvotes: 0