naokazuterada
11/23/2011 - 3:13 PM

Upload image to Twitter with OAuth

Upload image to Twitter with OAuth

#define DATA(str) [(NSString*)(str) dataUsingEncoding:NSUTF8StringEncoding]

- (NSData *)generateFormData:(NSDictionary *)dictionary boundary:(NSString *)boundary {
    NSMutableData *data = [[NSMutableData alloc] init];
    id key;
    NSEnumerator *enumerator = [dictionary keyEnumerator];
    
    while (key = [enumerator nextObject]) {
        id value = [dictionary valueForKey:key];
        [data appendData:DATA(([NSString stringWithFormat:@"--%@\r\n", boundary]))];
        if ([value isKindOfClass:[NSString class]]) {
            [data appendData:DATA(([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key]))];
            [data appendData:DATA(([NSString stringWithFormat:@"%@", value]))];
        } else if ([value class] == [UIImage class]) {
            [data appendData:DATA(([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%qi.jpg\"\r\n", key, key, time(NULL)]))];
            [data appendData:DATA(([NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"]))];
            [data appendData:UIImageJPEGRepresentation(value, 1.0)];
        }
        [data appendData:DATA(([NSString stringWithString:@"\r\n"]))];
    }
    [data appendData:DATA(([NSString stringWithFormat:@"--%@--\r\n", boundary]))];
    return [data autorelease];
}

- (void)uploadImage:(UIImage *)image comment:(NSString *)comment {
    NSString *consumerKey = @"...";
    NSString *consumerSecret = @"...";
    OAConsumer *consumer = [[OAConsumer alloc] initWithKey:consumerKey secret:consumerSecret];
    
    OAToken *authToken = [[[OAToken alloc] initWithKey:accessTokenKey secret:secretTokenKey] autorelease];
    OAMutableURLRequest *request = [[[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://upload.twitter.com/1/statuses/update_with_media.json"]
                                                                    consumer:consumer token:authToken realm:nil signatureProvider:nil] autorelease];
    
    [request setHTTPMethod:@"POST"];
    [request prepare];
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            comment, @"status", 
                            image, @"media[]",
                            nil];
    
    NSData *formData = [self generateFormData:params boundary:@"___boundary___"];
    [request addValue: @"multipart/form-data; boundary=___boundary___" forHTTPHeaderField: @"Content-Type"];
    [request setHTTPBody:formData];
    
    NSHTTPURLResponse *response;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    NSLog(@"%@", [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
    
    NSInteger statusCode = [response statusCode];
    NSLog(@"%d", statusCode); // => 200 is OK.
}