概要
Swiftビギナーズ勉強会 第13回で登壇者の方のスライドに書いてあった、下記のQiitaの記事を参考にして、Swiftの練習に書いてみた。
参考:AlamofireとSwiftyJSONでAPIを叩くチュートリアル
いきなり参考記事と違うことをする
ライブラリ管理ツールはCocoaPodsを使っているので、「Alamofire」と「SwiftyJSON」をCocoaPodsでライブラリを導入。
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で書いてしまった。
教えて、できる人。
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にしないといけないね。
動いた
TODO
- 新着記事だけじゃなくて、他のAPIも試す
- APIClientに他のAPIリクエストを処理するメソッドを追加する
- ちゃんと勉強する
ソースコード
Githubにあげました。
https://github.com/macneko-ayu/SwiftPractice/tree/master/QiitaAPISample
プロジェクトごとにリポジトリ作ったほうがよかったかも。