Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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
You can’t perform that action at this time.