Search code examples
htmlstringswiftmfmailcomposeviewcontroller

How to change content of HTML file with variables?


I have HTML. HTML file contains few such texts: \(something) . This HTML I converted into String. But when I put this into mail as html body (or web view), instead of my data are presented these \(something). Does anybody know how to handle this issue?

I know that html is not swift but when I convert this into string it should behave like swift string, no? Thank you

For better understanding check screenshot.

Piece of code from my html file:

OSX Mail app:

enter image description here


Solution

  • I had the same problem and used the stringByReplacingOccurrencesOfString. See below for an example code:

    You get the content of your html file by calling the NSBundle

    let filePath = NSBundle.mainBundle().pathForResource("emailTemplate", ofType: "html")
    let contentData = NSFileManager.defaultManager().contentsAtPath(filePath!)
    let emailTemplate = NSString(data: contentData!, encoding: NSUTF8StringEncoding) as? String
    

    In your html file you replace where you want your variables to be, with a unique target, for example @%, doesn't matter what that is as long as it is unique to that variable. Let's assume your html file would look like:

    HTML File

    You then replace the string with the target:

    let replacedHtmlContent = emailTemplate?.stringByReplacingOccurrencesOfString("@%", withString: "Name")
    

    Your new html content would be:

    New HTML Content output

    Hope this helps, good luck!