westbaer / FMEngine

Objective-C Framework for the last.fm API
MIT License
68 stars 15 forks source link

Ampersands and generatePOSTBodyFromDictionary #2

Open prendio2 opened 14 years ago

prendio2 commented 14 years ago

I encountered an error when fetching data for artists with ampersands in their name, like "Simon & Garfunkel"

The ampersand needs to be url endcoded or the artist named will be concatenated, in this case returning details for "Simon".

I added the following function, originally found at http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html

- (NSString *)urlEncodeValue:(NSString *)str
{
    NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8);
    return [result autorelease];
}

and adjusted generatePOSTBodyFromDictionary as follows

[rawBody appendString:[NSString stringWithFormat:@"&%@=%@", key, [self urlEncodeValue:[dict objectForKey:key]]]];
hjaltij commented 13 years ago

This also affects posting songs with ampersand, e.g. Belle & Sebastian to last.fm using either track.scrobble or track.updateNowPlaying.

You can run into problems if you apply the patch above because some values in the dictionary might not be NSStrings so you'll have to check for that, otherwise the patch above works.

You might also want to consider encoding more characters to comply with RFC 3986 (http://www.ietf.org/rfc/rfc3986.txt) Something like this would do that: NSString result = (NSString) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8);