Macehil
Macehil

Reputation: 69

Displaying UIActivityViewController in GameScene.swift

I have developed a little game which consists of the main menu, the game itself and there is a game over label. My Problem is that I have added everything programmatically in the GameScene.swift file.

Now I can present an UIActivityViewController using this lines of code:

class GameScene: SKScene, SKPhysicsContactDelegate {

var gameViewController: GameViewController!

In GameViewController.swift I put this code in the viewDidLoad() function:

scene.gameViewController = self

And then I added the following function to my GameScene.swift file:

func share()
{
    if gameViewController != nil {
        let myText = "some text"

        let activityVC:UIActivityViewController = UIActivityViewController(activityItems: [myText], applicationActivities: nil)

        gameViewController.presentViewController(activityVC, animated: true, completion: nil)
    }
}

This function is executed by a button which I added programmatically and everything works when I launch the app. But when I play my game and hit the replay button and the GameScene gets reloaded I get the following message when I hit the share button:

fatal error: unexpectedly found nil while unwrapping an Optional value

Please help me!

Upvotes: 2

Views: 420

Answers (1)

Macehil
Macehil

Reputation: 69

Ok I've found the answer after hours.

I didn't use the gameViewController variable which I have declared on the top of GameScene.swift file. Instead I've used the following lines of code:

func share()
{
    let vc = self.view?.window?.rootViewController

    let myText = "test"

    let activityVC:UIActivityViewController = UIActivityViewController(activityItems: [myText], applicationActivities: nil)

    vc?.presentViewController(activityVC, animated: true, completion: nil)

}

The answer to my question is really simple and I hope I can help somebody with my solution.

Upvotes: 2

Related Questions