evorg88
evorg88

Reputation: 215

GameScene Share Button

my game is pretty much ready to go, the only thing I am missing (and would like to add) is the option to share a standard message to social media. I have looked around and found different ways of doing this but none of them seem to work when I implement them. I've got a feeling it might be something simple that I'm doing wrong!

Here's my button:

func createShareButton() {
    shareButton = SKSpriteNode(imageNamed: "shareBtn")
    shareButton.size = CGSize(width: 240, height: 55)
    shareButton.position = CGPoint(x: self.frame.width / 2, y: (self.frame.height / 2) - 150)
    shareButton.zPosition = 6
    self.addChild(shareButton)
    shareButton.run(SKAction.scale(to: 1.0, duration: 0.3))
}

And here's my code when the button is pressed (inside my GameScene.swift file):

let vc = self.view?.window?.rootViewController
                let myText = "share test message!"
                let activityVC:UIActivityViewController = UIActivityViewController(activityItems: [myText], applicationActivities: nil)
                vc?.present(activityVC, animated: true, completion: nil)

When I tap the button I get an error in the console:

Warning: Attempt to present <UIActivityViewController: 0x149d4e880> on <MyGame.initialVC: 0x149d0fe90> whose view is not in the window hierarchy!

Any ideas where I am going wrong?

Thanks in advance!

Upvotes: 0

Views: 118

Answers (1)

ivan1ne
ivan1ne

Reputation: 46

I ran into this same issue two days ago. I fixed it using this stackoverflow answer

I kept getting the same error and it was because rootViewController was not the current top viewController in the hierarchy. It was trying to use my initial viewController when I wanted the viewController in control of the current SKScene.

Hope this helps

    func shareGame() {
        if var top = scene?.view?.window?.rootViewController {
            while let presentedViewController = top.presentedViewController {
                top = presentedViewController
            }
            let activityVC = UIActivityViewController(activityItems: ["I am playing Crashbox! Check it out."], applicationActivities: nil)
            activityVC.popoverPresentationController?.sourceView = view 
            top.present(activityVC, animated: true, completion: nil)
        }
    }

Upvotes: 3

Related Questions