Search code examples
swiftappdelegateuipasteboardios-background-mode

UIPasteboard returns nil in the background


I am trying to read the Pasteboard for 5 times in the applicatioDidEnterBackground section of the AppDelegate. To print the string I use print(UIPasteboard.general.string!) but it works only into the function and it doesn't in the other nested functions. Let me explain:

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    print(UIPasteboard.general.string!) //here it works perfectly and prints the string correctly

    for _ in 0...5 {
       print(UIPasteboard.general.string!) //here it returns nil 
    }

}

I have read other asks similar to the mine but no one of that helped me. I don't know if this is a security restriction, but if you can help me I'll appreciate 🙂


Solution

  • iOS 9 changed UIPasteboard to disallow background access:

    Presumably they made this change to prevent background apps from spying on your pasteboard contents. Sometimes people use the pasteboard to copy a password from one app to another, so blocking background pasteboard access is a security issue.

    Also, some apps (like Facebook) are known to collect as much data about the user as possibly while having much looser privacy policies than Apple's. Blocking background pasteboard access is a way to reduce Facebook's ability to spy on your non-Facebook activities.