Created
March 17, 2020 10:27
-
-
Save godrm/6b1155224be6b34f749b66faa0ba3c52 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import OctoKit | |
import AuthenticationServices | |
extension URL { | |
/// Returns a new URL by adding the query items, or nil if the URL doesn't support it. | |
/// URL must conform to RFC 3986. | |
func appending(_ queryItems: [URLQueryItem]) -> URL? { | |
guard var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true) else { | |
// URL is not conforming to RFC 3986 (maybe it is only conforming to RFC 1808, RFC 1738, and RFC 2732) | |
return nil | |
} | |
// append the query items to the existing ones | |
urlComponents.queryItems = (urlComponents.queryItems ?? []) + queryItems | |
// return the url from new url components | |
return urlComponents.url | |
} | |
} | |
class ViewController: UIViewController, ASWebAuthenticationPresentationContextProviding { | |
var tokenConfig : TokenConfiguration? = nil | |
let config = OAuthConfiguration.init(token: "", secret: "", scopes: ["repo", "read:org"]) | |
var webAuthSession: ASWebAuthenticationSession? | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view. | |
let callbackUrlScheme = "octoissue" | |
var url = config.authenticate()?.appending([URLQueryItem(name: "redirect_uri", value: "octoissue://tracker")]) | |
webAuthSession = ASWebAuthenticationSession.init(url: url!, callbackURLScheme: callbackUrlScheme, completionHandler: { (callBack:URL?, error:Error?) in | |
// handle auth response | |
guard error == nil, let successURL = callBack else { | |
return | |
} | |
self.config.handleOpenURL(url: successURL) { config in | |
self.loadCurrentUser(config: config) // purely optional of course | |
} | |
}) | |
// Kick it off | |
webAuthSession?.presentationContextProvider = self | |
webAuthSession?.start() | |
} | |
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { | |
return self.view.window ?? ASPresentationAnchor() | |
} | |
func loadCurrentUser(config: TokenConfiguration) { | |
Octokit(config).me() { response in | |
switch response { | |
case .success(let user): | |
print(user.login, user.email, user.name) | |
case .failure(let error): | |
print(error) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment