博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
利用信号量实现阿里云OSS多图片上传
阅读量:2442 次
发布时间:2019-05-10

本文共 3472 字,大约阅读时间需要 11 分钟。

#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);
        });
}

转载地址:http://cziqb.baihongyu.com/

你可能感兴趣的文章
graph api_与Facebook Graph API集成
查看>>
本地应用程序_本地化PHP应用程序的“正确方法”,第4部分
查看>>
mfc单文档绘制世界坐标系_文档使世界运转
查看>>
防止跨站请求伪造(CSRF)
查看>>
科创板 云计算业务公司_云计算对您的业务意味着什么
查看>>
SitePoint播客#80:与澳大利亚团队的FullCodePress
查看>>
BigCommerce和Volusion:比较设置和移动
查看>>
使用codeigniter_使用CodeIgniter探索面向方面的编程,第3部分
查看>>
使用codeigniter_使用CodeIgniter探索面向方面的编程,第2部分
查看>>
用Wufoo创建简单表单:开发人员的观点
查看>>
heroku_使用Heroku和Facebook SDK在云中构建您的应用
查看>>
SitePoint播客#145:Addy Osmani的Backbone.js基础
查看>>
Google发布Chrome 4.0
查看>>
将ip保存在txt文档中_将任何文件存储在Google文档中
查看>>
disconf apps_Google Apps Drop IE6支持
查看>>
使用Screenr创建截屏视频
查看>>
微信小程序使用flex布局_使用Flex来启动您PHP应用程序!
查看>>
互联网总线带宽_新技术将使互联网带宽翻倍
查看>>
java自由职业者是什么_一个成功的自由职业者需要什么?
查看>>
paas云平台架构_PaaS:通过Node.js中的RESTful API管理您的云基础架构
查看>>