ios 清空全部key chain以及userDefaults相关

清空相关信息,再构造唯一id等可做一键新机

清空全部key chain

+ (void)clearKeyChain {
    NSMutableDictionary *query = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                  (__bridge id)kCFBooleanTrue, (__bridge id)kSecReturnAttributes,
                                  (__bridge id)kSecMatchLimitAll, (__bridge id)kSecMatchLimit,
                                  nil];
    NSArray *secItemClasses = [NSArray arrayWithObjects:
                               (__bridge id)kSecClassGenericPassword,
                               (__bridge id)kSecClassInternetPassword,
                               (__bridge id)kSecClassCertificate,
                               (__bridge id)kSecClassKey,
                               (__bridge id)kSecClassIdentity,
                               nil];
    for (id secItemClass in secItemClasses) {
        NSLog(@"secItemClass %@",secItemClass);
        [query setObject:secItemClass forKey:(__bridge id)kSecClass];
        
        CFTypeRef result = NULL;
        SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
        if (result != NULL) CFRelease(result);

        NSDictionary *spec = @{(__bridge id)kSecClass: secItemClass};
        SecItemDelete((__bridge CFDictionaryRef)spec);
    }
}

  清空 userDefaults 用户相关

+ (void)clearUserDefaults {
    NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"Preferences"];
    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    
    for (NSString * filename in fileList) {
        NSString *filepath = [path stringByAppendingPathComponent:filename];
        BOOL isDir = NO;
        [[NSFileManager defaultManager] fileExistsAtPath:filepath isDirectory:(&isDir)];
        if (!isDir && [filename hasSuffix:@".plist"] && (![filename isEqualToString:appDomain])) {
            NSString *suitename = [filename stringByDeletingPathExtension];
            NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:suitename];
            [userDefaults removePersistentDomainForName:suitename];
            [[NSFileManager defaultManager] removeItemAtPath:filepath error:nil];
        }
    }
}

 

posted @ 2022-01-07 11:12  小君~  阅读(298)  评论(0编辑  收藏  举报