Skip to content

Instantly share code, notes, and snippets.

@AlexandreCools
Created May 17, 2020 14:24
Show Gist options
  • Select an option

  • Save AlexandreCools/d61505bce60da5b1a21105f87046509b to your computer and use it in GitHub Desktop.

Select an option

Save AlexandreCools/d61505bce60da5b1a21105f87046509b to your computer and use it in GitHub Desktop.
MEDIUM] Strava API - Access & Refresh token - iOS 13, Swift 5 - Step 7
import UIKit
import AuthenticationServices
class ViewController: UIViewController {
private var authSession: ASWebAuthenticationSession?
private let clientId: String = "11111"
private let urlScheme: String = "youUrlScheme"
private let fallbackUrl: String = "yourFallbackUrl"
private let clientSecret: String = "yourClientSecret"
@IBAction private func connectToStrava(_ sender: UIButton) {
presentStravaAuthentication()
}
private func presentStravaAuthentication() {
let url: String = "https://www.strava.com/oauth/mobile/authorize?client_id=\(clientId)&redirect_uri=\(urlScheme)%3A%2F%2F\(fallbackUrl)&response_type=code&approval_prompt=auto&scope=read"
guard let authenticationUrl = URL(string: url) else { return }
authSession = ASWebAuthenticationSession(url: authenticationUrl, callbackURLScheme: "\(urlScheme)://") { [weak self] url, error in
if let error = error {
print(error)
} else {
if let code = self?.getCode(from: url) {
print(code)
}
}
}
authSession?.presentationContextProvider = self
authSession?.start()
}
private func getCode(from url: URL?) -> String? {
guard let url = url?.absoluteString else { return nil }
let urlComponents: URLComponents? = URLComponents(string: url)
let code: String? = urlComponents?.queryItems?.filter { $0.name == "code" }.first?.value
return code
}
private func requestStravaTokens(with code: String) {
let parameters: [String: Any] = ["client_id": clientId, "client_secret": clientSecret, "code": code, "grant_type": "authorization_code"]
AF.request("https://www.strava.com/oauth/token", method: .post, parameters: parameters).response { response in
guard let data = response.data else { return }
if let json = try? JSONSerialization.jsonObject(with: data, options: []) {
print(json)
}
}
}
}
extension ViewController: ASWebAuthenticationPresentationContextProviding {
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
UIApplication.shared.windows[0]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment