前言:
项目要把图床从七牛迁到阿里云。因此,就要使用阿里云的图床上传。我去看了阿里云开发文档给出的示例代码和git。然而,我觉得他们给出的代码不好用,demo写得也不那么弱智易懂,shit!
上传图片有两种方式,一种是使用三个key,可以参考这位iOS玩家的文章:
iOS 阿里云图片上传
还有一个是使用 “initWithAuthServerUrl” 这种方式。我这里用的就是这个方式。
我不想再看见阿里云了。
自己新建一个类: AliyunOSSUpload,继承自 NSObject,
然后在 AliyunOSSUpload.m 里面,写一个内部类:ISAuthCredentialProvider ,继承自阿里云的 OSSFederationCredentialProvider。
上代码
.h
#import <Foundation/Foundation.h>
#import <AliyunOSSiOS/AliyunOSSiOS.h>
NS_ASSUME_NONNULL_BEGIN
/// 上传到阿里云的 EndPoint
static NSString * _Nonnull const OSS_ENDPOINT = @"这个地址,找自己后台要";
/// 上传到阿里云的 BucketName
static NSString * _Nonnull const BucketName = @"这个,找自己后台要";
@interface AliyunOSSUpload : NSObject
+(AliyunOSSUpload *)aliyunInit;
/// 上传图片
/// @param imgArray 放入需要上传的图片
/// @param success 上传成功,返回自己拼接的图片名字
- (void)uploadImage:(NSArray <UIImage *>*)imgArray success:(void (^)(NSArray <NSString *> * nameArray))success;
@end
NS_ASSUME_NONNULL_END
.m
#import "AliyunOSSUpload.h"
/// 在使用 initWithAuthServerUrl 这种方式初始化阿里云的时候, 传入的 url 是自己家的url.
/// 但是! 一般自己家的url在做请求的时候, 往往在请求头(HTTPHeaderField)里面需要加入参数, 比如自己家用户登录的时候拿到的 token, 需要在后续所有请求头里加上这个token,
/// 再就是加入一些其他请求头参数, 比如, 哪个端,iOS,Android, 版本号之类.
/// 所以,我们 新建一个类, 继承自 OSSFederationCredentialProvider, 然后把 阿 里 云 代 码 直 接 拷 贝 过 来 改写.
@interface ISAuthCredentialProvider : OSSFederationCredentialProvider
@property (nonatomic, copy) NSString * authServerUrl;
@property (nonatomic, copy) NSData * (^responseDecoder)(NSData *);
- (instancetype)initWithAuthServerUrl:(NSString *)authServerUrl;
- (instancetype)initWithAuthServerUrl:(NSString *)authServerUrl responseDecoder:(nullable OSSResponseDecoderBlock)decoder;
@end
@implementation ISAuthCredentialProvider
- (instancetype)initWithAuthServerUrl:(NSString *)authServerUrl {
return [self initWithAuthServerUrl:authServerUrl responseDecoder:nil];
}
- (instancetype)initWithAuthServerUrl:(NSString *)authServerUrl responseDecoder:(nullable OSSResponseDecoderBlock)decoder {
self = [super initWithFederationTokenGetter:^OSSFederationToken * {
NSURL * url = [NSURL URLWithString:authServerUrl];
//把原来的 NSURLRequest 改成 NSMutableURLRequest, 这样可以加入新的请求头参数, 就加入这么点东西,其余的代码不改.
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"用户登录时候拿到的 token" forHTTPHeaderField:@"你们定义好的 token key"];
[request setValue:@"其他需要放进来的参数" forHTTPHeaderField:@"其他的参数 key"];
OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
NSURLSession * session = [NSURLSession sharedSession];
NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
[tcs setError:error];
return;
}
[tcs setResult:data];
}];
[sessionTask resume];
[tcs.task waitUntilFinished];
if (tcs.task.error) {
return nil;
} else {
NSData* data = tcs.task.result;
if(decoder){
data = decoder(data);
}
NSDictionary * object = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:nil];
int statusCode = [[object objectForKey:@"StatusCode"] intValue];
if (statusCode == 200) {
OSSFederationToken * token = [OSSFederationToken new];
// All the entries below are mandatory.
token.tAccessKey = [object objectForKey:@"AccessKeyId"];
token.tSecretKey = [object objectForKey:@"AccessKeySecret"];
token.tToken = [object objectForKey:@"SecurityToken"];
token.expirationTimeInGMTFormat = [object objectForKey:@"Expiration"];
OSSLogDebug(@"token: %@ %@ %@ %@", token.tAccessKey, token.tSecretKey, token.tToken, [object objectForKey:@"Expiration"]);
return token;
}else{
return nil;
}
}
}];
if(self){
self.authServerUrl = authServerUrl;
}
return self;
}
@end
OSSClient * client;
@implementation AliyunOSSUpload
static AliyunOSSUpload *_uploader;
+ (AliyunOSSUpload *)aliyunInit {
@synchronized(self) {
if (_uploader == nil) {
[OSSLog enableLog];
_uploader = [[AliyunOSSUpload alloc] init];
NSString *OSS_STSTOKEN_URL = @"这个 AuthServerUrl 找后台要";
id<OSSCredentialProvider> credentialProvider = [[ISAuthCredentialProvider alloc] initWithAuthServerUrl:OSS_STSTOKEN_URL];
OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
client = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:credentialProvider clientConfiguration:cfg];
}
}
return _uploader;
}
- (void)uploadImage:(NSArray <UIImage *>*)imgArray success:(void (^)(NSArray <NSString *> * nameArray))success {
dispatch_group_t group = dispatch_group_create();
//名字数组
NSMutableArray *nameArray = [NSMutableArray array];
for (int i = 0; i < imgArray.count; i ++) {
dispatch_group_enter(group); //进入组
NSString *s = [NSString stringWithFormat:@"photot_name_%d_%@.jpg",i,[NSUUID UUID].UUIDString];
OSSPutObjectRequest * put = [OSSPutObjectRequest new];
put.contentType = @"image/jpeg";
put.bucketName = BucketName;
put.objectKey = s;
put.uploadingData = UIImageJPEGRepresentation(imgArray[i], 1);
put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
OSSTask * putTask = [client putObject:put];
[putTask continueWithBlock:^id(OSSTask *task) {
if (!task.error) {
NSLog(@"图片上传成功!");
[nameArray addObject:s];
} else{
NSLog(@"图片上传失败: %@" , task.error);
}
dispatch_group_leave(group); //不论是成功或者失败,都离开组
return nil;
}];
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
success(nameArray);
NSLog(@"任务全部完成,当前线程 %@",[NSThread currentThread]); //收到任务全部完成的通知
});
}
@end
调用
[[AliyunOSSUpload aliyunInit] uploadImage:arrayNewPhoto success:^(NSArray<NSString *> * _Nonnull nameArray) {'
NSLog(@"%@", nameArray);
}];
网友评论