UIWebView实现自动登陆(存储、读取Cookie)

iOS开发 专栏收录该内容
104 篇文章 2 订阅

1.AppDelegate中键入这几句代码

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    NSURL *cookieHost = [NSURLURLWithString:@"http://appweb.cosfund.com"];
    NSDictionary *propertiesDict = [NSDictionarydictionaryWithObjectsAndKeys:[cookieHosthost],NSHTTPCookieDomain,[cookieHostpath],NSHTTPCookiePath,@"COOKIE_NAME",NSHTTPCookieName,@"COOKIE_VALUE",NSHTTPCookieValue,nil];
    NSHTTPCookie *cookie = [NSHTTPCookiecookieWithProperties:propertiesDict];
    [[NSHTTPCookieStoragesharedHTTPCookieStorage] setCookie:cookie];

    return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    [[NSHTTPCookieStoragesharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
}

2.UIWebView加载的适合设置HTTPHeader

- (void)uiConfig
{
    NSURL *url = [NSURLURLWithString:@"http://appweb.cosfund.com/lcrank/index2.html?phone=15601667246"];
    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    NSDictionary *headers = [NSHTTPCookierequestHeaderFieldsWithCookies:cookies];
    [request setHTTPMethod:@"POST"];
    [request setHTTPShouldHandleCookies:YES];
    [request setAllHTTPHeaderFields:headers];
    [self.webViewloadRequest:request];
}

3.退出登陆时删除Cookie

- (void)LoggedOutBtnClick:(UIButton *)button
{
    //清空Cookie
    NSHTTPCookieStorage *myCookie = [NSHTTPCookieStoragesharedHTTPCookieStorage];
    for (NSHTTPCookie *cookiein [myCookie cookies])
    {
        [[NSHTTPCookieStoragesharedHTTPCookieStorage] deleteCookie:cookie];
    }
    //删除沙盒自动生成的Cookies.binarycookies文件
    NSString *path = NSHomeDirectory();
    NSString *filePath = [pathstringByAppendingPathComponent:@"/Library/Cookies/Cookies.binarycookies"];
    NSFileManager *manager = [NSFileManagerdefaultManager];
    [manager removeItemAtPath:filePath error:nil];
}












展开阅读全文
  • 2
    点赞
  • 0
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值