UIWebViewã§Webã¨ãã¤ãã£ããç¸äºé£æºãããæ¹æ³ã«ã¤ãã¦
ç¹å®ã®ãã¼ã¸ã®ã¿UIWebViewã使ã£ã¦Webãã¼ã¸ã表示ãããã¨ã¯ããããã¨æãã¾ããããã®ãã¼ã¸ã§ã®å¦ççµäºããã¿ã¤ãã³ã°ã§ãåã³ãã¤ãã£ãã³ã¼ããå®è¡ãããã¨ããã±ã¼ã¹ãããã¾ãã
PhoneGapã§ã¯JSãããã¤ãã£ãã³ã¼ããå¼ã¶ä»çµã¿ãå®ç¾ããã¦ãã¾ãããããã¨ä¼¼ããããªä»çµã¿ãä½ãã«ã¯ã©ãããã°ããã®ãç´¹ä»ãã¾ãã
ãã¤ãã£ãããWebå¼ã³åºã
JSãå®è¡ããããã®ã¡ã½ãããããã®ã§ä»»æã®ã¿ã¤ãã³ã°ã§ãããå©ç¨ããã ãã§OKã§ãã
[webView stringByEvaluatingJavaScriptFromString:@"alert('call from native');"];
ç°¡åã§ããã
Webãããã¤ãã£ãå¼ã³åºã
UIWebViewDelegateã«ããããã¼ã¸ããã¼ããããåã«å¼ã°ããã¡ã½ãããå©ç¨ãã¾ãã
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ return YES; }
ããã§YESãè¿ãã¨é常éããã¼ã¸é·ç§»ãããã®ã§ãããNOãè¿ãã¨ãã¼ã¸é·ç§»ããã£ã³ã»ã«ã§ãã¾ãããããå©ç¨ãã¦ãç¹å®ã®ãã¿ã¼ã³ã®å ´åã®ã¿ãã¼ã¸é·ç§»ããã£ã³ã»ã«ãã¦ä»ã®ã¡ã½ãããå®è¡ããã°Webãããã¤ãã£ãã³ã¼ããå¼ã³åºããã¨ãå¯è½ã«ãªãã¾ãã
ã¾ããWebããå¼ã³åºãéã®ã¹ãã¼ã ã決ãã¦ããã¾ãã
ä»åã¯ä¸è¨ã®ããã«ããparamsã¯JSONã§ã¾ã¨ãã¦å¤ã渡ãããã«ãã¾ãã
app-api://method(params)
Webå´ããã¯ãã±ã¼ã·ã§ã³ãå¤æ´ãããã¨ã§ãã¤ãã£ãã³ã¼ããå¼ã³åºãã¾ãã
document.location = "app-api://alert({'value':'call from web'})"
ä¸è¨ãã¿ã¼ã³ã®å¤å®ãã¸ãã¯ã追å ãã¾ãã
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ NSString *requestString = [[request URL] absoluteString]; if ([requestString rangeOfString:@"app-api://"].location == NSNotFound){ return YES; } NSError *error = nil; NSString *pattern = [NSString stringWithFormat:@"app-api://(.+)\\((.+)\\)"]; NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error]; if(error != nil){ NSLog(@"%@", [error description]); return NO; } NSTextCheckingResult *match = [reg firstMatchInString:requestString options:0 range:NSMakeRange(0, requestString.length)]; if(match.numberOfRanges == 0){ NSLog(@"not match"); return NO; } NSString *method = [requestString substringWithRange:[match rangeAtIndex:1]]; NSString *params = [requestString substringWithRange:[match rangeAtIndex:2]]; NSLog(@"%@, %@", method, params); // å¼ã°ããã¡ã½ãããå®è¡ if([method isEqualToString:@"alert"]){ [self alert:params]; } return NO; }
åãåã£ããã©ã¡ã¼ã¿ã¯SBJsonãªã©ã®ãã¼ãµã¼ãå©ç¨ãã¦ããã£ã¯ã·ã§ããªã¼ã§åå¾ã§ãã¾ãã
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *object = [parser objectWithString:params error:nil];
[parser release];
ããã¾ã§ããã°å¾ã¯å¯¾å¿ãããAPIã®ãã¸ãã¯ã追å ãã¦è¡ãã ãã§ããã
ã¹ãã¼ã ãèªç±ã«å¤æ´å¯è½ãªã®ã§ã解æããããå½¢ã§å®è£
ããã®ããããã¨æãã¾ãã