title: Sending file to iCloud
body: <p>This is a problem I could not find a satisfactory solution anywhere (including here). I just want to upload a text file created in my app to a folder in iCloud, where I'll be using it for other purposes. As far I could learn, this could be done by (1) setting iCloud capabilities in app target Signing&amp;Capabilities, (2) providing the necessary entry for NSUbiquitousContainers in plist, and (3) get the url for the UbiquitousContainer in my app as the address where to send my file (with some modifications).</p>
  <p>In order to test this scheme, I set up a very simple test app named SaveToiCloud, in which I have:</p>
  <p>1 - iCloud Signing&amp;Capabilities:</p>
  <p><a href="https://i.stack.imgur.com/s6PMx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s6PMx.png" alt="enter image description here" /></a></p>
  <p>2 - entry added plist:</p>
  <pre><code>&lt;key&gt;NSUbiquitousContainers&lt;/key&gt;
      &lt;dict&gt;
          &lt;key&gt;iCloud.com.oscarjs.SaveToiCloud&lt;/key&gt;
          &lt;dict&gt;
              &lt;key&gt;NSUbiquitousContainerIsDocumentScopePublic&lt;/key&gt;
              &lt;true/&gt;
              &lt;key&gt;NSUbiquitousContainerName&lt;/key&gt;
              &lt;string&gt;SaveToiCloud&lt;/string&gt;
              &lt;key&gt;NSUbiquitousContainerSupportedFolderLevels&lt;/key&gt;
              &lt;string&gt;Any&lt;/string&gt;
          &lt;/dict&gt;
      &lt;/dict&gt;
  </code></pre>
  <ol start="3">
  <li><p>ViewController:</p>
  <p>import UIKit</p>
  <p>class ViewController: UIViewController {</p>
  <pre><code> override func viewDidLoad() {
       super.viewDidLoad()
  
       let path = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent(&quot;Documents&quot;)
       let filePath = path!.appendingPathComponent(&quot;test.txt&quot;)
       do {
           try? &quot;Hello world&quot;.data(using: .utf8)?.write(to: filePath)
       } catch {
           print(error)
       }
   }
  </code></pre>
  <p>}</p>
  </li>
  </ol>
  <p>When I run the app, it crashes at the line below, because path is nil. No matter I tried many solutions, the results were always getting path = nil. For all I could gather, the problem seems related to the plist entry, for whicht I could not find a solution, but maybe I'm wrong with this guess. Can anyone help me?</p>
  <pre><code>let filePath = path!.appendingPathComponent(&quot;test.txt&quot;)
  </code></pre>