美文网首页iOS开发拾碎
iOS 上传图片等资源至阿里云的工具类整理

iOS 上传图片等资源至阿里云的工具类整理

作者: 王加水 | 来源:发表于2021-03-24 11:40 被阅读0次

    前言

    阿里云的对象存储OSS作为常用的上传存储图片音视频等资源的产品, 这里相关的前期集成这里且按下不表, 列位根据官方文档集成即可(官方文档传送门) , 这里只是写成一个工具类方便大家开发使用.

    晒代码

    过程相对简单分两步:

    1. 协商后台给一个接口获取STS参数信息信息
    2. 利用官方SDK拼接好参数,上传至云存储,获取回调

    下面是代码示例, 写成了一个工具类, +方法调用

    .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,    //视频
        //...自己根据实际需求添加枚举用于区分业务需要类型
    };
    @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参数信息
        NSMutableDictionary * param = [NSMutableDictionary dictionary];
        if (type == RPUploadSourceToAliyunOSSTypeImg) {
            param[@"type"] = @"与后台协商字符串区分类型";
        }else if(type == RPUploadSourceToAliyunOSSTypeAudio){
            param[@"type"] = @"与后台协商字符串区分类型";
        }else if (type == RPUploadSourceToAliyunOSSTypeVideo){
            param[@"type"] = @"与后台协商字符串区分类型";
        }
        //RPNetworkManager需替换, 换成自己用项目中集成的网络请求即可
        //kGetAliOSS_STS_InfoURL, 换成自己后台给的获取STS参数信息的接口
        [RPNetworkManager post:kGetAliOSS_STS_InfoURL params:param isShowLoad:NO success:^(id  _Nonnull json) {
            //2.调用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"];
            
            //拼接资源名称 (可根据业务需要自行拼接实际名称)
            //例如下面强制写死图片名为avatar,则存储文件永远在替换为最新的名为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;
    }
    

    当然还是要参考最新的官方Demo传送门

    相关文章

      网友评论

        本文标题:iOS 上传图片等资源至阿里云的工具类整理

        本文链接:https://www.haomeiwen.com/subject/fynchltx.html