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
Related
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)
}
}
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)")
}
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!
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.
I'm messing around with pdfs at the moment. I'm attempting to load a PDF into the system and write out the same PDF to gain an understandings of the the whole procedure.
The problem I've got it is that I'm having to load the pdf from the web and because the WebViewUI.loadRequest is asynchronous, it isn't completed in time.
override func viewDidLoad() {
super.viewDidLoad()
let filePath = getDocumentsDirectory().stringByAppendingPathComponent("output.pdf")
let url : NSURL! = NSURL(string: "http://www.nhs.uk/NHSEngland/Healthcosts/Documents/2014/HC5(T)%20June%202014.pdf")
loadTemplate(url, completion: {(webView: UIWebView) -> Void in
print("callback started")
let pdf = self.toPDF(webView)
do {
pdf!.writeToFile(filePath, atomically: true)
} catch {
// failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
}
print("callback started")
})
print("Finished viewDidLoad")
}
func loadTemplate(url: NSURL, completion: (webView: UIWebView) -> Void) {
print("Start loadTemplate")
// do some crunching to create the SketchAnimation instance...
let webView = UIWebView(frame: CGRectMake(20, 100, 300, 40))
webView.loadRequest(NSURLRequest(URL: url))
self.view.addSubview(webView)
// invoke the completion callback
completion(webView: webView)
print("finished loadTemplate")
}
How do I add a callback to the loadRequest instead of loadTemplate?
You don't, exactly. You'd set up your view controller to be the web view's delegate and implement the webViewDidFinishLoad method. In that method you'd check to make sure the load that finished is the one you were after, and if so, then you'd invoked the code you want to run when the load is complete.
Here is a basic example of how to set that up:
//
// ViewController.swift
//
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet var webView: UIWebView!
var url = NSURL(string: "http://google.com")
override func viewDidLoad() {
super.viewDidLoad()
//load initial URL
let req = NSURLRequest(URL : url!)
webView.delegate = self
webView.loadRequest(req)
}
func webViewDidStartLoad(webView : UIWebView) {
print("AA")
}
func webViewDidFinishLoad(webView : UIWebView) {
print("BB")
}
}