Podfile
文件中使用:pod 'QCloudCOSXML'
Podfile
文件中使用:pod 'QCloudCOSXML/Transfer'
-ObjC-all_load
git clone https://github.com/tencentyun/qcloud-sdk-ios
。source package.sh
。#import <QCloudCOSXML/QCloudCOSXML.h>
import QCloudCOSXML
#import <QCloudCOSXML/QCloudCOSXMLTransfer.h>
import QCloudCOSXMLTransfer
QCloudSignatureProvider
协议,在该协议中获取密钥后将密钥通过参数continueBlock
回调给 SDK。AppDelegate
或者程序单例中。//AppDelegate.m//AppDelegate 需遵循 QCloudSignatureProvider@interface AppDelegate()<QCloudSignatureProvider>@end@implementation AppDelegate- (BOOL)application:(UIApplication * )applicationdidFinishLaunchingWithOptions:(NSDictionary * )launchOptions {QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];// 替换为用户的 region,已创建桶归属的region可以在控制台查看,https://console.tencentcloud.com/cos5/bucket// COS支持的所有region列表参见https://www.qcloud.com/document/product/436/6224endpoint.regionName = @"COS_REGION";// 使用 HTTPSendpoint.useHTTPS = true;configuration.endpoint = endpoint;// 密钥提供者为自己configuration.signatureProvider = self;// 初始化 COS 服务示例[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];return YES;}// 获取签名的方法入口,这里演示了获取临时密钥并计算签名的过程// 您也可以自定义计算签名的过程- (void) signatureWithFields:(QCloudSignatureFields*)filedsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{//这里同步从后台服务器获取临时密钥,强烈建议将获取临时密钥的逻辑放在这里,最大程度上保证密钥的可用性//...QCloudCredential* credential = [QCloudCredential new];// 临时密钥 SecretId// sercret_id替换为用户的 SecretId,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretID = @"SECRETID";// 临时密钥 SecretKey// sercret_key替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretKey = @"SECRETKEY";// 临时密钥 Token// 如果使用永久密钥不需要填入token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见https://www.tencentcloud.com/document/product/436/14048credential.token = @"TOKEN";/** 强烈建议返回服务器时间作为签名的开始时间, 用来避免由于用户手机本地时间偏差过大导致的签名不正确(参数startTime和expiredTime单位为秒)*/credential.startDate = [NSDate dateWithTimeIntervalSince1970:startTime]; // 单位是秒credential.expirationDate = [NSDate dateWithTimeIntervalSince1970:expiredTime]];// 单位是秒QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]initWithCredential:credential];// 注意 这里不要对urlRequst 进行copy以及mutableCopy操作QCloudSignature *signature = [creator signatureForData:urlRequst];continueBlock(signature, nil);}@end
//AppDelegate.swift//AppDelegate 需遵循 QCloudSignatureProviderclass AppDelegate: UIResponder, UIApplicationDelegate,QCloudSignatureProvider {func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {let config = QCloudServiceConfiguration.init();let endpoint = QCloudCOSXMLEndPoint.init();// 替换为用户的 region,已创建桶归属的region可以在控制台查看,https://console.tencentcloud.com/cos5/bucket// COS支持的所有region列表参见https://www.qcloud.com/document/product/436/6224endpoint.regionName = "COS_REGION";// 使用 HTTPSendpoint.useHTTPS = true;config.endpoint = endpoint;// 密钥提供者为自己config.signatureProvider = self;// 初始化 COS 服务示例QCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);return true}// 获取签名的方法入口,这里演示了获取临时密钥并计算签名的过程// 您也可以自定义计算签名的过程func signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {//这里同步从后台服务器获取临时密钥//...let credential = QCloudCredential.init();// 临时密钥 SecretId// sercret_id替换为用户的 SecretId,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretID = "SECRETID";// 临时密钥 SecretKey// sercret_key替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretKey = "SECRETKEY";// 临时密钥 Token// 如果使用永久密钥不需要填入token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见https://www.tencentcloud.com/document/product/436/14048credential.token = "TOKEN";/** 强烈建议返回服务器时间作为签名的开始时间, 用来避免由于用户手机本地时间偏差过大导致的签名不正确(参数startTime和expiredTime单位为秒)*/credential.startDate = Date.init(timeIntervalSince1970: TimeInterval(startTime)!) DateFormatter().date(from: "startTime");credential.expirationDate = Date.init(timeIntervalSince1970: TimeInterval(expiredTime)!)let creator = QCloudAuthentationV5Creator.init(credential: credential);// 注意 这里不要对urlRequst 进行copy以及mutableCopy操作let signature = creator?.signature(forData: urlRequst);continueBlock(signature,nil);}}
QCloudCredentailFenceQueue
的脚手架,实现对临时密钥的缓存与复用。脚手架在密钥过期之后会重新调用该协议的方法来重新获取新的密钥,直到该密钥过期时间大于设备的当前时间。AppDelegate
或者程序单例中。使用脚手架您需要实现以下两个协议://AppDelegate.m//AppDelegate 需遵循 QCloudSignatureProvider 与//QCloudCredentailFenceQueueDelegate 协议@interface AppDelegate()<QCloudSignatureProvider, QCloudCredentailFenceQueueDelegate>// 一个脚手架实例@property (nonatomic) QCloudCredentailFenceQueue* credentialFenceQueue;@end@implementation AppDelegate- (BOOL)application:(UIApplication * )applicationdidFinishLaunchingWithOptions:(NSDictionary * )launchOptions {QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];// 替换为用户的 region,已创建桶归属的region可以在控制台查看,https://console.tencentcloud.com/cos5/bucket// COS支持的所有region列表参见https://www.qcloud.com/document/product/436/6224endpoint.regionName = @"COS_REGION";// 使用 HTTPSendpoint.useHTTPS = true;configuration.endpoint = endpoint;// 密钥提供者为自己configuration.signatureProvider = self;// 初始化 COS 服务示例[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];// 初始化临时密钥脚手架self.credentialFenceQueue = [QCloudCredentailFenceQueue new];self.credentialFenceQueue.delegate = self;return YES;}- (void) fenceQueue:(QCloudCredentailFenceQueue * )queue requestCreatorWithContinue:(QCloudCredentailFenceQueueContinue)continueBlock{//这里同步从◊后台服务器获取临时密钥,强烈建议将获取临时密钥的逻辑放在这里,最大程度上保证密钥的可用性//...QCloudCredential* credential = [QCloudCredential new];// 临时密钥 SecretId// sercret_id替换为用户的 SecretId,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretID = @"SECRETID";// 临时密钥 SecretKey// sercret_key替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretKey = @"SECRETKEY";// 临时密钥 Token// 如果使用永久密钥不需要填入token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见https://www.tencentcloud.com/document/product/436/14048credential.token = @"TOKEN";/** 强烈建议返回服务器时间作为签名的开始时间, 用来避免由于用户手机本地时间偏差过大导致的签名不正确(参数startTime和expiredTime单位为秒)*/credential.startDate = [NSDate dateWithTimeIntervalSince1970:startTime]; // 单位是秒credential.expirationDate = [NSDate dateWithTimeIntervalSince1970:expiredTime]];// 单位是秒QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]initWithCredential:credential];continueBlock(creator, nil);}// 获取签名的方法入口,这里演示了获取临时密钥并计算签名的过程// 您也可以自定义计算签名的过程- (void) signatureWithFields:(QCloudSignatureFields*)filedsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{[self.credentialFenceQueue performAction:^(QCloudAuthentationCreator *creator,NSError *error) {if (error) {continueBlock(nil, error);} else {// 注意 这里不要对urlRequst 进行copy以及mutableCopy操作QCloudSignature* signature = [creator signatureForData:urlRequst];continueBlock(signature, nil);}}];}@end
//AppDelegate.swift//AppDelegate 需遵循 QCloudSignatureProvider 与//QCloudCredentailFenceQueueDelegate 协议class AppDelegate: UIResponder, UIApplicationDelegate,QCloudSignatureProvider, QCloudCredentailFenceQueueDelegate {var credentialFenceQueue:QCloudCredentailFenceQueue?;func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {let config = QCloudServiceConfiguration.init();let endpoint = QCloudCOSXMLEndPoint.init();// 替换为用户的 region,已创建桶归属的region可以在控制台查看,https://console.tencentcloud.com/cos5/bucket// COS支持的所有region列表参见https://www.qcloud.com/document/product/436/6224endpoint.regionName = "COS_REGION";// 使用 HTTPSendpoint.useHTTPS = true;config.endpoint = endpoint;// 密钥提供者为自己config.signatureProvider = self;// 初始化 COS 服务示例QCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);// 初始化临时密钥脚手架self.credentialFenceQueue = QCloudCredentailFenceQueue.init();self.credentialFenceQueue?.delegate = self;return true}func fenceQueue(_ queue: QCloudCredentailFenceQueue!,requestCreatorWithContinue continueBlock:QCloudCredentailFenceQueueContinue!) {//这里同步从后台服务器获取临时密钥//...let credential = QCloudCredential.init();// 临时密钥 SecretId// sercret_id替换为用户的 SecretId,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretID = "SECRETID";// 临时密钥 SecretKey// sercret_key替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretKey = "SECRETKEY";// 临时密钥 Token// 如果使用永久密钥不需要填入token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见https://www.tencentcloud.com/document/product/436/14048credential.token = "TOKEN";/** 强烈建议返回服务器时间作为签名的开始时间, 用来避免由于用户手机本地时间偏差过大导致的签名不正确(参数startTime和expiredTime单位为秒)*/credential.startDate = Date.init(timeIntervalSince1970: TimeInterval(startTime)!) DateFormatter().date(from: "startTime");credential.expirationDate = Date.init(timeIntervalSince1970: TimeInterval(expiredTime)!)let auth = QCloudAuthentationV5Creator.init(credential: credential);continueBlock(auth,nil);}// 获取签名的方法入口,这里演示了获取临时密钥并计算签名的过程// 您也可以自定义计算签名的过程func signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {self.credentialFenceQueue?.performAction({ (creator, error) inif error != nil {continueBlock(nil,error!);}else{// 注意 这里不要对urlRequst 进行copy以及mutableCopy操作let signature = creator?.signature(forData: urlRequst);continueBlock(signature,nil);}})}}
QCloudServiceConfiguration
发生改变,可以通过以下方法注册一个新的实例:+ (QCloudCOSTransferMangerService*) registerCOSTransferMangerWithConfiguration:(QCloudServiceConfig
QCloudCredentailFenceQueueDelegate
协议。- (void) signatureWithFields:(QCloudSignatureFields*)filedsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{QCloudCredential* credential = [QCloudCredential new];// 永久密钥 secretID// sercret_id替换为用户的 SecretId,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretID = @"SECRETID";// 永久密钥 SecretKey// sercret_key替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretKey = @"SECRETKEY";// 使用永久密钥计算签名QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]initWithCredential:credential];// 注意 这里不要对urlRequst 进行copy以及mutableCopy操作QCloudSignature* signature = [creator signatureForData:urlRequst];continueBlock(signature, nil);}
func signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {let credential = QCloudCredential.init();// 永久密钥 secretID// sercret_id替换为用户的 SecretId,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretID = "SECRETID";// 永久密钥 SecretKey// sercret_key替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.tencentcloud.com/cam/capicredential.secretKey = "SECRETKEY";// 使用永久密钥计算签名let auth = QCloudAuthentationV5Creator.init(credential: credential);// 注意 这里不要对urlRequst 进行copy以及mutableCopy操作let signature = auth?.signature(forData: urlRequst)continueBlock(signature,nil);}
QCloudCredentailFenceQueueDelegate
协议。- (void) signatureWithFields:(QCloudSignatureFields*)filedsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{// 签名过期时间NSDate *expiration = [[[NSDateFormatter alloc] init]dateFromString:@"expiredTime"];QCloudSignature *sign = [[QCloudSignature alloc] initWithSignature:@"后台计算好的签名" expiration:expiration];continueBlock(signature, nil);}
func signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {// 签名过期时间let expiration = DateFormatter().date(from: "expiredTime");let sign = QCloudSignature.init(signature: "后台计算好的签名",expiration: expiration);continueBlock(signature,nil);}
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];// 本地文件路径NSURL* url = [NSURL fileURLWithPath:@"文件的URL"];// 存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.tencentcloud.com/cos5/bucketput.bucket = @"examplebucket-1250000000";// 对象键,是对象在 COS 上的完整路径,如果带目录的话,格式为 "video/xxx/movie.mp4"put.object = @"exampleobject";//需要上传的对象内容。可以传入NSData*或者NSURL*类型的变量put.body = url;//监听上传进度[put setSendProcessBlock:^(int64_t bytesSent,int64_t totalBytesSent,int64_t totalBytesExpectedToSend) {// bytesSent 本次要发送的字节数(一个大文件可能要分多次发送)// totalBytesSent 已发送的字节数// totalBytesExpectedToSend 本次上传要发送的总字节数(即一个文件大小)}];//监听上传结果[put setFinishBlock:^(id outputObject, NSError *error) {//可以从 outputObject 中获取 response 中 etag 或者自定义头部等信息NSDictionary * result = (NSDictionary *)outputObject;}];[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();// 存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.tencentcloud.com/cos5/bucketput.bucket = "examplebucket-1250000000";// 对象键,是对象在 COS 上的完整路径,如果带目录的话,格式为 "video/xxx/movie.mp4"put.object = "exampleobject";//需要上传的对象内容。可以传入NSData*或者NSURL*类型的变量put.body = NSURL.fileURL(withPath: "Local File Path") as AnyObject;//监听上传结果put.setFinish { (result, error) in// 获取上传结果if error != nil{print(error!);}else{print(result!);}}//监听上传进度put.sendProcessBlock = { (bytesSent, totalBytesSent,totalBytesExpectedToSend) in// bytesSent 本次要发送的字节数(一个大文件可能要分多次发送)// totalBytesSent 已发送的字节数// totalBytesExpectedToSend 本次上传要发送的总字节数(即一个文件大小)};//设置上传参数put.initMultipleUploadFinishBlock = {(multipleUploadInitResult, resumeData) in//在初始化分块上传完成以后会回调该 block,在这里可以获取 resumeData//并且可以通过 resumeData 生成一个分块上传的请求let resumeUploadRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>.init(request: resumeData as Data?);}QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
QCloudCOSXMLDownloadObjectRequest * request = [QCloudCOSXMLDownloadObjectRequest new];// 存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.tencentcloud.com/cos5/bucketrequest.bucket = @"examplebucket-1250000000";// 对象键,是对象在 COS 上的完整路径,如果带目录的话,格式为 "video/xxx/movie.mp4"request.object = @"exampleobject";//设置下载的路径 URL,如果设置了,文件将会被下载到指定路径中request.downloadingURL = [NSURL fileURLWithPath:@"Local File Path"];//监听下载结果[request setFinishBlock:^(id outputObject, NSError *error) {//outputObject 包含所有的响应 http 头部NSDictionary* info = (NSDictionary *) outputObject;}];//监听下载进度[request setDownProcessBlock:^(int64_t bytesDownload,int64_t totalBytesDownload,int64_t totalBytesExpectedToDownload) {// bytesDownload 本次要下载的字节数(一个大文件可能要分多次发送)// totalBytesDownload 已下载的字节数// totalBytesExpectedToDownload 本次要下载的总字节数(即一个文件大小)}];[[QCloudCOSTransferMangerService defaultCOSTransferManager] DownloadObject:request];
let request : QCloudCOSXMLDownloadObjectRequest = QCloudCOSXMLDownloadObjectRequest();// 存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.tencentcloud.com/cos5/bucketrequest.bucket = "examplebucket-1250000000";// 对象键request.object = "exampleobject";//设置下载的路径 URL,如果设置了,文件将会被下载到指定路径中request.downloadingURL = NSURL.fileURL(withPath: "Local File Path") as URL?;//监听下载进度request.sendProcessBlock = { (bytesDownload, totalBytesDownload,totalBytesExpectedToDownload) in// bytesDownload 本次要下载的字节数(一个大文件可能要分多次发送)// totalBytesDownload 已下载的字节数// totalBytesExpectedToDownload 本次要下载的总字节数(即一个文件大小)}//监听下载结果request.finishBlock = { (copyResult, error) inif error != nil{print(error!);}else{print(copyResult!);}}QCloudCOSTransferMangerService.defaultCOSTransferManager().downloadObject(request);
本页内容是否解决了您的问题?