美文网首页
iOS webView加载cookie的简单使用

iOS webView加载cookie的简单使用

作者: FredYJH | 来源:发表于2016-08-13 16:48 被阅读256次

    第一次使用markdown,网上看了一些介绍都是不同不痒的,我自己灵机一动,用sublime 为我的代码块加了一个Tab.然后粘贴到这里。里面的代码可以直接复制到你的ViewController.m里面测试。记得添加myWebview和Activity。

    //
    //  ViewController.m
    //  CookieTest
    //
    //  Created by yiLian on 16/8/13.
    //  Copyright © 2016年 yiLian. All rights reserved.
    //  这个程序规定:用户登录的时候,服务器传回一个cookie值,下次用户再登录时,只要获取到cookie就不用重新登录。
    
    #import "ViewController.h"
    
    @interface ViewController ()<UIWebViewDelegate>
    @property (weak, nonatomic) IBOutlet UIWebView               *myWebview;
    //@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *Activity;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self loadExamplePage];
        //self.Activity.hidesWhenStopped = YES;
    }
    #pragma mark - 加载数据
    - (void)loadExamplePage {
        NSURL *URL              = [NSURL URLWithString:@"http://www.baidu.com"];
        NSURLRequest *request   = [NSURLRequest requestWithURL:URL];
        self.myWebview.delegate = self;
        [self.myWebview loadRequest:request];
    }
    #pragma mark ---webViewDelegate
    - (void)webViewDidStartLoad:(UIWebView *)webView{
        [self setCookie];
       // [self.Activity startAnimating];
    }
    - (void)webViewDidFinishLoad:(UIWebView *)webView
    {
        NSData *cookiesData    = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
        //存储归档后的cookie
        [[NSUserDefaults standardUserDefaults] setObject: cookiesData forKey: @"cookie"];
        
       // [self.Activity stopAnimating];
    }
    - (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
    {
       // [self.Activity stopAnimating];
    }
    #pragma mark - 保持cookie
    - (void)setCookie{
        //取出保存的cookie
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        //对取出的cookie进行反归档处理
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:[userDefaults objectForKey:@"cookie"]];
        if (cookies) {
            NSLog(@"有cookie");
            //设置cookie
            NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
            for (NSHTTPCookie *cookie in cookies) {
                [cookieStorage setCookie:cookie];
                if ([cookie.name isEqualToString:@"ylusername"]) { // 这里服务端规定cookie的名称。
                    [[NSUserDefaults standardUserDefaults] setObject: cookie.value forKey: @"userID"];
                }
            }
        }else{
            NSLog(@"无cookie");
        }
    }
    @end

    相关文章

      网友评论

          本文标题:iOS webView加载cookie的简单使用

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