Is NSURLIsExcludedFromBackupKey recursive

六眼飞鱼酱① 提交于 2019-11-30 06:48:21

Yup, you can pass it a NSURL of the directory you want excluded.

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

And you can test any files if in doubt using

id flag = nil;
[URL getResourceValue: &flag
               forKey: NSURLIsExcludedFromBackupKey error: &error];
NSLog (@"NSURLIsExcludedFromBackupKey flag value is %@", flag)

From my tests (on a simulator), it is not recursive, and I've just had an app rejection because of too much data in Documents directory. Each folder directly in the Documents directory is flagged, so I guess the files inside them are not, even on a real device. But I also added new content in the folder, so I may just need to add the flag again.

So I'm using this recursive method now, and I add the flag on each new files added :

- (void) addSkipBackupAttributeToFolder:(NSURL*)folder
{
    [self addSkipBackupAttributeToItemAtURL:folder];

    NSError* error = nil;
    NSArray* folderContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[folder path] error:&error];

    for (NSString* item in folderContent)
    {
        NSString* path = [folder.path stringByAppendingPathComponent:item];
        [self addSkipBackupAttributeToFolder:[NSURL fileURLWithPath:path]];
    }
}

Here is a swift version of the accepted answer:

func addSkipBackupAttributeToItemAtURL(URL: NSURL) -> Bool {
    assert(NSFileManager.defaultManager().fileExistsAtPath(URL.path!))
    var success: Bool = true

    do {
        try URL.setResourceValue(NSNumber(bool: true), forKey: NSURLIsExcludedFromBackupKey)
    } catch {
        success = false
        print("Error excluding \(URL.lastPathComponent) from backup: \(error)")
    }

    return success
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!