CocoaPod 入门

5,046 阅读3分钟

使用 cocoapod

  1. 进入项目中和.xcodeproj同级的文件夹,创建 Podfile
touch Podfile
  1. 编辑 Podfile
# Uncomment this line to define a global platform for your project

platform :ios, '8.0'

target 'TestCocoaPods' do
  pod 'SDWebImage', '~> 4.3.2'
end

版本号有多种表示方式,其中:

  1. '>=1.0' 最低版本号为1.0
  2. '<=1.0' 最高版本号为1.0
  3. '~>1.0' 兼容1.0的版本的最新版本

使用私有库

# 注意替换私有git域名
pod 'ProjectName', :git=>"https://XXX.git"

使用本地库

pod 'CocoaPodDemo', :path => '../CocoaPodDemo/'
  1. 安装
pod install
# 或者
pod install --repo-update

如果有需求修改依赖的第三方库的版本号,修改完毕之后,执行命令:

pod update

开源项目支持 cocoapod

  1. 新建 podspec 文件
pod spec create $podspecName
  1. 编辑podspec文件

示例如下


Pod::Spec.new do |spec|

  # ―――  Spec Metadata  ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  These will help people to find your library, and whilst it
  #  can feel like a chore to fill in it's definitely to your advantage. The
  #  summary should be tweet-length, and the description more in depth.
  #

  spec.name         = "CocoaPodDemo"
  spec.version      = "0.0.2"
  spec.summary      = "A short meaningful description of CocoaPodDemo."

  # This description is used to generate tags and improve search results.
  #   * Think: What does it do? Why did you write it? What is the focus?
  #   * Try to keep it short, snappy and to the point.
  #   * Write the description between the DESC delimiters below.
  #   * Finally, don't worry about the indent, CocoaPods strips it!
  spec.description  = <<-DESC
  A long long long long long long description of CocoaPodDemo.
                   DESC

  spec.homepage     = "https://github.com/WhiteTeeth/CocoaPodDemo"
  # spec.screenshots  = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"


  # ―――  Spec License  ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  Licensing your code is important. See https://choosealicense.com for more info.
  #  CocoaPods will detect a license file if there is a named LICENSE*
  #  Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
  #

  spec.license      = "MIT"
  # spec.license      = { :type => "MIT", :file => "FILE_LICENSE" }


  # ――― Author Metadata  ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  Specify the authors of the library, with email addresses. Email addresses
  #  of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
  #  accepts just a name if you'd rather not provide an email address.
  #
  #  Specify a social_media_url where others can refer to, for example a twitter
  #  profile URL.
  #

  spec.author             = { "baiya" => "baiya@test.com" }
  spec.social_media_url   = "https://github.com/WhiteTeeth"

  # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  If this Pod runs only on iOS or OS X, then specify the platform and
  #  the deployment target. You can optionally include the target after the platform.
  #

  # spec.platform     = :ios
  # spec.platform     = :ios, "5.0"

  #  When using multiple platforms
  # spec.ios.deployment_target = "5.0"
  # spec.osx.deployment_target = "10.7"
  # spec.watchos.deployment_target = "2.0"
  # spec.tvos.deployment_target = "9.0"


  # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  Specify the location from where the source should be retrieved.
  #  Supports git, hg, bzr, svn and HTTP.
  #

  spec.source       = { :git => "https://github.com/WhiteTeeth/CocoaPodDemo.git", :tag => "#{spec.version}" }


  # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  CocoaPods is smart about how it includes source code. For source files
  #  giving a folder will include any swift, h, m, mm, c & cpp files.
  #  For header files it will include any header in the folder.
  #  Not including the public_header_files will make all headers public.
  #

  spec.source_files  = "CocoaPodDemo", "CocoaPodDemo/**/*.{h,m}"
  spec.subspec 'Group' do |subspec|
    subspec.source_files = "CocoaPodDemo/Group", "CocoaPodDemo/Group/**/*.{h,m}"
  end
  # spec.exclude_files = "Classes/Exclude"

  # spec.public_header_files = "Classes/**/*.h"


  # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  A list of resources included with the Pod. These are copied into the
  #  target bundle with a build phase script. Anything else will be cleaned.
  #  You can preserve files from being cleaned, please don't preserve
  #  non-essential files like tests, examples and documentation.
  #

  # spec.resource  = "icon.png"
  # spec.resources = "Resources/*.png"

  # spec.preserve_paths = "FilesToSave", "MoreFilesToSave"


  # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  Link your library with frameworks, or libraries. Libraries do not include
  #  the lib prefix of their name.
  #

  # spec.framework  = "SomeFramework"
  # spec.frameworks = "SomeFramework", "AnotherFramework"

  # spec.library   = "iconv"
  # spec.libraries = "iconv", "xml2"


  # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
  #
  #  If your library depends on compiler flags you can set them in the xcconfig hash
  #  where they will only apply to your library. If you depend on other Podspecs
  #  you can include multiple dependencies to ensure it works.

  # spec.requires_arc = true

  # spec.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
  # spec.dependency "JSONKit", "~> 1.4"

end

license 有多种协议,常见的6种关系如下:

更多标签参考 Podspec Syntax Reference

  1. 分支新建tag,并推送到远程仓库
# 新建tag
git tag 1.1.0
# 将本地的tag推送到远程仓库
git push --tags
  1. 验证podspec文件,解决提示的问题
# 本地验证
pod lib lint $podspecName
# 远程验证
pod spec lint $podspecName
  1. 提交至CocoaPods 略

打包静态库

  1. 安装 cocoapods-packager
gem install cocoapods-packager
  1. 打包静态库
pod package KFData.podspec
  1. ios 14打包静态库出错
...
Mangling symbols
Building mangled framework
fatal error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/lipo: Pods/build/package.a and Pods/build-sim/package.a have the same architectures (arm64) and can't be in the same fat output file

[!] 'VMEUploadLib-iOS' uses the unencrypted 'http' protocol to transfer the Pod. Please be sure you're in a safe network with only trusted hosts. Otherwise, please reach out to the library author to notify them of this security issue.

解决方案:

github.com/CocoaPods/c…

其他问题

私有库增加依赖

spec.dependency "JSONKit", "~> 1.4"

设置 arc 或者 mrc

是否是ARC,默认true,如果不是,会自动添加-fno-objc-arc compiler flag

spec.requires_arc = true

如果只是部分文件是 arc, 参考下面设置:

#该文件夹下是ARC,其它非ARC
spec.requires_arc = 'Classes/Arc'

或者

spec.requires_arc = ['Classes/*ARC.m', 'Classes/ARC.mm']

如果想再 arc 工程中标记部分文件为 mrc,可以通过子模块设置,参考下面设置:

#添加需要mrc标识的文件,为相对路径
non_arc_files = 'xxx/aa.m','xxx/xxx.m'
#从工程中排除
s.exclude_files = non_arc_files
#为需要添加mrc标识的文件添加子设置
s.subspec 'no-arc' do |sp|
    sp.source_files = non_arc_files
    sp.requires_arc = false
end

Header Search Path

设置头文件搜索路径:

s.xcconfig = { 'USER_HEADER_SEARCH_PATHS' => '"${PROJECT_DIR}/.."' }

设置头文件递归搜索:

s.xcconfig = { 'USER_HEADER_SEARCH_PATHS' => '"${PROJECT_DIR}/.."/**' }

header search path 设置相对 podspec 的路径

#对于HEADER_SEARCH_PATHS,对将设置的字符串直接拷贝到xcode中,不会像上面source_files这样使用相对路径。
#所以,在这里先获取当前路径,再设置进去。最后加**表示recursive,即循环查找子目录的意思
$dir = File.dirname(__FILE__)
$dir = $dir + "/MyLibrary/cfiles/**"  #$dir:/Users/wangbing/TempCode/MyLibrary/cfiles/**
subcfiles.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => $dir}

Library/Framework Search Path

Library Search Path 和 Header Search Path 类似,在xcconfig中添加

spec.xcconfig = { 'FRAMEWORK_SEARCH_PATHS' => '"$(SRCROOT)/libs/Frameworks/Huoyan"' }   
  
spec.xcconfig  = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/iOS_Util/iOS_Util/AMR/lib"' }

spec.xcconfig  = { "HEADER_SEARCH_PATHS" => "${PODS_ROOT}/boost" }

spec.xcconfig = { 'HEADER_SEARCH_PATHS' => '$(SDKROOT)/usr/include/libxml2' }

添加 pch 文件

spec.prefix_header_file = 'SDKDemo/SDKDemo-Prefix.pch'

或者通过下面方式在对应 pod 的 pch 文件中添加一行

s.prefix_header_contents = '#import "SomeClass.h"'

支持 c++

s.library = 'c++'
s.xcconfig = {
    'CLANG_CXX_LANGUAGE_STANDARD' => 'compiler-default',
    'CLANG_CXX_LIBRARY' => 'libc++'
}

引入系统库

引入系统 framwork

spec.framework = "CoreTelephony"

spec.frameworks = "CoreTelephony", "SystemConfiguration"

引入系统 library

spec.library   = "resolv"

spec.libraries = "c++", "resolv"

创建subspec

#创建一个subspec
s.subspec 'MyLibraryMain' do |submain|
    
    #引入代码文件
    submain.source_files = "MyLibrary/main/**/*.{h,m}"
    
    #设置公开头文件
    submain.public_header_files = "MyLibrary/main/public.h"
    
    #设置资源文件
    submain.resource  = "MyLibrary/resources/configFiles.bundle"
    
    #设置MyLibraryMain模块依赖的系统库,注意,这里加的是系统库
    submain.frameworks = "SystemConfiguration"
    
    #设置依赖,这里可以依赖当前spec中的subspec,也可以依赖github上公开的开源库,如'AFNetworking'。
    submain.dependency "MyLibrary/MyLibraryCFiles"
end

其他问题

  1. [CP] Prepare Artifacts 编译失败
Showing All Messages
Multiple commands produce '/Users/Alvin/Library/Developer/Xcode/DerivedData/XCFrameworkDemo-fjmdgsvymhuemlebgdzvccvivdtu/Build/Products/Debug-iphonesimulator/cocoapods-artifacts-Debug.txt':

1. That command depends on command in Target 'XCFrameworkDemo' (project 'XCFrameworkDemo'): script phase “[CP] Prepare Artifacts”
2. That command depends on command in Target 'XCFrameworkDemoTests' (project 'XCFrameworkDemo'): script phase “[CP] Prepare Artifacts”

具体分析: 使用 Cocoapods 集成 XCFramework 时的 “Multiple commands produce” 错误分析

遗留问题

  1. 私有库通过 podspec git 方式源码引入时,同时私有库依赖第三方c++ 库,podsepc 文件中如何设置 c++ 头文件的header search path ?

    比如引入 protobuf 库,.pb.cc 文件中引入头文件 #include <google/protobuf/stubs/common.h>, 如何可以在不更改头文件引入方式及使用方不手动添加 header search path 的情况下引入 protobuf。

参考文件

CocoaPods使用

cocoapods系列教程---spec文件

我所理解的 CocoaPods

使用CocoaPods开发lib库

iOS 组件化 使用cocoapods集成实战演练

Cocoapods原理总结