如何访问组共享文件夹中的NSCachesDirectory目录?

时间:2014-10-28 00:54:09

标签: ios

是否有正确的方法来访问容器应用及其扩展的共享目录中的NSCachesDirectory?

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

获得" /Library/Caches/"的正确方法是什么?在此之后?

1 个答案:

答案 0 :(得分: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;
}