I made an iOS app with Xcode and Swift.
I want to open specific hyperlinks in Safari browser, there others in the WebView itself.
To reach this, I'll have to check when an hyperlinks gets clicked.
This is the code I have so far:
//
// PushViewController.swift
// App
//
//
import UIKit
class PushViewController: UIViewController, UIWebViewDelegate {
#IBOutlet var openpushmessage: UIWebView!
var weburl:String = "http://www.example.com"
override func viewDidLoad() {
super.viewDidLoad()
let url: NSURL = NSURL(string: weburl)!
let requestURL: NSURLRequest = NSURLRequest(URL: url)
openpushmessage.loadRequest(requestURL)
}
override func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == .linkClicked
{
print("You clicked a hypelink!")
}
return true
}
}
The code in viewDidLoad() opens the loads the main URL (http://www.example.com) from my server. That works fine.
override fun webView[…] should detect if a hyperlink is clicked and then print("You clicked a hypelink!").
But unfortunately I'm getting the following errors:
What am I doing wrong? How to get rid of these errors?
please try
for swift 3.0
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
if navigationType == .linkClicked
{
}
return true;
}
swift 2.2
internal func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
if navigationType == .LinkClicked
{
}
return true;
}
This is the working solution (Xcode 7.3.1 and Swift 2.2):
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.URL?.query?.rangeOfString("target=external") != nil {
if let url = request.URL {
UIApplication.sharedApplication().openURL(url)
return false
}
}
return true
}
Many thanks to danhhgl from freelancer.com!
I think you can solve with this code:
function reportBackToObjectiveC(string)
{
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "callback://" + string);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
var links = document.getElementsByTagName("a");
for (var i=0; i<links.length; i++) {
links[i].addEventListener("click", function() {
reportBackToObjectiveC("link-clicked");
}, true);
}
in ios code:
if ([[[request URL] scheme] isEqualToString:#"callback"]) {
[self setNavigationLeavingCurrentPage:YES];
return NO;
}
More details you can check from here:
Related
As i implemented the code in which it perfectly work on Browser that is open the safari in ios and put myapp:// on address bar it open my app but i want when click on link which is inside UIWebView
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let setURL=URL(string:"https://myapp.com/")
let setURLRequest=URLRequest(url:setURL!)
webView.loadRequest(setURLRequest)
}
this is my code for loading website into webview and added URL TYPE >item0->myapp
item0->URL Scheme->myapp
when i add to link eg < a href="myapp://"></a> it does not launch the another view getting errors
Appdelegate
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.scheme == "myapp" {
// UIApplication.shared.open(request.url!, options: [:], //completionHandler: nil)
let myVC: MyAnotherController = MyAnotherController()
self.present(myVC, animated: true) { }
return false
}
return true
}
getting this error Value of type 'AppDelegate' has no member 'present'"
From inside if block, you need to return false, and it should work.
By returning false the delegate method tells that the webView should not start loading the url.
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.scheme == "myapp" {
// do your work here
UIApplication.shared.open(request.url!, options: [:], completionHandler: nil)
//Add the below line of code to the existing code
return false
}
return true
}
You can use UIWebView delegate method optional public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
Example
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.scheme == "myapp" {
// do your work here
UIApplication.shared.open(request.url, options: [:], completionHandler: nil)
}
return true
}
But you have to mention all the desire schemes in your app plist too..
Open other apps using url schemes
if let url = URL.init(string: "myapp://") {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
print("scheme is missing in info.plist or invalid scheme")
}
} else {
print("invalid url")
}
Use this code (It will work if the URL's last character contains "#"). "#" is added because if we navigate back to the last screen, it does not open.
link(www.google.com) in web view.
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest,
navigationType: UIWebViewNavigationType) -> Bool {
// request.url?.absoluteString = "www.google.com/#"
let last = request.url?.absoluteString.last
if last == "#" {
//do stuff here
}
return true
}
I'm trying to figure out how to shouldOverrideUrlLoading (Android) in Swift for IOS. I want to capture the URL from a webview and not load that URL. Is this possible with swift? How would it be implemented?
if you are using webview then use web view delegate method shouldStartLoadWithRequest to return false for not loading the URL in webview. For eg.
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.absoluteString == "https://www.google.com" {
return false
}
return true
}
Check out
func webView(UIWebView, shouldStartLoadWith: URLRequest, navigationType: UIWebViewNavigationType)
in UIWebViewDelegate (UIWebViewDelegate Documentation)
Set your view controller as the web view's delegate and return false in the method above to stop a url from loading in the web view.
Example:
class MyWebViewController: UIViewController, UIWebViewDelegate {
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.absoluteString.contains("dontLoadMe") {
return false
}
return true
}
}
I have a iOS app which has a uiwebview where it opens a website, but any link clicked in the webview opens up in Safari. In my code bellow, it get a memetype error on the line "webView.load(request)". Can you give me some code so I can fix this? Thanks! (I need to use a UIWebView instead of a WKWebView)
class VideosViewController : UIViewController, UIWebViewDelegate {
#IBOutlet weak var webView : UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "http://example.com") else { return }
let request = URLRequest(url: url)
webView.load(request)
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == .linkClicked {
guard let url = request.url else { return true }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
return false
}
return true
}
}
Try to call webView.loadRequest(request). This function has only one URLRequest parameter.
I wrote this code:
if navigationType == UIWebViewNavigationType.LinkClicked {
UIApplication.sharedApplication().openURL(request.URL!)
return false
}
and it works for all normal URLs. But when I click on the image/gif with the next code:
<a href="https://cdn-images-1.medium.com/max/800/1*IR7oti7mEsYunzp_HhcNig.gif"
target="_blank" class="c"
style="background-image: url('//cdn.iframe.ly/pj?url=https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1*IR7oti7mEsYunzp_HhcNig.gif&width=1280&
key=9b0e65e32a5412cf736c430972d914c33f46250b&cache=temp');">
1*IR7oti7mEsYunzp_HhcNig.gif </a>
it opens this gif/URL in my application, inside of UIWebView.
How can I force that it will open that gif/URL in Safari, too?
Something must be broken somewhere else in your code.
Working fine like this:
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet var webView : UIWebView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.webView?.loadHTMLString("<a href='https://cdn-images-1.medium.com/max/800/1*IR7oti7mEsYunzp_HhcNig.gif' target='_blank' class='c' style='background-image: url('//cdn.iframe.ly/pj?url=https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1*IR7oti7mEsYunzp_HhcNig.gif&width=1280& key=9b0e65e32a5412cf736c430972d914c33f46250b&cache=temp');'> 1*IR7oti7mEsYunzp_HhcNig.gif </a>", baseURL: NSURL(string: "testurl.com"))
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.LinkClicked {
UIApplication.sharedApplication().openURL(request.URL!)
return false
}
return true
}
}
I have a WebView in my application and I would like any links clicked within the WebView to open in Safari (instead of the WebView itself).
I am developing the application in Swift.
What is the best method to do this?
This is done essentially the same way in Swift as in Obj-C:
First, declare that your view controller conforms to UIWebViewDelegate
class MyViewController: UIWebViewDelegate
Then implement webViewShouldStartLoadingWithRequest:navigationType: in your View Controller:
// Swift 1 & 2
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
switch navigationType {
case .LinkClicked:
// Open links in Safari
UIApplication.sharedApplication().openURL(request.URL)
return false
default:
// Handle other navigation types...
return true
}
}
// Swift 3
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
switch navigationType {
case .linkClicked:
// Open links in Safari
guard let url = request.url else { return true }
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
// openURL(_:) is deprecated in iOS 10+.
UIApplication.shared.openURL(url)
}
return false
default:
// Handle other navigation types...
return true
}
}
Finally, set your UIWebView's delegate, e.g., in viewDidLoad or in your Storyboard:
webView.delegate = self
Updated for swift 3
func webView(_: UIWebView, shouldStartLoadWith: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.linkClicked {
UIApplication.shared.open(shouldStartLoadWith.url!, options: [:], completionHandler: nil)
return false
}
return true
}
According to recommendations in apple docs
Also UIWebView is deprecated after 12 iOS
Here is solution using Swift 5.3 and WKWebiew
First replace your UIWebview with WKWebview
Then conform to WKNavigationDelegate and implement method
Here is code
extension WebViewControllerImpl: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping (WKNavigationActionPolicy) -> Void) {
guard case .linkActivated = navigationAction.navigationType,
let url = navigationAction.request.url
else {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
UIApplication.shared.openURL(url)
}
}
Then set 'navigationDelegate' for your wkWebView
wkWebView.navigationDelegate = self
You need to implement the method webViewShouldStartLoadingWithRequest:navigationType on your web view's delegate and look for the links you want to open in Safari. If you send those off to the OS with [[UIApplication sharedApplication]openURL:] they will open in Safari.
Updated for swift 4.2
func webView(_: UIWebView, shouldStartLoadWith: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
if navigationType == UIWebView.NavigationType.linkClicked {
UIApplication.shared.open(shouldStartLoadWith.url!, options: [:], completionHandler: nil)
return false
}
return true
}