QNALAssetFile.m 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //
  2. // QNALAssetFile.m
  3. // QiniuSDK
  4. //
  5. // Created by bailong on 15/7/25.
  6. // Copyright (c) 2015年 Qiniu. All rights reserved.
  7. //
  8. #import "QNALAssetFile.h"
  9. #ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
  10. #if !TARGET_OS_MACCATALYST
  11. #import <AssetsLibrary/AssetsLibrary.h>
  12. #import "QNResponseInfo.h"
  13. @interface QNALAssetFile ()
  14. @property (nonatomic) ALAsset *asset;
  15. @property (readonly) int64_t fileSize;
  16. @property (readonly) int64_t fileModifyTime;
  17. @property (nonatomic, strong) NSLock *lock;
  18. @end
  19. @implementation QNALAssetFile
  20. - (instancetype)init:(ALAsset *)asset
  21. error:(NSError *__autoreleasing *)error {
  22. if (self = [super init]) {
  23. NSDate *createTime = [asset valueForProperty:ALAssetPropertyDate];
  24. int64_t t = 0;
  25. if (createTime != nil) {
  26. t = [createTime timeIntervalSince1970];
  27. }
  28. _fileModifyTime = t;
  29. _fileSize = asset.defaultRepresentation.size;
  30. _asset = asset;
  31. _lock = [[NSLock alloc] init];
  32. }
  33. return self;
  34. }
  35. - (NSData *)read:(long)offset
  36. size:(long)size
  37. error:(NSError **)error {
  38. NSData *data = nil;
  39. @try {
  40. [_lock lock];
  41. ALAssetRepresentation *rep = [self.asset defaultRepresentation];
  42. Byte *buffer = (Byte *)malloc(size);
  43. NSUInteger buffered = [rep getBytes:buffer fromOffset:offset length:size error:error];
  44. data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
  45. } @catch (NSException *exception) {
  46. *error = [NSError errorWithDomain:NSCocoaErrorDomain code:kQNFileError userInfo:@{NSLocalizedDescriptionKey : exception.reason}];
  47. NSLog(@"read file failed reason: %@ \n%@", exception.reason, exception.callStackSymbols);
  48. } @finally {
  49. [_lock unlock];
  50. }
  51. return data;
  52. }
  53. - (NSData *)readAllWithError:(NSError **)error {
  54. return [self read:0 size:(long)_fileSize error:error];
  55. }
  56. - (void)close {
  57. }
  58. - (NSString *)path {
  59. ALAssetRepresentation *rep = [self.asset defaultRepresentation];
  60. return [rep url].path;
  61. }
  62. - (int64_t)modifyTime {
  63. return _fileModifyTime;
  64. }
  65. - (int64_t)size {
  66. return _fileSize;
  67. }
  68. @end
  69. #endif
  70. #endif