1. Background
The author mentioned in the article 《WKWebView》 that WKWebView performs network requests in a process independent of the app process, and the requested data does not pass through the main process. Therefore, using NSURLProtocol directly on WKWebView cannot intercept the request. Therefore, if you need to intercept requests, a feasible solution is to use the private API exposed by Apple's open source Webkit2 source code (see section 3 of the original article for details: NSURLProtocol issue).
However, using private API will inevitably bring about the following problems:
- Audit risk
- When intercepting http/https, the post request body is lost
- If ajax hook is used, there may be post header character length limit, Put type request exception, etc.
From this point of view, before the arrival of iOS11 WKURLSchemeHandler [Explore], the private API was not so perfect.
Fortunately, through searching, we found that the iOS system has the ability to build a server, and it is theoretically possible to implement WKWebView offline resource loading.
2. Analysis
Local web server based on iOS currently has the following relatively complete frameworks:
- CocoaHttpServer (Supports iOS, macOS and various network scenarios)
- GCDWebServer (based on iOS, does not support https and webSocket)
- Telegraph (Swift implementation, more complete functions than the above two categories)
Because most APPs currently support ATS, and most domestic project codes are still implemented using OC, this article will conduct experiments based on CocoaHttpSever.
Telegraph was born to supplement the shortcomings of CocoaHttpSever and GCDWebServer. For pure Swift projects, it is recommended to use Telegraph.