Подтвердить что ты не робот

Objective-c clear NSURLCredential - NSURLCredentialPersistenceForSession

Я использую 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];
}

И теперь я ищу, чтобы очистить NSURLCredentials в методе выхода из системы следующим образом:

-(void)logout
{
   //Clear NSURLCredentialPersistenceForSession
}

Как мне это сделать? Должен ли я reset 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];

        }

    }

Отсюда: Используя NSURLCredentialPersistenceForSession во время запроса, а затем очистка учетных данных при выходе из системы по-прежнему сохраняются сертификаты

Это лучший способ? У меня только 1 учетная запись. Также этот код дает мне предупреждение в этой строке:

NSURLCredential *credential = [spaceDictionary objectForKey:userName];

и вот предупреждение... как удалить это предупреждение?

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

UPDATE

Хорошо, поэтому у меня есть 3 метода: UserLogin, Login и LogoutButtonPressed

UserLogin: Я использую AFNetworking для подключения к аутентифицированному URL-адресу Windows с использованием NSURLCredential, как показано выше:

-(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];

}

Этот метод вызывается методом 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;

        }
    }];

}

И я пытаюсь очистить сеанс с помощью 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];
            }
        }
    }
}

Я получил этот код из этого примера: http://www.springenwerk.com/2008/11/i-am-currently-building-iphone.html

Теперь моя проблема заключается в том, что когда я запускаю кнопку выхода из системы, а затем запускаю метод входа в систему БЕЗ ПОЛНОМОЧИЙ, я все равно могу войти в систему, если я выйду из системы, а затем подождите 2 - 3 минуты и войдите в систему без NO CREDENTIALS. Я не могу авторизоваться. Почему он ведет себя таким образом, его почти как кредиты все еще сохраняются. Пожалуйста, помогите.

UPDATE

Я попытался очистить кеш, куки и кредиты внутри моего LogoutButtonPressed:

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];
        }
    }
}

и все еще не работает.

4b9b3361

Ответ 1

Эту проблему можно легко устранить, добавив случайное число в конец 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];

}

И убедитесь, что у вас есть случайное число в конце всех URL-адресов, которые вы вызываете.

Ответ 2

LogoutButtonPressed удаляет учетные данные из NSURLCredentialStorage, итерации по тем же учетным данным - NSEnumerator не поддерживает это. Вы видите сообщение "cred для удаления" в журнале?

Вместо этого вы можете попробовать использовать метод _resetCredentials из https://developer.apple.com/library/ios/samplecode/AdvancedURLConnections/Listings/CredentialsController_m.html.

Независимо от того, имеет ли это значение, было бы интересно изучить вывод, как до, так и после вызова resetCredentials, _dumpCredentials - или еще лучше сделать дамп в вашем методе входа в систему и посмотреть, не произошло ли немедленного изменения после reset, а затем через 2-3 минуты.

Является ли self.passwordTextField.text очищенным? В случае отсутствия учетных данных, в котором он входит в систему, делает ли NSURLCredential credentialWithUser: значение nil?