Search code examples
iosswiftuipasteboardinstagram-story

SwiftUI UIPasteboard is cleared when posting to instagram-stories


I'm posting an Instagram story from my app and it works perfectly. But when I added a UIPasteboard string value where I store my URL, it's being cleared when I paste it in instagram link. What I notice is Instagram is clearing the paste board items when launched. Is there any way to keep the paste board items in Instagram? Here's my code snippet:

let urlScheme = URL(string:"instagram-stories://share")!
if UIApplication.shared.canOpenURL(urlScheme) {

    UIPasteboard.general.string = Global.hostURL // THIS GETS CLEARED
    
    let pasteBoardItems:Array<[String:Any]> = [
        ["com.instagram.sharedSticker.backgroundImage" : background.pngData()!]
    ]
    
    let expirationDate = Date().addingTimeInterval(60 * 5)
    let pasteBoardOptions = [UIPasteboard.OptionsKey.expirationDate: expirationDate]
    UIPasteboard.general.setItems(pasteBoardItems, options: pasteBoardOptions)
    
    UIApplication.shared.open(urlScheme)
}

Solution

  • UIPasteboard.general.setItems(pasteBoardItems, options: pasteBoardOptions)
    UIApplication.shared.open(shareURL, options: [:])
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        UIPasteboard.general.string = url.absoluteString
       // ☝️.setItems again 0.1s after opening Instagram.
      // or 0.2s, 0.25, 0.3 play around with it until it works.
      // Try to get a value that works 10/10 times. 0.1s wasn't as reliable as 0.2s
    
    }
    

    Alternative solution is after UIApplication.shared.open(shareURL, options: [:])

    Run UIPasteboard.general.string = url.absoluteString in the app delegate's applicationDidEnterBackground

    Or in SwiftUI's new lifecycle

    @Environment(\.scenePhase) var scenePhase
    ...
    .onChange(of: scenePhase) { scenePhase in
                switch scenePhase {
                case .background:
                        UIPasteboard.general.string = url.absoluteString
                    }