Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access NSCachesDirectory directory in group shared folder?

Tags:

ios

Is there a proper way to access the NSCachesDirectory in the shared directory for the container app and its extension?

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

What's the right way to obtain "/Library/Caches/" after this?

like image 729
anna Avatar asked Oct 28 '14 00:10

anna


1 Answers

I've found these two methods to be very helpful. You must #define g_groupName to be your shared app group. CachesDirectory will choose the shared app group caches folder first before falling back to the app specific caches folder. CachesDirectoryLocal always returns the app specific caches folder. Hope this helps!

#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;
}
like image 67
jjxtra Avatar answered Oct 05 '22 20:10

jjxtra