iOS开发:防止文件进行iCloud备份
代码如下:
#pragma mark – Excluding a File from Backups on iOS 5.1
– (BOOL)addSkipBackupAttributeToItemAtURL_iOS5_1:(NSURL *)URL
{
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(@”Error excluding %@ from backup %@”, [URL lastPathComponent], error);
}
return success;
}
#pragma mark – Setting the Extended Attribute on iOS 5.0.1
#import
– (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
const char* filePath = [[URL path] fileSystemRepresentation];
const char* attrName = “com.apple.MobileBackup”;
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
return result == 0;
}
– (NSURL *)getDefaultDir
{
NSURL *urlDefault = nil;
NSString *strDic = nil;
NSString *strVersion = [[UIDevice currentDevice] systemVersion];
float fVersion = 0.0;
if(strVersion.length > 0)
fVersion = [strVersion floatValue];
if (fVersion == 5.0) {
strDic = [NSString stringWithFormat:@”%@/Library/Caches/”,
NSHomeDirectory()];
} else {
strDic = [NSString stringWithFormat:@”%@/Library/%@/”,
NSHomeDirectory(),
[[NSBundle mainBundle] bundleIdentifier]];
}
if (![[NSFileManager defaultManager] fileExistsAtPath:strDic]) {
[[NSFileManager defaultManager] createDirectoryAtPath:strDic withIntermediateDirectories:YES attributes:nil error:nil];
}
urlDefault = [NSURL fileURLWithPath:strDic];
if (fVersion > 5.0 && fVersion < 5.1)
[self addSkipBackupAttributeToItemAtURL:urlDefault];
else if (fVersion >= 5.0)
[self addSkipBackupAttributeToItemAtURL_iOS5_1:urlDefault];
return urlDefault;
}
icloud备份,这个东西比较烦人,但从用户的角度,好多东西确实没必要备份。
苹果官方文档地址:https://developer.apple.com/library/ios/qa/qa1719/_index.html