日常开发中,存储对于短视频、直播、1v1、约玩等都是不可获取的功能,此次我们来介绍一下云豹直播网站源码中存储功能的代码封装,以七牛、腾讯为例,代码如下:
一、获取存储类型
#pragma mark - 第一步:获取存储类型(tx 、qiniu) -(void)getCOSType:(YBStorageTypeBlock)complete {
NSDate *oldDate = [StorageConfig getResTime] ? [StorageConfig getResTime] : [NSDate date]; NSDate *curDate = [NSDate date]; NSTimeInterval timeInterval = [curDate timeIntervalSinceDate:oldDate]; [MBProgressHUD showMessage:@""]; YBWeakSelf; //这里过期时间默认 10 分钟,不建议改特别大的值(七牛存储token有过期时间,这个时间一定要小于七牛的过期时间) if (![StorageConfig getResTime] || timeInterval > 600) { //说明没有存储过或者超过10分钟、获取存储类型(如果是七牛顺带获取token) [YBToolClass postNetworkWithUrl:@"Video.getCosInfo" andParameter:nil success:^(int code, id _Nonnull info, NSString * _Nonnull msg) { [MBProgressHUD hideHUD]; if (code == 0) { NSDictionary *infoDic = [info firstObject]; //保留存储时间、存储类型 [StorageConfig saveResTime:[NSDate date]]; [StorageConfig saveStorageType:minstr([infoDic valueForKey:@"cloudtype"])]; if ([[infoDic valueForKey:@"qiniuInfo"] isKindOfClass:[NSDictionary class]]) { NSDictionary *qnInfo = [infoDic valueForKey:@"qiniuInfo"]; [StorageConfig saveQNToken:minstr([qnInfo valueForKey:@"qiniuToken"])]; [StorageConfig saveQNDomain:minstr([qnInfo valueForKey:@"qiniu_domain"])]; [StorageConfig saveQNZone:minstr([qnInfo valueForKey:@"qiniu_zone"])]; } if ([[infoDic valueForKey:@"txCloudInfo"] isKindOfClass:[NSDictionary class]]) { NSDictionary *txInfo = [infoDic valueForKey:@"txCloudInfo"]; [StorageConfig saveTXRegion:minstr([txInfo valueForKey:@"region"])]; [StorageConfig saveTXBucket:minstr([txInfo valueForKey:@"bucket"])]; [StorageConfig saveTXAppID:minstr([txInfo valueForKey:@"appid"])]; } }else { [MBProgressHUD showError:msg]; } } fail:^{ [MBProgressHUD hideHUD]; }]; }else { //10分钟内不请求接口,使用本地存贮的值 [MBProgressHUD hideHUD]; }
}
二、开始上传
#pragma mark - 第二步:开始上传(tx 、qiniu) //图片 -(void)yb_storageImg:(UIImage *)img andName:(NSString *)imgName complete:(YBStorageFinishaBlock)complete{
NSString *cloudType = minstr([StorageConfig getStorageType]); NSData *thumbData = UIImagePNGRepresentation(img); if ([cloudType isEqual:@"tx"]) { //腾讯 QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new]; put.object = imgName;//[NSString stringWithFormat:@"dspdemo/%@",imgName]; put.bucket = minstr([StorageConfig getTXBucket]); put.body = thumbData; [put setSendProcessBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) { NSLog(@"rk;;upload %lld totalSend %lld aim %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend); }]; [put setFinishBlock:^(id outputObject, NSError* error) { QCloudUploadObjectResult *rst = outputObject; NSLog(@"rk;;111111:\nlocation:%@\n%@",rst.location,rst.key); if (error) { //失败 }else{ //成功 } }]; [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put]; }else { //七牛 QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) { builder.zone = [self getQNZone]; }]; QNUploadOption *option = [[QNUploadOption alloc]initWithMime:nil progressHandler:nil params:nil checkCrc:NO cancellationSignal:nil]; QNUploadManager *upManager = [[QNUploadManager alloc] initWithConfiguration:config]; [upManager putData:thumbData key:imgName token:minstr([StorageConfig getQNToken]) complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) { NSLog(@"info ===== %@ \n resp ===== %@", info,resp); if (info.ok) { //成功 }else { //失败 } } option:option]; } } //音、视频 -(void)yb_storageVideoOrVoice:(NSString *)filePath andName:(NSString *)fileName complete:(YBStorageFinishaBlock)complete{ NSString *cloudType = minstr([StorageConfig getStorageType]); if ([cloudType isEqual:@"tx"]) { //腾讯 QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new]; NSURL* pathUrl = [NSURL fileURLWithPath:filePath]; put.object = fileName; put.bucket = minstr([StorageConfig getTXBucket]); put.body = pathUrl; [put setSendProcessBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) { NSLog(@"rk;;upload %lld totalSend %lld aim %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend); }]; [put setFinishBlock:^(id outputObject, NSError* error) { QCloudUploadObjectResult *rst = outputObject; NSLog(@"rk;;111111:\nlocation:%@\n%@",rst.location,rst.key); if (error) { //失败 }else{ //成功 } }]; [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put]; }else { //七牛 QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) { builder.zone = [self getQNZone]; }]; QNUploadOption *option = [[QNUploadOption alloc]initWithMime:nil progressHandler:nil params:nil checkCrc:NO cancellationSignal:nil]; QNUploadManager *upManager = [[QNUploadManager alloc] initWithConfiguration:config]; [upManager putFile:filePath key:fileName token:minstr([StorageConfig getQNToken]) complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) { NSLog(@"info ===== %@ \n resp ===== %@", info,resp); if (info.ok) { //成功 }else { //失败 } } option:option]; } } #pragma mark - 腾讯初始化、验证开始 -(void)txInit { if (![[StorageConfig getStorageType] isEqual:@"tx"]) { return; } if ([PublicObj checkNull:[StorageConfig getTXAppID]] || [PublicObj checkNull:[StorageConfig getTXBucket]] ||[PublicObj checkNull:[StorageConfig getTXRegion]]) { dispatch_async(dispatch_get_main_queue(), ^{ [MBProgressHUD showError:@"腾讯云存储信息不完整"]; }); return; } QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new]; configuration.appID = minstr([StorageConfig getTXAppID]);//@"1258210369"; configuration.signatureProvider = self; QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init]; endpoint.regionName = minstr([StorageConfig getTXRegion]);//@"ap-shanghai"; configuration.endpoint = endpoint; [QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration]; [QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration]; } //腾讯验签 - (void)signatureWithFields:(QCloudSignatureFields*)fileds request:(QCloudBizHTTPRequest*)request urlRequest:(NSMutableURLRequest*)urlRequst compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock { //此接口代替原来的 8088 端口请求 [YBToolClass postNetworkWithUrl:@"Video.getTxCosFederationToken" andParameter:nil success:^(int code, id _Nonnull info, NSString * _Nonnull msg) { if (code == 0) { NSDictionary *infoDic = [info firstObject]; QCloudCredential* credential = [QCloudCredential new]; credential.secretID = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"tmpSecretId"]]; credential.secretKey = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"tmpSecretKey"]]; credential.token = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"sessionToken"]]; QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc] initWithCredential:credential]; QCloudSignature* signature = [creator signatureForData:urlRequst]; continueBlock(signature, nil); }else { dispatch_async(dispatch_get_main_queue(), ^{ [MBProgressHUD showError:msg]; }); } } fail:^{ }]; }
至此封装完毕,以后二次开发时可由此替换其他类型的存储,只需要在这个功能类中进行单独配置就好了,而外部只需要调用即可,具有高度解耦的属性,便于直播网站源码的二次开发。
声明:以上内容为作者本人原创,未经作者本人同意,禁止转载,否则将追究相关法律责任