QNUpProgress.m 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. if (self.maxProgressUploadBytes < 0) {
  31. self.maxProgressUploadBytes = totalBytes * 0.95;
  32. }
  33. if (uploadBytes > self.maxProgressUploadBytes) {
  34. return;
  35. }
  36. }
  37. if (uploadBytes > self.previousUploadBytes) {
  38. self.previousUploadBytes = uploadBytes;
  39. } else {
  40. return;
  41. }
  42. if (self.byteProgress) {
  43. QNAsyncRunInMain(^{
  44. self.byteProgress(key, self.previousUploadBytes, totalBytes);
  45. });
  46. return;
  47. }
  48. if (totalBytes < 0) {
  49. return;
  50. }
  51. if (self.progress) {
  52. QNAsyncRunInMain(^{
  53. double notifyPercent = (double) uploadBytes / (double) totalBytes;
  54. self.progress(key, notifyPercent);
  55. });
  56. }
  57. }
  58. - (void)notifyDone:(NSString *)key totalBytes:(long long)totalBytes {
  59. if (self.progress == nil && self.byteProgress == nil) {
  60. return;
  61. }
  62. if (self.byteProgress) {
  63. QNAsyncRunInMain(^{
  64. self.byteProgress(key, totalBytes, totalBytes);
  65. });
  66. return;
  67. }
  68. if (self.progress) {
  69. QNAsyncRunInMain(^{
  70. self.progress(key, 1);
  71. });
  72. }
  73. }
  74. @end