SFSafariViewController cookies

18.6k views Asked by At

I understand that as of iOS9 you should be able to read cookies with SFSafariViewController.

If I set a cookie on my page in JS using the following:

var dd = new Date(Date.now() + 1000 * 60 * 60 * 24).toGMTString();
var expires = "expires="+ dd;
document.cookie = "mycookie=cookievalue; " + expires  + " domain=.mydomain.co.uk ; path=/ ";

If I do :

- (void)safariViewController:(SFSafariViewController *)controller didCompleteInitialLoad:(BOOL)didLoadSuccessfully
{
  NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  NSArray *cookiesArray = [storage cookies];
}

cookiesArray is always empty.

If I use a traditional UIWebView

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
  NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  NSArray *cookiesArray = [storage cookies];
}

I get the cookie I was expecting.

Any ideas what I might be doing wrong?

2

There are 2 answers

7
wottle On BEST ANSWER

SFSafariViewController is basically a Safari process, running outside of your app. Your app will not have any access to the cookies used by the SFSafariViewController, just as your app has no access to the cookies in the Safari app itself.

If you need this functionality, you'll need to stuck with UIWebView or WKWebView.

0
Mohit Gonduley On

SFSafariViewController runs in a separate process, so reading cookies is NOT possible.

However, in case SFSafariViewController is the only option available due to some limitations with the existing available options like WKWebView, and UIWebView.Then the custom URL scheme approach will be helpful in sending the data from SFSafariViewController to the parent App which initiates the SFSafariViewController.

In the above case, a possible URL will be as follows, where "myapp" is the custom URL scheme

"myapp://SendData?mycookie=cookievalue&domain=.mydomain.co.uk&path=/"

So, the custom URL scheme will be registered against the parent app to launch it and custom URL scheme parameters will have the intended data to be received by the parent app. If the data is sensitive then it can be encrypted by javascript prior to sending and can be decrypted by the parent app after receiving it.

Hope this would help :)

For more details on the custom URL scheme, please visit https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app