QNUpProgress.m 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //
  2. // QNUpProgress.m
  3. // QiniuSDK
  4. //
  5. // Created by yangsen on 2021/5/21.
  6. // Copyright © 2021 Qiniu. All rights reserved.
  7. //
  8. #import "QNAsyncRun.h"
  9. #import "QNUpProgress.h"
  10. @interface QNUpProgress()
  11. @property(nonatomic, assign)long long maxProgressUploadBytes;
  12. @property(nonatomic, assign)long long previousUploadBytes;
  13. @property(nonatomic, copy)QNUpProgressHandler progress;
  14. @property(nonatomic, copy)QNUpByteProgressHandler byteProgress;
  15. @end
  16. @implementation QNUpProgress
  17. + (instancetype)progress:(QNUpProgressHandler)progress byteProgress:(QNUpByteProgressHandler)byteProgress {
  18. QNUpProgress *upProgress = [[QNUpProgress alloc] init];
  19. upProgress.maxProgressUploadBytes = -1;
  20. upProgress.previousUploadBytes = 0;
  21. upProgress.progress = progress;
  22. upProgress.byteProgress = byteProgress;
  23. return upProgress;
  24. }
  25. - (void)progress:(NSString *)key uploadBytes:(long long)uploadBytes totalBytes:(long long)totalBytes {
  26. if ((self.progress == nil && self.byteProgress == nil) || uploadBytes < 0 || (totalBytes > 0 && uploadBytes > totalBytes)) {
  27. return;
  28. }
  29. if (totalBytes > 0) {
  30. @synchronized (self) {
  31. if (self.maxProgressUploadBytes < 0) {
  32. self.maxProgressUploadBytes = totalBytes * 0.95;
  33. }
  34. }
  35. if (uploadBytes > self.maxProgressUploadBytes) {
  36. return;
  37. }
  38. }
  39. @synchronized (self) {
  40. if (uploadBytes > self.previousUploadBytes) {
  41. self.previousUploadBytes = uploadBytes;
  42. } else {
  43. return;
  44. }
  45. }
  46. [self notify:key uploadBytes:uploadBytes totalBytes:totalBytes];
  47. }
  48. - (void)notifyDone:(NSString *)key totalBytes:(long long)totalBytes {
  49. [self notify:key uploadBytes:totalBytes totalBytes:totalBytes];
  50. }
  51. - (void)notify:(NSString *)key uploadBytes:(long long)uploadBytes totalBytes:(long long)totalBytes {
  52. if (self.progress == nil && self.byteProgress == nil) {
  53. return;
  54. }
  55. if (self.byteProgress) {
  56. QNAsyncRunInMain(^{
  57. self.byteProgress(key, uploadBytes, totalBytes);
  58. });
  59. return;
  60. }
  61. if (totalBytes <= 0) {
  62. return;
  63. }
  64. if (self.progress) {
  65. QNAsyncRunInMain(^{
  66. double notifyPercent = (double) uploadBytes / (double) totalBytes;
  67. self.progress(key, notifyPercent);
  68. });
  69. }
  70. }
  71. @end