見出し画像

Alamofireを使ってみよう

有名なやつですね、自分もまだまだ理解が足りていないので備忘用に残します。

Github:


参考記事:



◉サンプル

こんな感じ


◆コード全体(pod installでAlamofireをインストールしておいてください)

Article.swiftというファイルを作成して以下コードを記述

struct Article: Codable {
    let title: String
    var user: User
    
    struct User: Codable {
        var name: String
    }
}


ViewController.swift内に以下コードを記述

import UIKit
import Alamofire
class ViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    //変数
    let decoder: JSONDecoder = JSONDecoder()
    var articles = [Article]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
        getQiitaArticles()
    }
    
    private func setup() {
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    //Alamofire
    private func getQiitaArticles() {
        AF.request("https://qiita.com/api/v2/items").responseJSON { response in
            switch response.result {
            case .success:
                do {
                    self.articles = try self.decoder.decode([Article].self, from: response.data!)
                    self.tableView.reloadData()
                } catch {
                    print("デコードに失敗しました")
                }
            case .failure(let error):
                print("error", error)
            }
        }
    }
    
    
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        articles.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath)
        cell.textLabel?.text = articles[indexPath.row].title
        return cell
        
    }
    
}


storyboardはテーブルビューとラベルだけでOKです

tableViewCellのIDは"articleCell"にしておくことを忘れずに


今回は以上です。

この記事が気に入ったらサポートをしてみませんか?