UIWebview reload doesn't work - ios

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)")
}

Related

Swift : Open mailto link in UIWebView

I am developing an application using UIWebView. Inside the web view I have mailto link and I want to open this link in the mail application of iOS.
That is my entire code of the application
override func viewDidLoad() {
//webview.delegate = self;
webview.dataDetectorTypes = UIDataDetectorTypes.all
super.viewDidLoad()
self.webview.delegate = self
let webURL = URL(string: "http://www.collegiodeirettori.net/palio/")
// Do any additional setup after loading the view, typically from a nib.
let urlRequest = URLRequest(url: webURL!)
webview.loadRequest(urlRequest)
webview.scrollView.bounces = false
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print(request)
let stringaURL = try! String(contentsOf: request.url!, encoding: String.Encoding.ascii)
if navigationType == UIWebViewNavigationType.linkClicked{
if((stringaURL.range(of:"www.collegiodeirettori.net/palio/")) != nil ){
print("ciao")
//print(stringaURL)
}
else{
print(stringaURL)
UIApplication.shared.openURL(request.url!)
//UIApplication.shared.open(URL(string: stringaURL)!)
return false;
}
}
return true;
}
I already made a func that control if a link have to be opened in safari and that works but no for the mailto link..
Any ideas? Thanks!

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.

webViewDidStartLoad not working

webViewDidStartLoad and webViewDidFinishLoad are not working.
What I have already done:
webView.delegate = self;
added UIWebViewDelegate
placed the code in viewDidAppear.
Here is the code:
func webViewDidStartLoad(webView: UIWebView!) {
print("Webview started Loading")
}
func webViewDidFinishLoad(webView: UIWebView!) {
print("Webview did finish load")
}
Check this simple example code which is working fine:
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = "http://apple.com"
let requestURL = NSURL(string:url)
let request = NSURLRequest(URL: requestURL!)
webView.delegate = self
webView.loadRequest(request)
}
func webViewDidStartLoad(webView: UIWebView) {
print("Webview started Loading")
}
func webViewDidFinishLoad(webView: UIWebView) {
print("Webview did finish load")
}
}
Update for Swift 3
let url = "http://apple.com"
let requestURL = URL(string:url)
let request = URLRequest(url: requestURL!)
webView.delegate = self
webView.loadRequest(request)
}
func webViewDidStartLoad(_ webView: UIWebView) {
print("Webview started Loading")
}
func webViewDidFinishLoad(_ webView: UIWebView) {
print("Webview did finish load")
}
}

Back button not working for my manually loaded UIWebView for external website

Technologies: Swift, iOS8.1.3, XCode 6, Maverick
I've added a "rewind" back button to my UIWebview via the main.storyboard and connected it here on my view with a backButton func:
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var webView: UIWebView!
var detailItem: NSURL?
var grabData = false
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
self.navigationController?.toolbarHidden = false;
}
#IBAction func backButton(sender: AnyObject) {
self.webView.goBack()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let url = self.detailItem {
webView.loadRequest(NSURLRequest(URL: url))
}
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request:
NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if grabData {
grabData = false
return true
} else {
grabData = true
manuallyLoadPage(request)
return false
}
}
func manuallyLoadPage(request: NSURLRequest) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(data, response, error) invar html = NSString(data: data, encoding: NSUTF8StringEncoding) as String
html = html.stringByReplacingOccurrencesOfString("</head>", withString: "<styles><link rel='stylesheet' type='text/css' href='link-to-styles.css' media='all'></styles></head>", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
self.webView.loadHTMLString(html, baseURL: response.URL!)
}
task.resume()
}
My back button doesn't do anything when clicked and I want it to show the previous webpage. I think it has something to do with how I am intercepting the session and manually loading the WebView. Maybe it doesn't know what the original base url is? Something else?

Resources