Mike Ross
Mike Ross

Reputation: 2972

Could not send cookies to WebView Objective C

I have written this following code which I found from a question on SO.

I am still confused because after doing all that I still can't access the cookies on my PHP page.

What am I doing wrong here?

- (void)viewDidLoad {

  [super viewDidLoad];

  UIWebView *webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height)];

  NSString *url=@"http://mywebsite.com";
  NSURL *nsurl=[NSURL URLWithString:url];
  NSMutableURLRequest *nsrequest=[NSMutableURLRequest requestWithURL:nsurl];

  NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
  [cookieProperties setObject:@"testCookie" forKey:NSHTTPCookieName];
  [cookieProperties setObject:@"someValue123456" forKey:NSHTTPCookieValue];
  [cookieProperties setObject:@"www.mywebsite.com" forKey:NSHTTPCookieDomain];
  [cookieProperties setObject:@"www.mywebsite.com" forKey:NSHTTPCookieOriginURL];
  [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
  [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

  [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

  NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
  [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

  [webview loadRequest:nsrequest];

}

Upvotes: 0

Views: 147

Answers (2)

Grifas
Grifas

Reputation: 217

Use this to set your object:

    nsrequest.addValue(value: "testCookie", forHTTPHeaderField: NSHTTPCookieName)
etc...

Sorry, it's in Swift 3 ^^ but you can convert to Obj-c

Upvotes: 1

IanW
IanW

Reputation: 456

You've set the cookie on "www.example.com/", but you're trying to load "my website.com" - change the NSHTTPCookieDomain and NSHTTPCookieOriginURL to "mywebsite.com" or try loading "www.example.com" in your request!

Upvotes: 0

Related Questions