Enable Cookies in UIWebView

前端 未结 2 367
轮回少年
轮回少年 2021-01-02 22:21

How can I enable cookies in my iPhone Application that uses a UIWebView Window, so that my login system will work?

2条回答
  •  情话喂你
    2021-01-02 22:28

    For sure start with

    [NSHTTPCookieStorage sharedHTTPCookieStorage].cookieAcceptPolicy = 
        NSHTTPCookieAcceptPolicyAlways;
    

    But, as mentioned by @JoelFan, the issue may be your User Agent string causing ASP.NET to attempt and fail at a cookieless login. Instead of a response that includes

    Set-Cookie: .ASPXAUTH=really-long-hex-number

    it returns a redirection to something like

    Location: /(F(long-sorta-base64ish-looking-string))/

    The default UIWebView user agent string is something like

    User-Agent: Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/11A501

    but ASP.NET doesn't like this. Safari sends something like this:

    User-Agent: Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A501 Safari/9537.53

    Do the following early on, maybe in your AppDelegate.m

    // DON'T try to reuse a UIWebView for this. 
    UIWebView *wv = [[UIWebView alloc] initWithFrame:CGRectZero];
    // This webview has already decided to use the default user agent string.
    
    // let's use javascript to get the existing user agent string
    NSString *userAgent = [wv stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    
    // let's tack on some stuff to make ASP.NET happy
    userAgent = [userAgent stringByAppendingString:@" Version/7.0 Safari/9537.53"];
    
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
    // New UIWebViews inited after here will use the user agent string you made.
    

提交回复
热议问题