0
votes

I have four tab controllers, one of them has a UIWebView in the view controller. I created a new thread to load web content in my webView when the app started, so when the web is finished load, it is ready for users to view when they tab to the view controller.

My problem is, the webVIew does not load request in the new created thread at all, but it is working when I put loadRequest in viewDidLoad. I spend one solid day to find the solution but no luck at all.

This is my code:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
     if (self)
        [NSThread detachNewThreadSelector:@selector(doStuff) toTarget:self withObject:nil];

     return self;
}

- (void)doStuff
{
     NSLog(@"Starting a new thread ...");

     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
     url = [NSURL URLWithString:@"http://www.myURL.com"];
     NSURLRequest *request = [NSURLRequest requestWithURL:url];
     [newsWebView loadRequest:request];

     [pool release];
 }

Can someone solve my problem? Thank you very much.

3
I imagine you have several issues here. You need to understand threading if you're going to attempt this.Jason McCreary
UIKit objects are not threadsafe, and this is the perfect example of that.CodaFi
So, is there any way to achieve my objective? Another issue is, my viewController is in blank white screen when I run loadView in main thread before the viewDidLoad function and [super viewDidLoad];felixwcf

3 Answers

2
votes
 - (void)doStuff
 {
 NSLog(@"Starting a new thread ...");

 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 url = [NSURL URLWithString:@"http://www.myURL.com"];
 NSURLRequest *request = [NSURLRequest requestWithURL:url];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [newsWebView loadRequest:request];
 });
[pool release];
}
1
votes

UIWebView is part of UIKit, so you should operate on the main thread.

- (void)doStuff
{
     NSLog(@"Starting a new thread ...");

     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
     url = [NSURL URLWithString:@"http://www.myURL.com"];
     NSURLRequest *request = [NSURLRequest requestWithURL:url];
     dispatch_async(dispatch_get_main_queue(), ^(void){
         [newsWebView loadRequest:request];
     });
     [pool release];
 }
-1
votes

Try this

func loadPdfFromDocumentDirectory(localPathUrl: URL)
{
    let urlRequest = URLRequest(url: localPathUrl)
    DispatchQueue.main.async {
        self.webView?.loadRequest(urlRequest)
    }
}