美文网首页食色男女
iOS开发之集成OSS上传文件获取URL

iOS开发之集成OSS上传文件获取URL

作者: chasitu | 来源:发表于2020-09-04 15:07 被阅读0次

最近公司APP用户变多需要文件上传方面要优化,领导最终决定直接上传阿里云OSS,遗弃我们后台中转处理的方案了,集成中也遇到了比较难受的问题,记录一下

开始集成

第一步:导入

我是使用pod导入的库

pod 'AliyunOSSiOS'
第二步:声明全局变量

工具类我一般不建议声明全局变量的这种方式,建议使用类方法的,可是这个不行,想了一下单例也不适合

@interface SHOSSObjectRequestTool ()
@property (nonatomic , strong) OSSClient *client;
@end
第三步:实现方法

简单解释一下(阿里云文档上有的参数我就不多解释了)

  • OSSPutObjectRequest是上传任务类
  • OSSClient是执行任务类(切记不能设置成局部变量)
- (void)upLoadWithDictionay:(NSDictionary *)param FilePath:(NSString *)filePath Success:(void (^)(NSString *,NSString *))success Failure:(void (^)(NSError *))failure Progress:(void(^)(float progress))progress
{
    NSLog(@"---相关参数----%@\n%@",param,filePath);
    OSSPutObjectRequest *put = [OSSPutObjectRequest new];
    put.bucketName = param[@"BucketName"];
    NSString *objectKey = [NSString stringWithFormat:@"%@/%@",[self getNowTimeTimestamp],filePath.lastPathComponent];
    put.objectKey = objectKey;
    put.uploadingFileURL = [NSURL fileURLWithPath:filePath];
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSString *totalUnitCount = [NSString stringWithFormat:@"%lld",totalBytesSent];
        NSString *totalUnit = [NSString stringWithFormat:@"%lld",totalBytesExpectedToSend];
        float slider = totalUnitCount.floatValue/totalUnit.floatValue;
        !progress ? : progress(slider);
    };
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:param[@"AccessKeyId"] secretKeyId:param[@"AccessKeySecret"] securityToken:param[@"SecurityToken"]];
#pragma clang diagnostic pop
    _client = [[OSSClient alloc] initWithEndpoint:param[@"EndPoint"] credentialProvider:credential];
    OSSTask *putTask = [_client putObject:put];
    __weak typeof(self) weakSelf = self;
    [putTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
        if (!task.error) {
//这一步是获取文件url的关键
            task = [weakSelf.client presignPublicURLWithBucketName:put.bucketName withObjectKey:objectKey];
//上一步调用之后task.result这个就是文件地址
            NSLog(@"--OSS成功了---%@",task.result);
            !success ? : success(put.objectKey,task.result);
        }else{
            NSLog(@"--OSS失败了---%@",task.error);
            !failure ? : failure(task.error);
        }
        return nil;
    }];
}

代码里面使用了一个时间戳的方法也分享给大家吧

- (NSString *)getNowTimeTimestamp{//毫秒级
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    return timeSp;
}

上面的代码大家可以直接粘贴过去就可以使用的,收工

相关文章

网友评论

    本文标题:iOS开发之集成OSS上传文件获取URL

    本文链接:https://www.haomeiwen.com/subject/hlizsktx.html