写入Swift中的本地html文件

时间:2017-07-11 05:50:08

标签: html ios swift bundle

我有一些我从json收到的HTML代码。现在我必须将这个html代码写入我项目中的html文档,而不是在webView中显示它。如何在项目中将HTML代码写入我的html文件。

我的内容变量中包含HTML代码。

func getArticles() {
    //let id = "1018"
    let url = "http://www.salemkz.kz/inc/API/getArticles.php?idArticle=170"
    print(url)
    URLSession.shared.dataTask(with: URL(string: url)!) { (data, response, error) in
        if (error != nil) {
            print(error!.localizedDescription)
        }
        else {
            let jsons = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: AnyObject]
            if let results = jsons["result"] as? [[String: AnyObject]] {
                //print("got Result", results)
                for result in results {
                    let content = result["content"] as? String
                    print(content!)
                }

            }

        }
        }.resume()

}

我必须将此代码写入此html文件(名为“articles-1.html”): enter image description here

怎么做???

1 个答案:

答案 0 :(得分:3)

好吧,您可以手动生成此文档。不是一个优雅的解决方案,但会起作用。试试这个:

@IBOutlet weak var webView: UIWebView!

var generatedHtml : String?
var receivedContent: String? = ""

func getArticles() {
        //let id = "1018"
        let url = "http://www.salemkz.kz/inc/API/getArticles.php?idArticle=170"

        print(url)
        URLSession.shared.dataTask(with: URL(string: url)!) { [weak self]
            (data, response, error) in
            if (error != nil) {
                print(error!.localizedDescription)
            }
            else {
                let jsons = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: AnyObject]
                if let results = jsons["result"] as? [[String: AnyObject]] {
                    //print("got Result", results)
                    for result in results {
                        let content = result["content"] as? String
                        if (content != nil) {
                            self?.receivedContent?.append(content!)
                        }
                        print(content!)
                    }
                    self?.generatedHtml = self?.generateString()
                    if ((self?.generatedHtml) != nil) {
                        self?.webView.loadHTMLString((self?.generatedHtml!)!, baseURL: nil)
                    }
                }

            }
            }.resume()
    }

func generateString() -> String? {
        var resultString: String?

        let firstString = "<DOCTYPE HTML> \r <html lang=\"en\" \r <head> \r <meta charset = \"utf-8\"> \r </head> \r <body>"
        let endString = "</body> \r </html>";
        resultString = firstString + self.receivedContent! + endString;

        return resultString
    }

webView这里是一个视图,您要在其中显示此html。如果你想将html保存到文件,你也可以这样做,只需修改一下代码。 (使用String.writeToFile方法)