iOS如何避免文件和數據被同步到iCloud和iTunes?

問:個人App沙盒包含一些文件,用於在設備離線時候可以正常使用。這些文件不包含用戶數據,同時也不須要被同步。我該怎樣作防止文件和數據被同步到iCloud呢?html

答:在iOS系統中,應用程序負責確保只有用戶數據(user data)而不是應用程序的數據被同步到iCloud和iTunes。爲了防止數據和文件被同步到iCloud,在不一樣的iOS系統中作法有所不一樣。想了解哪些數據是否應該被同步,能夠閱讀 App Backup Best Practices section of the iOS App Programming Guide文檔。ios

Important:應用程序須要避免將應用程序的數據和用戶數據存儲在同一個文件中。這樣作會不可避免地增大被同步的文件大小,同時也違背了iOS數據存儲的規範(iOS Data Storage Guidelines)。app

iOS 5.1 and lateride

從iOS 5.1開始,應用程序可使用文件系統中的NSURLIsExcludedFromBackupKey或者kCFURLIsExcludedFromBackupKey來避免同步文件和目錄。ui

- (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.1code

在iOS 5.0.1系統中,能夠採用以下方法orm

#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?htm

相關文章
相關標籤/搜索