我正在通过以下方法在Objective中提出异步请求:
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之前,这段代码很好地准备好,其中的代码退出时包含以下信息:
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],但是它产生了类似的错误。
发布于 2014-05-20 02:09:39
我可能鼓励您保持连接异步,但是尝试将stringByEvaluatingJavaScriptFromString分配到主队列(或者使用[NSOperationQueue mainQueue]作为sendAsynchronousRequest的queue参数;queue参数指定完成块将在哪个队列上运行,但原始请求仍然异步运行)。
这样,您可以保留请求的异步性质,但确保web视图交互发生在主队列上。
https://stackoverflow.com/questions/23748849
复制相似问题