在OC工程中接入纯swift二方库时二方库开发者提供了swift开发代码示例,因此如何在本项目的OC工程中引入swift文件并引用成为了现在面临的一个问题。(本博客未记录OC工程引入swift打包编译阶段需修改的内容)
1. OC工程中引入swift文件并调用
1. podspec文件中增加对应二方库及 修改source_files,确保新增的swift文件可以pod之后引入到工程中。代码示例:
source_files = '**/Overseas/**/*.{h,m,mm,c,swift}','**/Common/**/*.{h,m,mm,c,swift}'
2. 增加swift文件及相关逻辑
脱敏后文件框架:
swift
//
//
// Created by hanhaonan on 2024/2/6.
//
import Foundation
public class SomeIntegration : NSObject {
let someService : ObjectService
//对象实例化时自动调用
public override init() {
someService = ****
}
@objc
public func updateStatus(value0: String, value1: Int, value2: String) {
****
someService.updateStatus(param0: value0, param1: value1, param2: value2)
}
}
3. OC文件中调用Swift代码
OC
//***表示模块名称
#import "***-Swift.h"
//实例初始化
SomeIntegration* consentService = [[SomeIntegration alloc] init];
//updateStatus方法调用
[someService updateStatusWithvalue0: consentKey1 value1:0 value2:@"check_box"];
4. Swift文件中引入OC功能
新增 模块名称-Bridging-Header.h文件,后续Swift将通过该文件作为乔阶层调用OC代码。
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import <SDKCoreKit/NetworkManager.h>
#import <SDKCoreKit/SDKURLConfig.h>
5. Swift文件中调用OC逻辑
Swift文件在调用OC相关逻辑时无需再次进行头文件引入,sync之后乔阶层中OC头文件中相关方法可以直接在引用处调用。例如:
public class SomeNetworkManager: ObjectNetworkManager {
public func requestJSON(path: String,
method: String,
params: [String : Any]?,
completion: (([String: Any]?, Error?) -> Void)?) {
var logID: String
let url = URLConfig.sharedInstance().getSDKUrl+path
var params = params;
params?["**"] = "***";
if(method == "GET"){
NetworkManager.shareInstance().getTaskForJSON(withURL: url, headers: headers as! [AnyHashable : Any], params: params as! [AnyHashable : Any], callback: { error, jsonObj in
if ((error == nil)) {
var dic = jsonObj as! [String : Any];
completion?(dic as! [String : Any], nil)
} else {
completion?(nil, error)
}
})
} else {
NetworkManager.shareInstance().postTaskForJSON(withURL: url, headers: headers as! [AnyHashable : Any], params: params as! [AnyHashable : Any], callback: { error, jsonObj in
if ((error == nil)) {
var dic = jsonObj;
completion?(dic as! [String : Any], nil)
} else {
completion?(nil, error)
}
})
}
}
}