Skip to content

Instantly share code, notes, and snippets.

@robotsquidward
Last active August 23, 2018 16:34
Show Gist options
  • Save robotsquidward/3a2b3f54e403ec5122aa2d3be89e467b to your computer and use it in GitHub Desktop.
Save robotsquidward/3a2b3f54e403ec5122aa2d3be89e467b to your computer and use it in GitHub Desktop.
Get GitHub auth_token

Pass the auth_token in to make the request to GitHub.

func getAuthToken(code: URLQueryItem?) {
    // make network call to get actual token
    let requestManager = RequestManager()

    let session = URLSession.shared
    session.dataTask(with: requestManager.getAuthRequest(code: code),
                     completionHandler: { ( data: Data?, response: URLResponse?, error: Error?) -> Void in

        // Make sure we get an OK response
        if let errorMessage = error {
            print(errorMessage.localizedDescription)
            return
        }

        // Read the JSON
        if let postString = NSString(data:data!, encoding: String.Encoding.utf8.rawValue) as String? {

            guard let url = URLComponents(string: "?\(postString)") else { return }

            let oauthTokenResponse = url.queryItems?.first(where: { $0.name == "access_token" })?.value

            // Save oAuthToken to UserDefaults
            UserDefaults.standard.set(oauthTokenResponse, forKey: "oauthToken")

            self.launchNewNote()
        }

    }).resume()
}

In the Request Manager:

func getAuthRequest(code: URLQueryItem?) -> URLRequest {
    let oauthParam = "&code=\(code?.value ?? "")"
    let getTokenPostUrl = URL(string: "https://github.com/login/oauth/access_token\(clientId)\(clientSecret)\(oauthParam)")
    var oauthRequest = URLRequest(url: getTokenPostUrl!)
    oauthRequest.httpMethod = "POST"
    oauthRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    return oauthRequest
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment