Skip to content

Instantly share code, notes, and snippets.

View TwitterAPI.swift
import SwiftUI
import Combine
import CommonCrypto
class TwitterAPI: NSObject, ObservableObject {
@Published var authorizationSheetIsPresented = false
@Published var authorizationURL: URL?
@Published var user: User?
private var tokenCredentials: TokenCredentials?
View SafariView.swift
import SwiftUI
import SafariServices
struct SafariView: UIViewControllerRepresentable {
class SafariViewControllerWrapper: UIViewController {
private var safariViewController: SFSafariViewController?
var url: URL? {
didSet {
if let safariViewController = safariViewController {
View ContentView.swift
import SwiftUI
import Combine
struct ContentView: View {
@EnvironmentObject var twitterAPI: TwitterAPI
var body: some View {
VStack {
if let screenName = twitterAPI.user?.screenName {
Text("Welcome").font(.largeTitle)
View TwitterTutorialApp.swift
import SwiftUI
@main
struct TwitterTutorialApp: App {
@StateObject var twitterAPI = TwitterAPI()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(twitterAPI)
View oAuthAccessTokenSubscriber.swift
self.subscriptions["oAuthAccessTokenSubscriber"] =
self.oAuthAccessTokenPublisher(temporaryCredentials: temporaryCredentials,
verifier: oAuthVerifier) // 1
.receive(on: DispatchQueue.main) // 2
.sink(receiveCompletion: { _ in // 3
// Error handler
}, receiveValue: { [weak self] (tokenCredentials, user) in // 4
guard let self = self else { return }
// 5
View tokenCredentials.swift
private var tokenCredentials: TokenCredentials?
View TokenCredentials.swift
struct TokenCredentials {
let accessToken: String
let accessTokenSecret: String
}
View TwitterOAuthAccessTokenPublisher.swift
func oAuthAccessTokenPublisher(temporaryCredentials: TemporaryCredentials, verifier: String) -> AnyPublisher<(TokenCredentials, User), OAuthError> {
// 1
let request = (baseURLString: "https://api.twitter.com/oauth/access_token",
httpMethod: "POST",
consumerKey: ClientCredentials.APIKey,
consumerSecret: ClientCredentials.APIKeySecret)
// 2
guard let baseURL = URL(string: request.baseURLString) else {
return Fail(error: OAuthError.urlError(URLError(.badURL)))
View TwitterAPI-Authorize(1).swift
private var subscriptions: [String: AnyCancellable] = [:] // 1
func authorize() {
// 2
guard !self.authorizationSheetIsPresented else { return }
self.authorizationSheetIsPresented = true
// 3
self.subscriptions["oAuthRequestTokenSubscriber"] =
self.oAuthRequestTokenPublisher()
View ContentView.swift
import SwiftUI
struct ContentView: View {
@EnvironmentObject var twitterAPI: TwitterAPI // 1
var body: some View {
VStack {
if let screenName = twitterAPI.user?.screenName { // 2
Text("Welcome").font(.largeTitle)
Text(screenName).font(.largeTitle)