如何删除登录信息的keyChain信息?

时间:2011-03-02 18:27:31

标签: iphone ios keychain

以下是我遇到的用于登录的一些代码,但是如何将其删除到钥匙串中的信息?

+ (User *)currentUserForSite:(NSURL *)aSiteURL {
    User *user = [[[self alloc] init] autorelease];
    user.siteURL = aSiteURL;
    [user loadCredentialsFromKeychain];
    return user;
}

- (BOOL)hasCredentials {    
    return (self.login != nil && self.password != nil);
}

- (BOOL)authenticate:(NSError **)error { 
    if (![self hasCredentials]) {
        return NO;
    }

    Session *session = [[[Session alloc] init] autorelease];
    session.login = self.login;
    session.password = self.password;

    return [session createRemoteWithResponse:error];
}

- (void)saveCredentialsToKeychain {
    NSURLCredential *credentials = 
    [NSURLCredential credentialWithUser:self.login
                               password:self.password
                            persistence:NSURLCredentialPersistencePermanent];

    [[NSURLCredentialStorage sharedCredentialStorage]   
     setCredential:credentials forProtectionSpace:[self protectionSpace]];
}

#pragma mark -
#pragma mark Key-value observing

- (void)addObserver:(id)observer {
    [self addObserver:observer forKeyPath:kUserLoginKey options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:observer forKeyPath:kUserPasswordKey options:NSKeyValueObservingOptionNew context:nil];
}

- (void)removeObserver:(id)observer {
    [self removeObserver:observer forKeyPath:kUserLoginKey];
    [self removeObserver:observer forKeyPath:kUserPasswordKey];
}

#pragma mark -
#pragma mark Private methods

- (void)loadCredentialsFromKeychain {
    NSDictionary *credentialInfo = 
    [[NSURLCredentialStorage sharedCredentialStorage] 
     credentialsForProtectionSpace:[self protectionSpace]];

    // Assumes there's only one set of credentials, and since we
    // don't have the username key in hand, we pull the first key.
    NSArray *keys = [credentialInfo allKeys];
    if ([keys count] > 0) {
        NSString *userNameKey = [[credentialInfo allKeys] objectAtIndex:0]; 
        NSURLCredential *credential = [credentialInfo valueForKey:userNameKey];
        self.login = credential.user;
        self.password = credential.password;
    }
}

- (NSURLProtectionSpace *)protectionSpace {
    return [[[NSURLProtectionSpace alloc] initWithHost:[siteURL host]
                                                  port:[[siteURL port] intValue]
                                              protocol:[siteURL scheme]
                                                 realm:@"Web Password"
                                  authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
}

2 个答案:

答案 0 :(得分:2)

我不是专家,但我认为您不能删除使用NSURLCredentialPersistencePermanent存储的凭据。我只是将凭证更新为空字符串 - @“”

答案 1 :(得分:2)

我看到这个问题已经过时了,但对于今天看的人来说,有一种方法可以删除凭证:

a

参考: https://bugreports.qt.io/browse/QTBUG-36175