QNPHAssetFile.m 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. //
  2. // QNPHAssetFile.m
  3. // Pods
  4. //
  5. // Created by 何舒 on 15/10/21.
  6. //
  7. //
  8. #import "QNPHAssetFile.h"
  9. #import <Photos/Photos.h>
  10. #import "QNResponseInfo.h"
  11. #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 90100)
  12. @interface QNPHAssetFile ()
  13. @property (nonatomic) PHAsset *phAsset;
  14. @property (nonatomic) int64_t fileSize;
  15. @property (nonatomic) int64_t fileModifyTime;
  16. @property (nonatomic, strong) NSData *assetData;
  17. // file path 可能是导出的 file path,并不是真正的 filePath, 导出的文件在上传结束会被删掉,并不是真正有效的文件路径。
  18. @property(nonatomic, assign)BOOL hasRealFilePath;
  19. @property (nonatomic, copy) NSString *filePath;
  20. @property (nonatomic) NSFileHandle *file;
  21. @property (nonatomic, strong) NSLock *lock;
  22. @end
  23. @implementation QNPHAssetFile
  24. - (instancetype)init:(PHAsset *)phAsset error:(NSError *__autoreleasing *)error {
  25. if (self = [super init]) {
  26. NSDate *createTime = phAsset.creationDate;
  27. int64_t t = 0;
  28. if (createTime != nil) {
  29. t = [createTime timeIntervalSince1970];
  30. }
  31. _fileModifyTime = t;
  32. _phAsset = phAsset;
  33. [self getInfo];
  34. _lock = [[NSLock alloc] init];
  35. if (self.assetData == nil && self.filePath != nil) {
  36. NSError *error2 = nil;
  37. NSDictionary *fileAttr = [[NSFileManager defaultManager] attributesOfItemAtPath:self.filePath error:&error2];
  38. if (error2 != nil) {
  39. if (error != nil) {
  40. *error = error2;
  41. }
  42. return self;
  43. }
  44. _fileSize = [fileAttr fileSize];
  45. NSFileHandle *f = nil;
  46. NSData *d = nil;
  47. if (_fileSize > 16 * 1024 * 1024) {
  48. f = [NSFileHandle fileHandleForReadingFromURL:[NSURL fileURLWithPath:self.filePath] error:error];
  49. if (f == nil) {
  50. if (error != nil) {
  51. *error = [[NSError alloc] initWithDomain:self.filePath code:kQNFileError userInfo:[*error userInfo]];
  52. }
  53. return self;
  54. }
  55. } else {
  56. d = [NSData dataWithContentsOfFile:self.filePath options:NSDataReadingMappedIfSafe error:&error2];
  57. if (error2 != nil) {
  58. if (error != nil) {
  59. *error = error2;
  60. }
  61. return self;
  62. }
  63. }
  64. _file = f;
  65. _assetData = d;
  66. }
  67. }
  68. return self;
  69. }
  70. - (NSData *)read:(long long)offset
  71. size:(long)size
  72. error:(NSError **)error {
  73. NSData *data = nil;
  74. @try {
  75. [_lock lock];
  76. if (_assetData != nil && offset < _assetData.length) {
  77. NSUInteger realSize = MIN((NSUInteger)size, _assetData.length - (NSUInteger)offset);
  78. data = [_assetData subdataWithRange:NSMakeRange((NSUInteger)offset, realSize)];
  79. } else if (_file != nil && offset < _fileSize) {
  80. [_file seekToFileOffset:offset];
  81. data = [_file readDataOfLength:size];
  82. } else {
  83. data = [NSData data];
  84. }
  85. } @catch (NSException *exception) {
  86. *error = [NSError errorWithDomain:NSCocoaErrorDomain code:kQNFileError userInfo:@{NSLocalizedDescriptionKey : exception.reason}];
  87. NSLog(@"read file failed reason: %@ \n%@", exception.reason, exception.callStackSymbols);
  88. } @finally {
  89. [_lock unlock];
  90. }
  91. return data;
  92. }
  93. - (NSData *)readAllWithError:(NSError **)error {
  94. return [self read:0 size:(long)_fileSize error:error];
  95. }
  96. - (void)close {
  97. if (PHAssetMediaTypeVideo == self.phAsset.mediaType) {
  98. if (_file != nil) {
  99. [_file closeFile];
  100. }
  101. // 如果是导出的 file 删除
  102. if (!self.hasRealFilePath && self.filePath) {
  103. [[NSFileManager defaultManager] removeItemAtPath:self.filePath error:nil];
  104. }
  105. }
  106. }
  107. - (NSString *)path {
  108. return self.hasRealFilePath ? self.filePath : nil;
  109. }
  110. - (int64_t)modifyTime {
  111. return _fileModifyTime;
  112. }
  113. - (int64_t)size {
  114. return _fileSize;
  115. }
  116. - (NSString *)fileType {
  117. return @"PHAsset";
  118. }
  119. - (void)getInfo {
  120. if (PHAssetMediaTypeImage == self.phAsset.mediaType) {
  121. [self getImageInfo];
  122. } else if (PHAssetMediaTypeVideo == self.phAsset.mediaType) {
  123. // 1. 获取 video url 在此处打断点 debug 时 file path 有效,去除断点不进行 debug file path 无效,所以取消这种方式。
  124. // [self getVideoInfo];
  125. // 2. video url 获取失败则导出文件
  126. if (self.filePath == nil) {
  127. [self exportAssert];
  128. }
  129. } else {
  130. [self exportAssert];
  131. }
  132. }
  133. - (void)getImageInfo {
  134. PHImageRequestOptions *options = [PHImageRequestOptions new];
  135. options.version = PHImageRequestOptionsVersionCurrent;
  136. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  137. options.resizeMode = PHImageRequestOptionsResizeModeNone;
  138. //不支持icloud上传
  139. options.networkAccessAllowed = NO;
  140. options.synchronous = YES;
  141. #if TARGET_OS_MACCATALYST
  142. if (@available(macOS 10.15, *)) {
  143. [[PHImageManager defaultManager] requestImageDataAndOrientationForAsset:self.phAsset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, CGImagePropertyOrientation orientation, NSDictionary *info) {
  144. self.assetData = imageData;
  145. self.fileSize = imageData.length;
  146. self.hasRealFilePath = NO;
  147. }];
  148. }
  149. #else
  150. if (@available(iOS 13, *)) {
  151. [[PHImageManager defaultManager] requestImageDataAndOrientationForAsset:self.phAsset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, CGImagePropertyOrientation orientation, NSDictionary *info) {
  152. self.assetData = imageData;
  153. self.fileSize = imageData.length;
  154. self.hasRealFilePath = NO;
  155. }];
  156. } else {
  157. [[PHImageManager defaultManager] requestImageDataForAsset:self.phAsset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  158. self.assetData = imageData;
  159. self.fileSize = imageData.length;
  160. self.hasRealFilePath = NO;
  161. }];
  162. }
  163. #endif
  164. }
  165. - (void)getVideoInfo {
  166. PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
  167. options.version = PHVideoRequestOptionsVersionCurrent;
  168. options.deliveryMode = PHVideoRequestOptionsDeliveryModeHighQualityFormat;
  169. //不支持icloud上传
  170. options.networkAccessAllowed = NO;
  171. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  172. [[PHImageManager defaultManager] requestAVAssetForVideo:self.phAsset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
  173. if ([asset isKindOfClass:[AVURLAsset class]]) {
  174. self.filePath = [[(AVURLAsset *)asset URL] path];
  175. self.hasRealFilePath = YES;
  176. }
  177. dispatch_semaphore_signal(semaphore);
  178. }];
  179. dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
  180. }
  181. - (void)exportAssert {
  182. NSArray *assetResources = [PHAssetResource assetResourcesForAsset:self.phAsset];
  183. PHAssetResource *resource;
  184. for (PHAssetResource *assetRes in assetResources) {
  185. if (assetRes.type == PHAssetResourceTypePairedVideo || assetRes.type == PHAssetResourceTypeVideo) {
  186. resource = assetRes;
  187. }
  188. }
  189. NSString *fileName = [NSString stringWithFormat:@"tempAsset-%f-%d.mov", [[NSDate date] timeIntervalSince1970], arc4random()%100000];
  190. PHAssetResourceRequestOptions *options = [PHAssetResourceRequestOptions new];
  191. //不支持icloud上传
  192. options.networkAccessAllowed = NO;
  193. NSString *PATH_VIDEO_FILE = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
  194. [[NSFileManager defaultManager] removeItemAtPath:PATH_VIDEO_FILE error:nil];
  195. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  196. [[PHAssetResourceManager defaultManager] writeDataForAssetResource:resource toFile:[NSURL fileURLWithPath:PATH_VIDEO_FILE] options:options completionHandler:^(NSError *_Nullable error) {
  197. if (error) {
  198. self.filePath = nil;
  199. } else {
  200. self.filePath = PATH_VIDEO_FILE;
  201. }
  202. self.hasRealFilePath = NO;
  203. dispatch_semaphore_signal(semaphore);
  204. }];
  205. dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
  206. }
  207. @end
  208. #endif