All Products
Search
Document Center

ApsaraVideo VOD:Upload a file by using the iOS SDK

Last Updated:May 27, 2025

This topic describes how to use the iOS SDK to upload media files from a local device to ApsaraVideo VOD.

Prerequisites

  • The iOS version is iOS 8 or later.

  • The iOS upload SDK does not support Swift programming.

Integrate the SDK

Integration methods

Integrate the SDK by using pod (recommended)

  1. Run the pod 'VODUpload' command to add the VOD upload SDK dependency to the Podfile.

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

  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

  • Download package MD5 hash: f3551634b53cd1264013db4762f79a14

  • Download URL: V1.6.5 SDK

  1. In Xcode, drag VODUpload.framework and AliyunOSSiOS.framework to the 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 the project and modify the configuration by performing the following steps.

  1. Click Build Setting > Linking > Other Linker Flags in the menu bar.

  2. Add -Objc.

Basic settings

Initialize the upload instance

First, understand the client upload process, and deploy the corresponding authorization service based on the upload authorization method:

  1. If you choose to use the upload URL and credential method, obtain the upload URL and credential in the authorization service.

  2. If you choose to use the STS Token method, obtain the STS Token in the authorization service.

You need to configure the initialization callback before you initialize the upload instance.

  1. Declare the VODUploadClient property, which cannot be a local variable.

  2. Initialize the upload instance.

    Upload URL and credential method

    Note
    • If you use the upload URL and credential method, call the init method to initialize the upload instance.

    • You do not need to specify the obtained upload URL and credential during initialization. Instead, specify them in the SDK by calling the setUploadAuthAndAddress: uploadAuth:uploadAddress: method in the OnUploadStartedListener callback that is fired when the upload starts.

    • If the token expires, the OnUploadTokenExpiredListener callback is fired. To resume the upload by using a new upload credential, call the resumeWithAuth method.

    Show 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 callback videoid:%@, imageurl:%@", result.videoId, result.imageUrl);
    };
    OnUploadFailedListener FailedCallbackFunc = ^(UploadFileInfo* fileInfo, NSString *code, NSString* message){
        NSLog(@"upload failed callback code = %@, error message = %@", code, message);
    };
    OnUploadProgressListener ProgressCallbackFunc = ^(UploadFileInfo* fileInfo, long uploadedSize, long totalSize) {
        NSLog(@"upload progress callback uploadedSize : %li, totalSize : %li", uploadedSize, totalSize);
    };
    OnUploadTokenExpiredListener TokenExpiredCallbackFunc = ^{
        NSLog(@"upload token expired callback.");
        // When token expires, set a new upload credential to continue uploading
        [weakSelf.uploader resumeWithAuth:`new upload auth`];
    };
    OnUploadRertyListener RetryCallbackFunc = ^{
        NSLog(@"upload retry begin callback.");
    };
    OnUploadRertyResumeListener RetryResumeCallbackFunc = ^{
        NSLog(@"upload retry end callback.");
    };
    OnUploadStartedListener UploadStartedCallbackFunc = ^(UploadFileInfo* fileInfo) {
        NSLog(@"upload upload started callback.");
        // 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;
    // init with upload address and upload auth
    [self.uploader init:listener];

    STS Token method

    Note
    • If you use the STS method, call the init method to initialize the upload instance and pass the temporary STS credential through the setKeyId:accessKeySecret:secretToken:expireTime:listener: interface.

    • When the token expires, the OnUploadTokenExpiredListener callback is fired. To resume the upload by using a new STS token, call the resumeWithToken: accessKeySecret: secretToken: expireTime method.

    Show 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 callback videoid:%@, imageurl:%@", result.videoId, result.imageUrl);
    };
    OnUploadFailedListener FailedCallbackFunc = ^(UploadFileInfo* fileInfo, NSString *code, NSString* message){
        NSLog(@"upload failed callback code = %@, error message = %@", code, message);
    };
    OnUploadProgressListener ProgressCallbackFunc = ^(UploadFileInfo* fileInfo, long uploadedSize, long totalSize) {
        NSLog(@"upload progress callback uploadedSize : %li, totalSize : %li", uploadedSize, totalSize);
    };
    OnUploadTokenExpiredListener TokenExpiredCallbackFunc = ^{
        NSLog(@"upload token expired callback.");
        // When token expires, set a new STS to continue uploading
        [weakSelf.uploader resumeWithToken:`STS Key Id` accessKeySecret:`STS Key Secret` secretToken:`STS Secret Token` expireTime:`STS Expire Time`];
    };
    OnUploadRertyListener RetryCallbackFunc = ^{
        NSLog(@"upload retry begin callback.");
    };
    OnUploadRertyResumeListener RetryResumeCallbackFunc = ^{
        NSLog(@"upload retry end callback.");
    };
    OnUploadStartedListener UploadStartedCallbackFunc = ^(UploadFileInfo* fileInfo) {
        NSLog(@"upload upload started callback.");
    };
    // init
    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 STS and listener
    [self.uploader setKeyId:`STS Key Id` accessKeySecret:`STS Key Secret` secretToken:STS Secret Token` expireTime:`STS Expire Time` listener:listener];
  3. Configure callbacks to receive key messages during the upload.

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

    Show code

    /**
     Upload completion callback
     @param fileInfo Upload file information
     @param result Upload result information
     */
    typedef void (^OnUploadFinishedListener) (UploadFileInfo* fileInfo, VodUploadResult* result);
    /**
     Upload failure callback
     @param fileInfo Upload file information
     @param code Error code
     @param message Error description
     */
    typedef void (^OnUploadFailedListener) (UploadFileInfo* fileInfo, NSString *code, NSString * message);
    /**
     Upload progress callback
     @param fileInfo Upload file information
     @param uploadedSize Uploaded size
     @param totalSize Total size
     */
    typedef void (^OnUploadProgressListener) (UploadFileInfo* fileInfo, long uploadedSize, long totalSize);
    /**
     Token expiration callback
     For upload URL and credential method, call resumeWithAuth: method to continue uploading
     For STS method, call resumeWithToken:accessKeySecret:secretToken:expireTime: method to continue uploading
     */
    typedef void (^OnUploadTokenExpiredListener) ();
    /**
     Upload retry start callback
     */
    typedef void (^OnUploadRertyListener) ();
    /**
     Upload retry end, continue upload callback
     */
    typedef void (^OnUploadRertyResumeListener) ();
    /**
     Upload start callback
     For upload URL and credential method, call setUploadAuthAndAddress:uploadAuth:uploadAddress: method to set upload URL and credential
     @param fileInfo Upload file information
     */
    typedef void (^OnUploadStartedListener) (UploadFileInfo* fileInfo);
  4. Construct upload parameters based on the file type (audio/video or image).

    Note

    The upload parameters for audio/video and images are slightly different. Currently, the client does not support uploading auxiliary media assets.

    Audio/video file parameters

    Construct an upload request function to add audio/video files to the upload list.

    Show code

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Name of the video source file" ofType:@"Format of the video source file, such as mp4"];
    VodInfo *vodInfo = [[VodInfo alloc] init];
    vodInfo.title = @"Name of the video after upload";
    vodInfo.desc =@"Description of the video after upload";
    vodInfo.cateId = @(Video category ID);
    vodInfo.tags = @"Video tags, such as sports";
    [self.uploader addFile:filePath vodInfo:vodInfo];

    VodInfo description

    Show 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;
    // Cover URL (complete URL with https://)
    @property (nonatomic, copy) NSString* coverUrl;

    After adding a file, the SDK will encapsulate the file to be uploaded as an UploadFileInfo object with the following structure:

    Show code

    // File local path
    @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

    If you need to upload videos from an album, use the absolute path of the selected video obtained through the selector as the filepath for uploading.

    Image file parameters

    Show code

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Name of the image source file" ofType:@"Format of the image source file, such as jpg"];
    VodInfo *imageInfo = [[VodInfo alloc] init];
    imageInfo.title = @"Name of the image after upload";
    imageInfo.desc =@"Description of the image after upload";
    imageInfo.cateId = @(Image category ID);
    imageInfo.tags = @"Image tags, such as sports";
    [self.uploader addFile:filePath vodInfo:imageInfo];
  5. Start uploading.

    1. Call start to begin uploading.

      [self.uploader start];

      After this method is called, the OnUploadStartedListener callback is triggered. If you are using the upload URL and credential method, you need to set the upload URL and credential in this callback method. The code is as follows:

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

      The callback parameters include the uploaded file size uploadedSize and the total file size totalSize.

    3. After the file is successfully uploaded, the OnUploadFinishedListener callback will return the upload file information UploadFileInfo and the upload result VodUploadResult.

      VodUploadResult contains the following properties:

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

      videoId is only returned after a successful video upload using the STS method, and imageUrl is only returned after a successful image upload using the STS method. If you use the upload URL and credential method, videoId and imageUrl will not be returned. The corresponding values can be obtained when requesting the upload URL and credential.

Result

  • After a video is uploaded, the videoId parameter is returned. The value of the videoId parameter indicates the video ID. Then, you can obtain the streaming URL to play the video. For more information, see Obtain playback URLs to play videos.

  • After an image is uploaded, the imageUrl parameter is returned, which indicates the image URL. If URL signing is enabled, the image URL expires after a specific period of time. For more information, see Configure URL signing.

Queue management

The upload instance VODUploadClient allows you to add multiple files to be uploaded in sequence. You can use the following methods to manage the upload list:

Note

The VODUploadClient object allows you to upload multiple files at a time. However, if you use upload URLs and credentials to upload media files, you must separately set the configuration for each file. The code for uploading multiple files at a time is complex. Therefore, we recommend that you add a single file to the upload list at a time.

  • Remove a file from the upload list. If the file to be removed is being uploaded, the system cancels the upload and automatically starts to upload the next file in the list.

    - (BOOL)deleteFile:(int) index;
  • Clear the upload list. If the upload list to be cleared contains a file that is being uploaded, the system cancels the upload.

    - (BOOL)clearFiles;
  • Query the upload list.

    - (NSMutableArray<UploadFileInfo *> *)listFiles;
  • Mark a file in the upload list as canceled without removing it from the upload list. If the file to be canceled is being uploaded, the system cancels the upload and automatically starts to upload the next file in the list.

    - (BOOL)cancelFile:(int)index;
  • Resume a canceled file and automatically start to upload the file.

    - (BOOL)resumeFile:(int)index;

Upload control

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

    - (BOOL)stop;
    Note

    If you want to resume the upload after you stop the upload, call the resumeFile method. Alternatively, clear the upload list and add the file again to upload it.

  • Pause the upload.

    - (BOOL)pause;
  • Resume the upload.

    - (BOOL)resume;

Callback handling

  • Upload failure

    The OnUploadFailedListener callback is invoked if the upload fails. You can view the cause of the failure based on the code and message callback parameters. In addition, a prompt is displayed on the web page. For more information about error codes, see Error codes and Handle exceptions.

  • Credential or token expiration

    The OnUploadTokenExpiredListener callback is invoked if the upload credential or STS token expires. You can send a request to the AppServer to obtain a new upload credential or STS token, and call the following method to resume the upload:

    • Specify a new upload credential

      - (BOOL)resumeWithAuth:(NSString *)uploadAuth;
    • Specify a new STS token

      - (BOOL)resumeWithToken:(NSString *)accessKeyId
              accessKeySecret:(NSString *)accessKeySecret
                  secretToken:(NSString *)secretToken
                   expireTime:(NSString *)expireTime;
  • Upload timeout

    If the upload times out, the OnUploadRertyListener callback is invoked and the system automatically retries to upload the file. You can receive a prompt on the web page or call the stop method to stop the upload. In addition, you can set the maxRetryCount parameter to specify the maximum number of retries. If the retry result indicates that the upload can be resumed, the OnUploadRertyResumeListener callback is invoked and the upload is resumed.

Advanced settings

The VODUploadClient instance supports the following advanced settings: transcoding, retries upon a timeout, cache path, resumable upload, multipart upload, and service region. Sample code:

Upload acceleration

If you want to upload large files of gigabytes or terabytes, or upload videos across regions, such as to a storage address in the Singapore region from the Chinese mainland, you can enable the upload acceleration feature. For more information, see Enable upload acceleration. After you enable upload acceleration, you must add the corresponding key-value value to the UserData string assignment in the vodInfo configuration of the uploaded instance. Sample code:

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

Parameters

Parameter

Type

Description

Type

string

The type for which you want to enable upload acceleration. Only OSS is supported.

Domain

string

The accelerated domain name of the bucket. Default value: https.

Note

An accelerated endpoint that is assigned after you enable upload acceleration, such as vod-*******.oss-accelerate.aliyuncs.com.

Transcoding

/**
 Whether to transcode the file when uploading to the server, default value is YES. For formats generated by video transcoding, see: Audio and video transcoding.
 */
@property (nonatomic, assign) BOOL transcode;

Retry upon a timeout

/**
 Maximum timeout retry count, default value is INT_MAX
 */
@property (nonatomic, assign) uint32_t maxRetryCount;
/**
 Timeout interval
 */
@property (nonatomic, assign) NSTimeInterval timeoutIntervalForRequest;

Cache path

/**
 Cache folder location
 */
@property (nonatomic, copy) NSString * recordDirectoryPath;

Resumable upload

/**
 Whether to record upload progress (resumable upload), default value is YES
 */
@property (nonatomic, assign) BOOL recordUploadProgress;

Multipart upload

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

Service region

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