OSSHelper.m 8.43 KB
Newer Older
曹云霄's avatar
曹云霄 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
//
//  OSSHelper.m
//  patrol
//
//  Created by 曹云霄 on 16/8/23.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "OSSHelper.h"
#import <AVFoundation/AVFoundation.h>


NSString * const accessKey = @"LTAI6Km6HG7tXBBq";
NSString * const secretKey = @"xTrZGR9Q1V2Wguk10551upmDROU64k";
NSString * const endPoint = @"http://oss-cn-shanghai.aliyuncs.com";
NSString * const bucketName = @"oppledev";


/**
 *  OSS图片文件路径
 */
NSString * const OSSImagePath = @"image/opple_forum/";

/**
 *  OSS视频文件路径
 */
NSString * const OSSVideoPath = @"video/opple_forum/";



static OSSClient *client;

@implementation OSSHelper

+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // for test environment
        id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:accessKey secretKey:secretKey];
        OSSClientConfiguration * conf = [OSSClientConfiguration new];
        conf.maxRetryCount = 3;
        conf.enableBackgroundTransmitService = YES;
        conf.timeoutIntervalForRequest = 15;
        conf.timeoutIntervalForResource = 24 * 60 * 60;
        client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];
    });
}


/**
 *  上传图片
 *
 *  @param ObjectKey Key
 *  @param data      Data
 *  @param type      同步、异步
 *  @param progress  上传进度
 *  @param success   返回
 */
+ (void)uploadImageObjectWithKey:(NSString *)ObjectKey data:(NSData *)data type:(OSSHelperOperationType)type progress:(void (^)(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))progress success:(id (^)(OSSTask *task))success error:(void (^)(NSError *))error
{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = bucketName;
63
    put.objectKey = [NSString stringWithFormat:@"%@%@/%@",OSSImagePath,[[NSDate date] yearMonthDayString],ObjectKey];
曹云霄's avatar
曹云霄 committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    //判断文件在OSS是否存在
    if ([client doesObjectExistInBucket:put.bucketName objectKey:ObjectKey error:nil]) {
        success([OSSTask new]);
    }else
    {
        put.uploadingData = data;
        put.uploadProgress = progress;
        OSSTask * putTask = [client putObject:put];
        if (type == OSSHelperOperationTypeSynchronous) {
            [putTask waitUntilFinished];
        }
        [putTask continueWithSuccessBlock:success];
        [putTask continueWithBlock:^id(OSSTask *task) {
            if (!task.error) {
                NSLog(@"upload object success!");
            } else {
                error(task.error);
            }
            return nil;
        }];
    }
}

/**
 *  上传视频
 *
 *  @param ObjectKey Key
 *  @param data      Data
 *  @param type      同步、异步
 *  @param progress  上传进度
 *  @param success   返回
 */
+ (void)uploadVideoObjectWithKey:(NSString *)ObjectKey data:(NSData *)data type:(OSSHelperOperationType)type progress:(void (^)(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))progress success:(id (^)(OSSTask *task))success error:(void (^)(NSError *))error
{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = bucketName;
100
    put.objectKey = [NSString stringWithFormat:@"%@%@/%@",OSSVideoPath,[[NSDate date] yearMonthDayString],ObjectKey];
曹云霄's avatar
曹云霄 committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    //判断文件在OSS是否存在
    if ([client doesObjectExistInBucket:put.bucketName objectKey:ObjectKey error:nil]) {
        success([OSSTask new]);
    }else
    {
        put.uploadingData = data;
        put.uploadProgress = progress;
        OSSTask * putTask = [client putObject:put];
        if (type == OSSHelperOperationTypeSynchronous) {
            [putTask waitUntilFinished];
        }
        [putTask continueWithSuccessBlock:success];
        [putTask continueWithBlock:^id(OSSTask *task) {
            if (!task.error) {
                NSLog(@"upload object success!");
            } else {
                error(task.error);
            }
            return nil;
        }];
    }
}

/**
 *  下载附件
 *
 *  @param ObjectKey OSSkey
 *  @param type      同步、异步
 *  @param progress  进度
 *  @param success   成功回调
 */
+ (void)downloadObject:(NSString *)ObjectKey type:(OSSHelperOperationType)type progress:(void (^)(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))progress success:(id (^)(OSSTask *task))success error:(void(^)(NSError *))error
{
    OSSGetObjectRequest * request = [OSSGetObjectRequest new];
    request.bucketName = bucketName;
    request.objectKey = ObjectKey;
    request.downloadProgress = progress;
    NSArray *array = [ObjectKey componentsSeparatedByString:@"/"];
    request.downloadToFileURL = [NSURL fileURLWithPath:[kPathCaches stringByAppendingPathComponent:[NSString stringWithFormat:@"cache/%@",[array lastObject]]]];
    OSSTask * getTask = [client getObject:request];
    if (type == OSSHelperOperationTypeSynchronous) {
        [getTask waitUntilFinished];
    }
    [getTask continueWithSuccessBlock:success];
    [getTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"upload object success!");
        } else {
            error(task.error);
        }
        return nil;
    }];
}


/**
 *  获取OSS的ObjectKey
 *
 *  @return NSString
 */
+ (NSString *)getOSSObjectKey
{
    NSMutableString *ObjectKey = [[NSMutableString alloc]init];
    NSString *userName = [Shoppersmanager manager].shoppers.employee.fid;
    if(userName!=nil && userName.length>0)
    {
        [ObjectKey appendString:userName];
    }
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval  a = [dat timeIntervalSince1970] * 1000;  //  *1000 是精确到毫秒,不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //转为字符型
    if(timeString!=nil && timeString.length>0)
    {
        [ObjectKey appendString:timeString];
    }
    if(ObjectKey.length<=userName.length||ObjectKey.length<=timeString.length)
    {
        return nil;
    }
    else
    {
        return ObjectKey;
    }
}


/**
 *  获取OSS的ObjectKey,多个时,用index区分
 *
 *  @param index index
 *
 *  @return NSString
 */
+ (NSString *)getOSSObjectKey:(NSInteger)index
{
    NSMutableString *ObjectKey = [[NSMutableString alloc]init];
    NSString *userName = [Shoppersmanager manager].shoppers.employee.fid;
    if(userName!=nil && userName.length>0)
    {
        [ObjectKey appendString:userName];
    }
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970] * 1000;  //  *1000 是精确到毫秒,不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a+index]; //转为字符型
    if(timeString!=nil && timeString.length>0)
    {
        [ObjectKey appendString:timeString];
    }
    if(ObjectKey.length<=userName.length||ObjectKey.length<=timeString.length)
    {
        return nil;
    }
    else
    {
        return ObjectKey;
    }
}

/**
 *  获取文件名称
 *
 *  @param type 区分图片和视频<image/video>
 *
 *  @return NSString
 */
+ (NSString *)getOSSObjectKeyWithtype:(NSString *)type
{
    NSString *osskey = [[self class] getOSSObjectKey];
    NSString *urlString = [NSString stringWithFormat:@"IOS%@.%@",osskey,type];
    return urlString;
}


/**
 *  获取文件名称,多个时通过index区分
 *
 *  @param type 区分图片和视频<image/video>
 *
 *  @return NSString
 */
+ (NSString *)getOSSObjectKeyWithtype:(NSString *)type index:(NSInteger)index
{
    NSString *osskey = [[self class] getOSSObjectKey:index];
    NSString *urlString = [NSString stringWithFormat:@"IOS%@.%@",osskey,type];
    return urlString;
}


/**
 *  获得完整的图片路径
 *
 *  @param OSSKey OSSKey
 *
 *  @return 路径
 */
+ (NSString *)getCompleteImageURLWithOSSkey:(NSString *)OSSKey
{
    NSArray *ossStringArray = [endPoint componentsSeparatedByString:@"//"];
259
    return [NSString stringWithFormat:@"http://%@.%@/%@%@/%@",bucketName,[ossStringArray lastObject],OSSImagePath,[[NSDate date] yearMonthDayString],OSSKey];
曹云霄's avatar
曹云霄 committed
260 261 262 263 264 265 266 267 268 269 270 271
}

/**
 *  获得完整的视频路径
 *
 *  @param OSSKey OSSKey
 *
 *  @return 路径
 */
+ (NSString *)getCompleteVideoURLWithOSSkey:(NSString *)OSSKey
{
    NSArray *ossStringArray = [endPoint componentsSeparatedByString:@"//"];
272
    return [NSString stringWithFormat:@"http://%@.%@/%@%@/%@",bucketName,[ossStringArray lastObject],OSSVideoPath,[[NSDate date] yearMonthDayString],OSSKey];
曹云霄's avatar
曹云霄 committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
}













@end