Swift : Open mailto link in UIWebView - ios

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!

Related

Download .pdf or .ppt by WebView in Swift

I'm using the "webview" component to access the website. In an undetermined part of site, we have .pdf and .ppt format files.
Can I download these files when the user clicks on them? Today, the application only opens .pdf and .ppt, but I would like to download it.
My code is in pt_BR.
class PortalAcademicoViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
carregaSite()
}
func carregaSite(){
/*
let url = URL(string: "")
var urlRequest = URLRequest(url: url!)
urlRequest.cachePolicy = .returnCacheDataElseLoad
webView.loadRequest(urlRequest) */
//carregar o arquivo html
let htmlFile = Bundle.main.path(forResource: "portalacademico", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
HTTPCookieStorage.shared.cookieAcceptPolicy = .always
self.webView.frame = self.view.bounds
webView.loadHTMLString(html!, baseURL: Bundle.main.resourceURL)
//voltar e avançar entres as paginas do webview
let swipeLeftRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(recognizer:)))
let swipeRightRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(recognizer:)))
swipeLeftRecognizer.direction = .left
swipeRightRecognizer.direction = .right
webView.addGestureRecognizer(swipeLeftRecognizer)
webView.addGestureRecognizer(swipeRightRecognizer)
//fim
}
//trabalhando com avançar e voltar webview
#objc private func handleSwipe(recognizer: UISwipeGestureRecognizer) {
if (recognizer.direction == .left) {
if webView.canGoForward {
webView.goForward()
}
}
if (recognizer.direction == .right) {
if webView.canGoBack {
webView.goBack()
}
}
}
//FIM
}
I think you should perform download task with Javascript.
Check your requests in func webView(_ webView: WKWebView, decidePolicyFor navigationAction ...) and if there download request found call the javascript method.
Here is someone already done pdf download with wkwebview.
https://forums.developer.apple.com/thread/108394
You can set a UIWebViewDelegate to your WebView and check for PDF and PPT files in webViewShouldStartLoadWithRequest. webViewShouldStartLoadWithRequest is called every time when the user clicks on a link.
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request for a PPT or PDF file {
downloadFile()
return false
}
return true
}
https://developer.apple.com/documentation/uikit/uiwebviewdelegate/1617945-webview?language=objc
Side note: You are currently using UIWebView which is deprecated. You should consider using WKWebView instead.
with WKWebView download .pdf and .ppt or any specific file, check my solution in here
https://stackoverflow.com/a/60614921/1025070

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.

How to load a webview in a SWIFT based ios App

I am relatively very new to swift. Could you please help me how to load a webview in an ios app based on swift. Basically I want to load the contents of an external URL in an ios app.
Can anyone please help?
override func viewDidLoad() {
super.viewDidLoad()
let webV:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
webV.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.google.com")))
webV.delegate = self;
self.view.addSubview(webV)}
and if you want use delegate function
func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) {
print("Webview fail with error \(error)");
}
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
return true;
}
func webViewDidStartLoad(webView: UIWebView!) {
print("Webview started Loading")
}
func webViewDidFinishLoad(webView: UIWebView!) {
print("Webview did finish load")
Before asking your questions research what you're looking, because this question has been answered on many forums.
In the viewDidLoad() add the following code. Make sure to connect the WebView to the View and to connect the outlet.
let url = NSURL (string: "https://www.google.com");
let requestObj = NSURLRequest(URL: url!);
myWebView.loadRequest(requestObj);
}

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