0

我正在尝试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](播放器将自动嵌入到 web 视图中);

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

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

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

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

谢谢!

4

1 回答 1

0

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

于 2016-05-08T03:02:21.370 回答