Implementation of uploading / downloading OSS files for iOS Alibaba cloud object storage

Posted by ajcalvert on Mon, 07 Mar 2022 21:41:25 +0100

In previous projects, resource files such as pictures and voice were directly uploaded to the server, and then processed and stored by the server. In this recent project, the server opens the OSS directly, and then the client uses it directly Alibaba cloud Provide upload and download functions to upload and download resources.
Alibaba cloud The processing of pictures is in place, and the size can be customized when obtaining pictures.
First import in the project Alibaba cloud For OSS library, add the following code directly to pod:

pod 'AliyunOSSiOS'

If you don't use pod, you can click this link to download:
We can encapsulate an OSS tool class to manage file upload and download. OSS initialization and configuration code:

//The following parameters are available on the server side
#define ACCSECRET @"2QgUjalQoBsdLn2iYFpqW0TEST"
#define ENDPOINT @""

#import "BZHttpFileHelper.h"
#import <AliyunOSSiOS/OSSService.h>

@interface BZHttpFileHelper ()

@property(nonatomic,strong) OSSClient * client;


@implementation BZHttpFileHelper
    static BZHttpFileHelper * fileHelper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        fileHelper = [[BZHttpFileHelper alloc] init];
        [fileHelper initAliClient];
    return fileHelper;

    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:ACCKEY                                                                                                    secretKey:ACCSECRET];

    OSSClientConfiguration * conf = [OSSClientConfiguration new];

    // The number of retries after the network request encountered an abnormal failure
    conf.maxRetryCount = 3;

    // Timeout for network requests
    conf.timeoutIntervalForRequest =30;

    // Maximum time allowed for resource transfer
    conf.timeoutIntervalForResource =24 * 60 * 60;

    // Your Alibaba address is usually preceded by this format: http://oss ……
    self.client = [[OSSClient alloc] initWithEndpoint:ENDPOINT credentialProvider:credential];

File upload: convert the file into NSData to upload directly:

-(void)uploadAmr:(NSData *)amrData amrName:(NSString *)amrName callback:(void (^)(BOOL))callback{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = @"test";
    put.objectKey = amrName;
    put.uploadingData = amrData; // Upload NSData directly
    put.uploadProgress = ^(int64_t bytesSent,int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);

    OSSTask * putTask = [self.client putObject:put];

    // Upload [Alibaba cloud](
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"upload object success!");
            if (callback) {
        } else {

            NSLog(@"upload object failed, error: %@" , task.error);
            if (callback) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
                [window makeToast:@"File upload failed" duration:1.5 position:CSToastPositionCenter];
        return nil;

File download:

-(void)downloadFile:(NSString *)filename callback:(void (^)(NSData *, BOOL))callback{
    OSSGetObjectRequest * request = [OSSGetObjectRequest new];
    request.bucketName = @"savemoney";
    request.objectKey = filename;
    OSSTask * getTask = [self.client getObject:request];
    [getTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"download object success!");
            OSSGetObjectResult * getResult = task.result;
            if (callback) {
        } else {
            NSLog(@"download object failed, error: %@" ,task.error);
            if (callback) {
        return nil;

When uploading, the file name is defined by us. When downloading, just take this file name to download.
Therefore, after using OSS, the step of uploading pictures and other files is that our client first uploads the file to OSS, and then sends the file name to the server through the interface. The server stores the file name, and the server gives us the file name where we need the file, and then we go to OSS to get it.
Also refer to Alibaba cloud OSS development documents:
Finally, let's talk about the loading of pictures. We can read pictures in the format we need. We can write a classification of NSURL to return the paths of different pictures.
Because the server stores the file name, read the cdn domain name + file name of the original image, and use the following code to obtain the full path of the image:

+(NSURL *)photourlWithUrlString:(NSString *)url{
    //Original drawing
    return [NSURL URLWithString:[NSString stringWithFormat:@"",url]];

+(NSURL *)s_photourlWithUrlString:(NSString *)url{
//120 * 120 pictures
    return [NSURL URLWithString:[NSString stringWithFormat:@",w_120,h_120",url]];

+(NSURL *)s_chatPhotourlWithUrlString:(NSString *)url{
    return [NSURL URLWithString:[NSString stringWithFormat:@",m_lfit,h_200,w_200",url]];

For more picture styles and processing, please refer to the official documents:
OSS's support for image processing is really in place and easy to use.

Topics: server Alibaba Cloud Huawei Cloud Cloud Server cloud serving