Add Async image loading

This commit is contained in:
Ivan Vorobei
2019-06-06 22:24:34 +03:00
parent dbabd124fb
commit bcedea412a
914 changed files with 164 additions and 1 deletions

View File

@@ -0,0 +1,33 @@
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}

View File

@@ -0,0 +1,98 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>

View File

@@ -0,0 +1,17 @@
import SwiftUI
struct ContentView : View {
var body: some View {
TimeTravelView(initialState: TodoState()) {
TodoListView()
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif

View File

@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
</dict>
</array>
</dict>
</dict>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>

View File

@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@@ -0,0 +1,51 @@
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Use a UIHostingController as window root view controller
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}

View File

@@ -0,0 +1,11 @@
/// Conforming types serve as the state of a time travelable application
public protocol StateMachine {
/// Events define things that can happen within your application that change its state.
///
/// This might include things like text editing, button taps, or network responses.
associatedtype Event
/// Applies an event to the current state.
mutating func update(with event: Event)
}

View File

@@ -0,0 +1,44 @@
import SwiftUI
import Combine
public final class Store<StateType>: BindableObject where StateType: StateMachine {
private let initialState: StateType
private var subsequentStates: [StateType] = []
public let didChange = PassthroughSubject<Void, Never>()
public init(state: StateType) {
initialState = state
}
var allStates: [StateType] {
[[initialState], subsequentStates].flatMap({ $0 })
}
var stateCount: Int {
1 + subsequentStates.count
}
var currentStateIndex: Int = 0 {
didSet {
withAnimation {
didChange.send(())
}
}
}
/// The current state of the store. This will update as time traveling occurs.
public var state: StateType {
allStates[currentStateIndex]
}
/// Dispatches an event to be applied to the current state.
public func dispatch(event: StateType.Event) {
var newState = state
newState.update(with: event)
subsequentStates.append(newState)
currentStateIndex = stateCount - 1
}
}

View File

@@ -0,0 +1,25 @@
import SwiftUI
struct TimeTravelBarView : View {
@EnvironmentObject var store: Store<TodoState>
var body: some View {
let indexBinding = Binding<Double>(
getValue: { Double(self.store.currentStateIndex) },
setValue: { self.store.currentStateIndex = Int($0) })
return Slider(value: indexBinding, from: 0, through: Double(store.stateCount-1))
.background(Color.white)
.frame(height: 44.0, alignment: .bottom)
.padding()
}
}
#if DEBUG
struct TimeTravelBarView_Previews : PreviewProvider {
static var previews: some View {
TimeTravelBarView()
}
}
#endif

View File

@@ -0,0 +1,39 @@
import SwiftUI
public struct TimeTravelView<StateType, Content>: View where StateType: StateMachine, Content: View {
let initialState: StateType
private let content: Content
@State var store: Store<StateType>? = nil
public init(initialState: StateType, content: () -> Content) {
self.initialState = initialState
self.content = content()
}
public var body: some View {
let store = self.store ?? Store(state: initialState)
if (self.store == nil) {
self.store = store
}
return VStack {
content
TimeTravelBarView()
}
.environmentObject(store)
}
}
#if DEBUG
struct TimeTravelView_Previews : PreviewProvider {
static var previews: some View {
TimeTravelView(initialState: TodoState()) {
TodoListView()
}
}
}
#endif

View File

@@ -0,0 +1,40 @@
import SwiftUI
struct AddItemView: View {
@EnvironmentObject var store: Store<TodoState>
var body: some View {
let textBinding = Binding<String>(
getValue: { self.store.state.partialItemName },
setValue: { self.store.dispatch(event: .changePartialItemName($0)) })
return VStack(spacing: 16) {
TextField(textBinding, placeholder: Text("Title"))
Button(action: {
self.store.dispatch(event: .addItem)
}) {
HStack {
Spacer()
Text("Add").padding([.top, .bottom], 8.0)
Spacer()
}
}
.relativeWidth(1.0)
.background(Color.accentColor)
.disabled(store.state.partialItemName.isEmpty)
.foregroundColor(.white)
.cornerRadius(8.0)
}
.padding()
}
}
#if DEBUG
struct AddItemView_Previews : PreviewProvider {
static var previews: some View {
AddItemView()
}
}
#endif

View File

@@ -0,0 +1,27 @@
import SwiftUI
struct ModalDimmingView : View {
@EnvironmentObject var store: Store<TodoState>
var body: some View {
Color
.black
.relativeWidth(1.0)
.relativeHeight(1.0)
.opacity(0.3)
.edgesIgnoringSafeArea([.bottom, .top])
.transition(.opacity)
.tapAction {
self.store.dispatch(event: .cancelCreatingItem)
}
}
}
#if DEBUG
struct ModalDimmingView_Previews : PreviewProvider {
static var previews: some View {
ModalDimmingView()
}
}
#endif

View File

@@ -0,0 +1,26 @@
import SwiftUI
struct TodoListItemView : View {
@EnvironmentObject var store: Store<TodoState>
let item: TodoItem
var body: some View {
let binding = Binding(
getValue: { self.item.isFinished },
setValue: { self.store.dispatch(event: .setItemDone(identifier: self.item.id, isDone: $0)) })
return Toggle(isOn: binding) {
Text(item.title)
}
}
}
#if DEBUG
struct TodoListItemView_Previews : PreviewProvider {
static var previews: some View {
TodoListItemView(item: TodoItem(id: UUID(), title: "Test", isFinished: false))
}
}
#endif

View File

@@ -0,0 +1,7 @@
import SwiftUI
struct TodoItem: Identifiable {
var id: UUID
var title: String
var isFinished: Bool
}

View File

@@ -0,0 +1,39 @@
import SwiftUI
struct TodoState {
var isCreatingItem: Bool = false
var partialItemName: String = ""
var todoItems: [TodoItem] = []
}
extension TodoState: StateMachine {
enum Event {
case startCreatingItem
case cancelCreatingItem
case changePartialItemName(String)
case addItem
case setItemDone(identifier: UUID, isDone: Bool)
}
mutating func update(with event: TodoState.Event) {
switch event {
case .addItem:
todoItems.append(TodoItem(id: UUID(), title: partialItemName, isFinished: false))
partialItemName = ""
isCreatingItem = false
case .changePartialItemName(let name):
partialItemName = name
case .cancelCreatingItem:
isCreatingItem = false
case .startCreatingItem:
isCreatingItem = true
partialItemName = ""
case .setItemDone(let identifier, let isDone):
if let index = todoItems.firstIndex(where: { $0.id == identifier }) {
todoItems[index].isFinished = isDone
}
}
}
}

View File

@@ -0,0 +1,43 @@
import SwiftUI
struct TodoListView : View {
@EnvironmentObject var store: Store<TodoState>
var body: some View {
ZStack {
NavigationView {
List(store.state.todoItems) { item in TodoListItemView(item: item) }
.navigationBarTitle(Text("Todo List"))
.navigationBarItems(trailing: Button(action: {
withAnimation {
self.store.dispatch(event: .startCreatingItem)
}
}, label: { Image(systemName: "plus.circle") })) }
if store.state.isCreatingItem {
ModalDimmingView()
VStack {
Spacer()
AddItemView()
.relativeWidth(1.0)
.background(Color.white)
.cornerRadius(12.0)
.shadow(radius: 16.0)
.padding()
Spacer()
}
.transition(.move(edge: .bottom))
}
}
}
}
#if DEBUG
struct TodoListView_Previews : PreviewProvider {
static var previews: some View {
TodoListView()
}
}
#endif