Tim Dietrich

Custom Software Developer

Home Services Portfolio Blog About Contact Newsletter

Xojo: Using Data URIs With iOS HTML Viewers

I'm developing an iOS app with Xojo, and one of the requirements is to be able to display HTML content that's being stored in a database that's serving as a CMS. In this case, the database is an Airtable base.

It took me awhile, but I was able to get the content to display properly in an HTMLViewer. Here's how it works...

First, you have to URL-encode the content that you want to display. With help from "Xojo Wizard" Hal Gumbert, I whipped up a method to handle the URL encoding. That method is shown at the end of the post.

The HTML is being retrieved using an API call and stored in a dictionary. Here's the code that handles taking the HTML and loading it into the HTMLViewer control.

// If the record has HTML...
if fields.HasKey ( "HTML" ) then

// Get the HTML.
html = fields.Value ( "HTML" )

// URL-encode the HTML.
html = App.urlencode ( html )

// Load the HTML viewer with the using the HTML and a data URL.
DetailViewHTML ( currentView ).HTMLViewer1.LoadURL( "data:text/html," + html )

end

Notice the call to the HTMLViewer's "LoadURL" method. This creates a data URI, which causes the content to be rendered properly in the viewer.

Here's the "urlencode" method that I mentioned above. There's nothing particularly fancy about it, but it is simple and it works.

  // Remove newline characters.
  url = url.ReplaceAll ( &u0A, "" )
  
  // Make substitutions...
  url = url.ReplaceAll ( "%", "%25" )
  url = url.ReplaceAll ( " ", "%20" )
  url = url.ReplaceAll ( "!", "%21" )
  url = url.ReplaceAll ( """", "%22" )
  url = url.ReplaceAll ( "#", "%23" )
  url = url.ReplaceAll ( "$", "%24" )
  url = url.ReplaceAll ( "&", "%26" )
  url = url.ReplaceAll ( "'", "%27" )
  url = url.ReplaceAll ( "( ", "%28" )
  url = url.ReplaceAll ( ")", "%29" )
  url = url.ReplaceAll ( "*", "%2A" )
  url = url.ReplaceAll ( "+", "%2B" )
  url = url.ReplaceAll ( ",", "%2C" )
  url = url.ReplaceAll ( "-", "%2D" )
  url = url.ReplaceAll ( ".", "%2E" )
  url = url.ReplaceAll ( "/", "%2F" )
  url = url.ReplaceAll ( ":", "%3A" )
  url = url.ReplaceAll ( ";", "%3B" )
  url = url.ReplaceAll ( "<", "%3C" )
  url = url.ReplaceAll ( "=", "%3D" )
  url = url.ReplaceAll ( ">", "%3E" )
  url = url.ReplaceAll ( "?", "%3F" )
  url = url.ReplaceAll ( "@", "%40" )
  url = url.ReplaceAll ( "[", "%5B" )
  url = url.ReplaceAll ( "\\", "%5C" )
  url = url.ReplaceAll ( "]", "%5D" )
  url = url.ReplaceAll ( "^", "%5E" )
  url = url.ReplaceAll ( "`", "%60" )
  url = url.ReplaceAll ( "{", "%7B" )
  url = url.ReplaceAll ( "|", "%7C" )
  url = url.ReplaceAll ( "}", "%7D" )
  
  return url