CNWebRedirectHandle.m 4.85 KB
//
//  CNWebRedirectHandle.m
//  CNLiveNetAdd
//
//  Created by cnliveJunBo on 2019/1/3.
//  Copyright © 2019年 cnlive. All rights reserved.
//

#import "CNWebRedirectHandle.h"

@interface CNWebRedirectHandle ()<NSURLSessionTaskDelegate>

@property (nonatomic, copy)   NSString *loadUrlStr;
@property (nonatomic, assign) BOOL isRedirect;
@property (nonatomic, copy)   NSString *oldUrlStr;
@property (nonatomic, copy)   NSString *redirectUrlStr;

@end

@implementation CNWebRedirectHandle

+ (CNWebRedirectHandle *)manager
{
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)webRedirectHandleWithUrlStr:(NSString *)urlStr {
    
    urlStr = [urlStr stringByURLDecode];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self jb_webRedirectHandleWithUrlStr:urlStr];
}

- (void)turnToCategorySubWebVCWithUrl:(NSString *)urlStr {
    NSDictionary *dic = @{
        @"urlStr":urlStr
    };
    [CNLiveClassifyJumpBridge showViewOrPushVCWithCurrentVC:NULL pushType:CNLiveClassifyJumpTypeDarenWebVC pageType:0 param:dic];
    // 二级页
}

- (void)jb_webRedirectHandleWithUrlStr:(NSString *)urlStr {
    [QMUITips showLoadingInView:AppKeyWindow];
    self.loadUrlStr = urlStr?urlStr:@"";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *quest = [NSMutableURLRequest requestWithURL:url];
    quest.HTTPMethod = @"GET";
    
    weakself
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue currentQueue]];
    NSURLSessionDataTask *task = [urlSession dataTaskWithRequest:quest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                                  {
                                      [QMUITips hideAllTipsInView:AppKeyWindow];
                                      if (error) {
                                          if (error.code == -1009) {
                                              [QMUITips showError:@"似乎已断开与互联网的连接。" inView:AppKeyWindow hideAfterDelay:1.5];
                                          }
                                          weakSelf.isRedirect = NO;
                                          weakSelf.oldUrlStr = nil;
                                          weakSelf.redirectUrlStr = nil;
                                          return ;
                                      }
                                      
                                      NSString *loadUrlStr = weakSelf.loadUrlStr;
                                      if (weakSelf.isRedirect) {
                                          loadUrlStr = weakSelf.redirectUrlStr;
                                          [CNLiveClassifyJumpBridge checkWithFunctionForShareURL:loadUrlStr];
                                      } else {
                                          // 没有重定向
                                          [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveScanQRCodeScanErrorNotification object:nil];
                                          [QMUITips showWithText:@"链接地址错误" inView:AppKeyWindow hideAfterDelay:1.5f];
                                      }
                                      weakSelf.isRedirect = NO;
                                      weakSelf.oldUrlStr = nil;
                                      weakSelf.redirectUrlStr = nil;
                                  }];
    [task resume];
    
}

#pragma mark - NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * __nullable))completionHandler
{
    NSLog(@"statusCode: %ld", response.statusCode);
    
    NSDictionary *headers = response.allHeaderFields;
    NSLog(@"%@", headers);
    if (response.statusCode==302 || response.statusCode==301) {
        self.isRedirect = YES;
        self.oldUrlStr = [[response URL] absoluteString];
        self.redirectUrlStr = headers[@"Location"];
        NSLog(@"======>>>>>>111111:%@",headers[@"Location"]);
    }
    NSLog(@"redirect   url: %@", headers[@"Location"]); // 重定向的地址,如:http://www.jd.com
    NSLog(@"newRequest url: %@", [request URL]);        // 重定向的地址,如:http://www.jd.com
    NSLog(@"redirect response url: %@", [response URL]);// 触发重定向请求的地址,如:http://www.360buy.com
    
    completionHandler(request);
    //    completionHandler(nil);// 参数为nil,表示拦截(禁止)重定向
}

@end