DBRequestDataHandler.m 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. // The MIT License
  2. //
  3. // Copyright (c) 2016 Dariusz Bukowski
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. #import "DBRequestDataHandler.h"
  23. #import "DBNetworkToolkit.h"
  24. static CGSize const DBRequestDataHandlerThumbnailSize = { 50, 50 };
  25. @interface DBRequestDataHandler ()
  26. @property (nonatomic, copy) NSString *filename;
  27. @property (nonatomic, copy) void (^readingCompletion)(NSData *);
  28. @property (nonatomic, assign) DBRequestModelBodyType dataType;
  29. @property (nonatomic, assign) DBRequestModelBodySynchronizationStatus synchronizationStatus;
  30. @property (nonatomic, assign) NSInteger dataLength;
  31. @end
  32. @implementation DBRequestDataHandler
  33. #pragma mark - Initialization
  34. - (instancetype)initWithFilename:(NSString *)filename data:(NSData *)data shouldGenerateThumbnail:(BOOL)shouldGenerateThumbnail {
  35. self = [super init];
  36. if (self) {
  37. self.filename = filename;
  38. [self saveData:data shouldGenerateThumbnail:shouldGenerateThumbnail];
  39. }
  40. return self;
  41. }
  42. + (instancetype)dataHandlerWithFilename:(NSString *)filename data:(NSData *)data shouldGenerateThumbnail:(BOOL)shouldGenerateThumbnail {
  43. return [[self alloc] initWithFilename:filename data:data shouldGenerateThumbnail:(BOOL)shouldGenerateThumbnail];
  44. }
  45. #pragma mark - Saving data
  46. - (NSString *)pathForFile {
  47. NSString *savedRequestsPath = [DBNetworkToolkit sharedInstance].savedRequestsPath;
  48. return [savedRequestsPath stringByAppendingPathComponent:self.filename];
  49. }
  50. - (UIImage *)imageWithImage:(UIImage *)image scaledToFitSize:(CGSize)maxSize {
  51. CGFloat scale = MAX(image.size.width / maxSize.width, image.size.height / maxSize.height);
  52. CGSize newSize = CGSizeMake(image.size.width / scale, image.size.height / scale);
  53. UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
  54. [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
  55. UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  56. UIGraphicsEndImageContext();
  57. return newImage;
  58. }
  59. - (void)determineDataTypeWithData:(NSData *)data shouldGenerateThumbnail:(BOOL)shouldGenerateThumbnail completion:(void(^)(void))completion {
  60. __weak DBRequestDataHandler *weakSelf = self;
  61. dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
  62. DBRequestDataHandler *strongSelf = weakSelf;
  63. UIImage *image = [UIImage imageWithData:data];
  64. NSError *error;
  65. if (image) {
  66. strongSelf.dataType = DBRequestModelBodyTypeImage;
  67. if (shouldGenerateThumbnail) {
  68. strongSelf.thumbnail = [strongSelf imageWithImage:image scaledToFitSize:DBRequestDataHandlerThumbnailSize];
  69. }
  70. } else if ([NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error] != nil) {
  71. strongSelf.dataType = DBRequestModelBodyTypeJSON;
  72. } else {
  73. strongSelf.dataType = DBRequestModelBodyTypeOther;
  74. }
  75. dispatch_async(dispatch_get_main_queue(), ^(void){
  76. if (completion) {
  77. completion();
  78. }
  79. });
  80. });
  81. }
  82. - (void)saveData:(NSData *)data atFilePath:(NSString *)filePath {
  83. [[NSFileManager defaultManager] createDirectoryAtPath:[filePath stringByDeletingLastPathComponent]
  84. withIntermediateDirectories:YES
  85. attributes:nil
  86. error:nil];
  87. [data writeToFile:filePath atomically:YES];
  88. }
  89. - (void)saveData:(NSData *)data withCompletion:(void(^)(void))completion {
  90. NSString *filePath = [self pathForFile];
  91. dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
  92. [self saveData:data atFilePath:filePath];
  93. dispatch_async(dispatch_get_main_queue(), ^(void){
  94. if (completion) {
  95. completion();
  96. }
  97. });
  98. });
  99. }
  100. - (void)saveData:(NSData *)data shouldGenerateThumbnail:(BOOL)shouldGenerateThumbnail {
  101. self.dataLength = data.length;
  102. self.synchronizationStatus = DBRequestModelBodySynchronizationStatusStarted;
  103. if (self.dataLength > 0) {
  104. __weak DBRequestDataHandler *weakSelf = self;
  105. [self determineDataTypeWithData:data shouldGenerateThumbnail:(BOOL)shouldGenerateThumbnail completion:^{
  106. [self saveData:data withCompletion:^{
  107. DBRequestDataHandler *strongSelf = weakSelf;
  108. strongSelf.synchronizationStatus = DBRequestModelBodySynchronizationStatusFinished;
  109. [strongSelf.delegate requestDataHandlerDidFinishSynchronization:self];
  110. if (strongSelf.readingCompletion) {
  111. strongSelf.readingCompletion(data);
  112. strongSelf.readingCompletion = nil;
  113. }
  114. }];
  115. }];
  116. } else {
  117. self.dataType = DBRequestModelBodyTypeOther;
  118. self.synchronizationStatus = DBRequestModelBodySynchronizationStatusFinished;
  119. [self.delegate requestDataHandlerDidFinishSynchronization:self];
  120. if (self.readingCompletion) {
  121. self.readingCompletion(nil);
  122. self.readingCompletion = nil;
  123. }
  124. }
  125. }
  126. #pragma mark - Reading data
  127. - (void)readWithCompletion:(void(^)(NSData *))completion {
  128. if (self.synchronizationStatus != DBRequestModelBodySynchronizationStatusFinished) {
  129. self.readingCompletion = completion;
  130. } else {
  131. NSString *filePath = [self pathForFile];
  132. dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
  133. NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
  134. dispatch_async(dispatch_get_main_queue(), ^(void){
  135. if (completion) {
  136. completion(data);
  137. }
  138. });
  139. });
  140. }
  141. }
  142. @end