鯛’s PG blog

プログラミングに関するあれこれを書きます

【Swift4】Alamofire を使ってAPIを呼び出してみた

SwiftのHTTPネットワークライブラリ「Alamofire」を使うと
API叩いたりするのが簡単!とのことなので、使ってみた。

環境:
Xcode 9.2
Swift 4
iOS 11.2 (テスト端末のOS)
CocoaPods (Alamofire インストールに使用)

Xcode を起動し、新規プロジェクトを作成

1. Create a new Xcode project を選択
2. Single View App を選択
3. Product Name に適当に名前を入力(例:AlamofireSampleApp)
4. Alamofire インストールのため、いったんXcodeを閉じる

Alamofire のインストール

ここでは、CocoaPods を使ってインストールする。

CocoaPods 自体のインストール方法は以下のリンク先がわかりやすかった。
"CocoaPodsの環境構築" という部分を参照
qiita.com

ターミナルを起動し、cd コマンドでプロジェクトディレクトリの直下に移動

cd {workspaceのディレクトリ} /{プロジェクト名のディレクトリ}
ex. cd Desktop/workspace/AlamofireSampleApp

ディレクトリ移動できたら、以下コマンドで PodFile を作成

pod init

作成されたPodfile の中身を編集。以下を追記する。

pod 'Alamofire'


f:id:taiyaki_dos:20171216113324p:plain

上記図に記載されている '~> 4.5' というのは、
Alamofire のGitHubページ内、"Installation" 部分に記載されていたので、マネしてみた。

github.com


PodFileの編集が終わったら、以下コマンドを実行

pod install
Swift のコードを書いて動かしてみる

{プロジェクト名}.xworkspace からプロジェクトを開く

f:id:taiyaki_dos:20171216114033p:plain


とりあえずボタンを1つ用意する

f:id:taiyaki_dos:20171216114554p:plain


ボタンをコードに接続する

@IBAction func getWeather(_ sender: UIButton) {
}


今回使うAPIはこれ
weather.livedoor.com


東京のID "130010" で問い合わせしてみる
http://weather.livedoor.com/forecast/webservice/json/v1?city=400040

URLの宛先がhttpなので、明示的に許可してやらないとエラーになる
やり方は以下リンク先がわかりやすかった

qiita.com


コード内で、Alamofire を使って通信する処理を記述する
※エラーハンドリングは省略

import Alamofire

〜中略〜

    @IBAction func getWeather(_ sender: UIButton) {
        // 天気情報APIにアクセスする
        Alamofire.request("http://weather.livedoor.com/forecast/webservice/json/v1?city=130010").responseJSON {response in
            print("Request: \(String(describing: response.request))")
            print("Response: \(String(describing: response.response))")
            print("Result: \(String(describing: response.result))")
            
            if let json = response.result.value {
                print("JSON: \(json)")  // serialized json response
            }
            
            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)")  // original server data as UTF8 String
            }
        }
    }


Alamofireを使わなくてもHTTP通信は可能だが、使ったら楽になるよ、という話。