This topic describes how to use the OSS SDK for iOS to upload and download objects.
Prerequisites
Before you begin, ensure that you have:
Installed OSS SDK for iOS. For more information, see Installation (iOS SDK)
Demo projects
The following demo projects show how to create a bucket, upload a local file, and download an object:
To run a demo project:
Clone the demo projects using
git clone.-
Configure the required parameters:
For the AliyunOSSSwift demo: set the parameters in OSSSwiftGlobalDefines.swift.
For the AliyunOSSSDK demo: set the parameters in OSSTestMacros.h.
-
Start Security Token Service (STS):
Start the local STS authentication server by running the authentication script from the
sts_local_serverdirectory, then set theAccessKeyId,AccessKeySecret, andRoleArnparameters.Start the local HTTP service using httpserver.py. The client then fetches the
StsToken.AccessKeyId,StsToken.SecretKey, andStsToken.SecurityTokenvalues from this local HTTP service.
After launching the iOS demo, the app provides entry points for image selection (Select), custom signed uploads (CustomSign), uploads (Put), downloads (Get), thumbnail retrieval (GetResizeImage), text watermarking (Watermark), and upload callbacks (triggerCallback).
Sample code
The following steps show how to upload and download objects on iOS and macOS.
-
Import the OSS package.
Import the required header file before calling any OSS APIs:
#import <AliyunOSSiOS/OSSService.h>
-
Initialize an OSSClient instance.
-
Choose an authentication mode.
OSS SDK for iOS supports three authentication modes: plaintext, self-signed, and STS authentication. For mobile apps, use STS authentication — it issues short-lived credentials that limit exposure if a key is compromised and can be rotated without an app update. Hardcoding an AccessKey ID and AccessKey secret in the app binary exposes your account if the binary is reverse-engineered and prevents credential rotation without a new release.
For more information, see STS authentication mode.
-
Obtain credentials:
Plaintext mode: authenticate using your AccessKey ID and AccessKey secret directly.
Self-signed mode: generate a signature string for authentication. For more information, see Self-signed mode.
STS authentication mode: use temporary access credentials issued by Security Token Service (STS). Call the AssumeRole API or use STS SDKs to get temporary credentials. For details, see Access OSS by using STS temporary credentials.
Use the credentials to initialize OSS SDK for iOS.
-
-
The following code initializes an OSSClient instance for a complete application lifecycle.
OSSAuthCredentialProviderautomatically refreshes STS credentials from your server when they expire.@interface AppDelegate () @property (nonatomic, strong) OSSClient *client; @end /** * The URL to obtain STS information. Configure this on your own server. */ #define OSS_STS_URL @"oss_sts_url" /** * The endpoint of the region where the bucket is located. */ #define OSS_ENDPOINT @"your bucket's endpoint" /** * The region where the bucket is located. */ #define OSS_REGION @"your bucket's region" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // Initialize the OSSClient instance. [self setupOSSClient]; return YES; } - (void)setupOSSClient { // Initialize a provider that automatically refreshes credentials. id<OSSCredentialProvider> credentialProvider = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:OSS_STS_URL]; // Client-side configurations, such as timeout period and DNS pre-resolution. OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init]; cfg.signVersion = OSSSignVersionV4; client = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:credentialProvider clientConfiguration:cfg]; client.region = OSS_REGION; }NoteIf your app uses a single bucket in one region, set the OSSClient lifecycle to match the application lifecycle. See Regions and Endpoints.
-
-
Create a bucket.
The following code creates a bucket named
examplebucket:// Build a request to create a bucket. OSSCreateBucketRequest * create = [OSSCreateBucketRequest new]; // Set the bucket name to examplebucket. create.bucketName = @"examplebucket"; // Set the access control list (ACL) to private. create.xOssACL = @"private"; // Set the storage class to Infrequent Access (IA). create.storageClass = OSSBucketStorageClassIA; OSSTask * createTask = [client createBucket:create]; [createTask continueWithBlock:^id(OSSTask *task) { if (!task.error) { NSLog(@"create bucket success!"); } else { NSLog(@"create bucket failed, error: %@", task.error); } return nil; }]; // Wait for the task to complete synchronously. // [createTask waitUntilFinished];NoteAll SDK operations return an
OSSTaskobject. Set a continuation block on anOSSTaskto handle the result asynchronously, or callwaitUntilFinishedto block until the task completes. -
Upload a local file.
The following code uploads a local file to OSS:
Parameter
Description
bucketNameName of the target bucket. Example:
examplebucket.objectKeyFull object path, excluding the bucket name. Example:
exampledir/testdir/exampleobject.txt.uploadingFileURLLocal file path as an
NSURL.uploadingDataAlternative to
uploadingFileURL— passNSDatadirectly.uploadProgressCallback block reporting bytes sent, total bytes sent, and total bytes expected.
OSSPutObjectRequest * put = [OSSPutObjectRequest new]; // Specify the bucket name. Example: examplebucket. put.bucketName = @"examplebucket"; // Specify the full path of the object. Do not include the bucket name. Example: exampledir/testdir/exampleobject.txt. put.objectKey = @"exampledir/testdir/exampleobject.txt"; put.uploadingFileURL = [NSURL fileURLWithPath:@"<filePath>"]; // Alternatively, upload NSData directly. // 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 for the task to complete. // [putTask waitUntilFinished]; -
Download an object.
The following code downloads an object to your local device:
Parameter
Description
bucketNameName of the bucket that contains the object. Example:
examplebucket.objectKeyFull object path, excluding the bucket name. Example:
exampledir/testdir/exampleobject.txt.downloadProgressCallback block reporting bytes written, total bytes written, and total bytes expected.
OSSGetObjectRequest * request = [OSSGetObjectRequest new]; // Specify the bucket name. Example: examplebucket. request.bucketName = @"examplebucket"; // Specify the full path of the object. Do not include the bucket name. 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 for the task to complete. // [task waitUntilFinished];