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