3

SpriteKit用 xcode 创建了一个应用程序,当游戏结束时,它会显示你的分数,我想添加将你的分数发布到 facebook 的功能。几乎我所有的代码都在MyScene.m它无法访问的地方presentViewController。只有我的 ViewController.m 文件可以访问它,所以我尝试从 Myscene.m 调用 Viewcontroller 中的实例方法,但我找不到这样做的方法。我发现从其他文件调用方法的唯一方法是使用+(void)我认为的类方法。

Myscene.m:

    if (location.x < 315 && location.x > 261 && location.y < 404 && location.y > 361) {
 //if you click the post to facebook button (btw, location is a variable for where you tapped on the screen)

     [ViewController facebook];
                    }

视图控制器.m:

+(void)facebook{

    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
        SLComposeViewController *facebook = [[SLComposeViewController alloc] init];
        facebook = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

        [facebook setInitialText:@"initial text"];  
    }

    }

这样就成功了,它正确调用了facebook类方法,但是当我放在[self presentViewController:facebook animated:YES]setInitialText括号之后时,它给了我这个错误:选择器'presentViewController:animated:'没有已知的类方法

顺便说一句,它允许我presentViewController在实例方法中使用,但我不能从类方法内部或我的 Myscene 文件中调用该方法。有没有办法从另一个文件调用实例方法,或者presentViewController从类方法访问?谢谢

4

1 回答 1

3

您可以将 View Controller 的引用传递给您的 SKScene,也可以NSNotificationCenter改用。我更喜欢使用后者。

首先确保您已将 Social.framework 添加到您的项目中。

将社交框架导入您的视图控制器#import <Social/Social.h>

然后在 View Controller 的 viewDidLoad 方法中添加以下代码:

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

接下来将此方法添加到您的视图控制器:

-(void)createPost:(NSNotification *)notification
{
    NSDictionary *postData = [notification userInfo];
    NSString *postText = (NSString *)[postData objectForKey:@"postText"];
    NSLog(@"%@",postText);

    // build your tweet, facebook, etc...
    SLComposeViewController *mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
    [self presentViewController:mySLComposerSheet animated:YES completion:nil];

}

在您的 SKScene 中的适当位置(赢得比赛、输掉比赛等)添加以下代码:

NSString *postText = @"I just beat the last level.";
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:postText forKey:@"postText"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"CreatePost" object:self userInfo:userInfo];

上面的代码发送一个带有文本的 NSNotification,你的 View Controller 将获取并执行指定的方法。

于 2014-05-25T14:57:14.230 回答