阻止应用备份文档文件夹?

时间:2012-12-03 12:03:00

标签: objective-c ios xcode backup icloud

我正在尝试阻止我的应用程序将文件备份到iCloud,但已经完全混淆并且有点迷失。

- 编辑 -

我已经对此进行了更新,以反映我在下面的海报中所做的更改。

我想阻止备份到应用程序文档目录的文件。

到目前为止,我有一个名为PreventBackup的类,其方法如下:

+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{    
   NSError *error = nil;
   BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                              forKey: NSURLIsExcludedFromBackupKey error: &error];
   if(!success){
       NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
   }
   NSLog(@"prevent backup method called without error");
   return success;
}

我在应用程序启动时使用此代码调用它:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *pathURL= [NSURL fileURLWithPath:documentsDirectory];
[PreventBackup addSkipBackupAttributeToItemAtURL:pathURL];

cosole打印prevent backup method called without error但该应用程序仍然显示为具有与之前备份相同数量的数据。

知道这出错了吗?

-EDIT 2 -

好的,我认为这已经解决了。文件正在下载到名为“downloads”的子文件夹。更改上面的代码使其读取如下似乎已成功:

NSString *downloadsFolder = [documentsDirectory stringByAppendingPathComponent:(@"/downloads")];
NSURL *pathURL= [NSURL fileURLWithPath:downloadsFolder];
[PreventBackup addSkipBackupAttributeToItemAtURL:pathURL];

感谢大家的帮助。

2 个答案:

答案 0 :(得分:6)

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

NSURL *documentURLWithExtension = [documentURL URLByAppendingPathExtension:extensionType];

将此“documentURLWithExtension”传递给此函数

[self addSkipBackupAttributeToItemAtURL:documentURLWithExtension];

答案 1 :(得分:6)

在Swift中:

//Path of document directory
var docPathAry : NSArray! = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var docDirPathStr: AnyObject? = docPathAry.count > 0 ? docPathAry[0] : nil

self.addSkipBackupAttributeToItemAtURL(NSURL.fileURLWithPath(docDirPathStr as NSString))

func addSkipBackupAttributeToItemAtURL(URL: NSURL!) -> Bool {
    assert(NSFileManager.defaultManager().fileExistsAtPath(URL.path))
    var err : NSError? = nil
    var success : Bool! = URL.setResourceValue(NSNumber.numberWithBool(true), forKey: NSURLIsExcludedFromBackupKey, error: &err)

    if(!success) {
        println("Error excluding \(URL.lastPathComponent) from backup\(err) ")
    }

    return success
}