All Products
Search
Document Center

ApsaraVideo VOD:Upload files using the iOS SDK

Last Updated:Jan 28, 2026

This topic describes how to use the iOS software development kit (SDK) to upload local media files to VOD storage.

Prerequisites

  • You are using iOS 8.0 or later.

  • The iOS upload SDK does not support Swift.

Integrate the SDK

Integration methods

Integrate the SDK using CocoaPods (Recommended)

  1. Run the pod 'VODUpload' command to add the VOD upload SDK as a dependency in your Podfile.

  2. Run the pod repo update command to update the pod repository.

  3. Run the pod install command to install the VOD upload SDK.

Integrate the SDK manually

  • SDK version: 1.6.5

  • Update time: 2022-01-24

  • Package MD5 hash: f3551634b53cd1264013db4762f79a14

  • Download address: V1.6.5 SDK

  1. In Xcode, drag VODUpload.framework and AliyunOSSiOS.framework to your project target. In the dialog box that appears, select Copy items if needed.

  2. Add the following system dependency libraries.

    1. AVFoundation.framework

    2. CoreMedia.framework

    3. SystemConfiguration.framework

    4. MobileCoreServices.framework

    5. libresolv.9.tbd

Project configuration

After you integrate the SDK, open your project and modify the configuration as follows.

  1. In the menu bar, click Build Setting > Linking > Other Linker Flags.

  2. Add -Objc.

Basic settings

Initialize the upload instance

First, understand the overall upload process for client-side uploads. Then, deploy an authorization service based on your chosen authorization method:

  1. If you use an upload URL and credential, obtain the upload URL and credential from your authorization service.

  2. If you use a Security Token Service (STS) token, obtain an STS token from your authorization service.

Initializing the upload instance involves two steps: declaring the initialization callback and initializing the instance.

  1. Declare the VODUploadClient property. It cannot be a local variable.

  2. Initialize the upload instance.

    Upload URL and credential method

    Note
    • To use an upload URL and credential, call the init method for initialization.

    • Do not set the upload URL and credential during initialization. After the upload starts, the OnUploadStartedListener callback is triggered. Call the setUploadAuthAndAddress:uploadAuth:uploadAddress: method in this callback to set the URL and credential.

    • When the credential expires, the OnUploadTokenExpiredListener callback is triggered. Call the resumeWithAuth method and provide a new upload credential to resume the upload.

    Click to view the code

    // Create a VODUploadClient object
    self.uploader = [VODUploadClient new];
    // weakself
    __weak typeof(self) weakSelf = self;
    // setup callback
    OnUploadFinishedListener FinishCallbackFunc = ^(UploadFileInfo* fileInfo, VodUploadResult* result){
        NSLog(@"Upload finished. Video ID: %@, Image URL: %@", result.videoId, result.imageUrl);
    };
    OnUploadFailedListener FailedCallbackFunc = ^(UploadFileInfo* fileInfo, NSString *code, NSString* message){
        NSLog(@"Upload failed. Error code: %@, Error message: %@", code, message);
    };
    OnUploadProgressListener ProgressCallbackFunc = ^(UploadFileInfo* fileInfo, long uploadedSize, long totalSize) {
        NSLog(@"Upload progress. Uploaded size: %li, Total size: %li", uploadedSize, totalSize);
    };
    OnUploadTokenExpiredListener TokenExpiredCallbackFunc = ^{
        NSLog(@"Upload token expired.");
        // The token expired. Set a new upload credential to resume the upload.
        [weakSelf.uploader resumeWithAuth:@"new upload auth"];
    };
    OnUploadRertyListener RetryCallbackFunc = ^{
        NSLog(@"Upload retry started.");
    };
    OnUploadRertyResumeListener RetryResumeCallbackFunc = ^{
        NSLog(@"Upload retry finished.");
    };
    OnUploadStartedListener UploadStartedCallbackFunc = ^(UploadFileInfo* fileInfo) {
        NSLog(@"Upload started.");
        // Set the upload URL and upload credential.
        [weakSelf.uploader setUploadAuthAndAddress:fileInfo uploadAuth:@"upload auth" uploadAddress:@"upload address"];
    };
    VODUploadListener *listener = [[VODUploadListener alloc] init];
    listener.finish = FinishCallbackFunc;
    listener.failure = FailedCallbackFunc;
    listener.progress = ProgressCallbackFunc;
    listener.expire = TokenExpiredCallbackFunc;
    listener.retry = RetryCallbackFunc;
    listener.retryResume = RetryResumeCallbackFunc;
    listener.started = UploadStartedCallbackFunc;
    // Initialize the uploader.
    [self.uploader init:listener];

    STS token method

    Note
    • To initialize using an STS token, call the init method and pass the temporary STS credentials using the setKeyId:accessKeySecret:secretToken:expireTime:listener: method.

    • When the token expires, the OnUploadTokenExpiredListener callback is triggered. Call the resumeWithToken:accessKeySecret:secretToken:expireTime: method and provide a new STS token to resume the upload.

    Click to view the code

    // Create a VODUploadClient object
    self.uploader = [VODUploadClient new];
    // weakself
    __weak typeof(self) weakSelf = self;
    // setup callback
    OnUploadFinishedListener FinishCallbackFunc = ^(UploadFileInfo* fileInfo,  VodUploadResult* result){
        NSLog(@"Upload finished. Video ID: %@, Image URL: %@", result.videoId, result.imageUrl);
    };
    OnUploadFailedListener FailedCallbackFunc = ^(UploadFileInfo* fileInfo, NSString *code, NSString* message){
        NSLog(@"Upload failed. Error code: %@, Error message: %@", code, message);
    };
    OnUploadProgressListener ProgressCallbackFunc = ^(UploadFileInfo* fileInfo, long uploadedSize, long totalSize) {
        NSLog(@"Upload progress. Uploaded size: %li, Total size: %li", uploadedSize, totalSize);
    };
    OnUploadTokenExpiredListener TokenExpiredCallbackFunc = ^{
        NSLog(@"Upload token expired.");
        // The token expired. Set a new STS token to resume the upload.
        [weakSelf.uploader resumeWithToken:@"STS Key Id" accessKeySecret:@"STS Key Secret" secretToken:@"STS Secret Token" expireTime:@"STS Expire Time"];
    };
    OnUploadRertyListener RetryCallbackFunc = ^{
        NSLog(@"Upload retry started.");
    };
    OnUploadRertyResumeListener RetryResumeCallbackFunc = ^{
        NSLog(@"Upload retry finished.");
    };
    OnUploadStartedListener UploadStartedCallbackFunc = ^(UploadFileInfo* fileInfo) {
        NSLog(@"Upload started.");
    };
    // Initialize
    VODUploadListener *listener = [[VODUploadListener alloc] init];
    listener.finish = FinishCallbackFunc;
    listener.failure = FailedCallbackFunc;
    listener.progress = ProgressCallbackFunc;
    listener.expire = TokenExpiredCallbackFunc;
    listener.retry = RetryCallbackFunc;
    listener.retryResume = RetryResumeCallbackFunc;
    listener.started = UploadStartedCallbackFunc;
    // Set the STS token and listener.
    [self.uploader setKeyId:@"STS Key Id" accessKeySecret:@"STS Key Secret" secretToken:@"STS Secret Token" expireTime:@"STS Expire Time" listener:listener];
  3. Set callbacks to receive messages about key events during the upload process.

    Set the VODUploadListener object. This object is a callback class for the upload status. You need to set the following callback methods:

    Click to view the code

    /**
     Callback for a successful upload.
     @param fileInfo Information about the uploaded file.
     @param result The upload result.
     */
    typedef void (^OnUploadFinishedListener) (UploadFileInfo* fileInfo, VodUploadResult* result);
    /**
     Callback for a failed upload.
     @param fileInfo Information about the uploaded file.
     @param code The error code.
     @param message The error message.
     */
    typedef void (^OnUploadFailedListener) (UploadFileInfo* fileInfo, NSString *code, NSString * message);
    /**
     Callback for upload progress.
     @param fileInfo Information about the uploaded file.
     @param uploadedSize The size of the uploaded part.
     @param totalSize The total size of the file.
     */
    typedef void (^OnUploadProgressListener) (UploadFileInfo* fileInfo, long uploadedSize, long totalSize);
    /**
     Callback for an expired token.
     If you use an upload URL and credential, call the resumeWithAuth: method to resume the upload.
     If you use an STS token, call the resumeWithToken:accessKeySecret:secretToken:expireTime: method to resume the upload.
     */
    typedef void (^OnUploadTokenExpiredListener) ();
    /**
     Callback for the start of an upload retry.
     */
    typedef void (^OnUploadRertyListener) ();
    /**
     Callback for the end of an upload retry. The upload is resumed.
     */
    typedef void (^OnUploadRertyResumeListener) ();
    /**
     Callback for the start of an upload.
     If you use an upload URL and credential, call the setUploadAuthAndAddress:uploadAuth:uploadAddress: method to set the upload URL and credential.
     @param fileInfo Information about the uploaded file.
     */
    typedef void (^OnUploadStartedListener) (UploadFileInfo* fileInfo);
  4. Construct the upload parameters based on the file type, such as audio, video, or image.

    Note

    The upload parameters for audio or video files and image files are slightly different. The client does not support uploading auxiliary media assets.

    Audio and video file parameters

    Construct an upload request function to add an audio or video file to the upload list.

    Click to view the code

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"video_source_file_name" ofType:@"video_source_file_format_such_as_mp4"];
    VodInfo *vodInfo = [[VodInfo alloc] init];
    vodInfo.title = @"video_name_after_upload";
    vodInfo.desc = @"video_description_after_upload";
    vodInfo.cateId = @(video_category_id);
    vodInfo.tags = @"video_tags_such_as_sports";
    [self.uploader addFile:filePath vodInfo:vodInfo];

    VodInfo description

    Click to view the code

    // Title
    @property (nonatomic, copy) NSString* title;
    // Tags
    @property (nonatomic, copy) NSString* tags;
    // Description
    @property (nonatomic, copy) NSString* desc;
    // Category ID
    @property (nonatomic, strong) NSNumber* cateId;
    // Thumbnail URL (a complete URL that starts with https://)
    @property (nonatomic, copy) NSString* coverUrl;

    After you add a file, the SDK encapsulates the file into an UploadFileInfo object. The structure is as follows:

    Click to view the code

    // Local path of the file
    @property (nonatomic, copy) NSString* filePath;
    // Endpoint
    @property (nonatomic, copy) NSString* endpoint;
    // Bucket
    @property (nonatomic, copy) NSString* bucket;
    // Object
    @property (nonatomic, copy) NSString* object;
    // VodInfo
    @property (nonatomic, strong) VodInfo* vodInfo;
    Note

    To upload a video from a photo album, use the absolute path of the selected video as the file path for the upload.

    Image file parameters

    Click to view the code

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"image_source_file_name" ofType:@"image_source_file_format_such_as_jpg"];
    VodInfo *imageInfo = [[VodInfo alloc] init];
    imageInfo.title = @"image_name_after_upload";
    imageInfo.desc = @"image_description_after_upload";
    imageInfo.cateId = @(image_category_id);
    imageInfo.tags = @"image_tags_such_as_sports";
    [self.uploader addFile:filePath vodInfo:imageInfo];
  5. Start the upload.

    1. Call start to begin the upload.

      [self.uploader start];

      After this method is called, the OnUploadStartedListener callback is triggered. If you use an upload URL and credential, you must set the upload URL and credential in this callback method. The following code provides an example:

      [weakSelf.uploader setUploadAuthAndAddress:fileInfo uploadAuth:weakSelf.uploadAuth uploadAddress:weakSelf.uploadAddress];
    2. After the file starts uploading, the OnUploadProgressListener callback starts to synchronize the upload progress.

      The callback parameters include the size of the uploaded part (uploadedSize) and the total file size (totalSize).

    3. After the file is successfully uploaded, the OnUploadFinishedListener callback returns the uploaded file information (UploadFileInfo) and the upload result (VodUploadResult).

      The VodUploadResult object contains the following properties:

      @property (nonatomic, copy) NSString* videoId;
      @property (nonatomic, copy) NSString* imageUrl;
      Note

      The videoId property is returned only after a video is successfully uploaded using an STS token. The imageUrl property is returned only after an image is successfully uploaded using an STS token. If you use an upload URL and credential, videoId and imageUrl are not returned. You can obtain these values when you request the upload URL and credential.

Execution results

  • After a video is uploaded, a videoId is returned. Use this videoId to obtain a playback URL. For more information, see Obtain playback URLs.

  • After an image is uploaded, an imageUrl is returned. If you enable URL signing, the imageUrl has a time-to-live (TTL). For more information, see Configure URL signing.

Queue management

The VODUploadClient supports adding multiple files for sequential upload and provides the following methods to manage the upload queue:

Note

Although VODUploadClient supports uploading multiple files, you must set the upload credential and URL for each file individually if you use that method. Due to the complexity of the code for multi-file uploads, we recommend that you add and upload only one file at a time.

  • Delete a file from the upload queue. If the file is being uploaded, the upload is canceled, and the next file in the queue starts uploading automatically.

    - (BOOL)deleteFile:(int) index;
  • Clear the upload queue. If a file is being uploaded, the upload is canceled.

    - (BOOL)clearFiles;
  • Obtain the list of files in the upload queue.

    - (NSMutableArray<UploadFileInfo *> *)listFiles;
  • Mark a file as canceled. The file remains in the upload list. If the file is being uploaded, the upload is canceled, and the next file in the queue starts uploading automatically.

    - (BOOL)cancelFile:(int)index;
  • Resume the upload of a canceled file. The upload starts automatically.

    - (BOOL)resumeFile:(int)index;

Upload control

  • Stop the upload. If a file is being uploaded, the upload is canceled.

    - (BOOL)stop;
    Note

    After you stop an upload, you can call resumeFile to resume uploading the file, or clear the queue and add the file again to restart the upload.

  • Pause the upload.

    - (BOOL)pause;
  • Resume the upload.

    - (BOOL)resume;

Callback handling

  • Upload failure

    If an upload fails, the OnUploadFailedListener callback is triggered. In this callback method, you can view the cause of the failure from the code and message parameters and display a notification on the page. For more information about error codes, see Error codes and OSS error codes.

  • Expired credential handling

    If an upload credential or STS token expires, the OnUploadTokenExpiredListener callback is triggered. In this callback method, request a new upload credential or STS token from your app server and call one of the following methods to resume the upload.

    • Reset the upload credential

      - (BOOL)resumeWithAuth:(NSString *)uploadAuth;
    • Reset the STS token

      - (BOOL)resumeWithToken:(NSString *)accessKeyId
              accessKeySecret:(NSString *)accessKeySecret
                  secretToken:(NSString *)secretToken
                   expireTime:(NSString *)expireTime;
  • Timeout handling

    If an upload times out, the OnUploadRertyListener callback is triggered, and the upload is automatically retried. In this callback method, you can display a notification on the page or call the stop method to stop the upload. You can also set the maxRetryCount property to specify the maximum number of retries. If the upload can be resumed after a timeout retry, the OnUploadRertyResumeListener callback is triggered, and the upload resumes.

Advanced settings

The VODUploadClient supports advanced settings, such as upload acceleration, upload transcoding, timeout retries, setting the cache folder location, resumable uploads, multipart uploads, and setting the VOD service region. The following sections provide examples.

Upload acceleration

When you need to upload large files (in gigabytes or terabytes) or perform cross-region uploads, such as uploading a video from the Chinese mainland to a storage address in the Singapore storage region, you can enable the upload acceleration feature. For more information, see how to enable the feature. After you enable the feature, you must add the required key-value pair to the UserData string in the vodInfo configuration of the upload instance. This string must be in JSON format. The following example shows the configuration:

/** 
 Set custom data in VodInfo. 
*/
@property (nonatomic, copy) NSString *UserData;
vodInfo.UserData = "{\"Type\":\"oss\",\"Domain\":\"oss-accelerate.aliyuncs.com\"}";

Parameter descriptions

Name

Type

Description

Type

string

The type of upload acceleration to enable. Only `oss` is supported.

Domain

string

The accelerated domain name for the user's bucket. The default protocol is HTTPS.

Note

Use an accelerated domain name that is assigned after you enable the feature, such as vod-*******.oss-accelerate.aliyuncs.com.

Upload transcoding

/**
 Specifies whether to transcode the file on the server after upload. The default value is YES. To specify the output format for video transcoding, see Video transcoding.
 */
@property (nonatomic, assign) BOOL transcode;

Timeout and retry

/**
 The maximum number of retries. The default value is INT_MAX.
 */
@property (nonatomic, assign) uint32_t maxRetryCount;
/**
 The timeout period.
 */
@property (nonatomic, assign) NSTimeInterval timeoutIntervalForRequest;

Set the cache folder location

/**
 The location of the cache folder.
 */
@property (nonatomic, copy) NSString * recordDirectoryPath;

Resumable upload

/**
 Specifies whether to record the upload progress for resumable uploads. The default value is YES.
 */
@property (nonatomic, assign) BOOL recordUploadProgress;

Multipart upload

/**
 The part size. The default value is 1024 * 1024.
*/
@property (nonatomic, assign) NSInteger uploadPartSize;

Set the VOD service region

/**
 The VOD region. The default value is "cn-shanghai".
 */
@property (nonatomic, copy) NSString *region;