Breaking News
Home / iOS / iOS Snippets / How to read and write file from NSString and viceversa in iOS?

How to read and write file from NSString and viceversa in iOS?

Snippet

  1. // Write to Text File as String
  2. +(void) writeFile :(NSString*) data asFileName:(NSString*) filename inDirectory:(NSString*) directory onError:(NSError*) error{
  3.    
  4.     // create the full file name path
  5.     NSString *fileNameWithPath = [NSString stringWithFormat:@"%@/%@",  directory,filename];
  6.    
  7.     debugLog(@"Write to file %@",fileNameWithPath);
  8.  
  9.     // write the content
  10.     [data writeToFile:fileNameWithPath              atomically:NO                 encoding:NSUTF8StringEncoding                   error:&error];
  11.    
  12. }
  13.  
  14.  
  15.  
  16. // Read contents of a file
  17. +(NSString *) readFile :(NSString*) filename inDirectory:(NSString*) directory onError:(NSError*) error{
  18.     //get the documents directory:
  19.    
  20.     // create the full file name path
  21.     NSString *fileNameWithPath = [NSString stringWithFormat:@"%@/%@",  directory,filename];
  22.  
  23.     debugLog(@"Reading  file %@",fileNameWithPath);
  24.    
  25.     return  [[NSString alloc] initWithContentsOfFile:fileNameWithPath    usedEncoding:NSUTF8StringEncoding       error:&error];
  26.    
  27. }

<!>

[pb_builder]

Check Also

EKCalendar – That account does not allow calendars to be added or removed

Usecase When I am trying to create a new Calendar programmatically using the EventKit API …

Advertisment ad adsense adlogger