1. 安装
方式一:Homebrew(推荐)
无需 sudo,避免系统 Ruby 权限问题,适合 macOS Sonoma 及以上版本:
brew install cocoapods
更新:
brew upgrade cocoapods
方式二:RubyGems
sudo gem install cocoapods
如果不想使用 sudo,可以配置用户目录安装,在 ~/.bash_profile 或 ~/.zshrc 中添加:
export GEM_HOME=$HOME/.gem
export PATH=$GEM_HOME/bin:$PATH
然后执行:
gem install cocoapods --user-install
更新:
sudo gem install cocoapods
验证安装
pod --version
输出版本号(如 1.16.2)即表示安装成功。
2. 在项目中使用
进入 Xcode 项目根目录,创建 Podfile:
pod init
编辑 Podfile,添加依赖,例如:
platform :ios, '13.0'
target 'YourApp' do
use_frameworks!
pod 'Alamofire'
end
源(Source)配置
CocoaPods 1.8+ 默认使用 CDN 源,一般无需手动指定。如需显式声明或使用其他源,在 Podfile 顶部添加:
# 官方 CDN 源(默认,推荐)
source 'https://cdn.cocoapods.org/'
# 官方 Git 源(备用,旧版默认)
source 'https://github.com/CocoaPods/Specs.git'
# 清华镜像(国内访问更快)
source 'https://mirrors.tuna.tsinghua.edu.cn/git/CocoaPods/Specs.git'
| 源地址 | 说明 |
|---|---|
https://cdn.cocoapods.org/ | 官方默认,CDN 按需拉取,速度快 |
https://github.com/CocoaPods/Specs.git | 官方 Git 仓库,需完整克隆,作为备用 |
https://mirrors.tuna.tsinghua.edu.cn/git/CocoaPods/Specs.git | 清华镜像,国内网络推荐 |
| 私有 Git 仓库地址 | 企业内部私有库使用 |
安装依赖:
pod install
安装完成后,使用 .xcworkspace 文件打开项目。
3. 移除依赖
- 编辑
Podfile,删除不需要的pod 'xxx'行 - 重新执行安装:
pod install
CocoaPods 会自动移除已删除的依赖库并更新项目配置。
如需完全移除 CocoaPods(还原为纯 .xcodeproj 项目),可使用 cocoapods-deintegrate:
gem install cocoapods-deintegrate
pod deintegrate
然后手动删除 Podfile、Podfile.lock 和 Pods/ 目录即可。
常用命令
| 命令 | 说明 |
|---|---|
pod install | 安装/更新 Podfile 中的依赖 |
pod update | 更新所有依赖到最新版本 |
pod update PodName | 更新指定依赖 |
pod search PodName | 搜索可用库 |
pod outdated | 查看可更新的依赖 |