使用CocoaPod为xcode项目添加三方库的依赖
CocoaPod是什么
cocoaPod是Swift和objective-C的Cocoa项目的依赖管理器。它拥有53,000个库,并在超过300万个应用程序中使用。
配置Ruby环境
cocoaPod是用Ruby语言开发的,可用Mac OS本身自带的Ruby安装,记得更新Ruby,不然安装容易失败。
在终端中,检查版本: gem -v
尽可能使用较高的RubyGems版本,建议2.6.x以上.
$ gem update --system # 这里需要翻墙
$ gem -v
2.2.7
终端输入如下命令(把Ruby镜像指向ruby-china,避免被墙)
$ gem sources --add https://gems.ruby-china.com/ --remove https://rubygems.org/
$ gem sources -l
https://gems.ruby-china.com
#确保只有 gems.ruby.china.com
https://ruby.taobao.org/
https://gems.ruby-china.org/ 这两个镜像目前都是https://gems.ruby-china.com/代理
更新Ruby: gem update --system 如果显示权限问题,请在语句前加上sudo,使用管理员权限去执行命令,
sudo gem update --system
安装CocoaPod
终端敲入命令:
OS X 10.11 之前使用sudo gem install cocoapods
OS X 10.11以后使用sudo gem install -n /usr/local/bin cocoapods
$ sudo gem install cocoapods
ERROR: While executing gem ... (Gem::FilePermissionError) #如果显示这样的报错,可以重新定义安装路
You don't have write permissions for the /usr/bin directory.
$ sudo gem install -n /usr/local/bin cocoapods
Successfully installed cocoapods-1.5.3
Parsing documentation for cocoapods-1.5.3
Done installing documentation for cocoapods after 2 seconds
1 gem installed
$ pod --version
1.5.3
安装成功后,使用pod --version命令可以查看当前cocoaPod的版本号
使用CocoaPod
新建PodTest项目
使用终端,cd到PodTest项目的根目录
$ cd Documents/PodTest/
建立Podfile(配置文件)
$ pod init # 创建默认配置文件
$ touch Podfile # 创建配置文件
PodTest PodTestTests Podfile
PodTest.xcodeproj PodTestUITests
$ vim Podfile # 编辑Podfile文件,键入i进入编辑模式
platform :ios, '12.0'
target 'PodTest' do
# Comment the next line if you're not using Swift and don't want to use dynamic framworks
use_frameworks!
# Pods for PodTest
pod 'AFNetworking'
pod 'SnapKit'
pod 'SwiftyJSON', '~> 4.0'
end
#ESC 弹出vim编辑模式,:wq保存并推出vim编辑器
$ pod install # 安装pod库
Analyzing dependencies
Downloading dependencies
Using AFNetworking (2.6.3)
Using SnapKit (4.2.0)
Using SwiftyJSON (4.2.0)
Generating Pods project
Integrating client project
[!] Please close any current Xcode sessions and use `PodTest.xcworkspace` for this project from now on.
Sending stats
Pod installation complete! There are 3 dependencies from the Podfile and 3 total pods installed.
#安装pod库成功,现在关闭xcode,使用PodTest.xcworkspace打开项目.
$ open PodTest.xcworkspace # 打开项目
添加Pod库成功后,项目就可以看到导入的pod库,于是就可以使用import Moudle导入三方库,调用。
注意:使用正确的三方库版本,不然编译会报错,源于swift一直在更新。