面试20K+高级iOS开发必须深入掌握的知识点

ios 阿里云oss多线程上传图片

2017-06-07  本文已影响844人  进击的小杰
#import "AlyCommitImageTool.h"
#import <AliyunOSSiOS/OSSService.h>

@interface AlyCommitImageTool(){
    
    NSMutableArray *imageArray;//图片数组
    NSMutableArray *imageNameArray;//图片名字数组
    NSMutableArray *imagePathArray;//图片路径数组
    NSMutableArray *imagePutObjectArray;//图片上传数组
    NSInteger currentCommitIndex;
}

@property (strong, nonatomic) OSSClient *aliOssClient;

@end

@implementation AlyCommitImageTool

-(id)init{

    if(self=[super init]){
        
        imageArray=[[NSMutableArray alloc]init];
        imageNameArray=[[NSMutableArray alloc]init];
        imagePathArray=[[NSMutableArray alloc]init];
        imagePutObjectArray=[[NSMutableArray alloc]init];
    }
    return self;

}

//阿里云 oss 上传于下载实体
- (OSSClient *)aliOssClient
{
    if (!_aliOssClient) {
        //判断服务端是否返回key和id
        if(KgetUserValueByParaName(@"AccessKey")&& KgetUserValueByParaName(@"AccessId")){
            id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:KgetUserValueByParaName(@"AccessId")  secretKey: KgetUserValueByParaName(@"AccessKey")];
            _aliOssClient = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:credential];
        }else{
        id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:OSS_ACCESSKEYID  secretKey: OSS_ACCESSKEYSERCET];
        _aliOssClient = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:credential];
        }
    }
    return _aliOssClient;
}

- (void)uploadImages:(NSArray<UIImage *> *)images isAsync:(BOOL)isAsync fromWhere:(NSString *)path complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = images.count;
    
    NSMutableArray *callBackNames = [NSMutableArray array];
    int i = 0;
    for (UIImage *image in images) {
        if (image) {
            NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
                //任务执行
                OSSPutObjectRequest * put = [OSSPutObjectRequest new];
                
                put.bucketName = XinHuaAppDelegate.initialObj.UploadBucket;
                
                // 路径格式:NSString *imageName =@"Party/2/110038/ClientUpload/2017/03/23/201703231234.jpg";
                int aRandomNum = arc4random()%9996;
                
                NSDate *now = [NSDate date];
                NSLog(@"now date is: %@", now);
                NSCalendar *calendar = [NSCalendar currentCalendar];
                NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
                NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                [formatter setDateFormat:@"YYYYMMdd"];
                NSString *dateStr = [formatter stringFromDate:[NSDate date]];
                NSString *filePath = [NSString stringWithFormat:@"%@%d",dateStr,aRandomNum];
                NSString *imageName =[NSString stringWithFormat:@"%@%@/%ld/%ld/%ld/%@.jpg",XinHuaAppDelegate.initialObj.UploadRoot,path,(long)[dateComponent year],(long)[dateComponent month],(long)[dateComponent day],filePath];
                NSString *imageNamePath=imageName;
                //如果第一个字符是/ 则去除
                if([[imageName substringToIndex:1]isEqualToString:@"/"]){
                     imageName=[imageName substringFromIndex:1];
                }else{
                
                }
                put.objectKey = imageName;
                [callBackNames addObject:imageNamePath];
//                NSData *data = UIImageJPEGRepresentation(image, 0.3);
                NSData *data = [self imageData:image];
                put.uploadingData = data;
                
                OSSTask * putTask = [self.aliOssClient putObject:put];
                [putTask waitUntilFinished]; // 阻塞直到上传完成
                if (!putTask.error) {
                    NSLog(@"upload object success!");
                } else {
                    NSLog(@"upload object failed, error: %@" , putTask.error);
                }
                if (isAsync) {
                    if (image == images.lastObject) {
                        NSLog(@"upload object finished!");
                        if (complete) {
                            complete([NSArray arrayWithArray:callBackNames] ,UploadImageSuccess);
                        }
                    }
                }
            }];
            if (queue.operations.count != 0) {
                [operation addDependency:queue.operations.lastObject];
            }
            [queue addOperation:operation];
        }
        i++;
    }
    if (!isAsync) {
        [queue waitUntilAllOperationsAreFinished];
        NSLog(@"haha");
        if (complete) {
            if (complete) {
                complete([NSArray arrayWithArray:callBackNames], UploadImageSuccess);
            }
        }
    }
}

-(NSData *)imageData:(UIImage *)myimage
{
    NSData *data=UIImageJPEGRepresentation(myimage, 1.0);
    if (data.length>100*1024) {
        if (data.length>1024*1024) {//1M以及以上
//            data = [self compressImage:myimage toMaxFileSize:512*1024/5];
            data=[self resetSizeOfImageData:myimage maxSize:512*1024/5];
            //            data=UIImageJPEGRepresentation(myimage, 0.1);
        }else if (data.length>512*1024) {//0.5M-1M
            data=UIImageJPEGRepresentation(myimage, 0.5);
        }else if (data.length>200*1024) {//0.25M-0.5M
            data=UIImageJPEGRepresentation(myimage, 0.9);
        }
    }
    
    return data;
}

//压缩图片处理(先调整分辨率)
-(NSData*)resetSizeOfImageData:(UIImage*)sourceImage maxSize:(NSInteger)maxSize
{
    //优先调整分辨率
    
    CGSize newSize=CGSizeMake(sourceImage.size.width, sourceImage.size.height);
    
    CGFloat tempHeight=newSize.height/1024;
    
    CGFloat tempWidth=newSize.width/1024;
    
//    if (tempWidth>1.0&&tempWidth>tempHeight) {
    
    newSize=CGSizeMake(sourceImage.size.width/tempWidth, sourceImage.size.height/tempHeight);
        
//    }
    
    UIGraphicsBeginImageContext(newSize);
    
    [sourceImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    //再调整大小
    
    NSData *imageData=UIImageJPEGRepresentation(newImage, 0.4);
    
    NSUInteger sizeOrigin=[imageData length];
    
    NSUInteger sizeOriginKB=sizeOrigin/1024;
    
    if (sizeOriginKB>maxSize) {
        
        NSData *finalImageData=UIImageJPEGRepresentation(newImage, 0.5);
        
        return finalImageData;
    }
    NSLog(@"#####***%lu",(unsigned long)imageData.length);
    return imageData;
}

@end
上一篇下一篇

猜你喜欢

热点阅读