| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190 |
- //
- // OSSManager.m
- // AliyunOSSSDK-iOS-Example
- //
- // Created by huaixu on 2018/10/23.
- // Copyright © 2018 aliyun. All rights reserved.
- //
- #import "OSSManager.h"
- #import "OssNetApi.h"
- #import <AliyunOSSiOS/OSSService.h>
- // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
- #define endpoint @"https://oss-ap-southeast-1.aliyuncs.com"//生产服务器
- @interface OSSManager ()
- @property (nonatomic, strong) OSSPutObjectRequest *normalUploadRequest;
- @property (nonatomic, strong) OSSGetObjectRequest *normalDloadRequest;
- @end
- @implementation OSSManager
- + (instancetype)sharedManager {
- static OSSManager *_manager = nil;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- _manager = [[OSSManager alloc] init];
- });
-
- return _manager;
- }
- -(void)getOSSInfo{
-
- NSDictionary *dic = [UDManager.shareInstance getDDManager:nkOSSinfo];
- if(dic){
- self.OSSInfo = dic.copy;
- [self initmyAliyunOSS];
- }
-
- [OssNetApi getOSSInfo:nil succ:^(int code, NSDictionary * res) {
- NSLog(@"res:%@",res);
- NSString *codeV =res[@"code"];
- if(codeV.intValue==200){
- self.OSSInfo = res[@"data"];
- if(self.OSSInfo){
- [self initmyAliyunOSS];
- [UDManager.shareInstance setDDManager:self.OSSInfo key:nkOSSinfo];
- }
- }
- } fail:^(NSError * _Nonnull error) {
-
- }];
- }
- -(void)initmyAliyunOSS{
- if(self.OSSInfo){
- // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
- //NSString *endpoint = @"https://oss-ap-southeast-1.aliyuncs.com";
-
- // 旧版本图片服务的endpoint
- // NSString *oldimgendpoint = @"http://img-ap-southeast-1.aliyuncs.com";
- // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
- NSString *accessKeyId = self.OSSInfo[@"accessKeyId"];
- NSString *accessKeySecret = self.OSSInfo[@"accessKeySecret"];
- // 从STS服务获取的安全令牌(SecurityToken)。
- NSString *securityToken = self.OSSInfo[@"securityToken"];
- // NSString *expiration = self.OSSInfo[@"expiration"];
-
-
- id<OSSCredentialProvider> credentialProvider = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:accessKeyId secretKeyId:accessKeySecret securityToken:securityToken];
- OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
- cfg.maxRetryCount = 3;
- cfg.timeoutIntervalForRequest = 15;
- cfg.isHttpdnsEnable = NO;
- cfg.crc64Verifiable = YES;
-
- OSSClient *defaultClient = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credentialProvider clientConfiguration:cfg];
- [OSSManager sharedManager].defaultClient = defaultClient;
- //旧的图片服务
- // OSSClient *defaultImgClient = [[OSSClient alloc] initWithEndpoint:oldimgendpoint credentialProvider:credentialProvider clientConfiguration:cfg];
- // [OSSManager sharedManager].imageClient = defaultImgClient;
- }
- }
- //普通上传
- - (void)asyncPutFile:(NSString *)objectKey localFilePath:(NSString *)filePath thrid:(NSString *)strtime progress:(void (^)(NSInteger,NSString *))prgress success:(void (^)(id _Nullable,NSString *))success failure:(void (^)(NSError * _Nonnull,NSString *))failure{
- if([OSSManager sharedManager].defaultClient==nil){
- [MBProgressHUD showWithText:@"OSS文件服务初始化失败!請重試"];
- [self getOSSInfo];
- return;
- }
- if (![objectKey oss_isNotEmpty]) {
- NSError *error = [NSError errorWithDomain:NSInvalidArgumentException code:0 userInfo:@{NSLocalizedDescriptionKey: @"objectKey should not be nil"}];
- failure(error,strtime);
- return;
- }
-
- NSLog(@"objectKey:%@",objectKey);
- _normalUploadRequest = [OSSPutObjectRequest new];
- _normalUploadRequest.bucketName = self.OSSInfo[@"bucket"];
- _normalUploadRequest.objectKey = objectKey;
- _normalUploadRequest.uploadingFileURL = [NSURL fileURLWithPath:filePath];
- _normalUploadRequest.isAuthenticationRequired = YES;
- _normalUploadRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
- CGFloat progress = 1.f * totalByteSent / totalBytesExpectedToSend;
- // NSLog(@"上传文件进度: %f", progress);
- NSInteger pcent =progress*100;
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- prgress(pcent,strtime);
- });
-
- };
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- OSSTask * task = [[OSSManager sharedManager].defaultClient putObject:self->_normalUploadRequest];
- [task continueWithBlock:^id(OSSTask *task) {
- dispatch_async(dispatch_get_main_queue(), ^{
- if (task.error) {
- failure(task.error,strtime);
- } else {
- success(task,strtime);
- NSLog(@"上传文件完成");
- }
- });
-
- return nil;
- }];
- });
- }
- //断点续传
- - (void)asyncResumableUploadFile:(NSString *)objectKey localFilePath:(NSString *)filePath thrid:(NSString *)strtime progress:(void (^)(NSInteger,NSString *))prgress success:(void (^)(id _Nullable,NSString *))success failure:(void (^)(NSError * _Nonnull,NSString *))failure{
-
- if([OSSManager sharedManager].defaultClient==nil){
- [MBProgressHUD showWithText:@"OSS文件服务初始化失败!請重試"];
- [self getOSSInfo];
- return;
- }
-
- // 获取UploadId上传文件。
- OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];
- resumableUpload.bucketName = self.OSSInfo[@"bucket"];
- // objectKey等同于objectName,表示断点上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg
- resumableUpload.objectKey = objectKey;
- resumableUpload.partSize = 1024 * 1024;
- resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
- // NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
- CGFloat progress = 1.f * totalByteSent / totalBytesExpectedToSend;
- // NSLog(@"上传文件进度: %f", progress);
- NSInteger pcent =progress*100;
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- prgress(pcent,strtime);
- });
- };
- NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
- // 设置断点记录保存路径。
- resumableUpload.recordDirectoryPath = cachesDir;
- // 将参数deleteUploadIdOnCancelling设置为NO,表示不删除断点记录文件,上传失败后将从断点记录处继续上传直到文件上传完成。如果不设置此参数,即保留默认值YES,表示删除断点记录文件,下次再上传同一文件时则重新上传。
- resumableUpload.deleteUploadIdOnCancelling = NO;
- resumableUpload.uploadingFileURL = [NSURL fileURLWithPath:filePath];
- OSSTask * resumeTask = [[OSSManager sharedManager].defaultClient resumableUpload:resumableUpload];
- [resumeTask continueWithBlock:^id(OSSTask *task) {
- if (task.error) {
- NSLog(@"error: %@", task.error);
- if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {
- // 此任务无法续传,需获取新的uploadId重新上传。
- failure(task.error,strtime);
- }
- } else {
- NSLog(@"Upload file success");
- success(task,strtime);
- }
- return nil;
- }];
- // [resumeTask waitUntilFinished];
- // [resumableUpload cancel];
- }
- @end
|