Video thumbnail image moving for inset image using jwplayer video embedded Html content in web view from navigate in swift - html

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.

Related

Swift: UIActivityViewController with HTML content

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).

UIMarkupTextPrintFormatter never renders base64 images

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.

Examine html code before displaying on UIWebView using ios swift

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?

iOS: Excluding certain URLs when running webview

I am using Swift and have web-based content (an external webpage) embedded in WebView for my native app. On that webpage, again, which is in-app, I need to make one link open in Safari and not in the App. HTML target _blank code on the webpage doesn’t work (I wish it was that easy), looking for the right code to do it in Swift.
I have used this code for uiwebview:
#IBOutlet var news: UIWebView!
var theURL = "http://"
override func viewDidLoad() {
super.viewDidLoad()
loadWebPage()
}
func loadWebPage(){
let requestURL = NSURL (string: theURL)
let URLrequest = NSURLRequest (URL: requestURL!)
news.loadRequest(URLrequest)
I have used this code for WKNaviagtionDelegate:
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: ((WKNavigationActionPolicy) -> Void)) {
if (navigationAction.navigationType == WKNavigationType.LinkActivated && !navigationAction.request.URL!.host!.lowercaseString.hasPrefix("http://")) {
UIApplication.sharedApplication().openURL(navigationAction.request.URL!)
decisionHandler(WKNavigationActionPolicy.Cancel)
} else {
decisionHandler(WKNavigationActionPolicy.Allow)
}
Best, Drew
Because you need to create a button that looks like a link.
that should do the trick:
UIApplication.sharedApplication().openURL(NSURL(string: "http://...")!)
If the button is actually on a webpage in WebView... the link is not really controlled by the App unless you manipulate the link in iOS. It looks like the HTML target="_new" tag on the button might work in a later version of iOS. It's a bug in iOS 7 and was fixed in 7.0.3. Try a higher iOS version target for the App with the HTML target tag on the button.
How to open Safari from a WebApp in iOS 7

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