3

I an following THIS tutorial and everything works fine but I want to modified that in my application. In my app I want to remove some HTML tag from my HTML view for that I save the whole HTML code of the webPage into a string now I want to modify that string like I want to remove some tags from It but I don't have any Idea that how can I remove some specific tags from that string and I have following code from that tutorial:

    func loadTutorials(){

    var tutorialsUrl : NSURL = NSURL(string: "https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_467")!
    var tutorialsHtmlData : NSData = NSData(contentsOfURL: tutorialsUrl)!

    var string = NSString(data: tutorialsHtmlData, encoding: NSUTF8StringEncoding)

    println(string!)

//        var tutorialsParser : TFHpple = TFHpple(HTMLData: tutorialsHtmlData)
//        
//        var tutorialsXpathQueryString:String = "//div[@class='content-wrapper']/p[@class='header-text']/a"
//        
//        
//
//        var tutorialsNodes : Array = tutorialsParser.searchWithXPathQuery(tutorialsXpathQueryString)
//        
//        var newTutorials : NSMutableArray = NSMutableArray(capacity: 0)
//        
//        for element in tutorialsNodes as [TFHppleElement]{
//            
//            // 5
//            var  tutorial : Tutorial = Tutorial()
//            newTutorials.addObject(tutorial)
//            
//            // 6
//            tutorial.title = element.firstChild.content
//            
//            // 7
//            tutorial.url = element.objectForKey("href")
//        }

}

from this Link I want to remove below meta tags from the HTML:

<meta id="g-version" name="g-version" content="7fcbb0a2" />
<meta id="j-version" name="j-version" content="1.2.0" />
<meta id="build" name="build" content="60068c96635318099c2acaff2a2b2e00" />
<meta id="document-version" name="document-version" content="2.1.8" />
<meta id="book-assignments" name="book-assignments" content="{Type/Guide}, {Topic/Languages &amp; Utilities/Swift}" />
<meta scheme="apple_ref" id="identifier" name="identifier" content="//apple_ref/doc/uid/TP40014097" />
<meta id="chapterId" name="chapterId" content="TP40014097-CH5">
<meta id="book-title" name="book-title" content="The Swift Programming Language" />
<meta id="book-resource-type" name="book-resource-type" content="Guide" />
<meta id="book-root" name="book-root" content="./" />
<meta id="book-json" name="book-json" content="book.json">
<meta id="date" name="date" content="2014-10-16" />
<meta id="description" name="description" content="The definitive guide to Swift, Apple’s new programming language for building iOS and OS X apps." />
<meta id="IndexTitle" name="IndexTitle" content="" />

<meta id="devcenter" name="devcenter" content="<!-- DEVCENTER_NAME -->" />
<meta id="devcenter-url" name="devcenter-url" content="<!-- DEVCENTER_URL -->" />
<meta id="reflib" name="reflib" content="<!-- REFLIB_NAME -->" />

<meta id="xcode-display" name="xcode-display" content="render" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="width=device-width, maximum-scale=1.0">

But I have no Idea that how can I achieve this.

Here is my source code.

I have asked question on It is posible to load customise HTML view into webView in swift? but This time I want to achieve this programatically.Any solution for this?

4 Answers 4

4

Try this , Its working fine in swift for remove html

let html: String = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML")!  

do {
    let regex:NSRegularExpression  = try NSRegularExpression(  pattern: "<.*?>", options: NSRegularExpressionOptions.CaseInsensitive)
    let range = NSMakeRange(0, html.characters.count)
    let htmlLessString :String = regex.stringByReplacingMatchesInString(html, options: NSMatchingOptions(), range:range , withTemplate: "")

    print("Html Printing For payment \(htmlLessString)") jsonParsingOfWebviewReturn(htmlLessString)
} catch {
            // report error
}
Sign up to request clarification or add additional context in comments.

Comments

4

It can be done easily with SwiftSoup:

var htmlString                             // your html
let doc = try! SwiftSoup.parse(htmlString) // init SwiftSoup object
doc.select("meta").remove()                // css query to select, then remove
try! htmlString = doc.outerHtml()          // get the modified html

Comments

0

The easiest way would be to use NSRegularExpression. This allows to find "<meta[^>]*>" and replace it with a null string. This works in most cases. Note also that the above regex is just a quick and dirty one which I sketched right out of my mind.

A more secure way would be to use a XML parser. But in that case you might fail as many HTML sources are not XML compliant.

Comments

0

Here's a quick implementation which is not perfect (as suggested, you can also use regular expressions to achieve this), but works. I've had to change link from your code to another site because it've raised an exception (likely because developer.apple.com requires authorization).

func loadTutorials() {

    var tutorialsUrl: NSURL = NSURL(string: "http://rinatkhanov.me/")!
    var tutorialsHtmlData : NSData = NSData(contentsOfURL: tutorialsUrl)!

    var input = NSString(data: tutorialsHtmlData, encoding: NSUTF8StringEncoding)
    let lines = input?.componentsSeparatedByString("\n") as [String]
    var result = ""
    for line in lines {
        if !line.hasPrefix("<meta") {
            result += "\n" + line
        }
    }

    println(result)
}

It simply iterates over lines and eliminates ones that have opening meta tag.

1 Comment

thanks for the reply your code working perfectly fine but I don't want to remove only meta tags but many tags I want to remove like <a href and more and my code should looks like:pastebin.com/eu4d3AZ0 It is possible to achieve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.