簡體   English   中英

javascript中的Objective-C方法未調用

[英]Objective-C method from javascript is not called

我有一個UIWebView ,其中包含帶有JS功能的按鈕,但是按我的意圖,僅在加載頁面而不是在按下的按鈕上調用委托方法。

問題是什么?

聚苯乙烯

我正在模擬器上測試。

在.h中:

@interface MyViewController : UIViewController <UIWebViewDelegate>{
    UIWebView *webView;
}
@property (strong, nonatomic) IBOutlet UIWebView *webView;

在.m中:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *myHTML = @"<!DOCTYPE html><html><head><script type=\"text/javascript\">
    function myFunction(){document.location = \"myapp:\" + \"myfunction:\" 
    + param1 + \":\" + param2;}</script></head><body><button onclick=\
    "myFunction()\">Try it</button><p>By clicking the button above,
     a function will be called.</p></body></html>";

    [webView loadHTMLString:myHTML baseURL:nil];
    webView.delegate = self;
}


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

    NSString *requestString = [[request URL] absoluteString];
    NSArray *components = [requestString componentsSeparatedByString:@":"];

    if ([components count] > 1 && 
        [(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"]) {
        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myfunction"]) 
        {

            NSLog([components objectAtIndex:2]); // param1
            NSLog([components objectAtIndex:3]); // param2
            // Call your method in Objective-C method using the above...
        }
        return NO;
    }

    return YES; // Return YES to make sure regular navigation works as expected.
}

以這種方式測試對我有效

NSString *myHTML = @"<!DOCTYPE html><html><head>" "<script type='text/javascript'>function myFunction(){alert('ciao');document.location = 'myapp:myfunction:param1:param2';}
</script>"
"</head><body><button onclick='myFunction()'>Try it</button>" 
"<p>By clicking the button above,a function will be called.</p></body></html>";

您的錯誤應如下

document.location = \"myapp:\" + \"myfunction:\" + param1 + \":\" + param2;

你應該寫

document.location =\"myapp:myfunction:param1:param2\";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM