如何在Swift中将故事发布到Facebook?

时间:2014-11-15 22:12:01

标签: ios facebook-graph-api swift

我到处搜索过,我无法找到任何关于如何在Swift中向Facebook发帖的文档。我试图将这个代码从Obj-C转换为Swift,但我还没有取得多大进展(我不知道如何在Obj-C中编码)。我希望在Swift中完成类似的事情:https://developers.facebook.com/docs/ios/graph#postingstory

以下是相关代码:

// Create a like action
id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject];

// Link that like action to the restaurant object that we have created
[action setObject:_objectID forKey:@"object"];

// Post the action to Facebook
[FBRequestConnection startForPostWithGraphPath:@"me/og.likes"
                               graphObject:action
                         completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                           __block NSString *alertText;
                           __block NSString *alertTitle;
                           if (!error) {
                             // Success, the restaurant has been liked
                             NSLog(@"Posted OG action, id: %@", [result objectForKey:@"id"]);
                             alertText = [NSString stringWithFormat:@"Posted OG action, id: %@", [result objectForKey:@"id"]];
                             alertTitle = @"Success";
                             [[[UIAlertView alloc] initWithTitle:alertTitle
                                                         message:alertText
                                                        delegate:self
                                               cancelButtonTitle:@"OK!"
                                               otherButtonTitles:nil] show];
                           } else {
                             // An error occurred, we need to handle the error
                             // See: https://developers.facebook.com/docs/ios/errors    
                           }
                         }];

基本上我正在寻找这段代码的Swift翻译。在我的实际应用程序中,我将为游戏发布一个高分(不喜欢餐馆),但如果我有一些Swift可以使用,我应该能够弄清楚。

提前致谢!

1 个答案:

答案 0 :(得分:1)

根据要求,这是我最终使用的方法。它没有使用FBOpenGraphAction,这使我在我的情况下实现起来要简单得多。 (注意:您需要使用FBLoginViewDelegate):

    // Initialize variables
    let name = "Purple Square"
    let link = "https://itunes.apple.com/us/app/purple-square/id942125866?ls=1&mt=8"
    let description = String(format: "I got %.1f. Can you beat me?", highScore)
    let picture = "https://www.dropbox.com/s/2nbaxai1arhqqrn/purpleSquareSplash.png?dl=1"
    let caption = "Exceptionally simple. Deceivingly hard. Ridiculously addictive."

    // Add variables to dictionary
    var dict = NSMutableDictionary()
    dict.setValue(name, forKey: "name")
    dict.setValue(caption, forKey: "caption")
    dict.setValue(description, forKey: "description")
    dict.setValue(link, forKey: "link")
    dict.setValue(picture, forKey: "picture")

    // Present the feed dialog and post the story
    FBWebDialogs.presentFeedDialogModallyWithSession(nil, parameters: dict, handler: nil)