美文网首页
iOS组件化踩坑

iOS组件化踩坑

作者: 忧郁的小码仔 | 来源:发表于2018-01-11 15:16 被阅读690次

    之前写过一片组件化和创建私有pod的文章组件化和私有pod源仓库,这几天碰到一个比较庞大的项目,终于有机会来真正的实施组件化了。

    这里还是沿用Casa Taloyum的组件化思想,记录下组件化过程中遇到的问题。

    1. 关于pod私有源

    还碰到有朋友问pod私有源的问题。私有pod源就像一本书的目录一样,用来索引你的私有pod,它和CocoaPods公有源一样.

    2.组件中OC与Swift混编的问题

    首先,就是桥接文件的问题,在.podspec文件中这样指定桥接文件即可

      s.public_header_files = 'SwiftDemo/TargetA/*.h'
    

    再就是OC运行时中使用Swift类的问题。用NSClassFromString来获取Swift类的时候,需要在Swift类前添加名字空间,比如要获取组件TargetA中的类,就需要这样写TargetA.Swift类名

    3.资源问题

    当我们要在组件中使用storyboard, 图片,音视频等资源文件时,需要在.podspec中指定资源文件的位置

      s.resources = ['SwiftDemo/TargetA/TargetA.storyboard', 'SwiftDemo/*.xcassets']
    

    同时,用Bundle去获取各个资源,比如,要获取某个storyboard:

    let bundle = Bundle(for: self.classForCoder)
    let storyBoard = UIStoryboard.init(name: "TargetA", bundle: bundle)
    

    这里,组件中的资源不是被拷贝到mainbundle中,所以如果用Bundle.main或者不设置bundle是获取不到组件中的资源的。pod最终会把组件打包成framework,组件中的所有资源也会拷贝到这个framework的bundle下。这里通过Bundle(for: self.classForCoder)来获取当前类所在的framework下的bundle。

    注:
    还有一个s.source_bundles命令可以替代s.source用来给资源文件生成一个指定的bundle,暂时没有使用,比如:

    s.resource_bundles = {
      'MyLibrary' => ['Resources/*.png'],
      'OtherResources' => ['OtherResources/*.png']
    }
    

    后面要获取资源,就要像下面这样先获取对应的bundle:

    NSBundle *bundle = [NSBundle bundleForClass:[MYSomeClass class]];
    NSBundle *bundle = [bundle URLForResource:@"MyLibrary" withExtension:@"bundle"];
    

    这里有篇不错的文章专门介绍给 Pod 添加资源文件

    4. 当组件依赖私有pod时,如何验证组件的podspec正确性

    一般情况下,用下面的命令来验证podspec文件的正确性:

    pod spec lint AAA.podspec --verbose --allow-warnings
    

    当组件依赖私有pod时,我们要指定私有Pod源的地址:

    pod spec lint AAA.podspec --sources=https://gitee.com/SiYouKaiYuan/LjPrivateSpecs.git --verbose --allow-warnings
    

    5. podfile中的私有pod

    当我们在podfile中指定私有pod的同时,需要指定私有pod所在私有pod源的地址,同时,一旦我们自己指定了私有pod源,就需要指定公有源的地址。

    # Uncomment the next line to define a global platform for your project
    # platform :ios, '9.0'
    
    source 'https://gitee.com/SiYouKaiYuan/LjPrivateSpecs.git'
    source 'https://github.com/CocoaPods/Specs.git'
    
    target 'MainProject' do
      # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
      use_frameworks!
    
      # Pods for MainProject
      pod 'TargetA'
    end
    
    

    6. 使用__weak的问题

    /Users/archerlj/Desktop/myProjects/xiaodai/anshipai/Pods/LFAlert/LFAlert/LFAlert/LFAlert.h:21:28: Cannot create __weak reference because the current deployment target does not support weak references
    

    有时候在组件中如果使用了__weak关键字,然后podspec文件中又没有指定iOS支持的最低版本,使用组件的时候就会报错,因为iOS 5.0之前不支持ARC和weak reference。所以只需要在podspce文件中指定iOS支持的最低版本即可:

      s.platform     = :ios, "5.0"
    

    如需demo,请私信。

    加油站加盟

    相关文章

      网友评论

          本文标题:iOS组件化踩坑

          本文链接:https://www.haomeiwen.com/subject/oczznxtx.html