Resources
Download the iOS SDK source code here. Note:
If you encounter errors such as non-existent functions or methods when using the XML version of the SDK, please update the SDK to the latest version and try again.
Preparations
1. Prepare an iOS application; this can be an existing project or a new empty project.
2. Make sure that the application is built using an SDK running on iOS 8.0 or above.
3. You need a remote address where users can obtain your Tencent Cloud temporary key. For more information on temporary keys, see Direct Upload for Mobile Apps. Step 1. Install the SDK
Method 1: Integration using CocoaPods (recommended)
Standard SDK
Add the following content to the Podfile
of your project:
Simplified SDK
If you only need to perform upload and download operations and want a smaller sized SDK, you can use the simplified version.
The simplified SDK is implemented through the CocoaPods subspec feature, so it currently can only be integrated automatically. Add the following content to the Podfile
of your project:
pod 'QCloudCOSXML/Transfer'
Method 2: Manually integrate
You can directly download the latest version of the SDK here or you can find all of the versions here. 1. Import binary libraries
Drag QCloudCOSXML.framework
, QCloudCore.framework
, BeaconAPI_Base.framework
, and QimeiSDK.framework
into the project.
Then, add the following dependent libraries:
CoreTelephony
Foundation
SystemConfiguration
libc++.tbd
Configure "Other Linker Flags" in "Build Settings" by adding this parameter:
Note:
The SDK provides a packaging script that supports self-packaging according to business requirements. (The packaging script depends on CocoaPods. Please make sure CocoaPods is installed in your development environment first.) The packaging procedure is as follows:
1. Download the source code: git clone https://github.com/tencentyun/qcloud-sdk-ios
.
2. Run the packaging script: source package.sh
.
3. Drag and drop the packaging result to the project and perform manual integration as described above.
iOS: drag and drop the packaging result in the ios
folder to the project.
macOS: drag and drop the packaging result in the osx
folder to the project.
Step 2. Begin Using the SDK
Objective-c
#import <QCloudCOSXML/QCloudCOSXML.h>
swift
For the simplified SDK, import the following:
Objective-c
#import <QCloudCOSXML/QCloudCOSXMLTransfer.h>
swift
import QCloudCOSXMLTransfer
2. Initialize the COS service and implement the signature protocol
Method 1: Obtaining a temporary key pair to authenticate requests (recommended)
The SDK needs to get a temporary key to calculate the signature before sending a request. Therefore, you need to implement the 'QCloudSignatureProvider' protocol to obtain the key and call back the key to the SDK through the 'continueBlock' parameter.
It is recommended to place the initialization process in 'AppDelegate' or application singleton.
For the detailed procedure, see the following sample code:
Objective-c
@interface AppDelegate()<QCloudSignatureProvider>
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication * )application
didFinishLaunchingWithOptions:(NSDictionary * )launchOptions {
QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];
QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];
endpoint.regionName = @"COS_REGION";
endpoint.useHTTPS = true;
configuration.endpoint = endpoint;
configuration.signatureProvider = self;
[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];
[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:
configuration];
return YES;
}
- (void) signatureWithFields:(QCloudSignatureFields*)fields
request:(QCloudBizHTTPRequest*)request
urlRequest:(NSMutableURLRequest*)urlRequst
compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock
{
QCloudCredential* credential = [QCloudCredential new];
credential.secretID = @"SECRETID";
credential.secretKey = @"SECRETKEY";
credential.token = @"TOKEN";
credential.startDate = [NSDate dateWithTimeIntervalSince1970:startTime];
credential.expirationDate = [NSDate dateWithTimeIntervalSince1970:expiredTime]];
QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]
initWithCredential:credential];
QCloudSignature *signature = [creator signatureForData:urlRequst];
continueBlock(signature, nil);
}
@end
Swift
class 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;
config.signatureProvider = self;
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();
credential.secretID = "SECRETID";
credential.secretKey = "SECRETKEY";
credential.token = "TOKEN";
credential.startDate = Date.init(timeIntervalSince1970: TimeInterval(startTime)!) DateFormatter().date(from: "startTime");
credential.expirationDate = Date.init(timeIntervalSince1970: TimeInterval(expiredTime)!)
let creator = QCloudAuthentationV5Creator.init(credential: credential);
let signature = creator?.signature(forData: urlRequst);
continueBlock(signature,nil);
}
}
Note:
APPID is a permanent unique application ID assigned to you after you sign up for a Tencent Cloud account. You can view your APPID on the Account Information page. SecretId and SecretKey, collectively referred to as the cloud API key, are the security credential used for authentication when a user accesses a Tencent Cloud API and can be viewed in Manage API Key of the console. SecretKey is the key used to encrypt the signature string and server-side authentication signature string, and SecretId identifies an API caller. Multiple cloud API keys can be created under an APPID. The SDK provides the 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.
Note:
The scaffolding tool determines whether a key can be reused based only on whether the key expiration time is later than the current device time. If you set up a complex policy when requesting a key, the scaffolding tool is not recommended.
It is recommended to place the initialization process in 'AppDelegate' or application singleton. You need to implement the following two protocols to use the scaffolding tool:
QCloudSignatureProvider
QCloudCredentailFenceQueueDelegate
The following is the sample code:
Objective-c
@interface AppDelegate()<QCloudSignatureProvider, QCloudCredentailFenceQueueDelegate>
@property (nonatomic) QCloudCredentailFenceQueue* credentialFenceQueue;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication * )application
didFinishLaunchingWithOptions:(NSDictionary * )launchOptions {
QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];
QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];
endpoint.regionName = @"COS_REGION";
endpoint.useHTTPS = true;
configuration.endpoint = endpoint;
configuration.signatureProvider = self;
[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];
credential.secretID = @"SECRETID";
credential.secretKey = @"SECRETKEY";
credential.token = @"TOKEN";
credential.startDate = [NSDate dateWithTimeIntervalSince1970:startTime];
credential.expirationDate = [NSDate dateWithTimeIntervalSince1970:expiredTime]];
QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]
initWithCredential:credential];
continueBlock(creator, nil);
}
- (void) signatureWithFields:(QCloudSignatureFields*)fields
request:(QCloudBizHTTPRequest*)request
urlRequest:(NSMutableURLRequest*)urlRequst
compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock
{
[self.credentialFenceQueue performAction:^(QCloudAuthentationCreator *creator,
NSError *error) {
if (error){
continueBlock(nil, error);
} else {
QCloudSignature* signature = [creator signatureForData:urlRequst];
continueBlock(signature, nil);
}
}];
}
@end
Swift
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();
endpoint.regionName = "COS_REGION";
endpoint.useHTTPS = true;
config.endpoint = endpoint;
config.signatureProvider = self;
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();
credential.secretID = "SECRETID";
credential.secretKey = "SECRETKEY";
credential.token = "TOKEN";
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) in
if error != nil {
continueBlock(nil,error!);
}else{
let signature = creator?.signature(forData: urlRequst);
continueBlock(signature,nil);
}
})
}
}
Note:
We recommend requesting data over HTTPS. However, if you want to use HTTP protocol, you need to enable HTTP transfer for your application so that it can run on iOS 9.0 or above. For detailed directions, see Apple's official documentation Preventing Insecure Network Connections. If your QCloudServiceConfiguration
has changed, you can register a new instance by using the following method:
+ (QCloudCOSTransferMangerService*) registerCOSTransferMangerWithConfiguration:(QCloudServiceConfig
Method 2: Using a permanent key for local debugging
You can use your Tencent Cloud permanent key for local debugging during the development phase. Since this method exposes the key to leakage risks, please be sure to replace it with a temporary key before launching your application.
When using a permanent key, you can choose not to implement the QCloudCredentailFenceQueueDelegate
protocol.
Objective-C
- (void) signatureWithFields:(QCloudSignatureFields*)fields
request:(QCloudBizHTTPRequest*)request
urlRequest:(NSMutableURLRequest*)urlRequst
compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock
{
QCloudCredential* credential = [QCloudCredential new];
credential.secretID = @"SECRETID";
credential.secretKey = @"SECRETKEY";
QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]
initWithCredential:credential];
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();
credential.secretID = "SECRETID";
credential.secretKey = "SECRETKEY";
let auth = QCloudAuthentationV5Creator.init(credential: credential);
let signature = auth?.signature(forData: urlRequst)
continueBlock(signature,nil);
}
Method 3: Using a backend-calculated signature to authenticate requests
When the signature is generated on the backend, you can choose not to implement the QCloudCredentailFenceQueueDelegate
protocol
Objective-C
- (void) signatureWithFields:(QCloudSignatureFields*)fields
request:(QCloudBizHTTPRequest*)request
urlRequest:(NSMutableURLRequest*)urlRequst
compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock
{
NSDate *expiration = [[[NSDateFormatter alloc] init]
dateFromString:@"expiredTime"];
QCloudSignature *sign = [[QCloudSignature alloc] initWithSignature:
@"Signature calculated on backend" expiration:expiration];
continueBlock(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: "signature calculated on backend",
expiration: expiration);
continueBlock(signature,nil);
}
Step 3. Access COS
Uploading an object
The SDK allows you to upload local files and binary data in NSData format. The following uses local file upload as an example:
Objective-C
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
NSURL* url = [NSURL fileURLWithPath:@"file URL"];
put.bucket = @"examplebucket-1250000000";
put.object = @"exampleobject";
put.body = url;
[put setSendProcessBlock:^(int64_t bytesSent,
int64_t totalBytesSent,
int64_t totalBytesExpectedToSend) {
}];
[put setFinishBlock:^(id outputObject, NSError *error) {
NSDictionary * result = (NSDictionary *)outputObject;
}];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
Note:
For the complete sample, go to GitHub. You can generate a download URL for the uploaded file using the same key. For detailed directions, see Generating a Pre-Signed Link. Please note that for private-read files, the download URL is only valid for a limited period of time. Swift
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();
put.bucket = "examplebucket-1250000000";
put.object = "exampleobject";
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
};
put.initMultipleUploadFinishBlock = {(multipleUploadInitResult, resumeData) in
let resumeUploadRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>
.init(request: resumeData as Data?);
}
QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
Note:
For the complete sample, go to GitHub. You can generate a download URL for the uploaded file using the same key. For detailed directions, see Generating a Pre-Signed Link. Please note that for private-read files, the download URL is only valid for a limited period of time. Downloading an object
Objective-C
QCloudCOSXMLDownloadObjectRequest * request = [QCloudCOSXMLDownloadObjectRequest new];
request.bucket = @"examplebucket-1250000000";
request.object = @"exampleobject";
request.downloadingURL = [NSURL fileURLWithPath:@"Local File Path"];
[request setFinishBlock:^(id outputObject, NSError *error) {
NSDictionary* info = (NSDictionary *) outputObject;
}];
[request setDownProcessBlock:^(int64_t bytesDownload,
int64_t totalBytesDownload,
int64_t totalBytesExpectedToDownload) {
}];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] DownloadObject:request];
Note:
For the complete sample, please go to GitHub. Swift
let request : QCloudCOSXMLDownloadObjectRequest = QCloudCOSXMLDownloadObjectRequest();
request.bucket = "examplebucket-1250000000";
request.object = "exampleobject";
request.downloadingURL = NSURL.fileURL(withPath: "Local File Path") as URL?;
request.sendProcessBlock = { (bytesDownload, totalBytesDownload,
totalBytesExpectedToDownload) in
}
request.finishBlock = { (copyResult, error) in
if error != nil{
print(error!);
}else{
print(copyResult!);
}
}
QCloudCOSTransferMangerService.defaultCOSTransferManager().downloadObject(request);
Note:
For the complete sample, please go to GitHub.
Apakah halaman ini membantu?