37
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでQiitaのAPIを使う

Last updated at Posted at 2015-07-22

Swiftの勉強にQiitaAPIのSwiftインターフェースを作ってみました

QiitaKit

  • 通信には Alamofire を利用
  • Generics を用いて各リクエストレスポンスは対応したエンティティにマッピング
  • リクエストは Future でラップされたエンティティを返す
    • 例)GetItem -> Future<Item>

使い方

import QiitaKit

let Qiita = QiitaSession(
    baseURL: "https://qiita.com",
    clientId: "*****",
    clientSecret: "*****"
)

// アクセストークンの取得
Qiita.oauthAuthorize([.ReadQiita, .WriteQiita], scheme: "callback url scheme")
	.onSuccess { accessToken in
		println(accessToken)
	}


//条件にマッチする投稿リストの取得
let listItems = ListItems(page: "1", per_page: "20", query: "qiita user:yaotti")
Qiita.request(listItems)
	.onSuccess { items, meta in
		println(items)
	}
	.onFailure {
		println($0)
	}

//flatMapを使った例
Qiita.request(listItems)
	.flatMap {
		Qiita.request(GetItem(item_id:$0[0].id))
	}
	.flatMap {
	    ...
	}

API定義の例

Endpoint/Item/ListItems.swift
import Foundation
import APIKit

/**
*  投稿の一覧を作成日時の降順で返します。
*/
public struct ListItems {
    /// ページ番号 (1から100まで)
    /// example: 1
    /// ^[0-9]+$
    public let page: String

    /// 1ページあたりに含まれる要素数 (1から100まで)
    /// example: 20
    /// ^[0-9]+$
    public let per_page: String

    /// 検索クエリ
    /// example: qiita user:yaotti
    /// 
    public let query: String

    public init(page: String, per_page: String, query: String) {
        self.page = page
        self.per_page = per_page
        self.query = query
    }
}

extension ListItems: RequestToken {
    
    public typealias Response = ([Item], LinkMeta<ListItems>)
    public typealias SerializedType = [[String: AnyObject]]

    public var method: HTTPMethod {
        return .GET
    }

    public var URL: String {
        return "/api/v2/items"
    }

    public var headers: [String: AnyObject]? {
        return nil
    }

    public var parameters: [String: AnyObject]? {
        return [
            "page": page,
            "per_page": per_page,
            "query": query,
        ]
    }

    public var encoding: RequestEncoding {
        return .URL
    }

    public var resonseEncoding: ResponseEncoding {
        return .JSON(.AllowFragments)
    }
}

extension ListItems {
    
    public static func transform(request: NSURLRequest, response: NSHTTPURLResponse?, object: SerializedType) -> Result<Response> {
        
        return Result(_Items(object), LinkMeta<ListItems>(dict: response!.allHeaderFields))
    }
}

インストール

Carthage

非推奨

Cartfile に以下を追加し生成される Framework をプロジェクトに追加

github "sora0077/QiitaKit"

CocoaPods

Podfile に以下を追加し pod install を実行する

source 'https://github.com/sora0077/PodSpecs.git'
source 'https://github.com/CocoaPods/Specs.git'

pod 'QiitaKit', :git => 'https://github.com/sora0077/QiitaKit.git', :tag => "swift-2.0"
37
39
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
37
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?