自定义的NSURLProtocol问题优化

问题

  • 自定义的urlprotocolstoploading 上崩溃

解决方案

  • 修改了canInitWithRequest方法

接近历程

  • 只有有一个NSURLProtocolcanInitWithRequest返回YES,那其他的protocol就不会考虑了

  • canInitWithRequest 不能老是返回YES,会引发很多的额外开销,以下是原文

  • Think again about the URL Loading System and protocol registration, and you might have a notion about why this is happening. When the UIWebView wants to load the URL, the URL Loading System asks MyURLProtocol if it can handle that specific request. Your class says YES, it can handle it.

  • So the URL Loading System will create an instance of your protocol and call startLoading. Your implementation then creates and fires its NSURLConnection. But this also calls the URL Loading System. Guess what? Since you’re always returning YES in the +canInitWithRequest: method, it creates another MyURLProtocol instance.

  • This new instance will lead to a creation of one more, and then one more and then an ifinite number of instances. That’s why you app doesn’t load anything! It just keeps allocating more memory, and shows only one URL in the console. The poor browser is stuck in an infinite loop! Your users could be frustrated to the point of inflicting damage on their devices.

  • 另一段原文

  • Review what you’ve done and then move on to how you can fix it. Obviously you can’t just always return YES in the +canInitWithRequest: method. You need to have some sort of control to tell the URL Loading System to handle that request only once. The solution is in the NSURLProtocol interface. Look for the class method called +setProperty:forKey:inRequest: that allows you to add custom properties to a given URL request. This way, you can ‘tag’ it by attaching a property to it, and the browser will know if it’s already seen it before.

疑问

  • 为什么注册失效,在appdelegate里面注册失效
[NSURLProtocol registerClass:[SBLogURLProtocol class]];
       NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSMutableArray *protocols = [NSMutableArray arrayWithArray:[configuration protocolClasses]];
    [protocols insertObject:[SBLogURLProtocol class] atIndex:0];
    configuration.protocolClasses = protocols;

在appdelegate这么写后,我们发现跟视图控制器里面获取configuration,发现里面的protocolClasses还是没有变化。

  • 难道只有在用的时候,临时添加才有效,目前来看是的?
  • 光注册是没用的,还需要再用的时候,将这个类SBLogURLProtocol加进来,这样网络请求的时候才会走

搜索技巧

  • 搜索原文里面的方法,比如
  • defaultSessionConfigurationprotocols
  • canInitWithRequestNSURLProtocol
  • 搜索这些重要的关键词,你能发现很多重要排行很多的文档和问题,很有利于你解决问题

参考文章

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值