在NSURLProtocol中单独调用startLoading内部的调用

时间:2015-12-10 16:11:22

标签: ios nsurlprotocol

我想在提交原始请求之前在startLoading()内进行单独的http调用。代码如下:

+canInitWithRequest(){
   if(self.request.valueForKey("handledKey") != nil){
      return false;
   }
   return true;
}

-startLoading(){

   __block NSString * realURLString = self.request.URL.absoluteString;

   //send separate http call for validation

   NSMutableURLRequest validationRequest = [NSMutableURLRequest initWithURL:[URL initWithString:OUR_VALIDATION_SERVER_URL]];

   {code to fill info into validationRequest, etc.}   

   semaphore = dispatch_semaphore_create(0); // need to sync to make sure we use the expected/real url
   [NSURLProtocol setValue:YES forkey:"handledKey" inRequest: validationRequest];
   [NSURLSession sendAsyncRequest:validationRequest ...completionHandler(response, data, error){
            realURLString = xxxx;
            print(current thread info);// line 1
       dispatch_semaphore_signal(sema);
   }];
   print(current thread info);// line 2
   dispatch_semaphore_wait(sema);

  //continue original request with real url
  NSMutableURLRequest realRequest = NSMutableURLRequest(realURLString);
  [NSURLProtocol setValue:YES forkey:"handledKey" inRequest: realRequest];
  self.connection = [NSURLSession withRequst:realRequest delegate:self];
}

}

如果在webView中使用正常内容(htm, css, etc,则非常相同的代码。{案例1]或m3u8/mpg [案例2](播放器将自动嵌入到webView中); < / p>

但是,如果直接与AVPlayer一起使用来播放相同的m3u8 [案例3],则在canInitWithRequest()方法之后,验证调用将停留约1分钟(如果查看错误,请求超时) 。然后呈现以下请求失败。

起初我以为是线程问题。但是第1行和第2行给出了不同的线程。

我怀疑AVPlayer使用了一些与webView不同的机制来处理http请求。在[案例2]中,webView可能只是覆盖了AVPlayer。但不确定。

有人可以提供更多见解吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

你很有可能阻止主线程。 startLoading()方法需要立即返回。它绝不应该因任何原因而阻止。启动您的身份验证请求,然后返回。在您的信号量等待之后获取所有代码,并将其移动到完成处理程序中。