DFPlayerFileManager.m 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. //
  2. // DFPlayerFileManager.m
  3. // DFPlayer
  4. //
  5. // Created by ihoudf on 2017/7/30.
  6. // Copyright © 2017年 ihoudf. All rights reserved.
  7. //
  8. #import "DFPlayerFileManager.h"
  9. #import "DFPlayerTool.h"
  10. static NSString *DFPlayer_UserId = @"DFPlayerUserId";
  11. static NSString * DFCachePath(BOOL currentUser){
  12. // 所有缓存文件都放在了沙盒Cache文件夹下DFPlayerCache文件夹里,然后再根据userId分文件夹缓存
  13. NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"DFPlayerCache"];
  14. if (currentUser) {
  15. NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:DFPlayer_UserId];
  16. NSString *name = [NSString stringWithFormat:@"user_%@",userId];
  17. path = [path stringByAppendingPathComponent:name];
  18. }
  19. if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
  20. return path;
  21. }
  22. BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  23. return success ? path : nil;
  24. }
  25. static NSString * DFTempPath(){
  26. return [NSTemporaryDirectory() stringByAppendingPathComponent:@"MusicTemp.mp4"];
  27. }
  28. static NSString * DFArchiverPath(){
  29. return [DFCachePath(YES) stringByAppendingPathComponent:@"DFPlayer.archiver"];
  30. }
  31. @implementation DFPlayerFileManager
  32. + (void)df_saveUserId:(NSString *)userId{
  33. NSString *ids = @"public";
  34. if (![userId df_isEmpty]) {
  35. ids = userId;
  36. }
  37. [[NSUserDefaults standardUserDefaults] setObject:ids forKey:DFPlayer_UserId];
  38. [[NSUserDefaults standardUserDefaults] synchronize];
  39. }
  40. + (BOOL)df_createTempFile{
  41. NSFileManager *mgr = [NSFileManager defaultManager];
  42. NSString *path = DFTempPath();
  43. if ([mgr fileExistsAtPath:path]) {
  44. [mgr removeItemAtPath:path error:nil];
  45. }
  46. return [mgr createFileAtPath:path contents:nil attributes:nil];
  47. }
  48. + (void)df_writeDataToAudioFileTempPathWithData:(NSData *)data{
  49. NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:DFTempPath()];
  50. [handle seekToEndOfFile];
  51. [handle writeData:data];
  52. }
  53. + (NSData *)df_readTempFileDataWithOffset:(NSUInteger)offset length:(NSUInteger)length{
  54. NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:DFTempPath()];
  55. [handle seekToFileOffset:offset];
  56. return [handle readDataOfLength:length];
  57. }
  58. + (BOOL)df_moveAudioFileFromTempPathToCachePath:(NSURL *)audioUrl{
  59. NSString *path = [DFPlayerFileManager audioCachedPath:audioUrl];
  60. NSFileManager *mgr = [NSFileManager defaultManager];
  61. if (![mgr fileExistsAtPath:path]) {
  62. NSNumber *numberId = [NSNumber numberWithInt:[DFPlayer_UserId intValue]];
  63. [mgr createDirectoryAtPath:path withIntermediateDirectories:YES attributes:@{NSFileOwnerAccountID:numberId} error:nil];
  64. }
  65. NSString *audioName = [audioUrl.path lastPathComponent];
  66. NSString *cachePath = [path stringByAppendingPathComponent:audioName];
  67. NSError *error;
  68. BOOL success = [mgr moveItemAtPath:DFTempPath() toPath:cachePath error:&error];
  69. if (!success) {//安全性处理 如果没有保存成功,删除归档文件中的对应键值对
  70. [DFPlayerArchiverManager deleteKeyValueIfHaveArchivedWithUrl:audioUrl];
  71. }
  72. return success;
  73. }
  74. + (NSString *)df_cachePath:(NSURL *)audioUrl{
  75. NSString *path = [DFPlayerFileManager audioCachedPath:audioUrl];
  76. NSString *audioName = [audioUrl.path lastPathComponent];
  77. NSString *cachePath = [path stringByAppendingPathComponent:audioName];
  78. return [[NSFileManager defaultManager] fileExistsAtPath:cachePath] ? cachePath : nil;
  79. }
  80. + (NSString *)audioCachedPath:(NSURL *)audioUrl{
  81. NSString *backStr = [[audioUrl.absoluteString componentsSeparatedByString:@"//"].lastObject stringByDeletingLastPathComponent];
  82. return [DFCachePath(YES) stringByAppendingPathComponent:backStr];
  83. }
  84. + (CGFloat)df_cacheSize:(BOOL)currentUser{
  85. NSString *path = DFCachePath(currentUser);
  86. NSArray *fileArray = [[NSFileManager defaultManager] subpathsAtPath:path];
  87. CGFloat size = 0;
  88. for (NSString *file in fileArray) {
  89. NSString *filePath = [path stringByAppendingPathComponent:file];
  90. size += [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil].fileSize;
  91. }
  92. return size / 1000.0 / 1000.0;
  93. }
  94. + (BOOL)df_clearAudioCache:(NSURL *)audioUrl{
  95. NSString *path = [self df_cachePath:audioUrl];
  96. return [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
  97. }
  98. + (BOOL)df_clearUserCache:(BOOL)currentUser{
  99. return [[NSFileManager defaultManager] removeItemAtPath:DFCachePath(currentUser) error:nil];
  100. }
  101. @end
  102. @implementation DFPlayerArchiverManager
  103. + (NSMutableDictionary *)df_hasArchivedFileDictionary{
  104. _archiverDic = [NSKeyedUnarchiver unarchiveObjectWithFile:DFArchiverPath()];
  105. if (!_archiverDic){
  106. _archiverDic = [NSMutableDictionary dictionary];
  107. }
  108. return _archiverDic;
  109. }
  110. + (BOOL)df_archiveValue:(id)value forKey:(NSString *)key{
  111. NSMutableDictionary *dic = [DFPlayerArchiverManager df_hasArchivedFileDictionary];
  112. [dic setValue:value forKey:key];
  113. return [NSKeyedArchiver archiveRootObject:dic toFile:DFArchiverPath()];
  114. }
  115. + (void)deleteKeyValueIfHaveArchivedWithUrl:(NSURL *)url{
  116. NSMutableDictionary *dic = [DFPlayerArchiverManager df_hasArchivedFileDictionary];
  117. __block BOOL isHave = NO;
  118. [dic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
  119. if ([key isEqualToString:url.absoluteString]) {
  120. [dic removeObjectForKey:key];
  121. isHave = YES;
  122. *stop = YES;
  123. }
  124. }];
  125. if (isHave) {
  126. [NSKeyedArchiver archiveRootObject:dic toFile:DFArchiverPath()];
  127. }
  128. }
  129. @end