kai*_*oon 12 objective-c ios swift
我创建了一个我在多个项目中使用的Swift框架.有一个我想使用的Objectivce-C类很难直接移植到Swift中.让我们说这个课程是SFTest
@interface SFTest {
}
+ (NString *)myMethod(NSString *data);
@end
@implementation SFTest
+ (NString *)myMethod(NSString *data) {
// does some processing
return processedData;
}
@end
Run Code Online (Sandbox Code Playgroud)
我可以以某种方式在我的Swift框架项目中使用它,如果是的话,怎么样?我对此的研究提到了一些叫做桥接头的东西,但它们不能用在Swift框架中.
kai*_*oon 34
所以这花了一段时间,但我终于在我的设备上运行了一些东西.这是我的设置.我创建了一个名为swiftlib的Swift框架.我添加了一个名为"MyClass"的Objective-C类.基本上它看起来像这样:
然后我修改了"伞头"以导入我的新Objective-C类.伞标题是swift库项目的名称.所以在我的情况下,它是"swiftlib.h".这是我的伞头文件中的内容:
//
// swiftlib.h
// swiftlib
//
#import <UIKit/UIKit.h>
#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 <swiftlib/PublicHeader.h>
Run Code Online (Sandbox Code Playgroud)
确保将标题类设置为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
}
Run Code Online (Sandbox Code Playgroud)
这在我的设备上编译并运行.
对于那些好奇的人来说,这是Objective-C MyClass的实现代码:
#import "MyClass.h"
#import <CommonCrypto/CommonCrypto.h>
@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
Run Code Online (Sandbox Code Playgroud)