1

I got a HTML string and want to change the element inside of them, in img tag style to width = 100% and height auto, so that when I pass them into the web view, the image can fit to the super view layout.

HTML

<img alt=\"\" src=\"https://my.domain.com/img/ckeditor/55de838089041.jpg\" style=\"width:700px\" />

Swift

let doc : TFHpple = TFHpple(HTMLData: htmlText.dataUsingEncoding(NSUTF8StringEncoding))
for img: AnyObject in doc.searchWithXPathQuery("//img") {
    let imgElement : TFHppleElement = img as! TFHppleElement
    let attributes : [NSObject : AnyObject] = imgElement.attributes
    XCGLogger.defaultInstance().debug("attributes: \(attributes)")
    for eachElement : (NSObject, AnyObject) in attributes {
        if eachElement.0 == "style" {
            var elementText : String = eachElement.1 as! String
            eachElement.1 = "width:'100%',height:'auto'"
        }
     }
}

But eachElement.1 is not editable, can I use TFHpple 1 do this, or have to try other way.

Edward Chiang
  • 1,133
  • 2
  • 12
  • 24

1 Answers1

1

Faced a similar problem I edited the whole string which I got from the HMTL response, So you can try something like this :-

    let task = try session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        guard data != nil else {
            print("no data found: \(error)")
            self.displayServerAlert()
            return
        }
        print("Response: \(response)")

        var strData:String = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
        print("Body: \(strData)")

        var replaceStr = strData.stringByReplacingOccurrencesOfString("style=\"width:700px\", withString: "style=\"width:'100%',height:'auto'", options: NSStringCompareOptions.LiteralSearch, range: nil)

        print(replaceStr)
        let strtoData = replaceStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)


        self.parseData(strtoData!)

parseData is fucn where I sent the data to parse according to my needs..!! Hope this helps..!!

Irshad Qureshi
  • 807
  • 18
  • 41