IOS URL Chinese Scrambling Problem Solution

  • 2021-06-28 14:13:10
  • OfStack

IOS Solves Chinese Scrambling Problem in URL Solution

When making an HTTPS connection, ask the client to synthesize an HTTPS address

If the address contains Chinese, the program will crash. Check to see that it was originally the reason why Chinese was not transcoded

The following two methods were found in the NSString Library

- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

Try it, it works

NSString* string1 = @" Folder ";

NSString* string2 = [string1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string3 = [string2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSString* string4 = [string2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string5 = [string3 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSString* string6 = [string4 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string7 = [string5 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Output string1-7 results are as follows

string1: Folder 


string4: Folder 

string6: Folder 
string7: Folder 

To put it simply, how do I use it:

After synthesizing URL, transcode the entire String twice

NSMutableString *address = [[NSMutableString stringWithString:SetNiChengStringWithoutUserNameAndNiCheng] mutableCopy];
  address = [[address] mutableCopy];
  address = [[address stringByAppendingString:@"/"] mutableCopy];
  address = [[address stringByAppendingString:_nameTextField.text] mutableCopy];
  address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];
  address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];

How can the server store data without transcoding it into Chinese?

When the client requests this part of the data, the client decodes it by itself.

After getting the string and decoding it once, it will be displayed as Chinese:

str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Thank you for reading, I hope to help you, thank you for your support on this site!

Related articles: