How do you display a web view with a parsed XML variable in Swift 3?
I am pretty stuck with showing XML parsed data in web view.
import UIKit
import Fuzi
class ViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let myURLString = "https://www.naver.com"
var myHTMLString = ""
guard let myURL = URL(string: myURLString) else {
print("Error: \(myURLString) doesn't seem to be a valid URL")
return
}
do {
myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
} catch let error {
print("Error: \(error)")
}
do {
let doc = try! HTMLDocument(string: myHTMLString, encoding: String.Encoding.utf8)
// XPath queries
if let firstDiv = doc.firstChild(xpath: "//*[@id='PM_ID_ct']/div[@class='container']") {
print("44444")
print(firstDiv)
let body:String = firstDiv
webView.loadHTMLString(firstDiv as String, baseURL: nil)
}
} catch let error{
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The XML parsed well, but when I put the xml variable in the webview it was making a mistake. Mistake:
Cannot convert value of type "XMLElement" to specified type "String"
Edit Here's another try
When i changed
let body:String = firstDiv
to
let body:String = firstDiv.stringValue
It removes all tags and attributes and remains just text
+3
source to share