0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Swift]Alamofireで簡単にAPI通信してみた

Posted at

Alamofireについて

Alamofireはネットワーク通信(API通信)を簡単に行うためのSwift用ライブラリです。
標準のURLSessionよりも使いやすく、コードも短く書けるため非常に便利です。例えば、APIからデータを取得(GET)、データを送信(POST)、画像のアップロードなどが簡単にできます。

参考文献

実際に使ってみる

こちら纏めている内容のホットペッパーAPIを利用して、実際に実装を進めていきます。

GourmetResponse

Model側の実装。実際に取得しView側で表示する必要のあるデータを指定

GourmetResponse
struct GourmetResponse: Codable {
  let results: Results
}

// MARK: - Results
struct Results: Codable {
  let shops: [Shop]
   
  enum CodingKeys: String, CodingKey {
    case shops = "shop"
  }
}

// MARK: - Shop
struct Shop: Codable {
  let name: String?
  let address: String?
  let genre: Genre?
  let budget: Budget?
  let capacity: Int?
  let openTime: String?
  let urls: URLs?
  let photo: Photo?

  enum CodingKeys: String, CodingKey {
    case name
    case address
    case genre
    case budget
    case capacity
    case openTime = "open"
    case urls
    case photo
  }
}

// MARK: - Genre
struct Genre: Codable {
  let name: String?
}

// MARK: - Budget
struct Budget: Codable {
  let average: String?
}

// MARK: - URLs
struct URLs: Codable {
  let pc: String?
}

// MARK: - Photo
struct Photo: Codable {
  let mobile: PhotoSizes
}

// MARK: - PhotoSizes
struct PhotoSizes: Codable {
  let l: String?
}

HotPepperAPI

Viewから受け取ったキーワードにマッチする飲食店(レストラン)情報をAPIから取得する実装

HotPepperAPI
import Foundation
import Alamofire

class HotPepperAPI {
    private let key = "APIKey" // ← ここはご自身のAPIキーを入力してください
    private let baseURL = "https://webservice.recruit.co.jp/hotpepper/gourmet/v1/"

    func fetchRestaurants(keyword: String, completion: @escaping (Result<[Shop], Error>) -> Void) {
        let parameters: [String: String] = [
            "key": key,
            "keyword": keyword,
            "format": "json"
        ]

        AF.request(baseURL, parameters: parameters)
            .responseDecodable(of: GourmetResponse.self) { response in
                switch response.result {
                case .success(let gourmetResponse):
                    let shops = gourmetResponse.results.shops
                    completion(.success(shops))
                case .failure(let error):
                    debugPrint(response)
                    completion(.failure(error))
                }
            }
    }
}

GourmetViewController

受け取った値を表示させます。
本来ならviewModel側で行いますが、今回はデータ受取りの実装を纏めるのが目的なのでViewController側で実装してます。
api.fetchRestaurants(keyword: "")ここで検索したいキーワードを指定します。今回はカレーにしてますがラーメンや焼肉でも検索結果が返ってきます。

GourmetViewController
import UIKit
import Alamofire

class GourmetViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        bind()
    }
}

extension GourmetViewController {
    func bind() {
        let api = HotPepperAPI()
        api.fetchRestaurants(keyword: "カレー") { result in
            switch result {
            case .success(let shops):
                for shop in shops {
                    print("店名: \(shop.name ?? "")")
                    print("住所: \(shop.address ?? "")")
                    print("ジャンル: \(shop.genre?.name ?? "")")
                    print("平均予算: \(shop.budget?.average ?? "")")
                    print("営業時間: \(shop.openTime ?? "")")
                    print("写真URL: \(shop.photo?.mobile.l ?? "")")
                    print("Webサイト: \(shop.urls?.pc ?? "")")
                    print("---------------")
                }
            case .failure(let error):
                print("エラー: \(error)")
            }
        }

    }
}

まとめ

Alamofireを使うことで、URLSessionを使うよりも簡潔にAPI通信を実装できました。
Swiftには便利なライブラリがたくさんあるので、今後も積極的に使っていきたいです。

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?