平时生活和工作中的iOSiOS记录篇iOS网络篇

UIWebView实现自动登陆

2015-04-13  本文已影响5016人  ZhongXi

IOS中UIWebView不会自动存储、读取Cookie.
要实现UIWebView的自动登陆,需要手动存储、读取Cookie.
1.Appelegate.m中加入以下代码

- (void)applicationDidBecomeActive:(UIApplication *)application 
{    
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
    //存储Cookie,示例加载的URL:http://119.29.69.58:81/index
    NSURL * cookieHost = [NSURL URLWithString:@"http://119.29.69.58:81"];
    NSHTTPCookie * cookie = [NSHTTPCookie cookieWithProperties:
    [NSDictionary    dictionaryWithObjectsAndKeys:
    [cookieHost host],NSHTTPCookieDomain,
    [cookieHost path],NSHTTPCookiePath,
    @"COOKIE_NAME",NSHTTPCookieName,
    @"COOKIE_VALUE",NSHTTPCookieValue,nil]];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}

2.UIWebView加载URL时设置Header

NSURL * url = [NSURL URLWithString:@"http://119.29.69.58:81/index"];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSArray * cookies = [[NSHTTPCookieStorage  sharedHTTPCookieStorage] cookies];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[request setHTTPMethod:@"POST"];
[request setHTTPShouldHandleCookies:YES];
[request setAllHTTPHeaderFields:headers];
[self.WebView loadRequest:request];

3.退出登陆时删除Cookie

//清空Cookie
NSHTTPCookieStorage * myCookie = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie * cookie in [myCookie cookies])
{
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}

//删除沙盒自动生成的Cookies.binarycookies文件       
NSString * path = NSHomeDirectory();
NSString * filePath = [path stringByAppendingPathComponent:@"/Library/Cookies/Cookies.binarycookies"];
NSFileManager * manager = [NSFileManager defaultManager];
[manager removeItemAtPath:filePath error:nil];
上一篇下一篇

猜你喜欢

热点阅读