从Swift调用Objective C方法

时间:2014-06-25 18:51:58

标签: objective-c xcode facebook swift

我一直收到这个错误:

<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
Command /Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254

我想做什么: 用facebook登录。我有用于登录的客观C代码(来自他们的示例项目),但我使用的是Swift,因为我不知道Objective C。

如何从swift调用目标C方法?

这是我的目标C代码:

// If the session state is any of the two "open" states when the button is clicked
    if (FBSession.activeSession.state == FBSessionStateOpen
        || FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {

        // Close the session and remove the access token from the cache
        // The session state handler (in the app delegate) will be called automatically
        [FBSession.activeSession closeAndClearTokenInformation];

        // If the session state is not any of the two "open" states when the button is clicked
    } else {
        // Open a session showing the user the login UI
        // You must ALWAYS ask for public_profile permissions when opening a session
        [FBSession openActiveSessionWithReadPermissions:@[@"public_profile"]
                                           allowLoginUI:YES
                                      completionHandler:
         ^(FBSession *session, FBSessionState state, NSError *error) {

             // Retrieve the app delegate
             AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
             // Call the app delegate's sessionStateChanged:state:error method to handle session state changes
             [appDelegate sessionStateChanged:session state:state error:error];
         }];
    }

我的快捷代码:

var bridgeForFacebook: Bridge = Bridge()

@IBAction func fbSubmit(sender: AnyObject) {
    bridgeForFacebook.signIn();
}

1 个答案:

答案 0 :(得分:0)

可能是代码文件没有正确地看到,因此无法正常播放。

当您在Swift文件中使用Objective-C代码时,您需要将Objective-C类中的标头桥接到Swift中。通常,这是在您创建新的Objective-C文件时自动完成的。

您需要创建一个名为(your project name)-Bridging-Header.h的Objective-C标题文件。在该文件中,编写#import语句并导入要在Swift中访问的任何Objective-C类的标题文件。

现在转到您的项目构建设置并找到&#34; Objective-C Bridging Header&#34; &#34; Swift编译器 - 代码生成&#34;部分。在那里,填写新桥接文件的相对路径(应为(project name)/(project name)-Bridging-Header.h)。

然后你的类和方法调用应该按预期工作。

来源:Swift with Cocoa, Swift and Objective-C in the Same Project