Alibaba Cloud OSS SDK for iOS

repository·master·Indexed 19 days ago

https://github.com/aliyun/aliyun-oss-ios-sdk

A client-side library for iOS developers to interact with Alibaba Cloud Object Storage Service (OSS). The SDK supports uploading, downloading, and managing objects in OSS buckets. It features STS (Security Token Service) authentication, IPv6-only network compatibility (V2.5.0+), and Apple ATS compliance via HTTPS (V2.6.0+). The library can be installed via CocoaPods using the 'AliyunOSSiOS' pod or by manually integrating the AliyunOSSiOS.framework.

Tokens
2.7K
Snippets
8
Records
14
Agent score
64%

What's inside aliyun-oss-ios-sdk

  1. Configure HTTPS for Apple ATS Compliance

    master

    To comply with Apple's App Transport Security (ATS) policy, the SDK (version 2.6.0 and above) requires all network requests to be encrypted.

    When configuring the SDK:

    1. Use the https:// prefix when setting the Endpoint.
    2. Ensure any custom callbacks (such as signature generation or STSToken retrieval) do not initiate non-HTTPS requests.
  2. How OSSTask handles asynchronous and synchronous operations

    master

    Every API call in the OSS iOS SDK returns an OSSTask object. You have two ways to handle the result:

    1. Asynchronous (Recommended): Use continueWithBlock: to define a callback that executes when the task completes. This prevents blocking the main thread.
    2. Synchronous: Use [task waitUntilFinished] to block the current execution thread until the task is complete.

    Example of asynchronous callback:

    [task continueWithBlock: ^(OSSTask *task) {
        // handle result or error
        return nil;
    }];
  3. Understand OSSTask for Asynchronous Operations

    master

    Every API call in the OSS SDK returns an OSSTask object. You can handle the result in two ways:

    1. Asynchronous (Recommended): Use continueWithBlock: to define a callback that executes when the task completes.
    2. Synchronous: Use waitUntilFinished to block the current thread until the task is done.

    Example of asynchronous handling:

    OSSTask *task = [client getObject:get];
    [task continueWithBlock: ^(OSSTask *task) {
        if (!task.error) {
            // Success
        } else {
            // Handle error
        }
        return nil;
    }];
    OSSTask * task = [client getObject:get];
    
    [task continueWithBlock: ^(OSSTask *task) {
    	// do something
    	...
    
    	return nil;
    }];
    
    // Or synchronous:
    [task waitUntilFinished];
  4. Install the OSS iOS SDK via CocoaPods

    master

    If your project uses CocoaPods, add the AliyunOSSiOS pod to your Podfile. This is the recommended method as it handles dependencies automatically and you do not need to manually import the framework.

    pod 'AliyunOSSiOS'
    pod 'AliyunOSSiOS'
  5. Install Aliyun OSS SDK for iOS via Framework

    master

    You can manually build and include the AliyunOSSiOS.framework.

    1. Clone the repository and run the build script:
    git clone git@github.com:aliyun/aliyun-oss-ios-sdk.git
    cd aliyun-oss-ios-sdk
    sh ./buildiOSFramework.sh
    1. The generated framework will be in the Products directory.
    2. Drag the framework into your Xcode target and check Copy items if needed.

    Important Configuration:

    • In Xcode Build Settings, add -ObjC to Other Linker Flags.
    • If -force_load is already set, add -force_load <framework path>/AliyunOSSiOS.
    • Note: The script generates a version supporting i386, x86_64, armv7, and arm64. For production archives, you should use the project files to generate a version specifically for physical devices.
    git clone git@github.com:aliyun/aliyun-oss-ios-sdk.git
    cd aliyun-oss-ios-sdk
    sh ./buildiOSFramework.sh
    cd Products && ls
  6. Initialize the OSSClient with STS Authentication

    master

    For mobile applications, it is recommended to use STS (Security Token Service) authentication. You can initialize an OSSAuthCredentialProvider with an STS URL, which automatically fetches and updates credentials.

    Requirements:

    • Use an endpoint with the https:// prefix to comply with Apple's ATS policy (supported from V2.6.0+).
    • Ensure your app does not send non-HTTPS requests during signing or STSToken callbacks.
    #include <AliyunOSSiOS/AliyunOSSiOS.h>
    
    // ... inside your implementation ...
    
    - (void)setupOSSClient {
        // initialize credential provider, which auto fetch and update sts info from sts url.
        OSSAuthCredentialProvider *credentialProvider = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:OSS_STS_URL];
        
        // set config for oss client networking
        OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
        
        _client = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:credentialProvider clientConfiguration:cfg];
    }
  7. Install the OSS iOS SDK by introducing the framework directly

    master

    To manually include the framework, you can build it from the source repository:

    1. Clone the repository.
    2. Run the packaging script to generate the AliyunOSSiOS.framework.
    3. In Xcode, drag and drop the generated framework into your target and select Copy items if needed.

    Important Configuration:

    • Add -ObjC to your project's Other Linker Flags in Build Settings.
    • If your project uses -force_load, add -force_load <framework path>/AliyunOSSiOS.

    IPv6-Only Compatibility (V2.5.0+): If your app must support IPv6-only networks, you must also include these system libraries:

    • libresolv.tbd
    • SystemConfiguration.framework
    • CoreTelephony.framework
    # Clone the project
    $ git clone git@github.com:aliyun/aliyun-oss-ios-sdk.git
    
    # Enter the directory
    $ cd aliyun-oss-ios-sdk
    
    # Run the packaging script
    $ sh ./buildiOSFramework.sh
    
    # Enter the generated packaging directory where the AliyunOSSiOS.framework will be generated
    $ cd Products && ls
  8. Ensure IPv6-Only Network Compatibility

    master

    To support IPv6-only network environments (required for certain App Store reviews), ensure you are using SDK version 2.5.0 or higher. In addition to the -ObjC linker flag, you must include the following system libraries in your project:

    • libresolv.tbd
    • SystemConfiguration.framework
    • CoreTelephony.framework
  9. Upload a file using putObject

    master

    To upload data, create an OSSPutObjectRequest, specify the bucket and object key, and provide the data via uploadingData. The operation returns an OSSTask which can be handled asynchronously via a continuation block or synchronously via waitUntilFinished.

    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    put.bucketName = @"<bucketName>";
    put.objectKey = @"<objectKey>";
    
    put.uploadingData = <NSData *>; // Directly upload 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;
    }];
  10. Download an object using getObject

    master

    To download an object as NSData, create an OSSGetObjectRequest and specify the bucket and object key. The resulting OSSTask provides the downloaded data in its result property (as an OSSGetObjectResult).

    OSSGetObjectRequest * request = [OSSGetObjectRequest new];
    request.bucketName = @"<bucketName>";
    request.objectKey = @"<objectKey>";
    
    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;
    }];
  11. Initialize OSSClient with STS Authentication

    master

    For mobile environments, it is recommended to use STS (Security Token Service) authentication. This involves providing an STS URL where the client can fetch temporary credentials.

    // 1. Setup Credential Provider with your STS URL
    OSSAuthCredentialProvider *credentialProvider = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:@