我正在使用AWS SDK用于 iOS 将文件上传到本地硬盘到 Amazon S3 存储以及从本地硬盘下载文件。我有能力完成这项工作,但我无法让 S3 委托做出正确响应,以便在操作完成或导致错误时提醒我。
我有一系列要上传的文件。对于每个文件,我创建一个NSOperation
哪里的main
日常工作主要包括:
AmazonCredentials * credentials = [[AmazonCredentials alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY];
putObjectRequest = [[S3PutObjectRequest alloc] initWithKey:pathCopy inBucket:[self bucket]];
putObjectRequest.filename = pathSource;
putObjectRequest.credentials=credentials;
[putObjectRequest setDelegate:s3Delegate];
在此,代表 (s3Delegate
)作为常规创建AmazonServiceRequestDelegate当操作完成时,它应该能够发出响应。我的每一个NSOperations
已添加到我的NSOperationQueue
它非并发地执行操作。如果我使用委托[putObjectRequest setDelegate:s3Delegate]
操作不起作用。如果我删除委托的使用,操作将正确执行,但我无法收到对操作的任何响应,因为我没有委托。
如果我删除使用NSOperationQueue
完全并使用[putObjectRequest setDelegate:s3Delegate]
代表工作完美。
我的问题是我在队列中使用委托时做错了什么?由于委托完全能够在不在队列中时执行,这是否与不在主线程上执行有关?我真的希望能够使用队列来限制非并发操作的数量,但是我无法弄清楚这一点。我希望有人知道这里发生了什么,并且任何示例代码将不胜感激。谢谢!
干杯,特隆德
在您设置委托之后,aws sdk 似乎会异步运行。
因此,为了让您的异步 aws 内容在(异步)NSOperation 中工作,您必须使用一些魔法来等待 AWS 完成:
在 .h NSOperation 文件中,添加一个布尔值:
@interface UploadOperation : NSOperation <AmazonServiceRequestDelegate> {
@private
BOOL _doneUploadingToS3;
}
在你的 .m 文件中,你的 main 方法将如下所示:
- (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 ….
}
不要忘记实现您的委托方法
-(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:这个魔法可以适用于任何异步执行但必须在 NSOperation 中实现的东西。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)