title: Download a file using XHR in iOS Safari
body: <p>I am trying to add the functionality to download a file hosted in a server. To access the file I have to send the <code>Authorization</code> header, thus I have to send an XHR request to get the file from the server. Since the file content is in a variable, I have to create a data url to make it available as the <code>href</code> attribute of an anchor tag and click it programmatically to download the file.
  It's working good in almost all the browser (Except IE11, for which I have written a separate code), but in iOS Safari (in some versions of iOS), it's giving errors. Here's the code that I am using - </p>
  
  <pre><code>var isBrowserIE = window.navigator &amp;&amp; window.navigator.msSaveOrOpenBlob;
  var dataHref = 'https://example.com/doc.pdf';
  var xhr = new XMLHttpRequest();
  xhr.open('GET', dataHref, true);
  xhr.setRequestHeader('Content-Type', 'application/pdf');
  xhr.setRequestHeader('Authorization', 'Bearer ' + token);
  xhr.responseType = isBrowserIE ? 'blob' : 'arraybuffer';
  xhr.onload = function (e) {
      if (this.status == 200) {
          //For IE11
          if (isBrowserIE) {
              // Create a new Blob object using the response data of the onload object
              var blob = new Blob([this.response], { type: 'application/pdf' });
  
              var bool = window.navigator.msSaveOrOpenBlob(blob, docName);
              if (!bool) {
                  alert("Download failed, Please try again later");
              }
          } else {
              var uInt8Array = new Uint8Array(this.response);
              var i = uInt8Array.length;
              var binaryString = new Array(i);
              while (i--) {
                  binaryString[i] = String.fromCharCode(uInt8Array[i]);
              }
              var data = binaryString.join('');
  
              var base64 = window.btoa(data);
  
              var dataUrl = 'data:application/octet-stream;charset=utf-16le;base64,' + base64;
              var element = document.createElement('a');
              element.setAttribute('href', dataUrl);
              element.setAttribute('download', 'doc.pdf');
              element.style.display = 'none';
              document.body.appendChild(element);
              element.click();
              document.body.removeChild(element);
          }
      } else {
          alert("Download failed, Please try again later");
          closeWindow();
      }
  };
  
  xhr.send();
  </code></pre>
  
  <p>Here's the possible error I am getting which is related - </p>
  
  <p><code>Safari cannot open the page.&lt;br&gt;&lt;br&gt;The error was: “Data URL decoding&amp;nbsp;failed”.</code></p>
  
  <p>Is there anything I missed which is the reason for this error? The error is occuring only in iPad 4 and iPad 5, but working in iPad mini and iPhone XR. Not sure why is it working in some versions of iOS devices and not in others.</p>