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

后端 未结 4 402
独厮守ぢ
独厮守ぢ 2020-12-16 02:45

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         


        
4条回答
  •  不知归路
    2020-12-16 02:51

    #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
    

提交回复
热议问题