Tusker/Tusker/Screens/Onboarding/OnboardingViewController.swift

84 lines
2.6 KiB
Swift

//
// OnboardingViewController.swift
// Tusker
//
// Created by Shadowfacts on 8/18/18.
// Copyright © 2018 Shadowfacts. All rights reserved.
//
import UIKit
import AuthenticationServices
protocol OnboardingViewControllerDelegate {
func didFinishOnboarding()
}
class OnboardingViewController: UIViewController {
var delegate: OnboardingViewControllerDelegate?
@IBOutlet weak var urlTextField: UITextField!
var authenticationSession: ASWebAuthenticationSession?
init() {
super.init(nibName: "OnboardingViewController", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func loginPressed(_ sender: Any) {
guard let text = urlTextField.text,
let url = URL(string: text),
var components = URLComponents(string: text) else { return }
LocalData.shared.instanceURL = url
MastodonController.createClient()
MastodonController.registerApp {
let clientID = LocalData.shared.clientID!
let callbackURL = "tusker://oauth"
components.path = "/oauth/authorize"
components.queryItems = [
URLQueryItem(name: "client_id", value: clientID),
URLQueryItem(name: "response_type", value: "code"),
URLQueryItem(name: "scope", value: "read write follow"),
URLQueryItem(name: "redirect_uri", value: callbackURL)
]
let url = components.url!
self.authenticationSession = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackURL) { url, error in
guard error == nil,
let url = url,
let components = URLComponents(url: url, resolvingAgainstBaseURL: true),
let item = components.queryItems?.first(where: { $0.name == "code" }),
let authCode = item.value else { fatalError() }
MastodonController.authorize(authorizationCode: authCode) {
DispatchQueue.main.async {
self.delegate?.didFinishOnboarding()
}
}
}
self.authenticationSession!.start()
}
}
@IBAction func clearDataPressed(_ sender: Any) {
LocalData.shared.instanceURL = nil
LocalData.shared.clientID = nil
LocalData.shared.clientSecret = nil
LocalData.shared.accessToken = nil
}
}