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

时间:2018-07-02 22:53:29

标签: html json swift swifty-json

我正在使用SwiftyJSON构建新闻应用程序,并且能够正确提取数据。我还可以在tableView中显示标题和描述。但是,当我转到详细信息视图时,我希望能够显示提要中的完整文章摘要。

以下是提要元素:

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

}

1 个答案:

答案 0 :(得分:2)

您只需要正确地转义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)
}