Today found an egg ache problem, the server returned urlstring inside sometimes contain Chinese , use
[Nsurl Urlwithstring:urlstring] When the URL object is generated, the iOS Client does not make the network request correctly , and the UrlEncode method found on the Web does not completely solve the problem .
Method 1:
nsstring* encodedstring = [URLString stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];
Method 2:
NSString * encodedstring = (NSString *) cfurlcreatestringbyaddingpercentescapes (Kcfallocatordefault, (CFSTRINGREF) URLSTRING,NULL,NULL,KCFSTRINGENCODINGUTF8);
These two methods are correct when the URLString contains Chinese , but if they contain symbols that are escaped, they are again escaped and cause an error .
View Method 2 parameter description :
Cfstringref Cfurlcreatestringbyaddingpercentescapes (cfallocatorref allocator, Cfstringref originalString, Cfstringref characterstoleaveunescaped, Cfstringref legalurlcharacterstobeescaped, CFStringEncoding encoding);
So make a change and write the method :
NSString *encodedstring = (NSString *) cfurlcreatestringbyaddingpercentescapes (Kcfallocatordefault, ( CFSTRINGREF) urlstring, (cfstringref)@ "!$&"() *+,-./:;[ Email protected]_~%#[]", NULL, kCFStringEncodingUTF8);
If this method is used in all classes, it can be written as category and then called in the header file import "nsstring+url.h" .
@interface nsstring (URL) -(NSString *) urlencodedstring; @end
#import "nsstring+url.h" @implementationnsstring (URL)-(NSString *) urlencodedstring {nsstring*encodedstring = (NSString *) Cfurlcreatestringbyaddingpercentescapes (Kcfallocatordefault, (CFSt Ringref) Self, (cfstringref)@"!$& ' () *+,-./:; [Email protected]_~%#[]", NULL, Kcfstringencodingutf 8); returnencodedstring; } @end
Call Method:
NSString *encodedstring = [URLString urlencodedstring];
EncodedString do something
iOS Chinese URL path conversion urlencode