Skip to content

Instantly share code, notes, and snippets.

@mikehouse
Last active October 7, 2019 10:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mikehouse/562b10865bd89dfb1122cb3031fe8748 to your computer and use it in GitHub Desktop.
// Run (https://github.com/wilddylan/WKWebViewWithURLProtocol)
// Be aware it is a private API, it is wisely handled and shouldn't be a prloblem at Apple's code review
[NSURLProtocol wk_registerScheme:@"http"];
// URLProtocol.h
#import <Foundation/Foundation.h>
@interface URLProtocol : NSURLProtocol
- (instancetype)initWithRequest:(NSURLRequest *)request
cachedResponse:(NSCachedURLResponse *)cachedResponse
client:(id<NSURLProtocolClient>)client;
@end
// URLProtocol.m
@implementation URLProtocol
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
// It is AJAX request, that you cannot be tracked in WKWebView delegate, the only way is to track it here.
return ... // [request.URL.absoluteString hasPrefix:"http://"];
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
return request;
}
- (instancetype)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id <NSURLProtocolClient>)client {
self = [super initWithRequest:request cachedResponse:cachedResponse client:client];
if (self) {
}
return self;
}
- (void)startLoading {
NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.request.URL statusCode:200 HTTPVersion:nil headerFields:@{
@"Access-Control-Allow-Origin": @"*",
@"Access-Control-Allow-Headers": @"Origin, X-Requested-With, Content-Type, Accept",
@"Access-Control-Allow-Methods": @"GET, POST, OPTIONS",
@"Content-Type": @"text/plain; charset=utf-8"
}];
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowedInMemoryOnly];
[self.client URLProtocol:self didLoadData:data];
[self.client URLProtocolDidFinishLoading:self];
}
- (void)stopLoading {
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment