如何使用WebKit在HTML中显示更多的JSON项?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (58)

我正在使用SwiftyJSON构建一个新闻应用程序,我已经能够正确地提取数据。我也能够在一个表格视图中显示标题和描述。但是,当我转到详细视图时,我希望能够从提要中显示完整的文章摘要。

以下是提要元素:

func parse(json: JSON) {
        for article in json["articles"].arrayValue {
            let title = article["title"].stringValue
            let author = article["author"].stringValue
            let date = article["publishedAt"].stringValue
            let image = article["urlToImage"].stringValue
            let description = article["description"].stringValue

            let obj = ["title": title, "author": author, "date": date, "image": image, "description": description, ]
            news.append(obj)

        }

我将数据发送给详细视图控制器,如下所示:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = DetailViewController()
        vc.articleSummary = news[indexPath.row]
        navigationController?.pushViewController(vc, animated: true)
}

然后在详细视图控制器上,这里是代码。注释项是我要添加到显示中的项:

import UIKit
import WebKit

class DetailViewController: UIViewController {

    var webView: WKWebView!
    var articleSummary: [String: String]!

    override func loadView() {
        webView = WKWebView()
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        guard articleSummary != nil else { return }

        if let description = articleSummary["description"] {
            var html = "<html>"
            html += "<head>"
            html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
            html += "<style> body { font-size: 150%; } </style>"
            html += "</head>"
            html += "<body>"
         // html += <h1>title</h1>
         // html += <h4>author</h4>
         // html += <p>date</p>
         // html += <img src="image" alt="" />
            html += description
            html += "</body>"
            html += "</html>"
            webView.loadHTMLString(html, baseURL: nil)
        }
    }

}
提问于
用户回答回答于

你只需要正确地转义HTML字符串,数据就会显示出来。

if let description = articleSummary["description"],
   let title = articleSummary["title"],
   let author = articleSummary["author"],
   let image = articleSummary["image"],
   let date = articleSummary["date"] {
        var html = "<html>"
        html += "<head>"
        html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
        html += "<style> body { font-size: 150%; } </style>"
        html += "</head>"
        html += "<body>"
        html += "<h1>\(title)</h1>"
        html += "<h4>\(author)</h4>"
        html += "<p>\(date)</p>"
        html += "<img src=\"\(image)\" alt=\"\" />"
        html += description
        html += "</body>"
        html += "</html>"
    webView.loadHTMLString(html, baseURL: nil)
}

扫码关注云+社区

领取腾讯云代金券