You can use the following code to add tags to an object.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
do {
// Specify the region where the bucket is located. Example: China (Hangzhou) is cn-hangzhou.
let region = "cn-hangzhou" // Replace with your actual region ID.
// Specify the bucket name.
let bucket = "yourBucketName" // Replace with your actual bucket name.
// Optional. Specify the domain name to access OSS. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
let endpoint: String? = nil
// Specify the name of the object for which to set tags, such as document.txt.
let key = "yourObjectName" // Replace with your actual object name.
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
let credentialsProvider = EnvironmentCredentialsProvider()
// Configure OSS client parameters.
let config = Configuration.default()
.withRegion(region) // Set the region where the bucket is located.
.withCredentialsProvider(credentialsProvider) // Set the access credentials.
// Set a custom endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
var tags: [Tag] = []
tags.append(Tag(key: "key1",value: "value1")) // Replace with an actual tag key-value pair.
tags.append(Tag(key: "key2",value: "value2")) // Replace with an actual tag key-value pair.
// Set object tags.
let result = try await client.putObjectTagging(
PutObjectTaggingRequest(
bucket: bucket,
key: key,
tagging: Tagging(tagSet: TagSet(tags: tags))
)
)
print("result:\n\(result)") // Print the result.
} catch {
// Print the error.
print("error: \(error)")
}
}
}