文档:https://help.aliyun.com/document_detail/32058.html?spm=a2c4g.11186623.6.1129.dadb6affljcyzq
GitHub:https://github.com/aliyun/aliyun-oss-ios-sdk
iOS开发之上传图片至阿里云服务器:https://www.jianshu.com/p/a4496f7a99d0

先用pod导入阿里云

pod 'AliyunOSSiOS'

上传图片

- (void)ossPostImgsWithImgs:(NSArray *)imgs
{[OSSImageUploader asyncUploadImages:imgs complete:^(NSArray<NSString *> *names, UploadImageState state) {NSLog(@"names---%@", names);if (state == UploadImageFailed) {} else if (state == UploadImageSuccess) {}}];
}

本应该我们自己的服务端写个鉴权接口,然后对有权限上传的用户返回这些参数,然而这次服务端没搞定一些问题,所以让APP端将参数写死了。

///  阿里云上传配置本地写死
#define DE_accessKeyId @"LTAI4FiY7us4****"
#define DE_accessKeySecret @"WAPc9nzT3****"
#define DE_bucketName @"***oss"
#define DE_OSS_ENDPOINT @"https://oss-cn-hangzhou.aliyuncs.com/"
#define DE_OSS_MAIN_URL @"https://***oss.oss-cn-hangzhou.aliyuncs.com"
#define DE_GS_APP @"gs_app/2019"

OSSImageUploader
需要提一下OSSPutObjectRequest的objectKey并不是传全路径,应该穿bucketName往后拼的路径。

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <AliyunOSSiOS/OSSService.h>
#import "LYOSSVerifyModel.h"
#import "AliyunUploadShared.h"typedef NS_ENUM(NSInteger, UploadImageState) {UploadImageFailed   = 0,UploadImageSuccess  = 1
};@interface OSSImageUploader : NSObject+ (void)asyncUploadImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete;+ (void)syncUploadImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete;+ (void)asyncUploadImages:(NSArray<UIImage *> *)images complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete;+ (void)syncUploadImages:(NSArray<UIImage *> *)images complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete;//suffix - 文件类型后缀,如.mp4 - 阻塞式
+ (void)uploadFileData:(NSData *)uploadData withSuffix:(NSString *)suffix complete:(void(^)(NSString *fileName, UploadImageState state))complete;//IM ++ 上传文件(音视频等)//suffix - 文件类型后缀,如.mp4 - 非阻塞式 带进度(//注意因为是非阻塞,所以这里会直接返回complete, 实际判断是否上传完成需要用到progress中上传的与总的相等才行!)
+ (void)uploadNoWaitWithFileData:(NSData *)uploadData withSuffix:(NSString *)suffix withProgress:(OSSNetworkingUploadProgressBlock)progress complete:(void(^)(NSString *fileName, UploadImageState state))complete;//拍照购专用
+ (void)uploadPhotoSearchImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete;//获取阿里云图片信息
/*"FileSize": {"value": "21839"},"Format": {"value": "jpg"},"ImageHeight": {"value": "267"},"ImageWidth": {"value": "400"},"ResolutionUnit": {"value": "1"},"XResolution": {"value": "1/1"},"YResolution": {"value": "1/1"}}*/
+ (void)fetchOSSImageInfoWithImageUrl:(NSString *)imageUrl SucessBlock:(void(^)(NSDictionary *))successBlock FalierBlock:(void(^)(NSError *))falierBolck;@end
#import "OSSImageUploader.h"
#import <AliyunOSSiOS/AliyunOSSiOS.h>@implementation OSSImageUploader
//static NSString *const AccessKey = @"your-key";
//static NSString *const SecretKey = @"your-secret";
//static NSString *const BucketName = @"your-bucket";
//static NSString *const AliYunHost = @"http://oss-cn-shenzhen.aliyuncs.com/";//static NSString *kTempFolder = @"shop";+ (void)asyncUploadImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete
{[self uploadImages:@[image] isAsync:YES complete:complete];
}+ (void)syncUploadImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete
{[self uploadImages:@[image] isAsync:NO complete:complete];
}+ (void)asyncUploadImages:(NSArray<UIImage *> *)images complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{[self uploadImages:images isAsync:YES complete:complete];
}+ (void)syncUploadImages:(NSArray<UIImage *> *)images complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{[self uploadImages:images isAsync:NO complete:complete];
}+ (void)uploadImages:(NSArray<UIImage *> *)images isAsync:(BOOL)isAsync complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{//[self httpGetOSSUploadParmsWithSuccess:^{[self handleUploadImages:images isAsync:isAsync complete:complete];//} withFail:^(NSError *err) {//    [self handleUploadImages:images isAsync:isAsync complete:complete];//}];
}+ (void)handleUploadImages:(NSArray<UIImage *> *)images isAsync:(BOOL)isAsync complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{NSString *AccessKey = [LYOSSVerifyModel shareModel].accessKeyId;NSString *SecretKey = [LYOSSVerifyModel shareModel].accessKeySecret;NSString *BucketName = [LYOSSVerifyModel shareModel].bucketName;NSString *AliYunHost = [LYOSSVerifyModel shareModel].endpoint;//AliYunHost = [NSString stringWithFormat:@"http://%@",AliYunHost];NSDate *date =[NSDate date];//简书 FlyElephantNSDateFormatter *formatter = [[NSDateFormatter alloc]init];[formatter setDateFormat:@"yyyy"];NSString *currentYear=[formatter stringFromDate:date];[formatter setDateFormat:@"MM"];NSString *currentMonth=[formatter stringFromDate:date];[formatter setDateFormat:@"dd"];NSString *currentDay=[formatter stringFromDate:date];NSLog(@"currentDate = %@ ,year = %@ ,month=%@, day=%@",date,currentYear,currentMonth,currentDay);//NSString *kTempFolder = [NSString stringWithFormat:@"%@/%@/%@/%@",[LYOSSVerifyModel shareModel].rootPath,currentYear,currentMonth,currentDay];//NSString *kTempFolder = [NSString stringWithFormat:@"%@/%@",[LYOSSVerifyModel shareModel].rootPath,DE_GS_APP];/*OSSFederationToken *token = [[OSSFederationToken alloc]init];token.tAccessKey = AccessKey;token.tSecretKey = SecretKey;//token.tToken = [LYOSSVerifyModel shareModel].securityToken;//id <OSSCredentialProvider> credential1 = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey secretKey:SecretKey];id <OSSCredentialProvider> credential1 = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken *{return token;}];*/id <OSSCredentialProvider> credential1 = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:AccessKey secretKeyId:SecretKey securityToken:@""];//SecurityToken[AliyunUploadShared sharedUploadMethod].ossPicClient = [[OSSClient alloc] initWithEndpoint:AliYunHost credentialProvider:credential1];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 = BucketName;//NSString *imageName = [NSString stringWithFormat:@"%@/%@",kTempFolder,[[NSUUID UUID].UUIDString stringByAppendingString:@".jpeg"]];NSString *curTime = [GAPublicClass gs_getCurrentTimeStringToMilliSecond];NSString *imageName = [NSString stringWithFormat:@"%@/%@",DE_GS_APP,[curTime stringByAppendingString:@".jpg"]];put.objectKey = imageName;NSString *allImagePath = [NSString stringWithFormat:@"%@/%@",[LYOSSVerifyModel shareModel].rootPath,imageName];[callBackNames addObject:allImagePath];NSData *data = UIImageJPEGRepresentation(image, 0.3);NSData *handleData;if (data.length>Oss_Photo_Limit) {//限制handleData = [YSCUtils resetSizeOfImageData:image maxSize:Oss_Photo_Limit/1024];}if (handleData.length>0) {data = handleData;}put.uploadingData = data;put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {NSLog(@"put.uploadProgress  %lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);};OSSTask * putTask = [[AliyunUploadShared sharedUploadMethod].ossPicClient putObject:put];[putTask continueWithBlock:^id(OSSTask *task) {if (!task.error) {NSLog(@"1 upload object success!");} else {NSLog(@"1 upload object failed, error: %@" , task.error);}return nil;}];[putTask waitUntilFinished]; // 阻塞直到上传完成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);}}}
}+ (void)uploadFileData:(NSData *)uploadData withSuffix:(NSString *)suffix complete:(void(^)(NSString *fileName, UploadImageState state))complete
{[self httpGetOSSUploadParmsWithSuccess:^{[self hanldeUploadFileData:uploadData withSuffix:suffix complete:complete];} withFail:^(NSError *err) {[self hanldeUploadFileData:uploadData withSuffix:suffix complete:complete];}];}+ (void)hanldeUploadFileData:(NSData *)uploadData withSuffix:(NSString *)suffix complete:(void(^)(NSString *fileName, UploadImageState state))complete
{NSString *AccessKey = [LYOSSVerifyModel shareModel].accessKeyId;NSString *SecretKey = [LYOSSVerifyModel shareModel].accessKeySecret;NSString *BucketName = [LYOSSVerifyModel shareModel].bucketName;NSString *AliYunHost = [LYOSSVerifyModel shareModel].endpoint;//AliYunHost = [NSString stringWithFormat:@"http://%@",AliYunHost];NSDate *date =[NSDate date];//简书 FlyElephantNSDateFormatter *formatter = [[NSDateFormatter alloc]init];[formatter setDateFormat:@"yyyy"];NSString *currentYear=[formatter stringFromDate:date];[formatter setDateFormat:@"MM"];NSString *currentMonth=[formatter stringFromDate:date];[formatter setDateFormat:@"dd"];NSString *currentDay=[formatter stringFromDate:date];NSLog(@"currentDate = %@ ,year = %@ ,month=%@, day=%@",date,currentYear,currentMonth,currentDay);//    NSString *kTempFolder = [NSString stringWithFormat:@"%@/%@/%@",currentYear,currentMonth,currentDay];//NSString *kTempFolder = [NSString stringWithFormat:@"%@/%@/%@/%@",[LYOSSVerifyModel shareModel].rootPath,currentYear,currentMonth,currentDay];OSSFederationToken *token = [[OSSFederationToken alloc]init];token.tAccessKey = AccessKey;token.tSecretKey = SecretKey;token.tToken = [LYOSSVerifyModel shareModel].securityToken;//    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey                                                                                                            secretKey:SecretKey];id<OSSCredentialProvider> credential1 = [[OSSFederationCredentialProvider alloc]initWithFederationTokenGetter:^OSSFederationToken *{return token;}];[AliyunUploadShared sharedUploadMethod].ossFileClient = [[OSSClient alloc] initWithEndpoint:AliYunHost credentialProvider:credential1];//    [NSBlockOperation blockOperationWithBlock:^{//任务执行OSSPutObjectRequest *put = [OSSPutObjectRequest new];put.bucketName = BucketName;//NSString *fileName = [kTempFolder stringByAppendingPathComponent:[[NSUUID UUID].UUIDString stringByAppendingString:suffix]];NSString *curTime = [GAPublicClass gs_getCurrentTimeStringToMilliSecond];NSString *fileName = [NSString stringWithFormat:@"%@/%@",DE_GS_APP,[curTime stringByAppendingString:suffix]];put.objectKey = fileName;put.uploadingData = uploadData;NSString *allImagePath = [NSString stringWithFormat:@"%@/%@",[LYOSSVerifyModel shareModel].rootPath,fileName];OSSTask *putTask = [[AliyunUploadShared sharedUploadMethod].ossFileClient putObject:put];[putTask waitUntilFinished]; // 阻塞直到上传完成if (!putTask.error) {NSLog(@"upload file success!");if (complete) {complete(allImagePath, UploadImageSuccess);}} else {NSLog(@"upload file failed, error: %@" , putTask.error);}}+ (void)uploadNoWaitWithFileData:(NSData *)uploadData withSuffix:(NSString *)suffix withProgress:(OSSNetworkingUploadProgressBlock)progress complete:(void(^)(NSString *fileName, UploadImageState state))complete
{//[self httpGetOSSUploadParmsWithSuccess:^{[self handleUploadNoWaitWithFileData:uploadData withSuffix:suffix withProgress:progress complete:complete];//} withFail:^(NSError *err) {//    [self handleUploadNoWaitWithFileData:uploadData withSuffix:suffix withProgress:progress complete:complete];//}];
}+ (void)handleUploadNoWaitWithFileData:(NSData *)uploadData withSuffix:(NSString *)suffix withProgress:(OSSNetworkingUploadProgressBlock)progress complete:(void(^)(NSString *fileName, UploadImageState state))complete
{NSString *AccessKey = [LYOSSVerifyModel shareModel].accessKeyId;NSString *SecretKey = [LYOSSVerifyModel shareModel].accessKeySecret;NSString *BucketName = [LYOSSVerifyModel shareModel].bucketName;NSString *AliYunHost = [LYOSSVerifyModel shareModel].endpoint;//AliYunHost = [NSString stringWithFormat:@"http://%@",AliYunHost];NSDate *date =[NSDate date];//简书 FlyElephantNSDateFormatter *formatter = [[NSDateFormatter alloc]init];[formatter setDateFormat:@"yyyy"];NSString *currentYear=[formatter stringFromDate:date];[formatter setDateFormat:@"MM"];NSString *currentMonth=[formatter stringFromDate:date];[formatter setDateFormat:@"dd"];NSString *currentDay=[formatter stringFromDate:date];NSLog(@"currentDate = %@ ,year = %@ ,month=%@, day=%@",date,currentYear,currentMonth,currentDay);//    NSString *kTempFolder = [NSString stringWithFormat:@"%@/%@/%@",currentYear,currentMonth,currentDay];//NSString *kTempFolder = [NSString stringWithFormat:@"%@/%@/%@/%@",[LYOSSVerifyModel shareModel].rootPath,currentYear,currentMonth,currentDay];OSSFederationToken *token = [[OSSFederationToken alloc]init];token.tAccessKey = AccessKey;token.tSecretKey = SecretKey;token.tToken = [LYOSSVerifyModel shareModel].securityToken;//    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey                                                                                                            secretKey:SecretKey];id<OSSCredentialProvider> credential1 = [[OSSFederationCredentialProvider alloc]initWithFederationTokenGetter:^OSSFederationToken *{return token;}];[AliyunUploadShared sharedUploadMethod].ossFileClient = [[OSSClient alloc] initWithEndpoint:AliYunHost credentialProvider:credential1];//    [NSBlockOperation blockOperationWithBlock:^{//任务执行OSSPutObjectRequest *put = [OSSPutObjectRequest new];put.bucketName = BucketName;//https:/yxqoss.oss-cn-hangzhou.aliyuncs.com/2019/11/26/19D5FB49-D16C-4A53-BBC5-1733E5104E05.mp4//NSString *fileName = [kTempFolder stringByAppendingPathComponent:[[NSUUID UUID].UUIDString stringByAppendingString:suffix]];NSString *curTime = [GAPublicClass gs_getCurrentTimeStringToMilliSecond];NSString *fileName = [NSString stringWithFormat:@"%@/%@",DE_GS_APP,[curTime stringByAppendingString:suffix]];put.objectKey = fileName;put.uploadingData = uploadData;put.uploadProgress = progress;NSString *allImagePath = [NSString stringWithFormat:@"%@/%@",[LYOSSVerifyModel shareModel].rootPath,fileName];OSSTask *putTask = [[AliyunUploadShared sharedUploadMethod].ossFileClient putObject:put];if (!putTask.error) {NSLog(@"upload file success!");if (complete) {complete(allImagePath, UploadImageSuccess);}} else {NSLog(@"upload file failed, error: %@" , putTask.error);}
}+ (void)uploadPhotoSearchImage:(UIImage *)image complete:(void(^)(NSArray<NSString *> *names,UploadImageState state))complete
{[self uploadPhotoSearchImages:@[image] isAsync:YES complete:complete];
}+ (void)uploadPhotoSearchImages:(NSArray<UIImage *> *)images isAsync:(BOOL)isAsync complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{[self httpGetOSSUploadParmsWithSuccess:^{[self hanldeUploadPhotoSearchImages:images isAsync:isAsync complete:complete];} withFail:^(NSError *err) {[self hanldeUploadPhotoSearchImages:images isAsync:isAsync complete:complete];}];}+ (void)hanldeUploadPhotoSearchImages:(NSArray<UIImage *> *)images isAsync:(BOOL)isAsync complete:(void(^)(NSArray<NSString *> *names, UploadImageState state))complete
{NSString *AccessKey = [LYOSSVerifyModel shareModel].accessKeyId;NSString *SecretKey = [LYOSSVerifyModel shareModel].accessKeySecret;NSString *BucketName = [LYOSSVerifyModel shareModel].bucketName;NSString *AliYunHost = [LYOSSVerifyModel shareModel].endpoint;//AliYunHost = [NSString stringWithFormat:@"http://%@",AliYunHost];NSDate *date =[NSDate date];//简书 FlyElephantNSDateFormatter *formatter = [[NSDateFormatter alloc]init];[formatter setDateFormat:@"yyyy"];NSString *currentYear=[formatter stringFromDate:date];[formatter setDateFormat:@"MM"];NSString *currentMonth=[formatter stringFromDate:date];[formatter setDateFormat:@"dd"];NSString *currentDay=[formatter stringFromDate:date];NSLog(@"currentDate = %@ ,year = %@ ,month=%@, day=%@",date,currentYear,currentMonth,currentDay);//    NSString *kTempFolder = [NSString stringWithFormat:@"%@/%@/%@",currentYear,currentMonth,currentDay];NSString *kTempFolder;NSString *subPath = @"";Account *accountModel = [AccountTool account];if ([YSCUtils theStringIsValid:accountModel.userId]) {subPath = [NSString stringWithFormat:@"search/%@",accountModel.userId];kTempFolder = [NSString stringWithFormat:@"%@/%@",[LYOSSVerifyModel shareModel].rootPath,subPath];}else {subPath = @"search";kTempFolder = [NSString stringWithFormat:@"%@/%@",[LYOSSVerifyModel shareModel].rootPath,subPath];}OSSFederationToken *token = [[OSSFederationToken alloc]init];token.tAccessKey = AccessKey;token.tSecretKey = SecretKey;token.tToken = [LYOSSVerifyModel shareModel].securityToken;//    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey                                                                                                            secretKey:SecretKey];id<OSSCredentialProvider> credential1 = [[OSSFederationCredentialProvider alloc]initWithFederationTokenGetter:^OSSFederationToken *{return token;}];[AliyunUploadShared sharedUploadMethod].ossPicClient = [[OSSClient alloc] initWithEndpoint:AliYunHost credentialProvider:credential1];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 = BucketName;NSString *curTime = [GAPublicClass gs_getCurrentTimeStringToMilliSecond];NSString *imageName = [NSString stringWithFormat:@"%@/%@",DE_GS_APP,[curTime stringByAppendingString:@".jpg"]];put.objectKey = imageName;NSString *allImagePath = [NSString stringWithFormat:@"%@/%@",[LYOSSVerifyModel shareModel].rootPath,imageName];[callBackNames addObject:allImagePath];NSData *data = UIImageJPEGRepresentation(image, 0.3);NSData *handleData;if (data.length>Oss_Photo_Limit) {//限制handleData = [YSCUtils resetSizeOfImageData:image maxSize:Oss_Photo_Limit/1024];}if (handleData.length>0) {data = handleData;}put.uploadingData = data;OSSTask * putTask = [[AliyunUploadShared sharedUploadMethod].ossPicClient 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);}}}
}//LYZB +oss上传图片鉴权
+ (void)httpGetOSSUploadParmsWithSuccess:(void(^)(void))successHandle withFail:(void(^)(NSError *))failHandle
{Account *accountModel = [AccountTool account];// if ([YSCUtils theStringIsValid:[YSCApp sharedInstance].lbsToken]) {NSString *url = PostOSSMakeImgURL;AFHTTPSessionManager *requestManager = [AFHTTPSessionManager manager];requestManager.requestSerializer = [AFHTTPRequestSerializer serializer];// token[requestManager.requestSerializer setValue:accountModel.token?:@"" forHTTPHeaderField:@"token"];requestManager.responseSerializer = [AFHTTPResponseSerializer serializer];[requestManager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];LYOSSVerifyModel *model = [[LYOSSVerifyModel alloc] initWithDictionary:dic error:nil];[LYOSSVerifyModel shareModel].accessKeyId = model.accessKeyId;if ([YSCUtils theStringIsValid:model.accessKeyId]) {[[NSUserDefaults standardUserDefaults] setObject:model.accessKeyId forKey:@"OssAccessKeyId"];}[LYOSSVerifyModel shareModel].accessKeySecret = model.accessKeySecret;if ([YSCUtils theStringIsValid:model.accessKeySecret]) {[[NSUserDefaults standardUserDefaults] setObject:model.accessKeySecret forKey:@"OssAccessKeySecret"];}[LYOSSVerifyModel shareModel].securityToken = model.securityToken;if ([YSCUtils theStringIsValid:model.securityToken]) {[[NSUserDefaults standardUserDefaults] setObject:model.securityToken forKey:@"OssSecurityToken"];}[LYOSSVerifyModel shareModel].bucketName = model.bucketName;if ([YSCUtils theStringIsValid:model.bucketName]) {[[NSUserDefaults standardUserDefaults] setObject:model.bucketName forKey:@"OssBucketName"];}[LYOSSVerifyModel shareModel].endpoint = model.endpoint;if ([YSCUtils theStringIsValid:model.endpoint]) {[[NSUserDefaults standardUserDefaults] setObject:model.endpoint forKey:@"OssEndpoint"];}[LYOSSVerifyModel shareModel].imagePath = model.imagePath;if ([YSCUtils theStringIsValid:model.imagePath]) {[[NSUserDefaults standardUserDefaults] setObject:model.imagePath forKey:@"OssImagePath"];}[LYOSSVerifyModel shareModel].rootPath = model.rootPath;if ([YSCUtils theStringIsValid:model.rootPath]) {[[NSUserDefaults standardUserDefaults] setObject:model.rootPath forKey:@"OssRootPath"];}if (successHandle) {successHandle();}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);if (failHandle) {failHandle(error);}}];//    }
}+ (void)fetchOSSImageInfoWithImageUrl:(NSString *)imageUrl SucessBlock:(void(^)(NSDictionary *))successBlock FalierBlock:(void(^)(NSError *))falierBolck
{NSString *imgInfoUrl = [YSCUtils imgUrlGetUrlStr:imageUrl];if ([YSCUtils theStringIsValid:imgInfoUrl] && [imgInfoUrl containsString:@"?x-oss-process"]) {imgInfoUrl = [imgInfoUrl componentsSeparatedByString:@"?"].firstObject;}imgInfoUrl = [imgInfoUrl stringByAppendingString:@"?x-oss-process=image/info"];AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];manager.requestSerializer = [AFHTTPRequestSerializer serializer];manager.responseSerializer = [AFHTTPResponseSerializer serializer];[manager GET:imgInfoUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {if ([responseObject isKindOfClass:[NSData class]]) {NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];if (dic && successBlock) {successBlock(dic);}}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {if (error && falierBolck) {falierBolck(error);}}];
}@end

AliyunUploadShared

#import <Foundation/Foundation.h>@interface AliyunUploadShared : NSObject/// 防止oss client被提前释放导致有时上传失败!
@property (nonatomic, strong) OSSClient *ossPicClient;  // 图片上传专用
@property (nonatomic, strong) OSSClient *ossFileClient; // 其它诸如音视频专用+ (AliyunUploadShared *)sharedUploadMethod;@end
#import "AliyunUploadShared.h"static AliyunUploadShared * sharedUpload = nil;@implementation AliyunUploadShared+ (AliyunUploadShared *)sharedUploadMethod {@synchronized (self){if (!sharedUpload) {sharedUpload = [[AliyunUploadShared alloc] init];}return sharedUpload;}return sharedUpload;
}@end

LYOSSVerifyModel

@interface LYOSSVerifyModel : JSONModel@property (nonatomic, strong) NSString *accessKeyId;
@property (nonatomic, strong) NSString *accessKeySecret;
@property (nonatomic, strong) NSString *securityToken;
@property (nonatomic, strong) NSString *bucketName;
@property (nonatomic, strong) NSString *endpoint;
@property (nonatomic, strong) NSString *imagePath;
@property (nonatomic, strong) NSString *rootPath;+ (LYOSSVerifyModel *)shareModel;@end
#import "LYOSSVerifyModel.h"@implementation LYOSSVerifyModel+ (BOOL)propertyIsOptional:(NSString *)propertyName {return YES;
}+ (LYOSSVerifyModel *)shareModel
{static LYOSSVerifyModel *ossModel = nil;static dispatch_once_t predicate;dispatch_once(&predicate, ^{ossModel = [[self alloc] init];});return ossModel;
}- (NSString *)accessKeyId
{if (![YSCUtils theStringIsValid:_accessKeyId]) {_accessKeyId = [[NSUserDefaults standardUserDefaults] objectForKey:@"OssAccessKeyId"];}if (![_accessKeyId isKindOfClass:[NSString class]]) {_accessKeyId = DE_accessKeyId;}return _accessKeyId;
}- (NSString *)accessKeySecret
{if (![YSCUtils theStringIsValid:_accessKeySecret]) {_accessKeySecret = [[NSUserDefaults standardUserDefaults] objectForKey:@"OssAccessKeySecret"];}if (![_accessKeySecret isKindOfClass:[NSString class]]) {_accessKeySecret = DE_accessKeySecret;}return _accessKeySecret;
}- (NSString *)securityToken
{if (![YSCUtils theStringIsValid:_securityToken]) {_securityToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"OssSecurityToken"];}return _securityToken;
}- (NSString *)bucketName
{if (![YSCUtils theStringIsValid:_bucketName]) {_bucketName = [[NSUserDefaults standardUserDefaults] objectForKey:@"OssBucketName"];}if (![_bucketName isKindOfClass:[NSString class]]) {_bucketName = DE_bucketName;}return _bucketName;
}- (NSString *)endpoint
{if (![YSCUtils theStringIsValid:_endpoint]) {_endpoint = [[NSUserDefaults standardUserDefaults] objectForKey:@"OssEndpoint"];}if (![_endpoint isKindOfClass:[NSString class]]) {_endpoint = DE_OSS_ENDPOINT;}return _endpoint;
}- (NSString *)imagePath
{if (![YSCUtils theStringIsValid:_imagePath]) {_imagePath = [[NSUserDefaults standardUserDefaults] objectForKey:@"OssImagePath"];}return _imagePath;
}- (NSString *)rootPath
{if (![YSCUtils theStringIsValid:_rootPath]) {_rootPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"OssRootPath"];}if (![_rootPath isKindOfClass:[NSString class]]) {_rootPath = DE_OSS_MAIN_URL;}return _rootPath;
}@end

[iOS]上传图片和音视频到阿里云相关推荐

  1. 【Android视频 之 阿里云视频播放器 一】

    说到视频,现在短视频,小视频真是火的不行,抖音,快手,更是很多人手机上必会安装的一款app.那如何开发一款类似于抖音,集视频播放,直播,点播,拍摄,滤镜于一体的app呢,想想那都是相当的复杂.说到这里 ...

  2. 音视频技术在云会议场景的拓展和未来

    音视频技术不断发展,云会议场景在人们生活中也越来越常见.那么如何将云会议场景中的音视频技术不断提升改善?本次分享会我们邀请到了来自腾讯会议的商世东先生,他将与我们分享云视频技术在腾讯会议里面的一些领域 ...

  3. 用更少的钱看更清晰的视频——详谈阿里云窄带高清

    窄带高清代表的是一种成本与体验相调和的视频服务理念.体验方面,观众在观看视频时会受到片源清晰度.分辨率.码率.帧率.编码算法.播放策略等影响,所谓的窄带高清也是希望从这些角度提高观众观看体验:影响成本 ...

  4. 【Android视频 之 阿里云视频播放器 二】

    说明一下:写文章时,我用的最新sdk版本是 4.7.0 哦,这里也只贴出关键代码,更多详细代码在文章末尾有地址链接的. [Android视频 之 阿里云视频播放器 一] 1 视频试看功能的实现 效果图 ...

  5. 批量上传视频到阿里云

    批量上传视频到阿里云 这段时间项目里有一个上传视频到阿里云的功能是我来负责写的,之前一直没有写过这种功能,感觉很难的亚子,但是后来仔细研究了一遍发现也没想象中那么难,最后经过不懈的努力也算是搞出来了哈 ...

  6. 基于iOS的网络音视频实时传输系统(一)- 前言

    演示图 (由于GIF大小限制,图做得比较模糊和不太流畅,实际的效果是不错的,可以自己下下来实际跑一下) client端: server端: 下载 GitHub: client 端:https://gi ...

  7. 基于iOS的网络音视频实时传输系统(二)- 捕获音视频数据

    下载 GitHub: client 端:https://github.com/AmoAmoAmo/Smart_Device_Client server端:https://github.com/AmoA ...

  8. 上传视频到阿里云服务器

    ######上传视频到阿里云服务器工具类 1.maven坐标 <dependency><groupId>com.aliyun</groupId><artifa ...

  9. Springboot上传视频到阿里云(视频点播)和aliyun-java-sdk-vod依赖报红问题

    一.pom.xm中导入依赖 <dependency><groupId>com.aliyun</groupId><artifactId>aliyun-ja ...

最新文章

  1. 查看linux系统的平均负载
  2. 计算机组成原理课设总线,计算机组成原理课程设计(全).doc
  3. 【ES6-11(2015-2020)】特性总览与开发环境准备
  4. Nginx解决前端调用后端接口跨域问题
  5. C++ 函数重载 参数默认值可以不写
  6. 神经网络- 吴恩达Andrew Ng CNN卷积神经网络 论文等资料汇总
  7. 锐起无盘XP安装与配置图文(一)
  8. (七) 三维点云课程---ICP(Point-to-Point)
  9. ym——Android从零开始(27)(山寨版微信-下)(新)
  10. 360Hbase二级索引
  11. python3实现bicubic(双三次插值)重建四倍放大图像
  12. 使用wxml2canvas将微信小程序页面转为图片
  13. 1050Ti解决csgo打不开、电脑无缘无故蓝屏的终极方法
  14. uni-app微信小程序跳转公众号;微信小程序打开公众号;微信小程序识别二维码添加好友;微信小程序通过公众号添加好友;小程序里识别企业微信二维码点击联系人名片无反应?
  15. 启用Win10家庭版的远程桌面服务端
  16. 求n边形周长的k等分点坐标(今日头条)
  17. Mybatis源码学习-MapperMethod
  18. WinKawaks模拟器画面有条纹
  19. gis计算频数_频数 (分析)
  20. 双向长短期记忆网络模型_基于深度双向长短期记忆网络的空气质量预测方法与流程...

热门文章

  1. ITK——5. 利用ITK自身的多线程加速filter计算
  2. 最全的android各国语言对照表-转载
  3. 【转载】爸妈,求你们不要这么懂事
  4. java中protected权限与默认权限的区别
  5. Axure 8.1.0.3377 注册码激活
  6. mac使用git管理Github以及生成 SSH 公钥
  7. CI服务器-Hudson持续集成服务器的安装配置与使用
  8. Dashboard是什么意思 Dashboard怎么用?
  9. 牛客网做题笔记--洗牌问题
  10. css选择器优先级及权重计算