NSMutableURLRequest and setcookie don't work well.

Hello, please let me ask a question.


I'm trying to use NSMutableURLRequest with WKWebView in order to manage cookies.


I wrote the following code.


-----

// Client Application side (Objective-C)


NSMutableURLRequest* mutableRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxx.xxx.xxx.xxx/"]];

// add 2 cookies

[mutableRequest addValue:@"id1=AAA;id2=BBB;" forHTTPHeaderField:@"Cookie"];


[webView loadRequest:mutableRequest];

-----

// Server side (PHP / Symfony framework)


$timeout = strtotime( '2099-12-31' );

setcookie( 'id1', 'CCC', $timeout, '/' ); // change

setcookie( 'id2', 'DDD', $timeout, '/' ); // change

setcookie( 'id3', 'EEE', $timeout, '/' ); // add

print_r( 'cookie[id1] = '.$_COOKIE['id1'].'<br>' );

print_r( 'cookie[id2] = '.$_COOKIE['id2'].'<br>' );

print_r( 'cookie[id3] = '.$_COOKIE['id3'].'<br>' );

[...]

header( 'Location:'. $url ); // reload this page (once)

-----


However, I got the following results.

-----

(1st - before reload)

cookie[id1] = AAA

cookie[id2] = BBB

cookie[id3] =


(2nd - after reload)

cookie[id1] = AAA // not changed

cookie[id2] = BBB // not changed

cookie[id3] = // not added

-----


Why "setcookie" function loses effect in this case?

If not adding cookies "id1" and "id2" first, all "setcookie" worked well.


Can anyone help me?

I found the below description in https://developer.apple.com/reference/foundation/nsmutableurlrequest/1415485-httpshouldhandlecookies ...


If your app sets the

Cookie
header on an
NSMutableURLRequest
object, then this method has no effect, and the cookie data you set in the header overrides all cookies from the cookie store.

I understood that the behavior I wrote in this topic is correct.


I'll look for an another way to manage both App-set Cookie and Server-set Cookie.

NSMutableURLRequest and setcookie don't work well.
 
 
Q