我發現這兩種方法非常有幫助。您必須#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;
}