[iOS]上传图片和音视频到阿里云
文档:https://help.aliyun.com/document_detail/32058.html?spm=a2c4g.11186623.6.1129.dadb6affljcyzqGitHub:https://github.com/aliyun/aliyun-oss-ios-sdkiOS开发之上传图片至阿里云服务器:https://www.jianshu.com/p/a4496f7a9..
·
文档: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];//简书 FlyElephant
NSDateFormatter *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];//简书 FlyElephant
NSDateFormatter *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];//简书 FlyElephant
NSDateFormatter *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];//简书 FlyElephant
NSDateFormatter *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
更多推荐
所有评论(0)