I have some images on my server, named with special characters (å,ä,ö). I can't figure out how to convert the NSUrl to get them:
NSString *urlString = [NSString stringWithFormat: @".../Images/%@Image.png", playerName];
NSURL *url = [NSURL URLWithString: [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"url:%@", url);
//Get the image and assign it to the player
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
The log in the above example (if "playerName" = åäö):
.../Images/%C3%A5%C3%A4%C3%B6Image.png
but I need it to be:
.../Images/åäöImage.png
I tried different (stringByAddingPercentEscapesUsingEncoding) and the code below without success:
- (NSString *)URLEncodingOfString:(NSString *)s
{
return (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes
(kCFAllocatorDefault, (__bridge CFStringRef)s, NULL, NULL,
kCFStringEncodingISOLatin1);
}
Any advice is very appreciated, Thanks in advance
I think it'll depend entirely on what encoding the web server is using.
Since ISO-Latin-1 doesn't seem, from your test, to work, you might try replacing kCFStringEncodingISOLatin1
with kCFStringEncodingUTF8
.
Try this :
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingISOLatin1 );
Unfortunately, the stringByAddingPercentEscapesUsingEncoding
method doesn't encode all special characters properly.
Source: How to really URL encode an NSString in Objective-C, iPhone, etc.
EDIT:
Have you tried
NSString *urlString = [NSString stringWithFormat: @".../Images/%@Image.png", playerName];
NSURL *url = [NSURL URLWithString: [urlString stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding]];
Note the NSISOLatin1StringEncoding
instead of NSUTF8StringEncoding
Try This
To create NSURL
NSURL *url = [[NSURL alloc]initWithString:stringURL];
The stringURL is the string representing URL. While logging, try this
NSLog("%@",[url absoluteString]);
I ran into this issue due to "%C3%89%C3%89" which converts to ÉÉ within a url I was attempting to load. This seemed to convert the url into the desired format to allow me to download the file from the URL.
NSURL *url = [NSURL URLWithString:[[imageURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];