title: How to retrieve text from UIPasteboard after entering background, copying new text, and returning to the app?
body: <p>I'm trying to access the most recent item in <code>UIPasteboard</code>, specifically, the problem that I face is when I background the app, copy another piece of text and come back to the app, I'm seeing the <code>UIPasteboard.general.string</code> return nil. Now I've read that the reason it reads nil when I return to the app is that it is a new security measure implemented by Apple, but, is there any reliable way to circumvent this behavior?</p>
  
  <p>I've seen several apps that allow the user to copy and paste as much as they want, regardless if they backgrounded the app or not, so I know it is possible to do this but I can't seem to find anything on the internet.</p>
  
  <p>Here's an example of the code I'm using that prints nil:</p>
  
  <pre><code>@objc func pasteText() {
      print("Here's the string: \(UIPasteboard.general.string)")
      if let pasteboardText = UIPasteboard.general.string {
          self.searchBar.text = pasteboardText
      }
  }
  </code></pre>
  
  <p>After copying new text and coming back to the app, when I press my paste button the console reads <strong>Here's the string: nil</strong>. I'm not doing anything special just accessing the string directly from the UIPasteboard.</p>
  
  <p>Accessing the clipboard is pretty straightforward so I don't think I'm doing that wrong. I think maybe I have to write some code in the <code>AppDelegate</code> to retrieve the recently copied text after coming back into the app from the background? Is this a viable approach?</p>
  
  <p>Any guidance will be greatly appreciated.</p>
  
  <p>The pasting function only works after I copy some text outside of the app, press the sleep button and then navigate back to the app, only then does the most recent item in UIPasteboard update correctly and function like normal. Not really sure why my app has this behavior though.</p>
  
  <p><strong>Fixed My Issue:</strong></p>
  
  <p>Seems like no one else is having an issue accessing text from the UIPasteboard but for my case, I solved the issue. For me, it seems like the <code>UIPasteboard.general.string</code> was being set to nil shortly after coming back into the app, but in my <strong>appdelegate</strong> lifecycle method <strong>applicationWillEnterForeground</strong> it looks like upon returning to the app the correct, the copied text is briefly maintained. The simple solution I came up with was setting the <code>UIPasteboard.general.string</code> to itself, the code below explains it all:</p>
  
  <pre><code>if let recentlyCopiedText = UIPasteboard.general.string {
      UIPasteboard.general.string = recentlyCopiedText
  }
  </code></pre>
  
  <p>When I reference the <code>UIPasteboard.general.string</code> later, it pastes the correct value. Hopefully, this helps someone if they ever have trouble reading from the UIPasteboard.</p>