iOS webViewロードクッキーの簡単な使用
2435 ワード
初めて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 ()
@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