1. Scenario description:
The background gives a txt file, the encoding is utf-8. When reading the content of the txt file in the Xcode development environment of Mac computers, the Chinese characters will appear garbled, and there will be no garbled in English.
2. Try solutions:
Modify the encoding format and try NSUTF16StringEncoding, NSUTF8StringEncoding, NSASCIISTRingEncoding, etc. The problems that occur are sometimes garbled in Chinese, and sometimes utf-8 cannot open the file, and the problem is ultimately not solved.
3. Guess the reason:
The txt file is created from a window computer, which may be related to the environment. Second, the encoding problem.
4. Solution:
Step 1: Create a new txt file on your Mac and copy and paste the content of the txt file copied from window.
Step 2: Encoding format, use NSUTF16StringEncoding
5. Code:
NSError *error; NSString *path = [[NSBundle mainBundle]pathForResource:@"body" ofType:@"txt"]; NSString *content = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:&error]; if (error) { NSLog(@"====%@",); } else { }
The above is the solution to the garbled Chinese code in iOS when reading txt files. I hope it will be helpful to everyone's learning, and I hope everyone will support me more.