Quick Start (Swift SDK)

更新时间:
复制 MD 格式

Install the Swift SDK to manage OSS buckets, upload and download files, manage data, and process images. Select an installation method based on your scenario.

Requirements

  • Required version: Swift 5.9 or later

  • Supported platforms: iOS, macOS, visionOS, watchOS, tvOS, Linux, and Windows

Install the SDK

You can install the SDK by using one of the following methods.

Install with Swift Package Manager

Note
  • AlibabaCloudOSS provides basic bucket and object interfaces, along with advanced features such as paginators and pre-signed URLs.

  • AlibabaCloudOSSExtension includes the basic bucket interfaces and adds configuration interfaces such as cross-origin resource sharing (CORS).

The SDK uses Swift Package Manager to manage dependencies. Add the following package dependency to your Package.swift file.

dependencies: [.package(url: "https://github.com/aliyun/alibabacloud-oss-swift-sdk-v2.git", , from: "0.1.1")]

Then, add the product as a dependency of your target.

targets: [.target(name: "YourTarget", dependencies: [.product(name: "AlibabaCloudOSS", package: "alibabacloud-oss-swift-sdk-v2"),
        //.product(name: "AlibabaCloudOSSExtension", package: "alibabacloud-oss-swift-sdk-v2"),
    ]),]

Install using Swift Package Manager

Perform the following steps:

  1. In Xcode, create a project or open an existing one, choose Project > Package Dependencies, and then click +.

  2. Search for https://github.com/aliyun/alibabacloud-oss-swift-sdk-v2.git, and click Add Package.

Quick start

The following examples demonstrate how to create a bucket, upload, download, list, and delete objects.

Create a bucket

import AlibabaCloudOSS
import Foundation
import ArgumentParser

@main
struct PutBucket: AsyncParsableCommand {
    func run() async throws {
        do {
            // Set the OSS region.
            let region = "cn-hangzhou"

            // Set the name of the bucket to create.
            let bucket = "your bucket name"

            // Create a configuration object:
            // - Use the default configurations.
            // - Set the credential provider to load from environment variables.
            // - Set the region.
            let config = Configuration.default()
                .withCredentialsProvider(EnvironmentCredentialsProvider())
                .withRegion(region)

            // Create an OSS Client instance.
            let client = Client(config)

            // Call the putBucket operation to create a new bucket.
            let result = try await client.putBucket(
                PutBucketRequest(
                    bucket: bucket // The name of the bucket to create.
                )
            )

            // Print the request result.
            print("PutObject done, StatusCode:\(result.statusCode), RequestId:\(result.requestId).")
            
        } catch {
            Program.exit(withError: error)
        }
    }
}

Upload an object

import AlibabaCloudOSS
import Foundation
import ArgumentParser

@main
struct PutObject: AsyncParsableCommand {
    func run() async throws {

        do {
            // Set the OSS region.
            let region = "cn-hangzhou"

            // Set the name of the destination bucket.
            let bucket = "your bucket name"

            // Set the key of the object to upload. The key is the object name or path.
            let key = "your object name"

            // Create a client configuration:
            // - Use the default configurations.
            // - Load credentials from environment variables (OSS_ACCESS_KEY_ID / SECRET).
            // - Set the region.
            let config = Configuration.default()
                .withCredentialsProvider(EnvironmentCredentialsProvider())
                .withRegion(region)

            // Initialize the OSS client with the preceding configuration.
            let client = Client(config)

            // The text content to upload.
            let content = "hi oss"

            // Convert the string to the Data type with UTF-8 encoding.
            // Then, call the putObject operation to upload the data to OSS.
            let result = try await client.putObject(
                PutObjectRequest(
                    bucket: bucket,     // The destination bucket name.
                    key: key,           // The object key (file name).
                    body: .data(content.data(using: .utf8)!)  // The content to upload.
                )
            )

            // Print the upload result.
            print("PutObject done, StatusCode:\(result.statusCode), RequestId:\(result.requestId).")
        } catch {
            Program.exit(withError: error)
        }
    }
}

Download an object

import AlibabaCloudOSS
import Foundation
import ArgumentParser

@main
struct GetObject: AsyncParsableCommand {
    func run() async throws {
        do {
            // Set the OSS region.
            let region = "cn-hangzhou"

            // Set the name of the bucket that stores the object to download.
            let bucket = "your bucket name"

            // Set the key of the object to download. The key is the object name or path.
            let key = "your object name"

            // Create a client configuration:
            // - Use the default configurations.
            // - Load credentials from environment variables (OSS_ACCESS_KEY_ID / SECRET).
            // - Set the region.
            let config = Configuration.default()
                .withCredentialsProvider(EnvironmentCredentialsProvider())
                .withRegion(region)

            // Initialize the OSS client with the preceding configuration.
            let client = Client(config)

            // Call the getObject operation to download the object data from OSS to memory.
            let result = try await client.getObject(
                GetObjectRequest(
                    bucket: bucket,     // The destination bucket name.
                    key: key            // The object key (file name).
                )
            )

            // Print the request result.
            print("GetObject done, StatusCode:\(result.statusCode), RequestId:\(result.requestId).")
        } catch {
            Program.exit(withError: error)
        }
    }
}

List files

import AlibabaCloudOSS
import Foundation
import ArgumentParser

@main
struct ListObjects: AsyncParsableCommand {
    func run() async throws {

        do {
            // Set the OSS region.
            let region = "cn-hangzhou"

            // Set the name of the bucket whose objects you want to list.
            let bucket = "your bucket name"

            // Create a credential provider that uses credentials from environment variables.
            // The SDK reads OSS_ACCESS_KEY_ID / SECRET from environment variables.
            let credentialsProvider = EnvironmentCredentialsProvider()

            // Create a client configuration:
            // - Use the default configurations.
            // - Set the region.
            // - Set the credential provider to load from environment variables.
            let config = Configuration.default()
                .withRegion(region)
                .withCredentialsProvider(credentialsProvider)

            // Initialize the OSS client with the preceding configuration.
            let client = Client(config)

            // Create a paginator to perform a paged query for the object list.
            // Use the `listObjectsV2Paginator` operation to traverse all objects. Paging is handled automatically.
            for try await result in client.listObjectsV2Paginator(
                ListObjectsV2Request(bucket: bucket)
            ) {
                // Check the object list (contents) in the response.
                if let objects = result.contents {
                    // Traverse each object and print its information.
                    for object in objects {
                        print("object: $object)")
                    }
                }
            }
        } catch {
            Program.exit(withError: error)
        }
    }
}

Delete example

import AlibabaCloudOSS
import Foundation
import ArgumentParser

@main
struct deleteObject: AsyncParsableCommand {
    func run() async throws {

        do {
            // Set the OSS region.
            let region = "cn-hangzhou"

            // Set the name of the bucket that stores the object to delete.
            let bucket = "zhuyu-test"

            // Set the key of the object to delete. The key is the object name or path.
            let key = "your object name"

            // Use the default configurations of the SDK:
            // - Load credentials from environment variables (OSS_ACCESS_KEY_ID / SECRET).
            // - Set the region.
            let config = Configuration.default()
                .withCredentialsProvider(EnvironmentCredentialsProvider())
                .withRegion(region)

            // Initialize the OSS client with the preceding configuration.
            let client = Client(config)

            // Call the deleteObject operation to delete the specified object.
            let result = try await client.deleteObject(
                DeleteObjectRequest(
                    bucket: bucket,     // The destination bucket name.
                    key: key            // The key of the object to delete (file name).
                )
            )

            // Print the result of the delete operation.
            print("DeleteObject done, StatusCode:\(result.statusCode), RequestId:\(result.requestId).")
        } catch {
            Program.exit(withError: error)
        }
    }
}

Run the examples

  1. To run these examples in Xcode, first configure the environment variables in the IDE: OSS_ACCESS_KEY_ID="Your Access Key ID" and OSS_ACCESS_KEY_SECRET="Your Access Key Secret".

  2. Create a test.swift file in your test project directory and copy the sample code into it. Before you run the code, replace the "region", "bucket", and "key" placeholders with your actual values. For the region, specify the ID of the region where the bucket is located. For example, for China (Hangzhou), use cn-hangzhou.

References