iOS UIWebview 引用URL时存 cookie 方法 并向localStorage中存值


向URL中注入cookie:

-(void)saveCookie

{

    

    NSURL *url= [NSURL URLWithString:self.urlStr];

    NSString *hostStr= url.host;

        //注入Cookie

        NSMutableArray *myMuArr=[NSMutableArray array];

        NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

        [cookieProperties setObject:@"pId" forKey:NSHTTPCookieName];        

        [cookieProperties setObject:[NSString stringWithFormat:@"%@",pUserID] forKey:NSHTTPCookieValue];

        [cookieProperties setObject:hostStr forKey:NSHTTPCookieDomain];

        [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];

        [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

        NSHTTPCookie *cookie1 = [NSHTTPCookie cookieWithProperties:cookieProperties];

        [myMuArr addObject:cookie1];

        NSArray *mmmArr=[NSArray arrayWithArray:myMuArr];

        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:mmmArr forURL:url mainDocumentURL:url];

        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlStr]];

        [self.myWebView loadRequest:request];

    

}


注意: 需要在注入cookie后再reloadRequest Webview


向 localStorage 中存值


        NSString * userContent = [NSString stringWithFormat:@"%@",pUserID];

        NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('pid', '%@')", userContent];

        移除cookie

        NSString *jsString = @"localStorage.removeItem('pid')";

        [self.myWebView stringByEvaluatingJavaScriptFromString:jsString];


此方法可写在 

-(void)webViewDidFinishLoad:(UIWebView *)webView;代理方法中;











你可能感兴趣的:(iOS移动开发)