0

I am trying to make a separate http call inside startLoading() before submitting the original request. Code is like below :

+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];
}

}

The VERY SAME code works if used in a webView for either normal contents (htm, css, etc.) [case 1] or m3u8/mpg [case 2] (a player will automatically embedded in the webView);

However if used with AVPlayer directly to play the same m3u8 [case 3], the validation call will stuck for ~1 minute (a request timeout if looking into the error ) after the canInitWithRequest() method. And subsequently renders the following request fail.

At first I thought it was thread issue. But line 1 and line 2 gave different threads.

I suspect AVPlayer used some mechanism different than webView to process http request. In [case 2], the webView just overrode AVPlayer probably. But not sure.

Can anybody give more insight?

Thanks!

AVI
  • 5,516
  • 5
  • 29
  • 38
Rao
  • 51
  • 7

1 Answers1

0

You're blocking the main thread, in all likelihood. The startLoading() method needs to return immediately. It should never block for any reason. Kick off your authentication request, then return. Take all of the code after your semaphore wait, and move it into the completion handler.

dgatwood
  • 10,129
  • 1
  • 28
  • 49