在编写pod时,想要让自己的pod能在AppExtension中使用,经常会碰上API在Extension中不兼容的情况,例如:
// statusBar 高度
public let STATUSBARHEIGHT: CGFloat = UIApplication.shared.statusBarFrame.height
这句代码在AppExtension下编译会报错:
'shared' is unavailable in application extensions for iOS: Use view controller based solutions where appropriate instead.
然而在开发AppExtension时并不需要考虑StatusBar的高度,所以在Extension下不需要使用UIApplication.shared ,给STATUSBARHEIGHT赋值为零就好。如下:
// statusBar 高度
public let STATUSBARHEIGHT: CGFloat = 0.0
所以理想的代码应该是:
#if IN_APP_EXTENSIONS
//如果是在AppExtension下编译,直接给STATUSBARHEIGHT赋值为零
public let STATUSBARHEIGHT: CGFloat = 0
#else
public let STATUSBARHEIGHT: CGFloat = UIApplication.shared.statusBarFrame.height
#endif
如何定义宏IN_APP_EXTENSIONS?
一、在Spec创建子spec
Pod::Spec.new do |s|
s.name = 'MYLib'
s.version = '0.1.0'
s.source_files = 'MYLib/Classes/**/*'
#默认使用Core,即不指定子路径的时候,直接使用Core的路径下的内容
s.default_subspec = 'Core'
s.subspec 'Core' do |core|
core.source_files = 'MYLib/Classes/**/*'
end
#AppExtension使用此路径
s.subspec 'AppExtension' do |ext|
ext.source_files = 'MYLib/Classes/**/*'
# 使用IN_APP_EXTENSIONS来判断是否AppExtesion
ext.pod_target_xcconfig = { 'OTHER_SWIFT_FLAGS' => '-D IN_APP_EXTENSIONS' }
end
end
为自己的pod 创建了AppExtension子目录,在podfile中使用pod 'MYLib/AppExtension'
时,会以s.subspec 'AppExtension'安装此pod。
pod_target_xcconfig = { 'OTHER_SWIFT_FLAGS' => '-D IN_APP_EXTENSIONS' }
这一行就是今天的主角,在pod install时,会自动给 MYLib-AppExtension这个Target 增加Swift环境变量 IN_APP_EXTENSIONS。

二、Podfile中给AppExtension指定pod路径
target 'MYLib_Example' do
pod 'MYLib'
end
target 'today' do
pod 'MYLib/AppExtension'
end
为 today Extension指定了 MYLib 仓库的路径,在 today Extension 中使用时,只能使用 ext.source_files 中的类。这里ext.source_files 和 core.source_files 都是指向同一目录,所以使用的都是同一份代码。
二者的区别是:MYLib-AppExtension 能使 IN_APP_EXTENSIONS 生效,而MYLib不能
网友评论