iOS开发-阿里云上传图片

前言:项目中需要用到阿里云上传图片,而且用的地方有点多,废话不多说,直接封装了一下。

  • 导入阿里云SDK
  • 封装代码
1.导入阿里云SDK

注意事项:如果项目中已经使用过阿里云实人认证的,AliyunOSSiOS已经存在了,就不需要导入,不然会重复导入导致项目编译不了。

2.封装代码

1.新建一个类 BNNUploadAliCloudTool

typedef void(^successBlock)(NSString *imagUrl,UIImage *avImage);
typedef void(^failureBlock)(NSString *taskError);

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface BNNUploadAliCloudTool : NSObject

@property (nonatomic, strong) successBlock testSuccessBlock;
@property (nonatomic, strong) failureBlock testFailureBlock;



+ (BNNUploadAliCloudTool *)shareInstance;

- (void)shareUploadAliCloudImageWithSelfView:(UIView *)currentView SuccessBlock:(successBlock)successBlock failureBlock:(failureBlock)failureBlock;


#import "BNNUploadAliCloudTool.h"

NSString * const AccessKey2 = @"你的AccessKey";
NSString * const SecretKey2 = @"你的SecretKey";

@interface BNNUploadAliCloudTool ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
/********************** 阿里云 **********************/
{
    OSSClient * client;
}

/** 图片文件流 */
@property(nonatomic,strong)NSData *imageData;

@end


@implementation BNNUploadAliCloudTool

+ (BNNUploadAliCloudTool *)shareInstance{
    static BNNUploadAliCloudTool *bnnHomeWXShareTool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        bnnHomeWXShareTool = [[BNNUploadAliCloudTool alloc]init];
    });
    return bnnHomeWXShareTool;
}

- (void)shareUploadAliCloudImageWithSelfView:(UIView *)currentView SuccessBlock:(successBlock)successBlock failureBlock:(failureBlock)failureBlock{
    
    self.testSuccessBlock = successBlock;
    self.testFailureBlock = failureBlock;
    
    // 同步到主线程
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updataImageButtonActionWithCurrentView:currentView];
    });
   
}


#pragma mark -  上传照片
/** 上传照片 */
- (void)updataImageButtonActionWithCurrentView:(UIView *)currentView{
    
    UIAlertController *userIconActionSheet = [UIAlertController alertControllerWithTitle:@"请选择上传类型" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //相册选择
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"相册选择");
        //这里加一个判断,是否是来自图片库
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
            UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
            imagePicker.delegate = self;            //协议
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            
            [[[MYDCommomMethods sharedInstance] navigationControllerFromView:currentView] presentViewController:imagePicker animated:YES completion:nil];
            
            
        }
    }];
    //系统相机拍照
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"相机选择");
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [[[MYDCommomMethods sharedInstance] navigationControllerFromView:currentView] presentViewController:imagePicker animated:YES completion:nil];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //取消
        NSLog(@"取消");
    }];
    [userIconActionSheet addAction:albumAction];
    [userIconActionSheet addAction:photoAction];
    [userIconActionSheet addAction:cancelAction];

    [[[MYDCommomMethods sharedInstance] navigationControllerFromView:currentView] presentViewController:userIconActionSheet animated:YES completion:nil];
    
}
#pragma mark 调用系统相册及拍照功能实现方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *avatar = info[UIImagePickerControllerOriginalImage];
    //处理完毕,回到个人信息页面
    [picker dismissViewControllerAnimated:YES completion:NULL];
    //判断图片是不是png格式的文件
    if (UIImagePNGRepresentation(avatar)) {
        //返回为png图像。
        UIImage *imagenew = [self imageWithImageSimple:avatar scaledToSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.imageData = UIImagePNGRepresentation(imagenew);
    }else {
        //返回为JPEG图像。
        UIImage *imagenew = [self imageWithImageSimple:avatar scaledToSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.imageData = UIImageJPEGRepresentation(imagenew, 0.1);
    }
    
  
#warning 参数设置
    NSString *endpoint = @"";
    // 明文设置secret的方式建议只在测试时使用,更多鉴权模式参考后面链接给出的官网完整文档的`访问控制`章节
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey2
                                                                                                            secretKey:SecretKey2];
    client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // required fields
#warning 参数设置
    put.bucketName = @"";
    NSString *objectKeys = [NSString stringWithFormat:@"%@.png",[self getTimeNow]];
    
    put.objectKey = objectKeys;
    //put.uploadingFileURL = [NSURL fileURLWithPath:fullPath];
    put.uploadingData = self.imageData;
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask * putTask = [client putObject:put];
    
    [putTask continueWithBlock:^id(OSSTask *task) {
        task = [client presignPublicURLWithBucketName:@""
                                        withObjectKey:objectKeys];
        NSLog(@"objectKey: %@", put.objectKey);
        
        if (!task.error) {
    
            NSLog(@"upload object success!");
            NSString *baseALYUrl = @"";;
            NSString *aliyunUrl = [baseALYUrl stringByAppendingPathComponent:objectKeys];
	//  stringByAppendingPathComponent 的 Receiver 包含 “//” 时,会被自动格式化 Path 路径方式,即 “/”。需要用[NSString stringWithFormat:@"%@/%@", @"http://xxx", @“keng”];替代         

            /** block值 */
            if (self.testSuccessBlock != nil) {
                self.testSuccessBlock(aliyunUrl, avatar);
            }
            

        } else {
   
            if (self.testFailureBlock != nil) {
                self.testFailureBlock([NSString stringWithFormat:@"upload object failed, error: %@",task.error]);
                NSLog(@"");
            }
            
            
        }
        return nil;
    }];
    
    
}

/**
 *  返回当前时间
 *
 *  @return api
 */
- (NSString *)getTimeNow
{
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    //取出个随机数
    int last = arc4random() % 10000;
    NSString *timeNow = [[NSString alloc] initWithFormat:@"wtoken%@-%i", date,last];
    NSLog(@"%@", timeNow);
    return timeNow;
}
//用户取消选取时调用,可以用来做一些事情
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize{
    //    UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, TRUE, [[UIScreen mainScreen] scale]);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
@end

接下来就是在你需要的地方调用就可以。

    [[BNNUploadAliCloudTool shareInstance] shareUploadAliCloudImageWithSelfView:self.view SuccessBlock:^(NSString *imagUrl, UIImage *avImage) {
        NSLog(@"选中的照片:%@===上传的链接Url:%@",avImage,imagUrl);
        [SVProgressHUD showMessage:@"图片上传成功"];
    } failureBlock:^(NSString *taskError) {
        [SVProgressHUD showMessage:@"图片上传失败"];
    }];
    

CSDN 官方帮助文档 CSDN感觉写出来效果有点丑啊。。。这是官方帮助文档,多学习。cmd+shift+L

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值