Domanda

I'm new to iOS development, and Objective-C in general, but I have already created an android version of the app I am trying to build. The current hangup in developing the iOS version is an issue I am having trying to url encode a string. I have tried two different methods, both output the same really weird result.

@implementation NSString (PhantomEx)
-(NSString *)urlEncode
 {
    NSLog(self);

    NSString *encodedString = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
        NULL, 
        (CFStringRef)self,
        NULL,
        (CFStringRef)@"!*'();:@&=+$,/?%#[]",
        kCFStringEncodingUTF8 ));

    NSLog(encodedString);
    return encodedString;
  }

@end

When called, the first NSLog outputs a perfectly fine, un encoded string :

http://api.example.com/?userid=42&cmd={"cmd":"CheckLogin","data":{
  "username" : "joe@example.com",
  "password" : "verysecurepassword"
}}&auth=08fef10b96ac69fcc4bdcf09c3e3d851 

whilst the second NSLog outputs this :

2014-03-18 12:52:06.228 phantom[9706:60b] http0X1.1A8A9AP-10470.0000000.000000api.example.com0.0000000.000000userid2610411153                         pmd193317                     –md23AheckLogin22C             148133072ata23A7-0X1.FCF0808D30DP+0220                 10764sername2200X1.2E0C2351534P-1028222joe                           5.902543e-310xample.com22C0X1.463C008D30DP-882220             0x1a8321cassword2200X1.70101P-1020222verysecurepassword20A1390253627800088        0x1.006a0c88p-1040uth360473608fef10b96ac69fcc4bdcf09c3e3d851

This separate method produces the same result :

-(NSString *)urlEncode
{
    NSString *charactersToEscape = @"!*'();:@&=+$,/?%#[]\" ";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];

    NSString *encodedString = [self stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];

    return encodedString;
}

Also, I realise I am trying to encode the whole url, instead of just the parameters, I just haven't gotten around to changing that bit yet. I don't think it will make any difference to the current problem, however.

È stato utile?

Soluzione

The problem is with the logging itself, NSLog takes first argument as a format string and parses it as such. Change it to NSLog(@"%@", encodedString);

Altri suggerimenti

I have always used this without issues. Try a smaller character set and see you can determine if any of the individual characters are causing issues. Also change the fourth param to a CFSTR.

-(NSString *)encodeURL:(NSString *)urlString
{
    CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,   (CFStringRef)urlString, NULL, CFSTR("!*'();:@&=+@,/?#[]"), kCFStringEncodingUTF8);
    return (NSString *)CFBridgingRelease(newString);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top