阿里云 断点续传(仅供参考)

OSS 阿里云 断点续传

//初始化OSS token

#pragma mark  -- 阿里云客户端 OSS 客户端sts 临时token

- (void)initOSSClient{

uc_authcode *ucCode = [[uc_authcode alloc]init];

NSString *encryptionString = [ucCode getEncryptionString];

NSDictionary *callParamsDic = [[NSDictionary alloc]initWithObjectsAndKeys:@"ossStsbyram",@"action",nil];

[AFNetWorkTool post:NEW_USERADDRESS path:USERPATH encryptionString:encryptionString params:callParamsDic success:^(id responseObj) {

GJLog(@"%@",responseObj);

int nStautus = [[responseObj objectForKey:@"status"] intValue];

NSString *contentStr = [responseObj objectForKey:@"content"];

if (nStautus == 1) {

NSDictionary *dic = [responseObj objectForKey:@"data"];

_accessKeyId = [dic objectForKey:@"AccessKeyId"];

_accessKeySecret =[dic objectForKey:@"AccessKeySecret"];

_expiration =[dic objectForKey:@"Expiration"];

_securityToken = [dic objectForKey:@"SecurityToken"];

} else{

[self.view makeToast:contentStr];

}

} failure:^(NSError *error) {

}];

}

//设置阿里云token

[self xys_ALIYUNSend];

#pragma mark  -- 设置阿里云token

- (void)xys_ALIYUNSend{

id credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {

OSSFederationToken * token = [OSSFederationToken new];

token.tAccessKey = _accessKeyId;

token.tSecretKey = _accessKeySecret;

token.tToken = _securityToken;

token.expirationTimeInGMTFormat = _expiration;

return token;

}];

OSSClientConfiguration * conf = [OSSClientConfiguration new];

conf.maxRetryCount = 2;

conf.timeoutIntervalForRequest = 30;

conf.timeoutIntervalForResource = 24 * 60 * 60;

client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];

}

//阿里云断点续传

[self xys_ALIYUNsendVideo];

#pragma mark  -- 断点续传

- (void)xys_ALIYUNsendVideo{

[self.view addSubview:self.videoHud];

[SingleManager shareManager].isResumableUpload = YES;

//阿里云视频上传的方法

__block NSString * recordKey;

NSURL *filePath = [SingleManager shareManager].videoURL;

NSString * bucketName = @"xys-app-file";

NSString * objectKey;

if (_uploadid == nil) {

objectKey = [self getObjectKey];

_uploadid = objectKey;

} else{

objectKey = _uploadid;

}

[[[[[[OSSTask taskWithResult:nil] continueWithBlock:^id(OSSTask *task) {

// 为该文件构造一个唯一的记录键

//        NSURL * fileURL = [NSURL fileURLWithPath:filePath];

NSDate * lastModified;

NSError * error;

[filePath getResourceValue:&lastModified forKey:NSURLContentModificationDateKey error:&error];

if (error) {

return [OSSTask taskWithError:error];

}

recordKey = [NSString stringWithFormat:@"%@-%@-%@-%@", bucketName, objectKey, [OSSUtil getRelativePath:[filePath absoluteString]], lastModified];

NSLog(@"recordKeyrecordKeyrecordKey-------%@",recordKey);

// 通过记录键查看本地是否保存有未完成的UploadId

NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

return [OSSTask taskWithResult:[userDefault objectForKey:recordKey]];

}]

continueWithSuccessBlock:^id(OSSTask *task) {

if (!task.result) {

// 如果本地尚无记录,调用初始化UploadId接口获取

OSSInitMultipartUploadRequest * initMultipart = [OSSInitMultipartUploadRequest new];

initMultipart.bucketName = bucketName;

initMultipart.objectKey = objectKey;

initMultipart.contentType = @"application/octet-stream";

return [client multipartUploadInit:initMultipart];

}

OSSLogVerbose(@"An resumable task for uploadid: %@", task.result);

return task;

}]

continueWithSuccessBlock:^id(OSSTask *task) {

NSString * uploadId = nil;

if (task.error) {

return task;

}

if ([task.result isKindOfClass:[OSSInitMultipartUploadResult class]]) {

uploadId = ((OSSInitMultipartUploadResult *)task.result).uploadId;

} else {

uploadId = task.result;

}

if (!uploadId) {

return [OSSTask taskWithError:[NSError errorWithDomain:OSSClientErrorDomain

code:OSSClientErrorCodeNilUploadid

userInfo:@{OSSErrorMessageTOKEN: @"Can't get an upload id"}]];

}

// 将“记录键:UploadId”持久化到本地存储

NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

[userDefault setObject:uploadId forKey:recordKey];

[userDefault synchronize];

return [OSSTask taskWithResult:uploadId];

}]

continueWithSuccessBlock:^id(OSSTask *task) {

// 持有UploadId上传文件

OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];

resumableUpload.bucketName = bucketName;

resumableUpload.objectKey = objectKey;

resumableUpload.uploadId = task.result;

resumableUpload.uploadingFileURL = filePath;

resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {

float number = (float)totalBytesSent/(float)totalBytesExpectedToSend;

self.videoHud.progress = number;

};

return [client resumableUpload:resumableUpload];

}]

continueWithBlock:^id(OSSTask *task) {

if (task.error) {

if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {

// 如果续传失败且无法恢复,需要删除本地记录的UploadId,然后重启任务

[[NSUserDefaults standardUserDefaults] removeObjectForKey:recordKey];

}

} else {

dispatch_async(dispatch_get_main_queue(), ^{

[self.videoHud hide:YES];

self.videoHud = nil;

//删除沙盒下面对应的视频文件

//                 NSFileManager *defauleManager = [NSFileManager defaultManager];

//                 NSString *tempPath = [filePath absoluteString];

//                 [defauleManager removeItemAtPath:tempPath error:nil];

NSFileManager *fileManager = [NSFileManager defaultManager];

NSArray *fileListArray = [fileManager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"tmp"] error:nil];

for (NSString *file in fileListArray)

{

NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"tmp"] stringByAppendingPathComponent:file];

NSString *extension = [path pathExtension];

if ([extension compare:@"mp4" options:NSCaseInsensitiveSearch] == NSOrderedSame)

{

[fileManager removeItemAtPath:path error:nil];

}

}

});

NSLog(@"上传完成!");

// 上传成功,删除本地保存的UploadId

_uploadid = nil;

[[NSUserDefaults standardUserDefaults] removeObjectForKey:recordKey];

[self uploadVideoInfoWithObjectKey:objectKey duration:[NSString stringWithFormat:@"%f.1",VideoDuration]];

}

return nil;

}];

}

你可能感兴趣的:(阿里云 断点续传(仅供参考))