美文网首页
iOS UIWebView 添加cookie

iOS UIWebView 添加cookie

作者: 梦想不是遥不可及的 | 来源:发表于2022-03-29 15:13 被阅读0次

    - (void)viewDidLoad {

        [super viewDidLoad];

        // 清楚cookie

        [self deleteCookie];

        // 添加cookie

        [self saveCookies];

    //    // 加载webView

    //    [self refreshAction:nil];

    }

    /** 刷新 */

    - (IBAction)refreshAction:(id)sender

    {

        [[NSURLCache sharedURLCache] removeAllCachedResponses];

        if(self.webView) {

            self.webView.delegate=nil;

            self.webView=nil;

        }

        self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];

        self.webView.delegate=self;

        [self.viewaddSubview:self.webView];

        NSString *urlstr = [[[ProjectManager simpleManager] userModel] product_url];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstr]];

        [requestsetTimeoutInterval:10];

        [self.webViewloadRequest:request];

    }

    // 存储cookie

    - (void)saveCookies {

        NSString *cookiestr = [[[ProjectManager simpleManager] userModel] cookie];

        NSString *urlstr = [[[ProjectManager simpleManager] userModel] product_url];

        NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

        [cookiePropertiessetObject:@"userid"forKey:NSHTTPCookieName];

        [cookiePropertiessetObject:cookiestrforKey:NSHTTPCookieValue];

        [cookiePropertiessetObject:urlstrforKey:NSHTTPCookieOriginURL];

        [cookiePropertiessetObject:@"/"forKey:NSHTTPCookiePath];

        [cookiePropertiessetObject:@"0"forKey:NSHTTPCookieVersion];

        // 将可变字典转化为cookie

        NSHTTPCookie*cookie = [NSHTTPCookiecookieWithProperties:cookieProperties];

        // 获取cookieStorage

        NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

        // 存储cookie

        [cookieStoragesetCookie:cookie];

    }

    //清除cookie

    - (void)deleteCookie{

        NSHTTPCookie*cookie;

        NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

        NSArray*cookieAry = [cookieJarcookies];

        for(cookieincookieAry) {

            [cookieJardeleteCookie: cookie];

        }

    }

    作者:大漠赏花

    链接:https://www.jianshu.com/p/00027818c308

    来源:简书

    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    相关文章

      网友评论

          本文标题:iOS UIWebView 添加cookie

          本文链接:https://www.haomeiwen.com/subject/gznvjrtx.html