Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Last active October 17, 2023 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseidhof/ce581f84670b359fa9036328e7564881 to your computer and use it in GitHub Desktop.
Save chriseidhof/ce581f84670b359fa9036328e7564881 to your computer and use it in GitHub Desktop.
Networking
//
// AppDelegate.swift
// GithubInfo
//
// Created by Chris Eidhof on 25.06.19.
// Copyright © 2019 Chris Eidhof. All rights reserved.
//
import UIKit
import SwiftUI
import Combine
import TinyNetworking
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
}
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()
}
}
}
struct User: Codable {
var name: String
var location: String?
}
func userInfo(login: String) -> Endpoint<User> {
return Endpoint(json: .get, url: URL(string: "https://api.github.com/users/\(login)")!)
}
final class Resource<A>: BindableObject {
let didChange = PassthroughSubject<A?, Never>()
let endpoint: Endpoint<A>
var value: A? {
didSet {
DispatchQueue.main.async {
self.didChange.send(self.value)
}
}
}
init(endpoint: Endpoint<A>) {
self.endpoint = endpoint
reload()
}
func reload() {
URLSession.shared.load(endpoint) { result in
self.value = try? result.get()
}
}
}
struct ContentView : View {
@ObjectBinding var user = Resource(endpoint: userInfo(login: "objcio"))
var body: some View {
Group {
if user.value == nil {
Text("Loading...")
} else {
VStack {
Text(user.value!.name).bold()
Text(user.value!.location ?? "")
}
}
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment