Create a gist now

Instantly share code, notes, and snippets.

@rayc5 /TodoistAPI
Last active Aug 29, 2015

What would you like to do?
Todoist_API_sample
import Foundation
import UIKit
protocol TodoistAPIDelegate {
func didAuthorizeTodoist(success: Bool)
}
class TodoistAPI {
var delegate: TodoistAPIDelegate? = nil
// リクエスト時に利用するパラメータ
private struct APIInfo {
static let authURL: String = "https://todoist.com/oauth/authorize"
static let accessTokenURL: String = "https://todoist.com/oauth/access_token"
static let syncURL: String = "https://todoist.com/API/v6/sync"
static let redirectURL: String = "https://localhost"
static let client_id: String = "CLIENT_ID"
static let client_secret: String = "CLIENT_SECRET"
static let scope: String = "data:read"
static let state: String = "state"
static var code: String = ""
static var access_token: String = ""
}
// アクセスするURL
private var redirectURL: String { get { return APIInfo.redirectURL } }
private var authorizeURL: String {
get {
var string = APIInfo.authURL
string += "?client_id=" + APIInfo.client_id + "&scope=" + APIInfo.scope + "&state=" + APIInfo.state + "&redirect_uri=" + APIInfo.redirectURL
return string
}
}
private var accessTokenURL: String {
get {
var string = APIInfo.accessTokenUR
string += "?client_id=" + APIInfo.client_id + "&client_secret=" + APIInfo.client_secret + "&code=" + APIInfo.code
return string
}
}
private var getTasksURL: String {
get {
var string = APIInfo.syncURL
string += "?token=" + APIInfo.access_token + "&seq_no=0&seq_no_global=0&resource_types=[\"items\"]"
let result = string.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
return result!
}
}
// MARK: singleton
class var sharedInstance : TodoistAPI {
struct Static {
static let instance : TodoistAPI = TodoistAPI()
}
return Static.instance
}
// MARK: Authorize methods
func getAuthorizeController(delegate: TodoistAPIDelegate) -> UIViewController? {
self.delegate = delegate
let vc = TodoistAuthorizeViewController()
let request = NSMutableURLRequest(URL: NSURL(string: authorizeURL)!)
NSURLConnection.sendAsynchronousRequest(request,
queue: NSOperationQueue.mainQueue(),
completionHandler: {
(res, data, error) in
let responce = res as! NSHTTPURLResponse
vc.url = responce.URL!
})
return vc
}
private func getAuthorizeURL(completion: (NSURL) -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: authorizeURL)!)
NSURLConnection.sendAsynchronousRequest(request,
queue: NSOperationQueue.mainQueue(),
completionHandler: {
(res, data, error) in
let responce = res as! NSHTTPURLResponse
let url = responce.URL!
completion(url)
})
}
private func getAccessToken(code: String) {
APIInfo.code = code
let request = NSMutableURLRequest(URL: NSURL(string: accessTokenURL)!)
request.HTTPMethod = "POST"
NSURLConnection.sendAsynchronousRequest(request,
queue: NSOperationQueue.mainQueue(),
completionHandler: {
(res, data, error) in
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonResult = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.MutableContainers,
error: nil) as! NSDictionary
APIInfo.access_token = jsonResult["access_token"] as! String
self.delegate?.didAuthorizeTodoist(true)
})
}
// MARK: fetch
func getTasks() {
let request = NSMutableURLRequest(URL: NSURL(string: getTasksURL)!)
NSURLConnection.sendAsynchronousRequest(request,
queue: NSOperationQueue.mainQueue(),
completionHandler: {
(res, data, error) in
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonResult = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.MutableContainers,
error: nil) as! NSDictionary
let data: NSNumber = jsonResult["UserId"] as! NSNumber
User.userId = data.stringValue
let tasks = jsonResult["Items"] as! NSArray
for task in tasks {
let task = task as! NSDictionary
let id = task["id"] as! NSNumber
let title = task["content"] as! String
let date = task["due_date"] as! String
println("id: \(id.stringValue), title: \(title), date: \(date)")
}
})
}
}
// 認証用のViewController
class TodoistAuthorizeViewController: UIViewController, UIWebViewDelegate {
var webView: UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
var url: NSURL {
get {
return self.url
}
set {
webView.loadRequest(NSURLRequest(URL: newValue))
}
}
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
view.addSubview(webView)
}
// MARK: webView Delegate
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let url = request.URL!
if url.host == "todoist.com" {
if let path = url.path {
if path == "/Users/gplusRedirect" { // 認証後のコールバックURLが https://todoist.com/Users/gplusRedirect
if let fragment = url.fragment {
let qos = Int(QOS_CLASS_USER_INITIATED.value)
dispatch_async(dispatch_get_global_queue(qos, 0)) {
NSThread.sleepForTimeInterval(3.0)
TodoistAPI.sharedInstance.getAuthorizeURL() {
self.webView.loadRequest(NSURLRequest(URL: $0))
}
}
}
}
}
} else if url.host == "localhost" { // コールバックをlocalhostに設定している.
let query = url.query!
// https://localhost/?state=state&code=<CODE>
let code = query.substringFromIndex(advance(query.startIndex, 17)) // stateの長さに依存する. 12+(stateの長さ)
TodoistAPI.sharedInstance.getAccessToken(code)
}
return true
}
}
import UIKit
class ViewController: UIViewController, TodoistAPIDelegate
{
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Todoistの認証用VCを呼ぶ
if let avc = TodoistAPI.sharedInstance.getAuthorizeController(self) {
self.presentViewController(avc, animated: true, completion: nil)
}
}
// 認証終了時に呼ばれる関数
func didAuthorizeTodoist(success: Bool) {
// 認証用VCを閉じる
self.dismissViewControllerAnimated(false, completion: nil)
if success {
// 成功時の処理
TodoistAPI.sharedInstance.getTasks()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment