MacOS issue with loading url in web-view - swift

I have done with codes below but I'm having problem loading the webview with an url which show an error with on runtime
Thread 1:signal SIGABRT
so please help me with, i have just started with macOS application development,
Thanks,
import Cocoa
import WebKit
class ViewController: NSViewController, WebFrameLoadDelegate {
#IBOutlet weak var webView: WebView!
let urlpath = NSURL(string: "http://www.google.com/")!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//let url = "https:www.apple.com"
//self.webView.mainFrame.load(NSURLRequest(URL: NSURL(string: url)! as URL))
webView.policyDelegate = self as! WebPolicyDelegate
webView.mainFrame.load(NSURLRequest(url: self.urlpath as URL ) as URLRequest!)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}

You don't implement the WebPolicyDelegate so
webView.policyDelegate = self as! WebPolicyDelegate
will fail.
self (ViewController) does not implement WebPolicyDelegate.
You need to do:
class ViewController: NSViewController, WebFrameLoadDelegate, WebPolicyDelegate {
and implement the delegate.
Also make sure that your webView
#IBOutlet weak var webView: WebView!)
is connected to your webView in your Interface Builder!

Related

How to Autofill forms in WKWebView Using User Defaults or JavaScript

Hello Swift Developers!.
I am new to swift programming and need little help.
I am developing a very simple app, that should simply load the web using WkWebView and autofill the shipping form it have in on of its page.
I have successfully managed to fetch the page in webView(WkWebView).
First it loads this url https://www.adidas.com/us, after selecting the item in to cart it gets to this delivery page https://www.adidas.com/us/delivery where we have to fill this form. before this, no login information needed.
I am trying to make it done with both UIWebView and WkWebView but to no avail, here's my code, UIWebView part is commented.
class ViewController: UIViewController, WKUIDelegate {
#IBOutlet weak var uiWebView: UIWebView!
var webView: WKWebView!
let url: String = "https://www.adidas.com/us/delivery"
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
//WKWebView programatically so it can run below iOS 11
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
if let safeUrl = URL(string: url){
let request = URLRequest(url: safeUrl)
webView.load(request)
}
// uiWebView.loadRequest(NSURLRequest(url: NSURL(string: url)! as URL) as URLRequest)
// let result = uiWebView.stringByEvaluatingJavaScript(from: "document.title")
// print("result is: \(result!)")
self.webView.evaluateJavaScript("document.getElementById('di-id-cab9a55c-9d253ce3').value = 'Hello'") { (result, error) in
print(result) //This will Print Hello
}
}
// func webViewDidFinishLoad(_ webView: UIWebView) {
//
// let email = defaults.string(forKey: "EMAIL")
// let password = defaults.string(forKey: "Pass")
//
// let fillForm = "document.getElementById('f_707d6a95-3ef9-4b76-a162-9361b4ef7d4d').value = \(password)"
// webView.stringByEvaluatingJavaScript(from: fillForm)
// }
}
And Here's the screenshot of inspect element of First Name field.
After this I would use user default for autofill data. that step I know how to do just stuck here!
Can I have any helpful code snippet or suggestion please? I am really stuck at this point!
Thanks in advance
First: stop using UIWebView since it's deprecated from one side and stop supporting by AppStore from Dec 2020.
You should set navigationDelegate to you WKWebView and set your values to the fields on webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) when the page is loaded e.g.:
override func viewDidLoad() {
super.viewDidLoad()
...
webView?.navigationDelegate = self
...
}
extension ViewController : WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// Set a delay for dynamic pages
//DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
let fillForm = "document.getElementsByName('firstName')[0].value = 'My Name'"
webView.evaluateJavaScript(fillForm, completionHandler: nil)
//}
}

WKWebView SWIFT: not show messages in instagram

I'm a new in Swift/iOS developing. I try to create a simple browser:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.instagram.com")!
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true
}
}
When I go to https://www.instagram.com, I can't see my messages.
I got this (top header isn't shown):
But I expect this (top header is shown):
Why I can't see the top header through my browser?
I'm able to see the header at my end. The only difference is that I've added WKWebView in XIB and you are loading on view from the code.
Reason can be the frame & constraints of the page. Try setting frame & constraints -
webView = WKWebView(frame: self.view.frame)
webView.translatesAutoresizingMaskIntoConstraints = true
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

Xcode Wkwebview 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
Here is also a Video were 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()
}
}
Your data is not being shared between the two UIViewControllers because your WKWebViews are different instances of each other and don't share the same data. It's as if you opened two different tabs in your web browser. If you're logged in, and the cart data is stored on the server, it should work, if you refresh the cart's page. If it's cookie based, you'll need to ensure those cookies are common among the two web views. Instead, use the tab to redirect to the cart's page instead of creating a new View Controller instance, or put the instance of the WKWebView into a static variable that can be shared between the two tabs. You'll have to do a bit of hiding/showing of that view so that you don't see it loading, but that can be handled via the delegate.
If the data is stored on the server, you can simple just reload the webpage within the viewDidAppear() overridden function in your VC. It really depends on what you're going for, but those are a few suggestions that'll work.

Is my webView taking too much memory?

I have simple example where one webView is there which loads one link when the app loads successfully the Debug navigator looks like:
App takes 73.5 MB of Memory after that when I scroll down into simulator continuously memory increase too much like :
can anybody explain me why it is taking too much memory?
Or tell me if it causes any problem?
here is my code for this:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = "https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_456"
let requestURL = NSURL(string:url)
let request = NSURLRequest(URL: requestURL!)
webView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
you can use WKWebView instead of UIWebView which will not take more memory, here is an example how to use it in swift 3:
import UIKit
import WebKit
class ViewController: UIViewController
{
var webView: WKWebView!
override func viewDidload() {
super.viewDidload()
let url = "https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_456"
let requestURL = URL(string:url)
let request = URLRequest(url: requestURL!)
webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
self.view.addSubview(webView)
webView.load(request)
}
}

How to load URL in UIWebView in Swift?

I have the following code:
UIWebView.loadRequest(NSURLRequest(URL: NSURL(string: "google.ca")))
I am getting the following error:
'NSURLRequest' is not convertible to UIWebView.
Any idea what the problem is?
loadRequest: is an instance method, not a class method. You should be attempting to call this method with an instance of UIWebview as the receiver, not the class itself.
webviewInstance.loadRequest(NSURLRequest(URL: NSURL(string: "google.ca")!))
However, as #radex correctly points out below, you can also take advantage of currying to call the function like this:
UIWebView.loadRequest(webviewInstance)(NSURLRequest(URL: NSURL(string: "google.ca")!))
Swift 5
webviewInstance.load(NSURLRequest(url: NSURL(string: "google.ca")! as URL) as URLRequest)
UIWebView in Swift
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL (string: "url here")
let requestObj = URLRequest(url: url!)
webView.loadRequest(requestObj)
// Do any additional setup after loading the view.
}
/////////////////////////////////////////////////////////////////
if you want to use webkit
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height))
self.view.addSubview(webView)
let url = URL(string: "your URL")
webView.load(URLRequest(url: url!))
}
Try this:
Add UIWebView to View.
Connect UIWebview outlet using assistant editor and name your "webview".
UIWebView Load URL.
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Your webView code goes here
let url = URL(string: "https://www.example.com")
let requestObj = URLRequest(url: url! as URL)
webView.load(requestObj)
}
And run the app!!
Swift 3 doesn't use NS prefix anymore on URL and URLRequest, so the updated code would be:
let url = URL(string: "your_url_here")
yourWebView.loadRequest(URLRequest(url: url!))
In Swift 3 you can do it like this:
#IBOutlet weak var webview: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Web view load
let url = URL (string: "http://www.example.com/")
let request = URLRequest(url: url!)
webview.loadRequest(request)
}
Remember to add permission at Info.plist, add the following values:
In Swift 4 or 4.2 You can use like:
Add WKWebView & connect to you view comtroller.
Your view is like bellow:
import UIKit
import WebKit
class ViewController: UIViewController {
#IBOutlet weak var wkwebview: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let request = URLRequest(url: URL(string: "**your URL**")!)
wkwebview?.load(request)
}
}
Allow Allow Arbitrary Loads true info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>Allow Arbitrary Loads</key>
<true/>
</dict>
Note info.plist will look like bellow
Swift 3 - Xcode 8.1
#IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL (string: "https://ir.linkedin.com/in/razipour1993")
let requestObj = URLRequest(url: url!)
myWebView.loadRequest(requestObj)
}
Swift 3
#IBOutlet weak var webview: UIWebView!
webview.loadRequest(URLRequest(url: URL(string: "https://www.yourvideo.com")!))
Easy,Tested and working 100%
Import webkit :
import WebKit
Assign IBOutlet to webview:
var webView : WKWebView!
set delegate:
class ViewController: UIViewController , WKNavigationDelegate{
Write code on viewDidLoad():
// loading URL :
let myBlog = "https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile"
let url = NSURL(string: myBlog)
let request = NSURLRequest(url: url! as URL)
// init and load request in webview.
webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.load(request as URLRequest)
self.view.addSubview(webView)
self.view.sendSubview(toBack: webView)
Write delegate methods:
//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")
}
look like:
in swift 5
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
}
Loading URL to WebView is very easy. Just create a WebView in your storyboard and then you can use the following code to load url.
let url = NSURL (string: "https://www.simplifiedios.net");
let request = NSURLRequest(URL: url!);
webView.loadRequest(request);
As simple as that only 3 lines of codes :)
Ref: UIWebView Example
UIWebView loadRequest: Create NSURLRequest using NSURL object, then passing the request to uiwebview it will load the requested URL into the web view.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = NSURL (string: "http://www.google.com");
let requestObj = NSURLRequest(URL: url!);
myWebView.loadRequest(requestObj);
self.view.addSubview(myWebView)
}
For more reference:
https://sourcefreeze.com/uiwebview-example-using-swift-in-ios/
Used Webview in Swift Language
let url = URL(string: "http://example.com")
webview.loadRequest(URLRequest(url: url!))
For swift 4.2, 5+
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
//Func Gose Here
let url = URL(string: link)
let requestObj = URLRequest(url: url! as URL)
webView.loadRequest(requestObj)
}
For Swift 3.1 and above
let url = NSURL (string: "Your Url")
let requestObj = NSURLRequest(url: url as! URL);
YourWebViewName.loadRequest(requestObj as URLRequest)
Swift 4 Update Creating a WebView programatically.
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string: "https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.loadRequest(myRequest)
}}
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
//Func Gose Here
loadUrl()
}
func loadUrl(){
let url = URL(string: "Url which you want to load(www.google.com)")
let requestObj = URLRequest(url: url! as URL)
webView.load(requestObj)
}
}
You can load a page like this :
let url: URL = URL(string:"https://google.com")!
webView.loadRequest(URLRequest.init(url: url))
Or the one-line approach :
webView.loadRequest(URLRequest.init(url: URL(string: "https://google.com")!))
webView is your outlet var.
Try This
let url = NSURL (string: "http://www.apple.com");
myWebView.loadRequest(NSURLRequest(URL: url!));