Baidu AI Cloud
中国站

百度智能云

Object Storage

Initialization

Getting Started

1.Initialize BOSClient.

BOSClient is a client of BOS service interaction, and all BOS operations of BOS iOS SDK are completed via BOSClient.

Sample code:

BCECredentials* credentials = [[BCECredentials alloc] init];
// Access key and secret key respectively represent AK SK.
credentials.accessKey = @"<access key>";
credentials.secretKey = @"<secret key>";

BOSClientConfiguration* configuration = [[BOSClientConfiguration alloc] init];
configuration.endpoint = @"https://bj.bcebos.com";
configuration.credentials = credentials;

BOSClient* client = [[BOSClient alloc] initWithConfiguration:configuration];

2.Create bucket.

Bucket is a namespace on BOS. It is equivalent to a container of data and can store several data entities (objects). Before uploading data, you must create a bucket.

Sample code:

BCETask* task = [client putBucket:@"<bucketName>"];

// Task can be executed asynchronously
task.then(^(BCEOutput* output) {
  // Result of task execution can be judged in block.
  if (output.response) {
      // Task executed successfully
  }

  if (output.error) {
      // Task execution failed 
  }

  if (output.progress) {
      // Task execution progress 
  }
});

// Synchronous mode can be used, until task is executed completely 
[task waitUtilFinished];

3.Upload object.

Object is the most basic data unit in BOS. You can understand object as a file.

Sample code:

BOSObjectContent* content = [[BOSObjectContent alloc] init];
// Set one type in the following 2 lines.
content.objectData.file = @"<FilePath>";
content.objectData.data = <NSData object>;

BOSPutObjectRequest* request = [[BOSPutObjectRequest alloc] init];
request.bucket = @"<bucketname>";
request.key = @"<ObjectName>";
request.objectContent = content;

__block BOSPutObjectResponse* response;
BCETask* task = [client putObject:request];
task.then(^(BCEOutput* output) {
    if (output.progress) {
        // Printing progress 
        NSLog(@"put object progress is %@", output.progress);
    }

    if (output.response) {
        response = (BOSPutObjectResponse*)output.response;
        // Print ETag.
        NSLog(@"The eTag is %@", response.metadata.eTag);
    }

    if (output.error) {
        NSLog(@"put object failure with %@", output.error);
    }
});

4.View the objects list under bucket.

After completing uploads, you can refer to the following code to view all objects under bucket.

Sample code:

// Access all object information of specified bucket
BOSListObjectsRequest* request = [[BOSListObjectsRequest alloc] init];
request.bucket = @"<bucketname>";

__block BOSListObjectsResponse* response = nil;
BCETask* task = [client listObjects:request];
task.then(^(BCEOutput* output) {
  if (output.response) {
      response = (BOSListObjectsResponse*)output.response;
      for (BOSObjectInfo* object in response.contents) {
         NSLog(@"The object key is %@", object.key);
      }
  }

  if (output.error) {
      NSLog(@"list objects failure with %@", output.error);
  }
});

5.Get the specified object.

You can refer to the following code to get one or more objects.

Sample code:

BOSGetObjectRequest* request = [[BOSGetObjectRequest alloc] init];
request.bucket = @"<bucketname>";
request.key = @"<Objectname>";
request.file = @"<filename>";

__block BOSGetObjectResponse* response = nil;
BCETask* task = [self.client getObject:request];
task.then(^(BCEOutput* output) {
    // ...
});

Complete Example

    #import <BaiduBCEBasic/BaiduBCEBasic.h>
    #import <BaiduBCEBOS/BaiduBCEBOS.h>

    void example(void) {
    // Initialization
    BCECredentials* credentials = [[BCECredentials alloc] init];
    credentials.accessKey = @"<access key>";
    credentials.secretKey = @"<secret key>";
    BOSClientConfiguration* configuration = [[BOSClientConfiguration alloc] init];
    configuration.credentials = credentials;

    BOSClient* client = [[BOSClient alloc] initWithConfiguration:configuration];

    // 1.Create bucket
    BCETask* task = [client putBucket:@"<bucketName>"];
    task.then(^(BCEOutput* output) { // Task can be executed asynchronously 
        if (output.response) {
            // Task executed successfully
        }

        if (output.error) {
            // Task execution failed 
        }

        if (output.progress) {
            // Task execution progress 
        }
    });
    [task waitUtilFinished]; // Synchronous mode can be used, until task is executed completely 

    // 2.Upload object 
    BOSObjectContent* content = [[BOSObjectContent alloc] init];
    content.objectData.file = @"<FilePath>";

    BOSPutObjectRequest* request = [[BOSPutObjectRequest alloc] init];
    request.bucket = @"<bucketname>";
    request.key = @"<Objectname>";
    request.objectContent = content;

    __block BOSPutObjectResponse* response = nil;
    task = [client putObject:request];
    task.then(^(BCEOutput* output) {
        if (output.progress) {
            // Printing progress 
            NSLog(@"put object progress is %@", output.progress);
        }

        if (output.response) {
            response = (BOSPutObjectResponse*)output.response;
            //Print ETag.
            NSLog(@"The eTag is %@", response.metadata.eTag);
        }

        if (output.error) {
            NSLog(@"put object failure with %@", output.error);
        }
    });
    [task waitUtilFinished];

    // 3.View object
    BOSListObjectsRequest* listRequest = [[BOSListObjectsRequest alloc] init];
    listRequest.bucket = @"<bucketname>";

    __block BOSListObjectsResponse* listRepsponse = nil;
    task = [client listObjects:listRequest];
    task.then(^(BCEOutput* output) {
        if (output.response) {
            listRepsponse = (BOSListObjectsResponse*)output.response;
            for (BOSObjectInfo* object in listRepsponse.contents) {
                NSLog(@"The object key is %@", object.key);
            }
        }

        if (output.error) {
            NSLog(@"list objects failure with %@", output.error);
        }
    });
    [task waitUtilFinished];

    // 4. 4.Download object 
    BOSGetObjectRequest* getRequest = [[BOSGetObjectRequest alloc] init];
    getRequest.bucket = @"<bucketname>";
    getRequest.key = @"<Objectname>";
    getRequest.file = @"<file>";

    __block BOSGetObjectResponse* getResponse = nil;
    task = [client getObject:getRequest];
    task.then(^(BCEOutput* output) {
        if (output.response) {
            getResponse = (BOSGetObjectResponse*)output.response;
        }

        if (output.error) {
            NSLog(@"get object failure with %@", output.error);
        }
    });
    [task waitUtilFinished];

    // 5.Release client
    [client shutdown];
    }

Create BOSClient

BosClient is the client of BOS service, providing methods for developers to interact with BOS service. Before using SDK to initiate a request to BOS, you need to initialize a BosClient instance and make some necessary settings to it.

  • Basic procedure

    1.Determine service region, for example, Beijing is BCERegionBJ, Guangzhou is BCERegionGZ, and Suzhou is BCERegionSU; 2.Create a BCECredentials, and set accessKey and secretKey fields; 3.Create a BOSClientConfiguration instance, and set credentials field; 4.Introduce the configured BosClientConfiguration into BosClient.

  • Sample Code

    You can create a BOSClient by referring to the following code:

    BCECredentials* credentials = [[BCECredentials alloc] init];
    credentials.accessKey = @"<access key>";
    credentials.secretKey = @"<secret key>";
    
    BOSClientConfiguration* configuration = [[BOSClientConfiguration alloc] init];
    configuration.region = [BCERegion region:BCERegionBJ];
    configuration.credentials = credentials;

BOSClient* client = [[BOSClient alloc] initWithConfiguration:configuration];


  >**Note:** `Region` parameter can only be defined as a specified enumerated value, and if not specified, the region is Beijing by default. Baidu AI Cloud currently has opened access to multi-region support, please refer to [Region Selection Description](Reference/Region Selection Description/Region.md#). 
  > 
  > Currently, it supports "North China-Beijing", "South China-Guangzhou" and "East China-Suzhou". Beijing: `http://bj.bcebos.com`; Guangzhou: `http://gz.bcebos.com`; Suzhou: `http://su.bcebos.com`. 

## Create BosClient with STS Verification 

IOS SDK is mainly used for the mobile end development scene, while for mobile end authentication, if you disclose your AK/SK to mobile end directly, it will inevitably cause a potential hazard to account, so you are recommended to realize the authentication of mobile end with STS mode. Please refer to [Temporary Authorized Access](BOS/API Reference/Access Control.md#Temporary Authorized Access#) for detailed information on STS. 

To use STS mode, you need to create a BOSClient with STS first when calling API; for the BOS API interfaces supporting calling via STS, see [STS Service Interface](BOS/API Reference/Access Control.md#STS Service Interface#) 

- Sample code: 

      BCESTSCredentials* credentials = [[BCESTSCredentials alloc] init];
      credentials.accessKey = @"<access key>"; // Temporarily returned AK 
      credentials.secretKey = @"<secret key>"; // Temporarily returned SK 
      credentials.sessionToken = @"<session token>"; // Temporarily returned SessionToken 
      
      BOSClientConfiguration* configuration = [[BOSClientConfiguration alloc] init];
      configuration.credentials = credentials;
      
      BOSClient* client = [[BOSClient alloc] initWithConfiguration:configuration];

  >**Note:** In the following code examples, the original AK/SK is used to create a BOSClient. If you need to use a BOSClient with STS authentication, follow the above method when creating a BOSClient. 

## Configure HTTPS to Access BOS

BOS supports HTTPS, and you can access to BOS service with HTTPS in BOS iOS SDK as follows: 

  configuration.scheme = @"https";

## Configure BOSClient 

If you need to configure some detailed parameters of the BosClient, introduce into the BosClientConfiguration object when constructing the BosClient. BOSClientConfiguration is the configuration class of BOS service. You can set basic network parameters through BOSClientConfiguration. 

**Set Network Parameters** 

You can use BOSClientConfiguration to set basic network parameters. 

- Sample Code 

      BOSClientConfiguration config = [[BOSClientConfiguration alloc] init];
      
      // Set the maximum number of HTTP connections to 5
      config.maxConurrentConnection = 5;
      
      // Set TCP connection timeout to 5 seconds 
      config.connectionTimeout = 5;
      
      // Set the time to request longest transport data as 60 seconds 
      config.totalTransferTimeout = 60;

- Parameter description 

All parameters that can be specified through BOSClientConfiguration are shown in the following table: 

| Parameter                    |  Description                            |
| ----------------------|  --------------------------------------------|
| authVersion          |  The authentication algorithm version has a default value of 1 currently                           |
| APIVersion           |  The BOS API used has a default value of 1 currently                         |
| scheme               |  The value of HTTP protocol used can be http and https, with default value http.             |
| region               |  Use the region of BOS service                                  |
| endpoint             |  If you know the service address clearly, you may not set scheme and region, but set endpoint directly|
| allowsCellularAccess |  The default value of whether to use cellular network is NO                           |
| connectionTimeout    |  Set TCP connection timeout, with default value of 60s.                           |
| totalTransferTimeout |  Set the time to request longest transport data, in second, with default value of 7 days.                     |
| maxConurrentConnection|  Maximum number of HTTP connections allowed to open.                              |
Previous
SDK Installation
Next
Bucket Management