CNLiveUploadController.m
29.5 KB
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
63
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
100
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//
// CNLiveUploadController.m
// CNLiveUploadYunDemo
//
// Created by 张旭 on 2017/8/22.
// Copyright © 2017年 cnlive. All rights reserved.
//
#import "CNLiveUploadController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <CNLiveUploadYunSDK/CNLiveUploadYunSDK.h>
#import <MobileCoreServices/MobileCoreServices.h>
#define mScreenWidth ([UIScreen mainScreen].bounds.size.width)
#define mScreenHeight ([UIScreen mainScreen].bounds.size.height)
#define mUserDefaults [NSUserDefaults standardUserDefaults]
#define FileBlockSize 5*1024*1024 //一块大小,分块最小5M
//上传
#define keyUploadPartNum @"partNum" //需要app本地存储已经传成功的块号,demo为了演示,用NSUserDefaults存储,app可用数据库等
#define keyUploadId @"uploadId" //需要app本地存储已经初始化成功的uploadId,用于断点续传,demo为了演示,用NSUserDefaults存储,app可用数据库等
@interface CNLiveUploadController ()<UITableViewDelegate,UITableViewDataSource,KingSoftServiceRequestDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
NSURL *_imageAssetUrl;//相册文件URL
CNLiveUploadType _uploadType;//选择文件方式type
NSString *_bucketKey;//SP上传时用到的bucket里文件的路径(包含扩展名)
}
@property (nonatomic ,strong) UITableView * tableView;//列表
@property (nonatomic ,strong) UIButton * styleBtn;//上传方式按钮
@property (assign, nonatomic) long long fileSize;//文件大小
@property (assign, nonatomic) NSInteger partSize;//单块大小
@property (assign, nonatomic) long long partLength;//单块长度
@property (nonatomic) NSInteger uploadNum;//当前上传块
@property (nonatomic) NSInteger totalNum;//上传总块数
@property (strong, nonatomic) NSFileHandle *fileHandle;//文件管理
@property (nonatomic, strong) NSArray *arrItems;//数据源
@property (strong, nonatomic) CNLiveMultipartUpload *muilt;//分块上传对象
@end
@implementation CNLiveUploadController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
self.navigationItem.title = @"上传";
_arrItems = [NSArray arrayWithObjects:@"Multipart Upload", @"Abort Multipart Upload", @"Put Single Object", nil];
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMinY(self.view.frame), mScreenWidth, mScreenHeight-100)];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CNLiveUpload"];
[self.view addSubview:self.tableView];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.styleBtn];
[self getBucketKeyFromServer];
}
/**
从服务器获取BucketKey,BucketKey为文件路径
*/
- (NSString *)getBucketKeyFromServer
{
#warning 此处建议从server获取,为每一个上传的文件分配唯一的bucketKey,上传文件对应的bucketKey(文件路径包含扩展名). 例:完整bucketKey为@"cnlive-test/cnlive.mp4",可由服务器返回@"cnlive-test/cnlive",扩展名@".mp4"由开发者拼接,组成完整的bucketKey
#warning Demo为了演示 bucketKey用固定值
_bucketKey = @"cnlive-uploadtest/cnlive.mp4";//本地工程文件
return _bucketKey;
}
- (NSString *)bucketKey
{
switch (_uploadType) {
case kCNLiveUploadNormal:
{//本地文件
_bucketKey = [self getBucketKeyFromServer];
}
break;
case kCNLiveUploadAlasset:
{//相册选取的文件,重新拼接扩展名
NSString *bucketKeyUnExt = [[self getBucketKeyFromServer] substringToIndex:_bucketKey.length - 4];
NSArray *arr = [_imageAssetUrl.absoluteString componentsSeparatedByString:@"ext="];
NSString *ext = arr[1];
_bucketKey = [NSString stringWithFormat:@"%@.%@",bucketKeyUnExt,ext];
}
break;
default:
break;
}
return _bucketKey;
}
#pragma mark 上传方法
/*
当文件大于100MB的时候,可以选择分块上传。把大文件进行切割上传到服务器。 分块上传分为三步:
Initiate Multipart Upload 初始化分块上传
Upload Part 上传文件块
Complete Multipart Upload 完成分块上传
上传中,你可以使用Abort Multipart Upload取消上传,或者List Parts查看上传的分块。或者List Multipart Uploads查看当前的bucket下有多少个uploadid。
分块上传断点续传原理:
上传为了简化流程的复杂度,每次都是从初始化从头开始,依步骤进行:
1.初始化上传,发initMultiUpload请求,并记录uploadId,如果已存在uploadID,用已经存在的uploadID,进行第二步
2.分块上传数据块,一块一块串行的发uploadPart请求,直至所有块传输成功。若中间断开,从第一步重新开始。
3.完成上传,发complete请求,httpCode = 200,成功
Tips:1.基于分块上传的原理,上传暂停继续会有最多一个块的进度回退。
2.分块上传最小为5M一块,小于5M请使用单块上传,Put Object方法
*/
- (void)beginMultipartUpload
{
[CNLiveUpload initCNLiveUploadWithSuccess:^{
NSString *strKey = [self bucketKey];
_partSize = 5; // 文件大于5M为最小5M一块
CNLiveAccessControlList *acl = [[CNLiveAccessControlList alloc] init];
[acl setContronAccess:CNLiveYun_Permission_Public_Read];
CNLiveInitiateMultipartUploadRequest *initMultipartUploadReq = [[CNLiveInitiateMultipartUploadRequest alloc] initWithKey:strKey acl:acl grantAcl:nil];
[initMultipartUploadReq setCompleteRequest];
NSArray *array = [initMultipartUploadReq.CNYHeader componentsSeparatedByString:@"\n"];
NSString *headers = [array firstObject];
[CNLiveUpload getTokenWithMd5:initMultipartUploadReq.contentMd5 verb:initMultipartUploadReq.httpMethod type:initMultipartUploadReq.contentType res:initMultipartUploadReq.CNYResource headers:headers date:initMultipartUploadReq.strDate success:^(NSString *token ,NSString *cnliveDate) {
[initMultipartUploadReq setStrCNLiveToken:token];
[initMultipartUploadReq setStrDate:cnliveDate];
_muilt = [[CNLiveClient initialize] initiateMultipartUploadWithRequest:initMultipartUploadReq];
if (_muilt == nil) {
NSLog(@"####Init upload failed, please check access key, secret key and bucket name!####");
return ;
}
//选择相册还是普通方式
_muilt.uploadType = _uploadType;
//根据文件路径不一样,有如下两种上传
if (_muilt.uploadType == kCNLiveUploadNormal) { //如果是沙盒或者工程里的文件
//工程里,沙盒里,是沙盒路径
NSString *strFilePath = [[NSBundle mainBundle] pathForResource:@"cnlive" ofType:@"mp4"];
_fileHandle = [NSFileHandle fileHandleForReadingAtPath:strFilePath];
_fileSize = [_fileHandle availableData].length;
if (_fileSize <= 0) {
NSLog(@"####This file is not exist!####");
return ;
}
if (!(_partSize > 0 || _partSize != 0)) {
_partLength = _fileSize;
}else{
_partLength = _partSize * 1024.0 * 1024.0;
}
_totalNum = (ceilf((float)_fileSize / (float)_partLength));
[_fileHandle seekToFileOffset:0];
}else
{
//如果是相册里的,从这传
ALAsset *assets = [[CNLiveClient initialize] getAlassetFromAlassetURL:_imageAssetUrl];
ALAssetRepresentation *assetD = assets.defaultRepresentation;
_fileSize = assetD.size;
if (_fileSize <= 0) {
NSLog(@"####This file is not exist!####");
return ;
}
if (!(_partSize > 0 || _partSize != 0)) {
_partLength = _fileSize;
}else{
_partLength = _partSize * 1024.0 * 1024.0;
}
_totalNum = (ceilf((float)_fileSize / (float)_partLength));
}
#warning 上传的断点续传判断:初始化上传后,开始上传前,此处需要list一下所有的数据块,如果uploadID是新生成的,可以跳过list过程从第一块开始传,如果上传是断点续传,需用初始化用到的uploadId,list一下所有已经传过的数据块,再从暂停块上传即可, 这里用NSUserDefault演示存储过程。
//判断uploadId是否存在,进而进行上传的断点续传
if ([mUserDefaults objectForKey:keyUploadId] == nil) {
[mUserDefaults setObject:_muilt.uploadId forKey:keyUploadId];
[mUserDefaults synchronize];
_uploadNum = 1;
[self uploadWithPartNumber:_uploadNum];
}else
{
_muilt.uploadId = [mUserDefaults objectForKey:keyUploadId];
//list一下所有上传过的块
CNLiveListPartsRequest *req2 = [[CNLiveListPartsRequest alloc] initWithMultipartUpload:_muilt];
[req2 setCompleteRequest];
[CNLiveUpload getTokenWithMd5:req2.contentMd5 verb:req2.httpMethod type:req2.contentType res:req2.CNYResource headers:headers date:req2.strDate success:^(NSString *token ,NSString *cnliveDate) {
[req2 setStrCNLiveToken:token];
[req2 setStrDate:cnliveDate];
CNLiveListPartsResponse *response2 = [[CNLiveClient initialize] listParts:req2];
NSLog(@"response.listResult.parts.count =%lu",(unsigned long)[response2.listResult.parts count]);
//从这块开始上传,list结果的最后一块
_uploadNum = ((CNLivePart *)[response2.listResult.parts lastObject]).partNumber + 1 ;
//进度补齐
long long alreadyTotalWriten = (_uploadNum - 1) * _partLength ;
double progress = alreadyTotalWriten / (float)_fileSize;
UIProgressView *progressView = (UIProgressView *)[self.view viewWithTag:199];
progressView.progress = progress;
[self uploadWithPartNumber:_uploadNum];
} failure:^(NSDictionary *error) {
NSLog(@"error %@",error);
}];
}
} failure:^(NSDictionary *error) {
NSLog(@"error %@",error);
}];
} failure:^(NSDictionary *error) {
NSLog(@"error %@",error);
}];
}
- (void)uploadWithPartNumber:(NSInteger)partNumber
{
@autoreleasepool {
//如果暂停,恢复上传
if (_muilt.isPaused == YES || _muilt.isCanceled == YES ) {
[_muilt proceed];
}
NSData *data = nil;
if (_muilt.uploadType == kCNLiveUploadAlasset) {
//相册信息
ALAsset *assets = [[CNLiveClient initialize] getAlassetFromAlassetURL:_imageAssetUrl];
data = [[CNLiveClient initialize] getUploadPartDataWithPartNum:partNumber partLength:FileBlockSize Alasset:assets];
}else
{
//沙盒路径
if (_uploadNum == _totalNum) {
[_fileHandle seekToFileOffset:_partLength *(_uploadNum - 1 )];
data = [_fileHandle readDataToEndOfFile];
}else {
data = [_fileHandle readDataOfLength:(NSUInteger)_partLength];
[_fileHandle seekToFileOffset:_partLength*(_uploadNum)];
}
}
CNLiveUploadPartRequest *req = [[CNLiveUploadPartRequest alloc] initWithMultipartUpload:_muilt partNumber:(int32_t)partNumber data:data generateMD5:NO];
req.delegate = self;
req.contentLength = data.length;
req.contentMd5 = [CNLiveSDKUtil base64md5FromData:data];
[req setCompleteRequest];
NSArray *array = [req.CNYHeader componentsSeparatedByString:@"\n"];
NSString *headers = [array firstObject];
[CNLiveUpload getTokenWithMd5:req.contentMd5 verb:req.httpMethod type:req.contentType res:req.CNYResource headers:headers date:req.strDate success:^(NSString *token ,NSString *cnliveDate) {
[req setStrCNLiveToken:token];
[req setStrDate:cnliveDate];
[[CNLiveClient initialize] uploadPart:req];
} failure:^(NSDictionary *error) {
}];
}
}
//取消上传,调用abort 接口,终止上传,修改进度条即可
- (void)cancelMultipartUpload
{
if (_muilt == nil) {
NSLog(@"请先创建上传,再调用Abort");
return;
}
CNLiveAbortMultipartUploadRequest *request = [[CNLiveAbortMultipartUploadRequest alloc] initWithMultipartUpload:_muilt];
[request setCompleteRequest];
NSArray *array = [request.CNYHeader componentsSeparatedByString:@"\n"];
NSString *headers = [array firstObject];
[CNLiveUpload getTokenWithMd5:request.contentMd5 verb:request.httpMethod type:request.contentType res:request.CNYResource headers:headers date:request.strDate success:^(NSString *token ,NSString *cnliveDate) {
[request setStrCNLiveToken:token];
[request setStrDate:cnliveDate];
CNLiveAbortMultipartUploadResponse *response = [[CNLiveClient initialize] abortMultipartUpload:request];
if (response.httpStatusCode == 204) {
NSLog(@"Abort multipart upload success!");
[_muilt cancel];
[mUserDefaults setObject:nil forKey:keyUploadId];
[mUserDefaults setInteger:0 forKey:keyUploadPartNum];
[mUserDefaults synchronize];
UIProgressView *progressView = (UIProgressView *)[self.view viewWithTag:199];
progressView.progress = 0;
}
else {
NSLog(@"error: %@", response.error.description);
}
} failure:^(NSDictionary *error) {
}];
}
//若不选择分块上传,请使用单块上传,
//最小支持但块上传小于5M,最大支持单块上传为5G
- (void)beginSingleUpload:(NSInteger) row
{
[CNLiveUpload initCNLiveUploadWithSuccess:^{
CNLiveAccessControlList *ControlList = [[CNLiveAccessControlList alloc] init];
[ControlList setContronAccess:CNLiveYun_Permission_Public_Read_Write];
CNLivePutObjectRequest *putObjRequest = [[CNLivePutObjectRequest alloc] initWithAcl:ControlList grantAcl:nil];
NSString *fileName = [[NSBundle mainBundle] pathForResource:@"cnlive" ofType:@"mp4"];
putObjRequest.data = [NSData dataWithContentsOfFile:fileName options:NSDataReadingMappedIfSafe error:nil];
_fileSize = putObjRequest.data.length;
putObjRequest.delegate = self;
putObjRequest.filename = [self bucketKey];
putObjRequest.contentMd5 = [CNLiveSDKUtil base64md5FromData:putObjRequest.data];
[putObjRequest setCompleteRequest];
NSArray *array = [putObjRequest.CNYHeader componentsSeparatedByString:@"\n"];
NSString *headers = [array firstObject];
[CNLiveUpload getTokenWithMd5:putObjRequest.contentMd5 verb:putObjRequest.httpMethod type:putObjRequest.contentType res:putObjRequest.CNYResource headers:headers date:putObjRequest.strDate success:^(NSString *token ,NSString *cnliveDate) {
[putObjRequest setStrCNLiveToken:token];
[putObjRequest setStrDate:cnliveDate];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
CNLivePutObjectResponse *response = [[CNLiveClient initialize] putObject:putObjRequest];
//putObjRequest若没设置代理,则是同步的下方判断,
//putObjRequest若设置了代理,则走上传代理回调,
if (putObjRequest.delegate == nil) {
NSLog(@"%@",[[NSString alloc] initWithData:response.body encoding:NSUTF8StringEncoding]);
if (response.httpStatusCode == 200) {
NSLog(@"Put object success");
}
else {
NSLog(@"Put object failed");
}
}
});
} failure:^(NSDictionary *error) {
NSLog(@"error %@",error);
}];
} failure:^(NSDictionary *error) {
NSLog(@"error %@",error);
}];
}
#pragma mark -
#pragma mark - ButtonAction
- (void)uploadBtnClicked:(UIButton *)btn
{
btn.selected =! btn.selected;
if (btn.selected) {
[btn setTitle:@"暂停" forState:UIControlStateNormal];
[self beginMultipartUpload];
}else
{
if ([btn.titleLabel.text isEqualToString: @"完成" ]) {
UIProgressView *progressView = (UIProgressView *)[self.view viewWithTag:199];
progressView.progress = 0;
[btn setTitle:@"开始" forState:UIControlStateNormal];
_uploadType = kCNLiveUploadNormal;
return;
}
[_muilt pause];
[btn setTitle:@"继续" forState:UIControlStateNormal];
}
}
- (void)styleBtnAction
{
[self uploadStyle];
}
- (void)uploadStyle
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"上传方式" message:@"默认上传方式为本地文件" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *localAlert = [UIAlertAction actionWithTitle:@"本地文件" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
_uploadType = kCNLiveUploadNormal;
}];
[alert addAction:localAlert];
UIAlertAction *albumAlert = [UIAlertAction actionWithTitle:@"相册文件" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.allowsEditing = YES;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//相机相册
// 设置所支持的媒体功能,即只能拍照,或则只能录像,或者两者都可以
#warning 此处需要区分视频还是图片文件,获取上传资源路径([CNLiveUpload getUploadResourceUrlWithBucketKey:uploadType:success:failure:])时需要用到此CNLiveYun_UploadType,Demo演示相册中 视频文件的上传
// NSString *requiredMediaType = ( NSString *)kUTTypeImage;
NSString *requiredMediaType1 = ( NSString *)kUTTypeMovie;
NSArray *arrMediaTypes=[NSArray arrayWithObjects: requiredMediaType1,nil];//requiredMediaType
imagePicker.mediaTypes = arrMediaTypes;
[self presentViewController:imagePicker animated:YES completion:NULL];
_uploadType = kCNLiveUploadAlasset;
}];
[alert addAction:albumAlert];
UIAlertAction *cancelAlert = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:NULL];
}];
[alert addAction:cancelAlert];
[self presentViewController:alert animated:YES completion:NULL];
}
//#pragma mark 相册方法
///*
// 这里,枚举模拟器相册所有的视频,模拟器只有一个只能获得开头传入的cnlive.mp4视频,
// 具体工程使用时根据具体逻辑,获取到Alasset即可
//CNLiveClient 方法:
// - (NSData *)getUploadPartDataWithPartNum:(NSInteger)partNum
// partLength:(NSInteger)partlength
// alassetURL:(NSURL *)alassetURL;
//
// - (NSData *)getUploadPartDataWithPartNum:(NSInteger)partNum
// partLength:(NSInteger)partlength
// Alasset:(ALAsset *)assets;
//
// - (ALAsset *)getAlassetFromAlassetURL:(NSURL *)alassetURL;
//
// */
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
NSURL *imageAssetUrl = [info objectForKey:UIImagePickerControllerReferenceURL];
_imageAssetUrl = imageAssetUrl;
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:NULL];
NSLog(@"cancel");
}
#pragma mark - UITableView datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _arrItems.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *strIdentifier = @"CNLiveUpload";
UITableViewCell *cell;
if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strIdentifier];
if (indexPath.row == 0) { //分块上传
UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(mScreenWidth * .4 , 20, mScreenWidth * .45, 20)];
progressView.progressViewStyle = UIProgressViewStyleDefault;
progressView.tag = 199;
NSInteger finishCount = [mUserDefaults integerForKey:keyUploadPartNum];
progressView.progress = finishCount * FileBlockSize * 1.0 / _fileSize;
[cell.contentView addSubview:progressView];
UIButton *uploadBtn = [[UIButton alloc]initWithFrame:CGRectMake(mScreenWidth - 50, 10, 40, 20)];
[uploadBtn setTitle:@"开始" forState:UIControlStateNormal];
uploadBtn.titleLabel.font = [UIFont systemFontOfSize:14];
[uploadBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
uploadBtn.tag = 200;
[uploadBtn addTarget:self action:@selector(uploadBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:uploadBtn];
}
}
cell.textLabel.text = _arrItems[indexPath.row];
return cell;
}
#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.row) {
case 0:
{
//放在点击事件里,uploadBtnClicked
}
break;
case 1:
{
[self cancelMultipartUpload];
}
break;
case 2:
{
[self beginSingleUpload:indexPath.row];
}
break;
default:
break;
}
}
#pragma mark - 上传的回调方法
- (void)request:(KS3Request *)request didCompleteWithResponse:(KS3Response *)response
{
if ([request isKindOfClass:[KS3PutObjectRequest class]]) {
if (response.httpStatusCode == 200) {
NSLog(@"单块上传成功");
#warning 根据选择的文件类型更改CNLiveYun_UploadType,Demo演示视频路径的获取
[CNLiveUpload getUploadResourceUrlWithBucketKey:[self bucketKey] uploadType:CNLiveYun_UploadType_VideoFile success:^(NSString *resUrl) {
NSLog(@"资源路径: %@",resUrl);
} failure:^(NSDictionary *error) {
NSLog(@"error: %@",error);
}];
}else
{
NSLog(@"单块上传失败");
}
return;
}else if ([request isKindOfClass:[KS3UploadPartRequest class]])
{
[mUserDefaults setInteger:_uploadNum forKey:keyUploadPartNum];
[mUserDefaults synchronize];
_uploadNum ++;
if (_totalNum < _uploadNum) {
CNLiveListPartsRequest *req2 = [[CNLiveListPartsRequest alloc] initWithMultipartUpload:_muilt];
[req2 setCompleteRequest];
NSArray *array = [req2.CNYHeader componentsSeparatedByString:@"\n"];
NSString *headers = [array firstObject];
[CNLiveUpload getTokenWithMd5:req2.contentMd5 verb:req2.httpMethod type:req2.contentType res:req2.CNYResource headers:headers date:req2.strDate success:^(NSString *token ,NSString *cnliveDate) {
[req2 setStrCNLiveToken:token];
[req2 setStrDate:cnliveDate];
CNLiveListPartsResponse *response2 = [[CNLiveClient initialize] listParts:req2];
CNLiveCompleteMultipartUploadRequest *req = [[CNLiveCompleteMultipartUploadRequest alloc] initWithMultipartUpload:_muilt];
NSLog(@"%@",response2.listResult.parts);
for (KS3Part *part in response2.listResult.parts) {
[req addPartWithPartNumber:part.partNumber withETag:part.etag];
}
//req参数设置完一定要调这个函数
[req setCompleteRequest];
NSArray *array1 = [req.CNYHeader componentsSeparatedByString:@"\n"];
NSString *headers1 = [array1 firstObject];
[CNLiveUpload getTokenWithMd5:req.contentMd5 verb:req.httpMethod type:req.contentType res:req.CNYResource headers:headers1 date:req.strDate success:^(NSString *token ,NSString *cnliveDate) {
[req setStrCNLiveToken:token];
[req setStrDate:cnliveDate];
CNLiveCompleteMultipartUploadResponse *resp = [[CNLiveClient initialize] completeMultipartUpload:req];
NSString *bodyStr = [[NSString alloc]initWithData:resp.body encoding:NSUTF8StringEncoding];
if (resp.httpStatusCode != 200) {
NSLog(@"#####complete multipart upload failed!!! code: %d#####,body = %@", resp.httpStatusCode,bodyStr);
}else if (resp.httpStatusCode == 200)
{
NSLog(@"分块上传成功!!");
[mUserDefaults setObject:nil forKey:keyUploadId];
[mUserDefaults setInteger:0 forKey:keyUploadPartNum];
_uploadNum = 0 ;
[mUserDefaults synchronize];
#warning 根据选择的文件类型更改CNLiveYun_UploadType,Demo演示视频路径的获取
[CNLiveUpload getUploadResourceUrlWithBucketKey:[self bucketKey] uploadType:CNLiveYun_UploadType_VideoFile success:^(NSString *resUrl) {
NSLog(@"资源路径: %@",resUrl);
} failure:^(NSDictionary *error) {
NSLog(@"error: %@",error);
}];
}
} failure:^(NSDictionary *error) {
}];
} failure:^(NSDictionary *error) {
}];
}
else {
[self uploadWithPartNumber:_uploadNum];
}
}
}
- (void)request:(KS3Request *)request didFailWithError:(NSError *)error
{
NSLog(@"upload error: %@", error);
}
- (void)request:(KS3Request *)request didReceiveResponse:(NSURLResponse *)response
{
NSInteger statusCode = ((NSHTTPURLResponse*) response).statusCode;
if ( (statusCode>= 200 && statusCode <300) || statusCode == 304) {
NSLog(@"Put object success");
}
else {
NSLog(@"Put object failed");
}
}
- (void)request:(KS3Request *)request didReceiveData:(NSData *)data
{
/**
* Never call this method, because it's upload
*
* @return <#return value description#>
*/
}
-(void)request:(KS3Request *)request didSendData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten totalBytesExpectedToWrite:(long long)totalBytesExpectedToWrite
{
UIProgressView *progressView = (UIProgressView *)[self.view viewWithTag:199];
UIButton *button = (UIButton *)[self.view viewWithTag:200];
if ([request isKindOfClass:[KS3PutObjectRequest class]]) {
long long alreadyTotalWriten = totalBytesWritten;
double progress = alreadyTotalWriten * 1.0 / _fileSize;
NSLog(@"upload progress: %f", progress);
// progressView.progress = progress;
}else if([request isKindOfClass:[KS3UploadPartRequest class]])
{
if (_muilt.isCanceled ) {
[request cancel];
[button setTitle:@"开始" forState:UIControlStateNormal];
button.selected = NO;
progressView.progress = 0;
return;
}
long long alreadyTotalWriten = (_uploadNum - 1) * _partLength + totalBytesWritten;
double progress = alreadyTotalWriten / (float)_fileSize;
NSLog(@"upload progress: %f", progress);
progressView.progress = progress;
if (progress == 1) {
[_fileHandle closeFile];
[button setTitle:@"完成" forState:UIControlStateNormal];
}
}
}
#pragma mark - Lazy
- (UIButton *)styleBtn
{
if (!_styleBtn)
{
_styleBtn = [[UIButton alloc] initWithFrame:CGRectMake(mScreenWidth *0.5-70, CGRectGetMaxY(self.tableView.frame) + 20, 140, 30)];
[_styleBtn setTitle:@"选择上传方式" forState:UIControlStateNormal];
[_styleBtn addTarget:self action:@selector(styleBtnAction) forControlEvents:UIControlEventTouchUpInside];
_styleBtn.backgroundColor = [UIColor redColor];
}
return _styleBtn;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end