Comment get des cookies et les utiliser pour d'autres requests comme POST (iOS)?

Ma question précédente était sur le problème que je dois me connecter à chaque fois pour faire des services Web comme postr un lien ou download une image. Philipe a répondu que je devais utiliser des cookies au lieu du process de connection pour chaque request. J'ai trouvé cette méthode pour get des cookies:

- (void)getCookies { NSHTTPURLResponse * response; NSError * error; NSMutableURLRequest *request; request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithSsortingng:@"http://MyWebsite.com/login.php"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120]; NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"%@", [[NSSsortingng alloc] initWithData:data encoding:NSASCIISsortingngEncoding]); NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithSsortingng:@"http://MyWebsite.com/login.php"]]; NSLog(@"%d", all.count); for (NSHTTPCookie *cookie in all) { NSLog(@"Name: %@ : Value: %@", cookie.name, cookie.value); NSLog(@"Comment: %@ : CommentURL: %@", cookie.comment, cookie.commentURL); NSLog(@"Domain: %@ : ExpiresDate: %@", cookie.domain, cookie.expiresDate); NSLog(@"isHTTPOnly: %c : isSecure: %c", cookie.isHTTPOnly, cookie.isSecure); NSLog(@"isSessionOnly: %c : path: %@", cookie.isSessionOnly, cookie.path); NSLog(@"portList: %@ : properties: %@", cookie.portList, cookie.properties); NSLog(@"version: %u", cookie.version); } } 

J'ai également trouvé ce code pour utiliser ces cookies, mais je ne suis pas sûr de savoir comment l'utiliser:

 [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookies]; 

Voici ma méthode de POSTing, j'utilise l'API RestKit:

 - (IBAction)addLinkPressed:(UIButton *)sender { [RKClient clientWithBaseURLSsortingng:@"http://MyWebsite.com"]; NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys: self.linkField.text, @"url", self.linkTitleField.text, @"title", self.linkSummaryField.text, @"summary", nil]; RKRequest *request = [[RKClient sharedClient] post:@"/send_link.php" params:params delegate:self]; [request setUserData:@"sendLink"]; } 

Question: Quelle propriété des cookies dois-je stocker pour l'utiliser pour les informations de connection et où dois-je les mettre dans mon code?

J'ai résolu ce problème de manière inefficace. Voici ma méthodologie: Tout d'abord, j'essaie de postr sur le service web et après avoir posté, j'parsing le return HTML pour voir si l'envoi a été réussi ou non. Si l'envoi a réussi, je donne un message approprié à l'user que vous publiez avec succès, mais s'il échoue, il peut avoir deux raisons: Premièrement: il y a eu une erreur pendant l'exécution de la post. Deuxième: l'user n'était pas connecté. Je reconnais que la différenciation entre la première et la seconde erreur consiste simplement à parsingr la réponse HTML. Voici le code que j'ai utilisé pour cette méthodologie (c'est pour le moment que l'user veut changer le mot de passe)

 - (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error { NSRange range = [[error localizedDescription] rangeOfSsortingng:@"-1012"]; if (range.length > 0){ //First error occurs here } RKLogError(@"Hit error: %@", error); } - (IBAction)requestToChangePasswordPressed { MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; hud.labelText = @"Loading"; [RKClient clientWithBaseURLSsortingng:@"http://WebServiceDomain.com"]; NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys: self.oldPasswordField.text, @"oldPassword", self.passwordNew.text, @"newPassword", self.confirmPasswordField.text, @"confirmPassword", nil]; RKRequest *request = [[RKClient sharedClient] post:@"/change_password.php" params:params delegate:self]; [request setUserData:@"changePassword"]; [self.view endEditing:YES]; [MBProgressHUD hideHUDForView:self.view animated:YES]; } - (void)autoLogin { [RKClient clientWithBaseURLSsortingng:@"http://WebServiceDomain.com"]; [RKObjectManager sharedManager].client=[RKClient sharedClient]; RKParams *parameters = [RKParams params]; [parameters setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"defaultUsername"] forParam:@"username"]; [parameters setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"defaultPassword"] forParam:@"password"]; [[RKClient sharedClient] setAuthenticationType:RKRequestAuthenticationTypeHTTP]; // because we have two POSTs and we want to use the same method for both of the for didLoadResponse: we set the UserDate like bellow RKRequest *request = [[RKClient sharedClient] post:@"/login.php" params:parameters delegate:self]; [request setUserData:@"login"]; } - (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response { MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; hud.labelText = @"Loading"; id userData = [request userData]; if ([userData isEqual:@"login"]) { if ([request isGET]) { // Handling GET /foo.xml if ([response isOK]) { // Success! Let's take a look at the data NSLog(@"Resortingeved XML: %@", [response bodyAsSsortingng]); } } else if ([request isPOST]) { // Handling POST /other.json if ([response isJSON]) { NSLog(@"Got a JSON response back from our POST!"); } } else if ([request isDELETE]) { // Handling DELETE /missing_resource.txt if ([response isNotFound]) { NSLog(@"The resource path '%@' was not found.", [request resourcePath]); } } } else if ([userData isEqual:@"sendLink"]) { NSData *addLinksHtmlData = response.body; // 2 TFHpple *addlinksParser = [TFHpple hppleWithHTMLData:addLinksHtmlData]; // 3 NSSsortingng *errorLinksXpathQuerySsortingng = @"//div[@class='errorBox']/ul/li"; NSArray *errorLinksNodes = [addlinksParser searchWithXPathQuery:errorLinksXpathQuerySsortingng]; // 4 NSMutableArray *newErrorLinks = [[NSMutableArray alloc] initWithCapacity:0]; for (TFHppleElement *element in errorLinksNodes) { // 5 AllModels *errorTitle = [[AllModels alloc] init]; [newErrorLinks addObject:errorTitle]; // 6 errorTitle.errorTitle = [[element firstChild] content]; } // 8 self.linkErrorObjects = newErrorLinks; NSSsortingng *successLinksXpathQuerySsortingng = @"//div[@class='successBox']"; NSArray *successLinksNodes = [addlinksParser searchWithXPathQuery:successLinksXpathQuerySsortingng]; // 4 NSMutableArray *newSuccessLinks = [[NSMutableArray alloc] initWithCapacity:0]; for (TFHppleElement *element in successLinksNodes) { // 5 AllModels *successTitle = [[AllModels alloc] init]; [newSuccessLinks addObject:successTitle]; // 6 successTitle.successTitle = [[element firstChild] content]; } // 8 self.linkSuccessObjects = newSuccessLinks; } else { NSLog(@"HTTP status code: %d", response.statusCode); NSLog(@"HTTP status message: %@", [response localizedStatusCodeSsortingng]); NSLog(@"Header fields: %@", response.allHeaderFields); NSLog(@"Body: %@", response.bodyAsSsortingng); NSData *HtmlData = response.body; // 2 TFHpple *addParser = [TFHpple hppleWithHTMLData:HtmlData]; // 3 NSSsortingng *errorXpathQuerySsortingng = @"//div[@class='errorBox']/ul/li"; NSArray *errorNodes = [addParser searchWithXPathQuery:errorXpathQuerySsortingng]; // 4 NSMutableArray *newError = [[NSMutableArray alloc] initWithCapacity:0]; for (TFHppleElement *element in errorNodes) { // 5 AllModels *errorTitle = [[AllModels alloc] init]; [newError addObject:errorTitle]; // 6 errorTitle.errorTitle = [[element firstChild] content]; } // 8 self.ErrorObjects = newError; NSSsortingng *successXpathQuerySsortingng = @"//div[@class='successBox']"; NSArray *successNodes = [addParser searchWithXPathQuery:successXpathQuerySsortingng]; // 4 NSMutableArray *newSuccess = [[NSMutableArray alloc] initWithCapacity:0]; for (TFHppleElement *element in successNodes) { // 5 AllModels *successTitle = [[AllModels alloc] init]; [newSuccess addObject:successTitle]; // 6 successTitle.successTitle = [[element firstChild] content]; } // 8 self.successObjects = newSuccess; [self errorCheck]; } [MBProgressHUD hideHUDForView:self.view animated:YES]; [MBProgressHUD hideHUDForView:self.view animated:YES]; } - (void)errorCheck { MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; hud.labelText = @"Loading"; if(self.errorObjects.count > 0) { AllModels *errorlink = [self.errorObjects objectAtIndex:0]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"There is a problem" message:errorlink.errorTitle delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil , nil]; [alert show]; } else { if(self.linkErrorObjects.count > 0) { [self autoLogin]; [self requestToChangePasswordPressed]; } else { AllModels *successlink = [self.successObjects objectAtIndex:0]; self.successLabel.hidden = NO; self.successLabel.text = successlink.successTitle; NSLog(@"Success Title: %@",successlink.successTitle); [UIView animateWithDuration:3.0 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{ self.successLabel.alpha = 0.0; } completion:^(BOOL fin) { if (fin) [self.successLabel removeFromSuperview]; }]; [self performSelector:@selector(dismissModalViewController) withObject:nil afterDelay:1.0]; } } [MBProgressHUD hideHUDForView:self.view animated:YES]; [MBProgressHUD hideHUDForView:self.view animated:YES]; }