因为公司业务的原因,新的APP使用白山云存储上传图片视频资源,而白山云移动端存储功能的实现依赖亚马逊的SDK,下面就简单介绍一下使用亚马逊SDK上传图片
AmazonSDK地址
首先导入AmazonSDK
然后在application:didFinishLaunchingWithOptions方法里设置好SDK的配置
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
[self configAWS];
...
return YES;
}
配置上传需要的参数:
- (void)configAWS {
AWSEndpoint *EndPoint = [[AWSEndpoint alloc] initWithURLString:END_POINT];
AWSBasicSessionCredentialsProvider *provider =
[[AWSBasicSessionCredentialsProvider alloc] initWithAccessKey:ACCESS_KEY
secretKey:SECRET_KEY
sessionToken:@"latest"];
//如果有identityPoolId,可以使用identityPoolId设置
//AWSCognitoCredentialsProvider *provider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1 identityPoolId:POOL_ID];
AWSServiceConfiguration *configuration =
[[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1
endpoint:EndPoint
credentialsProvider:provider];
AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
}
上传实现:
+ (void)updateImageWithImage:(UIImage *)image completion:(void (^)(NSString *))completion {
CGFloat width = image.size.width;
CGFloat height = image.size.height;
NSString *fileName = [[[NSProcessInfo processInfo] globallyUniqueString] stringByAppendingString:@".png"];
NSString *filePath = [self saveToFilePathWithImage:image name:fileName];
__weak NSString *weakFileName = fileName;
id(^ContinuationBlock)(AWSTask *task) = ^id(AWSTask *task) {
if (task.error) {
[SVProgressHUD showErrorWithStatus:@"上传失败"];
if (completion) {
completion(nil);
}
}
else {
__strong NSString *strongFileName = weakFileName;
//上传成功并不返回url,访问资源需要使用AmazonSDK解码,可以在上传的时候设置成可读写,然后用拼接出来的url访问图片
NSString *url = [[@"http:/ /....com" stringByAppendingPathComponent:BUCKET_NAME] stringByAppendingPathComponent:strongFileName];
url = [url stringByReplacingOccurrencesOfString:@" " withString:@""];
if (completion) {
completion(url);
}
}
return nil;
};
AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.body = [NSURL fileURLWithPath:filePath];
uploadRequest.key = fileName;
uploadRequest.bucket = @"your bucket name(这里填你的bucketname)";
// 设置成可读写的,才可以使用拼接的url
uploadRequest.ACL = AWSS3ObjectCannedACLPublicReadWrite;
AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
[[transferManager upload:uploadRequest] continueWithBlock:ContinuationBlock];
}
+ (NSString *)saveToFilePathWithImage:(UIImage *)image
name:(NSString *)name {
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"upload"];
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:filePath]) {
[manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
}
filePath = [filePath stringByAppendingPathComponent:name];
NSData * imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];
return filePath;
}
这样就能实现上传功能了