Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ContentItemView.swift
- // AeroBuddy
- //
- // Created by Kieran Samuel Cross on 25/12/2019.
- // Copyright © 2019 Luke Collister. All rights reserved.
- //
- import UIKit
- import SwiftSoup
- class ContentItemView: UIView {
- @IBOutlet weak var ContentTitle: UILabel!
- @IBOutlet weak var ContentText: UILabel!
- var currentContent = 0
- var contentList: [Content]!
- func reload() {
- // Set the title
- ContentTitle.text = contentList[currentContent].title
- // Set the content text
- let htmlString = contentList[currentContent].content
- do {
- // Parse HTML
- guard let doc: Document = try? SwiftSoup.parse(htmlString!) else { return }
- // create an NSMutableAttributedString that we'll append everything to
- let fullString = NSMutableAttributedString(string: "")
- // Get all images from HTML content
- for element in try doc.select(".content").array() {
- print("ELEMENT: ", try element.html())
- print("-elem tag: ", element.tagName())
- if (element.tagName() == "img") {
- // It's an image
- print("ATTR SRC :", try element.attr("src"))
- let image1Attachment = NSTextAttachment()
- image1Attachment.image = convertBase64ToImage(imageString: try element.attr("src"))
- let image1String = NSAttributedString(attachment: image1Attachment)
- fullString.append(image1String)
- print("in the do")
- } else {
- print("in the catch")
- // It's not an image
- let div_data = try element.html().data(using: String.Encoding.unicode)!
- let formattedString = try? NSAttributedString(
- data: div_data,
- options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
- documentAttributes: nil)
- fullString.append(formattedString!)
- }
- }
- fullString.append(NSAttributedString(string: "End of text"))
- ContentText.attributedText = fullString
- } catch {
- print("There was an error parsing the HTML")
- }
- }
- }
- func convertBase64ToImage(imageString: String) -> UIImage {
- let imageString2 = String( imageString.dropFirst( 22 ) )
- let imageData = Data(base64Encoded: imageString2, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
- return UIImage(data: imageData)!
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement