最近项目集成阿里云存储oss,把其中踩过的坑记录一下;由于官方sak集成文档不够详细,特意写出来给正在集成的兄die查阅一下是否遇到同样问题,以下是实现步骤:
1.集成sdk:pod'AliyunOSSiOS';
注意:兼容IPv6-Only网络,需要导入以下库(libresolv.tbdCoreTelephony.frameworkSystemConfiguration.framework)
2.封装工具类
.h文件
//阿里云图片上传
+(void)upLoadImage:(UIImage*)image success:(void(^)(NSString*_Nonnullurl))success failure:(void(^)(NSString*_NonnullerrorString))failure;
+ (NSString*) getGMTDate;
.m文件
//阿里云图片上传
+(void)upLoadImage:(UIImage*)image success:(void(^)(NSString*_Nonnull url))success failure:(void(^)(NSString*_Nonnull errorString))failure{
// 将image转成Data
NSData *data = UIImagePNGRepresentation(image);
NSString *endpoint = @"endpoint";//去阿里云控制台查看
//AccessKeyId --- secretKeyId 去阿里云控制台查看 securityToken填空字符串就好了
id
OSSClient*client = [[OSSClient alloc]initWithEndpoint:endpoint credentialProvider:credential];
OSSPutObjectRequest * put = [OSSPutObjectRequest new];
put.bucketName = @"bucketName";//去阿里云控制台查看
//根据用户ID和时间戳来生成一段字符串 来保证图片的唯一性
NSString*timestr = [NSStringstringWithFormat:@"%@%@",UserInfo.userid,[self getGMTDate]];
// 其中test/是bucket下的子文件夹路径,可以根据路径上传到指定文件夹
put.objectKey= [NSStringstringWithFormat:@"test/%@.png",timestr];
put.uploadingData= data;// 直接上传NSData
put.uploadProgress= ^(int64_tbytesSent,int64_ttotalByteSent,int64_ttotalBytesExpectedToSend) {
NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
OSSTask* putTask = [client putObject:put];
[putTask continueWithBlock:^id(OSSTask*task) {
//这一步很关键 缺少这一步运行会出错 里面的参数和上面一样
task = [client presignPublicURLWithBucketName:@"bucketName"
withObjectKey:[NSString stringWithFormat:@"test/%@.png",timestr]];
NSLog(@"objectkey ========%@",put.objectKey);
if(!task.error) {
//task.result就是返回的外网访问路径,即图片URL
success(task.result);
}else{
NSLog(@"upload object failed, error: %@" , task.error);
failure(task.error.localizedDescription);
}
return nil;
}];
}
+ (NSString*) getGMTDate{
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a=[dat timeIntervalSince1970];
NSString*timeString = [NSStringstringWithFormat:@"%0.f", a];//转为字符型
returntimeString;
}
3.程序执行上传操作,去阿里控制台查看图片是否上传成功
注意:很多兄die会遇到返回的url链接打不开的情况,通常是bucket的读写权限设置的问题,只要在阿里控制台将读写属性改为公共读就OK了