LoginSignup
25

More than 5 years have passed since last update.

[Swift]QiitaのAPIを叩いて記事を取得して表示するサンプルアプリを書いてみた

Last updated at Posted at 2016-02-21

概要

Swiftビギナーズ勉強会 第13回で登壇者の方のスライドに書いてあった、下記のQiitaの記事を参考にして、Swiftの練習に書いてみた。

参考:AlamofireとSwiftyJSONでAPIを叩くチュートリアル

いきなり参考記事と違うことをする

ライブラリ管理ツールはCocoaPodsを使っているので、「Alamofire」と「SwiftyJSON」をCocoaPodsでライブラリを導入。

PodFile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target 'QiitaAPISample' do
  pod 'Alamofire'
  pod 'SwiftyJSON'
end

target 'QiitaAPISampleTests' do

end

target 'QiitaAPISampleUITests' do

end
コマンド
pod install

参考:SwiftでCocoaPodsを使い始めようとしてハマったことメモ

実装する

参考にした記事から書き換えたところをピックアップ。

UIはStoryboard使う

Storyboardも勉強中なので、Storyboardで実装できるところはStoryboardで実装した。
AutoLayoutの勉強にもなるし。
なるし。
なるよ。
…勉強しよ。

Alamofire関連はViewControllerから分離させる

非同期処理の終了を呼び出し元で判断する方法がわからず、Notificationで書いてしまった。
教えて、できる人。

APIClient.swift
import Alamofire
import SwiftyJSON

class APIClient {
    var items: [[String: String?]]?  {
        didSet {
            NSNotificationCenter.defaultCenter()
                .postNotificationName("ChangedItemsValue", object: nil, userInfo: nil)
        }
    }

    func getAllUserItems() {
        let urlString: String = "https://qiita.com/api/v2/items"

        Alamofire.request(.GET, urlString)
            .responseJSON { response in
                switch response.result {
                case .Success(let value):
                    let json = JSON(value)
                    var items: [[String: String?]] = []
                    json.forEach { (_, json) in
                        let item: [String: String?] = [
                            "title": json["title"].string,
                            "userId": json["user"]["id"].string
                        ]
                        items.append(item)
                    }
                    self.items = items
                    print(self.items)
                case .Failure(let error):
                    print(error)
                }
        }
    }
}

参考:SwiftでAPIクライアントをつくる (Alamofire+ObjectMapper)

間違ってるかもと思ったので直す

Storyboardの方ではArticleListViewControllerをInitial View Controllerにし、
ついでにNavigation Controllerをくっつけておきます。

これはNavigationViewControllerをInitialViewControllerにしないといけないね。

動いた

スクリーンショット-2016-02-21-17.01.40.png

TODO

  • 新着記事だけじゃなくて、他のAPIも試す
  • APIClientに他のAPIリクエストを処理するメソッドを追加する
  • ちゃんと勉強する

ソースコード

Githubにあげました。
https://github.com/macneko-ayu/SwiftPractice/tree/master/QiitaAPISample

プロジェクトごとにリポジトリ作ったほうがよかったかも。

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
25