Skip to content

Instantly share code, notes, and snippets.

@whoisronnoc
Created March 5, 2018 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisronnoc/4a8bf850d7d1097f87e112a28d42125e to your computer and use it in GitHub Desktop.
Save whoisronnoc/4a8bf850d7d1097f87e112a28d42125e to your computer and use it in GitHub Desktop.
// An example authorizing Google Api use with OAuthSwift https://github.com/OAuthSwift/OAuthSwift
import Foundation
import OAuthSwift // https://github.com/OAuthSwift/OAuthSwift
import KeychainAccess // https://github.com/kishikawakatsumi/KeychainAccess
import SwiftyJSON // https://github.com/SwiftyJSON/SwiftyJSON
class Google {
private let auth: OAuth2Swift
init(cKey: String) {
auth = OAuth2Swift(consumerKey: cKey, // your consumer key from https://console.developers.google.com
consumerSecret: "", // leave blank
authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
accessTokenUrl: "https://www.googleapis.com/oauth2/v4/token",
responseType: "code")
let bundleID = Bundle.main.bundleIdentifier!
let keychain = Keychain(service: bundleID)
// example to clear saved credentials
// keychain["google_oauthToken"] = nil
// keychain["google_oauthTokenSecret"] = nil
// keychain["google_oauthRefreshToken"] = nil
// setup oauth client if saved credentials exist
if let token = keychain["google_oauthToken"],
let tokenSecret = keychain["google_oauthTokenSecret"],
let refreshToken = keychain["google_oauthRefreshToken"]
{
auth.client.credential.oauthToken = token
auth.client.credential.oauthTokenSecret = tokenSecret
auth.client.credential.oauthRefreshToken = refreshToken
} else { // bring up auth dialog to get authorization tokens
// auth.authorizeURLHandler = SafariURLHandler(viewController: viewController, oauthSwift: auth) // this fails
auth.authorize(withCallbackURL: URL(string: "\(bundleId):/oauth2Callback")!, // setup your callback URL
scope: "https://www.googleapis.com/auth/calendar", // configure to the scope of api access you want to use
state: "test", // useless?
success: { (credential, response, parameters) in
// store tokens for future use in keychain using KeychainAccess
keychain["google_oauthToken"] = credential.oauthToken
keychain["google_oauthTokenSecret"] = credential.oauthTokenSecret
keychain["google_oauthRefreshToken"] = credential.oauthRefreshToken
// example authorized request returning json of user's google calendars
_ = auth.startAuthorizedRequest("https://www.googleapis.com/calendar/v3/users/me/calendarList",
method: .GET, parameters: [:],
success: { (response) in
let json = JSON(data: response.data)
print(json)
}, failure: { (error) in
print(error.localizedDescription)
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment