Using delegates, operations, and queues

前端 未结 1 1259
长发绾君心
长发绾君心 2021-01-16 08:40

I am using the AWS SDK for iOS to upload and download files to and from local hard drive to Amazon S3 storage. I am capable of making this work but I am unable to get the S3

1条回答
  •  迷失自我
    2021-01-16 09:38

    It seems that the aws sdk behaves asynchronously after the time you set your delegate. So in order to have your asynchronous aws stuff work in a (asynchronous) NSOperation, you got to put some magic to wait for AWS to complete:

    In your .h NSOperation file, add a boolean:

    @interface UploadOperation : NSOperation  {
        @private
        BOOL        _doneUploadingToS3;
    }
    

    and in your .m file, your main method will look like this:

    - (void) main
    {   
        ....  do your stuff …..
    
        _doneUploadingToS3 = NO;
    
        S3PutObjectRequest *por = nil;
        AmazonS3Client *s3Client = [[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY withSecretKey:SECRET_KEY];
        s3Client.endpoint = endpoint;
    
        @try {
            por = [[[S3PutObjectRequest alloc] initWithKey:KEY inBucket:BUCKET] autorelease];
            por.delegate = self;
            por.contentType = @"image/jpeg";
            por.data = _imageData;
    
            [s3Client putObject:por];
        }
        @catch (AmazonClientException *exception) {
            _doneUploadingToS3 = YES;
        }
    
        do {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        } while (!_doneUploadingToS3);
    
        por.delegate = nil;
    
        ....  continue with your stuff ….
    }
    

    do not forget to implement your delegate methods

    -(void)request:(AmazonServiceRequest *)request didCompleteWithResponse:(AmazonServiceResponse *)response
    {
        _doneUploadingToS3 = YES;
    }
    
    -(void)request:(AmazonServiceRequest *)request didFailWithError:(NSError *)error 
    {
        _doneUploadingToS3 = YES;
    }
    
    -(void)request:(AmazonServiceRequest *)request didFailWithServiceException:(NSException *)exception 
    {
        _doneUploadingToS3 = YES;
    }
    
    - (void) request:(AmazonServiceRequest *)request didSendData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
    {
        // Do what you want
    }
    
    -(void)request:(AmazonServiceRequest *)request didReceiveResponse:(NSURLResponse *)response
    {
        // Do what you want
    }
    
    -(void)request:(AmazonServiceRequest *)request didReceiveData:(NSData *)data
    {
        // Do what you want
    }
    

    Note: this magic can work for any stuff that performs asynchronously but have to be implemented in a NSOperation.

    0 讨论(0)
提交回复
热议问题