pod 'QCloudCOSXML'
pod 'QCloudCOSXML/Transfer'
pod 'QCloudCOSXML/Slim'


-ObjC


#import <QCloudCOSXML/QCloudCOSXML.h>
#import <QCloudCOSXML/QCloudCOSXMLTransfer.h>
#import <QCloudCOSXML/QCloudCOSXML.h>
import QCloudCOSXML
import QCloudCOSXML
import QCloudCOSXML
//AppDelegate.m@interface AppDelegate()@end@implementation AppDelegate- (BOOL)application:(UIApplication * )applicationdidFinishLaunchingWithOptions:(NSDictionary * )launchOptions {QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];// You can view the abbreviation of the bucket region in the console: https://console.tencentcloud.com/cos5/bucket// For example, the Guangzhou region is ap-guangzhou. For the full list of COS regions, see https://www.qcloud.com/document/product/436/6224endpoint.regionName = @"COS_REGION";// Use HTTPSendpoint.useHTTPS = true;configuration.endpoint = endpoint;// Example of Initializing the COS Service[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];return YES;}@end
//AppDelegate.swiftclass AppDelegate: UIResponder, UIApplicationDelegate {func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {let config = QCloudServiceConfiguration.init();let endpoint = QCloudCOSXMLEndPoint.init();// The abbreviation of the bucket region can be viewed in the console: https://console.tencentcloud.com/cos5/bucket// For example, the Guangzhou region is ap-guangzhou. For the full list of COS regions, see https://www.qcloud.com/document/product/436/6224.endpoint.regionName = "COS_REGION";// Use HTTPSendpoint.useHTTPS = true;config.endpoint = endpoint;// Example of Initializing the COS ServiceQCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);return true}}
import SwiftUIimport QCloudCOSXML@mainstruct SwiftUIDemoApp: App {init() {// Call SDK configuration during application initialization.COSManager.shared.setupCOSSDK();}var body: some Scene {WindowGroup {ContentView()}}}class COSManager: NSObject {static let shared = COSManager()private override init() {}func setupCOSSDK() {let config = QCloudServiceConfiguration.init();let endpoint = QCloudCOSXMLEndPoint.init();// The abbreviation of the bucket region can be viewed in the console: https://console.tencentcloud.com/cos5/bucket// For example, the Guangzhou region is ap-guangzhou. For the full list of COS regions, see https://www.qcloud.com/document/product/436/6224.endpoint.regionName = "COS_REGION";// Use HTTPSendpoint.useHTTPS = true;config.endpoint = endpoint;// Example of Initializing the COS ServiceQCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);}}
// Take a request for uploading files as an exampleQCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];QCloudCredential * credential = [QCloudCredential new];// Temporary ID of the Secret Keycredential.secretID = @"secretID";// Key of the Temporary Secretcredential.secretKey = @"secretKey";// Token of the Temporary Secretcredential.token = @"token";// Set temporary keys.put.credential = credential;// Local file pathNSURL* url = [NSURL fileURLWithPath:@"file's URL"];// Bucket name, composed of BucketName-Appid, can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.put.bucket = @"examplebucket-1250000000";// Object Key is the full path of the object on COS. If including directories, the format is "video/xxx/movie.mp4".put.object = @"exampleobject";// The content of the object to be uploaded. You can pass a variable of type NSData* or NSURL*.put.body = url;// Monitor upload progress.[put setSendProcessBlock:^(int64_t bytesSent,int64_t totalBytesSent,int64_t totalBytesExpectedToSend) {// bytesSent Number of bytes to be sent this time (a large file may be sent in multiple times).// totalBytesSent Bytes sent// totalBytesExpectedToSend Total bytes expected to be sent in this upload (that is, the file size)}];// Monitor upload result.[put setFinishBlock:^(id outputObject, NSError *error) {// You can obtain the etag or custom headers from the response in the outputObject.NSDictionary * result = (NSDictionary *)outputObject;}];[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
// Take a request for uploading files as an examplelet put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();let credential = QCloudCredential()// Temporary ID of the Secret Keycredential.secretID = "secretID"// Key of the Temporary Secretcredential.secretKey = "secretKey"// Token of the Temporary Secretcredential.token = "token"// Set temporary keys.put.credential = credential// Bucket name, composed of BucketName-Appid, can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.put.bucket = "examplebucket-1250000000";// Object Key is the full path of the object on COS. If including directories, the format is "video/xxx/movie.mp4".put.object = "exampleobject";// The content of the object to be uploaded. You can pass a variable of type NSData* or NSURL*.put.body = NSURL.fileURL(withPath: "Local File Path") as AnyObject;// Monitor upload result.put.setFinish { (result, error) in// Obtain the upload resultif error != nil{print(error!);}else{print(result!);}}// Monitor upload progress.put.sendProcessBlock = { (bytesSent, totalBytesSent,totalBytesExpectedToSend) in// bytesSent Number of bytes to be sent this time (a large file may be sent in multiple times).// totalBytesSent Bytes sent// totalBytesExpectedToSend Total bytes expected to be sent in this upload (that is, the file size)};// Set upload parameters.put.initMultipleUploadFinishBlock = {(multipleUploadInitResult, resumeData) in// After the initialization of multipart upload is completed, this block will be called back, where you can obtain the resumeData// and can generate a request for multipart upload using resumeDatalet resumeUploadRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>.init(request: resumeData as Data?);}QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
//AppDelegate.m//AppDelegate needs to conform to QCloudSignatureProvider@interface AppDelegate()<QCloudSignatureProvider>@end@implementation AppDelegate- (BOOL)application:(UIApplication * )applicationdidFinishLaunchingWithOptions:(NSDictionary * )launchOptions {QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];endpoint.regionName = @"COS_REGION";endpoint.useHTTPS = true;configuration.endpoint = endpoint;// Set delegation of key callbackconfiguration.signatureProvider = self;[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];return YES;}// Delegate method for key callback- (void)signatureWithFields:(QCloudSignatureFields*)filedsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{/*** Obtain the secret key here. If using a permanent secret key, it can be ignored.* ...*//*** Here, it can be either temporary keys or permanent keys.* To obtain temporary secret keys, see: https://www.tencentcloud.com/document/product/436/14048* Note: Permanent keys must not be used in production environments and are intended for debugging purposes only.*/QCloudCredential* credential = [QCloudCredential new];// Secret key SecretIdcredential.secretID = @"SECRETID";// Secret Key SecretKeycredential.secretKey = @"SECRETKEY";// Token for Secret Key (not required for permanent keys; required for temporary keys)credential.token = @"TOKEN";// It is strongly recommended to return the server time as the start time of the signature to avoid invalid signatures caused by significant deviations in the user's device local time (parameters startTime and expiredTime are in seconds).credential.startDate = [NSDate dateWithTimeIntervalSince1970:startTime]; // Unit is secondscredential.expirationDate = [NSDate dateWithTimeIntervalSince1970:expiredTime]];// Unit is seconds.QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]initWithCredential:credential];// In the SDK, by default, all Headers below are included in the signature and do not need to be set.// To exclude a specific Header from the signature, remove it from the array below and assign the updated array to shouldSignedList.// creator.shouldSignedList = @[@"Cache-Control", @"Content-Disposition", @"Content-Encoding", @"Content-Length", @"Content-MD5", @"Content-Type", @"Expect", @"Expires", @"If-Match" , @"If-Modified-Since" , @"If-None-Match" , @"If-Unmodified-Since" , @"Origin" , @"Range" , @"transfer-encoding" ,@"Host",@"Pic-Operations",@"ci-process"];// Note: Do not perform copy or mutableCopy operations on urlRequst hereQCloudSignature *signature = [creator signatureForData:urlRequst];continueBlock(signature, nil);}@end
//AppDelegate.swift//AppDelegate needs to conform to QCloudSignatureProviderclass AppDelegate: UIResponder, UIApplicationDelegate,QCloudSignatureProvider {func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {let config = QCloudServiceConfiguration.init();let endpoint = QCloudCOSXMLEndPoint.init();endpoint.regionName = "COS_REGION";endpoint.useHTTPS = true;config.endpoint = endpoint;// Set delegate for key callbackconfig.signatureProvider = self;QCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);return true}// Delegate method for key callbackfunc signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {/*** Obtain the secret key here. If using a permanent secret key, it can be ignored.* ...*//*** Here, it can be either temporary keys or permanent keys.* To obtain temporary secret keys, see: https://www.tencentcloud.com/document/product/436/14048.* Note: Permanent keys must not be used in production environments and are intended for debugging purposes only.*/let credential = QCloudCredential.init();// SecretId for Secret Keycredential.secretID = "SECRETID";// SecretKey for Secret Keycredential.secretKey = "SECRETKEY";// Token for Secret Key (not required for permanent keys; required for temporary keys)credential.token = "TOKEN";// It is strongly recommended to return the server time as the start time of the signature to avoid invalid signatures caused by significant deviations in the user's device local time (parameters startTime and expiredTime are in seconds).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 copy or mutableCopy operations on urlRequst here.let signature = creator?.signature(forData: urlRequst);continueBlock(signature,nil);}}
import SwiftUIimport QCloudCOSXML@mainstruct SwiftUIDemoApp: App {init() {// Call SDK configuration during application initialization.COSManager.shared.setupCOSSDK();}var body: some Scene {WindowGroup {ContentView()}}}// COSManager needs to conform to QCloudSignatureProvider.class COSManager: NSObject, QCloudSignatureProvider {static let shared = COSManager()private override init() {}func setupCOSSDK() {let config = QCloudServiceConfiguration.init();let endpoint = QCloudCOSXMLEndPoint.init();endpoint.regionName = "COS_REGION";endpoint.useHTTPS = true;config.endpoint = endpoint;config.signatureProvider = self;QCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);}// Delegate method for key callbackfunc signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {/*** Obtain the secret key here. If using a permanent secret key, it can be ignored.* ...*//*** Here, it can be either temporary keys or permanent keys.* To obtain temporary secret keys, see: https://www.tencentcloud.com/document/product/436/14048.* Note: Permanent keys must not be used in production environments and are intended for debugging purposes only.*/let credential = QCloudCredential.init();// SecretId for Secret Keycredential.secretID = "SECRETID";// SecretKey for Secret Keycredential.secretKey = "SECRETKEY";// Token for Secret Key (not required for permanent keys; required for temporary keys)credential.token = "TOKEN";// It is strongly recommended to return the server time as the start time of the signature to avoid invalid signatures caused by significant deviations in the user's device local time (parameters startTime and expiredTime are in seconds).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 copy or mutableCopy operations on urlRequst here.let signature = creator?.signature(forData: urlRequst);continueBlock(signature,nil);}}
// AppDelegate needs to conform to QCloudCredentailFenceQueueDelegate.@interface AppDelegate () <QCloudSignatureProvider, QCloudCredentailFenceQueueDelegate>// The object that controls the fence mechanism@property (nonatomic, strong) QCloudCredentailFenceQueue *credentialFenceQueue;@end@implementation AppDelegate- (BOOL)application:(UIApplication * )applicationdidFinishLaunchingWithOptions:(NSDictionary * )launchOptions {// ... Process related to SDK initialization is omitted here.self.credentialFenceQueue = [QCloudCredentailFenceQueue new];// Set the delegate object for the fence mechanismself.credentialFenceQueue.delegate = self;return YES;}// The delegate for key callback needs to use the fence object to retrieve signatures- (void)signatureWithFields:(QCloudSignatureFields *)filedsrequest:(QCloudBizHTTPRequest *)requesturlRequest:(NSMutableURLRequest *)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock {[self.credentialFenceQueue performAction:^(QCloudAuthentationCreator *creator, NSError *error) {if (error) {continueBlock(nil, error);} else {QCloudSignature *signature = [creator signatureForData:urlRequst];continueBlock(signature, nil);}}];}// Obtaining the secret key in the callback delegate of the fence mechanism.- (void)fenceQueue:(QCloudCredentailFenceQueue *)queue requestCreatorWithContinue:(QCloudCredentailFenceQueueContinue)continueBlock {[[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:@"http://******"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {// Request temporary keys from the interface for business services.NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingTopLevelDictionaryAssumed error:nil];NSDictionary * credentials = dic[@"credentials"];QCloudCredential *credential = [QCloudCredential new];credential.secretID = credentials[@"tmpSecretId"];credential.secretKey = credentials[@"tmpSecretKey"];;credential.token = credentials[@"sessionToken"];;// Expiration time of the signaturecredential.expirationDate = nil;credential.startDate = nil;QCloudAuthentationV5Creator *creator = [[QCloudAuthentationV5Creator alloc] initWithCredential:credential];continueBlock(creator, nil);}] resume];}@end
import UIKitimport QCloudCOSXML@mainclass AppDelegate: UIResponder, UIApplicationDelegate, QCloudSignatureProvider, QCloudCredentailFenceQueueDelegate {var window: UIWindow?var credentialFenceQueue: QCloudCredentailFenceQueue!func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {// ... Process related to SDK initialization is omitted here.credentialFenceQueue = QCloudCredentailFenceQueue()credentialFenceQueue.delegate = selfreturn true}// MARK: - QCloudSignatureProviderfunc signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {credentialFenceQueue.performAction { (creator: QCloudAuthentationCreator?, error: Error?) inif let error = error {continueBlock(nil, error)} else if let creator = creator {let signature = creator.signature(for: urlRequst)continueBlock(signature, nil)}}}// MARK: - QCloudCredentailFenceQueueDelegatefunc fenceQueue(_ queue: QCloudCredentailFenceQueue!, requestCreatorWithContinue continueBlock: QCloudCredentailFenceQueueContinue!) {// Construct the URL for requesting temporary keys (please replace with your actual server address).guard let url = URL(string: "http://******") else {// Handle failure of URL constructionlet error = NSError(domain: "AppDelegate", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL for temporary key"])continueBlock(nil, error)return}let task = URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in// Handle network errors.if let error = error {continueBlock(nil, error)return}// Ensure data exists.guard let data = data else {let error = NSError(domain: "AppDelegate", code: -2, userInfo: [NSLocalizedDescriptionKey: "No data received from server"])continueBlock(nil, error)return}do {// Parse JSON data.if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],let credentials = json["credentials"] as? [String: Any],let tmpSecretId = credentials["tmpSecretId"] as? String,let tmpSecretKey = credentials["tmpSecretKey"] as? String,let sessionToken = credentials["sessionToken"] as? String {// Create a QCloudCredential object and set temporary keys.let credential = QCloudCredential()credential.secretID = tmpSecretIdcredential.secretKey = tmpSecretKeycredential.token = sessionToken// If the server returns startTime and expiredTime, it is recommended to set them.// credential.startDate = Date(timeIntervalSince1970: startTime)// credential.expirationDate = Date(timeIntervalSince1970: expiredTime)let creator = QCloudAuthentationV5Creator(credential: credential)continueBlock(creator, nil)} else {// JSON parsing failed or key missing.let error = NSError(domain: "AppDelegate", code: -3, userInfo: [NSLocalizedDescriptionKey: "Failed to parse temporary key response"])continueBlock(nil, error)}} catch {// JSON parsing exceptioncontinueBlock(nil, error)}}task.resume() // Start the network task.}}
import SwiftUIimport QCloudCOSXML@mainstruct SwiftUIDemoApp: App {init() {// Call SDK configuration during application initialization.COSManager.shared.setupCOSSDK();}var body: some Scene {WindowGroup {ContentView()}}}class COSManager: NSObject, QCloudSignatureProvider, QCloudCredentailFenceQueueDelegate{static let shared = COSManager()private let credentialFenceQueue = QCloudCredentailFenceQueue()private override init() {}func setupCOSSDK() {// ... SDK initialization process omitted for brevitycredentialFenceQueue.delegate = self}// MARK: - QCloudSignatureProviderfunc signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {credentialFenceQueue.performAction { (creator: QCloudAuthentationCreator?, error: Error?) inif let error = error {continueBlock(nil, error)} else if let creator = creator {let signature = creator.signature(for: urlRequst)continueBlock(signature, nil)}}}// MARK: - QCloudCredentailFenceQueueDelegatefunc fenceQueue(_ queue: QCloudCredentailFenceQueue!, requestCreatorWithContinue continueBlock: QCloudCredentailFenceQueueContinue!) {// Construct the URL for requesting temporary keys (please replace with your actual server address).guard let url = URL(string: "http://******") else {// Handle failure of URL constructionlet error = NSError(domain: "AppDelegate", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL for temporary key"])continueBlock(nil, error)return}let task = URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in// Handle network errors.if let error = error {continueBlock(nil, error)return}// Ensure data exists.guard let data = data else {let error = NSError(domain: "AppDelegate", code: -2, userInfo: [NSLocalizedDescriptionKey: "No data received from server"])continueBlock(nil, error)return}do {// Parse JSON data.if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],let credentials = json["credentials"] as? [String: Any],let tmpSecretId = credentials["tmpSecretId"] as? String,let tmpSecretKey = credentials["tmpSecretKey"] as? String,let sessionToken = credentials["sessionToken"] as? String {// Create a QCloudCredential object and set temporary keys.let credential = QCloudCredential()credential.secretID = tmpSecretIdcredential.secretKey = tmpSecretKeycredential.token = sessionToken// If the server returns startTime and expiredTime, it is recommended to set them.// credential.startDate = Date(timeIntervalSince1970: startTime)// credential.expirationDate = Date(timeIntervalSince1970: expiredTime)let creator = QCloudAuthentationV5Creator(credential: credential)continueBlock(creator, nil)} else {// JSON parsing failed or key missing.let error = NSError(domain: "AppDelegate", code: -3, userInfo: [NSLocalizedDescriptionKey: "Failed to parse temporary key response"])continueBlock(nil, error)}} catch {// JSON parsing exceptioncontinueBlock(nil, error)}}task.resume() // Start the network task.}}
//AppDelegate.m//AppDelegate needs to conform to QCloudSignatureProvider@interface AppDelegate()<QCloudSignatureProvider>@end@implementation AppDelegate- (BOOL)application:(UIApplication * )applicationdidFinishLaunchingWithOptions:(NSDictionary * )launchOptions {QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];// Replace with the user's region. The region to which the created bucket belongs can be viewed in the console at https://console.tencentcloud.com/cos5/bucket.// For a list of all regions supported by COS, see https://www.qcloud.com/document/product/436/6224.endpoint.regionName = @"COS_REGION";// Use HTTPS.endpoint.useHTTPS = true;configuration.endpoint = endpoint;// The provider of the secret key is selfconfiguration.signatureProvider = self;// Initialize an Example of COS Service[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];return YES;}- (void)signatureWithFields:(QCloudSignatureFields*)filedsrequest:(QCloudBizHTTPRequest*)requesturlRequest:(NSMutableURLRequest*)urlRequstcompelete:(QCloudHTTPAuthentationContinueBlock)continueBlock{// Time of signature expirationNSDate *expiration = [[[NSDateFormatter alloc] init]dateFromString:@"expiredTime"];QCloudSignature *signature = [[QCloudSignature alloc] initWithSignature:@"signature calculated in the background" expiration:expiration];signature.token = @"Temporary Key Token";// Permanent Key does not need Token.continueBlock(signature, nil);}@end
//AppDelegate.swift//AppDelegate needs to conform to QCloudSignatureProviderclass AppDelegate: UIResponder, UIApplicationDelegate,QCloudSignatureProvider {func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {let config = QCloudServiceConfiguration.init();let endpoint = QCloudCOSXMLEndPoint.init();// Replace with the user's region. The region to which the created bucket belongs can be viewed in the console at https://console.tencentcloud.com/cos5/bucket.// For a list of all regions supported by COS, see https://www.qcloud.com/document/product/436/6224.endpoint.regionName = "COS_REGION";// Use HTTPS.endpoint.useHTTPS = true;config.endpoint = endpoint;// The provider of the secret key is selfconfig.signatureProvider = self;// Initialize an Example of COS ServiceQCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);return true}func signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {// Time of signature expirationlet expiration = DateFormatter().date(from: "expiredTime");let signature = QCloudSignature.init(signature: "signature calculated in the backend",expiration: expiration);signature.token = "Temporary Key Token";// Permanent Key does not need Token.continueBlock(signature,nil);}}
import SwiftUIimport QCloudCOSXML@mainstruct SwiftUIDemoApp: App {init() {// Call SDK configuration during application initialization.COSManager.shared.setupCOSSDK();}var body: some Scene {WindowGroup {ContentView()}}}class COSManager: NSObject, QCloudSignatureProvider {static let shared = COSManager()private override init() {}func setupCOSSDK() {let config = QCloudServiceConfiguration.init();let endpoint = QCloudCOSXMLEndPoint.init();// Replace with the user's region. The region to which the created bucket belongs can be viewed in the console at https://console.tencentcloud.com/cos5/bucket.// For a list of all regions supported by COS, see https://www.qcloud.com/document/product/436/6224.endpoint.regionName = "COS_REGION";// Use HTTPS.endpoint.useHTTPS = true;config.endpoint = endpoint;config.signatureProvider = self;// Initialize an Example of COS ServiceQCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);}// The entry point for obtaining the signature. This demonstrates the process of acquiring a temporary key and calculating the signature.// You can also customize the process of calculating the signature.func signature(with fileds: QCloudSignatureFields!,request: QCloudBizHTTPRequest!,urlRequest urlRequst: NSMutableURLRequest!,compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {// Time of signature expirationlet expiration = DateFormatter().date(from: "expiredTime");let signature = QCloudSignature.init(signature: "signature calculated in the backend",expiration: expiration);signature.token = "Token of the Temporary Key";// Permanent Key does not need TokencontinueBlock(signature,nil);}}
NSString *customDomain = @"exampledomain.com"; // Custom domain for the origin or Global Accelerate domainQCloudCOSXMLEndPoint *endpoint = [[QCloudCOSXMLEndPoint alloc] initWithLiteralURL:[NSURL URLWithString:customDomain]];QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];// Replace with the user's region. The host region of created buckets can be viewed in the console: https://console.tencentcloud.com/cos5/bucket.// For a list of all regions supported by COS, see https://www.qcloud.com/document/product/436/6224.// Use HTTPS.endpoint.regionName = @"COS_REGION";endpoint.useHTTPS = true;configuration.endpoint = endpoint;// Initialize a sample of the COS service[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];
let endpoint = QCloudCOSXMLEndPoint.init(literalURL: NSURL.init(string: "exampledomain.com") as URL?);let config = QCloudServiceConfiguration.init();// Replace with the user's region. The host region of created buckets can be viewed in the console: https://console.tencentcloud.com/cos5/bucket.// For a list of all regions supported by COS, see https://www.qcloud.com/document/product/436/6224.// Use HTTPS.endpoint.useHTTPS = true;endpoint.regionName = "COS_REGION";config.endpoint = endpoint;// Initialize a sample of the COS serviceQCloudCOSXMLService.registerDefaultCOSXML(with: config);QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(with: config);
// Set concurrency count to 4.[QCloudHTTPSessionManager shareClient].customConcurrentCount = 4;// Set automatic upper limit to 8.[QCloudHTTPSessionManager shareClient].maxConcurrencyTask = 8;
// Set concurrency number to 4QCloudHTTPSessionManager.shareClient.customConcurrentCount = 4;// Set automatic upper limit to 8.QCloudHTTPSessionManager.shareClient.maxConcurrencyTask = 8;
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];// Local file pathNSURL* url = [NSURL fileURLWithPath:@"URL of the file"];// Bucket name, composed of BucketName-Appid, can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.put.bucket = @"examplebucket-1250000000";// Object Key is the full path of the object on COS. If including directories, the format is "video/xxx/movie.mp4".put.object = @"exampleobject";// The content of the object to be uploaded. You can pass a variable of type NSData* or NSURL*.put.body = url;// Monitor upload progress.[put setSendProcessBlock:^(int64_t bytesSent,int64_t totalBytesSent,int64_t totalBytesExpectedToSend) {// bytesSent Number of bytes to be sent this time (a large file may be sent in multiple times).// totalBytesSent Bytes sent// totalBytesExpectedToSend Total bytes expected to be sent in this upload (that is, the file size)}];// Monitor upload result.[put setFinishBlock:^(id outputObject, NSError *error) {// You can obtain the etag or custom headers from the response in the outputObject.NSDictionary * result = (NSDictionary *)outputObject;}];[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();// Bucket name, composed of BucketName-Appid, can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.put.bucket = "examplebucket-1250000000";// Object Key is the full path of the object on COS. If including directories, the format is "video/xxx/movie.mp4".put.object = "exampleobject";// The content of the object to be uploaded. You can pass a variable of type NSData* or NSURL*.put.body = NSURL.fileURL(withPath: "Local File Path") as AnyObject;// Monitor upload result.put.setFinish { (result, error) in// Obtain the upload resultif error != nil{print(error!);}else{print(result!);}}// Monitor upload progress.put.sendProcessBlock = { (bytesSent, totalBytesSent,totalBytesExpectedToSend) in// bytesSent Number of bytes to be sent this time (a large file may be sent in multiple times).// totalBytesSent Bytes sent// totalBytesExpectedToSend Total bytes expected to be sent in this upload (that is, the file size)};// Set upload parameters.put.initMultipleUploadFinishBlock = {(multipleUploadInitResult, resumeData) in// After the initialization of multipart upload is completed, this block will be called back, where you can obtain the resumeData// and can generate a request for multipart upload using resumeDatalet resumeUploadRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>.init(request: resumeData as Data?);}QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
QCloudCOSXMLDownloadObjectRequest * request = [QCloudCOSXMLDownloadObjectRequest new];// Bucket name, composed of BucketName-Appid, can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.request.bucket = @"examplebucket-1250000000";// Object Key is the full path of the object on COS. If including directories, the format is "video/xxx/movie.mp4".request.object = @"exampleobject";//Set the URL for the download path. If the path is set, the file will be downloaded to the specified pathrequest.downloadingURL = [NSURL fileURLWithPath:@"Local File Path"];// Monitor download results.[request setFinishBlock:^(id outputObject, NSError *error) {// outputObject contains all the HTTP response headersNSDictionary* info = (NSDictionary *) outputObject;}];// Monitor download progress.[request setDownProcessBlock:^(int64_t bytesDownload,int64_t totalBytesDownload,int64_t totalBytesExpectedToDownload) {// bytesDownload Number of bytes to be downloaded this time (a large file may be transmitted in multiple parts)// totalBytesDownload Number of bytes downloaded// totalBytesExpectedToDownload Total number of bytes expected to be downloaded (that is, the file size).}];[[QCloudCOSTransferMangerService defaultCOSTransferManager] DownloadObject:request];
let request : QCloudCOSXMLDownloadObjectRequest = QCloudCOSXMLDownloadObjectRequest();// Bucket name, composed of BucketName-Appid, can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.request.bucket = "examplebucket-1250000000";// Object Keyrequest.object = "exampleobject";//Set the URL for the download path. If the path is set, the file will be downloaded to the specified pathrequest.downloadingURL = NSURL.fileURL(withPath: "Local File Path") as URL?;// Monitor download progress.request.downProcessBlock = { (bytesDownload, totalBytesDownload,totalBytesExpectedToDownload) in// bytesDownload Number of bytes to be downloaded this time (a large file may be transmitted in multiple parts).// totalBytesDownload Number of bytes downloaded// totalBytesExpectedToDownload Total number of bytes expected to be downloaded (that is, the file size).}// Monitor download results.request.finishBlock = { (copyResult, error) inif error != nil{print(error!);}else{print(copyResult!);}}QCloudCOSTransferMangerService.defaultCOSTransferManager().downloadObject(request);
Feedback