阿里OSS Objective-c多图片上传

向阿里云OSS里边上传图片,iOS系统,Objective-C语言。

//
//  AliOssUploadFiles.h
//  AliyunOssDemo
//
//  Created by Admin on 2018/10/17.
//  Copyright © 2018 huaibor. All rights reserved.
//
 
#import <Foundation/Foundation.h>
//
#import "AliOssUploadModel.h"
 
#define AliOSSFileManager [AliOssUploadFiles manager]
 
@interface AliOssUploadFiles : NSObject
+ (instancetype)manager;
//上传
- (void)uploadImages:(NSArray *)images beginHandle:(void(^)(void))beginHandle complate:(void(^)(NSArray *callResult,NSError *error))complate;
//处理图片,返回json字符串
- (NSString *)dealImageByUploadWithModels:(NSArray *)models;
@end


//
//  AliOssUploadFiles.m
//  AliyunOssDemo
//
//  Created by Admin on 2018/10/17.
//  Copyright © 2018 huaibor. All rights reserved.
//
 
#import "AliOssUploadFiles.h"
#import <AliyunOSSiOS/AliyunOSSiOS.h>
 
 
#define OSSEndpoint @""
#define OSSAccessKey @""
#define OSSSecretKey @""
#define OSSBucketName @""
#define OSSUploadDic @""
#define OSSImageSuffix @""
#define OSSUploadFileSuffix @".jpg"
//
#define FileUploadFailureReasonErrorValue @"文件上传错误"
#define FileUploadFailureReasonErrorCode -10090
 
 
@interface AliOssUploadFiles()
@property (nonatomic, strong) dispatch_semaphore_t dsema;
//
 
@property (nonatomic,strong)id<OSSCredentialProvider> credential;
@property (nonatomic,strong)OSSClientConfiguration *config;
@property (nonatomic,strong)OSSClient *client;
@end
 
@implementation AliOssUploadFiles
 
+ (instancetype)manager
{
    static dispatch_once_t onceQueue;
    static AliOssUploadFiles *ossUploadFiles = nil;
    
    dispatch_once(&onceQueue, ^{
        ossUploadFiles = [[self alloc] init];
    });
    return ossUploadFiles;
}
 
- (instancetype)init
{
    self = [super init];
    if(self){
        _dsema = dispatch_semaphore_create(1);
        //
        [self configUploadParams];
    }
    return self;
}
 
//配置oss
- (void)configUploadParams
{
    _credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:OSSAccessKey secretKey:OSSSecretKey];
    //
    _config = [OSSClientConfiguration new];
    _config.maxRetryCount = 6;
    _config.timeoutIntervalForRequest = 30;
    _config.timeoutIntervalForResource = 24 * 60 * 60;
    //
    _client = [[OSSClient alloc] initWithEndpoint:OSSEndpoint credentialProvider:_credential clientConfiguration:_config];
}
 
//上传
//异步序列同传,
- (void)uploadImages:(NSArray *)images beginHandle:(void(^)(void))beginHandle complate:(void(^)(NSArray *callResult,NSError *error))complate
{
    NSLog(@"begin upload !");
    if(beginHandle != nil) beginHandle();
    NSInteger uploadCount = images.count;
    NSMutableArray *callBackResults = [NSMutableArray array];
    //
    for (NSInteger i = 0; i < uploadCount; i++) {
        dispatch_semaphore_wait(_dsema, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ //
            UIImage *uploadImage = images[i];
            //请求3
            OSSPutObjectRequest * put = [OSSPutObjectRequest new];
            put.bucketName = OSSBucketName;
            put.objectKey = [NSString stringWithFormat:@"%@%@%@",OSSUploadDic,self.srandString,OSSUploadFileSuffix];
            //如果大于5M则压缩
            put.uploadingData = [uploadImage compressToByte:ImageDataMaxByte];
            //UIImagePNGRepresentation(uploadImage);
            //
            AliOssUploadModel *uploadModel = [AliOssUploadModel new];
            uploadModel.width = CGImageGetWidth(uploadImage.CGImage);
            uploadModel.height = CGImageGetHeight(uploadImage.CGImage);
            uploadModel.sourcePath = [NSString stringWithFormat:@"%@/%@",OSSEndpoint,put.objectKey];
            uploadModel.smallPath = [NSString stringWithFormat:@"%@/%@%@",OSSEndpoint,put.objectKey,OSSImageSuffix];
//            put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//                // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
//            };
            OSSTask * putTask = [_client putObject:put];
            [putTask continueWithBlock:^id(OSSTask *task) {
                if (!task.error) {
                    OSSHeadObjectResult *headResult = task.result;
                    if(headResult.httpResponseCode == RequestSucceedCode){
                        [callBackResults addObject:uploadModel];
                        //界面刷新
                        if(callBackResults.count == uploadCount){
                            dispatch_async(dispatch_get_main_queue(), ^{
                                complate(callBackResults.copy,nil);
                            });
                        }
                    }
                } else {
                    NSLog(@"upload object failed, error: %@" , task.error);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        complate(nil,[self uploadError]);
                    });
                }
                return nil;
            }];
            //[putTask waitUntilFinished];
            dispatch_semaphore_signal(_dsema);
        });
    }
}
 
//处理图片,返回json字符串
- (NSString *)dealImageByUploadWithModels:(NSArray *)models;
{
 
    NSMutableArray *uploadImages = [NSMutableArray array];
    [models enumerateObjectsUsingBlock:^(AliOssUploadModel *uploadObj, NSUInteger idx, BOOL * _Nonnull stop) {
        [uploadImages addObject:uploadObj.uploadDictionaryByModel];
    }];
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:uploadImages options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    if(error == nil){
        return jsonString;
    }else{
        return nil;
    }
}
 
 
//随机字符串-唯一
- (NSString *)srandString
{
    /*
    static int kNumber = 15;
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
     */
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970] * 1000;
    long long theTime = [[NSNumber numberWithDouble:nowtime] longLongValue];
    NSString *curTime = [NSString stringWithFormat:@"%llu",theTime];
    //
    CFUUIDRef uuidRef =CFUUIDCreate(NULL);
    CFStringRef uuidStringRef =CFUUIDCreateString(NULL, uuidRef);
    CFRelease(uuidRef);
    NSString *uniqueId = (__bridge NSString *)uuidStringRef;
    [resultStr appendString:curTime];
    [resultStr appendString:uniqueId];
    return resultStr.copy;
}
 
//没网网络返回Error
- (NSError *)uploadError
{
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:FileUploadFailureReasonErrorValue, NSLocalizedFailureReasonErrorKey,nil];
    NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:FileUploadFailureReasonErrorCode userInfo:userInfo];
    return error;
}
 
/*
*  config
*/
 
/*
UserAgent    用户代理,指HTTP的User-Agent头。默认为”aliyun-sdk-java”
ProxyHost    代理服务器主机地址
ProxyPort    代理服务器端口
ProxyUsername    代理服务器验证的用户名
ProxyPassword    代理服务器验证的密码
ProxyDomain    访问NTLM验证的代理服务器的Windows域名
ProxyWorkstation    NTLM代理服务器的Windows工作站名称
MaxConnections    允许打开的最大HTTP连接数。默认为50
SocketTimeout    通过打开的连接传输数据的超时时间(单位:毫秒)。默认为50000毫秒
ConnectionTimeout    建立连接的超时时间(单位:毫秒)。默认为50000毫秒
MaxErrorRetry    可重试的请求失败后最大的重试次数。默认为3次
*/
 
 
 
@end
//
//  AliOssUploadModel.h
//  AliyunOssDemo
//
//  Created by Admin on 2018/10/17.
//  Copyright © 2018 huaibor. All rights reserved.
//
 
#import "PublicModel.h"
#import <UIKit/UIKit.h>
 
@interface AliOssUploadModel : PublicModel
@property (nonatomic,strong)NSString *sourcePath;
@property (nonatomic,strong)NSString *smallPath;
@property (nonatomic,assign)CGFloat width;
@property (nonatomic,assign)CGFloat height;
 
//model转换成字典
- (id)uploadDictionaryByModel;
 
@end
//
//  AliOssUploadModel.m
//  AliyunOssDemo
//
//  Created by Admin on 2018/10/17.
//  Copyright © 2018 huaibor. All rights reserved.
//
 
#import "AliOssUploadModel.h"
 
@implementation AliOssUploadModel
- (id)uploadDictionaryByModel
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    unsigned int count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    for(int i = 0; i < count; i++)
    {
        objc_property_t property = properties[i];
        NSString *nameString = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        if([self valueForKey:nameString] == nil){
            [params setValue:[self valueForKey:nameString] forKey:@""];
        }else{
            [params setValue:[self valueForKey:nameString] forKey:nameString];
        }
        //
    }
    free(properties);
    return params.copy;
}
@end

Leave a Reply

Required fields are marked *