https://www.jianshu.com/p/14b9ea4bf1d4

https://github.com/Yeatse/NSURLProtocol-WebKitSupport/blob/master

重点在这

- (void)setUrl:(NSURL *)url {

_url = url;

HWWeakSelf(weakSelf)

//    NSURLRequest *request = [NSURLRequest requestWithURL:weakSelf.url];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:weakSelf.url];

#pragma mark - 添加请求头 (例子需要根据自己的需求修改)

NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];//当前时间距离

NSString *key = [NSString stringWithFormat:@"%.0f0001#j0ZAqg",timeInterval];

[request setValue:[HWDataManager getMD5HashWithMessage:key] forHTTPHeaderField:@"key"];

[request setValue:[NSString stringWithFormat:@"%.0f000", timeInterval] forHTTPHeaderField:@"times"];

[_webView loadRequest:request];

}

.h文件

#import <UIKit/UIKit.h>

#import <WebKit/WebKit.h>

#pragma mark - 尺寸相关

#define HWScreenW [UIScreen mainScreen].bounds.size.width

#define HWScreenH [UIScreen mainScreen].bounds.size.height

#define HWWeakSelf(weakSelf)  __weak __typeof(&*self)weakSelf = self;  // 弱引用

#ifdef DEBUG // 开发

#define HWLog(...) NSLog(@"%s %d \n%@\n\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])

#else // 生产

#define HWLog(...) //NSLog(@"%s %d \n%@\n\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])

#endif

@interface HWBaseWebViewController : UIViewController

/** <#注释#> */

@property(nonatomic, strong) NSURL *url;

/** <#注释#> */

@property(nonatomic, strong) WKWebView *webView;

@end

.m文件

#import "HWBaseWebViewController.h"

#define HWAdapterY (HWSystemVersion >= 11?kDevice_Is_iPhoneX?88:64:64)

@interface HWBaseWebViewController ()<WKNavigationDelegate>

/** <#注释#> */

@property(nonatomic, strong) UIView *mainView;

/** <#注释#> */

@property(nonatomic, strong) UIProgressView *progressView;

@end

@implementation HWBaseWebViewController

- (void)viewDidLoad {

[super viewDidLoad];

[self addMainView];

[self creatWebView];

self.view.backgroundColor = [UIColor whiteColor];

}

#pragma mark - 添加进度条

- (void)addMainView {

HWWeakSelf(weakSelf)

UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, HWScreenW, HWScreenH)];

mainView.backgroundColor = [UIColor clearColor];

_mainView = mainView;

[weakSelf.view addSubview:mainView];

UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, [HWTools HWAutoY:self], HWScreenW, 1)];

progressView.progress = 0;

_progressView = progressView;

[weakSelf.view addSubview:progressView];

}

- (void)creatWebView {

HWWeakSelf(weakSelf)

//    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, [HWTools HWAutoY:self], HWScreenW, HWScreenH - [HWTools HWAutoY:self])];

_webView = [[WKWebView alloc] initWithFrame:self.view.bounds];

_webView.backgroundColor = [UIColor whiteColor];

_webView.navigationDelegate = weakSelf;

_webView.scrollView.bounces = NO;

[weakSelf.mainView addSubview:_webView];

// 添加观察者

[_webView addObserver:weakSelf forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL]; // 进度

[_webView addObserver:weakSelf forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL]; // 标题

}

- (void)setUrl:(NSURL *)url {

_url = url;

HWWeakSelf(weakSelf)

//    NSURLRequest *request = [NSURLRequest requestWithURL:weakSelf.url];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:weakSelf.url];

#pragma mark - 添加请求头 (例子需要根据自己的需求修改)

NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];//当前时间距离

NSString *key = [NSString stringWithFormat:@"%.0f0001#j0ZAqg",timeInterval];

[request setValue:[HWDataManager getMD5HashWithMessage:key] forHTTPHeaderField:@"key"];

[request setValue:[NSString stringWithFormat:@"%.0f000", timeInterval] forHTTPHeaderField:@"times"];

[_webView loadRequest:request];

}

// 页面加载失败时调用

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {

}

// 页面加载完毕时调用

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {

}

#pragma mark - 监听加载进度

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

HWWeakSelf(weakSelf)

if ([keyPath isEqualToString:@"estimatedProgress"]) {

if (object == _webView) {

[weakSelf.progressView setAlpha:1.0f];

[weakSelf.progressView setProgress:weakSelf.webView.estimatedProgress animated:YES];

if(weakSelf.webView.estimatedProgress >= 1.0f) {

[UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{

[weakSelf.progressView setAlpha:0.0f];

} completion:^(BOOL finished) {

[weakSelf.progressView setProgress:0.0f animated:NO];

}];

}

} else {

[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

}

}  else if ([keyPath isEqualToString:@"title"]) {

HWLog(@"%@",weakSelf.webView.title);

if (object == weakSelf.webView) {

weakSelf.title = weakSelf.webView.title;

} else {

[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

}

} else {

[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

}

}

// 当对象即将销毁的时候调用

- (void)dealloc {

NSLog(@"webView释放");

//    HWWeakSelf(weakSelf)

[_webView removeObserver:self forKeyPath:@"estimatedProgress"];

[_webView removeObserver:self forKeyPath:@"title"];

_webView.navigationDelegate = nil;

}

#pragma mark - WKNavigationDelegate

#pragma mark - 截取当前加载的URL

//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

//    HWWeakSelf(weakSelf)

//    NSURL *URL = navigationAction.request.URL;

//    HWLog(@"%@", URL);

//    if (![[NSString stringWithFormat:@"%@", weakSelf.url] isEqualToString:[NSString stringWithFormat:@"%@", URL]]) { // 不相等

//        //        weakSelf.navigationView.titleLabel.text = @"攻略详情";

//        HWStrategyDetailsViewController *vc = [[HWStrategyDetailsViewController alloc] init];

//        vc.url = URL;

//        [weakSelf.navigationController pushViewController:vc animated:YES];

//        //        self.button.hidden = NO;

//        //        _webView.height = HWScreenH-64-50;

//        //        self.collectionButton.hidden = NO;

//        //        self.forwardingButton.hidden = NO;

//        decisionHandler(WKNavigationActionPolicyCancel);

//    }else {

//        weakSelf.navigationView.titleLabel.text = weakSelf.title;

//        decisionHandler(WKNavigationActionPolicyAllow); // 必须实现 不然会崩溃

//    }

//}

@end

WKWebView单个界面添加请求头的更多相关文章

  1. iOS UIWebview添加请求头的两种方式

    1.在UIWebviewDelegate的方法中拦截request,设置request的请求头,废话不多说看代码: - (BOOL)webView:(UIWebView *)webView shoul ...

  2. urllib2 post请求方式,带cookie,添加请求头

    #encoding = utf-8 import urllib2import urllib url = 'http://httpbin.org/post'data={"name": ...

  3. springcloud- FeginClient 调用统一拦截添加请求头 RequestInterceptor ,被调用服务获取请求头

    使用场景: 在springcloud中通过Fegin调用远端RestApi的时候,经常需要传递一些参数信息到被调用服务中去,比如从A服务调用B服务的时候, 需要将当前用户信息传递到B调用的服务中去,我 ...

  4. LoadRunner11脚本小技能之添加请求头+定义变量+响应内容乱码转换打印+事务拆分

    一.添加请求头 存在一些接口,发送请求时需要进行权限验证.登录验证(不加请求头时运行脚本,接口可能会报401等等),所以需要在脚本中给对应请求添加请求头.注意:请求头需在请求前添加,包含url类.su ...

  5. Retrofit2 动态(静态)添加请求头Header

    Retrofit提供了两个两种定义HTTP请求头字段的方法即静态和动态.静态头不能改变为不同的请求,头的键和值是固定的且不可改变的,随着程序的打开便已固定. 动态添加 @GET("/&quo ...

  6. python爬虫添加请求头和请求主体

    添加头部信息有两种方法 1.通过添加urllib.request.Request中的headers参数 #先把要用到的信息放到一个字典中 headers = {} headers['User-Agen ...

  7. 给requests模块添加请求头列表和代理ip列表

    Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,符合了Python语言的思想,通俗的说去繁存 ...

  8. ajax添加请求头(添加Authorization字段)

    我们在发AJAX请求的时候可能会需要自定义请求头,在jQuery的$.ajax()方法中提供了beforeSend属性方便我们进行此操作. beforeSend: function(request) ...

  9. 给HttpClient添加请求头(HttpClientFactory)

    前言 在微服务的大环境下,会出现这个服务调用这个接口,那个接口的情况.假设出了问题,需要排查的时候,我们要怎么关联不同服务之间的调用情况呢?换句话就是说,这个请求的结果不对,看看是那里出了问题. 最简 ...

随机推荐

  1. 网页链接在QQ内因多人投诉被拦截的解决方案

    背景 相信大家经常会遇到一个头疼的问题就是,明明自己的网页没有违规内容(比如线下活动的推广),但链接在QQ内转发分享会被QQ管家拦截,导致用户无法访问. 那么当大家遇到这个问题的时候应该怎么办呢?不用 ...

  2. js获取用户当前地理位置(省、市、经纬度)

    在很多情况下,我们需要用到定位功能,来获取用户当前位置.当前比较流行的定位API有腾讯地图.百度地图.高德地图.搜狗地图等等,在这里我使用的是腾讯地图定位API,根据用户IP获取用户当前位置,API返 ...

  3. Go常量

    1. 常量 package main import "fmt" func main() { /* 常量: 1.概念:同变量类似,程序执行过程中数值不能改变 2.语法: 显式类型定义 ...

  4. vim配置之——ctags与TagList的配置以及NERDTree && doxygentoolkit的安装

    参考(2)vim插件:显示树形目录插件NERDTree安装 和 使用 本文档主要对Linux下vim的ctags,TagList,NerdTree与doxgentoolkit进行相关的配置. 以下部分 ...

  5. 获取目标字符串在字符串中第N次出现的位置

    /** * 获取目标字符串在字符串中第N次出现的位置 * @file name * @author xiehongwei * @date 2017-8-2 下午3:29:09 * @param sou ...

  6. 流式计算(三)-Flink Stream 篇一

    原创文章,谢绝任何形式转载,否则追究法律责任! ​流的世界,有点乱,群雄逐鹿,流实在太多,看完这个马上又冒出一个,也不知哪个才是真正的牛,据说Flink是位重量级选手,能流计算,还能批处理, 和其他伙 ...

  7. itest(爱测试) 4.3.0 发布,开源BUG 跟踪管理 & 敏捷测试管理软件

    itest 简介:查看简介 test 开源敏捷测试管理,testOps 践行者.可按测试包分配测试用例执行,也可建测试迭代(含任务,测试包,BUG)来组织测试工作,也有测试环境管理,还有很常用的测试度 ...

  8. Django框架之ORM的相关操作(一)

    一.一般操作 from django.db import models import datetime # Create your models here. class Author(models.M ...

  9. acm数论之旅--欧拉函数的证明

    随笔 - 20  文章 - 0  评论 - 73 ACM数论之旅7---欧拉函数的证明及代码实现(我会证明都是骗人的╮( ̄▽ ̄)╭) https://blog.csdn.net/chen_ze_hua ...

  10. android实现扫一扫等功能

    链接:https://blog.csdn.net/weixin_40399313/article/details/78814325