How can send an email with HTML text? I use this code to send email from my swift application:
let subject = "Email test"
let content = "This is some text that I want to share."
// set up activity view controller
let objectsToShare = [content]
let activityViewController = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityViewController.setValue(subject, forKey: "Subject")
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
// exclude some activity types from the list (optional)
activityViewController.excludedActivityTypes = [ UIActivityType.airDrop]
// present the view controller
self.present(activityViewController, animated: true, completion: nil)
I want that the content had some HTML tags and to be interpreted as HTML.
How can I do that? Can anyone please provide me an exmaple?
I don't know if you're still looking for an answer but if you are, you just have to put the html tags around your content:
let content = "<html><body>This is some text that I want to share.</body></html>"
You can also create a subclass of UIActivityItemProvider so you can convert the html to an NSAttributedString depending on the application (e.g. the mail app supports html, but for the notes app you can convert it to an NSAttributedString).
Related
I am using html content for uiwebview in swift but going to one view controller to another controller navigate suddenly moving inner video image.i tried to clear web view- refer link How To Clear A UIWebView and
also used autoresizing autoresizingMask = .flexibleWidth but didn't solved.Clear web view cache using in viewDiddisappear cann't get solution[
Swift 3.0 code:
let htmlString:String = descriptionHtml
webView.loadHTMLString(htmlString, baseURL: nil)
webView.scrollView.isScrollEnabled = false
webView.allowsInlineMediaPlayback = true
let aStr = String(format: "%#%x", "document.querySelector('meta[name=viewport]').setAttribute('content', 'width=%d;', false); ", webView.frame.size.width)
webView.stringByEvaluatingJavaScript(from: aStr)
webView.delegate = self
I would appreciate if someone could help.
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:
Im creating a pdf file out of html content in swift 3.0:
/**
*
*/
func exportHtmlContentToPDF(HTMLContent: String, filePath: String) {
// let webView = UIWebView(frame: CGRect(x: 0, y: 0, width: 694, height: 603));
// webView.loadHTMLString(HTMLContent, baseURL: nil);
let pdfPrinter = PDFPrinter();
let printFormatter = UIMarkupTextPrintFormatter(markupText: HTMLContent);
// let printFormatter = webView.viewPrintFormatter();
pdfPrinter.addPrintFormatter(printFormatter, startingAtPageAt: 0);
let pdfData = self.drawPDFUsingPrintPageRenderer(printPageRenderer: pdfPrinter);
pdfData?.write(toFile: filePath, atomically: true);
}
/**
*
*/
func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -> NSData! {
let data = NSMutableData();
UIGraphicsBeginPDFContextToData(data, CGRect.zero, nil);
printPageRenderer.prepare(forDrawingPages: NSMakeRange(0, printPageRenderer.numberOfPages));
let bounds = UIGraphicsGetPDFContextBounds();
for i in 0...(printPageRenderer.numberOfPages - 1) {
UIGraphicsBeginPDFPage();
printPageRenderer.drawPage(at: i, in: bounds);
}
UIGraphicsEndPDFContext();
return data;
}
Everything is rendered fine except my base64 encoded images. The HTML content itself in a webview or inside safari or chrome browser is presented correctly and is showing all images correctly. But the images are never rendered into the pdf.
Why are the images not rendered and how can I get them to be rendered?
This happens because WebKit first parses the HTML into a DOM, and renders content on multiple event loop cycles. You therefore need to wait for not just the page DOM to be ready but for the resource loading to be complete. As you also suggest, you need to refactor your code such that the webview gets loaded first, and you only then export its contents.
To determine the correct time to fire the export, you can observe for the state of the DOM document in the web view. There are multiple ways to do this, but the most readable option I find is a port of an answer to a related Objective-C question: in your UIWebViewDelegate implementation, implement webViewDidFinishLoad in the following way to monitor document.readyState:
func webViewDidFinishLoad(_ webView: UIWebView) {
guard let readyState = webView.stringByEvaluatingJavaScript(from: "document.readyState"),
readyState == "complete" else
{
// document not yet parsed, or resources not yet loaded.
return
}
// This is the last webViewDidFinishLoad call --> export.
//
// There is a problem with this method if you have JS code loading more content:
// in that case -webViewDidFinishLoad can get called again still after document.readyState has already been in state 'complete' once or more.
self.exportHtmlContentToPDF(…)
}
I found the solution!
The export to PDF happens before the rendering process is finished. If you put in a very small picture it is showing up in the PDF. If the picture is too big the rendering process takes too much time but the PDF export isnt waiting for the rendering to finish.
So what I did to make it work is the following:
Before I export to PDF I show the Result of the HTML in a WebView. The WebView is rendering everything correctly and now when I press on export to PDF the PDF is showing up correctly with all images inside.
So I guess this is a huge lag that there is no way to tell the PDF Exporter to wait for the rendering process to finish.
I am trying to get a code that is sent to me in the title element of a web view. I need to send an initial request and display that view so that the user can input a password, then the response to that will be the view that I want with the code in the title element. Is there a way to get and examine the html code's title element before it gets displayed like some sort of function call from the UIWebView? I'm using this to send the initial request and to print the view with the code after I see it, but I don't really ever want to see it, I just want to examine the html and pull out the code in the title element.
let url2 = NSURL(string: "myURLString") //real string is hidden
let task = NSURLSession.sharedSession().dataTaskWithURL(url2!) {(data, response, error) in
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
}
task.resume()
// later I push a button and print the current page when I see my code
// on the web view with this
webView.reloadInputViews()
let html = webView.stringByEvaluatingJavaScriptFromString("document.all[0].outerHTML")
// print(html)
if let page = html{
print(html)
}
So is there a way to know that my webview has loaded a new page, or do i just have to continuously examine it and see if it has changed?
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 !!!