遇到的问题
平时很熟悉在Swift工程中使用Objective-C的方法,一个桥接头文件就搞定了。在写Swift Framework的时候很自然的就是先随意创建个oc文件,等待弹出是否需要自动创建桥接文件的提示。没出现! 手动添加也不生效!
那么如何在Swift的framework中使用OC的framework呢?
刚踩完坑,留个demo。
创建OC Framework
OCFramework为swift framework调用做配置
- 需要把给Swift调用的TestOCFramework.h添加到OCFramework.h中
- 设置OCFramework->BuildPhases->Headers
TestOCFramework
TestOCFramework.h
#import <Foundation/Foundation.h>
@interface TestOCFramework : NSObject
+(NSString *)hello;
@end
TestOCFramework.m
#import "TestOCFramework.h"
@implementation TestOCFramework
+(NSString *)hello {
return @"Objective-c hello";
}
@end
创建Swift Framework
SwiftFramework添加OCFramework.framework
添加OCFramework.frameworkimport OCFramework
添加需要调用的OCFramework的.hTestSwiftFramework
import UIKit
public class TestSwiftFramework: NSObject {
public class func hello() {
//测试调用OCFramework
if let ocHello = TestOCFramework.hello() {
print("TestSwiftFramework.hello load oc framework: \(ocHello)")
} else {
print("TestSwiftFramework load OCFramework failed")
}
}
}
SwiftFramework调用OCFramework就这样完成啦,分别创建OC和Swift的Demo来测试一下。
TestOCDemo
创建OC工程测试
OC测试工程添加Framework
添加使用的Framework为SwiftFramwork修改Build Settings
将Always Embed Swift Standard Libraries设置为Yes在AppDelegate调用SwiftFramework试试
#import "AppDelegate.h"
#import "SwiftFramework/SwiftFramework-Swift.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//测试调用SwiftFramework
[TestSwiftFramework hello];
return YES;
}
@end
日志
TestSwiftFramework.hello load oc framework: Objective-c hello
TestSwiftDemo
创建Swift工程测试
Swift测试工程添加Framework
添加Framework在AppDelegate调用SwiftFramework试试
import UIKit
import SwiftFramework
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//测试调用SwiftFramework
TestSwiftFramework.hello()
return true
}
}
日志
TestSwiftFramework.hello load oc framework: Objective-c hello
查看Demo源码
https://github.com/huhuegg/Demo/tree/master/UseOCFrameworkInSwiftFramework
网友评论
demo里面调用自己的oc framework,我试了是可以,但是用第三方的就失败。
1) Add @ObjC to Swift class
2) Add in .m
#import "(ProjectName)-Swift.h"
3) Call from .h
@class SwiftClass;
4)On SwiftClass
click "Command" + Left Click (Apple Documantation)
5) To see "-Swift.h" -> click "Command" + Left Click
/TestSwiftDemo Reason: image not found