Open specific link in Safari from UIWebView - html

I have a UIWebView which loads a local index.html file.
However I have an external link in this html file that I'd like to open in Safari instead of internally in the UIWebView.
Opening a link in safari from say a UIButton was simple enough:
UIApplication.sharedApplication().openURL(NSURL(string: "http://www.stackoverflow.com"))
Opening the Instagram app from a external link also works like a charm.
instagram://media?id=434784289393782000_15903882
So my first though was to do something like this:
Open in Safari
However that doesn't seem to work, then I read something about using webView:shouldStartLoadWithRequest:navigationType:
But everyone who's managed to open an external link in Safari is writing in Obj-C which I'm not too familiar with as I'm writing in Swift.
Update with Swift Code:
import UIKit
class AccessoriesViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var webView:UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
if let url = NSBundle.mainBundle().URLForResource("accessories", withExtension: "html") {
webView.loadRequest(NSURLRequest(URL: url))
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent;
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let url = request.URL where navigationType == UIWebViewNavigationType.LinkClicked {
UIApplication.sharedApplication().openURL(url)
return false
}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Here is how you can do it!
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let url = request.URL where navigationType == UIWebViewNavigationType.LinkClicked {
UIApplication.sharedApplication().openURL(url)
return false
}
return true
}

Related

Swift HTML content of URL of mobile site

I've got a URL and I'm trying to get the HTML content of the site the following way:
func getHtml(_ urlString: String) -> String? {
guard let url = URL(string: urlString) else {
return nil
}
do {
let html = try String(contentsOf: url, encoding: .ascii)
return html
} catch let error {
print("Error: \(error)")
return nil
}
}
if let html = getHtml("https://m.youtube.com/") {
print(html)
}
My issue is, that this gets me the html of the desktop version of the site, however I need the html of the mobile version.
I'm not looking for a workaround for this specific site, but for a general solution, so that, given any URL of a mobile site, it doesn't default to getting me the html of the desktop site.
If you use Viewcontroller in iOS to get the HTML, you can use hidden WKWebView as an alternative and implement the WKNavigationDelegate which has the didFinish method where you can use webView.evaluateJavaScript. As wkwebview is loading from mobile, you will get the mobile version html. Here is the sample of the code.
import UIKit
import WebKit
class YourViewController: UIViewController, WKNavigationDelegate {
let webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func BtnClicked(_ sender: Any) {
loadWeb(url: "https://m.youtube.com/")
}
func loadWeb(url: String) {
if let myURL = URL(string: url) {
let request = URLRequest(url: myURL)
webView.navigationDelegate = self
webView.load(request)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.documentElement.outerHTML") { (data, error) in
//use html data
print("data", data, error.debugDescription)
}
}
}

Prevent the user from copying text of HTML in WebKit View Xcode

I want to disable copying text of my html file that is displayed in a WebKit View. Here is my WebKit View code:
#IBOutlet weak var webView: WKWebView!
#IBOutlet weak var backgroundView: UIView!
var index = 0
var fileName = ""
override func viewDidLoad() {
super.viewDidLoad()
loadSubject()
// Load the appropriate file
let htmlPath = Bundle.main.path(forResource: fileName, ofType: "htm")
let url = URL(fileURLWithPath: htmlPath!)
let request = URLRequest(url: url)
webView.load(request)
}
I'm trying to find a solution and here's the closest one, but I'm not sure how to implement this if it is even the correct answer for me: Prevent user from copying text on browsers
I've been using Swift and Xcode for about 6 months, but I'm brand new to HTML and WebKit View, so I apologize if this is something simple.
Thanks!
try this code
func webViewDidFinishLoad(_ webView: UIWebView) {
webView.stringByEvaluatingJavaScript(from: "document.documentElement.style.webkitTouchCallout='none';")
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == Selector("customMethod:") {
return super.canPerformAction(action, withSender: sender)
}
return false
}

How to make webview only load specific website like youtube?

I am new to Swift and I'm making an app with webview which can display youtube videos. My problem is I don't want my user to go to another url or something like that. I want to make my app load youtube.com. I'm using HTML instead of a URL because I can tell my webview what height and width it's going to have.
HTML code:
<html><head><style type=\"text/css\">body {background-color: transparent;color: white;}</style></head><body style=\"margin:0\"><iframe frameBorder=\"0\" height=\"" + String(describing: height) + "\" width=\"" + String(describing: width) + "\" src=\"http://www.youtube.com/embed/" + vid.videoId + "?showinfo=0&modestbranding=1&frameborder=0&rel=0\"></iframe></body></html>
You could try using shouldStartLoadWith delegate method of UIWebViewDelegate
extension UIViewController: UIWebViewDelegate {
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let url = request.url?.absoluteString ?? ""
print("WebView shouldStartLoadWithRequest url -> \(url)")
if !url.contains("youtube.com") {
// avoid loading strange urls..
// manage error as you need..
webView.stopLoading()
return false
}
return true
}
}
Remember to set UIViewController as UIWebView delegate in viewDidLoad method:
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self
}

UIWebView white flashing when load page

i have build a WebApp for iOS. When i click/tap to move to a page for example from page - index.html to page2.html it flashing white. Did you know why, and how to solve this problem?
The Websites works fantastic in Browser (Safari, IE, Firefox and Chrome) but not as an Application.
My code is:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
webView.loadRequest(NSURLRequest(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("index", ofType: "html")!)))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Try my code will help you!
Step 1: Fetch UIWebView and UIActivityIndicatorView to your view controller.
Step 2: Delegate UIWebView to viewController and Create outlets for UIWebView and UIActivityIndicatorView.
Step 3: Select UIActivityIndicatorView on view controller then go to Attributes Inspector ->Activity Indicator View -> check Animating and Hides when Stopped on Behaviour
Step 4: Add Below codes to your ViewController.
import UIKit
class ViewController: UIViewController,UIWebViewDelegate{
#IBOutlet var loader: UIActivityIndicatorView!
#IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false //to avoid auto scrolling.
functionOfWebView()
}
func functionOfWebView()
{
let URL = NSURL(string: "http://www.google.com")
//let URL = NSBundle.mainBundle().URLForResource("index", withExtension: "html") //For local html file(index.html) with local file hyperlink(file.html) see on video tutorial
let request = NSURLRequest(URL: URL!)
webView.loadRequest(request)
}
func webViewDidStartLoad(webView: UIWebView)
{
loader.startAnimating()
}
func webViewDidFinishLoad(webView: UIWebView)
{
loader.stopAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
In Swift 3.0
import UIKit
class ViewController: UIViewController,UIWebViewDelegate{
#IBOutlet var loader: UIActivityIndicatorView!
#IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false //to avoid auto scrolling.
functionOfWebView()
}
func functionOfWebView()
{
let URL = NSURL(string: "http://www.google.com")
//let URL = Bundle.main.url(forResource: "index", withExtension: "html") //For local html file(index.html) with local file hyperlink(file.html) see on video tutorial
let request = NSURLRequest(url: URL! as URL)
webView.loadRequest(request as URLRequest)
}
func webViewDidStartLoad(_ webView: UIWebView)
{
loader.startAnimating()
}
func webViewDidFinishLoad(_ webView: UIWebView)
{
loader.stopAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
if you confuse or for Using Local html files then see this Youtube tutorial

Swift - Load Local Html in UiWebView

I created a UiWebView where a responsive app is loaded.
Now I want to check whether the page that is accessed throws the web or the native app.
To do this I need to insert specific html in my "uiwebview".
For now I have this:
import UIKit
class ViewController: UIViewController {
#IBOutlet var WebView: UIWebView!
override func prefersStatusBarHidden() -> Bool {
return true;
}
override func viewDidLoad() {
super.viewDidLoad()
var Url = NSURL(string: "http://localhost:8888")
WebView.loadRequest(NSURLRequest(URL: Url!))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
check out the UIWebViewDelegate methods
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebViewDelegate_Protocol/