如何从Web服务器获取cookie并将其保存在iOS应用程序中?

我想从http://mycompany.com/page1…http://mycompany.com/page2获取JSON …在web服务器端,它需要初始loginhttp://mycompany.com / login ,然后为用户维护一个cookie。 我怎么得到这个NSURLConnection行为,而不必每次都要求login? 这是使用NSURLCredential存储的非工作代码。 我是否需要在login时从web服务获取cookie,然后将其与以后的请求一起发送? 我一直在努力,所以你可以澄清一下你的答案。

- (IBAction)getJSON:(id)sender { NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user" password:@"pass" persistence:NSURLCredentialPersistenceForSession]; NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:@"myCompany.com" port:0 protocol:@"http" realm:nil authenticationMethod:nil]; [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace]; //////////GET JSON////////////// NSError *error; NSURL *url = [NSURL URLWithString:@"http://mycompany.com.jsonpage1"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [[NSURLConnection alloc] initWithRequest:request delegate:self]; } //I am NOT getting JSON in this delegate - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSLog(@"%@",responseString); } 

读取cookies:

请参阅pipe理iPhone上的HTTP Cookie

设置cookie:

…用cookie属性设置字典,然后:

 NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:[NSDictionary dictionaryWithObjects:object forKeys:keys]]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie]; 

但请记住,会话Cookie可能会在您的服务器上过期