Search code examples
nsstringnsurlnsstringencoding

stringByAddingPercentEscapesUsingEncoding adds unexpected characters?


I'm having a hard time getting my NSURL to work, when I create the final string before converting to URL it adds unwanted character to the end of the string, why is this happening and how can I fix it?

Here is my code:

NSString *remotepathstring = [[NSString alloc] init];
remotepathstring=newdata.remotepath;
NSLog(@"remotepathstring = %@",remotepathstring);

NSString *remotepathstringwithescapes = [remotepathstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"remotepathstring = %@",remotepathstringwithescapes);

remotepathURL =[NSURL URLWithString:remotepathstringwithescapes];
NSLog(@"RemotePathUrl=%@",remotepathURL);

Log outputs as follows:

"remotepathstring = http://nalahandthepinktiger.com/wp-content/uploads/nalah-sheet-5.pdf‎"

"remotepathstring = http://nalahandthepinktiger.com/wp-content/uploads/nalah-sheet-5.pdf%E2%80%8E"

"RemotePathUrl=http://nalahandthepinktiger.com/wp-content/uploads/nalah-sheet-5.pdf%E2%80%8E"

Solution

  • The sequence %E2%80%8E is a Unicode LEFT-TO-RIGHT MARK. This is present in your original remotepathstring, but invisible when printed out via NSLog.

    The question becomes: how does newdata.remotepath get populated in the first place? Somewhere along the line it sounds like you need to perform some extra cleanup of input strings to strip out such a character.

    Unrelated to the core question, it would seem you're a newcomer to Objective-C. This code is redundant and wasteful:

    NSString *remotepathstring = [[NSString alloc] init];
    remotepathstring=newdata.remotepath;
    

    You create a string, only to immediately throw it away and replace it with another. If you're not using ARC, this has the additional problem of leaking! Instead do:

    NSString *remotepathstring = newdata.remotepath;