2014-10-28 103 views
6

有沒有正確的方法來訪問容器應用及其擴展的共享目錄中的NSCachesDirectory?如何訪問組共享文件夾中的NSCachesDirectory目錄?

NSURL *sharedDirectory = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:APPS_GROUP_NAME]; 

在此之後,獲得「/Library/Caches/」的正確方法是什麼?

回答

1

我發現這兩種方法非常有幫助。您必須#define g_groupName作爲您的共享應用程序組。 CachesDirectory將首先選擇共享應用程序組緩存文件夾,然後再回退到應用程序特定的緩存文件夾。 CachesDirectoryLocal總是返回應用程序特定的緩存文件夾。希望這可以幫助!

#define g_groupName @"group.com.yourdomain.yourapp" 
#define DISPATCH_ONCE(var, code) static dispatch_once_t onceToken; var dispatch_once(&onceToken, ^{ code }); 
#define FILE_MANAGER ([[NSFileManager alloc] init]) 

NSString* CachesDirectory() 
{ 
    DISPATCH_ONCE(static NSString* s_cacheFolderForGroup = nil;, 
    { 
     if (g_groupName.length != 0) 
     { 
      s_cacheFolderForGroup = [FILE_MANAGER containerURLForSecurityApplicationGroupIdentifier:g_groupName].path; 
      s_cacheFolderForGroup = [s_cacheFolderForGroup stringByAppendingPathComponent:@"Library/Caches/"]; 
      [FILE_MANAGER createDirectoryAtPath:s_cacheFolderForGroup withIntermediateDirectories:YES attributes:nil error:nil]; 
     } 
    }); 

    if (s_cacheFolderForGroup.length != 0) 
    { 
     return s_cacheFolderForGroup; 
    } 

    return CachesDirectoryLocal(); 
} 

NSString* CachesDirectoryLocal() 
{ 
    DISPATCH_ONCE(static NSString* s_cacheFolder = nil;, 
    { 
     NSArray* docDirs = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
     if (docDirs.count != 0 && [[docDirs objectAtIndex:0] isKindOfClass:NSString.class]) 
     { 
      s_cacheFolder = (NSString*)[docDirs objectAtIndex:0]; 
      if (![s_cacheFolder hasSuffix:@"/"]) 
      { 
       s_cacheFolder = [s_cacheFolder stringByAppendingString:@"/"]; 
      } 
     } 
     else 
     { 
      s_cacheFolder = @"./Library/Caches/"; 
     } 
    }); 

    return s_cacheFolder; 
} 
相關問題