WKWebView ignores NSURLRequest body

https://forums.developer.apple.com/thread/18952


Hello,

 

I'm trying to migrate my code to WKWebView, and I have the following case:

  1. NSAssert(parameters.length > 0); // just to be sure  
  2.   
  3. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];  
  4. request.HTTPMethod = @"POST";  
  5. [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  
  6. [request setHTTPBody:[parameters dataUsingEncoding:NSUTF8StringEncoding]];  
  7.   
  8. [self.webView loadRequest:request];  

 

It works fine with UIWebView, but for WKWebView it sends a POST request with empty body.

 

I tried to add a policy decision handler for a WKWebView:

  1. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler  
  2. {  
  3.     NSURLRequest *request = navigationAction.request;  
  4.   
  5.     // request.HTTPBody is nil here  
  6.   
  7.     if ([request.HTTPMethod isEqualToString:@"POST"] && request.HTTPBody == nil && [request isKindOfClass:[NSMutableURLRequest class]])  
  8.     {  
  9.         // and even overwriting the body doesn't make it sent to server  
  10.         [(NSMutableURLRequest*)request setHTTPBody:[parameters dataUsingEncoding:NSUTF8StringEncoding]];  
  11.     }  
  12.   
  13.     decisionHandler(WKNavigationActionPolicyAllow);  
  14. }  

 

WKWebView is created with a default configuration. Tested in both 9.0 and 8.4 simulators, and 9.0 device.

Any suggestions? Is there some policy that prevents a WKWebView being initialized with a POST request, or is it a bug that survived since iOS 8?

 

I understand there's hardly a lot of people who need to initialize a web view with POST requests, but still?..

Thanks,

Alex.


It’s likely that this worked with UIWebView as an accident of the implementation.  WKWebView, OTOH, does all of its networking out of process, so such accidents are rare (everything that traverses the inter-process gap has to be explicitly coded to do so).

Having said that, the documentation doesn’t specifically state that web views must be initialised with a GET, so you’re not doing anything wrong here.

I recommend you create a small test app and attach it to a bug.  Please post your bug number, just for the record.

As to a workaround, can you run the POST request yourself (using NSURLSession, say) and then initialise the web view with the response?  Or run the POST request from within the web view using JavaScript?

Share and Enjoy 
— 
Quinn "The Eskimo!" 
Apple Developer Relations, Developer Technical Support, Core OS/Hardware 
let myEmail = "eskimo" + "1" + "@apple.com"




你可能感兴趣的:(WKWebView ignores NSURLRequest body)