BGOssManager.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. //
  2. // BGOssManager.m
  3. // BuguLive
  4. //
  5. // Created by 丁凯 on 2017/7/31.
  6. // Copyright © 2017年 xfg. All rights reserved.
  7. //
  8. #import "BGOssManager.h"
  9. NSString * const bucketName = @"sdk-demo";
  10. NSString * const STSServer = @"http://oss-cn-shanghai.aliyuncs.com/app-server/sts.php";
  11. @implementation BGOssManager
  12. - (id)initWithDelegate:(id<OssUploadImageDelegate>)delegate
  13. {
  14. if (self = [super init])
  15. {
  16. _BuguLive = [GlobalVariables sharedInstance];
  17. _httpsManager = [NetHttpsManager manager];
  18. self.OssDelegate = delegate;
  19. [self getinfomation];
  20. }
  21. return self;
  22. }
  23. #pragma mark 请求接口获得上传图片需要的各种参数
  24. - (void)getinfomation
  25. {
  26. NSMutableDictionary * mDict = [NSMutableDictionary dictionary];
  27. [mDict setObject:@"app" forKey:@"ctl"];
  28. [mDict setObject:@"aliyun_sts" forKey:@"act"];
  29. FWWeakify(self)
  30. [_httpsManager POSTWithParameters:mDict SuccessBlock:^(NSDictionary *responseJson) {
  31. FWStrongify(self)
  32. [self loadOssDic:responseJson];
  33. } FailureBlock:^(NSError *error){
  34. }];
  35. }
  36. #pragma mark 请求oss接口请求返回数据的处理
  37. - (void)loadOssDic:(NSDictionary *)responseJson
  38. {
  39. _oss_domain = [responseJson objectForKey:@"oss_domain"];
  40. _endPoint = [responseJson objectForKey:@"endpoint"];
  41. _imageEndPoint = [responseJson objectForKey:@"imgendpoint"];
  42. _callbackAddress = [responseJson objectForKey:@"callbackUrl"];
  43. _dir = [responseJson objectForKey:@"dir"];
  44. _AccessKeyId = [responseJson objectForKey:@"AccessKeyId"];
  45. _AccessKeySecret = [responseJson objectForKey:@"AccessKeySecret"];
  46. _SecurityToken = [responseJson objectForKey:@"SecurityToken"];
  47. _Expiration = [responseJson objectForKey:@"Expiration"];
  48. _bucket = [responseJson objectForKey:@"bucket"];
  49. if ([self isSetRightParameter])
  50. {
  51. [self ossInit];
  52. }
  53. }
  54. #pragma mark oss上传的参数是不是配置好
  55. - (BOOL)isSetRightParameter
  56. {
  57. if (_endPoint.length < 1 || _dir.length < 1 || _bucket.length < 1 || _AccessKeyId.length < 1 || _AccessKeySecret.length < 1 || _SecurityToken.length < 1 || _bucket.length < 1)
  58. {
  59. return NO;
  60. }else
  61. {
  62. return YES;
  63. }
  64. }
  65. #pragma mark 获取FederationToken
  66. - (OSSFederationToken *) getFederationToken
  67. {
  68. NSURL * url = [NSURL URLWithString:STSServer];
  69. NSURLRequest * request = [NSURLRequest requestWithURL:url];
  70. OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
  71. NSURLSession * session = [NSURLSession sharedSession];
  72. NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
  73. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  74. if (error) {
  75. [tcs setError:error];
  76. return;
  77. }
  78. [tcs setResult:data];
  79. }];
  80. [sessionTask resume];
  81. // 实现这个回调需要同步返回Token,所以要waitUntilFinished
  82. [tcs.task waitUntilFinished];
  83. if (tcs.task.error) {
  84. return nil;
  85. } else {
  86. OSSFederationToken * token = [OSSFederationToken new];
  87. token.tAccessKey = _AccessKeyId;
  88. token.tSecretKey = _AccessKeySecret;
  89. token.tToken = _SecurityToken;
  90. token.expirationTimeInGMTFormat = _Expiration;
  91. return token;
  92. }
  93. }
  94. #pragma mark 初始化获取OSSClient
  95. - (void)ossInit
  96. {
  97. id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
  98. return [self getFederationToken];
  99. }];
  100. _client = [[OSSClient alloc] initWithEndpoint:_endPoint credentialProvider:credential];
  101. }
  102. #pragma mark 设置server callback地址
  103. - (void)setCallbackAddress:(NSString *)address
  104. {
  105. _callbackAddress = address;
  106. }
  107. #pragma mark 上传图片
  108. - (void)asyncPutImage:(NSString *)objectKey
  109. localFilePath:(NSString *)filePath
  110. {
  111. if (objectKey == nil || [objectKey length] == 0)
  112. {
  113. return;
  114. }
  115. _putRequest = [OSSPutObjectRequest new];
  116. _putRequest.bucketName = _bucket;
  117. _putRequest.objectKey = objectKey;
  118. _putRequest.uploadingFileURL = [NSURL fileURLWithPath:filePath];
  119. _putRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  120. NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
  121. };
  122. if (_callbackAddress != nil) {
  123. _putRequest.callbackParam = @{
  124. @"callbackUrl": _callbackAddress,
  125. // callbackBody可自定义传入的信息
  126. @"callbackBody": @"filename=${object}"
  127. };
  128. }
  129. OSSTask * task = [_client putObject:_putRequest];
  130. [task continueWithBlock:^id(OSSTask *task) {
  131. OSSPutObjectResult * result = task.result;
  132. // 查看server callback是否成功
  133. if (!task.error) {
  134. NSLog(@"Put image success!");
  135. NSLog(@"result==%@",result);
  136. NSLog(@"server callback:%@", result.serverReturnJsonString);
  137. dispatch_async(dispatch_get_main_queue(), ^{
  138. self.statutCount = 0;
  139. if (self.OssDelegate)
  140. {
  141. if (self.OssDelegate) {
  142. if ([self.OssDelegate respondsToSelector:@selector(uploadImageWithUrlStr:withUploadStateCount:)])
  143. {
  144. [self.OssDelegate uploadImageWithUrlStr:result.serverReturnJsonString withUploadStateCount:self.statutCount];
  145. }
  146. }
  147. }
  148. });
  149. } else {
  150. NSLog(@"Put image failed, %@", task.error);
  151. if (task.error.code == OSSClientErrorCodeTaskCancelled) {
  152. dispatch_async(dispatch_get_main_queue(), ^{
  153. self.statutCount = 1;
  154. if (self.OssDelegate)
  155. {
  156. if (self.OssDelegate) {
  157. if ([self.OssDelegate respondsToSelector:@selector(uploadImageWithUrlStr:withUploadStateCount:)])
  158. {
  159. [self.OssDelegate uploadImageWithUrlStr:result.serverReturnJsonString withUploadStateCount:self.statutCount];
  160. }
  161. }
  162. }
  163. });
  164. } else {
  165. dispatch_async(dispatch_get_main_queue(), ^{
  166. self.statutCount = 2;
  167. if (self.OssDelegate)
  168. {
  169. if (self.OssDelegate) {
  170. if ([self.OssDelegate respondsToSelector:@selector(uploadImageWithUrlStr:withUploadStateCount:)])
  171. {
  172. [self.OssDelegate uploadImageWithUrlStr:result.serverReturnJsonString withUploadStateCount:self.statutCount];
  173. }
  174. }
  175. }
  176. });
  177. }
  178. }
  179. _putRequest = nil;
  180. return nil;
  181. }];
  182. }
  183. #pragma mark -------------------------------- oss 上传
  184. #pragma mark --- 上传照片 或视频 的二进制数据
  185. -(void)showUploadOfOssServiceOfDataMarray:(NSMutableArray<NSData *>*)dataArray
  186. andSTDynamicSelectType:(STDynamicSelectType)stDynamicSelectType
  187. andComplete:(void(^)(BOOL finished,
  188. NSMutableArray <NSString *>*urlStrMArray))block{
  189. #pragma mark --- 预处理
  190. //数据
  191. if (!dataArray.count||!dataArray) {
  192. if (block) {
  193. block(NO,nil);
  194. }
  195. return;
  196. }
  197. //设置数组 存放返回的url
  198. NSMutableArray *urlStrMArray = @[].mutableCopy;
  199. //开启 多线程 for 循环创立
  200. dispatch_queue_t st_queue = dispatch_queue_create("upLoadImgArray", DISPATCH_QUEUE_SERIAL);
  201. for (int i= 0;i <dataArray.count; i++) {
  202. //预处理 objectKeyStr
  203. NSString *objectKeyStr = [self getObjectKeyString];
  204. if (objectKeyStr == nil || [objectKeyStr length] == 0) {
  205. if (block) {
  206. block(NO,nil);
  207. }
  208. return;
  209. }
  210. //开启分线程
  211. dispatch_async(st_queue, ^{
  212. _putRequest = [OSSPutObjectRequest new];
  213. _putRequest.bucketName = _bucket;
  214. if (stDynamicSelectType == STDynamicSelectVideo ) {
  215. _putRequest.objectKey = [objectKeyStr stringByReplacingOccurrencesOfString:@"png" withString:@"mp4"];
  216. }else{
  217. _putRequest.objectKey = objectKeyStr;
  218. }
  219. // putRequest.objectKey = objectKeyStr;
  220. _putRequest.uploadingData = dataArray[i];
  221. _putRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  222. };
  223. if (_callbackAddress != nil) {
  224. _putRequest.callbackParam = @{
  225. @"callbackUrl": _callbackAddress,
  226. // callbackBody可自定义传入的信息
  227. @"callbackBody": @"filename=${object}"
  228. };
  229. }
  230. //上传任务
  231. OSSTask * task = [_client putObject:_putRequest];
  232. [task continueWithBlock:^id(OSSTask *task) {
  233. OSSPutObjectResult * result = task.result;
  234. //阻塞 上传
  235. [task waitUntilFinished];
  236. // 查看server callback是否成功
  237. if (!task.error) {
  238. NSLog(@"Put image success!");
  239. NSLog(@"result==%@",result);
  240. NSLog(@"server callback--------:%@", result.serverReturnJsonString);
  241. //返回urlStr
  242. NSString *tempStr;
  243. if (stDynamicSelectType == STDynamicSelectVideo ) {
  244. tempStr = [objectKeyStr stringByReplacingOccurrencesOfString:@"png" withString:@"mp4"];
  245. }else{
  246. tempStr = objectKeyStr;
  247. }
  248. NSString *urlStr = [NSString stringWithFormat:@"%@%@",@"./",tempStr];
  249. NSLog(@"------urlStr--------%@---------",urlStr);
  250. [urlStrMArray addObject:urlStr];
  251. if (i+1 ==dataArray.count ) {
  252. if (block) {
  253. block(YES,urlStrMArray);
  254. }
  255. }
  256. } else {
  257. NSLog(@"eqewqw2222");
  258. }
  259. _putRequest = nil;
  260. return nil;
  261. }];
  262. [task waitUntilFinished];
  263. });
  264. }
  265. }
  266. - (NSString *)getObjectKeyString
  267. {
  268. NSDate *currentDate = [NSDate date];//获取当前时间日期
  269. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  270. [dateFormatter setDateFormat:@"YYYYMMddhhmmssSSS"];
  271. NSString *dateString = [dateFormatter stringFromDate:currentDate];
  272. NSString *nameString = [NSString stringWithFormat:@"%@%d.png",dateString,arc4random()%10000/1000];
  273. _objectKey = [NSString stringWithFormat:@"%@%@",self.dir,nameString];
  274. return _objectKey;
  275. }
  276. @end