相信有很多公司都用过七牛,国产云存储,下面是我封装的图片上传API
整体过程:客户端向自家服务器请求token值,然后客户端再根据token值向七牛云存储上传资源,成功后会有一个回调,可以在block中获取URL,然后客户端再将URL上传到自家服务器上
//先向七牛上传图片,成功后将URL和文字内容发送到后台
- (void)getQiniuTokenWithImgArray:(NSArray*)ImgArray successArrBlock:(void (^)(NSArray *arr))successArr{
//作为上传成功后的图片的URL容器
NSMutableArray *dataArray = [NSMutableArray array];
int i = 0;
for (NSData *ImgData in ImgArray) {
//生成图片的名字key
NSString *key = [NSString stringWithFormat:@"%@-%d",[self uuid],i]; //加个个数,防止一秒内上传多张图片,这样上传到key就都一样了
NSString *strUrl = [NSString stringWithFormat:@"%@?uid=%@&device=%@",@"http://你自己服务器获取token的URL,找后台要",[Tools userInfoWithKey:@"id"],[Tools getDeviceID]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
//xmanager.responseSerializer = [AFHTTPResponseSerializer serializer];
//先从服务器获取token值
[manager GET:strUrl parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
NSString *token = responseObject[@"uptoken"];
//NSLog(@"token---%@",token);
//调用七牛的上传接口
QNUploadManager *upManager = [[QNUploadManager alloc] init];
[upManager putData:ImgData key:key token:token
complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
NSString *imgUrlStr = [NSString stringWithFormat:@"%@%@",@"http://七牛的域名/",key];
[dataArray addObject:imgUrlStr];
//上传图片的个数和返回的URL个数得一样
if (dataArray.count == ImgArray.count) {
//得到的URL数组,这些URL要上传的自己的服务器
successArr(dataArray);
}
} option:nil];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"获取token失败:%@",error.description);
}];
i++;
}
}
//通用唯一识别码
- (NSString*) uuid {
// CFUUIDRef puuid = CFUUIDCreate( nil );
// CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
// NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
// CFRelease(puuid);
// CFRelease(uuidString);
// return result;
//根据当前系统时间生成图片名称
NSDate *date = [NSDate date];
// NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
// [formatter setDateFormat:@"yyyy-MM-dd-HH-mm-ss"];
long time=(long)[date timeIntervalSince1970]; //获取时间戳
return [NSString stringWithFormat:@"babyShow/%ld",time];
}
//通过GET去请求数据
+ (NSURLSessionDataTask *)GetDataWithURI:(NSString *)URI Block:(void(^)(id obj,NSError *error))block{
return [[AFAppDotNetAPIClient sharedClient] GET:URI parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
//responseObject 返回的数据
block(responseObject,nil);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//NSLog(@"%@",[error localizedDescription]);
block(nil,error);
}];
}