WKWebView cookie同步问题:
利用runtime 在loadRequest时,先同步一下cookie就可以了!
以下是代码:
.h
#import
NS_ASSUME_NONNULL_BEGIN
@interface WKWebView (SafeUrl)
+ (void)changeMethodOriginalSelector:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector;
- (NSURL *)xxx_URL;
- (nullable WKNavigation *)xxx_loadRequest:(NSURLRequest *)request;
@end
NS_ASSUME_NONNULL_END
.m
#import "WKWebView+SafeUrl.h"
@implementation WKWebView (SafeUrl)
+(void)load{
NSString*className=NSStringFromClass(self.class);
NSLog(@"classname%@",className);
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
SELoriginalSelector=@selector(URL);
SELswizzledSelector=@selector(xxx_URL);
[self changeMethodOriginalSelector:originalSelector swizzledSelector:swizzledSelector];
SELoriginalSelector1=@selector(loadRequest:);
SELswizzledSelector1=@selector(xxx_loadRequest:);
[selfchangeMethodOriginalSelector:originalSelector1swizzledSelector:swizzledSelector1];
});
}
+ (void)changeMethodOriginalSelector:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector{
Classclass= [selfclass];
MethodoriginalMethod=class_getInstanceMethod(class,originalSelector);
MethodswizzledMethod=class_getInstanceMethod(class,swizzledSelector);
BOOLdidAddMethod=
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if(didAddMethod){
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod,swizzledMethod);
}
}
- (NSURL *)xxx_URL{
NSThread *thread = [NSThread currentThread];
if(thread.isMainThread) {
return [self xxx_URL];
}else{
dispatch_semaphore_t signal = dispatch_semaphore_create(1);
__blockNSURL*URL;
dispatch_async(dispatch_get_main_queue(), ^{
URL = [selfxxx_URL];
dispatch_semaphore_signal(signal);
});
dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
returnURL;
}
}
- (nullable WKNavigation *)xxx_loadRequest:(NSURLRequest *)request{
NSMutableURLRequest *muRequest = nil;
if ([request isKindOfClass:[NSMutableURLRequest class]]) {
muRequest = (NSMutableURLRequest*)request;
}else{
muRequest = [requestmutableCopy];
}
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
NSDictionary *dict = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
muRequest.allHTTPHeaderFields= dict;
return [self xxx_loadRequest:muRequest];
}
网友评论