How to open finder inside WKWebView in macOS app?

119 views Asked by At

In macOS, our requirement is to open a Finder when clicking Upload File from a web view. It works when I opened the same URL link in Safari but inside macOS application Open Finder its not getting triggered.

I've used WKWebKit delegate function but its not triggered.

- (void)webView:(WKWebView *)webView 
decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction 
decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;

Also I've tried with WKNavigationDelegate as well but no luck.

webView:didStartProvisionalNavigation:
webView:didCommitNavigation:
webView:didFinishNavigation:
webView:didFailNavigation:withError:
webView:decidePolicyForNavigationAction:decisionHandler: 

And also with WKUIDelegate functions as well.

webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:
webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:
webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:
webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:

Here is the code I have tried,

@interface ViewController() <WKUIDelegate, WKNavigationDelegate>
@property (nonatomic, assign) BOOL isFinderOpen;

@end

@implementation ViewController

(IBAction)buttonClick:(id)sender {
 NSString *urlAddress = [NSString stringWithFormat:@"https://www.diawi.com/"];
 [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlAddress]]];
}

- (void)webView:(WKWebView *)webView runOpenPanelWithParameters:(WKOpenPanelParameters *)parameters initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSArray<NSURL *> * _Nullable))completionHandler{
    
    if (!self.isFinderOpen) {
        self.isFinderOpen = YES;
        [self.webView.configuration.preferences setValue:@TRUE forKey:@"allowFileAccessFromFileURLs"];
        NSOpenPanel *openPanel = [NSOpenPanel openPanel];
        [openPanel setCanChooseFiles:YES];
        [openPanel beginWithCompletionHandler:^(NSInteger result) {
            self.isFinderOpen = NO;
            if (result == NSModalResponseOK) {
                NSURL *url = [openPanel URL];
                if (url) {
                    NSLog(@"%@",url);
                }
            }
            else if (result == NSModalResponseCancel) {
                NSLog(@"nil");
            }
        }];
    }    
}

Any thing I'm missing in this ?

0

There are 0 answers