views:

1660

answers:

3

Does anyone have any suggestions for GETing from or POSTing to Amazon S3 services using their REST API via the iPhone. It does not look like it is possible but I may be reading the docs wrong.

Thank you in advance for your help!

L.

+2  A: 

You should be able to use the NSURLRequest stuff to do what you want.

NSMutableData* _data = nil;

- (IBAction) doIt:(id)sender {
    NSURL* url = [NSURL URLWithString: @"http://theurl.com/"];
    NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: url];
    NSURLConnection* con = [NSURLConnection connectionWithRequest: req delegate: self];
    NSData* body = [@"body of request" dataUsingEncoding: NSUTF8StringEncoding];

    data = [NSMutableData new];
    [req setHTTPMethod: @"POST"];
    [req setHTTPBody: body]
    [con start];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_data appendData: data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString* result = [[[NSString alloc] initWithData: _data encoding: NSUTF8StringEncoding] autorelease];

    // process your result here
    NSLog(@"got result: %@", result);
}

This doesn't have any error checking in it and the _data variable should be stored in an instance variable, but the general idea should work for you. You will probably also need to set some request headers to tell the server what encoding the body data is in and so on.

Daniel
A: 

I'd recommend to use ASIHttpRequest, it has a lot of built-in functionality (REST compatible too) and a lot of things, making life easier than with NSURLConnection.

Valerii Hiora
I think you're a little confused. NSConnection is for Distributed Objects. Very different to NSURLConnection!
Mike Abdullah
Yes, you're right, I meant NSURLConnection. Will update answer.
Valerii Hiora
A: 

Great, thank you a lot for this code!

btw: In line 9 it should be _data instead of data, and in line 11 there's a ";" missing

milan