Search code examples
objective-cuiwebviewxamarin.ios

How to use this Objective-C code in monotouch


I need to use more than one UIWebView in a view controller, but after a few minutes launching the app it crashes because of LoadRequest.

I found this code block here for UIWebViewDelegate but I could not successfully convert it to C#.

-(void)spinlockedWebViewLoad:(NSArray*)arr {
  NSAutoreleasePool* pool=[[NSAutoreleasePool alloc] init];
  UIWebView* webView=(UIWebView*)[arr objectAtIndex:0];
  NSURLRequest* request=(NSURLRequest*)[arr objectAtIndex:1];
  @synchronized(self) {
  spinlock=webView;
  [webView loadRequest:request];
  while (spinlock==webView) [NSThread sleepForTimeInterval:0.1];
  }
  [pool drain];
 }

-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
  if (spinlock!=webView) {
     [NSThread detachNewThreadSelector:@selector(spinlockedWebViewLoad:) toTarget:self withObject:[NSArray arrayWithObjects:webView,request,nil]];
     return NO;
  }
  return YES;
}

Solution

  • In your code there is no need to use an (ObjectiveC-style) delegate, just use managed events:

    void SpinlockedWebViewLoad (NSObject [] arr)
    {
        ...
        UIWebView webView  = (UIWebView) arr [0];
        webView.ShouldStartLoad += ShouldStartLoad;
        ...
    }
    
    bool ShouldStartLoad (UIWebView webView, NSUrlRequest FileWebRequest, UIWebViewNavigationType navigationType)
    {
        ...
    }