LoginSignup
8

More than 5 years have passed since last update.

Swiftで外部ライブラリを追加する(CocoaPods)

Posted at

CocoaPodsのインストール

(CocoaPods は v0.36.0 より、Swift に対応。)

MacにはデフォルトでRubyがインストールされているので、それが前提。

1.ruby gemを最新にする
$ sudo gem update --system

2.インストール
導入方法は簡単で、
$ sudo gem install cocoapods
たったこれだけ。

※ OSXがEl Capitan方は、ターミナルで以下のコマンドを打ってください。
sudo gem install -n /usr/local/bin cocoapods

理由は下記。
MacOSX El Capitanでcocoapodsインストールが出来ない時の対処法
http://qiita.com/AcaiBowl/items/4bb4708de03e6ee14a4a

3.セットアップ
$ pod setup

CocoaPodsをつかう

次に、 Xcode のプロジェクトがあるディレクトリで、コマンドを実行します。
$ pod init
これで、 Podsfile が生成されるので、ここに導入するライブラリを記述します。

初期状態だと、このようになってるはず。(rensyuuプロジェクトの場合)

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

target 'rensyuu' do
  # Comment this line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for rensyuu

  target 'rensyuuTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'rensyuuUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end

( platfrom には ios, osx, tvos, watchos のいずれかが指定できます。)

次に、依存ライブラリを追加します。
target 'rensyuu' の部分は、 rensyuuプロジェクトで使うもの ということ。
全部共通で使う場合は、一番下などtarget の中でない部分に追加。

ここで、 Swift での定番ネットワークライブラリAlamofireを
rensyuu に対し導入してみます。

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

target 'rensyuu' do
  # Comment this line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for rensyuu
  pod 'Alamofire', '~> 3.0'

  target 'rensyuuTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'rensyuuUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end

で、保存して、コマンドを実行します。
$ pod install
これで導入完了です。

※注意
この時にxcodeでプロジェクトファイルを開いていると、
[!] From now on use ~~.xcworkspace.
と怒られてしまうので、xcodeを閉じてから実行する。

*.xcodeprojではなく、生成された *.xcworkspace を
Xcode で開くと、きちんと導入されており、
import Al
と入力すると、 Alamofire まで、補完が出るようになります。
出なかった場合は、一度ビルドすると、出るようになります。

※ 他のライブラリをインストールするときは、先ほどのPodfileにライブラリを追加し、
$ pod update
を実行する。

CocoaPodsでのブランチ指定方法

pod 'Podでの名前', :git => 'Gitへのアドレス', :branch => 'ブランチ名'

また、submodulesをダウンロードするにはさらに
pod 'Podでの名前', :git => 'Gitへのアドレス', :branch => 'ブランチ名', :submodules => true

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8