跳至主要内容

优雅的开发Swift和Objective C混编的Framework

原文链接

前言

为什么要写这样一篇文章,因为昨天和一个朋友讨论到Swift和Objective C如何混合开发Framework,中途发现了很多有意思的坑。
用Swift封装OC的库是一件比较常见的事情,毕竟对于大多数公司来说,老的代码都是用OC写的,而且经过多次迭代,这些OC的代码已经被验证了是稳定的,用Swift重写代价太大。这就引入了一个需求:
  • 用Swift和OC来混编一个Framework。
如果你之前没有用Swift和Objective C混合开发,建议看看这篇文档:
这篇文档很详细的讲解了如何运用Objective C和Swift进行混合开发App和Framework。于是,我们先按照文档来写一个混编的Framework

按照文档一步一步来

新建一个基于单页面工程,然后新建一个一个Target,选中Cocoa Touch Framework。然后,分别新建一个Swift文件和Objective C类,注意Target Member Ship选中Framework。类的内容如下:
OCSource.h
#import <Foundation/Foundation.h>

@interface OCSource : NSObject
- (void)functionFromOC;
@end

OCSource.m
#import "OCSource.h"

@implementation OCSource

- (void)functionFromOC{
    NSLog(@"%@",@"Log from objective c in framework");
}
@end


Swift调用OC

新建SwiftSource.swift
open class SwiftIt{
    public init(){}
    let ocObject = OCSource()
    public func encapsulate(){
        ocObject.functionFromOC()
    }
}
然后,按照文档中,为了让Swift文件访问Objective C文件,我们应该在umbrella header,也就是MixFramework.h中,暴露所需要的header。
也就是,MixFramework.h,
#import <MixFramework/OCSource.h>
然后,自信满满的点击build。
Boom~~~,编译不通过。
原因:OCSource.h默认编译的时候是Project权限. 为了在umbrella header中使用,要把这个文件的权限改成Public
按照图中的方式拖过去即可。
嗯,现在build,可以看到build成功了。

OC调用Swift

在SwiftSource.swift中,增加一个类,
open class ClassForOC:NSObject{
    public static let textForOC = "textForOC"
}
然后,为了在OC中调用Swift的方法,我们需要导入头文件,这时候,OCSource.m文件内容如下
#import "OCSource.h"
#import <MixFramework/MixFramework-Swift.h>

@implementation OCSource

- (void)functionFromOC{
    NSLog(@"%@",[ClassForOC textForOC]);
}
@end
然后,build,发现成功了,很开心。

外部调用

在ViewController.swift中,我们调用Framework中的内容。
import MixFramework
class ViewController: UIViewController {
    var t = SwiftIt()
    override func viewDidLoad() {
        super.viewDidLoad()
        t.encapsulate()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

然后运行,发现控制台打印出
2017-03-02 16:08:24.000 HostApplication[19524:167669] textForOC
嗯,framework打包成功了。

问题

通常,我们希望暴露给外部的接口是纯Swift,而OC文件的具体接口应该隐藏,这就是我标题中的优雅两个字的含义。
如果你好奇,你会发现,在ViewController.swift中你可以这么调用
    var s = OCSource()
也就是说,OC的内容也暴露出来了,这破坏了Framework的封装特性
通过查看MixFramework的编译结果,发现最后暴露出的接口是这样子的
import Foundation
import MixFramework.OCSource
import MixFramework
import MixFramework.Swift
import SwiftOnoneSupport
import UIKit

//
//  MixFramework.h
//  MixFramework
//
//  Created by Leo on 2017/3/2.
//  Copyright © 2017年 Leo Huang. All rights reserved.
//

//! Project version number for MixFramework.
public var MixFrameworkVersionNumber: Double
open class ClassForOC : NSObject {

    public static let textForOC: String
}

open class SwiftIt {

    public init()

    public func encapsulate()
}


这一行,把OC对应的实现暴露出来了
import MixFramework.OCSource

优雅的解决方案

不再通过umbrella header的方式让framework中的Swift调用OC方法。而是通过modulemap
新建一个module.modulemap文件,内容如下

module OCSource [system] {
    //由于module.modulemap和OCSource.h是在同一个文件夹的,如果不是同一个,路径要写全
    header "OCSource.h"
    export *
}
这里的#(SRCROOT)是XCode的宏,会自动替换成项目所在的根目录,这里输入的路径是module.modulemap文件所在的路径。
然后,删除MixFramework.h(umbrella header)中#import 的OC header。
把OCSource.h的权限改回默认的project。
再编译,发现OC的类被隐藏了。

转注:在使用ObjC类的Swift单元中需要添加"import OCSource"才可编译成功。

总结

如果你要开发一个framework,一定要想清楚哪些接口暴露出去,哪些封装起来,framework不是简单把一包文件加个壳子。

评论

此博客中的热门博文

Resolving errSecInternalComponent errors during code signing

原文链接 One code signing issue I commonly see, both here on DevForums and in my Day Job™ with DTS, is that the codesign command fails with errSecInternalComponent. This issue crops up in a wide variety of circumstances and the correct fix depends on the specific problem. This post is my attempt to clarify the potential causes of this error and help folks resolve it. If you have any questions or comments about this, please start a new thread, tagging it with Code Signing so that I see it. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Resolving errSecInternalComponent errors during code signing In some circumstances the codesign command might fail with the error errSecInternalComponent. For example: % codesign -s "Apple Development" "MyTrue" MyTrue: errSecInternalComponent This typically affects folks who are signing code in a nonstandard environm...

iOS:检测使用VPN或Proxy

参考链接: https://www.jianshu.com/p/c3b950dbf86a https://gist.github.com/PramodJoshi/4faad4c91f7dcb4eb9b06be8390c01db http://noodlecode.net/2018/04/check-if-ios-app-is-connected-to-vpn 第一种方法 需要导入框架CFNetwork 然后,这个方法是mrc的:需要添加-fno-objc-arc的flag 代码如下: + ( BOOL )getProxyStatus { NSDictionary *proxySettings = NSMakeCollectable ([( NSDictionary *) CFNetworkCopySystemProxySettings () autorelease]); NSArray *proxies = NSMakeCollectable ([( NSArray *) CFNetworkCopyProxiesForURL (( CFURLRef )[ NSURL URLWithString: @"http://www.google.com" ], ( CFDictionaryRef )proxySettings) autorelease]); NSDictionary *settings = [proxies objectAtIndex: 0 ]; NSLog ( @"host=%@" , [settings objectForKey:( NSString *)kCFProxyHostNameKey]); NSLog ( @"port=%@" , [settings objectForKey:( NSString *)kCFProxyPortNumberKey]); NSLog ( @"type=%@" , [settings objectForKey:( NSString *)kCFProxyTypeKey]); if ([[settings object...

去广告DNS设置,国内ADGuard DNS方案,手机电脑iOS去广告,保护隐私

 原文链接 之前分享过使用mac系统搭建adguard home,这几个月用下来零零散散基本上也被弃用了。主要原因是因为需要保持电脑一直开机。但是我的电脑是笔记本,存在移动各个地域的情况,也就是说只能够屏蔽电脑自身,对于手机而言不太现实。今天偶然发现dnspod推出了高级版的公共解析。dnspod背靠腾讯云,肯定是合法合规的公共解析服务,这个高级版用起来不错。 国内自己搭建解析服务是违法行为,所以这也是为什么使用dnspod的原因。 后台截图 开始使用 首先我们先进入dnspod的公共解析页面,点击开始使用。 专业版公共解析 dnspod会提供几种预设,我们选择「开发者」即可 开发者 然后你就成功的申请到自己个人使用的dns了! 更新拦截规则 我们可以将常见的广告过滤规则加入到dns中。我们在顶部选项卡中选择「拦截规则」。 拦截规则设置 打开adguard adguard 绑定iOS设备 推荐使用描述文件的方式,删除配置时删除描述文件即可。 描述文件 绑定macOS 推荐使用描述文件的方式,删除配置时删除描述文件即可。 描述文件 mac需要在「系统偏好设置」的「网络」中查看是否正在运行。 代理 如果没有运行需要点击「···」来启动服务。 启动服务 绑定路由器 找到自己路由器的DHCP设置,修改dns,然后记得绑定自己的ip。 修改dns 绑定ip 费用 目前有300万次/月的免费额度,但没有超出之后的价格。300万次一个人比较难用完,可以放心使用。 我个人使用iOS设备两台、智能家居、电脑两台,日均请求数大致2万/日。 判断是否搭建成功 可以通过查看日志的方式,日志大概有半小时到一小时的延迟,请耐心等待。