1.在WKWebView重定向处理:
在decidePolicyForNavigationAction 代理方法中添加
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *quest = [NSMutableURLRequest requestWithURL:url];
quest.HTTPMethod = @"GET";
NSURLConnection *connect = [NSURLConnection connectionWithRequest:quest delegate:self];
[connect start];
并在NSURLConnectionDataDelegate的代理方法
- (nullable NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)response
{
NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
NSLog(@"statusCode: %ld", urlResponse.statusCode);
NSDictionary *headers = urlResponse.allHeaderFields;
NSLog(@"%@", headers);
NSLog(@"redirect url: %@", headers[@"Location"]); // 重定向的地址
NSLog(@"newRequest url: %@", [request URL]); // 重定向的地址或原地址
NSLog(@"redirect response url: %@", [urlResponse URL]);// 触发重定向请求的地址,
if ([request URL] != nil && headers[@"Location"] != nil)
{
NSLog(@"重定向处理");
[self.wkWebView loadRequest:[NSURLRequest requestWithURL:[request URL]]];
self.shareUrl = [request URL].absoluteString;
}
else
{
NSLog(@"无重定向处理");
}
return request;
}
2.UIWebView 重定向处理
在 shouldStartLoadWithRequest中加入
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (connectionError || ([response respondsToSelector:@selector(statusCode)] && [((NSHTTPURLResponse *)response) statusCode] != 200 && [((NSHTTPURLResponse *)response) statusCode] != 302)) { NSLog(@"xy-statusCode = %zd", [(NSHTTPURLResponse *)response statusCode]); }else {// 重定向的URL NSString *url =response.URL.absoluteString;// [webView loadRequest:[NSURLRequest requestWithURL:kURLString(response.URL.absoluteString)]]; NSLog(@"xy-重定向statusCode = %zd", [(NSHTTPURLResponse *)response statusCode]); self.shareUrl =url; } NSLog(@"xy---------------------------------------------------------"); }];