Edit and Load HTML from local file in Swift - html

I have a .html file stored in my project bundle. When I load it in WebView.(UIWebview/WKWebview) the data is loaded but the table structure in it isn't visible. The table borders, columns , rows. The values are just floating . In Chrome browser it opens properly.
let myURL = Bundle.main.url(forResource: "prescription", withExtension: "html")
let myURLRequest:URLRequest = URLRequest(url: myURL!)
webView.loadRequest(myURLRequest)
Chrome browser :
iOS App UIWebView :
The Html page is made responsive to fit in any sizes but I am not able to load in UIWebview properly as Web.
I need to store the file locally because I need to make changes to its values and show on webview.

Found the solution :
If you are applying some local css whose path is there in HTML file.
viz.
Add that css file "myDefault.css" to your xcode project directory.
Convert the HTML to string and replace the path of css in HTML file with your local path. :
Load the content of HTML to UIWebView with base url. (Providing local file path as baseUrl is important)
webView = UIWebView()
let pathToInvoiceHTMLTemplate = Bundle.main.path(forResource: "presc", ofType: "html")
let pathToHTMLCSS = Bundle.main.path(forResource: "myDefault", ofType: "css")
do {
var strHTMLContent = try String(contentsOfFile: pathToInvoiceHTMLTemplate!)
strHTMLContent = strHTMLContent.replacingOccurrences(of: "./assets/stylesheets/myDefault.css", with: pathToHTMLCSS!)
let pdfURL = URL(fileURLWithPath: pathToInvoiceHTMLTemplate!)
webView.loadHTMLString(strHTMLContent, baseURL: pdfURL)
}catch let err{
print(err)
}

When loading local content into the WKWebView, you shoudl use loadHTMLString(_:baseURL:) instead of loadRequest. The first function allows you to provide a base URL, which you will also let point into the bundle - so you clearly need to add all the relevant files to your application bundle.
guard let indexPath = Bundle.main.path(forResource: "index", ofType: "html"),
let content = try String(contentsOfFile: indexPath, encoding: .utf8),
let baseUrl = URL(fileURLWithPath: indexPath) else {
// Error handling
}
webView.loadHTMLString(content, baseURL: baseUrl)

Related

iOS 13 Swift 5 wkwebview - display image from documents directory into wkwebview real device

I have an app with downloaded images to be displayed in local html in WKWEBVIEW. Everything is working fine but it is not showing image on iPhone device
the html is
"\n<img src="images/d35fb6a3-8a21-4196-9616-ad2c6db60669/fd21b894-38c0-42c5-aa69-a938abe40e4b2467857252325869136.png">\n<img src="images/d35fb6a3-8a21-4196-9616-ad2c6db60669/c927a2a6-4ef0-481d-b27d-525cec7ed3814195490571216387044.png">\n"
matching to this HTML it is to be displayed in a wkwebview which gets displayed perfectly on simulator with the following code
let baseURL = Functions.FileIO.contentFolderURL()
static func contentFolderURL() -> URL? {
guard let folderURL = DataManager.shared.applicationDocumentsURL?.appendingPathComponent("content") else {
return nil
}
do {
let properties = try (folderURL as NSURL).resourceValues(forKeys: [URLResourceKey.isDirectoryKey])
if let isDirectory = properties[URLResourceKey.isDirectoryKey] as? Bool , isDirectory == false {
return nil
}
} catch let error as NSError where error.code != NSFileReadNoSuchFileError {
return nil
} catch {
// No folder, so we create it.
do {
try FileManager.default.createDirectory(atPath: folderURL.path, withIntermediateDirectories: true, attributes: nil)
} catch {
return nil
}
}
return folderURL
}
and then finally displaying
baseURL comes to be
Optional ▿ some :
file:///Users/paza/Library/Developer/CoreSimulator/Devices/D2204E03-8A8F-4EF4-8924-683CF519DD19/data/Containers/Data/Application/E4ED56CF-B247-4471-9F9B-23384FD6D6B3/Documents/content/
- _url : file:///Users/paza/Library/Developer/CoreSimulator/Devices/D2204E03-8A8F-4EF4-8924-683CF519DD19/data/Containers/Data/Application/E4ED56CF-B247-4471-9F9B-23384FD6D6B3/Documents/content/
self.webView?.loadHTMLString(HTML, baseURL: baseURL)
working in simulator below does not work in Device
as https://stackoverflow.com/a/52838445/3455426[ ]2
suggested I tried
self.webView?.loadFileURL(baseURL, allowingReadAccessTo: baseURL)
but the result this comes blank on real device
any leads will be appreciated , Thanks in advance
In WKWebview if we have to show HTML with Cached resources ,firstly we have to save the html string in HTML file in documents directory.
make sure ur cached resources path and the path of HTML file are same also , the cached resources are identified by the lastPathComponent only .
So the fault was the HTML which should have been
let HTML = "<html><body>\n<p><img src=\"fd21b894-38c0-42c5-aa69-a938abe40e4b2467857252325869136.png\"></p>\n<p><img src=\"c927a2a6-4ef0-481d-b27d-525cec7ed3814195490571216387044.png\"><br></p>\n</body></html>"
Specifically the last path component should be there .
Also I followed
https://en.it1352.com/article/9f185d4d185243cc92128148443ca660.html
here the explanation is almost perfect , I just saved in documents directory for swift.

Can't load from documents folder into webView on iOS

I'm unsuccessfully trying to load some html and images from documents folder on iOS. Can someone help me to understand why this code does not work?
let html = "<html><body><font size='20>oi</font></body></html>"
let saveHTML = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("sample.html")
try? html.data(using: .utf8)!.write(to: saveHTML)
webView.load(URLRequest(url: saveHTML))
The problem was simple to solve, it was a lack of rights:
webView.loadFileURL(saveHTML, allowingReadAccessTo: saveHTML)

How to open local html file on Safari?

I want to open a local html file on Safari integration on my Swift 3 application.
I know how to do this with an url. This is the code that I use to do that:
let encodedString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let svc = SFSafariViewController(url: NSURL(string: encodedString!) as! URL)
self.present(svc, animated: true, completion: nil)
But I am not able to do the same with a local file. I have copied my html file on my project and I can see it on the directories tree but I am not able to make it to work. I have looked at Load local html into UIWebView using swift for reference.
How can I load a local html file into Safari integration?
Thanks in advance!
You can't do it using SFSafariViewController
From Apple Documentation:
1. Choosing the Best Web Viewing Class
If your app lets users view websites from anywhere on the Internet, use the SFSafariViewController class. If your app customizes, interacts with, or controls the display of web content, use the WKWebView class.
2. if you look at declaration of init
convenience init(url URL: URL)
url: The URL to navigate to. The URL must use the http or https scheme.
Using Webkit or WebView
helloAshok.html
<html>
<head>
</head>
<body>
<br />
<h2> Welcome ASHOK</h2>
</body>
</html>
ViewContrller.swift
class ViewController: UIViewController {
#IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let localFilePath = Bundle.main.url(forResource: "helloAshok", withExtension: "html")
let request = URLRequest(url: localFilePath!)
myWebView.loadRequest(request)
}
}
Output:

load html file to UIWebview from documents directory on ios with swift

I have an html file and other files that html uses(css,.png) that is saved in the documents directory.How can I load this html file in a UIWebView or wkwebview
using swift?I have found some examples in objective-c but nothing in swift.I don't know anything about objective-c..
let path=getCurrenttHtmlStartPage()
var hContent = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
webView!.loadHTMLString(hContent, baseURL: nil)
webView!.hidden=false
Path is the path in documents folder. /Users/pmdevios/Library/.../Documents/Content/Html/index.html.
With this way the other files inside html aren't showing(images) so I want to do it with another way like this
webView!.loadFileURL(path, allowingReadAccessToURL: path)
With the below code it worked!
let filePath = (folder as NSString).stringByAppendingPathComponent(_currentHtmlStartPage!)
var url:NSURL=NSURL(fileURLWithPath:filePath)
var request:NSURLRequest=NSURLRequest(URL:url)
webView!.loadRequest(request)
folder:string that represents the path in the documents folder
_currentHtmlStartPage:string of file's name (e.g. index.html)
EDIT
Get URL using NSFileManger instance method URLsForDirectory(inDomains:)
Append the file name (myFile.html) to the URL we get back from NSFileManager
Initialize a NSURLRequest object with the URL.
Use the UIWebView or WKWebView class to load the request.
let fileManager = NSFileManager.defaultManager()
var URL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
URL = URL.URLByAppendingPathComponent("myFile.html")
let request = NSURLRequest(URL: fileURL)
webView.loadRequest(request)
Of the top of my head:
if let fileURL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "html") {
let request = NSURLRequest(URL: fileURL)
webView.loadRequest(request)
}
You'll need a flat directory structure in your html and css files because that's how they end up in the app.

Swift convert Html to PDF but the CSS formatting disappear

I am now have UIWebView in my view controller , and I have the html file ( Template.html, including the css inside),using the Mustache to load the data to the html, just like this:
let template = Template(named: "Template")!
let rendering = template.render(Box(self.data))!
and then show it on the webview using this
self.webView.loadHTMLString(rendering, baseURL: nil))
self.webView.scalesPageToFit = true;
all it works well. Then I wanna transform this html to pdf and also show on the same web view, but it looks that all my css layout doesn't work anymore. It only show me the html text and without layout setting by the css.
I used this method to convert to pdf: https://gist.github.com/nyg/b8cd742250826cb1471f
and the only change is
let fmt = UIMarkupTextPrintFormatter(markupText: rendering)
render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)
and then save the pdf, and load it again by the web view
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
var pdfFile = documentsPath.stringByAppendingPathComponent("invoice.PDF")
pdfData.writeToFile(pdfFile, atomically: true)
let url : NSURL! = NSURL(string: pdfFile)
webView.loadRequest(NSURLRequest(URL: url))
But now the pdf has no layout provided by the css(such like the color, the position), but still has the html layout(such like the <\br>), I don't know why, please help me!!!
Thanks !!!