Use MathJax in iOS App

492 views
Skip to first unread message

a...@medbreaker.one

unread,
Sep 18, 2019, 7:15:17 AM9/18/19
to MathJax Users
I want to display math formulas in a WKView in an iOS Application, how do i manage the components in Xcode?
Message has been deleted

swiftCoder

unread,
Sep 18, 2019, 2:46:54 PM9/18/19
to MathJax Users
Ok i figured it out and would like to share my insides
first of all you have to get your head around the new components choose the ones you need and put them in a folder named "mathjax" now import this folder into Xcode but be carefull to Create folder refrences while doing so.

Next up i made a func that creates a temporary html file to display in a WKWebView, you might want to customize the CSS

func mathJaxSetup(math: String) -> URLRequest {
        guard let path
= Bundle.main.path(forResource: "tex-mml-chtml", ofType: "js", inDirectory: "mathjax") else { return URLRequest(url: URL(fileURLWithPath: "")) }
       
        let filePath
= URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(randomString(length: 10)+".html")
       
        let htmlStr
= """
                        <head>
                            <meta charset='UTF-8'>
                            <style type=\"text/css\">
                                body{font-family: '-apple-system','HelveticaNeue'; font-size:48;}
                                div{display:flex;align-items:center;height:100%;
                                    justify-content:flex-start;padding-left: 1em;
                                    padding-right: 1em;}
                            </style>
                            <script src='\(path)'></script>
                        </head>
                        <body><div><p>\(math)</p></div></body></html>
                    """

       
       
do {
           
try htmlStr.write(toFile: filePath.path, atomically: true, encoding: String.Encoding.utf8)
       
} catch { print(error) }
       
       
return URLRequest(url: filePath)
   
}
   
    func randomString
(length: Int) -> String {
        let letters
= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
       
return String((0..<length).map{ _ in letters.randomElement()! })
   
}

finally i can load the WKWebView like this (notice the backslahses need to be escaped for swift)


wkWebView
.load(mathJaxSetup(math: "Example: \\( \\frac{2}{6} \\div \\frac{3}{5} \\)"))

thats basically it, hope this helps somebody

some sources i used
https://stackoverflow.com/questions/26845307/generate-random-alphanumeric-string-in-swift
Reply all
Reply to author
Forward
0 new messages