えむじぃのアプリ開発

えむじぃのアプリ開発

元大手IT企業SE、現ベンチャー企業CTOのブログです。

【Swift】API通信(AlamofireとSwiftyJSONを使用)

今回はAlamofireとSwiftyJSONを使用してAPI通信するところまでをこの記事で説明します。

この記事のポイント・Podfileの編集(AlamofireとSwiftyJSONを使用)
API通信

Podfileの編集

Podfileを以下のように編集します。※今回はAlamofireとSwiftyJSONをインストールします。

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

target 'sample' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  pod 'SwiftyJSON'
  pod 'Alamofire'

  # Pods for sample

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

  target 'sampleUITests' do
    # Pods for testing
  end

end

 

バージョンを指定したい場合は以下のように設定します。

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

target 'sample' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  pod 'SwiftyJSON'
  pod 'Alamofire', '~> 4.7'  ← ここ

  # Pods for sample

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

  target 'sampleUITests' do
    # Pods for testing
  end

end

これでPodfileの編集は完了です。

 

 

インストール

前回のおさらいになりますが、初めてプロジェクトにインストールする場合は以下のコマンドを入力します。

pod install

 

2回目以降(追加、削除)の場合は以下のコマンドを入力します。

pod update

 

インストールが完了するとターミナルに以下のようなメッセージが表示されます。

Downloading dependencies
Installing Alamofire (4.9.1)
Installing SwiftyJSON (5.0.0)
Generating Pods project
Integrating client project
Pod installation complete! There are 2 dependencies from the Podfile and 2 total
pods installed.

これでインストールは完了です。

 

 

インストール後の注意事項

ライブラリをインストール後は「プロジェクト名.xcworkspace」ファイルをダブルクリックしてXcodeを実行する必要があります。(ライブラリインストール前は「プロジェクト名.xccodeproj」)

 

 

API通信

AlamofireとswiftyJSONのインストールが完了したら、実際にその2つのライブラリを使ってソースを書いていきます。

import UIKit
import Alamofire
import SwiftyJSON
class UIViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON {
            response in
            if let result = response.result.value as? [String: Any] {
                if let returnValue = response.result.value {
                    print(JSON(returnValue))
                }
            } else {
                print("Error!")
            }
        }
    }
}