我想做以下列表。
- 使用UIWebView
- 点击webview上的按钮,然后执行本机代码(http请求)并获取响应
我可以得到回应。但是,它在回调函数(冻结)中不能正确地工作"alert"。
为什么喜欢那样?
谢谢。
TextViewController
#import "TestViewController.h"
#import "AFNetworking.h"
@interface TestViewController ()
@end
@implementation TestViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization]
[self initWebView] ;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)initWebView{
self.webView = [[UIWebView alloc] initWithFrame:SCREEN_APPLICATIONFRAME] ;
[self.view addSubview:self.webView] ;
self.webView.delegate = self ;
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"SOME_HTML"]]] ;
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)
request navigationType:(UIWebViewNavigationType)navigationType
{
if ([ request.URL.scheme isEqualToString:@"native" ]) {
if ([request.URL.host isEqualToString:@"foo"]) {
NSURL *url = [[NSURL alloc]initWithString:@"SOME_JSON_RESPONSE_URL"] ;
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"SUCCESS") ;
[self.webView stringByEvaluatingJavaScriptFromString:@"cbFoo('OK')"] ;
} failure:^(NSURLRequest *request, NSURLResponse *response, NSError *error, id JSON){
NSLog(@"ERROR: %@",error) ;
[self.webView stringByEvaluatingJavaScriptFromString:@"cbFoo('NG')"] ;
}];
[operation start] ;
}
return NO;
}
// 通常のschemeの場合は、フックせずそのまま処理を続ける
else {
return YES;
}
}
@end
SOME_HTML是这样的
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset= UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// callback from native
function cbFoo(result){
alert(result) ; // FREEZE!!
alert('1st') ;
alert('2nd') ;
}
</script>
</head>
<body>
<a href="native://foo" >Native Func</a><br>
</body>
</html>
使用setTimeout,它工作正常。但是,我不想使用setTimeout来解决这个问题。。。
function cbFoo(result){
setTimeout(function(){
alert(result) ;
alert('1st') ;
alert('2nd') ;
},0) ;
}
最后我写了以下代码。
NSString *str = [NSString stringWithFormat:@"setTimeout(function(){cbGetCommentData('%@');},0)", text] ;
[self.webView stringByEvaluatingJavaScriptFromString:str] ;