objective-c clear NSURLCredential - NSURLCredentialPersistenceForSession

use*_*331 11 objective-c nsurlcredential ios afnetworking

NSURLCredentials在这个方法中使用:

-(void)UserLogin:(NSString *)user andPassWordExists:(NSString *)password completionHandler:(void (^)(NSArray *resultsObject, NSError *error))completionHandler
{


   NSURL *url = [NSURL URLWithString:kIP];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                         initWithRequest:request];


    NSURLCredential *credential = [NSURLCredential
                                   credentialWithUser:user
                                   password:password
                                   persistence:NSURLCredentialPersistenceForSession];

    [operation setCredential:credential];

    [[NSOperationQueue mainQueue] addOperation:operation];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (completionHandler) {
            completionHandler(responseObject, nil);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        if (completionHandler) {
            completionHandler(nil, error);
        }

    }];

    [operation start];
}
Run Code Online (Sandbox Code Playgroud)

现在我想在注销方法中清除NSURLCredentials,如下所示:

-(void)logout
{
   //Clear NSURLCredentialPersistenceForSession
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?我应该重置NSURLCredentials还是在那里清除它们?

UPDATE

我找到了这个解决方案

NSURLCredentialStorage *credentialStorage = [NSURLCredentialStorage sharedCredentialStorage];
    NSDictionary *credentialsDicationary = [credentialStorage allCredentials];


    for (NSURLProtectionSpace *space in [credentialsDicationary allKeys]) {

        NSDictionary *spaceDictionary = [credentialsDicationary objectForKey:space];

        for (id userName in [spaceDictionary allKeys]) {

            NSURLCredential *credential = [spaceDictionary objectForKey:userName];

            [credentialStorage removeCredential:credential forProtectionSpace:space];

        }

    }
Run Code Online (Sandbox Code Playgroud)

从这里:在请求时使用NSURLCredentialPersistenceForSession,然后在注销时清除凭据仍然保留cerdentials

这是最好的方法吗?我只存储了1个凭证.此代码也在此行上给出了警告:

NSURLCredential *credential = [spaceDictionary objectForKey:userName];
Run Code Online (Sandbox Code Playgroud)

这是警告......如何删除此警告?

/Users/jsuske/Documents/SSiPad(Device Only)ios7/SchedulingiPadApplication/ViewControllers/LHLoginController.m:496:73: Local declaration of 'userName' hides instance variable
Run Code Online (Sandbox Code Playgroud)

UPDATE

好的,我有3个方法:UserLogin,Login和LogoutButtonPressed

UserLogin:我正在使用AFNetworking使用NSURLCredential连接到Windows身份验证的URL,如上所示:

-(void)UserLogin:(NSString *)user andPassWordExists:(NSString *)password completionHandler:(void (^)(NSArray *resultsObject, NSError *error))completionHandler
{

   NSURL *url = [NSURL URLWithString:kIP];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                         initWithRequest:request];

    NSURLCredential *credential = [NSURLCredential
                                   credentialWithUser:user
                                   password:password
                                   persistence:NSURLCredentialPersistenceForSession];

    [operation setCredential:credential];


    [[NSOperationQueue mainQueue] addOperation:operation];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (completionHandler) {
            completionHandler(responseObject, nil);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        if (completionHandler) {
            completionHandler(nil, error);
        }

    }];

    [operation start];

}
Run Code Online (Sandbox Code Playgroud)

Login方法调用此方法:

- (void)Login
{
    NSString *rawString = [self.idTextField text];
    NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    [self.idTextField setText:[rawString stringByTrimmingCharactersInSet:whitespace]];


    [userName UserLogin:self.idTextField.text andPassWordExists:self.passwordTextField.text completionHandler:^(id responseObject, NSError *error) {
        if (responseObject) {

                [self.idTextField removeFromSuperview];
                [self.passwordTextField removeFromSuperview];
                [self.loginButton removeFromSuperview];
                self.idTextField = nil;
                self.passwordTextField = nil;
                //self.loginButton = nil;


                [self CreateMenu];



                [indicatorView stopAnimating];
                [indicatorView removeFromSuperview];
                indicatorView = nil;
                [loadingView removeFromSuperview];
                loadingView = nil;
        }else{


            [self CustomAlert:@"Sorry Login Failed, User and/or Passsword Incorrect"];

            [indicatorView stopAnimating];
            [indicatorView removeFromSuperview];
            indicatorView = nil;
            [loadingView removeFromSuperview];
            loadingView = nil;

        }
    }];

}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用LogoutButtonPressed清除我的会话:

- (void)LogoutButtonPressed
{

    //@TODO: Fix Logout

    NSDictionary *credentialsDict = [[NSURLCredentialStorage sharedCredentialStorage] allCredentials];

    if ([credentialsDict count] > 0) {
        NSEnumerator *protectionSpaceEnumerator = [credentialsDict keyEnumerator];
        id urlProtectionSpace;

        while (urlProtectionSpace = [protectionSpaceEnumerator nextObject]) {
            NSEnumerator *userNameEnumerator = [[credentialsDict objectForKey:urlProtectionSpace] keyEnumerator];
            id userNameCred;

            while (userNameCred = [userNameEnumerator nextObject]) {
                NSURLCredential *cred = [[credentialsDict objectForKey:urlProtectionSpace] objectForKey:userNameCred];
                NSLog(@"cred to be removed: %@", cred);
                [[NSURLCredentialStorage sharedCredentialStorage] removeCredential:cred forProtectionSpace:urlProtectionSpace];
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我从这个例子中得到了这个代码:http://www.springenwerk.com/2008/11/i-am-currently-building-iphone.html

现在我的问题是,当我触发注销按钮然后转到触发登录方法没有结果我仍然可以登录,如果我注销然后等待2 - 3分钟并登录没有证书我无法登录.为什么它表现得这样,它几乎就像信用卡仍然保存.请帮忙.

UPDATE

我试图清除LogoutButtonPressed中的缓存,cookie和信用:

NSURLCache *sharedCache = [NSURLCache sharedURLCache];
[sharedCache removeAllCachedResponses];

NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookies = [cookieStorage cookies];
id cookie;
for (cookie in cookies) {
    [cookieStorage deleteCookie:cookie];
}

NSDictionary *credentialsDict = [[NSURLCredentialStorage sharedCredentialStorage] allCredentials];
if ([credentialsDict count] > 0) {
    NSEnumerator *protectionSpaceEnumerator = [credentialsDict keyEnumerator];
    id urlProtectionSpace;
    while (urlProtectionSpace = [protectionSpaceEnumerator nextObject]) {
        NSEnumerator *userNameEnumerator = [[credentialsDict objectForKey:urlProtectionSpace] keyEnumerator];
        id userNameCreds;
        while (userNameCreds = [userNameEnumerator nextObject]) {
            NSURLCredential *cred = [[credentialsDict objectForKey:urlProtectionSpace] objectForKey:userNameCreds];
            [[NSURLCredentialStorage sharedCredentialStorage] removeCredential:cred forProtectionSpace:urlProtectionSpace];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它仍然无法正常工作.

use*_*331 5

通过在URL末尾添加一个随机数,可以轻松解决此问题:

-(void)UserLogin:(NSString *)user andPassWordExists:(NSString *)password completionHandler:(void (^)(NSArray *resultsObject, NSError *error))completionHandler
{
   NSInteger randomNumber = arc4random() % 999;

   NSString *requestURL = [NSString stringWithFormat:@"%@?cache=%ld",kIP,(long)randomNumber];

   NSURL *url = [NSURL URLWithString:requestURL];

   NSURLRequest *request = [NSURLRequest requestWithURL:url];
     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                         initWithRequest:request];

   NSURLCredential *credential = [NSURLCredential
                                   credentialWithUser:user
                                   password:password
                                   persistence:NSURLCredentialPersistenceForSession];


    [operation setCredential:credential];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    [[NSOperationQueue mainQueue] addOperation:operation];


    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (completionHandler) {
            completionHandler(responseObject, nil);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        if (completionHandler) {
            completionHandler(nil, error);
        }

    }];

    [operation start];

}
Run Code Online (Sandbox Code Playgroud)

并确保在您呼叫的所有URL的末尾都有一个随机数.