Search code examples
iosswiftuiactivityviewcontroller

Posting to correct Instagram Account with UIActivityViewController


I am using UIActivityViewController to post images to Instagram app from MY app.

Please note my app does not use Instagram API or log in to users' Instagram Account.

let sharingImage = button.backgroundImage(for: [])
let avc = UIActivityViewController(activityItems: [sharingImage as AnyObject], applicationActivities: nil)

avc.excludedActivityTypes = [.addToReadingList,.airDrop,.assignToContact,.copyToPasteboard,.openInIBooks,.postToFacebook,.postToFlickr,.postToTencentWeibo,.postToTwitter,.postToVimeo,.postToWeibo,.saveToCameraRoll,.message,.mail,.print]
if let wPPC = avc.popoverPresentationController {
    wPPC.sourceView = followUsButton
}
self.present(avc, animated: true, completion: nil)

I am logged into my Instagram App with multiple accounts. Upon share from MY app, Instagram tries to post to the account 'A' which is currently logged in (inside the Instagram app). This makes sense.

However, if I now switch to the Instagram app and switch to account 'B' inside it, go back to MY app and then try to share again, it continues to try to post to Account 'A'.

The only way to fix it, is to kill MY app and start it again and then it loads the correct currently logged in account 'B'.

Is there a way to programmatically reload the correct Insta account while sharing?


Solution

  • This is only a workaround however might be your only choice at the moment as you see that even native Photos has the same issue so it is rather down to Apple to fix it.

    In your application's Info.plist, add a boolean key UIApplicationExitsOnSuspend with the value YES. See the Information Property List Key Reference for more information.

    This way the app is getting terminated when enters a background state and once you go back to it it will get reloaded. The user might not notice the difference.

    Perhaps before killing the app you could add some interface state saving function in:

     optional func applicationWillTerminate(_ application: UIApplication)
    

    I don't know how your app is laid out but you could create a singleton class which could be implementing Codable and keep tracking all the app state variables which would have a save and load function. Saving would be triggered upon termination and loading when app is launching.

    I hope it will help in some way.

    EDIT1: Should work in iOS 13 Below this code should work and terminate your app however it is not recommended and you might face an issue when uploading to AppStore. I guess you can challenge the rejection with the Apple review team by explaining that they have a bug in the SDK and point them to the problem.

    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
        UIApplication.shared.perform(#selector(NSXPCConnection.suspend))
         DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
          exit(0)
         }
    }