Skip to content

Instantly share code, notes, and snippets.

@jumbo-in-Jap
Last active January 28, 2017 05:24
Show Gist options
  • Save jumbo-in-Jap/097842438587561c2f0d173ef5712fc5 to your computer and use it in GitHub Desktop.
Save jumbo-in-Jap/097842438587561c2f0d173ef5712fc5 to your computer and use it in GitHub Desktop.
「ハッカソン当日より前の開発環境の構築やプロトタイプの作成など、事前準備を可とします」とのことなので、ツイキャスハッカソン用にOauth2のログインでAccessTokenを取得するとこをSwift3で書きました
//
// TwicastLoginWebViewController.swift
// TwicasHackathonTest
//
// Created by HanedaKentarou on 2017/01/16.
// Copyright © 2017年 com.adriablue. All rights reserved.
//
/* How to use.
* Twicast API
http://apiv2-doc.twitcasting.tv/#introduction
---------------------
vc.loginCompleteion = { (credential:TwicastCredential?, error:Error?) in
if let credential = credential{
print(credential)
}
}
---------------------
*/
import UIKit
extension URL {
var params: [String : String] {
var results: [String : String] = [:]
guard let urlComponents = NSURLComponents(string: self.absoluteString), let items = urlComponents.queryItems else {
return results
}
for item in items {
results[item.name] = item.value
}
return results
}
}
struct TwicastCredential {
let tokenType:String
let expireDate:NSDate
let accessToken:String
}
class LoginWebViewController: UIViewController {
var webView:UIWebView = UIWebView()
// API Info
let CLIENT_ID = "XXXXX"
let CLIENT_SECRET = "XXXXX"
let CSRF_TOKEN = "XXXXX"
let REDIRECT_URL = "XXXXX"
var loginURL:URL?{
get{
return URL(string: "https://apiv2.twitcasting.tv/oauth2/authorize?client_id=\(CLIENT_ID)&response_type=code&state=\(CSRF_TOKEN)")
}
}
var loginCompleteion = { (credential:TwicastCredential?, error:Error?) in
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
webView = UIWebView(frame: self.view.bounds)
webView.delegate = self
self.view.addSubview(webView)
if let requestURL = loginURL{
webView.loadRequest(URLRequest(url: requestURL))
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension LoginWebViewController:UIWebViewDelegate{
// MARK: WebView Delegate
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let url = request.url, url.absoluteString.contains(REDIRECT_URL){
if let code = url.params["code"]{
requestAccessToken(code: code)
}
}
return true
}
func requestAccessToken(code:String){
let urlString = "https://apiv2.twitcasting.tv/oauth2/access_token"
let request = NSMutableURLRequest(url: URL(string: urlString)!)
// set the method(HTTP-POST)
request.httpMethod = "POST"
// set the header(s)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// set the request-body(JSON)
let params: [String: String] = [
"grant_type": "authorization_code",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"redirect_uri":REDIRECT_URL,
"code":code
]
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted)
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
do {
guard let resp = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject] else {
self.finish(credential: nil, error: error)
return
}
if let type = resp["token_type"] as? String,
let accessToken = resp["access_token"] as? String,
let expireIn = resp["expires_in"] as? Int{
let expireDate = NSDate(timeIntervalSinceNow: TimeInterval(expireIn))
let credential = TwicastCredential(tokenType: type, expireDate: expireDate, accessToken: accessToken)
self.finish(credential: credential, error: nil)
}
} catch {
self.finish(credential: nil, error: error)
return
}
})
task.resume()
}
func finish(credential:TwicastCredential?, error:Error?){
self.loginCompleteion(credential, error)
self.dismiss(animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment