Search code examples
iosobjective-curl-encoding

string modifications are not working?


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?


Solution

  • 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"];