Search code examples
iosobjective-camazon-web-servicesamazon-s3

How can I add a listener for when my S3PutObjectRequest has completed?


I'm uploading to Amazon S3 using the iOS SDK which is working great but I want to be able to trigger a method when the load is completed.

Here is my code:

AmazonS3Client *s3 = [[[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY] autorelease];
// Create the picture bucket.
[s3 createBucket:[[[S3CreateBucketRequest alloc] initWithName:[Constants pictureBucket]] autorelease]];
NSString *picName = [NSString stringWithFormat:@"%@%d", PICTURE_NAME, counter];
// Upload image data.  Remember to set the content type.
S3PutObjectRequest *por = [[[S3PutObjectRequest alloc] initWithKey:picName inBucket:[Constants pictureBucket]] autorelease];
NSLog(@"------------ SUBMITTING img :%@", picName);
por.contentType = @"image/jpeg";
por.data        = imageData;
counter++;                   
// Put the image data into the specified s3 bucket and object.
[s3 putObject:por];

Any help much appreciated thanks!


Solution

  • From the Amazon SDK Docs it seems that you get an S3PutObjectResponse

    so

    S3PutObjectResponse *response  = [s3 putObject:por];
    if ([response isFinishedLoading]) {
        //do something
    }
    

    or maybe you are searching for connectionDidFinishLoading: which is a delegate method from NSURLConnection which it seem they use accordingly to AmazonServiceResponse Class Reference

    in you .h file declare that you conform to the delegate protocol of NSURLConnection

    @interface MyClass : NSObject <NSURLConnectionDelegate>
    

    in your .m file implement the delegate methods you want

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
          //do your stuff here
    }
    

    and tell the NSURLConnection that you handle the delegate methods in your .m file

    S3PutObjectRequest *por = [[[S3PutObjectRequest alloc] initWithKey:picName inBucket:[Constants pictureBucket]] autorelease];
    por.urlRequest.delegate = self; // this is important !!!
    

    In general you should get used to work with delegates since they are often used throug the hole iOS SDK !!

    You can find additional docu here: Delegates and Data Sources