myszon
myszon

Reputation: 434

Decoding URLEncoded non standard characters

I am trying to decode some text sent from a server that is URLEncoded, and this is the best method I managed to find.

I use these standard functions for URLEncododing:

NSString* encodeToPercentEscapeString(NSString *string) {
    return (__bridge NSString *)
    CFURLCreateStringByAddingPercentEscapes(NULL,
                                        (__bridge CFStringRef) string,
                                        NULL,
                                        (CFStringRef) @"!*'();:@&=+$,/?%#[]",
                                        kCFStringEncodingUTF8);
}

NSString* decodeFromPercentEscapeString(NSString *string) {
    return (__bridge NSString *)
    CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                        (__bridge CFStringRef) string,
                                                        CFSTR(""),
                                                        kCFStringEncodingUTF8);
}

If I encode special characters:

NSString* encoded = encodeToPercentEscapeString(@"ąśżźćęółń");

I get @"%C4%85%C5%9B%C5%BC%C5%BA%C4%87%C4%99%C3%B3%C5%82%C5%84"

which is ok.

But if I try to decode it:

NSString* original = decodeFromPercentEscapeString(encoded);

I get :@"ńÖŇõŇľŇļńáńô√≥ŇāŇĄ".

Why?

Is there a better method to decode URLEncoded text?

Upvotes: 1

Views: 1247

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90531

Have you tried -[NSString stringByReplacingPercentEscapesUsingEncoding:]?

Also, you are using the bridging casts incorrectly. The created strings will leak, because ARC doesn't know it owns them. Use CFBridgingRelease(). It's nice because it is a variant of CFRelease() which is normally necessary to balance a Core Foundation "Create" function, but it cooperates with ARC.

Upvotes: 1

Related Questions