How do I present UIViewController from SKscene with social framework?

后端 未结 1 1529
孤街浪徒
孤街浪徒 2021-01-29 03:45

I am making a game like Flappy Bird. How do I present a UIViewController from SKScene? First of all, I tell my environments

  • Mac OS X 10.9
  • Xcode 5.0.2
相关标签:
1条回答
  • 2021-01-29 04:25

    You cannot present a viewController from within a SKScene as it is actually only being rendered on a SKView. You need a way to send a message to the viewController, which in turn will present the viewController. For this, you can use delegation.

    Add the following protocol definition to your SKScene's .h file:

    @protocol sceneDelegate <NSObject>
    -(void)showShareScreen;
    @end
    

    And declare a delegate property in the interface:

    @property (weak, nonatomic) id <sceneDelegate> delegate;
    

    Then, at the point where you want to present the share screen, instead of the line:

    [self presentViewController:tweetSheet animated:YES completion:nil];
    

    Use this line:

    [self.delegate showShareScreen];
    

    Now, in your viewController's .h file, implement the protocol:

    @interface ViewController : UIViewController <sceneDelegate>
    

    And, in your .m file, add the following line before you present the scene:

    scene.delegate = self;
    

    Then add the following method there:

    -(void)presentShareScreen
    {
    
        if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
        {
            SLComposeViewController *tweetSheet = [SLComposeViewController
            composeViewControllerForServiceType:SLServiceTypeTwitter];
            [tweetSheet setInitialText:@"TestTweet from the Game !!"];
            [self presentViewController:tweetSheet animated:YES completion:nil];
    
        }
    }
    

    An alternate method would be to use NSNotificationCenter

    Keep the -presentShareScreen method as described in the previous alternative.

    Add the viewController as a listener to the notification in it's -viewDidLoad method:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentShareScreen) name:@"showShareScreen" object:nil];
    

    Then, in the scene at the point where you want to show this viewController, use this line:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"showShareScreen" object:nil];

    0 讨论(0)
提交回复
热议问题