[Objective-C에서 Javascript를 호출]
@interface ViewController ()
@property (nonatomic, strong) UIWebView* webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// WebView
self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
self.webView.delegate = self;
[self.view addSubview:self.webView];
NSString *path = [[NSBundle mainBundle] pathForResource:@"callTest" ofType:@"html" inDirectory:@""];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
// call javascript button
UIButton* callJavascriptBtn = [[UIButton alloc] initWithFrame:CGRectMake(200, 50, 150, 50)];
[callJavascriptBtn setTitle:@"call javascript" forState:UIControlStateNormal];
[callJavascriptBtn setBackgroundColor:[UIColor grayColor]];
[callJavascriptBtn addTarget:self action:@selector(onCallJavascriptButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:callJavascriptBtn];
}
#pragma mark - Call javascript from objectiveC
- (void)onCallJavascriptButton:(id)sender {
[self.webView stringByEvaluatingJavaScriptFromString:@"callJavascriptFromObjectiveC();"];
}
...
@end
callTest.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name = "viewport" content = "width = device-width"/>
<title>Hybrid App</title>
<script type="text/javascript">
function callJavascriptFromObjectiveC() {
alert('called javascript function by objective-c');
}
</script>
</head>
<body>
<div id="container">
<h3>Call Javascript from Objective-C</h3>
</div>
</body>
</html>
</span>
2. Javascript에서 Objective-C를 호출하는 방법은 커스텀 Scheme를 이용하는 방법이다.
callTest.html에 button을 하나 만들고 버턴이 눌러지면 javascript에 구현한 callObjectiveCFromJavascript() 를 호출한다. 이 메소드 안에는 window.location를 이용해서 커스텀 scheme으로 이동하는 코드를 넣어둔다. 그러면 webView의 delegate 메소드의 webView: souldStartLoadWithRequest:navigationType 메소드를 호출하는데 이때 특정 메소드가 실행되게 구현하면 된다.
.m
@interface ViewController ()
@property (nonatomic, strong) UIWebView* webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// WebView
self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
self.webView.delegate = self;
[self.view addSubview:self.webView];
NSString *path = [[NSBundle mainBundle] pathForResource:@"callTest" ofType:@"html" inDirectory:@""];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
#pragma mark - Call objectiveC from javascript
- (void)callObjectiveCFromJavascript {
NSLog(@"called objective-c from javascript");
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
if ([[[request URL] absoluteString] hasPrefix:@"jscall:"]) {
NSString *requestString = [[request URL] absoluteString];
NSArray *components = [requestString componentsSeparatedByString:@"://"];
NSString *functionName = [components objectAtIndex:1];
if ([functionName isEqualToString:@"callObjectiveCFromJavascript"]) {
[self performSelector:@selector(callObjectiveCFromJavascript)];
}
return NO;
}
return YES;
}
...
@end
<html>
<head>
<meta charset="utf-8"/>
<meta name = "viewport" content = "width = device-width"/>
<title>Hybrid App</title>
<script type="text/javascript">
function callObjectiveCFromJavascript(){
window.location="jscall://callObjectiveCFromJavascript";
}
</script>
</head>
<body>
<div id="container">
<h3>Call Objective-C from Javascript</h3>
<button onclick="callObjectiveCFromJavascript();">Call Objective-C</button>
</div>
</body>
</html>
'Programming > iOS - ObjC' 카테고리의 다른 글
[NSArray] 배열에 있는 모든 객체에서 같은 함수 호출하기 (0) | 2018.05.07 |
---|---|
[AppIcon] iOS 10.3 Dynamic Alternate Icon Name (동적으로 앱 아이콘 변경) (0) | 2017.03.28 |
CLLocation - 두 점사이 거리 구하기 (0) | 2017.03.19 |
Layer - 그림자 넣기 (0) | 2017.03.19 |
[APNs] Push notification 등록 (iOS10 대응) (0) | 2016.12.11 |
UILabel - 특정 범위 색상 변경 (0) | 2015.07.09 |
Device type check (0) | 2015.07.09 |
CATransition - UINavigation push animation (0) | 2015.07.09 |
UIAlertView - TextField 추가 (0) | 2015.07.09 |
NSString - Base64 Encoding/Decoding (0) | 2015.06.30 |