문제

I have problem which drives me crazy. My API provider has url with diacritics signs e.g:

NSString *url = @"http://apiprovideraddress.com/user?param_id=sdn-ło-13/z" // ł - diacritic sign

If in url address exists any diacritic sign then "AFNetworking" return in this function NSParameterAssert which breaks code:

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                 URLString:(NSString *)URLString
                                parameters:(id)parameters
                                     error:(NSError *__autoreleasing *)error


NSParameterAssert(URLString) //URLString = nil

Stack:

[AFHTTPRequestSerializer requestWithMethod:URLString:parameters:error:]

[AFHTTPRequestOperationManager GET:parameters:success:failure:]

I'm using this function to "GET":

[myManager GET:url parameters:nil success:failure:];

If an "url" is without diacritic then everything works fine. Any ideas?

도움이 되었습니까?

해결책

From RFC 3986: When a new URI scheme defines a component that represents textual data consisting of characters from the Universal Character Set [UCS], the data should first be encoded as octets according to the UTF-8 character encoding [STD63]; then only those octets that do not correspond to characters in the unreserved set should be percent encoded. For example, the character A would be represented as "A", the character LATIN CAPITAL LETTER A WITH GRAVE would be represented as "%C3%80", and the character KATAKANA LETTER A would be represented as "%E3%82%A2".

Use stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding to encode the URL, it will do the right thing with UTF-8 non-ASCII characters.

Example:

NSString *urlString = @"http://apiprovideraddress.com/user?param_id=sdn-ło-13/z"; // ł - diacritic sign
NSLog(@"urlString: %@", urlString);
NSString *s = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"s: %@", s);

NSLog output:

urlString: http://apiprovideraddress.com/user?param_id=sdn-ło-13/z
s: http://apiprovideraddress.com/user?param_id=sdn-%C5%82o-13/z

Note: stringByAddingPercentEscapesUsingEncoding: is known to omit some escapes that are optional.

A more conservative answer to this particular URL is:
http%3A%2F%2Fapiprovideraddress.com%2Fuser%3Fparam_id%3Dsdn-%C5%82o-13%2Fz

다른 팁

URIs can only contain ACSII characters. They may not contain Unicode characters.

RFC3986

Those are the parameters of the requests, you can pass them in the parameter parameter, as a NSDictionary

something like

@{
   @"param_id" : @"sdn-ło-13/z"
 }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top