I am trying to get an authorization response so that I can use it to get the access and refresh tokens later for YouTube APIs using Swift. I would prefer not to use external libraries like AeroGear or OAuthSwift.

I have added the app to the Google API & Services console, created an API key and OAuth 2.0 client ID, dowloaded the OAuth 2.0 client ID plist file and added it to the project. I can try to get the authorization but, after approval allowing access, the browser comes back with "Safari cannot open the page because the page is invalid".

I have setup the scheme in Info.plist for the call back:


I use the following code to ask for the authorization:

let url = "https://accounts.google.com/o/oauth2/v2/auth"
let client_id = youTube_client_id      // client id value from the API console
let redirect_uri = "my.bundle.id:/oauth2Callback"
let response_type = "code";
let scope = "https://www.googleapis.com/auth/youtube"
let state = ""
let login_hint = "userEmail"

let finalURLString = url + "?scope=" + scope + "&response_type=" + response_type + "&redirect_uri=" + redirect_uri + "&client_id=" + client_id + "&login_hint=" + login_hint + "state=" + state
let urlOut = URL(string: finalURLString)!

UIApplication.shared.open(urlOut, options: [:], completionHandler: nil)

I have added some code to the AppDelegate but it never gets there anyway:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

// some code to handle the response
return true

What am I doing wrong? Any suggestions? The problem seems to be with the callback but I could not find anywhere how to solve it for Swift. Thanks.

0 Answers