Nitish
Nitish

Reputation: 14113

NSURL URLWithString: giving nil

Please see the below code :

UIImage *image;
NSString *str = [[[Data getInstance]arrPic]objectAtIndex:rowIndex];
NSLog(str);
NSURL *url = [NSURL URLWithString:str];
NSData *data = [NSData dataWithContentsOfURL:url];
image = [UIImage imageWithData:data];  

str is giving me http://MyDomain/Pics\\1.png but url is giving me nil.

Upvotes: 4

Views: 7572

Answers (3)

Ali Saeed
Ali Saeed

Reputation: 1569

As of iOS9, stringByAddingPercentEscapesUsingEncoding is deprecated. To safely escape a URL string, use:

NSMutableCharacterSet *alphaNumSymbols = [NSMutableCharacterSet characterSetWithCharactersInString:@"~!@#$&*()-_+=[]:;',/?."];
[alphaNumSymbols formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];

str = [str stringByAddingPercentEncodingWithAllowedCharacters:alphaNumSymbols];

This creates sets of characters to keep as is and asks everything outside of these CharacterSets to be converted to %percent encoded values.

Upvotes: 2

user971401
user971401

Reputation:

From the documentation, the URLWithString: methods takes a well-formed URL string :

This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.

I suggest you retry the same using NSString's (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding; method before.

Upvotes: 2

Mehul Mistri
Mehul Mistri

Reputation: 15147

Just try using this,

[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Upvotes: 18

Related Questions