This topic describes how to use Object Storage Service (OSS) SDK for iOS to perform basic operations such as file upload and download.

Background information

For more information about OSS SDK for iOS, see the following examples:

You can also clone the project by running the git clone command and configure necessary parameters such as OSS_ACCESSKEY_ID and OSS_SECRETKEY_ID.

ios

Run the project demo as shown in the following figure.

fig_ios_phpnedemo

Sample code

The following code shows how to upload and download objects on the iOS and macOS platforms:

  1. Add the required reference
    #import <AliyunOSSiOS/OSSService.h>                            
  2. Initialize an OSSClient instance

    To initialize an OSSClient instance, you must specify the endpoint, authentication mode, and client configurations. Three authentication modes are available: plaintext setting, self-signed, and Security Token Service (STS) authentication. For more information about how to use the STS authentication mode, see Authorize access.

    Configure the AccessKeyId, AccessKeySecret, and RoleArn parameters in the sts.py script file. Use OSS SDK for Python to start a local HTTP service. Use the client code to access the local service and obtain the values of the StsToken.AccessKeyId, StsToken.SecretKey, and StsToken.SecurityToken parameters.

    Note

    For more information about how to use STS to authorize access to OSS, see Use temporary credentials provided by STS to access OSS in OSS Developer Guide. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain temporary access credentials from STS. For more information, see STS SDK overview. Temporary access credentials include a security token and a temporary AccessKey pair that consists of an AccessKey ID and an AccessKey secret.

    NSString *endpoint = @"https://oss-cn-hangzhou.aliyuncs.com";
    
    // We recommend that you use STS to initialize the OSSClient instance if you use a mobile device. 
    id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * _Nullable{
        OSSFederationToken *token = [OSSFederationToken new];
        // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        token.tAccessKey = @"AccessKeyId";
        token.tSecretKey = @"AccessKeySecret";
        // Specify the security token obtained from STS. 
        token.tToken = @"SecurityToken";
        // Set the expiration time for the temporary access credentials. 
        token.expirationTimeInGMTFormat = @"Expiration";
        return token;
    }];
    
    client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];              

    You can use the OSSClient instance to initiate multi-threaded upload and download requests to concurrently run multiple tasks.

  3. Upload an object

    If you have a bucket in the OSS console, an OSSTask is returned for each SDK-relevant operation. You can configure a continuation for OSSTask to be asynchronously completed or call waitUntilFinished to wait for the task to be completed.

    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // Specify the name of the bucket. Example: examplebucket. 
    put.bucketName = @"examplebucket";
    // Specify the full path of the object. The full path of the object cannot contain bucket names. Example: exampledir/testdir/exampleobject.txt. 
    put.objectKey = @"exampledir/testdir/exampleobject.txt";
    // Directly upload NSData. 
    put.uploadingData = <NSData *>; 
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask * putTask = [client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"upload object success!");
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
    // Wait until the task is completed. 
    // [putTask waitUntilFinished];
  4. Download a specified object

    The following code provides an example on how to download a specified object as NSData:

    OSSGetObjectRequest * request = [OSSGetObjectRequest new];
    // Specify the name of the bucket. Example: examplebucket. 
    request.bucketName = @"examplebucket";
    // Specify the full path of the object. The full path of the object cannot contain bucket names. Example: exampledir/testdir/exampleobject.txt. 
    request.objectKey = @"exampledir/testdir/exampleobject.txt";
    request.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
        NSLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
    };
    OSSTask * getTask = [client getObject:request];
    [getTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"download object success!");
            OSSGetObjectResult * getResult = task.result;
            NSLog(@"download result: %@", getResult.downloadedData);
        } else {
            NSLog(@"download object failed, error: %@" ,task.error);
        }
        return nil;
    }];
    // Wait until the task is completed. 
    // [task waitUntilFinished];