当前位置:  开发笔记 > IOS > 正文

我可以在Swift框架库中使用Objective-C类吗?

如何解决《我可以在Swift框架库中使用Objective-C类吗?》经验,为你挑选了1个好方法。

我创建了一个我在多个项目中使用的Swift框架.有一个我想使用的Objectivce-C类很难直接移植到Swift中.让我们说这个课程是SFTest

@interface SFTest {
} 
+ (NString *)myMethod(NSString *data);
@end
@implementation SFTest
+ (NString *)myMethod(NSString *data) {
    // does some processing
    return processedData;
}
@end

我可以以某种方式在我的Swift框架项目中使用它,如果是的话,怎么样?我对此的研究提到了一些叫做桥接头的东西,但它们不能用在Swift框架中.



1> kailoon..:

所以这花了一段时间,但我终于在我的设备上运行了一些东西.这是我的设置.我创建了一个名为swiftlib的Swift框架.我添加了一个名为"MyClass"的Objective-C类.基本上它看起来像这样:

在此输入图像描述

然后我修改了"伞头"以导入我的新Objective-C类.伞标题是swift库项目的名称.所以在我的情况下,它是"swiftlib.h".这是我的伞头文件中的内容:

//
//  swiftlib.h
//  swiftlib
//

#import 
#import "MyClass.h"

//! Project version number for swiftlib.
FOUNDATION_EXPORT double swiftlibVersionNumber;

//! Project version string for swiftlib.
FOUNDATION_EXPORT const unsigned char swiftlibVersionString[];

// In this header, you should import all the public headers of your     framework using statements like #import 

确保将标题类设置为public,否则将出现编译错误.基本上,伞标题中包含的内容都暴露给您的swift框架的用户,因此它需要公开.选择MyClass.h并打开右侧详细信息栏并选择下拉列表:

在此输入图像描述

然后我在单个视图应用程序中使用此Swift框架进行测试,并且能够在AppDelegate.swift中使用我的Objective-C类,如下所示:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        let test = MyClass.myMethod()
        print("test = " + String(test))
        return true
    }

这在我的设备上编译并运行.

对于那些好奇的人来说,这是Objective-C MyClass的实现代码:

#import "MyClass.h"
#import 

@implementation MyClass

+ (NSString *)myMethod {
    NSString *key = @"test";
    NSString *data = @"mytestdata";
    const char *ckey = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cdata = [data cStringUsingEncoding:NSASCIIStringEncoding];
    unsigned char chmac[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, ckey, strlen(ckey), cdata, strlen(cdata), chmac);
    NSData *hmac = [[NSData alloc] initWithBytes:chmac length:sizeof(chmac)];
    NSString *hash = [hmac base64Encoding];
    return hash;
}

@end


你节省了我的一天^ _ ^
尚未成功。我也尝试了上述解决方案,但收到错误消息“ FrAmeworkNAme的框架模块内包含非模块头”,请帮帮我
推荐阅读
小妖694_807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有