Swift: call function from another class to appear in same webview - ios

I am trying to call loadAddressURL() into the Webview from callbackHandler() in the xWebAppJS class. I have no problem calling the callbackHandler() from the ViewController but the opposite does not hold true.
I am basically trying to reload the page or any other page in the Webview from another class.
Thanks in advance! Sorry if newbie question.
class ViewController: UIViewController, UIWebViewDelegate{
//... viewDidLoad()
//... viewDidAppear()
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let scheme = String(request.URL!)
NSLog(scheme)
//checks string if contains sequence
if scheme.containsString("ios:JS.") {
xWebAppJS.callbackHandler(scheme)
return false
}
NSLog("Link was not tapped")
return true
}
func loadAddressURL(URL: String) {
let requestURL = NSURL(string: URL)
let request = NSURLRequest(URL: requestURL!)
Webview.loadRequest(request)
}
This is the other class that contains the callbackHandler
class xWebAppJS: ViewController{
class func callbackHandler(oScheme: String) {
// I want to call the loadAddressURL() out of this function
}
}

Since xWebAppJS conforms to ViewController, you can just do xwebAppJS().loadAddressUrl(Url:String)

This will be the answer !
**inside the class**
let requestURL = NSURL(string: "string URL")
self.loadAddressUrl(requestURL)
**outside the class**
let xWebAppJS = xWebAppJS()
let requestURL = NSURL(string: "string URL")
xWebAppJS.loadAddressUrl(requestURL)
func loadAddressURL(requestURL: NSURL) {
let request = NSURLRequest(URL: requestURL)
webView.loadRequest(request)
}

Related

Intercept javascript file from loading in web view

I am using WKWebView to make a web view app
let url = NSURL(string: "http://www.example.com")
let request = NSURLRequest(url: url! as URL)
homeWebView.load(request as URLRequest)
But I want to intercept some javaScript file of this website before it
loads to change functionality and make the app a bit native looking
Any help would be appreciated.
Thank You.
Following is the complete example. I hope it will help you.
import UIKit
class ViewController: UIViewController,UIWebViewDelegate {
private var webView: UIWebView!
override func loadView() {
webView = UIWebView(frame: .zero)
webView.delegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// set the view controller title, navigation etc
self.loadWebPage()
}
func loadWebPage() {
let url = URL(string: "https://www.google.com.pk/")
// let localFileURL = URL(fileURLWithPath: Bundle.main.path(forResource: "ExampleHtmlFileName", ofType: "html", inDirectory: "HtmlFilesFolderName")!)
let myRequest = URLRequest(url: url!)
webView.loadRequest(myRequest)
}
//MARK: UIWebView Delegate
func webViewDidFinishLoad(_ webView: UIWebView) {
let jsScript = "exampleJSMethod()"
_ = webView.stringByEvaluatingJavaScript(from: jsScript)
}
}

How i can fix this error :Cannot convert value of type 'NSURL' to expected argument type 'URLRequest'

i was use it solution but it's not work
let targetURL = URL(string: request)
let request = URLRequest(url: targetURL!)
this is my code
import UIKit
class WebUIViewController: UIViewController,UIWebViewDelegate {
#IBOutlet weak var smartWebView: UIWebView!
#IBOutlet weak var activityWebload: UIActivityIndicatorView!
var smart :String?
i am pass url by first view controller using smart variable and i print url in console but cant show in my web view
override func viewDidLoad() {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Web View Controller
func webScreen(){
let request = NSURL(fileURLWithPath: smart!)
smartWebView.loadRequest(request)
super.viewDidLoad()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
activityWebload.startAnimating()
}
func webViewDidStartLoad(_ webView: UIWebView) {
activityWebload.stopAnimating()
}
#IBAction func refreshpage(_ sender: Any) {
smartWebView.reload()
}
}
Please check your URL is Correct or not after to open in webView
if let url = URL(string: "Your Url"){
if UIApplication.shared.canOpenURL(url) {
let request = URLRequest(url: url)
smartWebView.loadRequest(request)
}
}
This code is wrong:
let request = NSURL(fileURLWithPath: smart!)
smartWebView.loadRequest(request) //The parameter here should
//be of type URLRequest
The first line creates request as an NSURL. You name it request but it's not a URLRequest
The function UIWebView.loadRequest(_:) wants a parameter of type URLRequest, not URL or NSURL. You need to add a line to create a URL request from the URL:
//First create a URL object
let theURL = URL(fileURLWithPath: smart!)
//Now use the URL to create a ULRRequest object
let request = URLRequest(url: theURL)
//Use the URLRequest to submit the load request.
smartWebView.loadRequest(request)
(Note that you don't need to create an Objective-C NSURL. You can use the native Swift URL type.)

UIWebview reload doesn't work

I use UIWebView to load the remote url, the page is blank because the network is unavailable. After network is available ,i reload the UIWebView, but the page is still blank.
How can i solve it?
Try this
func reloadRequest() {
if let url = URL(string: "https://stackoverflow.com") {
let request = URLRequest(url: url);
self.loadRequest(request);
}
}
Load web view with request again, like:
if let url = URL(string: "https://www.google.com") {
let request = URLRequest(url: url)
wvWebView.loadRequest(request)
}
Here is sample code.
#IBOutlet var wvWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
wvWebView.delegate = self
reloadWebview()
}
// call this function to reload web view.
func reloadWebview(){
if let url = URL(string: "https://www.google.com") {
let request = URLRequest(url: url)
wvWebView.loadRequest(request)
}
}
// Webview Delegates
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print("\n\n**** webView:shouldStartLoadWithRequest: \(request.url) \(navigationType)")
return true
}
func webViewDidStartLoad(_ webView: UIWebView) {
print("webViewDidStartLoad")
}
func webViewDidFinishLoad(_ webView: UIWebView) {
print("webViewDidFinishLoad")
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
print("error description - \(error.localizedDescription)")
}

Meme Type Error on UiWebView

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.

UIWebView and JavaScriptInterface in Swift

How can I to create the JavascriptInterface channel from my web site to my UIWebView?
Example in Android:
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
And from this JavascriptInterface I would like to draw the methods, as for example:
func webViewDidStartLoad(webView: UIWebView)
or
myActivityIndicator.startAnimating()
How can I do?
For WKWebView: source here
JavaScript
function callNativeApp () {
try {
webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");
} catch(err) {
console.log('The native context does not exist yet');
}
}
Swift
import WebKit
class ViewController: UIViewController, WKScriptMessageHandler {
#IBOutlet var containerView: UIView? = nil
var webView: WKWebView?
override func loadView() {
super.loadView()
let contentController = WKUserContentController()
contentController.addScriptMessageHandler(self, name: "callbackHandler")
let config = WKWebViewConfiguration()
config.userContentController = contentController
self.webView = WKWebView( frame: self.containerView!.bounds, configuration: config)
self.view = self.webView
}
override func viewDidLoad() {
super.viewDidLoad()
//I use the file html in local
let path = NSBundle.mainBundle().pathForResource("index", ofType: "html")
let url = NSURL(fileURLWithPath: path!)
let req = NSURLRequest(URL: url)
self.webView!.loadRequest(req)
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {// edit: changed fun to func
if (message.name == "callbackHandler"){
print("\(message.body)")
}
}
}
For UIWebView: source here
JavaScript in HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
(function(){
$(window).load(function(){
$('.clickMe').on('click', function(){
window.location = "foobar://fizz?Hello_from_javaScript";
});
});
})(jQuery);
</script>
Swift
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var Web: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("index", ofType: "html")
let url = NSURL(fileURLWithPath: path!)
let req = NSURLRequest(URL: url)
Web.delegate = self
Web.loadRequest(req)
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.URL?.query != nil {
print("\(request.URL!.query!)")
}
return true
}
}
Here's a quick example:
Register a URL Scheme such as foobar in Xcode
Handle this URL Scheme in your web view
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.URL?.query?.containsString("show_activity_indicator=true") {
myActivityIndicator.startAnimating()
}
}
Finally, call this from your JavaScript
// Show your activity indicator from JavaScript.
window.location = "foobar://fizz?show_activity_indicator=true"
Note: See my question here for more information on web view communication in iOS.

Resources