使用CocoaPods创建新组件的步骤如下:
1. 安装CocoaPods
确保已安装最新版CocoaPods:
sudo gem install cocoapods
2. 创建组件模板
通过命令行生成组件目录结构:
pod lib create YourComponentName
按提示选择配置(语言、Demo项目、测试框架等)。
3. 目录结构说明
生成的文件结构通常包含:
-
Example
:测试组件的Demo项目。 -
Pod/Classes
:存放组件源码(Swift/Obj-C文件)。 -
YourComponentName.podspec
:组件的配置文件。
4. 编辑Podspec文件
修改YourComponentName.podspec
:
Pod::Spec.new do |s|
s.name = 'YourComponentName'
s.version = '0.1.0'
s.summary = 'A short description of YourComponent.'
s.homepage = 'https://github.com/YourGitHub/YourComponent'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'YourName' => 'your@email.com' }
s.source = { :git => 'https://github.com/YourGitHub/YourComponent.git', :tag => s.version.to_s }
s.ios.deployment_target = '12.0'
s.source_files = 'YourComponent/Classes/**/*' # 源码路径
# 添加依赖(可选)
s.dependency 'Alamofire', '~> 5.0'
end
5. 添加组件代码
将源码文件(.swift
或.m/.h
)放入Pod/Classes
目录,或通过Xcode直接添加。
6. 本地测试
在Example
目录下运行:
pod install
打开生成的.xcworkspace
文件,编写测试代码并运行Demo项目。
7. 推送代码到Git仓库
初始化Git仓库并推送到远程:
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/YourGitHub/YourComponent.git
git push -u origin master
8. 打版本Tag
git tag -a 0.1.0 -m "First release"
git push origin --tags
9. 验证Podspec
pod lib lint # 本地验证
pod spec lint # 远程验证(包括Tag是否存在)
10. 发布组件
公共仓库(CocoaPods Trunk)
-
注册Trunk账号(首次使用):
pod trunk register your@email.com 'Your Name' --description='macbook'
-
发布组件:
pod trunk push YourComponentName.podspec
私有仓库
- 在私有仓库的
Podfile
中指定源:source 'https://private/repo/specs.git' # 私有源URL source 'https://cdn.cocoapods.org/' # CocoaPods公共源
- 推送Podspec到私有源:
pod repo push PrivateRepoName YourComponentName.podspec
11. 使用组件
用户可在Podfile
中添加:
pod 'YourComponentName', '~> 0.1.0'
常见问题
- Podspec验证失败:检查路径、版本号、Tag是否匹配。
- Trunk权限问题:确保已通过注册邮件验证。
-
组件依赖:在
s.dependency
中声明所有第三方依赖。
完成以上步骤后,你的组件即可通过CocoaPods集成到项目中!🎉