防止文件备份到iCloud和iTunes中

 

  

ios5.0

在ios5.0中,不可能设置不备份的数据。如果app支持ios5.0的话,你需要将你不备份的数据放在Caches目录中。iOS会在必要的时候删除Caches目录中的文件,因此你的app需要处理这些文件被删除的情景

ios5.0.1

如果你的app支持ios5.0.1,如果不想将创建的文件或文件夹备份的话,你需要先将数据写道文件中然后调用下面的方法

 

#import <sys/xattr.h>

 - (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;
}

ios5.1+

从ios5.1开始,app可以用NSURLIsExcludedFromBackupKey 或者 kCFURLIsExcludedFromBackupKey 文件属性来设置以防止被备份。调用下面的方法即可

- (BOOL)addSkipBackupAttributeToItemAtURL:(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; }

  

总结所有版本

+(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)fileURL {
if (![[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
    NSLog(@"File %@ doesn't exist!",[fileURL path]);
    return NO;
}
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];    
if ([currSysVer isEqualToString:@"5.0.1"]) {
    const char* filePath = [[fileURL path] fileSystemRepresentation];
    const char* attrName = "com.apple.MobileBackup";
    u_int8_t attrValue = 1;
    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    NSLog(@"Excluded '%@' from backup",fileURL);
    return result == 0;
}
else if (&NSURLIsExcludedFromBackupKey) {
    NSError *error = nil;
    BOOL result = [fileURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error];
    if (!result) {
        NSLog(@"Error excluding '%@' from backup. Error: %@",fileURL, error);
    }
    return result;

}

  

 

转载于:https://www.cnblogs.com/binglin92/p/3524906.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值