Add examples project

This commit is contained in:
Ivan Vorobei
2019-06-06 11:16:28 +03:00
parent 86fe2d7323
commit b866885a44
962 changed files with 45026 additions and 5 deletions

View File

@@ -0,0 +1,41 @@
//
// AppDelegate.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/05.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
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,41 @@
//
// Combine.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/05.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
import Foundation
struct CombineExtension<Base> {
let base: Base
init(_ base: Base) {
self.base = base
}
}
protocol CombineCompatible {
associatedtype CombineExtensionBase
static var combine: CombineExtension<CombineExtensionBase>.Type { get set }
var combine: CombineExtension<CombineExtensionBase> { get set }
}
extension CombineCompatible {
static var combine: CombineExtension<Self>.Type {
get {
return CombineExtension<Self>.self
}
set {}
}
var combine: CombineExtension<Self> {
get {
return CombineExtension<Self>(self)
}
set {}
}
}

View File

@@ -0,0 +1,12 @@
//
// JSONDecoder.Extension.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/06.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
import Combine
import Foundation
extension JSONDecoder: TopLevelDecoder {}

View File

@@ -0,0 +1,58 @@
//
// URLSession.Combine.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/05.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
import Combine
import Foundation
extension URLSession: CombineCompatible {}
extension CombineExtension where Base == URLSession {
func send(request: URLRequest) -> AnyPublisher<Data, URLSessionError> {
AnyPublisher<Data, URLSessionError> { [base] subscriber in
let task = base.dataTask(with: request) { data, response, error in
guard let response = response as? HTTPURLResponse else {
subscriber.receive(completion: .failure(.invalidResponse))
return
}
guard 200..<300 ~= response.statusCode else {
let e = URLSessionError.serverError(statusCode: response.statusCode,
error: error)
subscriber.receive(completion: .failure(e))
return
}
guard let data = data else {
subscriber.receive(completion: .failure(.noData))
return
}
if let error = error {
subscriber.receive(completion: .failure(.unknown(error)))
} else {
_ = subscriber.receive(data)
subscriber.receive(completion: .finished)
}
}
// TODO: cancel task when subscriber cancelled
task.resume()
}
}
}
enum URLSessionError: Error {
case invalidResponse
case noData
case serverError(statusCode: Int, error: Error?)
case unknown(Error)
}

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,13 @@
//
// ItemResponse.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/06.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
import Foundation
struct ItemResponse<T: Decodable>: Decodable {
let items: [T]
}

View File

@@ -0,0 +1,17 @@
//
// Repository.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/05.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
import Foundation
struct Repository: Decodable {
let id: Int
let fullName: String
let description: String?
let stargazersCount: Int
let htmlUrl: URL
}

View File

@@ -0,0 +1,36 @@
//
// RepositoryModel.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/06.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
import Combine
import Foundation
enum RepositoryAPI {
static func search(query: String) -> AnyPublisher<[Repository], Error> {
guard var components = URLComponents(string: "https://api.github.com/search/repositories") else {
return Publishers.Empty<[Repository], Error>().eraseToAnyPublisher()
}
components.queryItems = [URLQueryItem(name: "q", value: query)]
guard let url = components.url else {
return Publishers.Empty<[Repository], Error>().eraseToAnyPublisher()
}
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return URLSession.shared.combine.send(request: request)
.decode(type: ItemResponse<Repository>.self, decoder: decoder)
.map { $0.items }
.handleEvents(receiveOutput: { print($0) },
receiveCompletion: { print($0)})
.eraseToAnyPublisher()
}
}

View File

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

View File

@@ -0,0 +1,61 @@
//
// SceneDelegate.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/05.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
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:
RepositoryListView().environmentObject(RepositoryListViewModel())
)
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,37 @@
//
// RepositoryListView.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/05.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
import SwiftUI
struct RepositoryListView : View {
@EnvironmentObject private var viewModel: RepositoryListViewModel
@State private var text: String = ""
var body: some View {
NavigationView {
TextField($text,
placeholder: Text("Search reposipories..."),
onCommit: { self.viewModel.search(query: self.text) })
.frame(height: 40)
.padding(EdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8))
.border(Color.gray, cornerRadius: 8)
.padding(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
List {
ForEach(viewModel.repositories.identified(by: \.id)) { repository in
RepositoryView(repository: repository)
}
}
.navigationBarTitle(Text("Search🔍"))
}
}
}

View File

@@ -0,0 +1,49 @@
//
// RepositoryListViewModel.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/06.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
import Combine
import Foundation
import SwiftUI
final class RepositoryListViewModel: BindableObject {
let didChange: AnyPublisher<RepositoryListViewModel, Never>
private let _didChange = PassthroughSubject<RepositoryListViewModel, Never>()
private let _searchWithQuery = PassthroughSubject<String, Never>()
private lazy var repositoriesAssign = Subscribers.Assign(object: self, keyPath: \.repositories)
private(set) var repositories: [Repository] = [] {
didSet {
// TODO: Do not want to use DispatchQueue.main here
DispatchQueue.main.async {
self._didChange.send(self)
}
}
}
deinit {
repositoriesAssign.cancel()
}
init() {
self.didChange = _didChange.eraseToAnyPublisher()
_searchWithQuery
.flatMap { query -> AnyPublisher<[Repository], Never> in
RepositoryAPI.search(query: query)
.replaceError(with: [])
.eraseToAnyPublisher()
}
.receive(subscriber: repositoriesAssign)
}
func search(query: String) {
_searchWithQuery.send(query)
}
}

View File

@@ -0,0 +1,36 @@
//
// RepositoryView.swift
// GitHubSearchWithSwiftUI
//
// Created by marty-suzuki on 2019/06/05.
// Copyright © 2019 jp.marty-suzuki. All rights reserved.
//
import SwiftUI
struct RepositoryView : View {
let repository: Repository
var body: some View {
VStack(alignment: .leading) {
HStack {
Image(systemName: "doc.text")
Text(repository.fullName)
.bold()
}
// Show text if description exists
repository.description
.map(Text.init)?
.lineLimit(nil)
HStack {
Image(systemName: "star")
Text("\(repository.stargazersCount)")
}
}
}
}