iOS如何避免文件和数据被同步到iCloud和iTunes?

问:我的App沙盒包含一些文件,用于在设备离线时候能够正常使用。这些文件不包含用户数据,同时也不需要被同步。我该怎样做防止文件和数据被同步到iCloud呢?

答:在iOS系统中,应用程序负责确保只有用户数据(user data)而不是应用程序的数据被同步到iCloud和iTunes。为了防止数据和文件被同步到iCloud,在不同的iOS系统中做法有所不同。想了解哪些数据是否应该被同步,可以阅读 App Backup Best Practices section of the iOS App Programming Guide文档。

Important:应用程序需要避免将应用程序的数据和用户数据存储在同一个文件中。这样做会不可避免地增大被同步的文件大小,同时也违背了iOS数据存储的规范(iOS Data Storage Guidelines)。

iOS 5.1 and later

从iOS 5.1开始,应用程序可以使用文件系统中的NSURLIsExcludedFromBackupKey或者kCFURLIsExcludedFromBackupKey来避免同步文件和目录。

- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
{
    NSURL* URL= [NSURL fileURLWithPath: filePathString];
    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;
}

iOS 5.0.1

在iOS 5.0.1系统中,可以采用如下方法

#import <sys/xattr.h>
- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
{
    assert([[NSFileManager defaultManager] fileExistsAtPath: filePathString]);

    const char* filePath = [filePathString 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;
}
Back to Top

How do I prevent files from being backed up to iCloud and iTunes?

    原文作者:leejan97
    原文地址: https://segmentfault.com/a/1190000002952903
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞