Podfile of your project:pod 'QCloudCOSXML'
Podfile of your project:pod 'QCloudCOSXML/Transfer'
QCloudCOSXML.framework, QCloudCore.framework, BeaconAPI_Base.framework, and QimeiSDK.framework into the project.
-ObjC-all_load

git clone https://github.com/tencentyun/qcloud-sdk-ios.source package.sh.ios folder to the project.osx folder to the project.

#import <QCloudCOSXML/QCloudCOSXML.h>
import QCloudCOSXML
#import <QCloudCOSXML/QCloudCOSXMLTransfer.h>
import QCloudCOSXMLTransfer
//AppDelegate.m// `AppDelegate` must follow `QCloudSignatureProvider`@interface AppDelegate()<QCloudSignatureProvider>@end@implementation AppDelegate- (BOOL)application:(UIApplication * )applicationdidFinishLaunchingWithOptions:(NSDictionary * )launchOptions {QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];// Replace it with the actual region, which can be viewed in the console at https://console.tencentcloud.com/cos5/bucket// For the list of regions supported by COS, see https://www.qcloud.com/document/product/436/6224endpoint.regionName = @"COS_REGION";// Use HTTPSendpoint.useHTTPS = true;configuration.endpoint = endpoint;// You are the key providerconfiguration.signatureProvider = self;// Initialize the COS instances[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];return YES;}// Getting the signature: Here you can see how to get the temporary key and calculate the signature// You can also customize the signature calculation process- (void) signatureWithFields:(QCloudSignatureFields*)fieldsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{// Here, get the temporary key from the background server synchronously. It is highly recommended that the logic for getting a temporary key be placed here to maximize the availability of the key//...QCloudCredential* credential = [QCloudCredential new];// Temporary key SecretId// Replace secret_id with the actual SecretId, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretID = @"SECRETID";// Temporary key SecretKey// Replace secret_key with the actual SecretKey, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretKey = @"SECRETKEY";// Temporary key token// Token is required for temporary keys but not permanent keys. For more information about how to generate and use a temporary key, see https://www.tencentcloud.com/document/product/436/14048credential.token = @"TOKEN";/** You are advised to use the returned server time as the start time of the signature, to avoid signature errors caused by the large deviation between your phone’s local time and the system time (the unit of `startTime` and `expiredTime` is second).*/credential.startDate = [NSDate dateWithTimeIntervalSince1970:startTime]; // Unit: secondcredential.expirationDate = [NSDate dateWithTimeIntervalSince1970:expiredTime]]; // Unit: secondQCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]initWithCredential:credential];// Note: Do not perform the copy or mutableCopy operation on `urlRequst`QCloudSignature *signature = [creator signatureForData:urlRequst];continueBlock(signature, nil);}@end
//AppDelegate.swift// `AppDelegate` must follow `QCloudSignatureProvider`class AppDelegate: UIResponder, UIApplicationDelegate,QCloudSignatureProvider {func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {let config = QCloudServiceConfiguration.init();let endpoint = QCloudCOSXMLEndPoint.init();// Replace it with the actual region, which can be viewed in the console at https://console.tencentcloud.com/cos5/bucket// For the list of regions supported by COS, see https://www.qcloud.com/document/product/436/6224endpoint.regionName = "COS_REGION";// Use HTTPSendpoint.useHTTPS = true;config.endpoint = endpoint;// You are the key providerconfig.signatureProvider = self;// Initialize the COS instancesQCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);return true}// Getting the signature: Here you can see how to get the temporary key and calculate the signature// You can also customize the signature calculation processfunc signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {// Get the temporary key from the backend server synchronously//...let credential = QCloudCredential.init();// Temporary key SecretId// Replace secret_id with the actual SecretId, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretID = "SECRETID";// Temporary key SecretKey// Replace secret_key with the actual SecretKey, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretKey = "SECRETKEY";// Temporary key token// Token is required for temporary keys but not permanent keys. For more information about how to generate and use a temporary key, see https://www.tencentcloud.com/document/product/436/14048credential.token = "TOKEN";/** You are advised to use the returned server time as the start time of the signature, to avoid signature errors caused by the large deviation between your phone’s local time and the system time (the unit of `startTime` and `expiredTime` is second).*/credential.startDate = Date.init(timeIntervalSince1970: TimeInterval(startTime)!) DateFormatter().date(from: "startTime");credential.expirationDate = Date.init(timeIntervalSince1970: TimeInterval(expiredTime)!)let creator = QCloudAuthentationV5Creator.init(credential: credential);// Note: Do not perform the copy or mutableCopy operation on `urlRequst`let signature = creator?.signature(forData: urlRequst);continueBlock(signature,nil);}}
QCloudCredentailFenceQueue scaffolding tool for you to cache and reuse your temporary key. After a key expires, the scaffolding tool will call the protocol again to retrieve the new key until the key expiration time is later than the current device time.//AppDelegate.m// `AppDelegate` needs to follow the `QCloudSignatureProvider` and// `QCloudCredentailFenceQueueDelegate` protocols@interface AppDelegate()<QCloudSignatureProvider, QCloudCredentailFenceQueueDelegate>// Scaffolding tool instance@property (nonatomic) QCloudCredentailFenceQueue* credentialFenceQueue;@end@implementation AppDelegate- (BOOL)application:(UIApplication * )applicationdidFinishLaunchingWithOptions:(NSDictionary * )launchOptions {QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];// Replace it with the actual region, which can be viewed in the console at https://console.tencentcloud.com/cos5/bucket// For the list of regions supported by COS, see https://www.qcloud.com/document/product/436/6224endpoint.regionName = @"COS_REGION";// Use HTTPSendpoint.useHTTPS = true;configuration.endpoint = endpoint;// You are the key providerconfiguration.signatureProvider = self;// Initialize the COS instances[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];// Initialize the temporary key scaffolding toolself.credentialFenceQueue = [QCloudCredentailFenceQueue new];self.credentialFenceQueue.delegate = self;return YES;}- (void) fenceQueue:(QCloudCredentailFenceQueue * )queue requestCreatorWithContinue:(QCloudCredentailFenceQueueContinue)continueBlock{// Here, get the temporary key from the background server synchronously. It is highly recommended that the logic for getting a temporary key be placed here to maximize the availability of the key//...QCloudCredential* credential = [QCloudCredential new];// Temporary key SecretId// Replace secret_id with the actual SecretId, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretID = @"SECRETID";// Temporary key SecretKey// Replace secret_key with the actual SecretKey, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretKey = @"SECRETKEY";// Temporary key token// Token is required for temporary keys but not permanent keys. For more information about how to generate and use a temporary key, see https://www.tencentcloud.com/document/product/436/14048credential.token = @"TOKEN";/** You are advised to use the returned server time as the start time of the signature, to avoid signature errors caused by the large deviation between your phone’s local time and the system time (the unit of `startTime` and `expiredTime` is second).*/credential.startDate = [NSDate dateWithTimeIntervalSince1970:startTime]; // Unit: secondcredential.expirationDate = [NSDate dateWithTimeIntervalSince1970:expiredTime]]; // Unit: secondQCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]initWithCredential:credential];continueBlock(creator, nil);}// Getting the signature: Here you can see how to get the temporary key and calculate the signature// You can also customize the signature calculation process- (void) signatureWithFields:(QCloudSignatureFields*)fieldsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{[self.credentialFenceQueue performAction:^(QCloudAuthentationCreator *creator,NSError *error) {if (error){continueBlock(nil, error);} else {// Note: Do not perform the copy or mutableCopy operation on `urlRequst`QCloudSignature* signature = [creator signatureForData:urlRequst];continueBlock(signature, nil);}}];}@end
//AppDelegate.swift// `AppDelegate` needs to follow the `QCloudSignatureProvider` and// `QCloudCredentailFenceQueueDelegate` protocolsclass 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();// Replace it with the actual region, which can be viewed in the console at https://console.tencentcloud.com/cos5/bucket// For the list of regions supported by COS, see https://www.qcloud.com/document/product/436/6224endpoint.regionName = "COS_REGION";// Use HTTPSendpoint.useHTTPS = true;config.endpoint = endpoint;// You are the key providerconfig.signatureProvider = self;// Initialize the COS instancesQCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);// Initialize the temporary key scaffolding toolself.credentialFenceQueue = QCloudCredentailFenceQueue.init();self.credentialFenceQueue?.delegate = self;return true}func fenceQueue(_ queue: QCloudCredentailFenceQueue!,requestCreatorWithContinue continueBlock:QCloudCredentailFenceQueueContinue!) {// Get the temporary key from the backend server synchronously//...let credential = QCloudCredential.init();// Temporary key SecretId// Replace secret_id with the actual SecretId, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretID = "SECRETID";// Temporary key SecretKey// Replace secret_key with the actual SecretKey, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretKey = "SECRETKEY";// Temporary key token// Token is required for temporary keys but not permanent keys. For more information about how to generate and use a temporary key, see https://www.tencentcloud.com/document/product/436/14048credential.token = "TOKEN";/** You are advised to use the returned server time as the start time of the signature, to avoid signature errors caused by the large deviation between your phone’s local time and the system time (the unit of `startTime` and `expiredTime` is second).*/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);}// Getting the signature: Here you can see how to get the temporary key and calculate the signature// You can also customize the signature calculation processfunc signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {self.credentialFenceQueue?.performAction({ (creator, error) inif error != nil {continueBlock(nil,error!);}else{// Note: Do not perform the copy or mutableCopy operation on `urlRequst`let signature = creator?.signature(forData: urlRequst);continueBlock(signature,nil);}})}}
QCloudServiceConfiguration has changed, you can register a new instance by using the following method:+ (QCloudCOSTransferMangerService*) registerCOSTransferMangerWithConfiguration:(QCloudServiceConfig
QCloudCredentailFenceQueueDelegate protocol.- (void) signatureWithFields:(QCloudSignatureFields*)fieldsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{QCloudCredential* credential = [QCloudCredential new];// secretID of the permanent key// Replace secret_id with the actual SecretId, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretID = @"SECRETID";// SecretKey of the permanent key// Replace secret_key with the actual SecretKey, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretKey = @"SECRETKEY";// Use the permanent key to calculate the signatureQCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]initWithCredential:credential];// Note: Do not perform the copy or mutableCopy operation on `urlRequst`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 of the permanent key// Replace secret_id with the actual SecretId, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretID = "SECRETID";// SecretKey of the permanent key// Replace secret_key with the actual SecretKey, which can be viewed at https://console.tencentcloud.com/cam/capicredential.secretKey = "SECRETKEY";// Use the permanent key to calculate the signaturelet auth = QCloudAuthentationV5Creator.init(credential: credential);// Note: Do not perform the copy or mutableCopy operation on `urlRequst`let signature = auth?.signature(forData: urlRequst)continueBlock(signature,nil);}
QCloudCredentailFenceQueueDelegate protocol- (void) signatureWithFields:(QCloudSignatureFields*)fieldsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{// Signature expiration timeNSDate *expiration = [[[NSDateFormatter alloc] init]dateFromString:@"expiredTime"];QCloudSignature *sign = [[QCloudSignature alloc] initWithSignature:@"Signature calculated on backend" expiration:expiration];continueBlock(signature, nil);}
func signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {// Signature expiration timelet expiration = DateFormatter().date(from: "expiredTime");let sign = QCloudSignature.init(signature: "signature calculated on backend",expiration: expiration);continueBlock(signature,nil);}
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];// Local file pathNSURL* url = [NSURL fileURLWithPath:@"file URL"];// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucketput.bucket = @"examplebucket-1250000000";// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"put.object = @"exampleobject";// Content of the object to be uploaded. You can pass in variables in `NSData*` or `NSURL*` formatput.body = url;// Monitor the upload progress[put setSendProcessBlock:^(int64_t bytesSent,int64_t totalBytesSent,int64_t totalBytesExpectedToSend) {// bytesSent Number of bytes to send in this request (a large file may require multiple requests)// totalBytesSent Total number of bytes sent so far// totalBytesExpectedToSend Total number of bytes expected to send, i.e. the size of the file}];// Monitor the upload result[put setFinishBlock:^(id outputObject, NSError *error) {// outputObject contains information such as the ETag or custom headers in the response.NSDictionary * result = (NSDictionary *)outputObject;}];[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucketput.bucket = "examplebucket-1250000000";// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"put.object = "exampleobject";// Content of the object to be uploaded. You can pass in variables in `NSData*` or `NSURL*` formatput.body = NSURL.fileURL(withPath: "Local File Path") as AnyObject;// Monitor the upload resultput.setFinish { (result, error) in// Get the upload resultif error != nil{print(error!);}else{print(result!);}}// Monitor the upload progressput.sendProcessBlock = { (bytesSent, totalBytesSent,totalBytesExpectedToSend) in// bytesSent Number of bytes to send in this request (a large file may require multiple requests)// totalBytesSent Total number of bytes sent so far// totalBytesExpectedToSend Total number of bytes expected to send, i.e. the size of the file};// Set the upload parametersput.initMultipleUploadFinishBlock = {(multipleUploadInitResult, resumeData) in// This block will be called back after the Initiate Multipart Upload operation is complete so you can get resumeData// and can generate a multipart upload request using resumeData.let resumeUploadRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>.init(request: resumeData as Data?);}QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
QCloudCOSXMLDownloadObjectRequest * request = [QCloudCOSXMLDownloadObjectRequest new];// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucketrequest.bucket = @"examplebucket-1250000000";// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"request.object = @"exampleobject";// Set the download URL. Once set, the file will be downloaded to the specified pathrequest.downloadingURL = [NSURL fileURLWithPath:@"Local File Path"];// Monitor the download result[request setFinishBlock:^(id outputObject, NSError *error) {// `outputObject` contains all HTTP response headersNSDictionary* info = (NSDictionary *) outputObject;}];// Monitor the download progress[request setDownProcessBlock:^(int64_t bytesDownload,int64_t totalBytesDownload,int64_t totalBytesExpectedToDownload) {// bytesDownload Number of bytes to download in this request (a large file may require multiple requests)// totalBytesDownload Number of bytes downloaded so far// totalBytesExpectedToDownload Total number of bytes expected to download, i.e. the size of the file}];[[QCloudCOSTransferMangerService defaultCOSTransferManager] DownloadObject:request];
let request : QCloudCOSXMLDownloadObjectRequest = QCloudCOSXMLDownloadObjectRequest();// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucketrequest.bucket = "examplebucket-1250000000";// Object keyrequest.object = "exampleobject";// Set the download URL. Once set, the file will be downloaded to the specified pathrequest.downloadingURL = NSURL.fileURL(withPath: "Local File Path") as URL?;// Monitor the download progressrequest.sendProcessBlock = { (bytesDownload, totalBytesDownload,totalBytesExpectedToDownload) in// bytesDownload Number of bytes to download in this request (a large file may require multiple requests)// totalBytesDownload Number of bytes downloaded so far// totalBytesExpectedToDownload Total number of bytes expected to download, i.e. the size of the file}// Monitor the download resultrequest.finishBlock = { (copyResult, error) inif error != nil{print(error!);}else{print(copyResult!);}}QCloudCOSTransferMangerService.defaultCOSTransferManager().downloadObject(request);
Feedback