UIWebView stringByEvaluatingJavaScriptFromString在后台 [英] UIWebView stringByEvaluatingJavaScriptFromString in background

查看:221
本文介绍了UIWebView stringByEvaluatingJavaScriptFromString在后台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iOS应用中,我使用 stringByEvaluatingJavaScriptFromString UIWebView 上运行一个相当大的脚本(大javascript字符串长度的术语)。调用javascript导致屏幕上的其他元素暂时打嗝后暂停一段时间。

In an iOS app, I'm running a fairly large script on a UIWebView using stringByEvaluatingJavaScriptFromString (large in terms of the length of the javascript string). There is a brief pause after calling the javascript causing other elements on the screen to hiccup for a moment.

将javascript调用放在后台调用的函数中 self performSelectorInBackground 打破了应用程序。是否有一种安全的方法可以在后台线程上调用run或者阻止接口暂停?

Placing the javascript call in a function called in the background with self performSelectorInBackground breaks the application. Is there a safe way to call run this on a background thread or otherwise prevent the interface from pausing?

推荐答案

好吧,我是做同样的事情。我不得不运行同步ajax请求,这会冻结我的UI。所以这就是我修复它的方法:

Well, I was doing the same thing. I had to run a synchronous ajax request which was freezing my UI. So this is how I fixed it :

__block NSString *message;
    dispatch_queue_t q = dispatch_queue_create("sign up Q", NULL);
    dispatch_async(q, ^{
        NSString *function = [[NSString alloc] initWithFormat: @"signup(\'%@\',\'%@\',\'%@\')",self.email.text,self.password.text,self.name.text];

        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:function];
            NSLog(@"%@",result);

            if ([result isEqualToString:@"1"]) {
                message = [NSString stringWithFormat:@"Welcome %@",self.name.text];
                [self.activityIndicator stopAnimating];
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            }

            else {
                message = [NSString stringWithFormat:@"%@ is a registered user",self.name.text];
                [self.activityIndicator stopAnimating];
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            }

            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Message" message:message delegate:self cancelButtonTitle:@"Okay" otherButtonTitles: nil];
            [alertView show];
        });
    });

逻辑很简单。转到一个新的线程,然后在那里,调度到主队列,然后做JS工作,一切都像我的魅力...

The logic is simple. Go to a new thread, and from within that, dispatch to the main queue and then do the JS work and everything worked like a charm for me...

这篇关于UIWebView stringByEvaluatingJavaScriptFromString在后台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆