利用信号量实现阿里云OSS多图片上传

#pragma mark Service
- (void)uploadImageArrayToAliyunOSS
{
    WS(weakself)
    
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(queue, ^{
            for (int i = 0; i < weakself.imageOrVideoMarray.count; i ++) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    WS(weakself)
                    [[LMSAPIClient apiManager]GET:kLMSAliyunOSSUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                        
                    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        NSDictionary *responseJSON;
                        if (![responseObject isKindOfClass:[NSDictionary class]])
                        {
                            NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                            NSData *JSONData = [result dataUsingEncoding:NSUTF8StringEncoding];
                            responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
                        }else
                        {
                            responseJSON = (NSDictionary*)responseObject;
                        }
                        NSLog(@"------------%@",responseJSON);

                        NSDictionary *dict = responseJSON[@"data"];
                        NSString *AccessKeyId = dict[@"accessKeyId"];
                        NSString *AccessKeySecret = dict[@"accessKeySecret"];
                        NSString *SecurityToken = dict[@"securityToken"];
                        NSString *host = dict[@"host"];
                        NSString *fileUrl = dict[@"fileUrl"];//显示的url路径
                        NSString *path = dict[@"dir"];//显示的url拼接的路径(不是完整的 还需在拼接)
                        NSRange rang = [host rangeOfString:@"."]; //已经解码
                        NSString *endpoint;
                        NSString *bucketName;
                        if (rang.location != NSIntegerMax)
                        {
                            bucketName = [host substringWithRange:NSMakeRange(8, rang.location-8)];//上传时用到的bucketName
                            endpoint = [host substringFromIndex:rang.location+1];
                        }
                        
                        self.apiOssDict = @{@"bucketName":bucketName,@"fileUrl":fileUrl,@"path":path};
                        
                        id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:AccessKeyId secretKeyId:AccessKeySecret securityToken:SecurityToken];
                        
                        OSSClientConfiguration * conf = [OSSClientConfiguration new];
                        conf.maxRetryCount = 1;
                        conf.timeoutIntervalForRequest = 30;
                        conf.timeoutIntervalForResource = 24 * 60 * 60;
                        
                        self.client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];
                         OSSPutObjectRequest * put = [OSSPutObjectRequest new];
                           put.bucketName =self.apiOssDict[@"bucketName"];
                           put.objectKey = [NSString stringWithFormat:@"%@%@.jpg",self.apiOssDict[@"path"],[self getTimestampFromTime]];
                           UIImage *testImage = self.imageOrVideoMarray[i];
                           put.uploadingData = UIImageJPEGRepresentation( testImage , 1.0); // 直接上传NSData
                           put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
                               NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
                           };
                           OSSTask * putTask = [weakself.client putObject:put];
                           [putTask continueWithBlock:^id(OSSTask *task) {
                               if (!task.error) {
                                        NSString *imageUrlStr = [NSString stringWithFormat:@"%@%@",weakself.apiOssDict[@"fileUrl"],put.objectKey];
                                         [weakself.photoMarray addObject:imageUrlStr];
                                         
                                         NSLog(@"upload object success!%@",self.photoMarray);
                                    dispatch_semaphore_signal(semaphore);
                                   NSLog(@"upload object success!");
                               } else {
                                   NSLog(@"upload object failed, error: %@" , task.error);
                               }
                               return nil;
                           }];
                        
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        NSLog(@"-------%@",error.localizedDescription);
                    }];
                });
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            }
            NSLog(@"任务全部执行完成%@",self.photoMarray);
        });
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值