美文网首页
NSURLProtocol协议拦截url

NSURLProtocol协议拦截url

作者: FlowYourHeart | 来源:发表于2019-05-20 17:48 被阅读0次

在开发中可能会有这样的需求,拦截一个url,然后用来进行其他操作。情景:封装了一个webView的VC,VC的代码不能动,现在想要在web的交互中跳出VC,实现原生操作。

其实之前一直没有用过,第一次也是在网上查资料的,所有简单记录一下。
因为我用的VC是封装了的,所以我把protocol注册放在了application:didFinishLaunching...中

DDURLProtocol是自定义 继承NSURLProtocol的协议

//设置拦截webview url协议
    [NSURLProtocol registerClass:[DDURLProtocol class]];

DDURLProtocol.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface DDURLProtocol : NSURLProtocol

@end

NS_ASSUME_NONNULL_END

DDURLProtocol.m


#import "DDURLProtocol.h"

@interface DDURLProtocol()

/*实名认证 被拦截的url中包含 会员编号和登录流水号,用于实名认证,因为从注册跳到实名认证需要在这里获取信息*/
@property (nonatomic, strong) NSMutableDictionary *userInfoForLoginDIc;
@end
@implementation DDURLProtocol


+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    /*防止无限循环,因为一个请求在被拦截处理过程中,也会发起一个请求,这样又会走到这里,如果不进行处理,就会造成无限循环
      */
    if ([NSURLProtocol propertyForKey:kProtocolKey inRequest:request]) {
        return NO;
     }
    BOOL shouldAccept;
    NSURL *url;
    shouldAccept = (request != nil);
    if (shouldAccept) {
        url = [request URL];
        shouldAccept = (url != nil);
        NSString *absoluteStr = url.absoluteString;
      //判断拿到的url是不是想要的
        if ([absoluteStr containsString:@"判断条件"]){
            NSURLComponents *urlCompts = [[NSURLComponents alloc] initWithString:absoluteStr];
            NSArray *queryItems = urlCompts.queryItems;
            NSMutableDictionary *parm = [[NSMutableDictionary alloc]init];
           // ............. 拿到url后的处理 ...............
            return YES;
        }
    }
    return NO;
    
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    return request;
}

- (void)startLoading {
    /*防止无限循环:改变property @YES 没有这一句 上面的那一句就是无效的
       */
    [NSURLProtocol setProperty:@YES forKey:kProtocolKey inRequest:[self request]];
    //发送拦截成功通知 或 其他操作
  
    return;
}

- (void)stopLoading {
    
}



@end

相关文章

网友评论

      本文标题:NSURLProtocol协议拦截url

      本文链接:https://www.haomeiwen.com/subject/jwclzqtx.html