Can't load from documents folder into webView on iOS - html

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)

Related

Swift UITextView HTML Image causes crash when copying

I currently have a UITextView that would represent an article in the app that I'm making. From the database, I am pulling a simple string that contains HTML formatting that I parse on-device. This is the function that parses the HTML for reference.
let htmlData = NSString(string: s).data(using: String.Encoding.unicode.rawValue);
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
NSAttributedString.DocumentType.html];
do{
let t = try NSMutableAttributedString(data: htmlData ?? Data(), options: options, documentAttributes: nil);
t.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "SFProDisplay-Regular", size: CGFloat(fontSize)) as Any, range: NSMakeRange(0, t.length));
return t;
}
catch let error{
print(error);
return NSMutableAttributedString(string: s);
}
Anyways, in the article, this is the html code that is causing the issue:
Thanks! <span class="q9uorilb tbxw36s4 knj5qynh kvgmc6g5 ditlmg2l oygrvhab nvdbi5me fgm26odu gl3lb2sf hhz5lgdu"><img src="https://static.xx.fbcdn.net/images/emoji.php/v9/tfb/1/16/263a.png" alt="☺️" width="16" height="16" /></span></p>
On the app, it currently looks like this:
When long pressed, it opens up this menu on ios:
When pressing on the copy image button, it throws this error in xcode:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIConcretePasteboard setImage:]: Argument is not an object of type UIImage [(null)]'
I've looked online for a solution but it seems like there hasn't been anyone else with this issue. I've only seen solutions for people who have had issues pasting to the uitextview. I would think that converting the image into a UIImage would help fix this issue but I have no clue on where to start with an html image. Anything that will point me in the right direction will be greatly appreciated! Thanks.

Edit and Load HTML from local file in Swift

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)

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 !!!