How to get the current Url in a Webview - IOS

Asked

Viewed 71 times

0

I’m trying to get the current URL because when I’m at a certain URL I need to open the camera of the phone. With android got it, but with iOS on Xcode I’m not getting it, I tried this code more unsuccessfully

- (BOOL) webView: (UIWebView *) webView shouldStartLoadWithRequest: (NSURLRequest *) request navigationType: (UIWebViewNavigationType) navigationType {
    NSString  *URL = request.URL.absoluteString;    NSLog(@"%@",URL);
    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"window.location"];


    return [self shouldStartDecidePolicy: request];
}

1 answer

1


After placing a Webkit View in Storyboard and dragging Outlet to the code use the following code:

Viewcontroller. h

#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>

@interface ViewController : UIViewController <WKNavigationDelegate>

@property (weak, nonatomic) IBOutlet WKWebView *webView;

@end

Viewcontroller. m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.webView.navigationDelegate = self;

    //URL do site que deseja iniciar  webView
    NSString * mURL = @"https://www.google.com";
    NSString * webStringURL = [mURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    NSURL* url = [NSURL URLWithString:webStringURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    [_webView loadRequest: requestObj];
}

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

    if(navigationAction.navigationType == WKNavigationTypeLinkActivated) {
        // Aqui você recebe a URL atual
        NSLog(@"%@", navigationAction.request.URL);
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

@end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.