2

I try to read string from a file with :

NSString* path = [[NSBundle mainBundle] pathForResource:@"dirty" ofType:@"txt"];
NSString* content = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&err];

And the string i get is nil. in the error i get :

Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x21063410 {NSFilePath=/var/mobile/Applications/78889F89-B83C-480C-A246-999152EE757C/Myapp.app/dirty.txt, NSStringEncoding=4}

Any idea what is the problem?

YosiFZ
  • 7,200
  • 19
  • 96
  • 198

4 Answers4

4

As mentioned, Cocoa error 261 is NSFileReadInapplicableStringEncodingError which means the encoding of file is different than what you are passing in the API.

For Hebrew language encoding, try this answer

NSString* content = [[NSString alloc] initWithContentsOfFile:path encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingWindowsHebrew) error:&err];

Hope that helps!

Community
  • 1
  • 1
Amar
  • 13,103
  • 7
  • 50
  • 69
1

The error seems to be the Encoding Issue ..

If you don't know the encoding of your file, you could try this method:

- (id)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error

Refer HERE

And Try Something like this:

NSError *error = nil;
NSStringEncoding encoding;

NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
                                                 usedEncoding:&encoding 
                                                        error:&error];
Hiren
  • 12,525
  • 7
  • 51
  • 71
Kumar KL
  • 15,086
  • 9
  • 36
  • 57
0

Try this.

NSString* content = [[NSString alloc] initWithContentsOfFile:path encoding:nil error:&err];

or change the type of "encoding" hope it will solve you problem.

Ayaz
  • 1,398
  • 15
  • 29
0

Try This

NSString *pathtest = [[NSBundle mainBundle] pathForResource:@"dirty" ofType:@"txt"];
NSString* content = [[NSString alloc] initWithContentsOfFile:pathtest encoding:NSASCIIStringEncoding error:&error];
NSLog(@"Test: %@",content);
Hemant Singh Rathore
  • 2,083
  • 1
  • 23
  • 38