WKWebView won't display the webpage I need it to - swift

Given the code below. I can't get the web page "https://baycare.clearstep.health/covid19" to show up. It shows up okay in Safari and I can get other pages to show up in the WKWebView. I have tried implementing all of the navigation and ui delegate methods to try and track down the problem but have failed to find anything.
The URL used to work, but the company has changed something and now it doesn't. Any help is appreciated.
The below is a complete program:
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let controller = UIViewController()
.setup { viewController in
WKWebView(frame: viewController.view.bounds)
.setup {
viewController.view.addSubview($0)
$0.uiDelegate = WebViewUIDelegate.instance
$0.navigationDelegate = WebViewDelegate.instance
$0.autoresizingMask = [.flexibleWidth, .flexibleHeight]
$0.load(URLRequest(url: URL(string: "https://baycare.clearstep.health/covid19")!))
}
}
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = controller
window?.makeKeyAndVisible()
return true
}
}
extension NSObjectProtocol {
#discardableResult
func setup(_ fn: (Self) -> Void) -> Self {
fn(self)
return self
}
}
final class WebViewUIDelegate: NSObject, WKUIDelegate {
static let instance = WebViewUIDelegate()
}
final class WebViewDelegate: NSObject, WKNavigationDelegate {
static let instance = WebViewDelegate()
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("This doesn't fire so no error?", error)
}
}

WKWebView is depricated version but still webview will works fine, I had same issue and I was doing same but then instead of WKWenView I used web view
import UIKit
import WebKit
class PolicyVC: UIViewController {
#IBOutlet weak var webView: UIWebView!
var isPolicyView = false
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: UIButton.ButtonType.custom)
button.setImage(UIImage(named: "ic_arrow_left"), for: .normal)
button.addTarget(self, action:#selector(popView), for: .touchUpInside)
button.frame=CGRect(x: 0, y: 0, width: 20, height: 20)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItems = [barButton]
setUpUI()
}
#objc func popView(){
self.navigationController?.popViewController(animated: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.navigationBar.isHidden = false
self.navigationController?.navigationBar.backgroundColor = .black
}
func setUpUI(){
if isPolicyView{
let url = URL(string: "https://www.termsfeed.com/privacy-policy/68c4cdaeba7e146a7d72bf57654520e7")
let urlRequest = URLRequest(url: url!)
webView.loadRequest(urlRequest)
}else{
let url = URL(string: "https://www.termsfeed.com/terms-conditions/0001db2c7a1061a55e2f933bb94102de")
let urlRequest = URLRequest(url: url!)
webView.loadRequest(urlRequest)
}
}
}

Related

Xcode Webview items not loading

I have a Xcode Project with a Webview and a TabBar and with the TabBar I can switch between WebViews. My Problem is that when I put something in my ShoppingCard under Lieferworld.de and switch with the TabBar to my Shopping Card url the Items in there are not Visible. How can I solve this? the ShoppingCard URL ends with .php. Below is the code which is implemented
I also uploaded a video on YouTube were I you can see the error
https://youtu.be/qU3Mu1G7MY0
Viewhome:
import UIKit
import WebKit
class viewHome: UIViewController, WKUIDelegate {
#IBOutlet var webViewHome: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webViewHome = WKWebView(frame: .zero, configuration: webConfiguration)
webViewHome.uiDelegate = self
webViewHome.configuration.preferences.javaScriptEnabled = true
//webViewHome.configuration.preferences.javaEnabled = true
view = webViewHome
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://lieferworld.de")
let request = URLRequest(url: url!)
webViewHome.configuration.preferences.javaScriptEnabled = true
//webViewHome.configuration.preferences.javaEnabled = true
webViewHome.load(request)
}
#IBAction func GoBackHome(_ sender: Any) {
if webViewHome.canGoBack {
webViewHome.goBack()
}
}
#IBAction func GoForwardHome(_ sender: Any) {
if webViewHome.canGoForward {
webViewHome.goForward()
}
}
}
ViewShopping | Shopping Cart Class:
import UIKit
import WebKit
class viewShopping: UIViewController, WKUIDelegate {
#IBOutlet var webViewShopping: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webViewShopping = WKWebView(frame: .zero, configuration: webConfiguration)
webViewShopping.uiDelegate = self
//webViewShopping.configuration.preferences.javaEnabled = true
webViewShopping.configuration.preferences.javaScriptEnabled = true
view = webViewShopping
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://lieferworld.de/warenkorb.php")
let request = URLRequest(url: url!)
webViewShopping.configuration.preferences.javaScriptEnabled = true
//webViewShopping.configuration.preferences.javaEnabled = true
webViewShopping.load(request)
}
#IBAction func goBackShoppingCart(_ sender: Any) {
if webViewShopping.canGoBack {
webViewShopping.goBack()
}
}
#IBAction func goForwardShoppingCart(_ sender: Any) {
if webViewShopping.canGoForward {
webViewShopping.goForward()
}
}
#IBAction func webViewRefresh(_ sender: Any) {
webViewShopping.reload()
}
}
WKNavigationDelegate has three delegates.
Here's an example;
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print(error.localizedDescription)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Start page load")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
{
let title = webView.title
print("finish load. \(title).")
// you can do processing on the results here or trigger processing elsewhere
webView.evaluateJavaScript("document.documentElement.outerHTML.toString()",completionHandler:
{ (html: Any?, error: Error?) in
print(html as Any)
self.htmlSource = html as! String
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pageLoaded"), object: nil)
})
}

Can't restore state from code created ViewController

I'm trying to restore ViewController created from code. I'm trying to make very simple example but I don't understand why it doesn't work. An application changes background color of view by clicking on image and should save it when app is stopped. I'm trying to store and restore Bool property, and basing on it app changes views background color. When I'm testing it I'm sending app to background by cmd + shift + h, after that stop app from xcode and open it again, but it doesn't save selected background color.
I've enabled restoration option in AppDelegate
In ViewController I've set restorationIdentifier and restorationClass
Adopted protocol UIViewControllerRestoration in extension to ViewController and implemented encoding and decoding methods
Implemented ViewController restoring method
AppDelegate class
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
return true
}
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
return true
}
}
ViewController class
class ViewController: UIViewController {
var sunny: Bool = true {
didSet {
setColor()
}
}
lazy var colorView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var changeColor: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Change", for: .normal)
button.addTarget(self, action: #selector(change), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.restorationIdentifier = "myVC"
self.restorationClass = ViewController.self
view.backgroundColor = .white
setupUI()
}
#objc func change() {
sunny.toggle()
}
func setColor() {
colorView.backgroundColor = sunny == true ? .yellow : .darkGray
}
}
extension ViewController: UIViewControllerRestoration {
func setupUI() {
view.addSubview(colorView)
NSLayoutConstraint.activate([
colorView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
colorView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
colorView.widthAnchor.constraint(equalToConstant: view.frame.width),
colorView.heightAnchor.constraint(equalToConstant: 500)
])
view.addSubview(changeColor)
NSLayoutConstraint.activate([
changeColor.topAnchor.constraint(equalTo: colorView.bottomAnchor, constant: 10),
changeColor.centerXAnchor.constraint(equalTo: colorView.centerXAnchor),
changeColor.widthAnchor.constraint(equalToConstant: 100),
changeColor.heightAnchor.constraint(equalToConstant: 45)
])
}
override func encodeRestorableState(with coder: NSCoder) {
coder.encode(sunny, forKey: "isSunny")
super.encodeRestorableState(with: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
guard let isSunny = coder.decodeBool(forKey: "isSunny") as? Bool else {return}
sunny = isSunny
setColor()
super.decodeRestorableState(with: coder)
}
static func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? {
let vc = ViewController()
return vc
}
}

I'm trying to open external links from my app but it won't open

I have a wkwebview app, I need help with my code, I can't seems to open external links from my website inside my app.
import UIKit
import WebKit
import UserNotifications
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView!
var bgImage: UIImageView!
var urlString = ""
override func loadView() {
super.loadView()
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
}
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame == nil {
let vc = ViewController()
vc.urlString = navigationAction.request.url?.absoluteString ?? "https://mywebsite"
vc.view.frame = UIScreen.main.bounds
vc.webView = WKWebView(frame: UIScreen.main.bounds, configuration: configuration)
navigationController?.pushViewController(vc, animated: false)
return vc.webView
}
return nil
}
override var prefersStatusBarHidden: Bool{
return true
}
override func viewDidLoad() {
super.viewDidLoad()
let image : UIImage = UIImage(named:"bgx1")!
bgImage = UIImageView(image: image)
bgImage.frame = CGRect(x: 0, y: 0, width: 1000, height: 2000)
view.addSubview(bgImage)
let myURL = URL(string: "https://mywebsite/")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
webView.allowsBackForwardNavigationGestures = true
activityIndicator = UIActivityIndicatorView()
activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
self.activityIndicator.center = CGPoint(x:self.view.bounds.size.width/2.0,y: self.view.bounds.size.height/2.0);
activityIndicator.autoresizingMask = (UIView.AutoresizingMask(rawValue: UIView.AutoresizingMask.RawValue(UInt8(UIView.AutoresizingMask.flexibleRightMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleLeftMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleBottomMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleTopMargin.rawValue))))
activityIndicator.hidesWhenStopped = true
activityIndicator.style = UIActivityIndicatorView.Style.whiteLarge
activityIndicator.color = UIColor.darkGray
self.view.addSubview(activityIndicator)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
activityIndicator.startAnimating()
bgImage.startAnimating()
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("It is an error")
activityIndicator.stopAnimating()
bgImage.stopAnimating()
let alert = UIAlertController(title: "Network Error", message: "You have no internet connection", preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Reload page", style: .default, handler: { (UIAlertAction) in
self.viewDidLoad()
})
alert.addAction(restartAction)
present(alert, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicator.stopAnimating()
bgImage.stopAnimating()
bgImage.isHidden = true
}
}
What am I doing wrong? Please help.
You have to implement the webView(_:decidePolicyFor:decisionHandler:) function of WKNavigationDelegate protocol in order to allow following the links in your web view.
Here is the documentation
please use this webview as I shown in image
code:-
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self;
webView.loadRequest(URLRequest.init(url: URL(string: "https://mywebsite")!));
}
func webViewDidStartLoad(_ webView: UIWebView) {
SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.custom)
SVProgressHUD.show();
}
func webViewDidFinishLoad(_ webView: UIWebView) {
SVProgressHUD.dismiss();
}

Open a link using the button and textfield

Can I open a link using the button and textfield on which the link is listed on another page within the app itself and not with Safari?
I'm using Swift 4
You have to open webview in destination view controller and send url string from first view controller to destination like below:
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
#IBAction func action(_ sender: Any) {
if let mainVC = storyboard?.instantiateViewController(withIdentifier: "second") as? DestinationViewController {
mainVC.urlStr = textField.text
self.navigationController?.pushViewController(mainVC, animated: true)
}
}
}
Destination View controller:
class DestinationViewController: UIViewController {
var urlStr: String?
override func viewDidLoad() {
super.viewDidLoad()
let webView = UIWebView(frame: self.view.frame)
self.view.addSubview(webView)
if let urlString = urlStr, let url = URL(string: urlString) {
webView.loadRequest(URLRequest(url: url))
}
}
}
Just Use WKWebView to open the link on Button action using this
Import WebKit
import WebKit
In your FirstViewController pass the URL while pushing to
SecondViewController
FirstViewController
if let secondVC = (UIStoryboard.init(name: "Main", bundle: nil)).instantiateViewController(withIdentifier: "secondVCID") {
secondVC.url = textFiled.text // OR send the URL you want to send
self.navigationController?.pushViewController(secondVC, animated: true)
}
In SecondViewController
Import Webkit
declare the delegate
class SecondViewController: UIViewController,WKNavigationDelegate {
declare the URL var so that u cab access it n FirstVC
var url: String?
#IBOutlet weak var webView: WKWebView!
In ViewDidLoad Of SecondVC
let webUrl = NSURL(string: url!)
let request = NSURLRequest(URL: webUrl)
// load request in webview.
webView.navigationDelegate = self
webView.loadRequest(request)
and Implement all delegate methods of WKWebview
//MARK:- WKNavigationDelegate
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
print(error.localizedDescription)
}
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Strat to load")
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
print("finish to load")
}

viewWillAppear/DidAppear called twice when changing rootViewController with an Animation

Here is the code of my animation/transition :
if let window = self.window where animated {
window.rootViewController?.dismissViewControllerAnimated(true, completion: {
UIView.transitionFromView(window.rootViewController!.view, toView: tabBarController.view, duration: 0.8, options: .TransitionFlipFromLeft, completion: { _ in
window.rootViewController = tabBarController
})
})
}
Without the animation code, (just setting the rootViewControlller), the problem does not appear.
Any idea why it makes the view appear twice and how I could fix this ?
using UIViewController.transitionFromViewController1 ,instead of your UIView.transitionFromView.act like it :
//
// AppDelegate.swift
// helloapp
//
// Created by quota on 2/18/16.
// Copyright © 2016 liu. All rights reserved.
//
import UIKit
class ViewController1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.greenColor()
let button = UIButton()
button.setTitle("transit", forState: .Normal)
button.frame = CGRectMake(20, 20, 100,20)
button.addTarget(self, action: "click:", forControlEvents: .TouchDown)
view.addSubview(button)
}
func click(sender:UIButton!){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
if let window = appDelegate.window {
// let v2 = ViewController2()
if let r = window.rootViewController{
r.transitionFromViewController(
appDelegate.v1!
,toViewController:appDelegate.v2!,duration:0.8,options: .TransitionFlipFromLeft,animations:nil){_ in }
}
}
}
}
class ViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blueColor()
}
override func viewWillAppear(animated: Bool) {
print(animated)
}
}
class ViewController3: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.redColor()
}
}
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var v1 : ViewController1?
var v2 : ViewController2?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = ViewController3()
v1 = ViewController1()
v2 = ViewController2()
v1!.view.frame = self.window!.frame
self.window!.rootViewController?.addChildViewController(v1!)
self.window!.rootViewController?.view.addSubview(v1!.view)
self.window!.rootViewController?.addChildViewController(v2!)
self.window?.makeKeyAndVisible()
return true
}
}