Initialization
Quick Start
-
Initialize the BOSClient.
A BOSClient is the interface for interacting with the BOS service. All BOS operations in the BOS iOS SDK are executed through the BOSClient.
Create a new BOSClient with STS authentication:
Example code:
Swift1BCESTSCredentials* credentials = [[BCESTSCredentials alloc] init]; 2 // access key and secret key represent AKSK respectively. 3 credentials.accessKey = @"<access key>"; // Temporarily returned AK 4 credentials.secretKey = @"<secret key>"; // Temporarily returned SK 5 credentials.sessionToken = @"<session token>"; // Temporarily returned SessionToken 6BOSClientConfiguration* configuration = [[BOSClientConfiguration alloc] init]; 7configuration.credentials = credentials; 8BOSClient* client = [[BOSClient alloc] initWithConfiguration:configuration]; -
Create a bucket.
A bucket is a namespace in BOS that serves as a container for data and can hold multiple data entities (objects). You must create a bucket before uploading data.
Example code:
Swift1BCETask* task = [client putBucket:@"<bucketName>"]; 2// Tasks can be executed asynchronously. 3task.then(^(BCEOutput* output) { 4// Task execution results can be checked within the block. 5 if (output.response) { 6// Task executed successfully. 7 } 8 if (output.error) { 9// Task execution failed. 10 } 11 if (output.progress) { 12// Task execution progress. 13 } 14}); 15// You can wait synchronously until the task is finished. 16[task waitUtilFinished]; -
Upload an object.
An object is the fundamental data unit in BOS. You can think of an object as a file.
Example code:
Swift1BOSObjectContent* content = [[BOSObjectContent alloc] init]; 2// Set one of the following two lines. 3content.objectData.file = @"<FilePath>"; 4content.objectData.data = <NSData object>; 5BOSPutObjectRequest* request = [[BOSPutObjectRequest alloc] init]; 6request.bucket = @"<bucketname>"; 7request.key = @"<ObjectName>"; 8request.objectContent = content; 9__block BOSPutObjectResponse* response; 10BCETask* task = [client putObject:request]; 11task.then(^(BCEOutput* output) { 12 if (output.progress) { 13// Print progress 14 NSLog(@"put object progress is %@", output.progress); 15 } 16 if (output.response) { 17 response = (BOSPutObjectResponse*)output.response; 18// Print eTag 19 NSLog(@"The eTag is %@", response.metadata.eTag); 20 } 21 if (output.error) { 22 NSLog(@"put object failure with %@", output.error); 23 } 24}); 25[task waitUtilFinished]; -
View the list of objects within a bucket.
Once you've finished uploading a series of files, use the following code to list all objects within the bucket.
Example code:
Swift1// Obtain all object information under the specified bucket 2BOSListObjectsRequest* request = [[BOSListObjectsRequest alloc] init]; 3request.bucket = @"<bucketname>"; 4__block BOSListObjectsResponse* response = nil; 5BCETask* task = [client listObjects:request]; 6task.then(^(BCEOutput* output) { 7 if (output.response) { 8 response = (BOSListObjectsResponse*)output.response; 9 for (BOSObjectInfo* object in response.contents) { 10 NSLog(@"The object key is %@", object.key); 11 } 12 } 13 if (output.error) { 14 NSLog(@"list objects failure with %@", output.error); 15 } 16}); -
Get the specified object.
Refer to the code below to fetch one or multiple objects.
Example code:
Swift1BOSGetObjectRequest* request = [[BOSGetObjectRequest alloc] init]; 2request.bucket = @"<bucketname>"; 3request.key = @"<Objectname>"; 4request.file = @"<filename>"; 5__block BOSGetObjectResponse* response = nil; 6BCETask* task = [self.client getObject:request]; 7task.then(^(BCEOutput* output) { 8 // ... 9});
Complete example
1#import <BaiduBCEBasic/BaiduBCEBasic.h>
2#import <BaiduBCEBOS/BaiduBCEBOS.h>
3void example(void) {
4// Initialize a BOSClient with STS authentication
5 BOSClient* client = [[BOSClient alloc] initWithConfiguration:configuration];
6 BCESTSCredentials* credentials = [[BCESTSCredentials alloc] init];
7// access key and secret key represent AKSK respectively.
8credentials.accessKey = @"<access key>"; // Temporarily returned AK
9credentials.secretKey = @"<secret key>"; // Temporarily returned SK
10credentials.sessionToken = @"<session token>"; // Temporarily returned SessionToken
11 BOSClientConfiguration* configuration = [[BOSClientConfiguration alloc] init];
12 configuration.credentials = credentials;
13 BOSClient* client = [[BOSClient alloc] initWithConfiguration:configuration];
14// 1. Create bucket
15BCETask* task = [client putBucket:@"<bucketName>"];
16task.then(^(BCEOutput* output) { // Tasks can be executed asynchronously.
17 if (output.response) {
18// Task executed successfully.
19 }
20 if (output.error) {
21// Task execution failed.
22 }
23 if (output.progress) {
24// Task execution progress.
25 }
26});
27[task waitUtilFinished]; // You can wait synchronously until the task is finished.
28// 2. Upload object
29BOSObjectContent* content = [[BOSObjectContent alloc] init];
30content.objectData.file = @"<FilePath>";
31BOSPutObjectRequest* request = [[BOSPutObjectRequest alloc] init];
32request.bucket = @"<bucketname>";
33request.key = @"<Objectname>";
34request.objectContent = content;
35__block BOSPutObjectResponse* response = nil;
36task = [client putObject:request];
37task.then(^(BCEOutput* output) {
38 if (output.progress) {
39// Print progress
40 NSLog(@"put object progress is %@", output.progress);
41 }
42 if (output.response) {
43 response = (BOSPutObjectResponse*)output.response;
44// Print eTag
45 NSLog(@"The eTag is %@", response.metadata.eTag);
46 }
47 if (output.error) {
48 NSLog(@"put object failure with %@", output.error);
49 }
50});
51[task waitUtilFinished];
52// 3. View object
53BOSListObjectsRequest* listRequest = [[BOSListObjectsRequest alloc] init];
54listRequest.bucket = @"<bucketname>";
55__block BOSListObjectsResponse* listRepsponse = nil;
56task = [client listObjects:listRequest];
57task.then(^(BCEOutput* output) {
58 if (output.response) {
59 listRepsponse = (BOSListObjectsResponse*)output.response;
60 for (BOSObjectInfo* object in listRepsponse.contents) {
61 NSLog(@"The object key is %@", object.key);
62 }
63 }
64 if (output.error) {
65 NSLog(@"list objects failure with %@", output.error);
66 }
67});
68[task waitUtilFinished];
69// 4. Download object
70BOSGetObjectRequest* getRequest = [[BOSGetObjectRequest alloc] init];
71getRequest.bucket = @"<bucketname>";
72getRequest.key = @"<Objectname>";
73getRequest.file = @"<file>";
74__block BOSGetObjectResponse* getResponse = nil;
75task = [client getObject:getRequest];
76task.then(^(BCEOutput* output) {
77 if (output.response) {
78 getResponse = (BOSGetObjectResponse*)output.response;
79 }
80 if (output.error) {
81 NSLog(@"get object failure with %@", output.error);
82 }
83});
84[task waitUtilFinished];
85}
Create a new BOSClient with STS authentication
The BOSClient acts as the client for BOS services, offering developers a variety of methods to interact with BOS features. Before making any SDK requests to BOS, you must initialize a BOSClient instance and set up the required configurations.
Note: iOS SDK is primarily used for mobile development scenarios. Mobile an untrusted environment, and there is a high risk of directly saving AAccessKey and SecretKey in the terminal for signing requests. It is recommended to use the STS authentication mode. For detailed introduction to STS, please refer to [Temporary Authorization Access](BOS/API Reference/Access control.md#Temporary authorized access).
When using the STS method, you need to first create a BOSClient with STS to execute when calling the API. For the BOS APIs currently supported by the STS method, please refer to STS Service APIs.
-
Example code:
Swift1BCESTSCredentials* credentials = [[BCESTSCredentials alloc] init]; 2 credentials.accessKey = @"<access key>"; // Temporarily returned AK 3 credentials.secretKey = @"<secret key>"; // Temporarily returned SK 4 credentials.sessionToken = @"<session token>"; // Temporarily returned SessionToken 5BOSClientConfiguration* configuration = [[BOSClientConfiguration alloc] init]; 6 configuration.region = [BCERegion region:BCERegionBJ]; // Service region, BCERegionBJ for Beijing, BCERegionGZ for Guangzhou, BCERegionSU for Suzhou; the default is Beijing if not specified 7configuration.credentials = credentials; 8BOSClient* client = [[BOSClient alloc] initWithConfiguration:configuration];Plain Text1> 2> **Note:** 3> 4> - The `region` parameter can only be defined as the specified enumeration value; if not specified, the default is the Beijing region. Baidu AI Cloud currently supports multiple regions. Please refer to[Region Selection Guide](Reference/Region Selection Instructions/Region.md). 5> 6> - Currently, the regions open to the public on the BOS official website are supported. For specific domain names, please refer to [BOS region](https://cloud.baidu.com/doc/BOS/s/lk24fdmgt#region).
Create a new BOSClient with AKSK authentication
Creating a BOSClient with AKSK authentication is similar to the STS method described earlier.
-
Example code:
Swift1 BCECredentials* credentials = [[BCECredentials alloc] init]; 2 credentials.accessKey = @"AK"; 3 credentials.secretKey = @"SK"; 4 BOSClientConfiguration* configuration = [[BOSClientConfiguration alloc] init]; 5 configuration.credentials = credentials; 6 configuration.endpoint = @"http://bj.bcebos.com"; 7 BOSClient* client = [[BOSClient alloc] initWithConfiguration:configuration];
Configure HTTPS access to BOS
BOS supports HTTPS transport protocol. You can use HTTPS to access the BOS service in the BOS iOS SDK in the following ways:
1configuration.scheme = @"https";
Configure BOSClient
If you want to configure specific parameters for the BOSClient, you can pass a BOSClientConfiguration object when constructing the BOSClient. The BOSClientConfiguration class allows you to define essential network parameters for interacting with the BOS service.
Set network parameters
You can configure basic network parameters using the BOSClientConfiguration.
-
Example code
Swift1BOSClientConfiguration config = [[BOSClientConfiguration alloc] init]; 2 // Set maximum number of HTTP connections to 5 3config.maxConurrentConnection = 5; 4 // Set TCP connection timeout to 5 seconds 5config.connectionTimeout = 5; 6 // Set the maximum data transmission time for the request to 60 seconds 7config.totalTransferTimeout = 60; - Parameter description
The following parameters can be configured via BOSClientConfiguration:
| Parameters | Description |
|---|---|
| authVersion | The version of the authentication algorithm used, currently the default value is 1 |
| APIVersion | The version of the BOS API used, currently the default value is 1 |
| scheme | The HTTP protocol used, which can be http or https, with the default value being http |
| region | The region where the BOS service is used |
| endpoint | If the exact service address is known, you can directly set the endpoint without setting the scheme and region, etc. |
| allowsCellularAccess | Whether to allow the use of cellular networks, the default value is NO |
| connectionTimeout | Set the TCP connection timeout, the default value is 60 s |
| totalTransferTimeout | Set the maximum data transmission time for the request, in seconds, with the default value being 7 days |
| maxConurrentConnection | Specifies the maximum allowed HTTP connections. |
Configure the access domain name style
Starting from version 1.3.1, the SDK will automatically enable bucket virtual hosting by default.
path-style: ${region}.bcebos.com/${bucket}/${object}
virtual-hosted: {bucket}.${region}.bcebos.com/${object}
You can enable the endpoint using PathStyle through the following configuration:
1BOSClientConfiguration* configuration = [[BOSClientConfiguration alloc] init];
2configuration.isPathStyleAccessEnable = YES;
Note: Under some non-conventional BOS domain names, the default bucket virtual hosting style may have incompatibility issues, such as DNS resolution failures. This can be resolved by enabling PathStyle. It is recommended to use the default style in other scenarios.
