Send a BOOL value from JavaScript to Objective-C(UIWebview interact with app)

本文介绍了一种在iOS应用中通过JavaScript在UIWebView内运行quiz,并使用Objective-C进行结果验证的方法,包括如何在JavaScript与Objective-C之间传递布尔值。

I’m developing an iPhone app which has a built-in quiz which runs using JavaScript within a UIWebView. After a user clicks aCheck Answers button, I have to use JavaScript to determine if all the answers are correct, so I can save this result for later.

Here is the relevant JavaScript:

function checkAnswers() {
  // Do stuff to see if all answers were correct
  ...

  // Send all correct status back to Objective-C
  window.location = "/allCorrect/" + allCorrect;
}

In Objective-C, you then need to set up a UIWebViewDelegate to intercept whenever a new URL is to be loaded into the UIWebView. Then you need to callshouldStartLoadWithRequest and if you called your fake URL, then it shouldn’t load, but execute the code you need to run in Objective-C instead. Here is the relevant Objective-C code:

- (BOOL)webView:(UIWebView *)webView
        shouldStartLoadWithRequest:(NSURLRequest *)request
        navigationType:(UIWebViewNavigationType)navigationType {

  if ( [request.mainDocumentURL.relativePath
        isEqualToString:@"/allCorrect/false"] ) {
    NSLog( @"Nope, that is not right!" );
    return false;
  }

  if ( [request.mainDocumentURL.relativePath
        isEqualToString:@"/allCorrect/true"] ) {
    NSLog( @"You got them all!" );
    return false;
  }

  return true;
}


From: http://www.chucksmith.de/2009/04/send-bool-value-from-javascript-to-objective-c/

see also: http://iphoneincubator.com/blog/tag/uiwebview

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值