NSURL URLWithString: gives zero

See 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 gives me http://MyDomain/Pics\\1.png , but url gives me nil .

+4
source share
3 answers

Just try using this,

 [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
+18
source

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

This method expects the URLString to contain all the necessary percentage escape codes, which are: ",", "%", "#" and "@". Note that '% escapes are broadcast via UTF-8.

I suggest you try again using the NSString (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding; .

+2
source

Starting with iOS9, stringByAddingPercentEscapesUsingEncoding deprecated. To safely avoid a URL string, use:

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

This creates a lot of characters that need to be stored as is, and requests that everything outside of these character sets be converted to percentages encoded in percent.

+2
source

Source: https://habr.com/ru/post/1397793/


All Articles