docomo Developper Supportから「OAuth SDK for iOS」というSDKが提供されています。
提供されているサンプルがObjective-Cなので勉強を兼ねてSwiftで書き直してみました。
docomo Developper Support
https://dev.smt.docomo.ne.jp/?p=index
今回試したのは「OAuth認証に必要なパラメータの設定」して「OAuth 認証を開始」するだけの単純なものです。
認証に必要なパラメータは下記の4つです。
1、クライアント ID
2、secret
3、scope
4、redirectUri
これを設定して認証を開始すると
成功した場合は、
・アクセストークン
・リフレッシュトークン
・トークンの有効期限
・トークンタイプ
・スコープ
失敗した場合は、
・エラーコード
・エラーメッセージ
・例外オブジェクト
が返ってきます。
import UIKit
class ViewController: UIViewController {
let clientID = "" //クライアント ID を設定
let secret = "" //クライアントシークレットを設定
let scope = "" //スコープを設定
let redirectUri = "" //リダイレクト URI を設定
var oAuth: OAuth!
override func viewDidLoad() {
super.viewDidLoad()
oAuth = OAuth()
//OAuth 認証に必要なパラメータの設定
oAuth.setClientID(clientID)
oAuth.setSecret(secret)
oAuth.setScope(scope)
oAuth.setRedirectUri(redirectUri)
}
@IBAction func oauthButton(sender: AnyObject) {
//OAuth 認証を開始
oAuth.startAuth(self, onComplete: { (token) -> Void in
//アクセストークンの取得
let access_token = token.accessToken
//リフレッシュトークンの取得
let refreshtoken = token.refreshToken
//トークンの有効期限の取得
let expires_in = token.expiresIn
//トークンタイプの取得
let token_type = token.tokenType
//スコープの取得
let scope = token.scope
//取得情報出力
println("認証成功!")
println("access_token: \(access_token)")
println("refreshtoken: \(refreshtoken)")
println("expires_in: \(expires_in)")
println("token_type: \(token_type)")
println("scope: \(scope)")
}) { (error) -> Void in
//エラーコードの取得
let error_code = error.code
//エラーメッセージの取得
let rror_message = error.localizedDescription
//例外オブジェクトの取得
let cause = error.cause
//取得情報出力
println("認証失敗!")
println("error_code: \(error_code)")
println("rror_message: \(rror_message)")
println("cause: \(cause)")
}
}
}
docomo Developper Supportには、雑談対話やトレンド記事抽出など面白そうなAPIが幾つかあるので試してみようと思います。
ひとまずそれぞれのサンプルをSwiftで書き直してみることから始めようかと思っています。
文章やコードに読み難い箇所、間違っている箇所などあればご指摘いただけるとありがたいです。