title: Cleaning malformed UTF-8 data
body: <h3>Background</h3>
  
  <p>With Swift, I'm trying to fetch HTML via <code>URLSession</code> rather than by loading it into a <code>WKWebView</code> first as I only need the HTML and none of the subresources. I'm running into a problem with certain pages that work when loaded into <code>WKWebView</code> but when loaded via <code>URLSession</code> (or even a simple <code>NSString(contentsOf: url, encoding String.Encoding.utf8.rawValue)</code>) the UTF-8 conversion fails.</p>
  
  <h3>How to reproduce</h3>
  
  <p>This fails (prints "nil"):</p>
  
  <p><code>print(try? NSString(contentsOf: URL(string: "http://www.huffingtonpost.jp/techcrunch-japan/amazon-is-gobbling-whole-foods-for-a-reported-13-7-billion_b_17171132.html?utm_hp_ref=japan&amp;ir=Japan")!, encoding: String.Encoding.utf8.rawValue))
  </code></p>
  
  <p>But changing the URL to the site's homepage, it succeeds:</p>
  
  <p><code>print(try? NSString(contentsOf: URL(string: "http://www.huffingtonpost.jp")!, encoding: String.Encoding.utf8.rawValue))</code></p>
  
  <h3>Question</h3>
  
  <p>How can I "clean" the data returned by a URL that contains malformed UTF-8? I'd like to either remove or replace any invalid sequences in the malformed UTF-8 so that the rest of it can be viewed. WKWebView is able to render the page just fine (and claims it's UTF-8 content as well), as you can see by visiting the URL: <a href="http://www.huffingtonpost.jp/techcrunch-japan/amazon-is-gobbling-whole-foods-for-a-reported-13-7-billion_b_17171132.html?utm_hp_ref=japan&amp;ir=Japan" rel="nofollow noreferrer">http://www.huffingtonpost.jp/techcrunch-japan/amazon-is-gobbling-whole-foods-for-a-reported-13-7-billion_b_17171132.html?utm_hp_ref=japan&amp;ir=Japan</a></p>