简体   繁体   中英

GCD ERROR :Tried to obtain the web lock from a thread other than the main thread or the web thread

My code:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *prePath = [[spineArray objectAtIndex:spineIndex - 1] spinePath];
        NSURL *preURL = [NSURL fileURLWithPath:prePath];
        UIWebView *tmpWebView = [self createWebView:preURL];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.preWebView = tmpWebView;
        });

});

- (UIWebView *)createWebView:(NSURL *)url
{
UIWebView *tmpWebView = [[[UIWebView alloc] initWithFrame:CGRectMake(0, 0,kRootViewWidth, kRootViewHeight)] autorelease];
tmpWebView.delegate = self;
[tmpWebView setBackgroundColor:[UIColor whiteColor]];


currentTextSize = 100;

UISwipeGestureRecognizer *rightSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gotoNextPage)];
[rightSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionLeft];

UISwipeGestureRecognizer *leftSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gotoPrevPage)];
[leftSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionRight];

[tmpWebView addGestureRecognizer:rightSwipeRecognizer];
[tmpWebView addGestureRecognizer:leftSwipeRecognizer];

[rightSwipeRecognizer release];
[leftSwipeRecognizer release];

[tmpWebView loadRequest:[NSURLRequest requestWithURL:url]];
return tmpWebView;

}

When we run it, the prompt error is:

Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...

Your error tells you exactly what your problem is This may be a result of calling to UIKit from a secondary thread. In your createWebView method you make calls to UIKit. This isn't allowed when you aren't running on the main thread and in this code example you call that method from another thread.

Why not move the call to that method into the dispatch that is on the main thread?

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSString *prePath = [[spineArray objectAtIndex:spineIndex - 1] spinePath];
    NSURL *preURL = [NSURL fileURLWithPath:prePath];
    dispatch_async(dispatch_get_main_queue(), ^{
        UIWebView *tmpWebView = [self createWebView:preURL];
        self.preWebView = tmpWebView;
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM