views:

2656

answers:

7

Hey all,

I'm trying to post an image to TwitPic.com using their API.

However, I have never posted an image using HTTPPOST or however else before.

Anybody enlighten me to how I can post NSData from a UIImage using their api?

+5  A: 

TwitPic is expecting a multi-part form data. There is a great open source library called ASIHTTPRequest.

You can use their APIs and post your image as multi-part/form-data.

See below for the sample.

http://allseeing-i.com/ASIHTTPRequest/How-to-use

keremk
Cheers for that. However, I still get a crash.. This is what I have got:http://pastie.org/445027
Domness
In the linked code, you passed the data instead of the file path for the "media" parameter. I see there's also a setData:forKey: method, which maybe you can use without writing out to a file first.
Daniel Dickison
+2  A: 

Use the UIImagePNGRepresentation function or its JPEG equivalent to turn a UIImage into an NSData:

http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIKitFunctionReference/Reference/reference.html#//apple_ref/c/func/UIImagePNGRepresentation

Daniel Dickison
+2  A: 

I'm trying to do this too... I think I'm close but so far no cigar - I'm getting the error 'image not found' back from the call. My code looks like this:

    NSURL *url = [NSURL URLWithString:@"http://twitpic.com/api/upload"];
NSString *username = @"myUsername";
NSString *password = @"myPassword";
NSData *twitpicImage = UIImagePNGRepresentation(imageView.image);

// Now, set up the post data:
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];

[request setPostValue:twitpicImage forKey:@"media"];
[request setPostValue:username forKey:@"username"];
[request setPostValue:password forKey:@"password"];

// Initiate the WebService request
[request start];

The imageView.image is showing a picture on the iPhone screen so I know there's something there.

Anyone have any idea what I'm doing wrong?

Cheers,

Jamie.

+1  A: 

@Jamie:

Try:

[request setData:twitpicImage forKey:@"media"];

If the image view is actually displaying an image that is stored in a file on disk, use:

[request setFile:theImagePath forKey:@"media"];

This way, ASIHTTPRequest will stream the image data from disk, so you don't have to keep an NSData instance in memory.

Ta

Ben

pokeb
A: 

Thanks guys!

A: 

Instead of setPostValue for the image, use setData instead.

A: 

@Jamie

I keep getting an "error: 'ASIFormDataRequest' undeclared (first use in this function)" and and "error: 'request' undeclared (first use in this function)"

both on the line where you put the asiformdatarequest...

What else do you have in your code?

Giles Van Gruisen
Have you included the .h file in your controller?
Domness