Search code examples
objective-ctwittertwitter-oauth

twitter error 401 - What should I do with the exclamation mark?


I have a problem with Oauth and twitter api ver1.1. My app will tweet a post to twitter when post something to another site. But when the post body contains exclamation mark ('!'), I get twitter 401 error that is 'Unauthorized'. I searched on google, and found that it may related to Oauth. Some people says that the '!' must be encoded to '%21'. I tried it, but when I tweet '!' to twitter, I just got '%21' but not '!' itself. How can I encode the '!' correctly?


Solution

  • you must encode your tweet with this category

    #import "NSString+URLEncoding.h"
    @implementation NSString (OAURLEncodingAdditions)
    
    - (NSString *)URLEncodedString 
    {
        NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                           (CFStringRef)self,
                                                                           NULL,
                                                                           CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                           kCFStringEncodingUTF8);
        [result autorelease];
        return result;
    }
    
    - (NSString*)URLDecodedString
    {
        NSString *result = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
                                                                                           (CFStringRef)self,
                                                                                           CFSTR(""),
                                                                                           kCFStringEncodingUTF8);
        [result autorelease];
        return result;  
    }
    
    @end