OSSManager.m 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. //
  2. // OSSManager.m
  3. // AliyunOSSSDK-iOS-Example
  4. //
  5. // Created by huaixu on 2018/10/23.
  6. // Copyright © 2018 aliyun. All rights reserved.
  7. //
  8. #import "OSSManager.h"
  9. #import "OssNetApi.h"
  10. #import <AliyunOSSiOS/OSSService.h>
  11. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  12. #define endpoint @"https://oss-ap-southeast-1.aliyuncs.com"//生产服务器
  13. @interface OSSManager ()
  14. @property (nonatomic, strong) OSSPutObjectRequest *normalUploadRequest;
  15. @property (nonatomic, strong) OSSGetObjectRequest *normalDloadRequest;
  16. @end
  17. @implementation OSSManager
  18. + (instancetype)sharedManager {
  19. static OSSManager *_manager = nil;
  20. static dispatch_once_t onceToken;
  21. dispatch_once(&onceToken, ^{
  22. _manager = [[OSSManager alloc] init];
  23. });
  24. return _manager;
  25. }
  26. -(void)getOSSInfo{
  27. NSDictionary *dic = [UDManager.shareInstance getDDManager:nkOSSinfo];
  28. if(dic){
  29. self.OSSInfo = dic.copy;
  30. [self initmyAliyunOSS];
  31. }
  32. [OssNetApi getOSSInfo:nil succ:^(int code, NSDictionary * res) {
  33. NSLog(@"res:%@",res);
  34. NSString *codeV =res[@"code"];
  35. if(codeV.intValue==200){
  36. self.OSSInfo = res[@"data"];
  37. if(self.OSSInfo){
  38. [self initmyAliyunOSS];
  39. [UDManager.shareInstance setDDManager:self.OSSInfo key:nkOSSinfo];
  40. }
  41. }
  42. } fail:^(NSError * _Nonnull error) {
  43. }];
  44. }
  45. -(void)initmyAliyunOSS{
  46. if(self.OSSInfo){
  47. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  48. //NSString *endpoint = @"https://oss-ap-southeast-1.aliyuncs.com";
  49. // 旧版本图片服务的endpoint
  50. // NSString *oldimgendpoint = @"http://img-ap-southeast-1.aliyuncs.com";
  51. // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
  52. NSString *accessKeyId = self.OSSInfo[@"accessKeyId"];
  53. NSString *accessKeySecret = self.OSSInfo[@"accessKeySecret"];
  54. // 从STS服务获取的安全令牌(SecurityToken)。
  55. NSString *securityToken = self.OSSInfo[@"securityToken"];
  56. // NSString *expiration = self.OSSInfo[@"expiration"];
  57. id<OSSCredentialProvider> credentialProvider = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:accessKeyId secretKeyId:accessKeySecret securityToken:securityToken];
  58. OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
  59. cfg.maxRetryCount = 3;
  60. cfg.timeoutIntervalForRequest = 15;
  61. cfg.isHttpdnsEnable = NO;
  62. cfg.crc64Verifiable = YES;
  63. OSSClient *defaultClient = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credentialProvider clientConfiguration:cfg];
  64. [OSSManager sharedManager].defaultClient = defaultClient;
  65. //旧的图片服务
  66. // OSSClient *defaultImgClient = [[OSSClient alloc] initWithEndpoint:oldimgendpoint credentialProvider:credentialProvider clientConfiguration:cfg];
  67. // [OSSManager sharedManager].imageClient = defaultImgClient;
  68. }
  69. }
  70. //普通上传
  71. - (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{
  72. if([OSSManager sharedManager].defaultClient==nil){
  73. [MBProgressHUD showWithText:@"OSS文件服务初始化失败!請重試"];
  74. [self getOSSInfo];
  75. return;
  76. }
  77. if (![objectKey oss_isNotEmpty]) {
  78. NSError *error = [NSError errorWithDomain:NSInvalidArgumentException code:0 userInfo:@{NSLocalizedDescriptionKey: @"objectKey should not be nil"}];
  79. failure(error,strtime);
  80. return;
  81. }
  82. NSLog(@"objectKey:%@",objectKey);
  83. _normalUploadRequest = [OSSPutObjectRequest new];
  84. _normalUploadRequest.bucketName = self.OSSInfo[@"bucket"];
  85. _normalUploadRequest.objectKey = objectKey;
  86. _normalUploadRequest.uploadingFileURL = [NSURL fileURLWithPath:filePath];
  87. _normalUploadRequest.isAuthenticationRequired = YES;
  88. _normalUploadRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  89. CGFloat progress = 1.f * totalByteSent / totalBytesExpectedToSend;
  90. // NSLog(@"上传文件进度: %f", progress);
  91. NSInteger pcent =progress*100;
  92. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  93. prgress(pcent,strtime);
  94. });
  95. };
  96. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  97. OSSTask * task = [[OSSManager sharedManager].defaultClient putObject:self->_normalUploadRequest];
  98. [task continueWithBlock:^id(OSSTask *task) {
  99. dispatch_async(dispatch_get_main_queue(), ^{
  100. if (task.error) {
  101. failure(task.error,strtime);
  102. } else {
  103. success(task,strtime);
  104. NSLog(@"上传文件完成");
  105. }
  106. });
  107. return nil;
  108. }];
  109. });
  110. }
  111. //断点续传
  112. - (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{
  113. if([OSSManager sharedManager].defaultClient==nil){
  114. [MBProgressHUD showWithText:@"OSS文件服务初始化失败!請重試"];
  115. [self getOSSInfo];
  116. return;
  117. }
  118. // 获取UploadId上传文件。
  119. OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];
  120. resumableUpload.bucketName = self.OSSInfo[@"bucket"];
  121. // objectKey等同于objectName,表示断点上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg
  122. resumableUpload.objectKey = objectKey;
  123. resumableUpload.partSize = 1024 * 1024;
  124. resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  125. // NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
  126. CGFloat progress = 1.f * totalByteSent / totalBytesExpectedToSend;
  127. // NSLog(@"上传文件进度: %f", progress);
  128. NSInteger pcent =progress*100;
  129. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  130. prgress(pcent,strtime);
  131. });
  132. };
  133. NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  134. // 设置断点记录保存路径。
  135. resumableUpload.recordDirectoryPath = cachesDir;
  136. // 将参数deleteUploadIdOnCancelling设置为NO,表示不删除断点记录文件,上传失败后将从断点记录处继续上传直到文件上传完成。如果不设置此参数,即保留默认值YES,表示删除断点记录文件,下次再上传同一文件时则重新上传。
  137. resumableUpload.deleteUploadIdOnCancelling = NO;
  138. resumableUpload.uploadingFileURL = [NSURL fileURLWithPath:filePath];
  139. OSSTask * resumeTask = [[OSSManager sharedManager].defaultClient resumableUpload:resumableUpload];
  140. [resumeTask continueWithBlock:^id(OSSTask *task) {
  141. if (task.error) {
  142. NSLog(@"error: %@", task.error);
  143. if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {
  144. // 此任务无法续传,需获取新的uploadId重新上传。
  145. failure(task.error,strtime);
  146. }
  147. } else {
  148. NSLog(@"Upload file success");
  149. success(task,strtime);
  150. }
  151. return nil;
  152. }];
  153. // [resumeTask waitUntilFinished];
  154. // [resumableUpload cancel];
  155. }
  156. @end