首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在WebView内部使用sendAsynchronousRequest?

在WebView内部使用sendAsynchronousRequest?
EN

Stack Overflow用户
提问于 2014-05-19 23:41:42
回答 1查看 124关注 0票数 1

我正在通过以下方法在Objective中提出异步请求:

代码语言:javascript
复制
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    NSInteger code = [httpResponse statusCode];
    if (code == 200){
        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        // Escape single quotes
        jsonString = [jsonString stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat: @"window.displayVotes('%@')", jsonString]];
    } else {
        // Error
        ...
    }
}];

在我到达stringByEvaluatingJavaScriptFromString之前,这段代码很好地准备好,其中的代码退出时包含以下信息:

代码语言:javascript
复制
1   0x7fff891faf1f WebCore::ScriptController::evaluateInWorld(WebCore::ScriptSourceCode const&, WebCore::DOMWrapperWorld*)
2   0x7fff891fadc9 WebCore::ScriptController::evaluate(WebCore::ScriptSourceCode const&)
3   0x7fff89338466 WebCore::ScriptController::executeScript(WebCore::ScriptSourceCode const&)
4   0x7fff89338290 WebCore::ScriptController::executeScript(WTF::String const&, bool)
5   0x7fff8c85265e -[WebFrame(WebInternal) _stringByEvaluatingJavaScriptFromString:forceUserGesture:]
6   0x100008fc9 __31-[CCAppDelegate getVotes:name:]_block_invoke
7   0x7fff90da26ad __67+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]_block_invoke_2
8   0x7fff90c2c0b5 -[NSBlockOperation main]
9   0x7fff90c0b8a1 -[__NSOperationInternal _start:]
10  0x7fff90c0b54b __NSOQSchedule_f
11  0x7fff915a62ad _dispatch_client_callout
12  0x7fff915aa7ff _dispatch_async_redirect_invoke
13  0x7fff915a62ad _dispatch_client_callout
14  0x7fff915a809e _dispatch_root_queue_drain
15  0x7fff915a9193 _dispatch_worker_thread2
16  0x7fff8d179ef8 _pthread_wqthread
17  0x7fff8d17cfb9 start_wqthread

我不完全确定为什么会发生这种情况(因此我才会这么做),但我的猜测是,这与self.webView是否可用于另一个线程有关。我会将其保留为同步请求,但我请求的URL可能需要一段时间才能返回,因此会阻塞UI。

有什么办法补救吗?我尝试将stringByEvaluatingJavaScriptFromString代码移动到它自己的方法,然后在完成回调中调用[self thatMethod],但是它产生了类似的错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-20 02:09:39

我可能鼓励您保持连接异步,但是尝试将stringByEvaluatingJavaScriptFromString分配到主队列(或者使用[NSOperationQueue mainQueue]作为sendAsynchronousRequestqueue参数;queue参数指定完成块将在哪个队列上运行,但原始请求仍然异步运行)。

这样,您可以保留请求的异步性质,但确保web视图交互发生在主队列上。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23748849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档