iOS 上傳圖片等資源至阿里云的工具類整理

前言

阿里云的對象存儲OSS作為常用的上傳存儲圖片音視頻等資源的產(chǎn)品, 這里相關(guān)的前期集成這里且按下不表, 列位根據(jù)官方文檔集成即可(官方文檔傳送門) , 這里只是寫成一個工具類方便大家開發(fā)使用.

曬代碼

過程相對簡單分兩步:

  1. 協(xié)商后臺給一個接口獲取STS參數(shù)信息信息
  2. 利用官方SDK拼接好參數(shù),上傳至云存儲,獲取回調(diào)

下面是代碼示例, 寫成了一個工具類, +方法調(diào)用

.h
//
//  RPCustomTool.h
//  RPCustomProject
//
//  Created by RollingPin on 2021/03/23.
//  Copyright ? 2021 RollingPin. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <AliyunOSSiOS/OSSService.h>
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

typedef NS_ENUM(NSUInteger, RPUploadSourceToAliyunOSSType) {
    RPUploadSourceToAliyunOSSTypeImg = 0,  //圖片
    RPUploadSourceToAliyunOSSTypeAudio,    //音頻
    RPUploadSourceToAliyunOSSTypeVideo,    //視頻
    //...自己根據(jù)實際需求添加枚舉用于區(qū)分業(yè)務(wù)需要類型
};
@interface RPCustomTool : NSObject
// 上傳圖片語音等資源至阿里云存儲
+ (void)uploadSourceToAliyunOSBySTSWithType:(RPUploadSourceToAliyunOSSType )type
                                 sourceData:(NSData *)sourceData
                                 sourceName:(NSString *)sourceName
                                    success:(void (^)(NSDictionary* infoDic))success
                                    failure:(void (^)(NSDictionary* infoDic))failure;
@end

NS_ASSUME_NONNULL_END

.m
//
//  RPCustomTool.h
//  RPCustomProject
//
//  Created by RollingPin on 2021/03/23.
//  Copyright ? 2021 RollingPin. All rights reserved.
//

#import "QJYCustomTool.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/PHPhotoLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>
OSSClient * client;

@implementation QJYCustomTool
+ (void)uploadSourceToAliyunOSBySTSWithType:(RPUploadSourceToAliyunOSSType )type
                                 sourceData:(NSData *)sourceData
                                 sourceName:(NSString *)sourceName
                                    success:(void (^)(NSDictionary* infoDic))success
                                    failure:(void (^)(NSDictionary* infoDic))failure;
{
    //1.先從后臺獲取STS參數(shù)信息
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    if (type == RPUploadSourceToAliyunOSSTypeImg) {
        param[@"type"] = @"與后臺協(xié)商字符串區(qū)分類型";
    }else if(type == RPUploadSourceToAliyunOSSTypeAudio){
        param[@"type"] = @"與后臺協(xié)商字符串區(qū)分類型";
    }else if (type == RPUploadSourceToAliyunOSSTypeVideo){
        param[@"type"] = @"與后臺協(xié)商字符串區(qū)分類型";
    }
    //RPNetworkManager需替換, 換成自己用項目中集成的網(wǎng)絡(luò)請求即可
    //kGetAliOSS_STS_InfoURL, 換成自己后臺給的獲取STS參數(shù)信息的接口
    [RPNetworkManager post:kGetAliOSS_STS_InfoURL params:param isShowLoad:NO success:^(id  _Nonnull json) {
        //2.調(diào)用AliyunOSS_SDK上傳資源
        NSString * AccessKeyId = [json objectForKey:@"AccessKeyId"];
        NSString * AccessKeySecret = [json objectForKey:@"AccessKeySecret"];
        NSString * SecurityToken = [json objectForKey:@"SecurityToken"];
        NSString * endpoint = [json objectForKey:@"endpoint"];
        NSString * domain = [json objectForKey:@"domain"];
        id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:AccessKeyId secretKeyId:AccessKeySecret securityToken:SecurityToken];
        
        OSSClientConfiguration * conf = [OSSClientConfiguration new];
        conf.maxRetryCount = 2;
        conf.timeoutIntervalForRequest = 30;
        conf.timeoutIntervalForResource = 24 * 60 * 60;

        client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];
        
        OSSPutObjectRequest * put = [OSSPutObjectRequest new];
        // required fields
        put.bucketName = [json objectForKey:@"bucket"];
        
        //拼接資源名稱 (可根據(jù)業(yè)務(wù)需要自行拼接實際名稱)
        //例如下面強制寫死圖片名為avatar,則存儲文件永遠(yuǎn)在替換為最新的名為avatar的圖片,方便頭像更新
        NSString * sourceName_check = @"";
        if (type == RPUploadSourceToAliyunOSSTypeImg) {
            sourceName_check = [NSString stringWithFormat:@"avatar.%@",[QJYCustomTool imageFormatFromImageData:sourceData]];
        }else{
            sourceName_check = sourceName;
        }
        put.objectKey = [NSString stringWithFormat:@"%@/%@",[json objectForKey:@"prefix"],sourceName_check];
        put.uploadingData = sourceData;

        // optional fields
        put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//                NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
            };
        put.contentType = @"";
        put.contentMd5 = @"";
        put.contentEncoding = @"";
        put.contentDisposition = @"";

        OSSTask * putTask = [client putObject:put];
        
        [putTask waitUntilFinished]; // 阻塞直到上傳完成
//       Warning: A long-running operation is being executed on the main thread. Break on warnBlockingOperationOnMainThread() to debug.
        if (!putTask.error) {
            NSLog(@"upload object success!");
            NSDictionary * callBackDic = @{@"status":@"1",
                                          @"content":put.objectKey,
                                           @"domain":domain
            };
            success(callBackDic);
        } else {
            NSLog(@"upload object failed, error: %@" , putTask.error);
            NSDictionary * callBackDic = @{@"status":@"0",
                                          @"content":@"SDK錯誤"};
            failure(callBackDic);
        }
    } failure:^(NSError * _Nonnull error) {
        NSDictionary * callBackDic = @{@"status":@"0",
                                     @"content":@"獲取STS信息接口失敗"};
        failure(callBackDic);
    }];
}
#pragma mark - 獲取圖片格式
+ (NSString *)imageFormatFromImageData:(NSData *)imageData{
    
    uint8_t first_byte;
    [imageData getBytes:&first_byte length:1];
    switch (first_byte) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
        case 0x52:
            if ([imageData length] < 12) {
                return @"";
            }
            NSString *dataString = [[NSString alloc] initWithData:[imageData subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([dataString hasPrefix:@"RIFF"] && [dataString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return @"";
    }
    return nil;
}

當(dāng)然還是要參考最新的官方Demo傳送門

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容