This topic describes how to use the upload SDK for iOS to upload a file.

Prerequisites

The upload SDK for iOS is integrated. For more information about how to integrate the upload SDK for iOS, see Integrate the upload SDK for iOS. For more information about how to download the demo for iOS, see the "Download client SDKs" section of SDK download.

Upload a file

This section describes the procedure for uploading a file by using the upload SDK for iOS.

  1. Request an upload URL and an upload credential or a Security Token Service (STS) token for upload authorization.

    The upload SDK for iOS supports the following two upload authorization methods:

    Verify the result

    Use the obtained upload URL and credential or the obtained STS token to initialize the upload instance.

  2. Use the upload URL and credential or the STS token to initialize an upload instance.

    The initialization process consists of the following two steps:

    1. Declare a VODUploadClient object, which cannot be a local variable.
    2. Initialize the upload instance. Use the upload URL and credential or the STS token to initialize the upload instance as needed.
      • Use the upload URL and credential (recommended)
        Note
        • If you use the upload URL and credential, 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 invoked when the upload starts.
        • If the upload credential expires, the OnUploadTokenExpiredListener callback is invoked. To resume the upload by using a new upload credential, call the resumeWithAuth method.
        // 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.");
            // Specify a new upload credential to resume the upload upon credential expiration.
            [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.");
            // Specify the upload URL and 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];
      • Use the STS token
        Note
        • If you use the STS token, call the init method to initialize the upload instance and the setKeyId:accessKeySecret:secretToken:expireTime:listener: method to specify the STS token.
        • If the STS token expires, the OnUploadTokenExpiredListener callback is invoked. To resume the upload by using a new STS token, call the resumeWithToken: accessKeySecret: secretToken: expireTime method.
        // 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.");
            // Specify a new STS token to resume the upload upon credential expiration.
            [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. Set callbacks to receive messages about key events in the upload process.

    Set the VODUploadListener object, which belongs to the class of callbacks for upload statuses. You must set the following callbacks:

    /**
     The callback that is invoked if the upload is successful.
     @param fileInfo The information about the file that you upload.
     @param result The upload result.
     */
    typedef void (^OnUploadFinishedListener) (UploadFileInfo* fileInfo, VodUploadResult* result);
    /**
     The callback that is invoked if the upload fails.
     @param fileInfo The information about the file that you upload.
     @param code The error code.
     @param message The error message.
     */
    typedef void (^OnUploadFailedListener) (UploadFileInfo* fileInfo, NSString *code, NSString * message);
    /**
     The callback that is invoked if the default or custom upload progress is reached.
     @param fileInfo The information about the file that you upload.
     @param uploadedSize The size of uploaded parts.
     @param totalSize The total size of the file that you upload.
     */
    typedef void (^OnUploadProgressListener) (UploadFileInfo* fileInfo, long uploadedSize, long totalSize);
    /**
     The callback that is invoked if the upload credential or STS token expires.
     If you use the upload URL and credential to upload a file, call the resumeWithAuth: method to resume the upload.
     If you use the STS token to upload a file, call the resumeWithToken:accessKeySecret:secretToken:expireTime: method to resume the upload.
     */
    typedef void (^OnUploadTokenExpiredListener) ();
    /**
     The callback that is invoked if the system retries the upload.
     */
    typedef void (^OnUploadRertyListener) ();
    /**
     The callback that is invoked if the system resumes the upload after the upload retry is complete.
     */
    typedef void (^OnUploadRertyResumeListener) ();
    /**
     The callback that is invoked if the upload starts.
     If you use the upload URL and credential to upload a file, call the setUploadAuthAndAddress:uploadAuth:uploadAddress: method to specify the upload URL and credential.
     @param fileInfo The information about the file that you upload.
     */
    typedef void (^OnUploadStartedListener) (UploadFileInfo* fileInfo);
  4. Set upload parameters based on the type of the file that you want to upload. The file can be an audio file, a video file, or an image file.
    Note The upload parameters for audio and video files are different from those for image files. You cannot upload auxiliary media assets by using client upload SDKs.
    Upload parameters for audio and video files

    Set the upload parameters for adding an audio or video file to the upload list.

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Name of the source video file" ofType:@"Format of the source video file, such as MP4"];
    VodInfo *vodInfo = [[VodInfo alloc] init];
    vodInfo.title = @"Name of the uploaded video";
    vodInfo.desc =@"Description of the uploaded video";
    vodInfo.ca teId = @(Category ID of the uploaded video);
    vodInfo.tags = @"Video tags, such as sports";
    [self.uploader addFile:filePath vodInfo:vodInfo];
    Structure of the VodInfo object
    // The title.
    @property (nonatomic, copy) NSString* title;
    // The tags.
    @property (nonatomic, copy) NSString* tags;
    // The description.
    @property (nonatomic, copy) NSString* desc;
    // The category ID.
    @property (nonatomic, strong) NSNumber* cateId;
    // The URL of the thumbnail. The value must be a complete URL that starts with https://.
    @property (nonatomic, copy) NSString* coverUrl;
    After you add a file to be uploaded, the SDK encapsulates the file in the UploadFileInfo object that has the following structure:
    // The 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 If you need to upload a video from an album, set the filePath parameter to the absolute path of the video that is selected by using the selector.
    Upload parameters for image files
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Name of the source image file" ofType:@"Format of the source image file, such as JPG"];
    VodInfo *imageInfo = [[VodInfo alloc] init];
    vodInfo.title = @"Name of the uploaded image";
    vodInfo.desc =@"Description of the uploaded image";
    vodInfo.ca teId = @(Category ID of the uploaded image);
    vodInfo.tags = @"Image tags, such as sports";
    [self.uploader addFile:filePath vodInfo:imageInfo];
  5. Start the upload.
    1. The start method is called to start the upload.
      [self.uploader start];
      When this method is called, the OnUploadStartedListener callback is invoked. If you use an upload URL and an upload credential to upload a file, specify the upload URL and credential in this callback, as shown in the following code:
      [weakSelf.uploader setUploadAuthAndAddress:fileInfo uploadAuth:weakSelf.uploadAuth uploadAddress:weakSelf.uploadAddress];
    2. When the upload starts, the OnUploadProgressListener callback is invoked to synchronize the upload progress.

      The callback parameters include uploadedSize and totalSize. The uploadedSize parameter specifies the size of uploaded parts, and the totalSize parameter specifies the total size of the file that you upload.

    3. If the file is uploaded, the OnUploadFinishedListener callback is invoked. The callback parameters include UploadFileInfo and VodUploadResult. The UploadFileInfo parameter specifies the information about the file that you upload, and the VodUploadResult parameter specifies the upload result.
      The VodUploadResult object contains the following properties:
      @property (nonatomic, copy) NSString* videoId;
      @property (nonatomic, copy) NSString* imageUrl;
      Note The videoId or imageUrl parameter is returned only when a video or an image is uploaded to ApsaraVideo VOD by using an STS token. If you use an upload URL and an upload credential to upload a video or an image, the videoId or imageUrl parameter is not returned. You can obtain the parameter value when you request an upload URL and an upload credential.
Upload results
  • After a video is uploaded, the videoId parameter is returned, which indicates the video ID. Then, you can obtain the streaming URL based on the video ID 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 URL authentication.

Manage the upload list

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

Note The VODUploadClient object allows you to upload multiple files. However, if you use upload URLs and credentials to upload 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;

Control the upload

  • Stop the upload. If a file is being uploaded, the system cancels the upload.
    - (BOOL)stop;
    Note If you need 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;

Handle callbacks

  • Upload failure

    The OnUploadFailedListener callback is invoked if the upload fails. You can obtain the cause of the failure based on the code and message callback parameters. In addition, you can display a prompt on the client. 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 display a prompt on the client 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 object supports the following advanced settings: transcoding, retries upon a timeout, cache path, resumable upload, multipart upload, and service region. Sample code:

Transcoding
/**
 Specify whether to transcode a video after it is uploaded to ApsaraVideo VOD. Default value: YES. For more information about video transcoding formats, see Audio and video transcoding. 
 */
@property (nonatomic, assign) BOOL transcode;
Retires upon a timeout
/**
 Specify the maximum number of retries allowed upon a timeout. Default value: INT_MAX.
 */
@property (nonatomic, assign) uint32_t maxRetryCount;
/**
 Specify the timeout period.
 */
@property (nonatomic, assign) NSTimeInterval timeoutIntervalForRequest;
Cache path
/**
 Specify the path of the directory in which cached data is stored.
 */
@property (nonatomic, copy) NSString * recordDirectoryPath;
Resumable upload
/**
 Specify whether to record the upload progress for a resumable upload. Default value: YES.
 */
@property (nonatomic, assign) BOOL recordUploadProgress;
Multipart upload
/**
 Specify the size of each part in multipart upload. Default value: 1024 × 1024.
*/
@property (nonatomic, assign) NSInteger uploadPartSize;
Service region
/**
 Specify the region of the ApsaraVideo VOD service. Default value: cn-shanghai.
 */
@property (nonatomic, copy) NSString *region;