How to read/write file with iOS, in simulator as well as on device?
Asked Answered
T

4

10

As I need to read a file when my app is launched and write it sometimes while using it, I tried to reach it with :

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];
NSLog(@"%@",dataFile);

And the file, that should be in my project folder, is instead in the simulator folder :

2012-06-13 17:36:56.398 MyFileApp[610:15203] /Users/Rob/Library/Application Support/iPhone Simulator/5.1/Applications/1FFD4436-DCCA-4280-9E47-F6474BEE0183/MyFileApp.app/myFile.txt

So if I want to read/write it in using the simulator as well as the real device, what should I do ?

Thanks for your advices

Tannie answered 18/6, 2012 at 7:37 Comment(0)
O
24

To read the file from the bundle do the following

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];

To read it from your sandbox storage (documents)

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourFile.txt"];
NSString *dataFile = [NSString stringWithContentsOfFile:docPath 
                                           usedEncoding:NSUTF8StringEncoding 
                                                  error:NULL];

To write to document folder

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourFile.txt"];
[dataFile writeToFile:docPath 
          atomically:YES 
            encoding:NSUTF8StringEncoding 
               error:NULL];

Please note you will not be able to write the file in the bundle folder of your application

Overwrought answered 18/6, 2012 at 7:40 Comment(5)
If I use a file from my documents folder it will work with the simulator, but when I use my app on a device, what to do ? Use the bundle folder ?Tannie
Right, I see what you do using NSHomeDirectory. Thanks a lot !Tannie
I just need a last information. I have a folder called myFileApp, containing some folders (and another folder myFileApp), this one contains my .m/.h docs and my data file. What's the path I have to use in stringByAppendingPathComponent with this config ?Tannie
If this is inside your bundle then use the first line i added, to load it from bundle resources :)Overwrought
Well I see... so in fact, when the app launches, I have to read my bundle's file, then copy it in the sandbox, and make all the edits here ? And if I finally want to replace the bundle's file with the sandbox's one when exiting the app? I'm sorry but it's a little hard to understand..Tannie
M
2

Here is what you need to write and read a file text:

Write a file:

-(void) writeStringToFile:(NSString *)aString{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fileName = @"textFile.txt";
    NSString *fileAtPath = [filePath stringByAppendingString:fileName];
    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
        [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
    }
    [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}

and read a file:

-(NSString *)readStringFromFile{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fileName = @"textFile.txt";
    NSString *fileAtPath = [filePath stringByAppendingString:fileName];
    return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}

and finally I test my code at viewDidLoad:

    NSString *text = @"I'm an iOS developer and I'm living at HCM city";
    [self writeStringToFile:text];
    NSString *strResult = [self readStringFromFile];
    NSLog(@"%@", strResult);
Mobilize answered 29/10, 2014 at 7:28 Comment(0)
K
1

For write files the methods are -[NSData writeToURL:atomically:] and -[NSString writeToURL:atomically:encoding:error:] can be used if you link to the Foundation framework.

For reading files the methods are -[NSData initWithContentsOfURL:options:error:] and -[NSString initWithContentsOfURL:encoding:error:].

Kirkendall answered 18/6, 2012 at 7:44 Comment(0)
K
0
#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UITextView *txtWriteText;
@property (strong, nonatomic) IBOutlet UIButton *btnWriteFile;
@property (strong, nonatomic) IBOutlet UIButton *btnReadFile;
@property (strong, nonatomic) IBOutlet UILabel *lblReadText;

- (IBAction)btnWriteFileTouched:(id)sender;
- (IBAction)btnReadFileTouched:(id)sender;

@property NSFileManager *filemgr;
@property NSString *docsDir;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    _filemgr =[NSFileManager defaultManager];
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    _docsDir = dirPaths[0];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (IBAction)btnWriteFileTouched:(id)sender {
    NSString *filePath = [_docsDir stringByAppendingPathComponent: @"texfile.txt"];
    NSData *databuffer = [@"PREFIX: " dataUsingEncoding: NSASCIIStringEncoding];
    [_filemgr createFileAtPath: filePath contents: databuffer attributes:nil];

    NSFileHandle *file = [NSFileHandle fileHandleForWritingAtPath:                                filePath];
    if (file == nil){
        NSLog(@"Failed to open file");
        return;
    }

    NSMutableData *data = [NSMutableData dataWithData:[_txtWriteText.text dataUsingEncoding:NSASCIIStringEncoding]];

    [file seekToEndOfFile];
    [file writeData: data];
    [file closeFile];
}

- (IBAction)btnReadFileTouched:(id)sender {
    NSString *filePath = [_docsDir stringByAppendingPathComponent: @"texfile.txt"];
    NSData *databuffer;
    NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath: filePath];
    if (file == nil){
        NSLog(@"Failed to open file");
        return;
    }

    databuffer = [file readDataToEndOfFile];
    [file closeFile];

    NSString *datastring = [[NSString alloc] initWithData: databuffer encoding:NSASCIIStringEncoding];
    _lblReadText.text = datastring;
}

@end
Kelter answered 25/8, 2015 at 6:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.