-1

This is my code and in my url string white spaces are not encoded by the code

NSString *str  = item.fileArtPath;
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
[str stringByAddingPercentEncodingWithAllowedCharacters:set];
[str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSURL *urlString = [NSURL URLWithString:str];

for below string:

http://xx.xx.xx.xxx:xx/xx/xx/xx/xxx/Audio Adrenaline.jpg
                                    ^^^^^^^^^^^^^^^^^^^^

The white space after Audio is not converted to %20 after I used string replacement. And in Debugging urlString is nil why so?

SUDHAKAR RAYAPUDI
  • 549
  • 1
  • 9
  • 18

3 Answers3

1

From the NSString Class Reference

Returns a new string made from the receiver by replacing all characters not in the specified set with percent encoded characters.

Meaning it doesn't permute the instance it's called on. You need to say something like str = [str stringByAddingPercentEncodingWithAllowedCharacters:set]; Same with [str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

beyowulf
  • 15,101
  • 2
  • 34
  • 40
1

Recall that NSString is immutable. Calling methods stringBy... returns the modified string, rather than modifying the original one. Therefore your code should be rewritten as follows:

str = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1
 NSString *search = [searchBar.text stringByReplacingOccurrencesOfString:@" " withString:@"%20"];