Question

I have an editable uitextview in which the user types in Russian or English. I then save this text as a .txt file in the files directory, and read it later.

Here is the portion to save the text

-(IBAction)saveText:(id)sender{


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"testing.txt"];
    [self.textBox.text writeToFile:path atomically:YES];
    NSLog(path);

}

There is a separate button to display this text in a popover:

-(IBAction)readText:(id)sender{

    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"testing.txt"];
    NSError *error = nil;
 myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
    NSLog(@"myText: %@", myText);
    self.textBox.text= myText;
    }

with this declaration in the .h file

NSString *myText;

it works fine if I only type English, but if I type Russian characters then nothing saves/displays.

So, say I type "hello" it works, but ifI then type " some Russian phrase " to append self.textBox.text it doesn't work.

How can I make this Russian (or UTF8/charcode) compatible?

Was it helpful?

Solution

writeToFile:atomically: is deprecated and writes the string in the default encoding (whatever that is, probably MacRoman). Better use

[self.textBox.text writeToFile:path
                    atomically:NO
                      encoding:NSUTF8StringEncoding
                         error:&error];

to write the string UTF-8 encoded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top