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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With