相关资源
SDK 源码地址请参考: XML iOS SDK。
SDK 快速下载地址:XML iOS SDK。
示例 Demo 可参考:XML iOS SDK Demo。
SDK 接口与参数文档请参见 SDK API 参考。
SDK 文档中的所有示例代码请参见 SDK 代码示例。
SDK 更新日志请参见:ChangeLog。
SDK 常见问题请参见:iOS SDK 常见问题。
说明:
准备工作
您需要一个 iOS 应用,这个应用可以是您现有的工程,也可以是您新建的一个空的工程。
请确保应用基于 iOS 8.0及以上版本的 SDK 构建。
您需要一个可以获取腾讯云临时密钥的远程地址,关于临时密钥的有关说明请参见 移动应用直传实践。
步骤1:安装 SDK
方式一:使用 Cocoapods 集成(推荐)
标准版 SDK
在您工程的
Podfile
文件中使用。pod 'QCloudCOSXML'
精简版 SDK
如果您仅仅使用到上传和下载功能,并且对 SDK 体积要求较高,可以使用我们的精简版 SDK。
精简版 SDK 是通过 Cocoapods 的 Subspec 功能实现的,因此目前只支持通过自动集成的方式。在您工程的
Podfile
文件中使用。pod 'QCloudCOSXML/Transfer'
关闭腾讯灯塔上报功能
若是想关闭该功能,请在
podfile
文件中将 pod 'QCloudCOSXML'
依赖改为:pod 'QCloudCOSXML/Slim'
即可。注意:
Swift 项目使用 Pod 集成时,需要在 podfile 文件中加上
use_frameworks!
。方式二:手动集成
1. 导入二进制库
将 QCloudCOSXML.framework、QCloudCore.framework 、QCloudTrack.framework和 COSBeaconAPI_Base.framework 以及 QimeiSDK.framework 拖入到工程中。

说明:
QCloudCore.framework、QCloudCOSXML.framework 为 SDK 核心组件,必选。
COSBeaconAPI_Base.framework、QCloudTrack.framework、QimeiSDK.framework 为日志上报组件,可选依赖。
并添加以下依赖库:
CoreTelephony
Foundation
SystemConfiguration
libc++.tbd
2. 工程配置
在 Build Settings 中设置 Other Linker Flags,添加以下参数:
-ObjC-all_load


说明:
SDK 提供了打包脚本,支持根据业务需求自行打包(该打包脚本依赖于 Cocoapods,请先确保您的开发环境安装了 Cocoapods。)打包步骤如下:
1. 下载源码:
git clone https://github.com/tencentyun/qcloud-sdk-ios
。2. 运行打包脚本:
source package.sh
。3. 将打包产物拖到工程中,然后按照上面手动集成的方式操作即可。
iOS:将 ios 文件夹下的产物拖入项目。
macOS:将 osx 文件夹下的产物拖入项目。


步骤2:开始使用
1. 导入头文件
标准版 SDK,请导入:
Objective-c
#import <QCloudCOSXML/QCloudCOSXML.h>
swift
import QCloudCOSXML
精简版 SDK,请导入:
Objective-c
#import <QCloudCOSXML/QCloudCOSXMLTransfer.h>
swift
import QCloudCOSXML
2. 初始化 COS 服务
说明:
适用于每组临时密钥只用于上传一个文件或一次请求。
单次临时密钥的优先级高于 QCloudCOSXMLService 中初始化配置的 configuration.signatureProvider ,因此 QCloudCOSXMLService 中配置的 configuration.signatureProvider 不会影响单次临时密钥的设置,
COS SDK 中所有 Request 都支持通过 credential 属性来设置单次临时密钥。
若项目中全部使用单次临时密钥,则可以不配置 configuration.signatureProvider,也无需实现 QCloudSignatureProvider 代理。
COS iOS SDK 版本需要大于等于 v6.4.2。
具体步骤请参考下面的完整示例代码。
1. 初始化 COS 服务实例。
Objective-c
//AppDelegate.m@interface AppDelegate()@end@implementation AppDelegate- (BOOL)application:(UIApplication * )applicationdidFinishLaunchingWithOptions:(NSDictionary * )launchOptions {QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];// 替换为用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket// COS 支持的所有 region 列表参见 https://www.qcloud.com/document/product/436/6224endpoint.regionName = @"COS_REGION";// 使用 HTTPSendpoint.useHTTPS = true;configuration.endpoint = endpoint;// 初始化 COS 服务示例[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];return YES;}@end
Swift
//AppDelegate.swiftclass AppDelegate: UIResponder, UIApplicationDelegate {func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {let config = QCloudServiceConfiguration.init();let endpoint = QCloudCOSXMLEndPoint.init();// 替换为用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket// COS 支持的所有 region 列表参见 https://www.qcloud.com/document/product/436/6224endpoint.regionName = "COS_REGION";// 使用 HTTPSendpoint.useHTTPS = true;config.endpoint = endpoint;// 初始化 COS 服务示例QCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);return true}}
2. 设置单次临时密钥。
以上传为例,后续示例代码不再赘述。
Objective-c
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];QCloudCredential * credential = [QCloudCredential new];credential.secretID = @"secretID";credential.secretKey = @"secretKey";credential.token = @"token";// 设置临时密钥put.credential = credential;// 本地文件路径NSURL* url = [NSURL fileURLWithPath:@"文件的URL"];// 存储桶名称,由 BucketName-Appid 组成,可以在 COS 控制台查看 https://console.cloud.tencent.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];
Swift
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();let credential = QCloudCredential()credential.secretID = "secretID"credential.secretKey = "secretKey"credential.token = "token"// 设置临时密钥put.credential = credential// 存储桶名称,由BucketName-Appid 组成,可以在 COS 控制台查看 https://console.cloud.tencent.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);
说明:
适用于临时密钥可复用于上传多个文件或多个请求
SDK 在发出请求时,需要获取临时密钥计算签名,因此需要您实现
QCloudSignatureProvider
协议,在该协议中获取密钥后将密钥通过参数continueBlock
回调给 SDK。建议把初始化过程放在
AppDelegate
或者程序单例中。具体步骤请参考下面的完整示例代码。
Objective-c
//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.cloud.tencent.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.cloud.tencent.com/cam/capicredential.secretID = @"SECRETID";// 临时密钥 SecretKey// sercret_key替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capicredential.secretKey = @"SECRETKEY";// 临时密钥 Token// 如果使用永久密钥不需要填入 token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见 https://cloud.tencent.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
Swift
//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.cloud.tencent.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.cloud.tencent.com/cam/capicredential.secretID = "SECRETID";// 临时密钥 SecretKey// sercret_key 替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capicredential.secretKey = "SECRETKEY";// 临时密钥 Token// 如果使用永久密钥不需要填入 token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见 https://cloud.tencent.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);}}
注意:
APPID 是您在成功申请腾讯云账户后所得到的账号,由系统自动分配,具有固定性和唯一性,可在 账号信息 中查看。腾讯云账号的 APPID,是与账号 ID 有唯一对应关系的应用 ID。
SecretId 和 SecretKey 合称为云 API 密钥,是用户访问腾讯云 API 进行身份验证时需要用到的安全凭证,可在 API 密钥管理 中获取。SecretKey 是用于加密签名字符串和服务器端验证签名字符串的密钥。SecretId 用于标识 API 调用者身份。一个 APPID 可以创建多个云 API 密钥。
SDK 提供了一个
QCloudCredentailFenceQueue
的脚手架,实现对临时密钥的缓存与复用。脚手架在密钥过期之后会重新调用该协议的方法来重新获取新的密钥,直到该密钥过期时间大于设备的当前时间。注意:
脚手架只是根据密钥的过期时间是否大于设备的当前时间来判断密钥是否能复用,如果您申请密钥时设置了复杂的策略,则不建议使用脚手架工具。
建议把初始化过程放在
AppDelegate
或者程序单例中。使用脚手架您需要实现以下两个协议:QCloudSignatureProvider
QCloudCredentailFenceQueueDelegate
完整示例代码请参考如下:
Objective-c
//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.cloud.tencent.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.cloud.tencent.com/cam/capicredential.secretID = @"SECRETID";// 临时密钥 SecretKey// sercret_key 替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capicredential.secretKey = @"SECRETKEY";// 临时密钥 Token// 如果使用永久密钥不需要填入token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见https://cloud.tencent.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
Swift
//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.cloud.tencent.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.cloud.tencent.com/cam/capicredential.secretID = "SECRETID";// 临时密钥 SecretKey// sercret_key 替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capicredential.secretKey = "SECRETKEY";// 临时密钥 Token// 如果使用永久密钥不需要填入 token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见 https://cloud.tencent.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);}})}}
注意:
关于存储桶不同地域的简称请参考 地域和访问域名。
建议您使用 HTTPS 来请求数据,但如果您希望使用 HTTP 协议,为了确保在 iOS 9.0以上的系统上可以运行,您需要为应用开启允许通过 HTTP 传输。详细的指引请参考 Apple 官方的说明文档 Preventing Insecure Network Connections。
如果您的
QCloudServiceConfiguration
发生改变,可以通过以下方法注册一个新的实例:+ (QCloudCOSTransferMangerService*) registerCOSTransferMangerWithConfiguration:(QCloudServiceConfig
在签名过程放在后台时,您可以不实现
QCloudCredentailFenceQueueDelegate
协议。Objective-C
- (void) signatureWithFields:(QCloudSignatureFields*)filedsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{// 签名过期时间NSDate *expiration = [[[NSDateFormatter alloc] init]dateFromString:@"expiredTime"];QCloudSignature *sign = [[QCloudSignature alloc] initWithSignature:@"后台计算好的签名" expiration:expiration];sign.token = @"临时密钥Token";// 永久密钥不需要 TokencontinueBlock(signature, nil);}
Swift
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);sign.token = "临时密钥Token";// 永久密钥不需要 TokencontinueBlock(signature,nil);}
说明:
由于该方式存在泄漏密钥的风险,请务必在上线前替换为临时密钥的方式。
SDK 在发出请求时,需要获取临时密钥计算签名,因此需要您实现
QCloudSignatureProvider
协议,在该协议中获取密钥后将密钥通过参数continueBlock
回调给 SDK。建议把初始化过程放在
AppDelegate
或者程序单例中。
您可以使用腾讯云的永久密钥来进行开发阶段的本地调试。由于该方式存在泄漏密钥的风险,请务必在上线前替换为临时密钥的方式。
在使用永久密钥时,您可以不实现
QCloudCredentailFenceQueueDelegate
协议。Objective-C
- (void) signatureWithFields:(QCloudSignatureFields*)filedsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{QCloudCredential* credential = [QCloudCredential new];// 永久密钥 secretID// sercret_id 替换为用户的 SecretId,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capicredential.secretID = @"SECRETID";// 永久密钥 SecretKey// sercret_key 替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capicredential.secretKey = @"SECRETKEY";// 使用永久密钥计算签名QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]initWithCredential:credential];// 注意 这里不要对 urlRequst 进行 copy 以及 mutableCopy 操作QCloudSignature* signature = [creator signatureForData:urlRequst];continueBlock(signature, nil);}
Swift
func signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {let credential = QCloudCredential.init();// 永久密钥 secretID// sercret_id替换为用户的 SecretId,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capicredential.secretID = "SECRETID";// 永久密钥 SecretKey// sercret_key替换为用户的 SecretKey,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capicredential.secretKey = "SECRETKEY";// 使用永久密钥计算签名let auth = QCloudAuthentationV5Creator.init(credential: credential);// 注意:这里不要对 urlRequst 进行 copy 以及 mutableCopy 操作let signature = auth?.signature(forData: urlRequst)continueBlock(signature,nil);}
3. 配置域名
若业务中不需要指定自定义源站域名或全球加速域名,则跳过该步骤。
使用方式:在“初始化 COS 服务”步骤中,实例化 QCloudCOSXMLEndPoint 时传入指定的域名。
说明:
建议使用自定义源站域名或全球加速域名,不推荐使用自定义 CDN加速域名。CDN加速域名主要用于加速下载,不适用于加速上传场景。若使用 CDN加速域名,则没有加速效果。
Objective-C
NSString *customDomain = @"exampledomain.com"; // 自定义源站域名或全球加速域名QCloudCOSXMLEndPoint *endpoint = [[QCloudCOSXMLEndPoint alloc] initWithLiteralURL:[NSURL URLWithString:customDomain]];QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];// 替换为用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket// COS 支持的所有 region 列表参见https://www.qcloud.com/document/product/436/6224// 使用 HTTPSendpoint.useHTTPS = true;configuration.endpoint = endpoint;// 初始化 COS 服务示例[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];
Swift
let endpoint = QCloudCOSXMLEndPoint.init(literalURL: NSURL.init(string: "exampledomain.com") as URL?);let config = QCloudServiceConfiguration.init();// 替换为用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket// COS 支持的所有 region 列表参见https://www.qcloud.com/document/product/436/6224// 使用 HTTPSendpoint.useHTTPS = true;config.endpoint = endpoint;// 初始化 COS 服务示例QCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);
步骤3:访问 COS 服务
上传对象
SDK 支持上传本地文件与二进制数据 NSData。下面以上传本地文件为例。
Objective-C
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];// 本地文件路径NSURL* url = [NSURL fileURLWithPath:@"文件的URL"];// 存储桶名称,由 BucketName-Appid 组成,可以在 COS 控制台查看 https://console.cloud.tencent.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];
说明:
更多完整示例,请前往 GitHub 查看。
上传之后,您可以用同样的 Key 生成文件下载链接,具体使用方法请参见 生成预签名链接 文档。但注意如果您的文件是私有读权限,那么下载链接只有一定的有效期。
Swift
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();// 存储桶名称,由 BucketName-Appid 组成,可以在 COS 控制台查看 https://console.cloud.tencent.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);
说明:
更多完整示例,请前往 GitHub 查看。
上传之后,您可以用同样的 Key 生成文件下载链接,具体使用方法请参见 生成预签名链接 文档。但注意如果您的文件是私有读权限,那么下载链接只有一定的有效期。
下载对象
Objective-C
QCloudCOSXMLDownloadObjectRequest * request = [QCloudCOSXMLDownloadObjectRequest new];// 存储桶名称,由 BucketName-Appid 组成,可以在 COS 控制台查看 https://console.cloud.tencent.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];
说明:
Swift
let request : QCloudCOSXMLDownloadObjectRequest = QCloudCOSXMLDownloadObjectRequest();// 存储桶名称,由 BucketName-Appid 组成,可以在 COS 控制台查看 https://console.cloud.tencent.com/cos5/bucketrequest.bucket = "examplebucket-1250000000";// 对象键request.object = "exampleobject";//设置下载的路径 URL,如果设置了,文件将会被下载到指定路径中request.downloadingURL = NSURL.fileURL(withPath: "Local File Path") as URL?;//监听下载进度request.downProcessBlock = { (bytesDownload, totalBytesDownload,totalBytesExpectedToDownload) in// bytesDownload 本次要下载的字节数(一个大文件可能要分多次发送)// totalBytesDownload 已下载的字节数// totalBytesExpectedToDownload 本次要下载的总字节数(即一个文件大小)}//监听下载结果request.finishBlock = { (copyResult, error) inif error != nil{print(error!);}else{print(copyResult!);}}QCloudCOSTransferMangerService.defaultCOSTransferManager().downloadObject(request);
说明: