ios objective-c afnetworking nsurlcredential

ios - AFNetworking con NSURLCredential



objective-c (1)

Tengo 3 métodos, UserLogin, Login y LogoutButtonPressed:

UserLogin: Estoy usando AFNetworking para conectarme a una URL autenticada de Windows usando 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]; }

Este método es llamado por el método de inicio de sesión:

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

Y estoy tratando de borrar mi sesión con 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]; } } } }

Obtuve este código de este ejemplo: http://www.springenwerk.com/2008/11/i-am-currently-building-iphone.html

Ahora mi problema es que cuando enciendo el botón de cierre de sesión y luego voy a activar el método de inicio de sesión SIN CREDENCIALES, aún puedo iniciar sesión. Si me desconecto, espere 2 - 3 minutos y no inicie sesión SIN CREDENCIALES. No puedo iniciar sesión. ¿Por qué se está comportando de esta manera, es casi como si las credenciales todavía se guardaran? Por favor ayuda.

ACTUALIZAR

He intentado borrar el caché, las cookies y los credenciales dentro de mi 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]; } } }

Y todavía no funcionó.

También intenté borrar AuthorizationHeader y cancelar AllOperations y todavía nada, todavía puedo iniciar sesión con credenciales incorrectas o sin credenciales después de cerrar sesión:

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]; } } } NSURL *url = [NSURL URLWithString:kIP]; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = manager.requestSerializer; [requestSerializer clearAuthorizationHeader]; AFHTTPRequestOperationManager *httpClient = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url]; [[httpClient operationQueue] cancelAllOperations];


Este problema se puede solucionar fácilmente agregando un número aleatorio al final de la 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]; }

Y asegúrese de tener un número aleatorio al final de todas las URL que está llamando.