hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
1e5090bef4ebd2a76b95cda59717b950898ff368 | 698 | //
// RequestHeader.swift
// VFNetwork
//
// Created by Victor Alves De Freitas on 30/06/19.
// Copyright © 2019 brvlab. All rights reserved.
//
import Foundation
class RequestHeader {
/**
Enum for http content types
*/
enum ContentType: String {
case json = "application/json"
case urlEncoded = "application/x-www-form-urlencoded"
}
/**
Method for generate a "default" http request header based on ContentType choosed.
- Parameters:
- type: ContentType
- Returns:
Void
*/
func `default`(_ type: ContentType) -> [String: String] {
return ["Content-Type": type.rawValue]
}
}
| 20.529412 | 87 | 0.594556 |
f5fb7f17997dcbe272d0a2b11a2668d80f46ce70 | 334 | //
// RoundedView.swift
// Dictionary
//
// Created by Alex Golub on 9/23/16.
// Copyright © 2016 Alex Golub. All rights reserved.
//
import UIKit
@IBDesignable class RoundedView: UIView {
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
}
| 17.578947 | 53 | 0.61976 |
9cb5f795abc13164a58e1afeeb777c7608fa0e74 | 663 | //
// ButtonTheme.swift
// roundrect
//
// Created by Gabriel O'Flaherty-Chan on 2019-01-11.
// Copyright © 2019 gabrieloc. All rights reserved.
//
import UIKit
// dark theme is dark button with light text
// light theme is light button with dark text
extension UIButton {
enum Theme: String, CaseIterable {
case extraLight, light, dark
var foregroundColor: UIColor {
switch self {
case .light, .extraLight:
return .black
default:
return .white
}
}
var inverse: Theme {
switch self {
case .dark:
return .light
default:
return .dark
}
}
}
}
| 17.918919 | 53 | 0.594268 |
bfc47b1b80138bcb71d92cde0fcd3299b9a3b7c4 | 11,235 | // ScanfileProtocol.swift
// Copyright (c) 2020 FastlaneTools
public protocol ScanfileProtocol: class {
/// Path to the workspace file
var workspace: String? { get }
/// Path to the project file
var project: String? { get }
/// The project's scheme. Make sure it's marked as `Shared`
var scheme: String? { get }
/// The name of the simulator type you want to run tests on (e.g. 'iPhone 6')
var device: String? { get }
/// Array of devices to run the tests on (e.g. ['iPhone 6', 'iPad Air'])
var devices: [String]? { get }
/// Should skip auto detecting of devices if none were specified
var skipDetectDevices: Bool { get }
/// Enabling this option will automatically killall Simulator processes before the run
var forceQuitSimulator: Bool { get }
/// Enabling this option will automatically erase the simulator before running the application
var resetSimulator: Bool { get }
/// Enabling this option will disable the simulator from showing the 'Slide to type' prompt
var disableSlideToType: Bool { get }
/// Enabling this option will launch the first simulator prior to calling any xcodebuild command
var prelaunchSimulator: Bool? { get }
/// Enabling this option will automatically uninstall the application before running it
var reinstallApp: Bool { get }
/// The bundle identifier of the app to uninstall (only needed when enabling reinstall_app)
var appIdentifier: String? { get }
/// Array of strings matching Test Bundle/Test Suite/Test Cases to run
var onlyTesting: String? { get }
/// Array of strings matching Test Bundle/Test Suite/Test Cases to skip
var skipTesting: String? { get }
/// The testplan associated with the scheme that should be used for testing
var testplan: String? { get }
/// Array of strings matching test plan configurations to run
var onlyTestConfigurations: String? { get }
/// Array of strings matching test plan configurations to skip
var skipTestConfigurations: String? { get }
/// Run tests using the provided `.xctestrun` file
var xctestrun: String? { get }
/// The toolchain that should be used for building the application (e.g. `com.apple.dt.toolchain.Swift_2_3, org.swift.30p620160816a`)
var toolchain: String? { get }
/// Should the project be cleaned before building it?
var clean: Bool { get }
/// Should code coverage be generated? (Xcode 7 and up)
var codeCoverage: Bool? { get }
/// Should the address sanitizer be turned on?
var addressSanitizer: Bool? { get }
/// Should the thread sanitizer be turned on?
var threadSanitizer: Bool? { get }
/// Should the HTML report be opened when tests are completed?
var openReport: Bool { get }
/// Disable xcpretty formatting of build, similar to `output_style='raw'` but this will also skip the test results table
var disableXcpretty: Bool? { get }
/// The directory in which all reports will be stored
var outputDirectory: String { get }
/// Define how the output should look like. Valid values are: standard, basic, rspec, or raw (disables xcpretty during xcodebuild)
var outputStyle: String? { get }
/// Comma separated list of the output types (e.g. html, junit, json-compilation-database)
var outputTypes: String { get }
/// Comma separated list of the output files, corresponding to the types provided by :output_types (order should match). If specifying an output type of json-compilation-database with :use_clang_report_name enabled, that option will take precedence
var outputFiles: String? { get }
/// The directory where to store the raw log
var buildlogPath: String { get }
/// If the logs generated by the app (e.g. using NSLog, perror, etc.) in the Simulator should be written to the output_directory
var includeSimulatorLogs: Bool { get }
/// Suppress the output of xcodebuild to stdout. Output is still saved in buildlog_path
var suppressXcodeOutput: Bool? { get }
/// A custom xcpretty formatter to use
var formatter: String? { get }
/// Pass in xcpretty additional command line arguments (e.g. '--test --no-color' or '--tap --no-utf')
var xcprettyArgs: String? { get }
/// The directory where build products and other derived data will go
var derivedDataPath: String? { get }
/// Should zip the derived data build products and place in output path?
var shouldZipBuildProducts: Bool { get }
/// Should an Xcode result bundle be generated in the output directory
var resultBundle: Bool { get }
/// Generate the json compilation database with clang naming convention (compile_commands.json)
var useClangReportName: Bool { get }
/// Specify the exact number of test runners that will be spawned during parallel testing. Equivalent to -parallel-testing-worker-count
var concurrentWorkers: Int? { get }
/// Constrain the number of simulator devices on which to test concurrently. Equivalent to -maximum-concurrent-test-simulator-destinations
var maxConcurrentSimulators: Int? { get }
/// Do not run test bundles in parallel on the specified destinations. Testing will occur on each destination serially. Equivalent to -disable-concurrent-testing
var disableConcurrentTesting: Bool { get }
/// Should debug build be skipped before test build?
var skipBuild: Bool { get }
/// Test without building, requires a derived data path
var testWithoutBuilding: Bool? { get }
/// Build for testing only, does not run tests
var buildForTesting: Bool? { get }
/// The SDK that should be used for building the application
var sdk: String? { get }
/// The configuration to use when building the app. Defaults to 'Release'
var configuration: String? { get }
/// Pass additional arguments to xcodebuild. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS="-ObjC -lstdc++"
var xcargs: String? { get }
/// Use an extra XCCONFIG file to build your app
var xcconfig: String? { get }
/// App name to use in slack message and logfile name
var appName: String? { get }
/// Target version of the app being build or tested. Used to filter out simulator version
var deploymentTargetVersion: String? { get }
/// Create an Incoming WebHook for your Slack group to post results there
var slackUrl: String? { get }
/// #channel or @username
var slackChannel: String? { get }
/// The message included with each message posted to slack
var slackMessage: String? { get }
/// Use webhook's default username and icon settings? (true/false)
var slackUseWebhookConfiguredUsernameAndIcon: Bool { get }
/// Overrides the webhook's username property if slack_use_webhook_configured_username_and_icon is false
var slackUsername: String { get }
/// Overrides the webhook's image property if slack_use_webhook_configured_username_and_icon is false
var slackIconUrl: String { get }
/// Don't publish to slack, even when an URL is given
var skipSlack: Bool { get }
/// Only post on Slack if the tests fail
var slackOnlyOnFailure: Bool { get }
/// Use only if you're a pro, use the other options instead
var destination: String? { get }
/// Platform to build when using a Catalyst enabled app. Valid values are: ios, macos
var catalystPlatform: String? { get }
/// **DEPRECATED!** Use `--output_files` instead - Sets custom full report file name when generating a single report
var customReportFileName: String? { get }
/// Allows for override of the default `xcodebuild` command
var xcodebuildCommand: String { get }
/// Sets a custom path for Swift Package Manager dependencies
var clonedSourcePackagesPath: String? { get }
/// Should this step stop the build if the tests fail? Set this to false if you're using trainer
var failBuild: Bool { get }
}
public extension ScanfileProtocol {
var workspace: String? { return nil }
var project: String? { return nil }
var scheme: String? { return nil }
var device: String? { return nil }
var devices: [String]? { return nil }
var skipDetectDevices: Bool { return false }
var forceQuitSimulator: Bool { return false }
var resetSimulator: Bool { return false }
var disableSlideToType: Bool { return true }
var prelaunchSimulator: Bool? { return nil }
var reinstallApp: Bool { return false }
var appIdentifier: String? { return nil }
var onlyTesting: String? { return nil }
var skipTesting: String? { return nil }
var testplan: String? { return nil }
var onlyTestConfigurations: String? { return nil }
var skipTestConfigurations: String? { return nil }
var xctestrun: String? { return nil }
var toolchain: String? { return nil }
var clean: Bool { return false }
var codeCoverage: Bool? { return nil }
var addressSanitizer: Bool? { return nil }
var threadSanitizer: Bool? { return nil }
var openReport: Bool { return false }
var disableXcpretty: Bool? { return nil }
var outputDirectory: String { return "./test_output" }
var outputStyle: String? { return nil }
var outputTypes: String { return "html,junit" }
var outputFiles: String? { return nil }
var buildlogPath: String { return "~/Library/Logs/scan" }
var includeSimulatorLogs: Bool { return false }
var suppressXcodeOutput: Bool? { return nil }
var formatter: String? { return nil }
var xcprettyArgs: String? { return nil }
var derivedDataPath: String? { return nil }
var shouldZipBuildProducts: Bool { return false }
var resultBundle: Bool { return false }
var useClangReportName: Bool { return false }
var concurrentWorkers: Int? { return nil }
var maxConcurrentSimulators: Int? { return nil }
var disableConcurrentTesting: Bool { return false }
var skipBuild: Bool { return false }
var testWithoutBuilding: Bool? { return nil }
var buildForTesting: Bool? { return nil }
var sdk: String? { return nil }
var configuration: String? { return nil }
var xcargs: String? { return nil }
var xcconfig: String? { return nil }
var appName: String? { return nil }
var deploymentTargetVersion: String? { return nil }
var slackUrl: String? { return nil }
var slackChannel: String? { return nil }
var slackMessage: String? { return nil }
var slackUseWebhookConfiguredUsernameAndIcon: Bool { return false }
var slackUsername: String { return "fastlane" }
var slackIconUrl: String { return "https://fastlane.tools/assets/img/fastlane_icon.png" }
var skipSlack: Bool { return false }
var slackOnlyOnFailure: Bool { return false }
var destination: String? { return nil }
var catalystPlatform: String? { return nil }
var customReportFileName: String? { return nil }
var xcodebuildCommand: String { return "env NSUnbufferedIO=YES xcodebuild" }
var clonedSourcePackagesPath: String? { return nil }
var failBuild: Bool { return true }
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.58]
| 41.921642 | 252 | 0.698709 |
91efd7f7cff910b4656388486db9e53d8581f5b2 | 5,022 | //
// Tool.swift
// QRCode
//
// Created by gaofu on 16/9/9.
// Copyright © 2016年 gaofu. All rights reserved.
//
import UIKit
import AudioToolbox
struct PhotoSource:OptionSet
{
let rawValue:Int
static let camera = PhotoSource(rawValue: 1)
static let photoLibrary = PhotoSource(rawValue: 1<<1)
}
func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool
{
switch (lhs, rhs)
{
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool
{
switch (lhs, rhs)
{
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
typealias finishedImage = (_ image:UIImage) -> ()
class Tool: NSObject
{
///1.单例
static let shareTool = Tool()
private override init() {}
var finishedImg : finishedImage?
var isEditor = false
///2.选择图片
func choosePicture(_ controller : UIViewController, editor : Bool,options : PhotoSource = [.camera,.photoLibrary], finished : @escaping finishedImage)
{
finishedImg = finished
isEditor = editor
if options.contains(.camera) && options.contains(.photoLibrary)
{
let alertController = UIAlertController(title: "请选择图片", message: nil, preferredStyle: .actionSheet)
let photographAction = UIAlertAction(title: "拍照", style: .default) { (_) in
self.openCamera(controller: controller, editor: editor)
}
let photoAction = UIAlertAction(title: "从相册选取", style: .default) { (_) in
self.openPhotoLibrary(controller: controller, editor: editor)
}
let cannelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alertController.addAction(photographAction)
alertController.addAction(photoAction)
alertController.addAction(cannelAction)
controller.present(alertController, animated: true, completion: nil)
}
else if options.contains(.photoLibrary)
{
self.openPhotoLibrary(controller: controller, editor: editor)
}
else if options.contains(.camera)
{
self.openCamera(controller: controller, editor: editor)
}
}
///打开相册
func openPhotoLibrary(controller : UIViewController, editor : Bool)
{
let photo = UIImagePickerController()
photo.delegate = self
photo.sourceType = .photoLibrary
photo.allowsEditing = editor
controller.present(photo, animated: true, completion: nil)
}
///打开相机
func openCamera(controller : UIViewController, editor : Bool)
{
guard UIImagePickerController.isSourceTypeAvailable(.camera) else { return }
let photo = UIImagePickerController()
photo.delegate = self
photo.sourceType = .camera
photo.allowsEditing = editor
controller.present(photo, animated: true, completion: nil)
}
///3.确认弹出框
class func confirm(title:String?,message:String?,controller:UIViewController,handler: ( (UIAlertAction) -> Swift.Void)? = nil)
{
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let entureAction = UIAlertAction(title: "确定", style: .destructive, handler: handler)
alertVC.addAction(entureAction)
controller.present(alertVC, animated: true, completion: nil)
}
///4.播放声音
class func playAlertSound(sound:String)
{
guard let soundPath = Bundle.main.path(forResource: sound, ofType: nil) else { return }
guard let soundUrl = NSURL(string: soundPath) else { return }
var soundID:SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundUrl, &soundID)
AudioServicesPlaySystemSound(soundID)
}
}
//MARK: -
//MARK: Delegate
extension Tool : UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
guard let image = info[isEditor ? UIImagePickerControllerEditedImage : UIImagePickerControllerOriginalImage] as? UIImage else { return }
picker.dismiss(animated: true) { [weak self] in
guard let tmpFinishedImg = self?.finishedImg else { return }
tmpFinishedImg(image)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
picker.dismiss(animated: true, completion: nil)
}
}
| 25.622449 | 155 | 0.585026 |
4b92478090be2ffff3e492d21f1415e0c70714fb | 8,231 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
The view controller that displays the postcards.
*/
import UIKit
class ViewController: UIViewController,
UIFontPickerViewControllerDelegate,
UINavigationControllerDelegate,
UIImagePickerControllerDelegate,
UITextViewDelegate {
@IBOutlet var imageView: UIImageView!
@IBOutlet var textView: UITextView!
var imageViewAspectRatioConstraint: NSLayoutConstraint?
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
imageView.layer.cornerRadius = 8.0
imageView.layer.cornerCurve = .continuous
}
// MARK: SettingsViewController
@IBAction func showSettings(_ sender: UIBarButtonItem) {
guard presentedViewController == nil else {
dismiss(animated: true, completion: {
self.showSettings(sender)
})
return
}
// MARK: - 属性注释
if let settingsViewController = self.storyboard?.instantiateViewController(withIdentifier: "settings") {
// 设置转场样式为popover
settingsViewController.modalPresentationStyle = .popover
if let popover = settingsViewController.popoverPresentationController {
popover.barButtonItem = sender
// 获取UISheetPresentationController
let sheet = popover.adaptiveSheetPresentationController
// 设置内容大小
sheet.detents = [.medium(), .large()]
sheet.largestUndimmedDetentIdentifier =
PresentationHelper.sharedInstance.largestUndimmedDetentIdentifier
// 设置为NO,滚动到顶部 拖动不能展开
sheet.prefersScrollingExpandsWhenScrolledToEdge =
PresentationHelper.sharedInstance.prefersScrollingExpandsWhenScrolledToEdge
// 是否适配横屏尺寸,充满安全域
sheet.prefersEdgeAttachedInCompactHeight =
PresentationHelper.sharedInstance.prefersEdgeAttachedInCompactHeight
// YES:允许preferredContentSize在边缘附加时影响工作表的宽度
sheet.widthFollowsPreferredContentSizeWhenEdgeAttached =
PresentationHelper.sharedInstance.widthFollowsPreferredContentSizeWhenEdgeAttached
}
textView.resignFirstResponder()
present(settingsViewController, animated: true, completion: nil)
}
}
// MARK: UIImagePickerViewController
@IBAction func showImagePicker(_ sender: UIBarButtonItem) {
guard presentedViewController == nil else {
dismiss(animated: true, completion: {
self.showImagePicker(sender)
})
return
}
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.modalPresentationStyle = .popover
if let popover = imagePicker.popoverPresentationController {
popover.barButtonItem = sender
let sheet = popover.adaptiveSheetPresentationController
sheet.detents = [.medium(), .large()]
sheet.largestUndimmedDetentIdentifier = .medium
sheet.prefersScrollingExpandsWhenScrolledToEdge =
PresentationHelper.sharedInstance.prefersScrollingExpandsWhenScrolledToEdge
sheet.prefersEdgeAttachedInCompactHeight =
PresentationHelper.sharedInstance.prefersEdgeAttachedInCompactHeight
sheet.widthFollowsPreferredContentSizeWhenEdgeAttached =
PresentationHelper.sharedInstance.widthFollowsPreferredContentSizeWhenEdgeAttached
}
textView.resignFirstResponder()
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let image = info[.originalImage] as? UIImage {
imageView.image = image
if let constraint = imageViewAspectRatioConstraint {
NSLayoutConstraint.deactivate([constraint])
}
let newConstraint = imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: image.size.width / image.size.height)
NSLayoutConstraint.activate([newConstraint])
imageViewAspectRatioConstraint = newConstraint
view.layoutIfNeeded()
}
// MARK: - 选中动画缩回
if let sheet = picker.popoverPresentationController?.adaptiveSheetPresentationController {
// 无动画更新大小
// sheet.selectedDetentIdentifier = .medium
// 动画改变大小
sheet.animateChanges {
sheet.selectedDetentIdentifier = .medium
}
}
}
// MARK: UIFontPickerViewController
@IBAction func showFontPicker(_ sender: UIBarButtonItem) {
guard presentedViewController == nil else {
dismiss(animated: true, completion: {
self.showFontPicker(sender)
})
return
}
let fontPicker = UIFontPickerViewController()
fontPicker.delegate = self
fontPicker.modalPresentationStyle = .popover
if let popover = fontPicker.popoverPresentationController {
popover.barButtonItem = sender
let sheet = popover.adaptiveSheetPresentationController
sheet.detents = [.medium(), .large()]
sheet.largestUndimmedDetentIdentifier =
PresentationHelper.sharedInstance.largestUndimmedDetentIdentifier
sheet.prefersScrollingExpandsWhenScrolledToEdge =
PresentationHelper.sharedInstance.prefersScrollingExpandsWhenScrolledToEdge
sheet.prefersEdgeAttachedInCompactHeight =
PresentationHelper.sharedInstance.prefersEdgeAttachedInCompactHeight
sheet.widthFollowsPreferredContentSizeWhenEdgeAttached =
PresentationHelper.sharedInstance.widthFollowsPreferredContentSizeWhenEdgeAttached
}
textView.resignFirstResponder()
present(fontPicker, animated: true, completion: nil)
let inputView = UIInputView(frame: .zero, inputViewStyle: .default)
inputView.isUserInteractionEnabled = false
inputView.allowsSelfSizing = true
textView.inputView = inputView
textView.reloadInputViews()
}
func fontPickerViewControllerDidPickFont(_ viewController: UIFontPickerViewController) {
if let descriptor = viewController.selectedFontDescriptor {
let font = UIFont(descriptor: descriptor, size: 56.0)
let selectedRange = textView.selectedRange
if textView.isFirstResponder {
let attributedText = NSMutableAttributedString(attributedString: textView.attributedText)
attributedText.addAttribute(.font, value: font, range: selectedRange)
textView.attributedText = attributedText
textView.selectedRange = selectedRange
} else {
textView.font = font
}
view.layoutIfNeeded()
}
if let sheet = viewController.popoverPresentationController?.adaptiveSheetPresentationController {
sheet.animateChanges {
sheet.selectedDetentIdentifier = .medium
}
}
}
func fontPickerViewControllerDidCancel(_ viewController: UIFontPickerViewController) {
dismiss(animated: true)
}
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
super.dismiss(animated: flag, completion: completion)
// Reset the inputView each time we dismiss a view controller.
self.textView.inputView = nil
self.textView.reloadInputViews()
}
// MARK: UITextView
func textViewDidBeginEditing(_ textView: UITextView) {
if presentedViewController != nil {
dismiss(animated: true)
}
}
}
| 39.195238 | 147 | 0.646094 |
795082fe4d713cf1b5798f3b4b1af05f06f34acc | 209 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum S<T where T:Dictionary<g,C>{func c
| 34.833333 | 87 | 0.76555 |
9cb8524ef246134a5530fd4285d19b1616cb9e65 | 272 | //
// Secret.swift
// ChampSelect
//
// Created by Chinmay Ghotkar on 4/18/18.
// Copyright © 2018 Chinmay Ghotkar. All rights reserved.
//
import Foundation
struct Key {
struct Riot{
static let API = "RGAPI-9d60161d-fb1f-429f-a5fc-d64fb8ed7112"
}
}
| 17 | 69 | 0.661765 |
e410a53f1ced936a4dddb7adff761ae8566e6b07 | 2,152 | //
// AppDelegate.swift
// RHAnimatedTitleView
//
// Created by Roy Hsu on 2015/3/31.
// Copyright (c) 2015年 tinyWorld. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.787234 | 285 | 0.754647 |
e0b0db3046126dd429fb26eb1160e14eb916c926 | 2,411 | //
// AXPagingConfig.swift
// AXPhotoViewer
//
// Created by Alex Hill on 6/1/17.
// Copyright © 2017 Alex Hill. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
fileprivate let DefaultHorizontalSpacing: CGFloat = 20
@objc open class AXPagingConfig: NSObject {
/// Navigation configuration to be applied to the internal pager of the `PhotosViewController`.
@objc fileprivate(set) var navigationOrientation: UIPageViewController.NavigationOrientation
/// Space between photos, measured in points. Applied to the internal pager of the `PhotosViewController` at initialization.
@objc fileprivate(set) var interPhotoSpacing: CGFloat
/// The loading view class which will be instantiated instead of the default `AXLoadingView`.
@objc fileprivate(set) var loadingViewClass: AXLoadingViewProtocol.Type = AXLoadingView.self
@objc public init(navigationOrientation: UIPageViewController.NavigationOrientation,
interPhotoSpacing: CGFloat,
loadingViewClass: AXLoadingViewProtocol.Type? = nil) {
self.navigationOrientation = navigationOrientation
self.interPhotoSpacing = interPhotoSpacing
super.init()
if let loadingViewClass = loadingViewClass {
guard loadingViewClass is UIView.Type else {
assertionFailure("`loadingViewClass` must be a UIView.")
return
}
self.loadingViewClass = loadingViewClass
}
}
@objc public convenience override init() {
self.init(navigationOrientation: .horizontal, interPhotoSpacing: DefaultHorizontalSpacing, loadingViewClass: nil)
}
@objc public convenience init(navigationOrientation: UIPageViewController.NavigationOrientation) {
self.init(navigationOrientation: navigationOrientation, interPhotoSpacing: DefaultHorizontalSpacing, loadingViewClass: nil)
}
@objc public convenience init(interPhotoSpacing: CGFloat) {
self.init(navigationOrientation: .horizontal, interPhotoSpacing: interPhotoSpacing, loadingViewClass: nil)
}
@objc public convenience init(loadingViewClass: AXLoadingViewProtocol.Type?) {
self.init(navigationOrientation: .horizontal, interPhotoSpacing: DefaultHorizontalSpacing, loadingViewClass: loadingViewClass)
}
}
| 38.887097 | 134 | 0.709664 |
18b0a1128b8ae34c3d4c62642b2f927c9f45ace9 | 1,181 | //
// SFDisplayLinkView.swift
// iOSTips
//
// Created by brian on 2018/3/12.
// Copyright © 2018年 brian. All rights reserved.
//
import UIKit
class SFDisplayLinkView: UIView {
var y: CGFloat = 0
override func awakeFromNib() {
super.awakeFromNib()
/*
* CADisplayLink定时器在每一个屏幕刷新时调用(屏幕每一秒至少刷新60次)
*/
let displayLink = CADisplayLink(target: self, selector: #selector(update))
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
@objc
func update() {
y += 5
if y > bounds.height {
y = 0
}
/*
* setNeedsDisplay方法在屏幕刷新时会调用drawRect方法
* 因为定时器CADisplayLink执行方法的时间(屏幕刷新时)和setNeedDisplay调用drawRect方法(屏幕刷新时重绘)的时间是一致的。所以动画会很流畅
* 适用的场景:二维码扫描的“扫描线”
*/
self.setNeedsDisplay()
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
let image = UIImage(named: "snow")
image?.draw(at: CGPoint(x: 0, y: y))
}
}
| 24.604167 | 95 | 0.595258 |
ffb59e2bbfe545fae1444752c6a51e022a403b8c | 715 | //
// Array+NSCopying.swift
// StockMarketForecaster
//
// Created by Dicky on 02/06/20.
// Copyright © 2020 Organization Name. All rights reserved.
//
import Foundation
extension Array where Element: NSCopying {
func copy(with zone: NSZone? = nil) -> [Element] {
var result: [Element] = []
for element in self {
let copiedElement = element.copy(with: zone) as? Element
if let data = copiedElement {
result.append(data)
}
}
return result
}
}
extension Array {
subscript(safe index: Int) -> Element? {
guard index >= 0 && index < self.count else { return nil }
return self[index]
}
}
| 23.064516 | 68 | 0.576224 |
1c015dd6b7cdbe107ce507fa11574b3f7f6db192 | 1,184 | import Foundation
/// All mockable declaration types conform to this protocol.
public protocol Declaration {}
/// Mockable declarations.
public class AnyDeclaration: Declaration {}
/// Mockable variable declarations.
public class VariableDeclaration: Declaration {}
/// Mockable property getter declarations.
public class PropertyGetterDeclaration: VariableDeclaration {}
/// Mockable property setter declarations.
public class PropertySetterDeclaration: VariableDeclaration {}
/// Mockable function declarations.
public class FunctionDeclaration: Declaration {}
/// Mockable throwing function declarations.
public class ThrowingFunctionDeclaration: FunctionDeclaration {}
/// Mockable subscript declarations.
public class SubscriptDeclaration: Declaration {}
/// Mockable subscript getter declarations.
public class SubscriptGetterDeclaration: SubscriptDeclaration {}
/// Mockable subscript setter declarations.
public class SubscriptSetterDeclaration: SubscriptDeclaration {}
/// Represents a mocked declaration that can be stubbed or verified.
public struct Mockable<DeclarationType: Declaration, InvocationType, ReturnType> {
let mock: Mock
let invocation: Invocation
}
| 35.878788 | 82 | 0.816723 |
79eedea7278d50ad58beb5611d53838496b69583 | 1,719 | //
// Injection.swift
// Injection
//
// Created by Gary Hanson on 8/28/21.
//
// Property wrapper based injection has been around for a couple of years. Very clean, and swift-y.
// I like this implementation which does that in a very nice way.
// Based on article from Antoine van der Lee: https://www.avanderlee.com/swift/dependency-injection/
//
import Foundation
public protocol InjectionKey {
/// The associated type representing the type of the dependency injection key's value.
associatedtype Value
/// The default value for the dependency injection key.
static var currentValue: Self.Value { get set }
}
/// Provides access to injected dependencies.
struct InjectedValues {
/// This is only used as an accessor to the computed properties within extensions of `InjectedValues`.
private static var current = InjectedValues()
/// A static subscript for updating the `currentValue` of `InjectionKey` instances.
static subscript<K>(key: K.Type) -> K.Value where K : InjectionKey {
get { key.currentValue }
set { key.currentValue = newValue }
}
/// A static subscript accessor for updating and references dependencies directly.
static subscript<T>(_ keyPath: WritableKeyPath<InjectedValues, T>) -> T {
get { current[keyPath: keyPath] }
set { current[keyPath: keyPath] = newValue }
}
}
@propertyWrapper
struct Injected<T> {
private let keyPath: WritableKeyPath<InjectedValues, T>
var wrappedValue: T {
get { InjectedValues[keyPath] }
set { InjectedValues[keyPath] = newValue }
}
init(_ keyPath: WritableKeyPath<InjectedValues, T>) {
self.keyPath = keyPath
}
}
| 30.696429 | 106 | 0.688191 |
6199ec61734e1746b5e43010d27dfa83e0c7daec | 54,224 | //
// SJSwiftSideMenuController.swift
// SJSwiftNavigationController
//
// Created by Sumit Jagdev on 1/6/17.
// Copyright © 2017 Sumit Jagdev. All rights reserved.
//
import UIKit
public enum SJSideMenuPosition {
case LEFT
case RIGHT
case NONE
}
public enum SJSideMenuType {
case SlideOver
case SlideView
}
public class SJSwiftSideMenuController: UIViewController, UINavigationControllerDelegate {
private static var swipeMenuSide : SJSideMenuPosition = .NONE
private static var isSetup : Bool = false
public static var enableDimbackground : Bool = false
public static var shouldLeaveSpaceForStatusBar : Bool = false
private static var shouldShowLeftButton : Bool = false
private static var shouldShowRightButton : Bool = false
private static var menuIcon_Left : UIImage = UIImage()
private static var menuIcon_Right : UIImage = UIImage()
private static var navigator : UINavigationController! = nil
public static var navigationContainer : UIViewController! = nil
// left menu views
private static var leftSideMenuController : UIViewController!
private static var leftSideMenuType : SJSideMenuType = .SlideView
public static var leftMenuWidth : CGFloat = 150
private static var leftSideMenuView : UIView! = UIView()
// Right menu views
private static var rightSideMenuController : UIViewController!
private static var rightSideMenuType : SJSideMenuType = .SlideView
public static var rightMenuWidth : CGFloat = 250
private static var rightSideMenuView : UIView! = UIView()
private static var containerView : UIView! = UIView()
private static var dimBGView : UIView! = UIView()
// Left Menu constraint
private static var leadingConstraintOfSideMenu_Left : NSLayoutConstraint!
private static var topConstraintOfSideMenu_Left : NSLayoutConstraint!
private static var bottomConstraintOfSideMenu_Left : NSLayoutConstraint!
private static var widthConstraintOfSideMenu_Left : NSLayoutConstraint!
// Right Menu constraint
private static var leadingConstraintOfSideMenu_Right : NSLayoutConstraint!
private static var topConstraintOfSideMenu_Right : NSLayoutConstraint!
private static var bottomConstraintOfSideMenu_Right : NSLayoutConstraint!
private static var widthConstraintOfSideMenu_Right : NSLayoutConstraint!
private static var leadingConstraintOfContainer : NSLayoutConstraint!
private static var topConstraintOfSideContainer : NSLayoutConstraint!
private static var bottomConstraintOfContainer : NSLayoutConstraint!
private static var trailingConstraintOfContainer : NSLayoutConstraint!
//MARK: Methods
public static func setUpNavigation(rootController:UIViewController, leftMenuController : UIViewController?, rightMenuController : UIViewController?, leftMenuType: SJSideMenuType, rightMenuType: SJSideMenuType){
var isMenu : Bool = false
if leftMenuController != nil {
isMenu = true
}
if rightMenuController != nil {
isMenu = true
}
assert(isMenu != false, "Please provide side menu controller")
isSetup = true
leftSideMenuController = leftMenuController
leftSideMenuType = leftMenuType
rightSideMenuController = rightMenuController
rightSideMenuType = rightMenuType
let appNav = UINavigationController()
appNav.viewControllers = NSArray(object: rootController) as! [UIViewController]
navigator = appNav
assert(isMenu != false, "Please provide any one side menu controller")
assert(appNav.viewControllers.count > 0, "Please provide root controller")
}
public static func enableSwipeGestureWithMenuSide(menuSide : SJSideMenuPosition){
SJSwiftSideMenuController.swipeMenuSide = menuSide
}
override public func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.navigator.delegate = self
self.view.backgroundColor = UIColor.white
SJSwiftSideMenuController.navigationContainer = self;
SJSwiftSideMenuController.navigator.delegate = self
setUpContainers()
// Do any additional setup after loading the view.
// menu gesture recognisers
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(SJSwiftSideMenuController.toggleMenuWithGesture(gesture:)))
swipeRight.direction = UISwipeGestureRecognizer.Direction.right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action:#selector(SJSwiftSideMenuController.toggleMenuWithGesture(gesture:)))
swipeLeft.direction = UISwipeGestureRecognizer.Direction.left
self.view.addGestureRecognizer(swipeLeft)
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private static func addDefaultLeftMenuButton(){
// let menuIcon : UIImage = UIImage(named: "menu")!
let menuIcon = menuIcon_Left
let button : UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
button .setImage(menuIcon, for: .normal)
button .addTarget(SJSwiftSideMenuController.navigationContainer, action: #selector(SJSwiftSideMenuController.leftMenuButtonTapped(_:)), for: .touchUpInside)
button .imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
let leftButton = UIBarButtonItem(customView: button)
self.navigator.topViewController?.navigationItem.leftBarButtonItem = leftButton
}
private static func addDefaultRightMenuButton(){
// let menuIcon : UIImage = UIImage(named: "menu")!
let menuIcon = menuIcon_Right
let button : UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
button .setImage(menuIcon, for: .normal)
button .addTarget(SJSwiftSideMenuController.navigationContainer, action: #selector(SJSwiftSideMenuController.rightMenuButtonTapped(_:)), for: .touchUpInside)
button .imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
let rightButton = UIBarButtonItem(customView: button)
self.navigator.topViewController?.navigationItem.rightBarButtonItem = rightButton
}
public static func showLeftMenuNavigationBarButton(image : UIImage){
shouldShowLeftButton = true
menuIcon_Left = image
}
public static func showRightMenuNavigationBarButton(image : UIImage){
shouldShowRightButton = true
menuIcon_Right = image
}
static func setUpLeftMenuWidth(width : CGFloat){
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
leftMenuWidth = width
if SJSwiftSideMenuController.navigator != nil {
SJSwiftSideMenuController.navigator .viewWillAppear(true)
}
}
static func setUpRightMenuWidth(width : CGFloat){
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
rightMenuWidth = width
if SJSwiftSideMenuController.navigator != nil {
SJSwiftSideMenuController.navigator .viewWillAppear(true)
}
}
func setUpContainers() {
//======================= Container View ===============================
SJSwiftSideMenuController.containerView = UIView()
SJSwiftSideMenuController.containerView.backgroundColor = UIColor.white
let frame = self.view.bounds
SJSwiftSideMenuController.containerView.frame = frame
SJSwiftSideMenuController.containerView.autoresizingMask = [UIView.AutoresizingMask.flexibleLeftMargin, UIView.AutoresizingMask.flexibleRightMargin, UIView.AutoresizingMask.flexibleTopMargin, UIView.AutoresizingMask.flexibleBottomMargin]
self.view.addSubview(SJSwiftSideMenuController.containerView)
SJSwiftSideMenuController.topConstraintOfSideContainer = SJSwiftSideMenuController.containerView.addTopConstraint(toView: view, constant: 0.0)
SJSwiftSideMenuController.leadingConstraintOfContainer = SJSwiftSideMenuController.containerView.addLeadingConstraint(toView: view, constant: 0.0)
SJSwiftSideMenuController.trailingConstraintOfContainer = SJSwiftSideMenuController.containerView.addTrailingConstraint(toView: view, constant: 0.0)
SJSwiftSideMenuController.bottomConstraintOfContainer = SJSwiftSideMenuController.containerView.addBottomConstraint(toView: view, constant: 0.0)
addViewControllerAsChildViewController(SJSwiftSideMenuController.navigator, inContainer: SJSwiftSideMenuController.containerView)
//===================== Dim BG View ================================
addDimBG()
//=================== Left menu setup=========================
if SJSwiftSideMenuController.leftSideMenuController != nil {
SJSwiftSideMenuController.leftSideMenuView = UIView()
SJSwiftSideMenuController.leftSideMenuView.backgroundColor = UIColor.white
var frame = CGRect(x: 0, y: 0, width: SJSwiftSideMenuController.leftMenuWidth, height: self.view.frame.size.height)
if SJSwiftSideMenuController.leftSideMenuType == .SlideView {
frame.origin.x = -(SJSwiftSideMenuController.leftMenuWidth)
}
SJSwiftSideMenuController.leftSideMenuView.frame = frame
SJSwiftSideMenuController.leftSideMenuView.autoresizingMask = [UIView.AutoresizingMask.flexibleLeftMargin, UIView.AutoresizingMask.flexibleRightMargin, UIView.AutoresizingMask.flexibleTopMargin, UIView.AutoresizingMask.flexibleBottomMargin]
self.view.addSubview(SJSwiftSideMenuController.leftSideMenuView)
SJSwiftSideMenuController.topConstraintOfSideMenu_Left = SJSwiftSideMenuController.leftSideMenuView.addTopConstraint(toView: view, constant: 0.0)
if SJSwiftSideMenuController.leftSideMenuType == .SlideOver {
SJSwiftSideMenuController.leadingConstraintOfSideMenu_Left = SJSwiftSideMenuController.leftSideMenuView.addLeadingConstraint(toView: view, constant: -(SJSwiftSideMenuController.leftMenuWidth))
}else{
SJSwiftSideMenuController.leadingConstraintOfSideMenu_Left = SJSwiftSideMenuController.leftSideMenuView.addLeadingConstraint(toView: view, constant: -(SJSwiftSideMenuController.leftMenuWidth))
}
SJSwiftSideMenuController.bottomConstraintOfSideMenu_Left = SJSwiftSideMenuController.leftSideMenuView.addWidthConstraint(widthConstant: SJSwiftSideMenuController.leftMenuWidth)
SJSwiftSideMenuController.bottomConstraintOfSideMenu_Left = SJSwiftSideMenuController.leftSideMenuView.addBottomConstraint(toView: view, constant: 0.0)
addViewControllerAsChildViewController(SJSwiftSideMenuController.leftSideMenuController, inContainer: SJSwiftSideMenuController.leftSideMenuView)
SJSwiftSideMenuController.leftSideMenuView.isHidden = true
}
//==================================================================
//=================== Right menu setup=========================
if SJSwiftSideMenuController.rightSideMenuController != nil {
SJSwiftSideMenuController.rightSideMenuView = UIView()
SJSwiftSideMenuController.rightSideMenuView.backgroundColor = UIColor.white
var frameRight = CGRect(x: self.view.frame.size.width, y: 0, width: SJSwiftSideMenuController.rightMenuWidth, height: self.view.frame.size.height)
if SJSwiftSideMenuController.rightSideMenuType == .SlideView {
// frameRight.origin.x = -(SJNavigationController.rightMenuWidth)
frameRight.origin.x = 0
}
SJSwiftSideMenuController.rightSideMenuView.frame = frameRight
SJSwiftSideMenuController.rightSideMenuView.autoresizingMask = [UIView.AutoresizingMask.flexibleLeftMargin, UIView.AutoresizingMask.flexibleRightMargin, UIView.AutoresizingMask.flexibleTopMargin, UIView.AutoresizingMask.flexibleBottomMargin]
self.view.addSubview(SJSwiftSideMenuController.rightSideMenuView)
self.view.bringSubviewToFront(SJSwiftSideMenuController.rightSideMenuView)
SJSwiftSideMenuController.topConstraintOfSideMenu_Right = SJSwiftSideMenuController.rightSideMenuView.addTopConstraint(toView: view, constant: 0.0)
if SJSwiftSideMenuController.rightSideMenuType == .SlideOver {
SJSwiftSideMenuController.leadingConstraintOfSideMenu_Right = SJSwiftSideMenuController.rightSideMenuView.addLeadingConstraint(toView: view, constant: view.frame.size.width)
}else{
SJSwiftSideMenuController.leadingConstraintOfSideMenu_Right = SJSwiftSideMenuController.rightSideMenuView.addLeadingConstraint(toView: view, constant: view.frame.size.width)
}
SJSwiftSideMenuController.widthConstraintOfSideMenu_Right = SJSwiftSideMenuController.rightSideMenuView.addWidthConstraint(widthConstant: SJSwiftSideMenuController.rightMenuWidth)
SJSwiftSideMenuController.bottomConstraintOfSideMenu_Right = SJSwiftSideMenuController.rightSideMenuView.addBottomConstraint(toView: view, constant: 0.0)
// SJSwiftSideMenuController.rightSideMenuView.backgroundColor = UIColor.red
addViewControllerAsChildViewController(SJSwiftSideMenuController.rightSideMenuController, inContainer: SJSwiftSideMenuController.rightSideMenuView)
SJSwiftSideMenuController.rightSideMenuView.isHidden = true
}
}
private func addDimBG() {
if SJSwiftSideMenuController.dimBGView != nil {
SJSwiftSideMenuController.dimBGView.removeFromSuperview()
}
SJSwiftSideMenuController.dimBGView = UIView()
SJSwiftSideMenuController.dimBGView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
let frame = self.view.bounds
SJSwiftSideMenuController.dimBGView.frame = frame
SJSwiftSideMenuController.dimBGView.autoresizingMask = [UIView.AutoresizingMask.flexibleLeftMargin, UIView.AutoresizingMask.flexibleRightMargin, UIView.AutoresizingMask.flexibleTopMargin, UIView.AutoresizingMask.flexibleBottomMargin]
self.view.addSubview(SJSwiftSideMenuController.dimBGView)
SJSwiftSideMenuController.dimBGView.addTopConstraint(toView: view, constant: 0.0)
SJSwiftSideMenuController.dimBGView.addLeadingConstraint(toView: view, constant: 0.0)
SJSwiftSideMenuController.dimBGView.addTrailingConstraint(toView: view, constant: 0.0)
SJSwiftSideMenuController.dimBGView.addBottomConstraint(toView: view, constant: 0.0)
SJSwiftSideMenuController.dimBGView.isHidden = true
let tapG = UITapGestureRecognizer(target: self, action: #selector(SJSwiftSideMenuController.dimBgTappedGesture(gesture:)))
tapG.numberOfTapsRequired = 1
SJSwiftSideMenuController.dimBGView.addGestureRecognizer(tapG)
SJSwiftSideMenuController.dimBGView.isHidden = true
}
private static func showDimBackground(show: Bool) {
if SJSwiftSideMenuController.dimBGView == nil {
return
}
if enableDimbackground == false {
return;
}
UIView.transition(with: SJSwiftSideMenuController.dimBGView, duration: 0.25, options: .curveEaseInOut, animations: {() -> Void in
SJSwiftSideMenuController.dimBGView.isHidden = !show
}, completion: { _ in
})
}
fileprivate func addViewControllerAsChildViewController(_ viewController: UIViewController, inContainer: UIView) {
// Add Child View Controller
addChild(viewController)
//
// // Add Child View as Subview
inContainer.addSubview(viewController.view!)
//
// // Configure Child View
var childFrame = inContainer.frame
childFrame.origin = CGPoint.zero
viewController.view?.frame = childFrame
viewController.view.autoresizingMask = [UIView.AutoresizingMask.flexibleLeftMargin, UIView.AutoresizingMask.flexibleRightMargin, UIView.AutoresizingMask.flexibleTopMargin, UIView.AutoresizingMask.flexibleBottomMargin
, UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]
//
// // Notify Child View Controller
viewController.didMove(toParent: self)
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if SJSwiftSideMenuController.shouldLeaveSpaceForStatusBar == true {
if UIApplication.shared.isStatusBarHidden {
SJSwiftSideMenuController.topConstraintOfSideContainer.constant = 0
SJSwiftSideMenuController.topConstraintOfSideMenu_Left.constant = 0
SJSwiftSideMenuController.topConstraintOfSideMenu_Right.constant = 0
}else{
SJSwiftSideMenuController.topConstraintOfSideContainer.constant = 20
SJSwiftSideMenuController.topConstraintOfSideMenu_Left.constant = 20
SJSwiftSideMenuController.topConstraintOfSideMenu_Right.constant = 20
}
}
}
@objc private func toggleMenuWithGesture(gesture: UISwipeGestureRecognizer) {
if SJSwiftSideMenuController.swipeMenuSide == .RIGHT {
toggleRightMenuWithGesture(gesture: gesture)
}else if SJSwiftSideMenuController.swipeMenuSide == .LEFT {
toggleLeftMenuWithGesture(gesture: gesture)
}
}
@objc private func dimBgTappedGesture(gesture: UITapGestureRecognizer) {
if SJSwiftSideMenuController.leftSideMenuController != nil {
SJSwiftSideMenuController.hideLeftMenu()
}
if SJSwiftSideMenuController.rightSideMenuController != nil {
SJSwiftSideMenuController.hideRightMenu()
}
}
@IBAction func leftMenuButtonTapped(_ sender: AnyObject){
SJSwiftSideMenuController.toggleLeftSideMenu()
}
@IBAction func rightMenuButtonTapped(_ sender: AnyObject){
SJSwiftSideMenuController.toggleRightSideMenu()
}
//MARK : Left menu
// left side menu methods
public static func toggleLeftSideMenu() {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.validateForLeftMenuSetup()
if SJSwiftSideMenuController.leftSideMenuType == .SlideOver {
toggleLeftSlideOverMenu()
}else if SJSwiftSideMenuController.leftSideMenuType == .SlideView {
toggleLeftSlideViewMenu()
}
}
public static func showLeftMenu(){
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.validateForLeftMenuSetup()
if SJSwiftSideMenuController.leftSideMenuType == .SlideOver {
showLeftMenuOver()
}else if SJSwiftSideMenuController.leftSideMenuType == .SlideView {
showLeftMenuBySide()
}
}
public static func hideLeftMenu(){
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.validateForLeftMenuSetup()
if SJSwiftSideMenuController.leftSideMenuType == .SlideOver {
hideLeftMenuOver()
}else if SJSwiftSideMenuController.leftSideMenuType == .SlideView {
hideLeftMenuBySide()
}
}
private static func toggleLeftSlideOverMenu() {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
if SJSwiftSideMenuController.leftSideMenuView.isHidden == true {
SJSwiftSideMenuController.showLeftMenuOver()
}else{
SJSwiftSideMenuController.hideLeftMenuOver()
}
if leftSideMenuController != nil {
leftSideMenuController .viewWillAppear(true)
}
}
private static func toggleLeftSlideViewMenu() {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
if SJSwiftSideMenuController.containerView.frame.origin.x == 0 {
showLeftMenuBySide()
}else{
hideLeftMenuBySide()
}
}
private func toggleLeftMenuWithGesture(gesture: UISwipeGestureRecognizer)
{
SJSwiftSideMenuController.validateForLeftMenuSetup()
switch gesture.direction {
case UISwipeGestureRecognizer.Direction.right:
SJSwiftSideMenuController.showLeftMenu()
case UISwipeGestureRecognizer.Direction.left:
SJSwiftSideMenuController.hideLeftMenu()
default:
SJSwiftSideMenuController.hideLeftMenu()
}
if SJSwiftSideMenuController.leftSideMenuController != nil {
SJSwiftSideMenuController.leftSideMenuController .viewWillAppear(true)
}
}
private static func showLeftMenuOver() {
if SJSwiftSideMenuController.rightSideMenuController != nil {
SJSwiftSideMenuController.hideRightMenu()
}
showDimBackground(show: true)
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.navigationContainer.view.bringSubviewToFront(SJSwiftSideMenuController.leftSideMenuView)
SJSwiftSideMenuController.leftSideMenuView.isHidden = false
UIView.animate(withDuration: 0.25, animations: {
// var frame = leftSideMenuView.frame
// frame.origin.x = 0
// leftSideMenuView.frame = frame
// SJSwiftSideMenuController.navigationContainer.view.layoutSubviews()
// SJSwiftSideMenuController.leftSideMenuView.layoutSubviews()
// SJSwiftSideMenuController.navigator.view.layoutSubviews()
leadingConstraintOfSideMenu_Left.constant = 0
SJSwiftSideMenuController.navigationContainer.view.layoutIfNeeded()
}) { (isComplete) in
}
}
private static func hideLeftMenuOver() {
showDimBackground(show: false)
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
if SJSwiftSideMenuController.navigationContainer == nil {
return
}
SJSwiftSideMenuController.navigationContainer.view.bringSubviewToFront(SJSwiftSideMenuController.leftSideMenuView)
UIView.animate(withDuration: 0.25, animations: {
leadingConstraintOfSideMenu_Left.constant = -(leftMenuWidth)
SJSwiftSideMenuController.navigationContainer.view.layoutIfNeeded()
}) { (isComplete) in
SJSwiftSideMenuController.leftSideMenuView.isHidden = true
}
}
private static func showLeftMenuBySide(){
if SJSwiftSideMenuController.rightSideMenuController != nil {
SJSwiftSideMenuController.hideRightMenu()
}
showDimBackground(show: true)
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.leftSideMenuView.isHidden = false
UIView.animate(withDuration: 0.25, animations: {
var frame = SJSwiftSideMenuController.containerView.frame
frame.origin.x = +(leftMenuWidth)
SJSwiftSideMenuController.containerView.frame = frame
//Side Menu
frame = leftSideMenuView.frame
frame.origin.x = 0
leftSideMenuView.frame = frame
SJSwiftSideMenuController.containerView.layoutIfNeeded()
}) { (isComplete) in
}
}
private static func hideLeftMenuBySide(){
showDimBackground(show: false)
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
UIView.animate(withDuration: 0.25, animations: {
var frame = SJSwiftSideMenuController.containerView.frame
frame.origin.x = 0
SJSwiftSideMenuController.containerView.frame = frame
//Side Menu
frame = leftSideMenuView.frame
frame.origin.x = -(leftMenuWidth)
leftSideMenuView.frame = frame
SJSwiftSideMenuController.containerView.layoutIfNeeded()
}) { (isComplete) in
SJSwiftSideMenuController.leftSideMenuView.isHidden = true
}
}
//MARK : Right menu
// Right side menu methods
public static func toggleRightSideMenu() {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.validateForRightMenuSetup()
if SJSwiftSideMenuController.rightSideMenuType == .SlideOver {
SJSwiftSideMenuController.toggleRightSlideOverMenu()
}else if SJSwiftSideMenuController.rightSideMenuType == .SlideView {
SJSwiftSideMenuController.toggleRightSlideViewMenu()
}
}
public static func showRightMenu(){
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.validateForRightMenuSetup()
if SJSwiftSideMenuController.rightSideMenuType == .SlideOver {
SJSwiftSideMenuController.showRightMenuOver()
}else if SJSwiftSideMenuController.rightSideMenuType == .SlideView {
SJSwiftSideMenuController.showRightMenuBySide()
}
}
public static func hideRightMenu(){
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.validateForRightMenuSetup()
if SJSwiftSideMenuController.rightSideMenuType == .SlideOver {
SJSwiftSideMenuController.hideRightMenuOver()
}else if SJSwiftSideMenuController.rightSideMenuType == .SlideView {
SJSwiftSideMenuController.hideRightMenuBySide()
}
}
private static func toggleRightSlideOverMenu() {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
if SJSwiftSideMenuController.rightSideMenuView.isHidden == true {
SJSwiftSideMenuController.showRightMenuOver()
}else{
SJSwiftSideMenuController.hideRightMenuOver()
}
}
private static func toggleRightSlideViewMenu() {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
if SJSwiftSideMenuController.containerView.frame.origin.x == 0 {
SJSwiftSideMenuController.showRightMenuBySide()
}else{
SJSwiftSideMenuController.hideRightMenuBySide()
}
}
private func toggleRightMenuWithGesture(gesture: UISwipeGestureRecognizer)
{
SJSwiftSideMenuController.validateForRightMenuSetup()
switch gesture.direction {
case UISwipeGestureRecognizer.Direction.right:
SJSwiftSideMenuController.hideRightMenu()
case UISwipeGestureRecognizer.Direction.left:
SJSwiftSideMenuController.showRightMenu()
default:
SJSwiftSideMenuController.hideRightMenu()
}
}
private static func showRightMenuOver() {
if SJSwiftSideMenuController.leftSideMenuController != nil {
SJSwiftSideMenuController.hideLeftMenu()
}
showDimBackground(show: true)
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.navigationContainer.view.bringSubviewToFront(SJSwiftSideMenuController.rightSideMenuView)
SJSwiftSideMenuController.rightSideMenuView.isHidden = false
UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.curveEaseOut, animations: {
self.leadingConstraintOfSideMenu_Right.constant = SJSwiftSideMenuController.containerView.frame.size.width - rightMenuWidth
SJSwiftSideMenuController.navigationContainer.view.layoutIfNeeded()
}, completion: nil)
}
private static func hideRightMenuOver() {
showDimBackground(show: false)
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.navigationContainer.view.bringSubviewToFront(SJSwiftSideMenuController.rightSideMenuView)
UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.curveEaseOut, animations: {
self.leadingConstraintOfSideMenu_Right.constant = SJSwiftSideMenuController.containerView.frame.size.width
SJSwiftSideMenuController.navigationContainer.view.layoutIfNeeded()
}, completion: { _ in
SJSwiftSideMenuController.rightSideMenuView.isHidden = true
})
}
private static func showRightMenuBySide(){
if SJSwiftSideMenuController.leftSideMenuController != nil {
SJSwiftSideMenuController.hideLeftMenu()
}
showDimBackground(show: true)
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.rightSideMenuView.isHidden = false
UIView.transition(with: rightSideMenuView, duration: 0.5, options: .curveEaseOut, animations: {() -> Void in
var frame = SJSwiftSideMenuController.containerView.frame
frame.origin.x = -(rightMenuWidth)
SJSwiftSideMenuController.containerView.frame = frame
//Side Menu
frame = rightSideMenuView.frame
frame.origin.x = containerView.frame.size.width - rightMenuWidth
rightSideMenuView.frame = frame
SJSwiftSideMenuController.containerView.layoutIfNeeded()
}, completion: { _ in
})
}
private static func hideRightMenuBySide(){
showDimBackground(show: false)
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
UIView.transition(with: rightSideMenuView, duration: 0.5, options: .curveEaseOut, animations: {() -> Void in
var frame = SJSwiftSideMenuController.containerView.frame
frame.origin.x = 0
SJSwiftSideMenuController.containerView.frame = frame
//Side Menu
frame = rightSideMenuView.frame
frame.origin.x = containerView.frame.size.width
rightSideMenuView.frame = frame
SJSwiftSideMenuController.containerView.layoutIfNeeded()
}, completion: { _ in
SJSwiftSideMenuController.rightSideMenuView.isHidden = true
})
}
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// SJNavigationController.toggleRightSideMenu()
}
//MARK: Navigation
// Uses a horizontal slide transition. Has no effect if the view controller is already in the stack.
public static func setRootController(_ viewController: UIViewController, animated: Bool) {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.navigator.pushViewController(viewController, animated: animated)
SJSwiftSideMenuController.navigator.viewControllers = [viewController]
// SJSwiftSideMenuController.navigator.pushViewController(viewController, animated: animated)
}
// Uses a horizontal slide transition. Has no effect if the view controller is already in the stack.
public static func pushViewController(_ viewController: UIViewController, animated: Bool) {
DispatchQueue.main.async {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
var vcList = SJSwiftSideMenuController.viewControllers
if vcList.contains(viewController) == true {
let index = vcList.firstIndex(of: viewController)
vcList.remove(at: index!)
SJSwiftSideMenuController.navigator.viewControllers = vcList
}
SJSwiftSideMenuController.navigator.pushViewController(viewController, animated: animated)
}
}
// Returns the popped controller.
public static func popViewController(animated: Bool){
DispatchQueue.main.async {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
SJSwiftSideMenuController.navigator.popViewController(animated: animated)
}
}
// Returns the popped controller.
public static func popAndGetViewController(animated: Bool) -> UIViewController?{
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
return SJSwiftSideMenuController.navigator.popViewController(animated: animated)
}
// Pops view controllers until the one specified is on top. Returns the popped controllers.
public static func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]?{
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
return SJSwiftSideMenuController.navigator.popToViewController(viewController, animated: animated)
}
// Pops until there's only a single view controller left on the stack. Returns the popped controllers.
public static func popToRootViewController(animated: Bool) -> [UIViewController]?{
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
return SJSwiftSideMenuController.navigator.popToRootViewController(animated: animated)
}
// The top view controller on the stack.
public static var topViewController: UIViewController?{
get {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
return SJSwiftSideMenuController.navigator.topViewController
}
}
// Return modal view controller if it exists. Otherwise the top view controller.
public static var visibleViewController: UIViewController?{
get {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
return SJSwiftSideMenuController.navigator.visibleViewController
}
}
// The current view controller stack.
public static var viewControllers: [UIViewController]{
get {
SJSwiftSideMenuController.validateForNavigationSetup() //Check for setup
return SJSwiftSideMenuController.navigator.viewControllers
}
}
//MARK: Navigation delegate
public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if SJSwiftSideMenuController.shouldShowLeftButton == true {
SJSwiftSideMenuController.addDefaultLeftMenuButton()
}
if SJSwiftSideMenuController.shouldShowRightButton == true {
SJSwiftSideMenuController.addDefaultRightMenuButton()
}
}
private static func validateForNavigationSetup(){
assert((SJSwiftSideMenuController.isSetup == true) == true, "Please call setupNavigationMethod in AppDelegate class") // here
}
private static func validateForLeftMenuSetup(){
assert(SJSwiftSideMenuController.leftSideMenuController != nil, "Please set LeftSideMenuController before using left menu methods.") // here
}
private static func validateForRightMenuSetup(){
assert(SJSwiftSideMenuController.rightSideMenuController != nil, "Please set RightSideMenuController before using left menu methods.") // here
}
public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if SJSwiftSideMenuController.leftSideMenuController != nil {
SJSwiftSideMenuController.hideLeftMenu()
}
if SJSwiftSideMenuController.rightSideMenuController != nil {
SJSwiftSideMenuController.hideRightMenu()
}
}
public static func replaceViewController(atIndex : Int, newVC : UIViewController) {
SJSwiftSideMenuController.navigator.viewControllers[atIndex] = newVC
}
}
//MARK : UIColor
//
//
//extension CGFloat {
// public static func random() -> CGFloat {
// return CGFloat(arc4random()) / CGFloat(UInt32.max)
// }
//}
//
//extension UIColor {
// public static func randomColor() -> UIColor {
// // If you wanted a random alpha, just create another
// // random number for that too.
// return UIColor(red: .random(),
// green: .random(),
// blue: .random(),
// alpha: 1.0)
// }
//}
extension UIButton {
public func centerTextAndImage(spacing: CGFloat) {
let insetAmount = spacing / 2
imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount, bottom: 0, right: insetAmount)
titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: -insetAmount)
contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
}
}
//MARK : UIView
extension UIView {
// MARK: - Fill
/**
Creates and adds an array of NSLayoutConstraint objects that relates this view's top, leading, bottom and trailing to its superview, given an optional set of insets for each side.
Default parameter values relate this view's top, leading, bottom and trailing to its superview with no insets.
@note The constraints are also added to this view's superview for you
:param: edges An amount insets to apply to the top, leading, bottom and trailing constraint. Default value is UIEdgeInsetsZero
:returns: An array of 4 x NSLayoutConstraint objects (top, leading, bottom, trailing) if the superview exists otherwise an empty array
*/
@discardableResult
public func fillSuperView(_ edges: UIEdgeInsets = UIEdgeInsets.zero) -> [NSLayoutConstraint] {
var constraints: [NSLayoutConstraint] = []
if let superview = superview {
let topConstraint = addTopConstraint(toView: superview, constant: edges.top)
let leadingConstraint = addLeadingConstraint(toView: superview, constant: edges.left)
let bottomConstraint = addBottomConstraint(toView: superview, constant: -edges.bottom)
let trailingConstraint = addTrailingConstraint(toView: superview, constant: -edges.right)
constraints = [topConstraint, leadingConstraint, bottomConstraint, trailingConstraint]
}
return constraints
}
// MARK: - Leading / Trailing
/**
Creates and adds an `NSLayoutConstraint` that relates this view's leading edge to some specified edge of another view, given a relation and offset.
Default parameter values relate this view's leading edge to be equal to the leading edge of the other view.
@note The new constraint is added to this view's superview for you
:param: view The other view to relate this view's layout to
:param: attribute The other view's layout attribute to relate this view's leading edge to e.g. the other view's trailing edge. Default value is `NSLayoutAttribute.Leading`
:param: relation The relation of the constraint. Default value is `NSLayoutRelation.Equal`
:param: constant An amount by which to offset this view's left from the other view's specified edge. Default value is 0
:returns: The created `NSLayoutConstraint` for this leading attribute relation
*/
@discardableResult
public func addLeadingConstraint(toView view: UIView?, attribute: NSLayoutConstraint.Attribute = .leading, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = createConstraint(attribute: .leading, toView: view, attribute: attribute, relation: relation, constant: constant)
addConstraintToSuperview(constraint)
return constraint
}
@discardableResult
public func addWidthConstraint(widthConstant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: widthConstant)
addConstraintToSuperview(constraint)
return constraint
}
/**
Creates and adds an `NSLayoutConstraint` that relates this view's trailing edge to some specified edge of another view, given a relation and offset.
Default parameter values relate this view's trailing edge to be equal to the trailing edge of the other view.
@note The new constraint is added to this view's superview for you
:param: view The other view to relate this view's layout to
:param: attribute The other view's layout attribute to relate this view's leading edge to e.g. the other view's trailing edge. Default value is `NSLayoutAttribute.Trailing`
:param: relation The relation of the constraint. Default value is `NSLayoutRelation.Equal`
:param: constant An amount by which to offset this view's left from the other view's specified edge. Default value is 0
:returns: The created `NSLayoutConstraint` for this trailing attribute relation
*/
@discardableResult
public func addTrailingConstraint(toView view: UIView?, attribute: NSLayoutConstraint.Attribute = .trailing, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = createConstraint(attribute: .trailing, toView: view, attribute: attribute, relation: relation, constant: constant)
addConstraintToSuperview(constraint)
return constraint
}
// MARK: - Left
/**
Creates and adds an NSLayoutConstraint that relates this view's left to some specified edge of another view, given a relation and offset.
Default parameter values relate this view's left to be equal to the left of the other view.
@note The new constraint is added to this view's superview for you
:param: view The other view to relate this view's layout to
:param: attribute The other view's layout attribute to relate this view's left side to e.g. the other view's right. Default value is NSLayoutAttribute.Left
:param: relation The relation of the constraint. Default value is NSLayoutRelation.Equal
:param: constant An amount by which to offset this view's left from the other view's specified edge. Default value is 0
:returns: The created NSLayoutConstraint for this left attribute relation
*/
@discardableResult
public func addLeftConstraint(toView view: UIView?, attribute: NSLayoutConstraint.Attribute = .left, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = createConstraint(attribute: .left, toView: view, attribute: attribute, relation: relation, constant: constant)
addConstraintToSuperview(constraint)
return constraint
}
// MARK: - Right
/**
Creates and adds an NSLayoutConstraint that relates this view's right to some specified edge of another view, given a relation and offset.
Default parameter values relate this view's right to be equal to the right of the other view.
@note The new constraint is added to this view's superview for you
:param: view The other view to relate this view's layout to
:param: attribute The other view's layout attribute to relate this view's right to e.g. the other view's left. Default value is NSLayoutAttribute.Right
:param: relation The relation of the constraint. Default value is NSLayoutRelation.Equal
:param: constant An amount by which to offset this view's right from the other view's specified edge. Default value is 0.0
:returns: The created NSLayoutConstraint for this right attribute relation
*/
@discardableResult
public func addRightConstraint(toView view: UIView?, attribute: NSLayoutConstraint.Attribute = .right, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = createConstraint(attribute: .right, toView: view, attribute: attribute, relation: relation, constant: constant)
addConstraintToSuperview(constraint)
return constraint
}
// MARK: - Top
/**
Creates and adds an NSLayoutConstraint that relates this view's top to some specified edge of another view, given a relation and offset.
Default parameter values relate this view's right to be equal to the right of the other view.
@note The new constraint is added to this view's superview for you
:param: view The other view to relate this view's layout to
:param: attribute The other view's layout attribute to relate this view's top to e.g. the other view's bottom. Default value is NSLayoutAttribute.Bottom
:param: relation The relation of the constraint. Default value is NSLayoutRelation.Equal
:param: constant An amount by which to offset this view's top from the other view's specified edge. Default value is 0.0
:returns: The created NSLayoutConstraint for this top edge layout relation
*/
@discardableResult
public func addTopConstraint(toView view: UIView?, attribute: NSLayoutConstraint.Attribute = .top, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = createConstraint(attribute: .top, toView: view, attribute: attribute, relation: relation, constant: constant)
addConstraintToSuperview(constraint)
return constraint
}
// MARK: - Bottom
/**
Creates and adds an NSLayoutConstraint that relates this view's bottom to some specified edge of another view, given a relation and offset.
Default parameter values relate this view's right to be equal to the right of the other view.
@note The new constraint is added to this view's superview for you
:param: view The other view to relate this view's layout to
:param: attribute The other view's layout attribute to relate this view's bottom to e.g. the other view's top. Default value is NSLayoutAttribute.Botom
:param: relation The relation of the constraint. Default value is NSLayoutRelation.Equal
:param: constant An amount by which to offset this view's bottom from the other view's specified edge. Default value is 0.0
:returns: The created NSLayoutConstraint for this bottom edge layout relation
*/
@discardableResult
public func addBottomConstraint(toView view: UIView?, attribute: NSLayoutConstraint.Attribute = .bottom, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = createConstraint(attribute: .bottom, toView: view, attribute: attribute, relation: relation, constant: constant)
addConstraintToSuperview(constraint)
return constraint
}
// MARK: - Center X
/**
Creates and adds an NSLayoutConstraint that relates this view's center X attribute to the center X attribute of another view, given a relation and offset.
Default parameter values relate this view's center X to be equal to the center X of the other view.
:param: view The other view to relate this view's layout to
:param: relation The relation of the constraint. Default value is NSLayoutRelation.Equal
:param: constant An amount by which to offset this view's center X attribute from the other view's center X attribute. Default value is 0.0
:returns: The created NSLayoutConstraint for this center X layout relation
*/
@discardableResult
public func addCenterXConstraint(toView view: UIView?, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = createConstraint(attribute: .centerX, toView: view, attribute: .centerX, relation: relation, constant: constant)
addConstraintToSuperview(constraint)
return constraint
}
// MARK: - Center Y
/**
Creates and adds an NSLayoutConstraint that relates this view's center Y attribute to the center Y attribute of another view, given a relation and offset.
Default parameter values relate this view's center Y to be equal to the center Y of the other view.
:param: view The other view to relate this view's layout to
:param: relation The relation of the constraint. Default value is NSLayoutRelation.Equal
:param: constant An amount by which to offset this view's center Y attribute from the other view's center Y attribute. Default value is 0.0
:returns: The created NSLayoutConstraint for this center Y layout relation
*/
@discardableResult
public func addCenterYConstraint(toView view: UIView?, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = createConstraint(attribute: .centerY, toView: view, attribute: .centerY, relation: relation, constant: constant)
addConstraintToSuperview(constraint)
return constraint
}
// MARK: - Width
/**
Creates and adds an NSLayoutConstraint that relates this view's width to the width of another view, given a relation and offset.
Default parameter values relate this view's width to be equal to the width of the other view.
:param: view The other view to relate this view's layout to
:param: relation The relation of the constraint. Default value is NSLayoutRelation.Equal
:param: constant An amount by which to offset this view's width from the other view's width amount. Default value is 0.0
:returns: The created NSLayoutConstraint for this width layout relation
*/
@discardableResult
public func addWidthConstraint(toView view: UIView?, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = createConstraint(attribute: .width, toView: view, attribute: .width, relation: relation, constant: constant)
addConstraintToSuperview(constraint)
return constraint
}
// MARK: - Height
/**
Creates and adds an NSLayoutConstraint that relates this view's height to the height of another view, given a relation and offset.
Default parameter values relate this view's height to be equal to the height of the other view.
:param: view The other view to relate this view's layout to
:param: relation The relation of the constraint. Default value is NSLayoutRelation.Equal
:param: constant An amount by which to offset this view's height from the other view's height amount. Default value is 0.0
:returns: The created NSLayoutConstraint for this height layout relation
*/
@discardableResult
public func addHeightConstraint(toView view: UIView?, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0) -> NSLayoutConstraint {
let constraint = createConstraint(attribute: .height, toView: view, attribute: .height, relation: relation, constant: constant)
addConstraintToSuperview(constraint)
return constraint
}
// MARK: - Private
/// Adds an NSLayoutConstraint to the superview
fileprivate func addConstraintToSuperview(_ constraint: NSLayoutConstraint) {
translatesAutoresizingMaskIntoConstraints = false
superview?.addConstraint(constraint)
}
/// Creates an NSLayoutConstraint using its factory method given both views, attributes a relation and offset
fileprivate func createConstraint(attribute attr1: NSLayoutConstraint.Attribute, toView: UIView?, attribute attr2: NSLayoutConstraint.Attribute, relation: NSLayoutConstraint.Relation, constant: CGFloat) -> NSLayoutConstraint {
let constraint = NSLayoutConstraint(
item: self,
attribute: attr1,
relatedBy: relation,
toItem: toView,
attribute: attr2,
multiplier: 1.0,
constant: constant)
return constraint
}
}
extension NSObject {
var theClassName: String {
return NSStringFromClass(type(of: self))
}
}
| 46.624248 | 253 | 0.693936 |
67d16b7c9a0d8b29125cf8fe0343febb6e8ccff5 | 442 | //
// CommunityBuilder.swift
// OutreachApp
//
// Created by Demicheli, Stefano on 10/3/2563 BE.
// Copyright © 2563 NECSI. All rights reserved.
//
import UIKit
struct CommunityBuilder {
static func build() -> UIViewController {
let service = CommunityServiceImpl()
let viewModel = CommunityListViewModel(communityService: service)
return CommunityViewController(style: .plain,viewModel: viewModel)
}
}
| 23.263158 | 74 | 0.70362 |
146e31a48c5ce674b77717af287d7071477d2b99 | 9,550 | extension BinaryInteger {
public func to(_ type: Int.Type) -> Int {
return Int(self)
}
}
extension BinaryFloatingPoint {
public func to(_ type: Int.Type) -> Int {
return Int(self)
}
}
extension Double {
public func to(_ type: Int.Type) -> Int {
return Int(self)
}
}
extension Float {
public func to(_ type: Int.Type) -> Int {
return Int(self)
}
}
extension Float80 {
public func to(_ type: Int.Type) -> Int {
return Int(self)
}
}
extension StringProtocol {
public func to(_ type: Int.Type) -> Int? {
return Int(self)
}
}
extension BinaryInteger {
public func to(_ type: Int8.Type) -> Int8 {
return Int8(self)
}
}
extension BinaryFloatingPoint {
public func to(_ type: Int8.Type) -> Int8 {
return Int8(self)
}
}
extension Double {
public func to(_ type: Int8.Type) -> Int8 {
return Int8(self)
}
}
extension Float {
public func to(_ type: Int8.Type) -> Int8 {
return Int8(self)
}
}
extension Float80 {
public func to(_ type: Int8.Type) -> Int8 {
return Int8(self)
}
}
extension StringProtocol {
public func to(_ type: Int8.Type) -> Int8? {
return Int8(self)
}
}
extension BinaryInteger {
public func to(_ type: Int16.Type) -> Int16 {
return Int16(self)
}
}
extension BinaryFloatingPoint {
public func to(_ type: Int16.Type) -> Int16 {
return Int16(self)
}
}
extension Double {
public func to(_ type: Int16.Type) -> Int16 {
return Int16(self)
}
}
extension Float {
public func to(_ type: Int16.Type) -> Int16 {
return Int16(self)
}
}
extension Float80 {
public func to(_ type: Int16.Type) -> Int16 {
return Int16(self)
}
}
extension StringProtocol {
public func to(_ type: Int16.Type) -> Int16? {
return Int16(self)
}
}
extension BinaryInteger {
public func to(_ type: Int32.Type) -> Int32 {
return Int32(self)
}
}
extension BinaryFloatingPoint {
public func to(_ type: Int32.Type) -> Int32 {
return Int32(self)
}
}
extension Double {
public func to(_ type: Int32.Type) -> Int32 {
return Int32(self)
}
}
extension Float {
public func to(_ type: Int32.Type) -> Int32 {
return Int32(self)
}
}
extension Float80 {
public func to(_ type: Int32.Type) -> Int32 {
return Int32(self)
}
}
extension StringProtocol {
public func to(_ type: Int32.Type) -> Int32? {
return Int32(self)
}
}
extension BinaryInteger {
public func to(_ type: Int64.Type) -> Int64 {
return Int64(self)
}
}
extension BinaryFloatingPoint {
public func to(_ type: Int64.Type) -> Int64 {
return Int64(self)
}
}
extension Double {
public func to(_ type: Int64.Type) -> Int64 {
return Int64(self)
}
}
extension Float {
public func to(_ type: Int64.Type) -> Int64 {
return Int64(self)
}
}
extension Float80 {
public func to(_ type: Int64.Type) -> Int64 {
return Int64(self)
}
}
extension StringProtocol {
public func to(_ type: Int64.Type) -> Int64? {
return Int64(self)
}
}
extension BinaryInteger {
public func to(_ type: UInt.Type) -> UInt {
return UInt(self)
}
}
extension BinaryFloatingPoint {
public func to(_ type: UInt.Type) -> UInt {
return UInt(self)
}
}
extension Double {
public func to(_ type: UInt.Type) -> UInt {
return UInt(self)
}
}
extension Float {
public func to(_ type: UInt.Type) -> UInt {
return UInt(self)
}
}
extension Float80 {
public func to(_ type: UInt.Type) -> UInt {
return UInt(self)
}
}
extension StringProtocol {
public func to(_ type: UInt.Type) -> UInt? {
return UInt(self)
}
}
extension BinaryInteger {
public func to(_ type: UInt8.Type) -> UInt8 {
return UInt8(self)
}
}
extension BinaryFloatingPoint {
public func to(_ type: UInt8.Type) -> UInt8 {
return UInt8(self)
}
}
extension Double {
public func to(_ type: UInt8.Type) -> UInt8 {
return UInt8(self)
}
}
extension Float {
public func to(_ type: UInt8.Type) -> UInt8 {
return UInt8(self)
}
}
extension Float80 {
public func to(_ type: UInt8.Type) -> UInt8 {
return UInt8(self)
}
}
extension StringProtocol {
public func to(_ type: UInt8.Type) -> UInt8? {
return UInt8(self)
}
}
extension BinaryInteger {
public func to(_ type: UInt16.Type) -> UInt16 {
return UInt16(self)
}
}
extension BinaryFloatingPoint {
public func to(_ type: UInt16.Type) -> UInt16 {
return UInt16(self)
}
}
extension Double {
public func to(_ type: UInt16.Type) -> UInt16 {
return UInt16(self)
}
}
extension Float {
public func to(_ type: UInt16.Type) -> UInt16 {
return UInt16(self)
}
}
extension Float80 {
public func to(_ type: UInt16.Type) -> UInt16 {
return UInt16(self)
}
}
extension StringProtocol {
public func to(_ type: UInt16.Type) -> UInt16? {
return UInt16(self)
}
}
extension BinaryInteger {
public func to(_ type: UInt32.Type) -> UInt32 {
return UInt32(self)
}
}
extension BinaryFloatingPoint {
public func to(_ type: UInt32.Type) -> UInt32 {
return UInt32(self)
}
}
extension Double {
public func to(_ type: UInt32.Type) -> UInt32 {
return UInt32(self)
}
}
extension Float {
public func to(_ type: UInt32.Type) -> UInt32 {
return UInt32(self)
}
}
extension Float80 {
public func to(_ type: UInt32.Type) -> UInt32 {
return UInt32(self)
}
}
extension StringProtocol {
public func to(_ type: UInt32.Type) -> UInt32? {
return UInt32(self)
}
}
extension BinaryInteger {
public func to(_ type: UInt64.Type) -> UInt64 {
return UInt64(self)
}
}
extension BinaryFloatingPoint {
public func to(_ type: UInt64.Type) -> UInt64 {
return UInt64(self)
}
}
extension Double {
public func to(_ type: UInt64.Type) -> UInt64 {
return UInt64(self)
}
}
extension Float {
public func to(_ type: UInt64.Type) -> UInt64 {
return UInt64(self)
}
}
extension Float80 {
public func to(_ type: UInt64.Type) -> UInt64 {
return UInt64(self)
}
}
extension StringProtocol {
public func to(_ type: UInt64.Type) -> UInt64? {
return UInt64(self)
}
}
extension Int {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension Int8 {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension Int16 {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension Int32 {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension Int64 {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension UInt {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension UInt8 {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension UInt16 {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension UInt32 {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension UInt64 {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension Double {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension Float {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension Float80 {
public func to(_ type: Double.Type) -> Double {
return Double(self)
}
}
extension StringProtocol {
public func to(_ type: Double.Type) -> Double? {
return Double(self)
}
}
extension Int {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension Int8 {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension Int16 {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension Int32 {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension Int64 {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension UInt {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension UInt8 {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension UInt16 {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension UInt32 {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension UInt64 {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension Double {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension Float {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension Float80 {
public func to(_ type: Float.Type) -> Float {
return Float(self)
}
}
extension StringProtocol {
public func to(_ type: Float.Type) -> Float? {
return Float(self)
}
}
| 18.05293 | 52 | 0.593298 |
2327788e72dc1d8a76b874fa73f28eb98e830667 | 157 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(ChimneyTests.allTests),
]
}
#endif
| 15.7 | 45 | 0.66879 |
bf1b08329068c2bb9230e6bb032ac4c78cf27618 | 11,401 | //
// JSONAPIMetadata.swift
// Envoy
//
// Created by Fang-Pen Lin on 11/2/16.
// Copyright © 2016 Envoy Inc. All rights reserved.
//
import Foundation
import SwiftyJSON
/// Metadata for JSON API model
public final class JSONAPIMetadata {
public enum RelationshipType {
/// Has one relationship type
case singular(
getter: ((JSONAPIModelType) -> JSONAPIModelType?),
setter: ((JSONAPIModelType, JSONAPIModelType?) -> Void)
)
/// Has many relationship type
case multiple(
getter: ((JSONAPIModelType) -> [JSONAPIModelType]),
setter: ((JSONAPIModelType, [JSONAPIModelType]) -> Void)
)
}
public struct Relationship {
/// Key name in `relationships` of JSON API payload
let key: String
/// Type of relationship
let type: RelationshipType
}
public let type: String
public fileprivate(set) var relationships: [Relationship] = []
public init(type: String) {
self.type = type
}
/// Define a relationship
/// - Parameter relationship: relationship to add
public func define(_ relationship: Relationship) {
relationships.append(relationship)
}
}
/// MetadataHelper is a helper for creating JSONAPIMetadata, it does the ugly type casting for you
/// so that you don't need to.
public struct MetadataHelper<ModelType: JSONAPIModelType> {
public let metadata: JSONAPIMetadata
public init(type: String) {
metadata = JSONAPIMetadata(type: type)
}
/// Define a has-one relationship
/// - Parameters key: key of relationship
/// - Parameters getter: getter function for getting relationship JSONAPIModelType object from
/// model
/// - Parameters setter: setter function for setting relationship JSONAPIModelType object to
/// model
public func hasOne<ValueType: JSONAPIModelType>(
_ key: String,
_ getter: @escaping ((ModelType) -> ValueType?),
_ setter: @escaping ((ModelType, ValueType?) -> Void)
) {
let relationship = JSONAPIMetadata.Relationship(
key: key,
type: .singular(
getter: { (model: JSONAPIModelType) -> JSONAPIModelType? in
return getter(model as! ModelType)
},
setter: { (model: JSONAPIModelType, value: JSONAPIModelType?) -> Void in
return setter(model as! ModelType, value as? ValueType)
}
)
)
metadata.define(relationship)
}
/// Define a has-many relationship
/// - Parameters key: key of relationship
/// - Parameters getter: getter function for getting relationship JSONAPIModelType object
/// array from model
/// - Parameters setter: setter function for setting relationship JSONAPIModelType object
/// array to model
public func hasMany<ValueType: JSONAPIModelType>(
_ key: String,
_ getter: @escaping ((ModelType) -> [ValueType]),
_ setter: @escaping ((ModelType, [ValueType]) -> Void)
) {
let relationship = JSONAPIMetadata.Relationship(
key: key,
type: .multiple(
getter: { (model: JSONAPIModelType) -> [JSONAPIModelType] in
return getter(model as! ModelType).map { $0 as JSONAPIModelType }
},
setter: { (model: JSONAPIModelType, values: [JSONAPIModelType]) -> Void in
return setter(model as! ModelType, values.map { $0 as! ValueType })
}
)
)
metadata.define(relationship)
}
}
/// Attribute provides value binding between JSON with key to the left-hand-side value
public struct Attribute {
/// JSON object
public let json: JSON
/// Key for reading value from the JSON object
public let key: String
/// Callback for collecting values
public let collectValue: ((Any?) -> Void)?
public init(json: JSON, key: String) {
self.json = json
self.key = key
collectValue = nil
}
public init(key: String, collectValue: @escaping ((Any?) -> Void)) {
self.key = key
self.collectValue = collectValue
json = JSON([])
}
//// Bind value between `json[keyPath]` to the left-hand-side value
//// - Parameters lhs: the left-hande-side value to be bound to
public func bind<T>(_ lhs: inout T) throws {
if collectValue != nil {
try bindToJSON(lhs)
} else {
try bindFromJSON(&lhs)
}
}
//// Bind value between `json[keyPath]` to the left-hand-side optional value
//// - Parameters lhs: the optional left-hande-side optional value to be bound to
public func bind<T>(_ lhs: inout T?) throws {
if collectValue != nil {
try bindToJSON(lhs)
} else {
try bindFromJSON(&lhs)
}
}
private func bindToJSON<T>(_ lhs: T) throws {
collectValue!(lhs)
}
private func bindToJSON<T>(_ lhs: T?) throws {
guard let value = lhs else {
return
}
collectValue!(value)
}
private func bindFromJSON<T>(_ lhs: inout T) throws {
let jsonValue = json[key]
guard jsonValue.exists() else {
throw JSONAPIMap.Error.keyError(key: key)
}
guard let value = jsonValue.object as? T else {
throw JSONAPIMap.Error.valueError(key: key)
}
lhs = value
}
private func bindFromJSON<T>(_ lhs: inout T?) throws {
let jsonValue = json[key]
guard jsonValue.exists() else {
return
}
guard jsonValue.null == nil else {
lhs = nil
return
}
guard let value = jsonValue.object as? T else {
return
}
lhs = value
}
}
/// TransformedAttribute provides value binding between JSON with key to the left-hand-side value
/// with data transofmration
public struct TransformedAttribute<TransformType: Transform> {
/// JSON object
public let json: JSON
/// Key for reading value from the JSON object
public let key: String
/// The transform to be applied on the value we get from JSON object
public let transform: TransformType
/// Callback for collecting values
public let collectValue: ((Any?) -> Void)?
public init(json: JSON, key: String, transform: TransformType) {
self.json = json
self.key = key
self.transform = transform
collectValue = nil
}
public init(key: String, transform: TransformType, collectValue: @escaping ((Any?) -> Void)) {
json = JSON([])
self.key = key
self.transform = transform
self.collectValue = collectValue
}
//// Bind value between `json[keyPath]` to the left-hand-side value
//// - Parameters lhs: the left-hande-side value to be bound to
public func bind<T>(_ lhs: inout T) throws {
if collectValue != nil {
try bindToJSON(lhs)
} else {
try bindFromJSON(&lhs)
}
}
/// Bind value between `json[keyPath]` to the left-hand-side optional value
/// - Parameters lhs: the left-hande-side optional value to be bound to
public func bind<T>(_ lhs: inout T?) throws {
if collectValue != nil {
try bindToJSON(lhs)
} else {
try bindFromJSON(&lhs)
}
}
private func bindToJSON<T>(_ lhs: T) throws {
guard
let value = lhs as? TransformType.ValueType,
let transformed = transform.backward(value)
else {
throw JSONAPIMap.Error.valueError(key: key)
}
collectValue!(transformed)
}
private func bindToJSON<T>(_ lhs: T?) throws {
guard
let value = lhs as? TransformType.ValueType,
let transformed = transform.backward(value)
else {
return
}
collectValue!(transformed)
}
private func bindFromJSON<T>(_ lhs: inout T) throws {
let jsonValue = json[key]
guard jsonValue.exists() else {
throw JSONAPIMap.Error.keyError(key: key)
}
guard let value = transform.forward(jsonValue.object) as? T else {
throw JSONAPIMap.Error.valueError(key: key)
}
lhs = value
}
private func bindFromJSON<T>(_ lhs: inout T?) throws {
let jsonValue = json[key]
guard jsonValue.exists() else {
return
}
guard jsonValue.null == nil else {
lhs = nil
return
}
guard let value = transform.forward(jsonValue.object) as? T else {
return
}
lhs = value
}
}
/// JSONAPIMap provides `attribute` mapping methods for `JSONAPIModelType.mapping` method to define
/// attribute binding
public final class JSONAPIMap {
public static let attributesKey = "attributes"
public enum Error: Swift.Error {
case keyError(key: String)
case valueError(key: String)
}
/// Collected attributes for reading mode
public private(set) var collectedAttributes: [String: Any]?
private let json: JSON
public init(json: JSON) {
self.json = json
}
public init() {
json = JSON([])
collectedAttributes = [:]
}
/// Define attribute binding
/// - Parameters key: the key in `attributes` JSON dict for binding value from
/// - Returns: an Attribute object for the attribute binding
public func attribute(_ key: String) -> Attribute {
if collectedAttributes != nil {
return Attribute(key: key) { value in
self.collectedAttributes![key] = value
}
} else {
return Attribute(json: json[JSONAPIMap.attributesKey], key: key)
}
}
/// Define attribute binding using data transformer
/// - Parameters key: the key in `attributes` JSON dict for binding value from
/// - Parameters using: the TransformType to be used for transforming binding data
/// - Returns: an Attribute object for the attribute binding
public func attribute<TransformType: Transform>(
_ key: String,
using transform: TransformType
) -> TransformedAttribute<TransformType> {
if collectedAttributes != nil {
return TransformedAttribute(
key: key,
transform: transform
) { value in
self.collectedAttributes![key] = value
}
} else {
return TransformedAttribute(
json: json[JSONAPIMap.attributesKey],
key: key,
transform: transform
)
}
}
}
infix operator <-
public func <- <T>(lhs: inout T, rhs: Attribute) throws {
try rhs.bind(&lhs)
}
public func <- <T>(lhs: inout T?, rhs: Attribute) throws {
try rhs.bind(&lhs)
}
public func <- <T, TransformType: Transform>(lhs: inout T, rhs: TransformedAttribute<TransformType>) throws {
try rhs.bind(&lhs)
}
public func <- <T, TransformType: Transform>(lhs: inout T?, rhs: TransformedAttribute<TransformType>) throws {
try rhs.bind(&lhs)
}
| 31.935574 | 110 | 0.590825 |
d7c2d2a5d42f0d54ef593f439d268fbbdbadeb18 | 3,753 | //
// RemoteRequest.swift
// ListOfEmployees
//
// Created by Andrius Shiaulis on 10.08.2018.
// Copyright © 2018 Andrius Shiaulis. All rights reserved.
//
import Foundation
import os.log
class RemoteRequest {
// MARK: - Properties -
static private let logger = OSLog.init(subsystem: LogSubsystem.applicationModel, object: RemoteRequest.self)
private var dataObjects: [Data]
private var responses: [URLResponse]
private var errors: [Error]
// MARK: - Initialization -
init() {
self.dataObjects = []
self.responses = []
self.errors = []
}
// MARK: - Public methods
func performRequest(usingURLs urls:[URL], queue:DispatchQueue, completionHandler:@escaping ([Data], [URLResponse], [Error]) -> Void) {
queue.async { [weak self] in
guard let strongSelf = self else {
assertionFailure()
return
}
let urlSession = URLSession.init(configuration: .default)
// Dispatch group is used to implement synchronous waiting
// until all requests withing current DataFetcher will be finished
let group = DispatchGroup.init()
for url in urls {
group.enter()
os_log("Data fetch request started for URL '%@'", log: RemoteRequest.logger, type: .debug, url.absoluteString)
urlSession.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in
self?.handleNetworkResponse(data: data, response: response, error: error, dispatchGroup: group, queue: queue)
}).resume()
}
strongSelf.waitForFinishAllFetches(withGroup: group, queue: queue, completionHandler: completionHandler)
}
}
// MARK: - Private methods -
private func handleNetworkResponse(data: Data?, response: URLResponse?, error: Error?, dispatchGroup: DispatchGroup, queue: DispatchQueue) {
queue.sync { [weak self] in
guard let strongSelf = self else {
assertionFailure()
dispatchGroup.leave()
return
}
if let error = error {
os_log("Data fetch request for URL '%@' finished with error %@",
log: RemoteRequest.logger,
type: .debug,
response?.url?.path ?? "", error.localizedDescription)
strongSelf.errors.append(error)
dispatchGroup.leave()
return
}
guard let data = data else {
assertionFailure("Data expected to exist")
dispatchGroup.leave()
return
}
guard let response = response else {
assertionFailure("Response expected to exist")
dispatchGroup.leave()
return
}
os_log("Data fetch request for URL '%@' finished successfully",
log: RemoteRequest.logger,
type: .debug,
response.url?.absoluteString ?? "")
strongSelf.dataObjects.append(data)
strongSelf.responses.append(response)
dispatchGroup.leave()
}
}
private func waitForFinishAllFetches(withGroup group: DispatchGroup, queue: DispatchQueue, completionHandler:@escaping ([Data], [URLResponse], [Error]) -> Void) {
group.notify(queue: queue) { [weak self] in
guard let strongSelf = self else {
assertionFailure()
return
}
completionHandler(strongSelf.dataObjects, strongSelf.responses, strongSelf.errors)
}
}
}
| 34.431193 | 166 | 0.573141 |
469df6ca3f599cddeafda9f270095216b3d82bdd | 4,611 | // swift-tools-version:5.2
import PackageDescription
var dependencies: [Package.Dependency] = [
.package(url: "https://github.com/apple/swift-system", from: "1.0.0"),
.package(url: "https://github.com/jpsim/Yams", from: "4.0.0"),
.package(url: "https://github.com/tadija/AEXML", from: "4.0.0"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0"),
.package(name: "SwiftIndexStore", url: "https://github.com/kateinoigakukun/swift-indexstore", from: "0.0.0")
]
#if swift(>=5.5)
dependencies.append(
.package(
name: "SwiftSyntax",
url: "https://github.com/apple/swift-syntax",
.exact("0.50500.0")
)
)
#elseif swift(>=5.4)
dependencies.append(
.package(
name: "SwiftSyntax",
url: "https://github.com/apple/swift-syntax",
.exact("0.50400.0")
)
)
#elseif swift(>=5.3)
dependencies.append(
.package(
name: "SwiftSyntax",
url: "https://github.com/apple/swift-syntax",
.exact("0.50300.0")
)
)
#else
fatalError("This version of Periphery does not support Swift <= 5.2.")
#endif
#if os(macOS)
dependencies.append(
.package(
name: "XcodeProj",
url: "https://github.com/tuist/xcodeproj",
from: "8.0.0"
)
)
#endif
var frontendDependencies: [PackageDescription.Target.Dependency] = [
.target(name: "Shared"),
.target(name: "PeripheryKit"),
.product(name: "ArgumentParser", package: "swift-argument-parser")
]
#if os(macOS)
frontendDependencies.append(.target(name: "XcodeSupport"))
#endif
var targets: [PackageDescription.Target] = [
.target(
name: "Frontend",
dependencies: frontendDependencies
),
.target(
name: "PeripheryKit",
dependencies: [
.target(name: "Shared"),
.product(name: "SystemPackage", package: "swift-system"),
.product(name: "AEXML", package: "AEXML"),
.product(name: "SwiftSyntax", package: "SwiftSyntax"),
.product(name: "SwiftIndexStore", package: "SwiftIndexStore")
]
),
.target(
name: "Shared",
dependencies: [
.product(name: "Yams", package: "Yams"),
.product(name: "SystemPackage", package: "swift-system")
]
),
.target(
name: "RetentionFixturesCrossModule"
),
.target(
name: "TestShared",
dependencies: [
.target(name: "PeripheryKit")
],
path: "Tests/Shared"
),
.target(
name: "RetentionFixtures",
dependencies: ["RetentionFixturesCrossModule"],
path: "Tests/Fixtures/RetentionFixtures"
),
.target(
name: "UnusedParameterFixtures",
path: "Tests/Fixtures/UnusedParameterFixtures"
),
.target(
name: "TypeSyntaxInspectorFixtures",
path: "Tests/Fixtures/TypeSyntaxInspectorFixtures"
),
.target(
name: "FunctionVisitorFixtures",
path: "Tests/Fixtures/FunctionVisitorFixtures"
),
.target(
name: "PropertyVisitorFixtures",
path: "Tests/Fixtures/PropertyVisitorFixtures"
),
.testTarget(
name: "PeripheryTests",
dependencies: [
.target(name: "TestShared"),
.target(name: "PeripheryKit")
]
),
.testTarget(
name: "SPMTests",
dependencies: [
.target(name: "TestShared"),
.target(name: "PeripheryKit")
],
exclude: ["SPMProject"]
),
.testTarget(
name: "AccessibilityTests",
dependencies: [
.target(name: "TestShared"),
.target(name: "PeripheryKit")
],
exclude: ["AccessibilityProject"]
)
]
#if os(macOS)
targets.append(contentsOf: [
.target(
name: "XcodeSupport",
dependencies: [
.target(name: "Shared"),
.target(name: "PeripheryKit"),
.product(name: "XcodeProj", package: "XcodeProj"),
]
),
.target(
name: "ObjcRetentionFixtures",
path: "Tests/Fixtures/ObjcRetentionFixtures"
),
.testTarget(
name: "XcodeTests",
dependencies: [
.target(name: "TestShared"),
.target(name: "PeripheryKit"),
.target(name: "XcodeSupport")
],
exclude: ["UIKitProject", "SwiftUIProject"]
)
])
#endif
let package = Package(
name: "Periphery",
products: [
.executable(name: "periphery", targets: ["Frontend"])
],
dependencies: dependencies,
targets: targets,
swiftLanguageVersions: [.v5]
)
| 26.653179 | 112 | 0.576231 |
e54c0a35910670b00d450d3c43e71574c1f7031d | 2,321 | //
// DDZBaseViewModel.swift
// diandianzanumsers
//
// Created by 楠 on 2017/6/10.
// Copyright © 2017年 specddz. All rights reserved.
//
import UIKit
import RxSwift
public enum SNJumpType {
case push
case pop
case present
case dismiss
case popToRoot
}
open class SNBaseViewModel: NSObject {
public let disposeBag = DisposeBag()
public let jumpSubject = PublishSubject<(UIViewController?, SNJumpType)>()
static public var isCanJumpLogin = true
public let endRefresh = PublishSubject<Bool>()
override public init() {
super.init()
loading()
}
}
extension SNBaseViewModel {
@objc open func loading() {
}
// func validToLogin(code: Int?, backType: DDZLoginViewController.PopType) {
//
// if code == 1006 || code == 1080 {
// let vc = DDZLoginViewController()
// vc.backType = backType
// self.jumpSubject.onNext((vc, SNJumpType.push))
// }
//
// }
// func needLogin(error: SNNetError) {
//
// if error == .needLogin {
//
// let loginSingle = DDZSingleton.shared
//
// if loginSingle.isCancelLogin {
//
// } else {
//
// let vc = DDZLoginViewController()
// jumpSubject.onNext((vc, .push))
// }
// }
// }
}
public func VCJump(VC: UIViewController,to: UIViewController?, type: SNJumpType, completion: (() -> Swift.Void)? = nil) {
switch type {
case .push:
VC.navigationController?.pushViewController(to!, animated: true)
case .present:
VC.present(to!, animated: true, completion: completion)
case .pop, .dismiss:
// VC.navigationController?.popViewController(animated: true)
if let _ = VC.presentingViewController {
VC.dismiss(animated: true, completion: nil)
} else if let navi = VC.navigationController {
navi.popViewController()
}
case .popToRoot:
// VC.navigationController?.popToRootViewController(animated: true)
if let _ = VC.presentingViewController {
VC.dismiss(animated: true, completion: nil)
} else if let navi = VC.navigationController {
navi.popToRootViewController(animated: true)
}
}
}
| 24.691489 | 121 | 0.596295 |
f9e0132dc6456a8789eba70f55cc189d94f003be | 222 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
0.a
protocol B : a {
let a : e
0
{
{
}
}
typealias e
| 15.857143 | 87 | 0.716216 |
9058e0c672ee762ae54ee9b3c192231b4790a470 | 54,534 | import Foundation
import UIKit
import SafariServices
import SnapKit
import RxSwift
import RxCocoa
import MobileCoreServices
class TopicDetailViewController: DataViewController, TopicService {
/// MARK: - UI
private lazy var tableView: UITableView = {
let view = UITableView()
view.delegate = self
view.dataSource = self
view.separatorStyle = .none
view.rowHeight = UITableView.automaticDimension
view.estimatedRowHeight = 80
view.backgroundColor = .clear
// view.keyboardDismissMode = .onDrag
view.register(cellWithClass: TopicCommentCell.self)
var inset = view.contentInset
inset.top = navigationController?.navigationBar.height ?? 64
view.contentInset = inset
inset.bottom = 0
if #available(iOS 11.0, *) {
view.contentInsetAdjustmentBehavior = .never
}
view.scrollIndicatorInsets = inset
view.cellLayoutMarginsFollowReadableWidth = false
self.view.addSubview(view)
return view
}()
private lazy var imagePicker: UIImagePickerController = {
let view = UIImagePickerController()
view.mediaTypes = [kUTTypeImage as String]
view.sourceType = .photoLibrary
view.delegate = self
return view
}()
private lazy var headerView: TopicDetailHeaderView = {
let view = TopicDetailHeaderView()
view.isHidden = true
return view
}()
private lazy var commentInputView: CommentInputView = {
let view = CommentInputView(frame: .zero)
view.isHidden = true
self.view.addSubview(view)
return view
}()
private lazy var backTopBtn: UIButton = {
let view = UIButton()
view.setImage(#imageLiteral(resourceName: "backTop"), for: .normal)
view.setImage(#imageLiteral(resourceName: "backTop"), for: .selected)
view.sizeToFit()
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOpacity = 0.2
view.layer.shadowRadius = 4
self.view.addSubview(view)
view.isHidden = true
return view
}()
// MARK: Propertys
private var topic: TopicModel? {
didSet {
guard let topic = topic else { return }
title = topic.title
headerView.topic = topic
}
}
public var anchor: Int?
public var replyCount: Int?
private var isShowBackLastBrowseView: Bool = false
private var selectComment: CommentModel? {
guard let selectIndexPath = tableView.indexPathForSelectedRow else {
return nil
}
return dataSources[selectIndexPath.row]
}
public var topicID: String
public var showInputView: Bool?
// 加工数据
private var dataSources: [CommentModel] = [] {
didSet {
var title = dataSources.count.boolValue ? "全部回复" : ""
if isShowOnlyFloor {
title = dataSources.count.boolValue ? "楼主回复" : "楼主暂无回复"
}
headerView.replyTitle = title
}
}
// 原始数据
private var comments: [CommentModel] = []
private var commentText: String = ""
private var isShowOnlyFloor: Bool = false
private var page = 1, maxPage = 1, currentPage = 1, size = 100
private var inputViewBottomConstranit: Constraint?
private var inputViewHeightConstraint: Constraint?
private let isSelectedVariable = Variable(false)
private let isShowToolBarVariable = Variable(false)
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
userActivity = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)
userActivity?.webpageURL = API.topicDetail(topicID: topicID, page: page).url
userActivity?.becomeCurrent()
}
deinit {
setStatusBarBackground(.clear)
userActivity?.invalidate()
guard let topic = self.topic else { return }
let offsetY = Int(self.tableView.contentOffset.y)
// SQLiteDatabase.instance?.setAnchor(topicID: topicID, anchor: y)
if let topicID = topicID.int, let username = topic.member?.username, let avatarSrc = topic.member?.avatarSrc {
SQLiteDatabase.instance?.addHistory(tid: topicID, title: topic.title, username: username, avatarURL: avatarSrc, offsetY: offsetY, replyCount: replyCount)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let isShow = showInputView {
if isShow == false {
commentInputView.isHidden = true
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
commentInputView.textView.resignFirstResponder()
isShowToolBarVariable.value = false
setStatusBarBackground(.clear)
// guard let topicID = topicID.int else { return }
// let y = Int(self.tableView.contentOffset.y)
// SQLiteDatabase.instance?.setAnchor(topicID: topicID, anchor: y)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
setStatusBarBackground(.clear)
isShowToolBarVariable.value = false
}
init(topicID: String) {
self.topicID = topicID
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
// 如果当前 textView 是第一响应者,则忽略自定义的 MenuItemAction, 不在 Menu视图上显示自定义的 item
if !isFirstResponder, [#selector(copyCommentAction),
#selector(replyCommentAction),
#selector(thankCommentAction),
#selector(viewDialogAction),
#selector(atMemberAction),
#selector(fenCiAction)].contains(action) {
return false
}
return super.canPerformAction(action, withSender: sender)
}
// MARK: - Setup
override func setupSubviews() {
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: tableView)
}
tableView.tableHeaderView = headerView
headerView.tapHandle = { [weak self] type in
self?.tapHandle(type)
}
headerView.webLoadComplete = { [weak self] in
guard let `self` = self else { return }
self.endLoading()
self.headerView.isHidden = false
self.tableView.reloadData()
self.setupRefresh()
self.perform(#selector(self.scrollToAnchor), with: nil, afterDelay: 0.5)
}
commentInputView.sendHandle = { [weak self] in
self?.replyComment()
}
commentInputView.uploadPictureHandle = { [weak self] in
guard let `self` = self else { return }
self.present(self.imagePicker, animated: true, completion: nil)
}
commentInputView.atUserHandle = { [weak self] in
guard let `self` = self,
self.comments.count.boolValue else { return }
self.atMembers()
}
commentInputView.updateHeightHandle = { [weak self] height in
self?.inputViewHeightConstraint?.update(offset: height)
}
navigationItem.rightBarButtonItem = UIBarButtonItem(
image: #imageLiteral(resourceName: "moreNav"),
style: .plain,
action: { [weak self] in
self?.moreHandle()
})
title = "加载中..."
}
private func setupRefresh() {
tableView.addHeaderRefresh { [weak self] in
self?.fetchTopicDetail()
}
tableView.addFooterRefresh { [weak self] in
self?.fetchMoreComment()
}
}
private func scrollToLastBrwoseLocation() {
guard let topicID = topicID.int, !isShowBackLastBrowseView else { return }
guard let offsetY = SQLiteDatabase.instance?.getAnchor(topicID: topicID)?.f else { return }
guard offsetY != -1, offsetY > tableView.height || CGFloat(offsetY) > headerView.height else { return }
isShowBackLastBrowseView = true
HUD.showBackBrowseLocationView("回到上次浏览位置") { [weak self] in
self?.tableView.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true)
}
}
// 滚动到锚点位置
@objc private func scrollToAnchor() {
if self.anchor == nil {
scrollToLastBrwoseLocation()
return
}
guard let maxFloor = dataSources.last?.floor.int else { return }
guard let anchor = self.anchor,
maxFloor >= anchor else { return }
// tableView.numberOfRows(inSection: 0) >= anchor else { return }
self.anchor = nil
isShowBackLastBrowseView = true
guard let index = (dataSources.firstIndex { $0.floor == anchor.description }) else { return }
let indexPath = IndexPath(row: Int(index), section: 0)
guard indexPath.row < tableView.numberOfRows(inSection: 0) else { return }
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
GCD.delay(1, block: {
UIView.animate(withDuration: 1, delay: 0, options: .curveLinear, animations: {
self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
}, completion: { _ in
UIView.animate(withDuration: 0.5, delay: 0.8, options: .curveLinear, animations: {
self.tableView.deselectRow(at: indexPath, animated: true)
})
})
})
}
private func interactHook(_ URL: URL) {
let link = URL.absoluteString
if URL.path.contains("/member/") {
let href = URL.path
let name = href.lastPathComponent
let member = MemberModel(username: name, url: href, avatar: "")
tapHandle(.member(member))
} else if URL.path.contains("/t/") {
let topicID = URL.path.lastPathComponent
tapHandle(.topic(topicID))
} else if URL.path.contains("/go/") {
tapHandle(.node(NodeModel(title: "", href: URL.path)))
} else if link.hasPrefix("https://") || link.hasPrefix("http://"){
tapHandle(.webpage(URL))
}
}
override func setupConstraints() {
tableView.snp.makeConstraints {
$0.left.right.bottom.equalToSuperview()
// $0.top.equalToSuperview().offset(0.5)
$0.top.equalToSuperview().offset(-(tableView.contentInset.top - 0.8))
}
var inputViewHeight = KcommentInputViewHeight
if #available(iOS 11.0, *) {
inputViewHeight += AppWindow.shared.window.safeAreaInsets.bottom//view.safeAreaInsets.bottom
}
tableView.contentInset = UIEdgeInsets(top: tableView.contentInset.top, left: tableView.contentInset.left, bottom: KcommentInputViewHeight, right: tableView.contentInset.right)
commentInputView.snp.makeConstraints {
$0.left.right.equalToSuperview()
self.inputViewBottomConstranit = $0.bottom.equalToSuperview().constraint
self.inputViewHeightConstraint = $0.height.equalTo(inputViewHeight).constraint
}
backTopBtn.snp.makeConstraints {
$0.right.equalToSuperview().inset(12)
$0.bottom.equalTo(commentInputView.snp.top).offset(-12)
}
}
override func setupRx() {
ThemeStyle.style.asObservable()
.subscribeNext { [weak self] theme in
setStatusBarBackground(theme.navColor, borderColor: .clear)
self?.headerView.topic = self?.topic
}.disposed(by: rx.disposeBag)
NotificationCenter.default.rx
.notification(UIApplication.willEnterForegroundNotification)
.subscribeNext { _ in
setStatusBarBackground(.clear)
}.disposed(by: rx.disposeBag)
/// 登录成功后, 刷新 once
NotificationCenter.default.rx
.notification(Notification.Name.V2.LoginSuccessName)
.subscribeNext { [weak self] _ in
self?.fetchTopicDetail()
}.disposed(by: rx.disposeBag)
backTopBtn.rx.tap
.subscribeNext { [weak self] in
guard let `self` = self else { return }
self.isShowToolBarVariable.value = false
if self.backTopBtn.isSelected {
self.tableView.setContentOffset(CGPoint(x: 0, y: -self.tableView.contentInset.top), animated: true)
} else {
// 会导致UI卡顿, 原因未知
// if self.dataSources.count.boolValue {
// let indexPath = IndexPath(row: self.dataSources.count - 1, section: 0)
// self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
// } else {
self.tableView.scrollToBottom()
// }
}
}.disposed(by: rx.disposeBag)
backTopBtn.rx.longPressGesture
.subscribeNext { [weak self] _ in
guard let `self` = self, self.maxPage > 1 else { return }
let alertController = UIAlertController(title: "切换分页", message: nil, preferredStyle: .actionSheet)
let rows = self.tableView.numberOfRows(inSection: 0)
if self.currentPage > 1 {
alertController.addAction(UIAlertAction(title: "上一页", style: .default, handler: { alertAction in
self.currentPage -= 1
let previousRow = ((self.currentPage - 1) * self.size)
guard rows >= previousRow else { return }
self.tableView.scrollToRow(at: IndexPath(row: previousRow, section: 0), at: .top, animated: true)
}))
}
if self.currentPage < self.maxPage {
alertController.addAction(UIAlertAction(title: "下一页", style: .default, handler: { alertAction in
let nextRow = (self.currentPage) * self.size
guard rows >= nextRow else { return }
self.tableView.scrollToRow(at: IndexPath(row: rows > nextRow ? nextRow : nextRow - 1, section: 0), at: .top, animated: true)
self.currentPage += 1
}))
}
alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
alertController.show(self, sourceView: self.backTopBtn)
}.disposed(by: rx.disposeBag)
Observable.of(NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification),
NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification),
NotificationCenter.default.rx.notification(UIResponder.keyboardDidShowNotification),
NotificationCenter.default.rx.notification(UIResponder.keyboardDidHideNotification)).merge()
.subscribeNext { [weak self] notification in
guard let `self` = self else { return }
guard var userInfo = notification.userInfo,
let keyboardRect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
let convertedFrame = self.view.convert(keyboardRect, from: nil)
let heightOffset = self.view.bounds.size.height - convertedFrame.origin.y
let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
self.inputViewBottomConstranit?.update(offset: -heightOffset)
UIView.animate(withDuration: duration ?? 0.25) {
self.view.layoutIfNeeded()
}
if self.commentInputView.textView.isFirstResponder {
_ = self.selectComment
}
}.disposed(by: rx.disposeBag)
// NotificationCenter.default.rx
// .notification(.UIApplicationUserDidTakeScreenshot)
// .subscribeNext { noti in
// guard let img = AppWindow.shared.window.screenshot else { return }
// showImageBrowser(imageType: .image(img))
// }.disposed(by: rx.disposeBag)
isSelectedVariable.asObservable()
.distinctUntilChanged()
.subscribeNext { [weak self] isSelected in
guard let `self` = self else { return }
UIView.animate(withDuration: 0.2) {
self.backTopBtn.transform = isSelected ? CGAffineTransform(rotationAngle: .pi) : .identity
self.backTopBtn.isSelected = isSelected
}
}.disposed(by: rx.disposeBag)
isShowToolBarVariable.asObservable()
.distinctUntilChanged()
.subscribeNext { [weak self] isShow in
self?.setTabBarHiddn(isShow)
}.disposed(by: rx.disposeBag)
// tableView.rx.tapGesture
// .subscribeNext { [weak self] gesture in
// guard let `self` = self else { return }
// let point = gesture.location(in: self.tableView)
// guard let indexPath = self.tableView.indexPathForRow(at: point) else { return }
// self.didSelectRowAt(indexPath, point: point)
// }.disposed(by: rx.disposeBag)
NotificationCenter.default.rx
.notification(UIMenuController.didHideMenuNotification)
.subscribeNext { [weak self] _ in
guard let selectIndexPath = self?.tableView.indexPathForSelectedRow else { return }
GCD.delay(0.3, block: {
if UIMenuController.shared.isMenuVisible.not {
self?.tableView.deselectRow(at: selectIndexPath, animated: false)
}
})
}.disposed(by: rx.disposeBag)
}
// MARK: States Handle
override func hasContent() -> Bool {
let hasContent = topic != nil
if hasContent && (showInputView == nil || showInputView == true) {
commentInputView.isHidden = false
}
return hasContent
}
override func loadData() {
fetchTopicDetail()
}
override func errorView(_ errorView: ErrorView, didTapActionButton sender: UIButton) {
fetchTopicDetail()
}
}
// MARK: - UITableViewDelegate, UITableViewDataSource
extension TopicDetailViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSources.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withClass: TopicCommentCell.self)!
let comment = dataSources[indexPath.row]
cell.hostUsername = topic?.member?.username ?? ""
let forewordComment = CommentModel.forewordComment(comments: comments, currentComment: comment)
cell.forewordComment = forewordComment
cell.comment = comment
cell.tapHandle = { [weak self] type in
self?.tapHandle(type)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 强制结束 HeaderView 中 WebView 的第一响应者, 不然无法显示 MenuView
if !commentInputView.textView.isFirstResponder { view.endEditing(true) }
// 如果当前控制器不是第一响应者不显示 MenuView
if isFirstResponder.not { commentInputView.textView.resignFirstResponder() }
guard let cell = tableView.cellForRow(at: indexPath) else { return }
let comment = dataSources[indexPath.row]
let menuVC = UIMenuController.shared
var targetRectangle = cell.frame
let cellFrame = tableView.convert(tableView.rectForRow(at: indexPath), to: tableView.superview)
let cellbottom = cellFrame.maxY
let cellTop = cellFrame.origin.y
let cellBottomVisibleHeight = (cellFrame.height - (cellbottom - view.height) - (isShowToolBarVariable.value.not ? commentInputView.height : 0)).half
let cellTopVisibleHeight = abs(cellTop) + ((cellFrame.height - abs(cellTop)).half)
targetRectangle.origin.y = cellbottom > tableView.height ? cellBottomVisibleHeight : cellTop < tableView.y ? cellTopVisibleHeight : targetRectangle.height.half
let replyItem = UIMenuItem(title: "回复", action: #selector(replyCommentAction))
let atUserItem = UIMenuItem(title: "@TA", action: #selector(atMemberAction))
let copyItem = UIMenuItem(title: "复制", action: #selector(copyCommentAction))
let fenCiItem = UIMenuItem(title: "分词", action: #selector(fenCiAction))
let thankItem = UIMenuItem(title: "感谢", action: #selector(thankCommentAction))
let viewDialogItem = UIMenuItem(title: "对话", action: #selector(viewDialogAction))
menuVC.setTargetRect(targetRectangle, in: cell)
menuVC.menuItems = [replyItem, copyItem, atUserItem, viewDialogItem]
if comment.content.trimmed.isNotEmpty {
menuVC.menuItems?.insert(fenCiItem, at: 2)
}
// 不显示感谢的情况
// 1. 已经感谢
// 2. 当前题主是登录用户本人 && 点击的回复是题主本人
// 3. 当前点击的回复是登录用户本人
if comment.isThank ||
(topic?.member?.username == comment.member.username &&
AccountModel.current?.username == topic?.member?.username) ||
AccountModel.current?.username == comment.member.username {
} else {
menuVC.menuItems?.insert(thankItem, at: 1)
}
menuVC.setMenuVisible(true, animated: true)
if #available(iOS 10.0, *) {
let generator = UIImpactFeedbackGenerator(style: .light)
generator.prepare()
generator.impactOccurred()
}
}
}
// MARK: - UIScrollViewDelegate
extension TopicDetailViewController {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let currentIndexPath = self.tableView.indexPathsForVisibleRows?.last?.row {
currentPage = (currentIndexPath / size) + 1
// log.info(currentPage)
}
commentInputView.textView.resignFirstResponder()
let isReachedBottom = scrollView.isReachedBottom()
if backTopBtn.isHidden.not {
isSelectedVariable.value = isReachedBottom// ? true : scrollView.contentOffset.y > 2000
}
let contentHeightLessThanViewHeight = scrollView.contentOffset.y < (navigationController?.navigationBar.height ?? 64)
let isReachedTop = scrollView.contentOffset.y < 0
if isReachedTop {
isShowToolBarVariable.value = false
return
}
if contentHeightLessThanViewHeight || isReachedBottom {
return
}
//获取到拖拽的速度 >0 向下拖动 <0 向上拖动
let velocity = scrollView.panGestureRecognizer.velocity(in: scrollView).y
if (velocity < -5) {
//向上拖动,隐藏导航栏
if !isShowToolBarVariable.value {
isShowToolBarVariable.value = true
}
}else if (velocity > 5) {
//向下拖动,显示导航栏
if isShowToolBarVariable.value {
isShowToolBarVariable.value = false
}
}else if (velocity == 0) {
//停止拖拽
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// commentInputView.textView.resignFirstResponder()
// ContentSize 大于 当前视图高度才显示, 滚动到底部/顶部按钮
// 150 的偏差
backTopBtn.isHidden = tableView.contentSize.height < (tableView.height + 150)
}
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
isShowToolBarVariable.value = false
return true
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.isReachedBottom() {
setTabBarHiddn(false, duration: 0.3)
isShowToolBarVariable.value = false
}
}
private func setTabBarHiddn(_ hidden: Bool, duration: TimeInterval = 0.1) {
guard tableView.contentSize.height > view.height else { return }
guard let navHeight = navigationController?.navigationBar.height else { return }
UIView.animate(withDuration: duration, animations: {
if hidden {
self.inputViewBottomConstranit?.update(inset: -self.commentInputView.height)
self.view.layoutIfNeeded()
self.navigationController?.navigationBar.y -= navHeight + UIApplication.shared.statusBarFrame.height
GCD.delay(0.1, block: {
setStatusBarBackground(ThemeStyle.style.value.navColor, borderColor: ThemeStyle.style.value.borderColor)
})
self.tableView.height = Constants.Metric.screenHeight
} else { //显示
self.inputViewBottomConstranit?.update(inset: 0)
self.view.layoutIfNeeded()
self.navigationController?.navigationBar.y = UIApplication.shared.statusBarFrame.height
setStatusBarBackground(.clear)
}
})
}
}
// MARK: - UIImagePickerControllerDelegate && UINavigationControllerDelegate
extension TopicDetailViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true, completion: nil)
guard var image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
image = image.resized(by: 0.7)
guard let data = image.jpegData(compressionQuality: 0.5) else { return }
let path = FileManager.document.appendingPathComponent("smfile.png")
let error = FileManager.save(data, savePath: path)
if let err = error {
HUD.showTest(err)
log.error(err)
}
uploadPictureHandle(path)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true) {
self.commentInputView.textView.becomeFirstResponder()
}
}
}
// MARK: - 处理 Cell 内部、导航栏Item、SheetShare 的 Action
extension TopicDetailViewController {
/// Cell 内部点击处理
///
/// - Parameter type: 触发的类型
private func tapHandle(_ type: TapType) {
switch type {
case .reply, .memberAvatarLongPress: break
default: setStatusBarBackground(.clear)
}
switch type {
case .webpage(let url):
openWebView(url: url)
case .member(let member):
self.setTabBarHiddn(false)
let memberPageVC = MemberPageViewController(memberName: member.username)
self.navigationController?.pushViewController(memberPageVC, animated: true)
case .memberAvatarLongPress(let member):
atMember(member.atUsername)
case .reply(let comment):
if comment.member.atUsername == commentInputView.textView.text && commentInputView.textView.isFirstResponder { return }
commentInputView.textView.text = ""
if let index = comments.firstIndex(of: comment) {
tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none)
GCD.delay(1) {
self.tableView.deselectRow(at: IndexPath(row: index, section: 0), animated: true)
}
}
atMember(comment.member.atUsername, comment: comment)
case .imageURL(let src):
showImageBrowser(imageType: .imageURL(src))
case .image(let image):
showImageBrowser(imageType: .image(image))
case .node(let node):
let nodeDetailVC = NodeDetailViewController(node: node)
self.navigationController?.pushViewController(nodeDetailVC, animated: true)
case .topic(let topicID):
let topicDetailVC = TopicDetailViewController(topicID: topicID)
self.navigationController?.pushViewController(topicDetailVC, animated: true)
case .foreword(let comment):
if isShowOnlyFloor {
HUD.showInfo("当前为\"只看楼主\"模式,请切换到\"查看所有\"模式下查看")
return
}
// 主题可能被抽层, 不在依赖 floor, 而去数据源中查
// guard let floor = comment.floor.int else { return }
guard let index = dataSources.firstIndex(of: comment) else { return }
let forewordIndexPath = IndexPath(row: Int(index), section: 0)
// 在当前可视范围内 并且 cell没有超出屏幕外
if let cell = tableView.cellForRow(at: forewordIndexPath),
(tableView.visibleCells.contains(cell) && (cell.y - tableView.contentOffset.y > 10 || cell.y - tableView.contentOffset.y > cell.height)) {
} else {
let currentContentOffset = tableView.contentOffset
tableView.scrollToRow(at: forewordIndexPath, at: .top, animated: true)
HUD.showBackBrowseLocationView("返回") { [weak self] in
self?.tableView.setContentOffset(currentContentOffset, animated: true)
}
}
GCD.delay(0.6, block: {
UIView.animate(withDuration: 1, delay: 0, options: .curveLinear, animations: {
self.tableView.selectRow(at: forewordIndexPath, animated: true, scrollPosition: .none)
}, completion: { _ in
UIView.animate(withDuration: 0.5, delay: 0.8, options: .curveLinear, animations: {
self.tableView.deselectRow(at: forewordIndexPath, animated: true)
})
})
})
}
}
/// 点击更多处理
private func moreHandle() {
setStatusBarBackground(.clear)
view.endEditing(true)
/// 切换 是否显示楼主
let floorItem = isShowOnlyFloor ?
ShareItem(icon: #imageLiteral(resourceName: "unfloor"), title: "查看所有", type: .floor) :
ShareItem(icon: #imageLiteral(resourceName: "floor"), title: "只看楼主", type: .floor)
let favoriteItem = (topic?.isFavorite ?? false) ?
ShareItem(icon: #imageLiteral(resourceName: "favorite"), title: "取消收藏", type: .favorite) :
ShareItem(icon: #imageLiteral(resourceName: "unfavorite"), title: "收藏", type: .favorite)
var section1 = [floorItem, favoriteItem]
// 如果已经登录 并且 是当前登录用户发表的主题, 则隐藏 感谢和忽略
let username = AccountModel.current?.username ?? ""
if username != topic?.member?.username {
let thankItem = (topic?.isThank ?? false) ?
ShareItem(icon: #imageLiteral(resourceName: "thank"), title: "已感谢", type: .thank) :
ShareItem(icon: #imageLiteral(resourceName: "alreadyThank"), title: "感谢", type: .thank)
section1.append(thankItem)
section1.append(ShareItem(icon: #imageLiteral(resourceName: "ignore"), title: "忽略", type: .ignore))
section1.append(ShareItem(icon: #imageLiteral(resourceName: "report"), title: "举报", type: .report))
if let _ = topic?.reportToken {
section1.append(ShareItem(icon: #imageLiteral(resourceName: "report"), title: "报告主题", type: .reportTopic))
}
}
let section2 = [
ShareItem(icon: #imageLiteral(resourceName: "copy_link"), title: "复制链接", type: .copyLink),
ShareItem(icon: #imageLiteral(resourceName: "safari"), title: "在 Safari 中打开", type: .safari),
ShareItem(icon: #imageLiteral(resourceName: "share"), title: "分享", type: .share)
]
let sheetView = ShareSheetView(sections: [section1, section2])
sheetView.present()
sheetView.shareSheetDidSelectedHandle = { [weak self] type in
self?.shareSheetDidSelectedHandle(type)
}
}
// 点击导航栏右侧的 更多
private func shareSheetDidSelectedHandle(_ type: ShareItemType) {
// 需要授权的操作
if type.needAuth, !AccountModel.isLogin{
HUD.showError("请先登录")
return
}
switch type {
case .floor:
showOnlyFloorHandle()
case .favorite:
favoriteHandle()
case .thank:
thankTopicHandle()
case .ignore:
ignoreTopicHandle()
case .report:
reportHandle()
case .reportTopic:
reportTopicHandle()
case .copyLink:
copyLink()
case .safari:
openSafariHandle()
case .share:
systemShare()
default:
break
}
}
}
// MARK: - 点击回复的相关操作
extension TopicDetailViewController {
// 如果已经 at 的用户, 让 TextView 选中用户名
private func atMember(_ atUsername: String?, comment: CommentModel? = nil) {
guard var `atUsername` = atUsername, atUsername.trimmed.isNotEmpty else { return }
commentInputView.textView.becomeFirstResponder()
if commentInputView.textView.text.contains(atUsername) {
let range = commentInputView.textView.text.NSString.range(of: atUsername)
commentInputView.textView.selectedRange = range
return
}
if let lastCharacter = commentInputView.textView.text.last, lastCharacter != " " {
atUsername.insert(" ", at: commentInputView.textView.text.startIndex)
}
let selectedComment = comment ?? selectComment
if Preference.shared.atMemberAddFloor, let floor = selectedComment?.floor {
atUsername += ("#" + floor + " ")
// 如果设置了 selectedRange, 文本会被替换, 故重新设置 range
commentInputView.textView.selectedRange = NSRange(location: commentInputView.textView.text.count, length: 0)
}
commentInputView.textView.insertText(atUsername)
}
private func atMembers() {
// 解层
let members = self.comments.compactMap { $0.member }
let memberSet = Set<MemberModel>(members)
let uniqueMembers = Array(memberSet).filter { $0.username != AccountModel.current?.username }
let memberListVC = MemberListViewController(members: uniqueMembers )
let nav = NavigationViewController(rootViewController: memberListVC)
self.present(nav, animated: true, completion: nil)
memberListVC.callback = { [weak self] members in
guard let `self` = self else { return }
self.commentInputView.textView.becomeFirstResponder()
guard members.count.boolValue else { return }
var atsWrapper = members
.filter{ !self.commentInputView.textView.text.contains($0.atUsername) }
.map { $0.atUsername }
.joined()
if self.commentInputView.textView.text.last != " " {
atsWrapper.insert(" ", at: self.commentInputView.textView.text.startIndex)
}
self.commentInputView.textView.deleteBackward()
self.commentInputView.textView.insertText(atsWrapper)
}
}
@objc private func replyCommentAction() {
commentInputView.textView.text = ""
atMember(selectComment?.member.atUsername)
}
@objc private func thankCommentAction() {
guard let replyID = selectComment?.id,
let token = topic?.token else {
HUD.showError("操作失败")
return
}
thankReply(replyID: replyID, token: token, success: { [weak self] in
guard let `self` = self,
let selectIndexPath = self.tableView.indexPathForSelectedRow else { return }
HUD.showSuccess("已成功发送感谢")
self.dataSources[selectIndexPath.row].isThank = true
if let thankCount = self.dataSources[selectIndexPath.row].thankCount {
self.dataSources[selectIndexPath.row].thankCount = thankCount + 1
} else {
self.dataSources[selectIndexPath.row].thankCount = 1
}
// self.tableView.reloadData {}
log.info([selectIndexPath])
self.tableView.reloadRows(at: [selectIndexPath], with: .none)
}) { error in
HUD.showError(error)
}
}
@objc private func copyCommentAction() {
guard let content = selectComment?.content else { return }
let result = TextParser.extractLink(content)
// 如果没有识别到链接, 或者 结果只有一个并且与本身内容一样
// 则直接复制到剪切板
if result.count == 0 || result.count == 1 && result[0] == content {
UIPasteboard.general.string = content
HUD.showSuccess("已复制到剪切板")
return
}
let alertVC = UIAlertController(title: "提取文本", message: nil, preferredStyle: .actionSheet)
let action: ((UIAlertAction) -> Void) = {
UIPasteboard.general.string = $0.title;
HUD.showSuccess("已复制到剪切板")
}
alertVC.addAction(
UIAlertAction(
title: content.deleteOccurrences(target: "\r").deleteOccurrences(target: "\n"),
style: .default,
handler: action)
)
for item in result {
alertVC.addAction(UIAlertAction(title: item, style: .default, handler: action))
}
if let indexPath = tableView.indexPathForSelectedRow,
let cell = tableView.cellForRow(at: indexPath) {
alertVC.popoverPresentationController?.sourceView = cell
alertVC.popoverPresentationController?.sourceRect = cell.bounds
}
alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
setStatusBarBackground(.clear)
present(alertVC, animated: true, completion: nil)
}
@objc private func fenCiAction() {
guard let text = selectComment?.content else { return }
let vc = FenCiViewController(text: text)
navigationController?.pushViewController(vc, animated: true)
}
@objc private func viewDialogAction() {
guard let `selectComment` = selectComment else { return }
let dialogs = CommentModel.atUsernameComments(comments: comments, currentComment: selectComment)
guard dialogs.count.boolValue else {
HUD.showInfo("没有找到与该用户有关的对话")
return
}
let viewDialogVC = ViewDialogViewController(comments: dialogs, username: selectComment.member.username)
let nav = NavigationViewController(rootViewController: viewDialogVC)
present(nav, animated: true, completion: nil)
}
@objc private func atMemberAction() {
atMember(selectComment?.member.atUsername)
}
}
// MARK: - Request
extension TopicDetailViewController {
/// 获取主题详情
func fetchTopicDetail(complete: (() -> Void)? = nil) {
page = 1
startLoading()
topicDetail(topicID: topicID, success: { [weak self] topic, comments, maxPage in
guard let `self` = self else { return }
self.dataSources = comments
self.comments = comments
self.topic = topic
self.tableView.endHeaderRefresh()
self.maxPage = maxPage
self.isShowOnlyFloor = false
complete?()
}, failure: { [weak self] error in
self?.errorMessage = error
self?.endLoading(error: NSError(domain: "V2EX", code: -1, userInfo: nil))
self?.tableView.endHeaderRefresh()
self?.title = "加载失败"
})
}
/// 获取更多评论
func fetchMoreComment() {
if page >= maxPage {
self.tableView.endRefresh(showNoMore: true)
return
}
page += 1
topicMoreComment(topicID: topicID, page: page, success: { [weak self] comments in
guard let `self` = self else { return }
self.dataSources.append(contentsOf: comments)
self.comments.append(contentsOf: comments)
self.tableView.endFooterRefresh(showNoMore: self.page >= self.maxPage)
self.refreshDataSource()
}, failure: { [weak self] error in
self?.tableView.endFooterRefresh()
self?.page -= 1
})
}
/// 回复评论
private func replyComment() {
guard let `topic` = self.topic else {
HUD.showError("回复失败")
return
}
guard AccountModel.isLogin else {
HUD.showError("请先登录", completionBlock: {
presentLoginVC()
})
return
}
guard commentInputView.textView.text.trimmed.isNotEmpty else {
HUD.showInfo("回复失败,您还没有输入任何内容", completionBlock: { [weak self] in
self?.commentInputView.textView.becomeFirstResponder()
})
return
}
guard let once = topic.once ?? AccountModel.getOnce() else {
HUD.showError("无法获取 once,请尝试重新登录", completionBlock: {
presentLoginVC()
})
return
}
commentText = commentInputView.textView.text
commentInputView.textView.text = nil
commentInputView.textView.resignFirstResponder()
HUD.show()
comment(
once: once,
topicID: topicID,
content: commentText, success: { [weak self] in
guard let `self` = self else { return }
HUD.showSuccess("回复成功")
HUD.dismiss()
guard self.page == 1 else { return }
self.fetchTopicDetail(complete: { [weak self] in
self?.tableView.reloadData {}
})
}) { [weak self] error in
guard let `self` = self else { return }
HUD.dismiss()
HUD.showError(error)
self.commentInputView.textView.text = self.commentText
self.commentInputView.textView.becomeFirstResponder()
}
}
// 上传配图请求
private func uploadPictureHandle(_ fileURL: String) {
HUD.show()
uploadPicture(localURL: fileURL, success: { [weak self] url in
log.info(url)
self?.commentInputView.textView.insertText(url + " ")
self?.commentInputView.textView.becomeFirstResponder()
HUD.dismiss()
}) { error in
HUD.dismiss()
HUD.showError(error)
}
}
/// 收藏、取消收藏请求
private func favoriteHandle() {
guard let `topic` = topic,
let token = topic.token else {
HUD.showError("操作失败")
return
}
// 已收藏, 取消收藏
if topic.isFavorite {
unfavoriteTopic(topicID: topicID, token: token, success: { [weak self] in
HUD.showSuccess("取消收藏成功")
self?.topic?.isFavorite = false
}, failure: { error in
HUD.showError(error)
})
return
}
// 没有收藏
favoriteTopic(topicID: topicID, token: token, success: { [weak self] in
HUD.showSuccess("收藏成功")
self?.topic?.isFavorite = true
}) { error in
HUD.showError(error)
}
}
/// 感谢主题请求
private func thankTopicHandle() {
guard let `topic` = topic else {
HUD.showError("操作失败")
return
}
// 已感谢
guard !topic.isThank else {
HUD.showInfo("主题已感谢,无法重复提交")
return
}
guard let token = topic.token else {
HUD.showError("操作失败")
return
}
thankTopic(topicID: topicID, token: token, success: { [weak self] in
HUD.showSuccess("感谢已发送")
self?.topic?.isThank = true
}) { error in
HUD.showError(error)
}
}
/// 忽略主题请求
private func ignoreTopicHandle() {
guard let `topic` = topic,
let once = topic.once ?? AccountModel.getOnce() else {
HUD.showError("操作失败")
return
}
ignoreTopic(topicID: topicID, once: once, success: { [weak self] in
// 需要 pop 掉该控制器? YES
// 需要刷新主题列表? NO
HUD.showSuccess("已成功忽略该主题", completionBlock: { [weak self] in
self?.navigationController?.popViewController(animated: true)
})
}) { error in
HUD.showError(error)
}
}
/// 举报主题, 主要是过审核用
private func reportHandle() {
let alert = UIAlertController(title: "举报", message: "请填写举报原因,举报后将通知管理员", preferredStyle: .alert)
alert.addTextField(configurationHandler: { textView in
textView.placeholder = "举报原因"
})
alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
let sureAction = UIAlertAction(title: "确定举报", style: .destructive, handler: { _ in
guard let text = alert.textFields?.first?.text else { return }
HUD.show()
self.comment(
once: self.topic?.once ?? AccountModel.getOnce() ?? "",
topicID: self.topicID,
content: "@Livid " + text, success: {
HUD.showSuccess("举报成功")
HUD.dismiss()
}) { error in
log.error(error)
}
})
alert.addAction(sureAction)
_ = alert.textFields?.first?.rx
.text
.filterNil()
.takeUntil(alert.rx.deallocated)
.map { $0.trimmed.isNotEmpty }
.bind(to: sureAction.rx.isEnabled)
present(alert, animated: true, completion: nil)
}
/// 报告主题
private func reportTopicHandle() {
let alert = UIAlertController(title: nil, message: "你确认需要报告这个主题?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
let sureAction = UIAlertAction(title: "确定", style: .destructive, handler: { [weak self] _ in
guard let `self` = self else { return }
HUD.show()
guard
let `topic` = self.topic,
let token = topic.reportToken else {
HUD.showError("操作失败")
return
}
self.reportTopic(topicID: self.topicID, token: token, success: {
HUD.showSuccess("举报成功")
HUD.dismiss()
}) { error in
HUD.dismiss()
HUD.showError(error)
}
})
alert.addAction(sureAction)
present(alert, animated: true, completion: nil)
}
}
// MARK: - Action Handle
extension TopicDetailViewController {
private func copyLink() {
UIPasteboard.general.string = API.topicDetail(topicID: topicID, page: page).defaultURLString
HUD.showSuccess("链接已复制")
}
/// 打开系统分享
func systemShare() {
guard let url = API.topicDetail(topicID: topicID, page: page).url else { return }
let controller = UIActivityViewController(
activityItems: [url],
applicationActivities: BrowserActivity.compatibleActivities)
controller.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
currentViewController().present(controller, animated: true, completion: nil)
}
/// 是否只看楼主
func showOnlyFloorHandle() {
isShowOnlyFloor = !isShowOnlyFloor
refreshDataSource()
// tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
}
func refreshDataSource() {
if isShowOnlyFloor {
dataSources = comments.filter { $0.member.username == topic?.member?.username }
if dataSources.count.boolValue.not {
// 视图错误, 延迟 0.3 秒
GCD.delay(0.3, block: {
self.tableView.setContentOffset(CGPoint(x: 0, y: -self.tableView.contentInset.top), animated: true)
})
}
} else {
dataSources = comments
}
tableView.reloadData()
}
/// 从系统 Safari 浏览器中打开
func openSafariHandle() {
guard let url = API.topicDetail(topicID: topicID, page: page).url,
UIApplication.shared.canOpenURL(url) else {
HUD.showError("无法打开网页")
return
}
UIApplication.shared.openURL(url)
}
private func didSelectRowAt(_ indexPath: IndexPath, point: CGPoint) {
// 强制结束 HeaderView 中 WebView 的第一响应者, 不然无法显示 MenuView
if !commentInputView.textView.isFirstResponder {
view.endEditing(true)
}
// 如果当前控制器不是第一响应者不显示 MenuView
// guard isFirstResponder else { return }
if isFirstResponder.not {
commentInputView.textView.resignFirstResponder()
}
guard let cell = tableView.cellForRow(at: indexPath) else { return }
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
let comment = dataSources[indexPath.row]
let menuVC = UIMenuController.shared
var targetRectangle = cell.frame
let pointCell = tableView.convert(point, to: cell)
targetRectangle.origin.y = pointCell.y//targetRectangle.height * 0.4
targetRectangle.size.height = 1
let replyItem = UIMenuItem(title: "回复", action: #selector(replyCommentAction))
let atUserItem = UIMenuItem(title: "@TA", action: #selector(atMemberAction))
let copyItem = UIMenuItem(title: "复制", action: #selector(copyCommentAction))
let fenCiItem = UIMenuItem(title: "分词", action: #selector(fenCiAction))
let thankItem = UIMenuItem(title: "感谢", action: #selector(thankCommentAction))
let viewDialogItem = UIMenuItem(title: "对话", action: #selector(viewDialogAction))
menuVC.setTargetRect(targetRectangle, in: cell)
menuVC.menuItems = [replyItem, copyItem, atUserItem, viewDialogItem]
if comment.content.trimmed.isNotEmpty {
menuVC.menuItems?.insert(fenCiItem, at: 2)
}
// 不显示感谢的情况
// 1. 已经感谢
// 2. 当前题主是登录用户本人 && 点击的回复是题主本人
// 3. 当前点击的回复是登录用户本人
if comment.isThank ||
(topic?.member?.username == comment.member.username &&
AccountModel.current?.username == topic?.member?.username) ||
AccountModel.current?.username == comment.member.username {
} else {
menuVC.menuItems?.insert(thankItem, at: 1)
}
menuVC.setMenuVisible(true, animated: true)
if #available(iOS 10.0, *) {
let generator = UIImpactFeedbackGenerator(style: .light)
generator.prepare()
generator.impactOccurred()
}
}
}
// MARK: - Peek && Pop
extension TopicDetailViewController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
let vc = viewControllerToCommit
let nav = NavigationViewController(rootViewController: vc)
show(nav, sender: self)
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location),
let cell = tableView.cellForRow(at: indexPath) as? TopicCommentCell else { return nil }
let selectComment = dataSources[indexPath.row]
// 和长按头像手势冲突
// let loc = tableView.convert(location, to: cell)
// cell.avatarView.layer.contains(loc)
// x + 50 容错点, y + 15 容错点
// if loc.x < cell.avatarView.right + 50 && loc.y < (cell.avatarView.bottom + 15) {
// let memberPageVC = MemberPageViewController(memberName: selectComment.member.username)
// previewingContext.sourceRect = cell.frame
// return memberPageVC
// }
let dialogs = CommentModel.atUsernameComments(comments: comments, currentComment: selectComment)
guard dialogs.count.boolValue else { return nil }
let viewDialogVC = ViewDialogViewController(comments: dialogs, username: selectComment.member.username)
previewingContext.sourceRect = cell.frame
var contentSize = viewDialogVC.tableView.size
if let lastCellBottom = viewDialogVC.tableView.visibleCells.last?.bottom {
contentSize.height = lastCellBottom + viewDialogVC.tableView.contentInset.top
}
viewDialogVC.preferredContentSize = contentSize
return viewDialogVC
}
override var previewActionItems: [UIPreviewActionItem] {
// Bug - 如果数据没有加载完成, 此时用户上拉, 无法获取到 是否收藏
let favoriteTitle = (topic?.isFavorite ?? false) ? "取消收藏" : "收藏"
let favoriteAction = UIPreviewAction(
title: favoriteTitle,
style: .default) { [weak self] action, vc in
self?.favoriteHandle()
}
let copyAction = UIPreviewAction(
title: "复制链接",
style: .default) { [weak self] action, vc in
self?.copyLink()
}
let shareAction = UIPreviewAction(
title: "分享",
style: .default) { [weak self] action, vc in
self?.systemShare()
}
return [favoriteAction, copyAction, shareAction]
}
}
| 38.029289 | 183 | 0.595225 |
4646a13fddc7e8df75f1e466a2f4fa921b6ba18b | 525 | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "Cache",
products: [
.library(
name: "Cache",
targets: ["Cache"]),
],
dependencies: [],
targets: [
.target(
name: "Cache",
path: "Source/Shared",
exclude: ["Library/ImageWrapper.swift"]), // relative to the target path
.testTarget(
name: "CacheTests",
dependencies: ["Cache"],
path: "Tests"),
]
)
| 21.875 | 84 | 0.493333 |
ded77593dc4701f14d51bc25f7f13bf4beecc331 | 1,193 | //
// MockAppSettings.swift
// DuckDuckGo
//
// Copyright © 2019 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
class MockAppSettings: AppSettings {
var autocomplete: Bool = true
var currentThemeName: ThemeName = ThemeName.dark
var autoClearTiming: AutoClearSettingsModel.Timing = .termination
var autoClearAction: AutoClearSettingsModel.Action = []
var allowUniversalLinks: Bool = true
var longPressPreviews: Bool = true
var sendDoNotSell: Bool = true
var currentFireButtonAnimation: FireButtonAnimationType = FireButtonAnimationType.fireRising
var textSize: Int = 100
}
| 34.085714 | 96 | 0.740989 |
e94febd99471f540a6f8a9e690f56f6260727ff8 | 2,001 | //
// AppDelegate.swift
// FinalProject
//
// Created by PCI0001 on 10/7/20.
// Copyright © 2020 Thinh Nguyen X. All rights reserved.
//
import Foundation
import GoogleSignIn
import UIKit
import Firebase
import FBSDKCoreKit
import SVProgressHUD
enum RootType {
case login
case tabbar
}
typealias HUD = SVProgressHUD
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
static let shared: AppDelegate = {
guard let shared = UIApplication.shared.delegate as? AppDelegate else { fatalError("cant cast UIAPP") }
return shared
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = .white
changeRootViewController(changeRoot: .tabbar)
window?.makeKeyAndVisible()
FirebaseApp.configure()
GIDSignIn.sharedInstance()?.delegate = self
GIDSignIn.sharedInstance()?.clientID = FirebaseApp.app()?.options.clientID
ApplicationDelegate.shared.application( application, didFinishLaunchingWithOptions: launchOptions )
return true
}
func changeRootViewController(changeRoot: RootType) {
switch changeRoot {
case .login:
window?.rootViewController = LoginViewController()
default:
window?.rootViewController = TabBarViewController()
}
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
guard let url = GIDSignIn.sharedInstance()?.handle(url) else { return true }
return url
}
}
extension AppDelegate: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if error == nil {
changeRootViewController(changeRoot: .tabbar)
}
}
}
| 28.585714 | 145 | 0.689655 |
622fec601b421819e2f87b3b3a9e7f65a549c800 | 9,940 | #if canImport(ImageIO)
import ImageIO
public extension CGImageSource {
/// Creates an image source that reads data from the specified data provider.
///
/// - Parameters:
/// - dataProvider: The data provider to read from. For more information
/// on data providers, see CGDataProvider and Quartz 2D Programming Guide.
/// - options: A dictionary that specifies additional creation options.
/// See Image Source Option Dictionary Keys for the keys you can supply.
/// - Returns: An image source. You are responsible for releasing this
/// object using CFRelease.
@inlinable static func create(dataProvider: CGDataProvider, options: [Option: Any] = [:]) -> CGImageSource? {
return CGImageSourceCreateWithDataProvider(dataProvider, options as CFDictionary)
}
/// reates an image source that reads from a Core Foundation data object.
/// - Parameters:
/// - data: The data object to read from. For more information on data
/// objects, see CFData and Data Objects.
/// - options: A dictionary that specifies additional creation options.
/// See Image Source Option Dictionary Keys for the keys you can supply.
/// - Returns: An image source. You are responsible for releasing this
/// object using CFRelease.
@inlinable static func create(data: CFData, options: [Option: Any] = [:]) -> CGImageSource? {
return CGImageSourceCreateWithData(data, options as CFDictionary)
}
/// Creates an image source that reads from a location specified by a URL.
/// - Parameters:
/// - url: The URL to read from.
/// - options: A dictionary that specifies additional creation options.
/// See Image Source Option Dictionary Keys for the keys you can supply.
/// - Returns: An image source. You are responsible for releasing this
/// object using CFRelease.
@inlinable static func create(url: CFURL, options: [Option: Any] = [:]) -> CGImageSource? {
return CGImageSourceCreateWithURL(url, options as CFDictionary)
}
/// Create an incremental image source.
///
/// The function CGImageSourceCreateIncremental creates an empty image
/// source container to which you can add data later by calling the
/// functions CGImageSourceUpdateDataProvider or CGImageSourceUpdateData.
/// You don’t provide data when you call this function.
///
/// An incremental image is an image that is created in chunks, similar to
/// the way large images viewed over the web are loaded piece by piece.
///
/// - Parameter options: A dictionary that specifies additional creation
/// options. See Image Source Option Dictionary Keys for the keys you can
/// supply.
/// - Returns: Returns an image source object. You are responsible for
/// releasing this object using CFRelease.
@inlinable static func createIncremental(options: [Option: Any] = [:]) -> CGImageSource {
return CGImageSourceCreateIncremental(options as CFDictionary)
}
/// Returns the uniform type identifier of the source container.
///
/// The uniform type identifier (UTI) of the source container can be
/// different from the type of the images in the container. For example, the
/// .icns format supports embedded JPEG2000. The type of the source
/// container is "com.apple.icns" but type of the images is JPEG2000.
///
/// See Uniform Type Identifier Concepts for a list of system-declared and
/// third-party UTIs.
@inlinable var type: CFString? {
return CGImageSourceGetType(self)
}
/// Returns the number of images (not including thumbnails) in the image
/// source.
///
/// The number of images. If the image source is a multilayered PSD file,
/// the function returns 1.
///
/// This function does not extract the layers of a PSD file.
@inlinable var count: Int {
return CGImageSourceGetCount(self)
}
/// Returns the properties of the image source.
///
/// These properties apply to the container in general but not necessarily
/// to any individual image contained in the image source.
///
/// - Parameter options: A dictionary you can use to request additional
/// options. See Image Source Option Dictionary Keys for the keys you can
/// supply.
/// - Returns: A dictionary that contains the properties associated with the
/// image source container. See CGImageProperties for a list of properties
/// that can be in the dictionary.
@inlinable func properties(options: [Option: Any] = [:]) -> [CGImage.PropertyName: Any] {
return CGImageSourceCopyProperties(self, options as CFDictionary) as! [CGImage.PropertyName: Any]? ?? [:]
}
/// Returns the properties of the image at a specified location in an image
/// source.
///
/// - Parameters:
/// - index: The index of the image whose properties you want to obtain.
/// The index is zero-based.
/// - options: A dictionary you can use to request additional options. See
/// Image Source Option Dictionary Keys for the keys you can supply.
/// - Returns: A dictionary that contains the properties associated with the
/// image. See CGImageProperties for a list of properties that can be in the
/// dictionary.
@inlinable func properties(at index: Int, options: [Option: Any] = [:]) -> [CGImage.PropertyName: Any] {
return CGImageSourceCopyPropertiesAtIndex(self, index, options as CFDictionary) as! [CGImage.PropertyName: Any]? ?? [:]
}
/// Return the metadata of the image at 'index' in the image source 'isrc'.
/// The index is zero-based. The `options' dictionary may be used to request
/// additional options; see the list of keys above for more information.
/// Please refer to CGImageMetadata.h for usage of metadata.
@inlinable func metadata(at index: Int, options: [Option: Any] = [:]) -> CGImageMetadata? {
return CGImageSourceCopyMetadataAtIndex(self, index, options as CFDictionary)
}
/// Return the image at 'index' in the image source 'isrc'. The index is
/// zero-based. The `options' dictionary may be used to request additional
/// creation options; see the list of keys above for more information.
@inlinable func image(at index: Int, options: [Option: Any] = [:]) -> CGImage? {
return CGImageSourceCreateImageAtIndex(self, index, options as CFDictionary)
}
/// Remove the cached decoded image data for the image at 'index' in the
/// image source 'isrc'. The index is zero-based.
@inlinable func removeCache(at index: Int) {
return CGImageSourceRemoveCacheAtIndex(self, index)
}
/// Return the thumbnail of the image at 'index' in the image source 'isrc'.
/// The index is zero-based. The `options' dictionary may be used to request
/// additional thumbnail creation options; see the list of keys above for
/// more information.
@inlinable func thumbnail(at index: Int, options: [Option: Any]) -> CGImage? {
return CGImageSourceCreateThumbnailAtIndex(self, index, options as CFDictionary)
}
/// Update the incremental image source 'isrc' with new data. The new data
/// must include all the previous data plus any additional new data. The
/// 'final' parameter should be true when the final set of data is provided;
/// false otherwise. */
@inlinable func update(data: CFData, final: Bool = false) {
return CGImageSourceUpdateData(self, data, final)
}
/// Update the incremental image source 'isrc' with a new data provider.
/// The new data provider must provide all the previous data plus any
/// additional new data. The `final' parameter should be true when the final
/// set of data is provided; false otherwise. */
@inlinable func update(dataProvider: CGDataProvider, final: Bool = false) {
return CGImageSourceUpdateDataProvider(self, dataProvider, final)
}
/// Return the overall status of the image source 'isrc'. The status is
/// particularly informative for incremental image sources, but may be used
/// by clients providing non-incremental data as well. */
@inlinable var status: CGImageSourceStatus {
return CGImageSourceGetStatus(self)
}
/// Return the current status of the image at 'index' in the image source
/// 'isrc'. The index is zero-based. The returned status is particularly
/// informative for incremental image sources but may used by clients
/// providing non-incremental data as well. */
@inlinable func status(at index: Int) -> CGImageSourceStatus {
return CGImageSourceGetStatusAtIndex(self, index)
}
/// Return the primary image index for HEIF images. Zero for all other
/// formats.
@available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 5.0, *)
@inlinable var primaryImageIndex: Int {
return CGImageSourceGetPrimaryImageIndex(self)
}
/// Depth data support for JPEG, HEIF, and DNG images.
///
/// The returned CFDictionary contains:
///
/// - the depth data (CFDataRef) - (kCGImageAuxiliaryDataInfoData),
/// - the depth data description (CFDictionary) - (kCGImageAuxiliaryDataInfoDataDescription)
/// - metadata (CGImageMetadataRef) - (kCGImageAuxiliaryDataInfoMetadata)
///
/// CGImageSourceCopyAuxiliaryDataInfoAtIndex returns nil if the image did not contain ‘auxiliaryImageDataType’ data.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
@inlinable func auxiliaryDataInfo(at index: Int, type: CGImage.AuxiliaryDataType) -> [CGImage.AuxiliaryDataInfoKey: Any] {
return CGImageSourceCopyAuxiliaryDataInfoAtIndex(self, index, type.rawValue) as! [CGImage.AuxiliaryDataInfoKey: Any]? ?? [:]
}
}
#endif
| 49.949749 | 132 | 0.685111 |
2151b863b93d2f3abba053a7467d8f978e51cbc7 | 1,447 | //
// Prework_jvaradiUITests.swift
// Prework_jvaradiUITests
//
// Created by JOHN VARADI on 7/18/21.
//
import XCTest
class Prework_jvaradiUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.651163 | 182 | 0.660677 |
5b067106845d5f529e159b3627b159b3dbceda45 | 1,660 | //
// ObservableViewController.swift
// WjnHub
//
// Created by wjn on 2020/6/12.
// Copyright © 2020 wjn. All rights reserved.
//
/**
Observable 可监听的序列
再RXSwift里,Observable存在一些特征序列,利用语法糖简化序列
Single
Completable
Maybe
Driver
Signal
ControlEvent
*/
import UIKit
import RxSwift
import RxCocoa
enum DataError: Error {
case cantParseJSON
}
class ObservableViewController: UIViewController {
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
json.subscribe(onNext: { (json) in
print("请求成功的json数据: \(json)")
}, onError: { (error) in
print("error: \(error)")
}, onCompleted: {
print("请求json完成")
}).disposed(by: disposeBag)
}
typealias JSON = Any
let json: Observable<JSON> = Observable.create { (observer) -> Disposable in
let url = URL(string: "http://www.baidu.com")
let task = URLSession.shared.dataTask(with: url!) { (data, _, error) in
guard error == nil else {
observer.onError(error!)
return
}
guard let data = data,
let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) else {
observer.onError(DataError.cantParseJSON)
return
}
observer.onNext(data)
observer.onCompleted()
}
task.resume()
return Disposables.create {
task.cancel()
}
}
}
| 23.380282 | 115 | 0.538554 |
4831511a4e2b9bbf091f47b6406e51314f9b8896 | 3,149 | //
// HomeViewController.swift
// Example
//
// Created by Jiar on 2018/12/12.
// Copyright © 2018 Jiar. All rights reserved.
//
import UIKit
import SegementSlide
class HomeViewController: BaseSegementSlideDefaultViewController {
private var badges: [Int: BadgeType] = [:]
init() {
super.init(nibName: nil, bundle: nil)
title = "Home"
tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "tab_home")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tab_home_sel")?.withRenderingMode(.alwaysOriginal))
modalPresentationStyle = .fullScreen
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var bouncesType: BouncesType {
return .parent
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
// override func scrollViewDidScroll(_ scrollView: UIScrollView, isParent: Bool) {
// guard !isParent else {
// return
// }
// guard let navigationController = navigationController else {
// return
// }
// let translationY = -scrollView.panGestureRecognizer.translation(in: scrollView).y
// if translationY > 0 {
// guard !navigationController.isNavigationBarHidden else {
// return
// }
// navigationController.setNavigationBarHidden(true, animated: true)
// } else {
// guard !scrollView.isTracking else {
// return
// }
// guard navigationController.isNavigationBarHidden else {
// return
// }
// navigationController.setNavigationBarHidden(false, animated: true)
// }
// }
override var switcherConfig: SegementSlideDefaultSwitcherConfig {
var config = super.switcherConfig
config.type = .tab
return config
}
override var titlesInSwitcher: [String] {
return DataManager.shared.homeLanguageTitles
}
override func showBadgeInSwitcher(at index: Int) -> BadgeType {
if let badge = badges[index] {
return badge
} else {
let badge = BadgeType.random
badges[index] = badge
return badge
}
}
override func segementSlideContentViewController(at index: Int) -> SegementSlideContentScrollViewDelegate? {
let viewController = ContentViewController()
viewController.refreshHandler = { [weak self] in
guard let self = self else {
return
}
self.badges[index] = BadgeType.random
self.reloadBadgeInSwitcher()
}
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
defaultSelectedIndex = 0
reloadData()
}
// override func viewWillDisappear(_ animated: Bool) {
// super.viewWillDisappear(animated)
// navigationController?.setNavigationBarHidden(false, animated: true)
// }
}
| 30.572816 | 202 | 0.6094 |
1a43e47c0343f488c9d64f1994da7e4b11847fdc | 7,361 | //
// DirectoryMonitor.swift
// Vienna
//
// Copyright 2017-2018
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import CoreServices
import Foundation
import os.log
final class DirectoryMonitor: NSObject {
// MARK: Initialization
/// The directories to monitor.
let directories: [URL]
/// Creates a directory monitor for the directories.
///
/// - Parameter directories: The directories to monitor.
@objc
init(directories: [URL]) {
self.directories = directories.filter { $0.isFileURL }
}
// When the instance is ready to be deinitialized, the stream should be
// invalidated properly. This is necessary, because the stream must be
// released manually.
deinit {
stop()
}
// MARK: Monitoring
typealias EventHandler = () -> Void
// The stream will be kept in memory until stop() is called.
private var stream: FSEventStreamRef?
// The eventHandler will be kept in memory until stop() is called.
private var eventHandler: EventHandler?
// The callback will pass along the raw pointer to the direcory monitor
// instance. Recasting this will make the event handler accessible.
private var callback: FSEventStreamCallback = { _, info, eventCount, paths, flags, _ -> Void in
guard let info = info else {
os_log("No pointer to the event handler", log: .discoverer, type: .fault)
return
}
if let paths = Unmanaged<NSArray>.fromOpaque(paths).takeUnretainedValue() as? [String] {
for index in 0..<eventCount {
let path = paths[index]
let flag = flags[index]
if flag & UInt32(kFSEventStreamEventFlagRootChanged) != 0 {
os_log("Root path %@ changed", log: .discoverer, type: .debug, path)
}
if flag & UInt32(kFSEventStreamEventFlagItemCreated) != 0 {
os_log("%@ added", log: .discoverer, type: .debug, path)
}
if flag & UInt32(kFSEventStreamEventFlagItemRenamed) != 0 {
os_log("%@ renamed or moved", log: .discoverer, type: .debug, path)
}
if flag & UInt32(kFSEventStreamEventFlagItemRemoved) != 0 {
os_log("%@ removed", log: .discoverer, type: .debug, path)
}
if flag & UInt32(kFSEventStreamEventFlagRootChanged) == 0,
flag & UInt32(kFSEventStreamEventFlagItemCreated) == 0,
flag & UInt32(kFSEventStreamEventFlagItemRenamed) == 0,
flag & UInt32(kFSEventStreamEventFlagItemRemoved) == 0 {
os_log("Unhandled file-system event: %d", log: .discoverer, type: .debug, flag)
}
}
}
os_log("Calling the event handler", log: .discoverer, type: .debug)
let monitor = Unmanaged<DirectoryMonitor>.fromOpaque(info).takeUnretainedValue()
monitor.eventHandler?()
}
/// Starts or resumes the monitor, invoking the event-handler block if the
/// directory contents change.
///
/// - Parameter eventHandler: The handler to call when an event occurs.
/// - Throws: An error of type `DirectoryMonitorError`.
@objc
func start(eventHandler: @escaping EventHandler) throws {
if stream != nil {
stop()
}
if directories.isEmpty {
return
}
// The callback does not allow capturing external properties. Instead,
// the event handler is passed as a stream context, allowing the handler
// to be called from within the closure.
let pointer = Unmanaged.passUnretained(self).toOpaque()
var context = FSEventStreamContext(version: 0,
info: pointer,
retain: nil,
release: nil,
copyDescription: nil)
// The directory monitor will listen to events that happen in both
// directions of each directory's hierarchy and will coalesce events
// that happen within 2 seconds of each other.
let paths = directories.map { $0.path as CFString } as CFArray
let flags = UInt32(kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagUseCFTypes)
guard let stream = FSEventStreamCreate(kCFAllocatorDefault,
callback,
&context,
paths,
FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
2,
flags) else {
throw DirectoryMonitorError.streamCouldNotBeCreated
}
self.stream = stream
self.eventHandler = eventHandler
// FSEvents has a two-pronged approach: schedule a stream (and
// record the changes) and start sending events. This granualarity
// is not desirable for the directory monitor, so they are combined.
FSEventStreamScheduleWithRunLoop(stream,
RunLoop.current.getCFRunLoop(),
CFRunLoopMode.defaultMode.rawValue)
if !FSEventStreamStart(stream) {
// This closure is executed if start() fails. Accordingly, the
// stream must be unscheduled.
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
throw DirectoryMonitorError.streamCouldNotBeStarted
}
}
/// Stops the monitor, preventing any further invocation of the event-
/// handler block.
func stop() {
// Unschedule the stream from its run loop and remove the (only)
// reference count before unsetting the pointer.
if let stream = stream {
FSEventStreamStop(stream)
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
self.stream = nil
}
eventHandler = nil
}
}
// MARK: - Error handling
enum DirectoryMonitorError: LocalizedError {
case streamCouldNotBeCreated
case streamCouldNotBeStarted
var errorDescription: String? {
switch self {
case .streamCouldNotBeCreated:
return "The file-system event stream could not be created"
case .streamCouldNotBeStarted:
return "The file-system event stream could not be started"
}
}
}
// MARK: - Public extensions
extension OSLog {
static let monitor = OSLog(subsystem: "--", category: "DirectoryMonitor")
}
| 37.176768 | 135 | 0.596251 |
bbcdb523ce9905171e13ddcd797e69e979b2d708 | 665 | //
// LocalizedCategory+RealmLoader.swift
// SuperLachaiseRealmLoader
//
// Created by Maxime Le Moine on 21/05/2017.
//
//
import Foundation
import RealmSwift
import SwiftyJSON
extension LocalizedCategory {
convenience init(json: JSON, category: Category, realm: Realm) throws {
self.init()
try json["language"].assertType(type: .string)
try json["label"].assertType(type: .string)
self.language = json["language"].stringValue
self.category = category
self.id = "\(language)|\(category.id)"
self.label = json["label"].stringValue
realm.add(self)
}
}
| 22.166667 | 75 | 0.621053 |
dd3966fd266b867c554000c73f2e17ed982fae7f | 286 | //
// DNSRecord.swift
// MixedNetworkSys
//
// Created by jimmy on 08/02/2019.
//
import Foundation
public typealias TTL = TimeInterval
public struct DNSRecord {
public let ip: IP
public let ttl: TTL
public init(ip: IP, ttl: TTL) {
self.ip = ip
self.ttl = ttl
}
}
| 14.3 | 35 | 0.65035 |
399506dec384a09421b753622b065a3c7413cba7 | 2,666 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
A view showing a list of landmarks.
*/
import SwiftUI
struct LandmarkList: View {
@EnvironmentObject var modelData: ModelData
@State private var showFavoritesOnly = false
@State private var filter = FilterCategory.all
@State private var selectedLandmark: Landmark?
enum FilterCategory: String, CaseIterable, Identifiable {
case all = "All"
case lakes = "Lakes"
case rivers = "Rivers"
case mountains = "Mountains"
var id: FilterCategory { self }
}
var filteredLandmarks: [Landmark] {
modelData.landmarks.filter { landmark in
(!showFavoritesOnly || landmark.isFavorite)
}
}
var title: String {
let title = filter == .all ? "Landmarks" : filter.rawValue
return showFavoritesOnly ? "Favorite \(title)" : title
}
var index: Int? {
modelData.landmarks.firstIndex(where: { $0.id == selectedLandmark?.id })
}
var body: some View {
NavigationView {
List(selection: $selectedLandmark) {
Toggle(isOn: $showFavoritesOnly) {
Text("Favorites only")
}
ForEach(filteredLandmarks) { landmark in
NavigationLink {
LandmarkDetail(landmark: landmark)
} label: {
LandmarkRow(landmark: landmark)
}
.tag(landmark)
}
}
.navigationTitle(title)
.frame(minWidth: 300)
.toolbar {
ToolbarItem {
Menu {
Picker("Category", selection: $filter) {
ForEach(FilterCategory.allCases) { category in
Text(category.rawValue).tag(category)
}
}
.pickerStyle(.inline)
Toggle(isOn: $showFavoritesOnly) {
Label("Favorites only", systemImage: "star.fill")
}
} label: {
Label("Filter", systemImage: "slider.horizontal.3")
}
}
}
Text("Select a Landmark")
}
.focusedValue(\.selectedLandmark, $modelData.landmarks[index ?? 0])
}
}
struct LandmarkList_Previews: PreviewProvider {
static var previews: some View {
LandmarkList()
.environmentObject(ModelData())
}
}
| 29.955056 | 80 | 0.504126 |
723955ebcb603f2533ab2994cac0f96491727c5c | 2,233 | import Cocoa
class CommentOutlineRowView: NSTableRowView {
var level: Int
var isExpandable: Bool
var indentationPerLevel: CGFloat
init(withLevel level: Int, isExpandable: Bool, indentationPerLevel: CGFloat) {
self.level = level
self.isExpandable = isExpandable
self.indentationPerLevel = indentationPerLevel
super.init(frame: .zero)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
var isMouseHovering = false {
didSet {
setNeedsDisplay(
NSRect(
x: 0, y: 0, width: CGFloat(level + 1) * indentationPerLevel,
height: bounds.height))
}
}
lazy var trackingArea = makeTrackingArea()
override func updateTrackingAreas() {
removeTrackingArea(trackingArea)
trackingArea = makeTrackingArea()
let mouseLocation = convert(window!.mouseLocationOutsideOfEventStream, from: nil)
if bounds.contains(mouseLocation) {
mouseEntered(with: NSEvent())
} else {
mouseExited(with: NSEvent())
}
addTrackingArea(trackingArea)
super.updateTrackingAreas()
}
func makeTrackingArea() -> NSTrackingArea {
NSTrackingArea(
rect: bounds, options: [.mouseEnteredAndExited, .activeInKeyWindow], owner: self,
userInfo: nil)
}
override func mouseEntered(with event: NSEvent) {
super.mouseEntered(with: event)
isMouseHovering = true
}
override func mouseExited(with event: NSEvent) {
super.mouseExited(with: event)
isMouseHovering = false
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if isMouseHovering {
NSColor.systemGray.setFill()
let minX: CGFloat = CGFloat(level + 1) * indentationPerLevel
let minY: CGFloat = isExpandable ? 22 : 2
let height = frame.height - (isExpandable ? 24 : 4)
let barRect = NSRect(x: minX, y: minY, width: 4, height: height)
let barPath = NSBezierPath(roundedRect: barRect, xRadius: 2, yRadius: 2)
barPath.fill()
}
}
}
| 31.9 | 93 | 0.615316 |
d9ccea36d39d96fd18bc0267bc5ed0a6148061d5 | 473 | //
// Movie+CoreDataProperties.swift
// Project12
//
// Created by Paul Hudson on 17/02/2020.
// Copyright © 2020 Paul Hudson. All rights reserved.
//
//
import Foundation
import CoreData
extension Movie {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Movie> {
return NSFetchRequest<Movie>(entityName: "Movie")
}
@NSManaged public var title: String
@NSManaged public var director: String
@NSManaged public var year: Int16
}
| 21.5 | 72 | 0.699789 |
14b0513be9919e69dc0df0c56e3d8606cb7641cd | 13,274 | //
// Place+Basic.swift
// Modular
//
// Created by Ondrej Rafaj on 02/12/2017.
//
import Foundation
#if os(iOS) || os(tvOS)
@_exported import UIKit
#elseif os(OSX)
@_exported import Cocoa
#endif
@_exported import SnapKit
extension Place where T: ViewAlias {
/**
Place view **on** a superview and **expand** to cover all space
- parameters:
- view: target view
- top: optional, default 0
- left: optional, default 0
- right: optional, default 0
- bottom: optional, default 0
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func on(andFill view: ViewAlias, top: CGFloat? = 0, left: CGFloat? = 0, right: CGFloat? = 0, bottom: CGFloat? = 0) -> Make<T> {
view.addSubview(element)
element.snp.makeConstraints { (make) in
make.set(top: top)
make.set(left: left)
make.set(right: right)
make.set(bottom: bottom)
}
return Make(element)
}
/**
Place view **on** a superview
- parameters:
- view: target view
- width: optional, default nil
- height: optional, default nil
- top: optional, default nil
- left: optional, default nil
- right: optional, default nil
- bottom: optional, default nil
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func on(_ view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat? = nil, left: CGFloat? = nil, right: CGFloat? = nil, bottom: CGFloat? = nil) -> Make<T> {
view.addSubview(element)
element.snp.makeConstraints { (make) in
make.set(top: top)
make.set(left: left)
make.set(right: right)
make.set(bottom: bottom)
make.set(width: width, height: height)
if bottom != nil {
make.bottom.equalToSuperview().offset(bottom!)
}
}
return Make(element)
}
/**
Place view **above** another view
- parameters:
- view: target view
- width: optional, default nil
- height: optional, default nil
- top: optional, default nil
- left: optional, default nil
- right: optional, default nil
- bottom: default `DefaultValues.verticalSpacingMargin` to the view below
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func above(_ view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat? = nil, left: CGFloat? = nil, right: CGFloat? = nil, bottom: CGFloat = DefaultValues.verticalSpacingMargin) -> Make<T> {
guard let superview = view.superview else {
fatalError("Other view doesn't have a superview")
}
superview.addSubview(element)
element.snp.makeConstraints { (make) in
make.set(top: top)
make.set(left: left)
make.set(right: right)
make.bottom.equalTo(view.snp.top).offset(bottom)
make.set(width: width, height: height)
}
return Make(element)
}
/**
Place view **under** another view
- parameters:
- view: target view
- width: optional, default nil
- height: optional, default nil
- top: default `DefaultValues.verticalSpacingMargin` to the view above
- left: optional, default nil
- right: optional, default nil
- bottom: optional, default nil
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func below(_ view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat = DefaultValues.verticalSpacingMargin, left: CGFloat? = nil, right: CGFloat? = nil, bottom: CGFloat? = nil) -> Make<T> {
guard let superview = view.superview else {
fatalError("Other view doesn't have a superview")
}
superview.addSubview(element)
element.snp.makeConstraints { (make) in
make.top.equalTo(view.snp.bottom).offset(top)
make.set(left: left)
make.set(right: right)
make.set(bottom: bottom)
make.set(width: width, height: height)
}
return Make(element)
}
/**
Place view **under** the lowest view of a given array
- parameters:
- views: target views
- width: optional, default nil
- height: optional, default nil
- top: default `DefaultValues.verticalSpacingMargin` to the views above
- left: optional, default nil
- right: optional, default nil
- bottom: optional, default nil
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func below(_ views: [ViewAlias], width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat = DefaultValues.verticalSpacingMargin, left: CGFloat? = nil, right: CGFloat? = nil, bottom: CGFloat? = nil) -> Make<T> {
guard let superview = views.first?.superview else {
fatalError("One of the wiews doesn't have a superview")
}
superview.addSubview(element)
element.snp.makeConstraints { (make) in
for view in views {
make.top.greaterThanOrEqualTo(view.snp.bottom).offset(top)
}
make.set(left: left)
make.set(right: right)
make.set(bottom: bottom)
make.set(width: width, height: height)
}
return Make(element)
}
/**
Place view **next** to another view from right hand side
- parameters:
- view: target view
- width: optional, default nil
- height: optional, default nil
- top: optional, default nil
- left: default `DefaultValues.verticalSpacingMargin` to the original view on the left
- right: optional, default nil
- bottom: optional, default nil
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func next(to view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat? = nil, left: CGFloat = DefaultValues.horizontalSpacingMargin, right: CGFloat? = nil, bottom: CGFloat? = nil) -> Make<T> {
guard let superview = view.superview else {
fatalError("Other view doesn't have a superview")
}
superview.addSubview(element)
element.snp.makeConstraints { (make) in
make.set(top: top)
make.left.equalTo(view.snp.right).offset(left)
make.set(right: right)
make.set(bottom: bottom)
make.set(width: width, height: height)
}
return Make(element)
}
/**
Place view **in front** of another view from left hand side
- parameters:
- view: target view
- width: optional, default nil
- height: optional, default nil
- top: optional, default nil
- left: optional, default nil
- right: default `DefaultValues.verticalSpacingMargin` to the original view on the right
- bottom: optional, default nil
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func before(_ view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat? = nil, left: CGFloat? = nil, right: CGFloat = DefaultValues.horizontalSpacingMargin, bottom: CGFloat? = nil) -> Make<T> {
guard let superview = view.superview else {
fatalError("Other view doesn't have a superview")
}
superview.addSubview(element)
element.snp.makeConstraints { (make) in
make.set(top: top)
make.set(left: left)
make.right.equalTo(view.snp.left).offset(right)
make.set(bottom: bottom)
make.set(width: width, height: height)
}
return Make(element)
}
/**
Place view **between** two other views
- parameters:
- view1: target view on the left
- view2: target view on the right
- width: optional, default nil
- height: optional, default nil
- top: optional, default nil
- left: default `DefaultValues.verticalSpacingMargin` to the view on the left
- right: default `DefaultValues.verticalSpacingMargin` to the view on the right
- bottom: optional, default nil
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func between(_ view1: ViewAlias, and view2: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat? = nil, left: CGFloat = DefaultValues.horizontalSpacingMargin, right: CGFloat = -DefaultValues.horizontalSpacingMargin, bottom: CGFloat? = nil) -> Make<T> {
guard let superview = view1.superview, let _ = view2.superview else {
fatalError("One of the other views doesn't have a superview")
}
superview.addSubview(element)
element.snp.makeConstraints { (make) in
make.set(top: top)
make.left.equalTo(view1.snp.right).offset(left)
make.right.equalTo(view2.snp.left).offset(right)
make.set(bottom: bottom)
make.set(width: width, height: height)
}
return Make(element)
}
/**
Place view at the **bottom** of another view
- parameters:
- bottom: target view
- width: optional, default nil
- height: optional, default nil
- top: optional, default nil
- left: optional, default nil
- right: optional, default nil
- bottom: default 0
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func on(bottom view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat? = nil, left: CGFloat? = nil, right: CGFloat? = nil, bottom: CGFloat = 0) -> Make<T> {
view.addSubview(element)
element.snp.makeConstraints { (make) in
make.set(top: top)
make.set(left: left)
make.set(right: right)
make.bottom.equalToSuperview().offset(bottom)
make.set(width: width, height: height)
}
return Make(element)
}
@available(*, unavailable, message: "This method has been replaced", renamed: "on(bottom:width:height:top:left:right:bottom:)")
public func onBottom(of view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, bottom: CGFloat = 0) -> Make<T> {
fatalError()
}
/**
Place view to the **top left** corner of another view
- parameters:
- topLeft: target view
- width: optional, default nil
- height: optional, default nil
- top: default 0
- left: default 0
- right: optional, default nil
- bottom: optional, default nil
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func on(topLeft view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat = 0, left: CGFloat = 0, right: CGFloat? = nil, bottom: CGFloat? = nil) -> Make<T> {
view.addSubview(element)
element.snp.makeConstraints { (make) in
make.set(top: top)
make.set(left: left)
make.set(right: right)
make.set(bottom: bottom)
make.set(width: width, height: height)
}
return Make(element)
}
@available(*, unavailable, message: "This method has been replaced", renamed: "on(topLeft:width:height:top:left:right:bottom:)")
public func onTopLeft(of view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat? = nil, left: CGFloat? = nil) -> Make<T> {
fatalError()
}
/**
Place view to the **top right** corner of another view
- parameters:
- topRight: target view
- width: optional, default nil
- height: optional, default nil
- top: default 0
- left: optional, default NIL
- right: default 0
- bottom: optional, default nil
- returns: `Make` instance to allow further modifications
*/
@discardableResult public func on(topRight view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat? = 0, left: CGFloat? = nil, right: CGFloat? = 0, bottom: CGFloat? = nil) -> Make<T> {
view.addSubview(element)
element.snp.makeConstraints { (make) in
make.set(top: top)
make.set(left: left)
make.set(right: right)
make.set(bottom: bottom)
make.set(width: width, height: height)
}
return Make(element)
}
@available(*, unavailable, message: "This method has been replaced", renamed: "on(topRight:width:height:top:left:right:bottom:)")
public func onTopRight(of view: ViewAlias, width: CGFloat? = nil, height: CGFloat? = nil, top: CGFloat? = nil, right: CGFloat? = nil) -> Make<T> {
fatalError()
}
}
| 38.699708 | 301 | 0.598312 |
507ce870a9f601fe04aa8e3872a05c50decfb0f7 | 1,272 | //
// ScoreKeeper.swift
// NobleBout
//
// Created by Lee Davis on 3/7/21.
// Copyright © 2021 EightFoldGames. All rights reserved.
//
protocol ScoreKeeperDelegate {
func bout(winner: RuleBook.Winner)
func matchPoint()
func updateRoundScore(p1: Int, p2: Int)
func reset()
}
protocol ScoreKeeperUIDelegate {
func bout(winner: RuleBook.Winner)
func updateRoundScore(p1: Int, p2: Int)
}
final class ScoreKeeper {
private var p1Score: Int = 0
private var p2Score: Int = 0
var delegate: ScoreKeeperDelegate?
var delegateUI: ScoreKeeperUIDelegate?
func bout(winner: RuleBook.Winner) {
delegateUI?.bout(winner: winner)
}
func awardPoint(to winner: RuleBook.Winner) {
switch winner {
case .pOne:
p1Score += 1
case .pTwo:
p2Score += 1
case .draw:
break
}
if (p1Score.isMatchPoint() == true) || (p2Score.isMatchPoint() == true) {
reset()
delegate?.reset()
delegate?.matchPoint()
}
else {
delegateUI?.updateRoundScore(p1: p1Score, p2: p2Score)
}
}
private func reset() {
p1Score = 0
p2Score = 0
}
}
| 22.315789 | 81 | 0.569969 |
1c61a41429fac80574875341ab7a54c77e82ed07 | 2,565 | //
// ProgressBarView.swift
// ios-app-bootstrap
//
// Created by xdf on 3/24/16.
// Copyright © 2016 open source. All rights reserved.
//
import UIKit
import Logger_swift
class ProgressBarView: UIView {
let logger = Logger()
var currentProgress: CGFloat = 0
var lastProgress: CGFloat = 0
var timer: Timer!
var isReverse = false
var reverseCache = false
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
required init(coder: NSCoder) {
super.init(coder: coder)!
initView()
}
func initView() {
backgroundColor = UIColor.clear
}
@objc func update() {
logger.debug("currentProgress:", currentProgress)
if (currentProgress >= 360 || currentProgress <= -360) {
reset()
}
if (currentProgress == 0) {
reverseCache = isReverse
}
if (isReverse) {
currentProgress -= 1
} else {
currentProgress += 1
}
setNeedsDisplay()
}
func run() {
logger.info("process bar run")
startTimer()
}
func pause() {
logger.info("process bar pause")
stopTimer()
}
func reset() {
currentProgress = 0
logger.info("process bar reset")
}
func reverse() {
logger.info("process bar reverse")
isReverse = !isReverse
}
func startTimer() {
if ((timer) != nil) {
return
}
timer = Timer.scheduledTimer(timeInterval: 0.016, target: self, selector: #selector(ProgressBarView.update), userInfo: nil, repeats: true)
}
func stopTimer() {
if ((timer == nil)) {
return
}
timer.invalidate()
timer = nil
}
override func draw(_ rect: CGRect) {
logger.info("drawRect")
let lineWidth: CGFloat = 1
let context = UIGraphicsGetCurrentContext()
context?.clear(rect)
context?.saveGState()
context?.beginPath()
context?.setStrokeColor(UIColor.blue.cgColor.components!)
context?.addArc(center: CGPoint(x: self.frame.width / 2 + lineWidth, y: self.frame.height / 2 + lineWidth), radius: self.frame.width / 2 - lineWidth * 2, startAngle: 0, endAngle: CGFloat(currentProgress / 180 * CGFloat(M_PI)), clockwise: reverseCache)
context?.setLineWidth(lineWidth)
context?.strokePath()
context?.restoreGState()
}
}
| 24.663462 | 259 | 0.557895 |
e6c0ed5fd61cb94d5eb33969a0bde07db5883bb3 | 37,322 | import Foundation
import CocoaLumberjackSwift
// Sync keys
let WMFReadingListSyncStateKey = "WMFReadingListsSyncState"
private let WMFReadingListSyncRemotelyEnabledKey = "WMFReadingListSyncRemotelyEnabled"
let WMFReadingListUpdateKey = "WMFReadingListUpdateKey"
// Default list key
private let WMFReadingListDefaultListEnabledKey = "WMFReadingListDefaultListEnabled"
// Batch size keys
let WMFReadingListBatchSizePerRequestLimit = 500
let WMFReadingListCoreDataBatchSize = 500
// Reading lists config keys
let WMFReadingListsConfigMaxEntriesPerList = "WMFReadingListsConfigMaxEntriesPerList"
let WMFReadingListsConfigMaxListsPerUser = "WMFReadingListsConfigMaxListsPerUser"
struct ReadingListSyncState: OptionSet {
let rawValue: Int64
static let needsRemoteEnable = ReadingListSyncState(rawValue: 1 << 0)
static let needsSync = ReadingListSyncState(rawValue: 1 << 1)
static let needsUpdate = ReadingListSyncState(rawValue: 1 << 2)
static let needsRemoteDisable = ReadingListSyncState(rawValue: 1 << 3)
static let needsLocalReset = ReadingListSyncState(rawValue: 1 << 4) // mark all as unsynced, remove remote IDs
static let needsLocalArticleClear = ReadingListSyncState(rawValue: 1 << 5) // remove all saved articles
static let needsLocalListClear = ReadingListSyncState(rawValue: 1 << 6) // remove all lists
static let needsRandomLists = ReadingListSyncState(rawValue: 1 << 7) // for debugging, populate random lists
static let needsRandomEntries = ReadingListSyncState(rawValue: 1 << 8) // for debugging, populate with random entries in any language
static let needsRandomEnEntries = ReadingListSyncState(rawValue: 1 << 9) // for debugging, populate with random english wikipedia entries
static let needsEnable: ReadingListSyncState = [.needsRemoteEnable, .needsSync]
static let needsLocalClear: ReadingListSyncState = [.needsLocalArticleClear, .needsLocalListClear]
static let needsClearAndEnable: ReadingListSyncState = [.needsLocalClear, .needsRemoteEnable, .needsSync]
static let needsDisable: ReadingListSyncState = [.needsRemoteDisable, .needsLocalReset]
}
public enum ReadingListError: Error, Equatable {
case listExistsWithTheSameName
case unableToCreateList
case generic
case unableToDeleteList
case unableToUpdateList
case unableToAddEntry
case unableToRemoveEntry
case entryLimitReached(name: String, count: Int, limit: Int)
case listWithProvidedNameNotFound(name: String)
case listLimitReached(limit: Int)
case listEntryLimitsReached(name: String, count: Int, listLimit: Int, entryLimit: Int)
public var localizedDescription: String {
switch self {
case .generic:
return WMFLocalizedString("reading-list-generic-error", value: "An unexpected error occurred while updating your reading lists.", comment: "An unexpected error occurred while updating your reading lists.")
case .listExistsWithTheSameName:
return WMFLocalizedString("reading-list-exists-with-same-name", value: "Reading list name already in use", comment: "Informs the user that a reading list exists with the same name.")
case .listWithProvidedNameNotFound(let name):
let format = WMFLocalizedString("reading-list-with-provided-name-not-found", value: "A reading list with the name “%1$@” was not found. Please make sure you have the correct name.", comment: "Informs the user that a reading list with the name they provided was not found. %1$@ will be replaced with the name of the reading list which could not be found")
return String.localizedStringWithFormat(format, name)
case .unableToCreateList:
return WMFLocalizedString("reading-list-unable-to-create", value: "An unexpected error occurred while creating your reading list. Please try again later.", comment: "Informs the user that an error occurred while creating their reading list.")
case .unableToDeleteList:
return WMFLocalizedString("reading-list-unable-to-delete", value: "An unexpected error occurred while deleting your reading list. Please try again later.", comment: "Informs the user that an error occurred while deleting their reading list.")
case .unableToUpdateList:
return WMFLocalizedString("reading-list-unable-to-update", value: "An unexpected error occurred while updating your reading list. Please try again later.", comment: "Informs the user that an error occurred while updating their reading list.")
case .unableToAddEntry:
return WMFLocalizedString("reading-list-unable-to-add-entry", value: "An unexpected error occurred while adding an entry to your reading list. Please try again later.", comment: "Informs the user that an error occurred while adding an entry to their reading list.")
case .entryLimitReached(let name, let count, let limit):
return String.localizedStringWithFormat(CommonStrings.readingListsEntryLimitReachedFormat, count, limit, name)
case .unableToRemoveEntry:
return WMFLocalizedString("reading-list-unable-to-remove-entry", value: "An unexpected error occurred while removing an entry from your reading list. Please try again later.", comment: "Informs the user that an error occurred while removing an entry from their reading list.")
case .listLimitReached(let limit):
return String.localizedStringWithFormat(CommonStrings.readingListsListLimitReachedFormat, limit)
case .listEntryLimitsReached(let name, let count, let listLimit, let entryLimit):
let entryLimitReached = String.localizedStringWithFormat(CommonStrings.readingListsEntryLimitReachedFormat, count, entryLimit, name)
let listLimitReached = String.localizedStringWithFormat(CommonStrings.readingListsListLimitReachedFormat, listLimit)
return "\(entryLimitReached)\n\n\(listLimitReached)"
}
}
public static func ==(lhs: ReadingListError, rhs: ReadingListError) -> Bool {
return lhs.localizedDescription == rhs.localizedDescription //shrug
}
}
public typealias ReadingListsController = WMFReadingListsController
@objc public class WMFReadingListsController: NSObject {
@objc public static let readingListsServerDidConfirmSyncWasEnabledForAccountNotification = NSNotification.Name("WMFReadingListsServerDidConfirmSyncWasEnabledForAccount")
@objc public static let readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncEnabledKey = NSNotification.Name("wasSyncEnabledForAccount")
@objc public static let readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncEnabledOnDeviceKey = NSNotification.Name("wasSyncEnabledOnDevice")
@objc public static let readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncDisabledOnDeviceKey = NSNotification.Name("wasSyncDisabledOnDevice")
@objc public static let syncDidStartNotification = NSNotification.Name(rawValue: "WMFSyncDidStartNotification")
@objc public static let readingListsWereSplitNotification = NSNotification.Name("WMFReadingListsWereSplit")
@objc public static let readingListsWereSplitNotificationEntryLimitKey = NSNotification.Name("WMFReadingListsWereSplitNotificationEntryLimitKey")
@objc public static let syncDidFinishNotification = NSNotification.Name(rawValue: "WMFSyncFinishedNotification")
@objc public static let syncDidFinishErrorKey = NSNotification.Name(rawValue: "error")
@objc public static let syncDidFinishSyncedReadingListsCountKey = NSNotification.Name(rawValue: "syncedReadingLists")
@objc public static let syncDidFinishSyncedReadingListEntriesCountKey = NSNotification.Name(rawValue: "syncedReadingListEntries")
@objc public static let userDidSaveOrUnsaveArticleNotification = NSNotification.Name(rawValue: "WMFUserDidSaveOrUnsaveArticleNotification")
internal weak var dataStore: MWKDataStore!
internal let apiController: ReadingListsAPIController
private let operationQueue = OperationQueue()
private var observedOperations: [Operation: NSKeyValueObservation] = [:]
private var isSyncing = false {
didSet {
guard oldValue != isSyncing, isSyncing else {
return
}
DispatchQueue.main.async {
NotificationCenter.default.post(name: ReadingListsController.syncDidStartNotification, object: nil)
}
}
}
@objc init(dataStore: MWKDataStore) {
self.dataStore = dataStore
self.apiController = ReadingListsAPIController(session: dataStore.session, configuration: dataStore.configuration)
super.init()
operationQueue.maxConcurrentOperationCount = 1
}
private func addOperation(_ operation: ReadingListsOperation) {
observedOperations[operation] = operation.observe(\.state, changeHandler: { (operation, change) in
if operation.isFinished {
self.observedOperations.removeValue(forKey: operation)?.invalidate()
DispatchQueue.main.async {
var userInfo: [Notification.Name: Any] = [:]
if let error = operation.error {
userInfo[ReadingListsController.syncDidFinishErrorKey] = error
}
if let syncOperation = operation as? ReadingListsSyncOperation {
userInfo[ReadingListsController.syncDidFinishSyncedReadingListsCountKey] = syncOperation.syncedReadingListsCount
userInfo[ReadingListsController.syncDidFinishSyncedReadingListEntriesCountKey] = syncOperation.syncedReadingListEntriesCount
}
NotificationCenter.default.post(name: ReadingListsController.syncDidFinishNotification, object: nil, userInfo: userInfo)
self.isSyncing = false
}
} else if operation.isExecuting {
self.isSyncing = true
}
})
operationQueue.addOperation(operation)
}
// User-facing actions. Everything is performed on the main context
public func createReadingList(named name: String, description: String? = nil, with articles: [WMFArticle] = []) throws -> ReadingList {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
let list = try createReadingList(named: name, description: description, with: articles, in: moc)
if moc.hasChanges {
try moc.save()
}
let listLimit = moc.wmf_readingListsConfigMaxListsPerUser
let readingListsCount = try moc.allReadingListsCount()
guard readingListsCount + 1 <= listLimit else {
throw ReadingListError.listLimitReached(limit: listLimit)
}
try throwLimitErrorIfNecessary(for: nil, articles: [], in: moc)
sync()
return list
}
private func throwLimitErrorIfNecessary(for readingList: ReadingList?, articles: [WMFArticle], in moc: NSManagedObjectContext) throws {
let listLimit = moc.wmf_readingListsConfigMaxListsPerUser
let entryLimit = moc.wmf_readingListsConfigMaxEntriesPerList.intValue
let readingListsCount = try moc.allReadingListsCount()
let countOfEntries = Int(readingList?.countOfEntries ?? 0)
let willExceedListLimit = readingListsCount + 1 > listLimit
let didExceedListLimit = readingListsCount > listLimit
let willExceedEntryLimit = countOfEntries + articles.count > entryLimit
if let name = readingList?.name {
if didExceedListLimit && willExceedEntryLimit {
throw ReadingListError.listEntryLimitsReached(name: name, count: articles.count, listLimit: listLimit, entryLimit: entryLimit)
} else if willExceedEntryLimit {
throw ReadingListError.entryLimitReached(name: name, count: articles.count, limit: entryLimit)
}
} else if willExceedListLimit {
throw ReadingListError.listLimitReached(limit: listLimit)
}
}
public func createReadingList(named name: String, description: String? = nil, with articles: [WMFArticle] = [], in moc: NSManagedObjectContext) throws -> ReadingList {
let listExistsWithTheSameName = try listExists(with: name, in: moc)
guard !listExistsWithTheSameName else {
throw ReadingListError.listExistsWithTheSameName
}
guard let list = moc.wmf_create(entityNamed: "ReadingList", withKeysAndValues: ["canonicalName": name, "readingListDescription": description]) as? ReadingList else {
throw ReadingListError.unableToCreateList
}
list.createdDate = NSDate()
list.updatedDate = list.createdDate
list.isUpdatedLocally = true
try add(articles: articles, to: list, in: moc)
return list
}
func listExists(with name: String, in moc: NSManagedObjectContext) throws -> Bool {
let name = name.precomposedStringWithCanonicalMapping
let existingOrDefaultListRequest: NSFetchRequest<ReadingList> = ReadingList.fetchRequest()
existingOrDefaultListRequest.predicate = NSPredicate(format: "(canonicalName MATCHES %@ OR isDefault == YES) AND isDeletedLocally == NO", name)
existingOrDefaultListRequest.fetchLimit = 2
let lists = try moc.fetch(existingOrDefaultListRequest)
return lists.first(where: { $0.name == name }) != nil
}
public func updateReadingList(_ readingList: ReadingList, with newName: String?, newDescription: String?) {
assert(Thread.isMainThread)
guard !readingList.isDefault else {
assertionFailure("Default reading list cannot be updated")
return
}
let moc = dataStore.viewContext
if let newName = newName, !newName.isEmpty {
readingList.name = newName
}
readingList.readingListDescription = newDescription
readingList.isUpdatedLocally = true
if moc.hasChanges {
do {
try moc.save()
} catch let error {
DDLogError("Error updating name or description for reading list: \(error)")
}
}
sync()
}
/// Marks that reading lists were deleted locally and updates associated objects. Doesn't delete them from the NSManagedObjectContext - that should happen only with confirmation from the server that they were deleted.
///
/// - Parameters:
/// - readingLists: the reading lists to delete
func markLocalDeletion(for readingLists: [ReadingList]) throws {
for readingList in readingLists {
readingList.isDeletedLocally = true
readingList.isUpdatedLocally = true
try markLocalDeletion(for: Array(readingList.entries ?? []))
}
}
/// Marks that reading list entries were deleted locally and updates associated objects. Doesn't delete them from the NSManagedObjectContext - that should happen only with confirmation from the server that they were deleted.
///
/// - Parameters:
/// - readingListEntriess: the reading lists to delete
internal func markLocalDeletion(for readingListEntries: [ReadingListEntry]) throws {
guard !readingListEntries.isEmpty else {
return
}
var lists: Set<ReadingList> = []
for entry in readingListEntries {
entry.isDeletedLocally = true
entry.isUpdatedLocally = true
guard let list = entry.list else {
continue
}
lists.insert(list)
}
for list in lists {
try list.updateArticlesAndEntries()
}
}
public func delete(readingLists: [ReadingList]) throws {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
try markLocalDeletion(for: readingLists)
if moc.hasChanges {
try moc.save()
}
sync()
}
internal func add(articles: [WMFArticle], to readingList: ReadingList, in moc: NSManagedObjectContext) throws {
guard !articles.isEmpty else {
return
}
// We should not add the same article in multiple variants.
// Keying on articleKey instead of inMemoryKey matches any variant of an article
var existingKeys = Set(readingList.articleKeys)
for article in articles {
guard let key = article.key, !existingKeys.contains(key) else {
continue
}
guard let entry = moc.wmf_create(entityNamed: "ReadingListEntry", withValue: key, forKey: "articleKey") as? ReadingListEntry else {
return
}
existingKeys.insert(key)
entry.variant = article.variant
entry.createdDate = NSDate()
entry.updatedDate = entry.createdDate
entry.isUpdatedLocally = true
entry.displayTitle = article.displayTitle
entry.list = readingList
}
try readingList.updateArticlesAndEntries()
}
public func add(articles: [WMFArticle], to readingList: ReadingList) throws {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
try throwLimitErrorIfNecessary(for: readingList, articles: articles, in: moc)
try add(articles: articles, to: readingList, in: moc)
if moc.hasChanges {
try moc.save()
}
sync()
}
var syncState: ReadingListSyncState {
get {
assert(Thread.isMainThread)
let rawValue = dataStore.viewContext.wmf_numberValue(forKey: WMFReadingListSyncStateKey)?.int64Value ?? 0
return ReadingListSyncState(rawValue: rawValue)
}
set {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
moc.wmf_setValue(NSNumber(value: newValue.rawValue), forKey: WMFReadingListSyncStateKey)
do {
try moc.save()
} catch let error {
DDLogError("Error saving after sync state update: \(error)")
}
}
}
public func debugSync(createLists: Bool, listCount: Int64, addEntries: Bool, randomizeLanguageEntries: Bool, entryCount: Int64, deleteLists: Bool, deleteEntries: Bool, doFullSync: Bool, completion: @escaping () -> Void) {
dataStore.viewContext.wmf_setValue(NSNumber(value: listCount), forKey: "WMFCountOfListsToCreate")
dataStore.viewContext.wmf_setValue(NSNumber(value: entryCount), forKey: "WMFCountOfEntriesToCreate")
let oldValue = syncState
var newValue = oldValue
if createLists {
newValue.insert(.needsRandomLists)
} else {
newValue.remove(.needsRandomLists)
}
if randomizeLanguageEntries {
newValue.insert(.needsRandomEntries)
} else if addEntries {
newValue.insert(.needsRandomEnEntries)
} else {
newValue.remove(.needsRandomEntries)
newValue.remove(.needsRandomEnEntries)
}
if deleteLists {
newValue.insert(.needsLocalListClear)
} else {
newValue.remove(.needsLocalListClear)
}
if deleteEntries {
newValue.insert(.needsLocalArticleClear)
} else {
newValue.remove(.needsLocalArticleClear)
}
cancelSync {
self.syncState = newValue
if doFullSync {
self.fullSync(completion)
} else {
self._sync(completion)
}
}
}
// is sync enabled for this user
@objc public var isSyncEnabled: Bool {
assert(Thread.isMainThread)
let state = syncState
return state.contains(.needsSync) || state.contains(.needsUpdate)
}
// is sync available or is it shut down server-side
@objc public var isSyncRemotelyEnabled: Bool {
get {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
return moc.wmf_isSyncRemotelyEnabled
}
set {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
moc.wmf_isSyncRemotelyEnabled = newValue
}
}
// should the default list be shown to the user
@objc public var isDefaultListEnabled: Bool {
get {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
return moc.wmf_numberValue(forKey: WMFReadingListDefaultListEnabledKey)?.boolValue ?? false
}
set {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
moc.wmf_setValue(NSNumber(value: newValue), forKey: WMFReadingListDefaultListEnabledKey)
do {
try moc.save()
} catch let error {
DDLogError("Error saving after sync state update: \(error)")
}
}
}
@objc public var maxEntriesPerList: NSNumber {
get {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
return moc.wmf_readingListsConfigMaxEntriesPerList
}
set {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
moc.wmf_readingListsConfigMaxEntriesPerList = newValue
}
}
@objc public var maxListsPerUser: Int {
get {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
return moc.wmf_readingListsConfigMaxListsPerUser
}
set {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
moc.wmf_readingListsConfigMaxListsPerUser = newValue
}
}
func postReadingListsServerDidConfirmSyncWasEnabledForAccountNotification(_ wasSyncEnabledForAccount: Bool) {
// we want to know if sync was ever enabled on this device
let wasSyncEnabledOnDevice = apiController.lastRequestType == .setup
let wasSyncDisabledOnDevice = apiController.lastRequestType == .teardown
DispatchQueue.main.async {
NotificationCenter.default.post(name: ReadingListsController.readingListsServerDidConfirmSyncWasEnabledForAccountNotification, object: nil, userInfo: [ReadingListsController.readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncEnabledKey: NSNumber(value: wasSyncEnabledForAccount), ReadingListsController.readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncEnabledOnDeviceKey: NSNumber(value: wasSyncEnabledOnDevice), ReadingListsController.readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncDisabledOnDeviceKey: NSNumber(value: wasSyncDisabledOnDevice)])
}
}
public func eraseAllSavedArticlesAndReadingLists() {
assert(Thread.isMainThread)
let oldSyncState = syncState
var newSyncState = oldSyncState
if isSyncEnabled {
// Since there is no batch delete on the server,
// we remove local and remote reading lists
// by disabling and then enabling the service.
// Otherwise, we'd have to delete everything via single requests.
newSyncState.insert(.needsRemoteDisable)
newSyncState.insert(.needsRemoteEnable)
newSyncState.insert(.needsSync)
} else {
newSyncState.insert(.needsLocalClear)
newSyncState.remove(.needsSync)
}
newSyncState.remove(.needsUpdate)
guard newSyncState != oldSyncState else {
return
}
syncState = newSyncState
sync()
}
@objc public func setSyncEnabled(_ isSyncEnabled: Bool, shouldDeleteLocalLists: Bool, shouldDeleteRemoteLists: Bool) {
let oldSyncState = self.syncState
var newSyncState = oldSyncState
if shouldDeleteLocalLists {
newSyncState.insert(.needsLocalClear)
} else {
newSyncState.insert(.needsLocalReset)
}
if isSyncEnabled {
newSyncState.insert(.needsRemoteEnable)
newSyncState.insert(.needsSync)
newSyncState.remove(.needsUpdate)
newSyncState.remove(.needsRemoteDisable)
} else {
if shouldDeleteRemoteLists {
newSyncState.insert(.needsRemoteDisable)
}
newSyncState.remove(.needsSync)
newSyncState.remove(.needsUpdate)
newSyncState.remove(.needsRemoteEnable)
}
guard newSyncState != oldSyncState else {
return
}
self.syncState = newSyncState
sync()
}
@objc public func start() {
assert(Thread.isMainThread)
sync()
}
private func cancelSync(_ completion: @escaping () -> Void) {
operationQueue.cancelAllOperations()
apiController.cancelAllTasks()
operationQueue.addOperation {
DispatchQueue.main.async(execute: completion)
}
}
@objc public func stop(_ completion: @escaping () -> Void) {
assert(Thread.isMainThread)
cancelSync(completion)
}
@objc public func fullSync(_ completion: (() -> Void)? = nil) {
#if TEST
#else
var newValue = self.syncState
if newValue.contains(.needsUpdate) {
newValue.remove(.needsUpdate)
newValue.insert(.needsSync)
self.syncState = newValue
}
_sync({
if let completion = completion {
DispatchQueue.main.async(execute: completion)
}
})
#endif
}
@objc private func _sync(_ completion: (() -> Void)? = nil) {
let sync = ReadingListsSyncOperation(readingListsController: self)
addOperation(sync)
if let completion = completion {
let completionBlockOp = BlockOperation(block: completion)
completionBlockOp.addDependency(sync)
operationQueue.addOperation(completionBlockOp)
}
}
@objc private func _syncIfNotSyncing() {
assert(Thread.isMainThread)
guard operationQueue.operationCount == 0 else {
return
}
_sync()
}
@objc public func sync() {
guard !Bundle.main.isAppExtension else {
return
}
#if TEST
#else
assert(Thread.isMainThread)
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(_syncIfNotSyncing), object: nil)
perform(#selector(_syncIfNotSyncing), with: nil, afterDelay: 0.5)
#endif
}
/// Note that the predicate does not take the article language variant into account. This is intentional.
/// Only one variant of an article can be added to a reading list. However *all* variants of the same article appear saved in the user interface.
/// The 'unsave' button can be tapped by the user on *any* variant of the article.
/// By only searching for article key, the saved article variant is removed regardless of which variant of the article was tapped.
public func remove(articles: [WMFArticle], readingList: ReadingList) throws {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
let articleKeys = articles.compactMap { $0.key }
let entriesRequest: NSFetchRequest<ReadingListEntry> = ReadingListEntry.fetchRequest()
entriesRequest.predicate = NSPredicate(format: "list == %@ && articleKey IN %@", readingList, articleKeys)
let entriesToDelete = try moc.fetch(entriesRequest)
try remove(entries: entriesToDelete)
}
public func remove(entries: [ReadingListEntry]) throws {
assert(Thread.isMainThread)
let moc = dataStore.viewContext
try markLocalDeletion(for: entries)
if moc.hasChanges {
try moc.save()
}
sync()
}
@objc public func addArticleToDefaultReadingList(_ article: WMFArticle) throws {
try article.addToDefaultReadingList()
}
@objc public func userSave(_ article: WMFArticle) {
assert(Thread.isMainThread)
do {
let moc = dataStore.viewContext
try article.addToDefaultReadingList()
if moc.hasChanges {
try moc.save()
}
NotificationCenter.default.post(name: WMFReadingListsController.userDidSaveOrUnsaveArticleNotification, object: article)
sync()
} catch let error {
DDLogError("Error saving article: \(error)")
}
}
@objc public func userUnsave(_ article: WMFArticle) {
assert(Thread.isMainThread)
do {
let moc = dataStore.viewContext
guard let savedArticleVariant = article.savedVariant else {
assertionFailure("An article without a saved variant should never be passed to \(#function).")
return
}
unsave([savedArticleVariant], in: moc)
if moc.hasChanges {
try moc.save()
}
// The notification needs to include the exact article acted on.
// Getting the savedVariant ensures we pass the correct variant.
NotificationCenter.default.post(name: WMFReadingListsController.userDidSaveOrUnsaveArticleNotification, object: savedArticleVariant)
sync()
} catch let error {
DDLogError("Error unsaving article: \(error)")
}
}
/// Note that the predicate does not take the article language variant into account. This is intentional.
/// Only one variant of an article can be saved. However *all* variants of the same article appear saved in the user interface.
/// The 'unsave' button can be tapped by the user on *any* variant of the article.
/// By only searching for article key, the saved article variant is removed regardless of which variant of the article was tapped.
public func unsave(_ articles: [WMFArticle], in moc: NSManagedObjectContext) {
do {
let keys = articles.compactMap { $0.key }
let entryFetchRequest: NSFetchRequest<ReadingListEntry> = ReadingListEntry.fetchRequest()
entryFetchRequest.predicate = NSPredicate(format: "articleKey IN %@", keys)
let entries = try moc.fetch(entryFetchRequest)
try markLocalDeletion(for: entries)
} catch let error {
DDLogError("Error removing article from default list: \(error)")
}
}
}
extension WMFArticle {
fileprivate func addToDefaultReadingList() throws {
guard let moc = self.managedObjectContext else {
return
}
guard try fetchDefaultListEntry() == nil else {
return
}
guard let defaultReadingList = moc.fetchOrCreateDefaultReadingList() else {
assert(false, "Default reading list should exist")
return
}
guard let defaultListEntry = NSEntityDescription.insertNewObject(forEntityName: "ReadingListEntry", into: moc) as? ReadingListEntry else {
return
}
defaultListEntry.createdDate = NSDate()
defaultListEntry.updatedDate = defaultListEntry.createdDate
defaultListEntry.articleKey = self.key
defaultListEntry.variant = self.variant
defaultListEntry.list = defaultReadingList
defaultListEntry.displayTitle = displayTitle
defaultListEntry.isUpdatedLocally = true
try defaultReadingList.updateArticlesAndEntries()
}
/// The purpose of these two methods is to answer the question 'is included in default reading list?'.
/// Since only one language variant per article can be included, searching for articleKey will
/// find any variant of the article that is on the default reading list.
/// This is the intended behavior.
private func fetchReadingListEntries() throws -> [ReadingListEntry] {
guard let moc = managedObjectContext, let key = key else {
return []
}
let entryFetchRequest: NSFetchRequest<ReadingListEntry> = ReadingListEntry.fetchRequest()
entryFetchRequest.predicate = NSPredicate(format: "articleKey == %@", key)
return try moc.fetch(entryFetchRequest)
}
private func fetchDefaultListEntry() throws -> ReadingListEntry? {
let readingListEntries = try fetchReadingListEntries()
return readingListEntries.first(where: { (entry) -> Bool in
return (entry.list?.isDefault ?? false) && !entry.isDeletedLocally
})
}
func readingListsDidChange() {
let readingLists = self.readingLists ?? []
if readingLists.isEmpty && savedDate != nil {
savedDate = nil
} else if !readingLists.isEmpty && savedDate == nil {
savedDate = Date()
}
}
private var isInDefaultList: Bool {
guard let readingLists = self.readingLists else {
return false
}
return !readingLists.filter { $0.isDefault }.isEmpty
}
@objc public var isOnlyInDefaultList: Bool {
return (readingLists ?? []).count == 1 && isInDefaultList
}
private var userCreatedReadingLists: [ReadingList] {
return (readingLists ?? []).filter { !$0.isDefault }
}
@objc public var userCreatedReadingListsCount: Int {
return userCreatedReadingLists.count
}
}
public extension NSManagedObjectContext {
// use with caution, fetching is expensive
@objc(wmf_fetchOrCreateDefaultReadingList)
@discardableResult func fetchOrCreateDefaultReadingList() -> ReadingList? {
assert(Thread.isMainThread, "Only create the default reading list on the view context to avoid duplicates")
var defaultList = defaultReadingList
if defaultList == nil { // failsafe
defaultList = wmf_fetchOrCreate(objectForEntityName: "ReadingList", withValue: ReadingList.defaultListCanonicalName, forKey: "canonicalName") as? ReadingList
defaultList?.isDefault = true
do {
try save()
} catch let error {
DDLogError("Error creating default reading list: \(error)")
}
}
return defaultList
}
var defaultReadingList: ReadingList? {
return wmf_fetch(objectForEntityName: "ReadingList", withValue: NSNumber(value: true), forKey: "isDefault") as? ReadingList
}
// is sync available or is it shut down server-side
@objc var wmf_isSyncRemotelyEnabled: Bool {
get {
return wmf_numberValue(forKey: WMFReadingListSyncRemotelyEnabledKey)?.boolValue ?? true
}
set {
guard newValue != wmf_isSyncRemotelyEnabled else {
return
}
wmf_setValue(NSNumber(value: newValue), forKey: WMFReadingListSyncRemotelyEnabledKey)
do {
try save()
} catch let error {
DDLogError("Error saving after sync state update: \(error)")
}
}
}
// MARK: - Reading lists config
@objc var wmf_readingListsConfigMaxEntriesPerList: NSNumber {
get {
return wmf_numberValue(forKey: WMFReadingListsConfigMaxEntriesPerList) ?? 5000
}
set {
wmf_setValue(newValue, forKey: WMFReadingListsConfigMaxEntriesPerList)
do {
try save()
} catch let error {
DDLogError("Error saving new value for WMFReadingListsConfigMaxEntriesPerList: \(error)")
}
}
}
@objc var wmf_readingListsConfigMaxListsPerUser: Int {
get {
return wmf_numberValue(forKey: WMFReadingListsConfigMaxListsPerUser)?.intValue ?? 100
}
set {
wmf_setValue(NSNumber(value: newValue), forKey: WMFReadingListsConfigMaxListsPerUser)
do {
try save()
} catch let error {
DDLogError("Error saving new value for WMFReadingListsConfigMaxListsPerUser: \(error)")
}
}
}
func allReadingListsCount() throws -> Int {
assert(Thread.isMainThread)
let request: NSFetchRequest<ReadingList> = ReadingList.fetchRequest()
request.predicate = NSPredicate(format: "isDeletedLocally == NO")
return try self.count(for: request)
}
}
extension ReadingListsController: PeriodicWorker {
public func doPeriodicWork(_ completion: @escaping () -> Void) {
DispatchQueue.main.async {
self._sync(completion)
}
}
}
extension ReadingListsController: BackgroundFetcher {
public func performBackgroundFetch(_ completion: @escaping (UIBackgroundFetchResult) -> Void) {
doPeriodicWork {
completion(.newData)
}
}
}
| 44.063754 | 588 | 0.661808 |
90890dc87b8458404d4f7fc1ce09a325d830f53a | 3,410 | //
// Copyright (c) Vatsal Manot
//
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
import SwiftUI
import UIKit
fileprivate struct UIViewControllerResolver: UIViewControllerRepresentable {
class UIViewControllerType: UIViewController {
var onResolution: (UIViewController) -> Void = { _ in }
var onAppear: (UIViewController) -> Void = { _ in }
var onDisappear: (UIViewController) -> Void = { _ in }
var onDeresolution: (UIViewController) -> Void = { _ in }
weak var resolvedParent: UIViewController?
override func didMove(toParent parent: UIViewController?) {
super.didMove(toParent: parent)
if let parent = parent {
onResolution(parent)
resolvedParent = parent
} else if let resolvedParent = resolvedParent {
onDeresolution(resolvedParent)
self.resolvedParent = nil
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let parent = parent {
onAppear(parent)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
if let parent = parent {
onDisappear(parent)
}
}
override func removeFromParent() {
super.removeFromParent()
if let resolvedParent = resolvedParent {
onDeresolution(resolvedParent)
self.resolvedParent = nil
}
}
}
var onResolution: (UIViewController) -> Void
var onAppear: (UIViewController) -> Void
var onDisappear: (UIViewController) -> Void
var onDeresolution: (UIViewController) -> Void
func makeUIViewController(context: Context) -> UIViewControllerType {
UIViewControllerType()
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
uiViewController.onResolution = onResolution
uiViewController.onAppear = onAppear
uiViewController.onDisappear = onDisappear
uiViewController.onDeresolution = onDeresolution
}
}
extension View {
public func onUIViewControllerResolution(
perform action: @escaping (UIViewController) -> ()
) -> some View {
background(
UIViewControllerResolver(
onResolution: action,
onAppear: { _ in },
onDisappear: { _ in },
onDeresolution: { _ in }
)
)
}
@_disfavoredOverload
public func onUIViewControllerResolution(
perform resolutionAction: @escaping (UIViewController) -> (),
onAppear: @escaping (UIViewController) -> () = { _ in },
onDisappear: @escaping (UIViewController) -> () = { _ in },
onDeresolution deresolutionAction: @escaping (UIViewController) -> () = { _ in }
) -> some View {
background(
UIViewControllerResolver(
onResolution: resolutionAction,
onAppear: onAppear,
onDisappear: onDisappear,
onDeresolution: deresolutionAction
)
)
}
}
#endif
| 31.284404 | 93 | 0.570968 |
ed2345495fbbc14ab6ef745c5c08a24bcbd0da62 | 27,583 | import StoreKit
@objc(PurchasesSdk)
class PurchasesSdk: NSObject {
private let linkfivePurchases = LinkFivePurchases.shared
@objc(launch:withEnvironment:withResolver:withRejecter:)
func launch(apiKey: String, environment: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
let environment = LinkFiveEnvironment(rawValue: environment) ?? .staging
linkfivePurchases.launch(with: apiKey, environment: environment)
resolve("\(apiKey) + \(environment)")
}
@objc(fetchSubscriptions:withRejecter:)
func fetchSubscriptions(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
linkfivePurchases.fetchSubscriptions { result in
switch result {
case .failure(let error):
reject("error", error.localizedDescription, error)
case .success(let products):
resolve(products.map({ $0.asDictionary }))
}
}
}
@objc(purchase:withResolver:withRejecter:)
func purchase(productId: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
linkfivePurchases.purchase(productId: productId) { result in
switch result {
case .failure(let error):
reject("error", error.localizedDescription, error)
case .success(let succeeded):
resolve(succeeded)
}
}
}
@objc(restore:withRejecter:)
func restore(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
linkfivePurchases.restore { result in
switch result {
case .failure(let error):
reject("error", error.localizedDescription, error)
case .success(let succeeded):
resolve(succeeded)
}
}
}
@objc(fetchReceiptInfo:withResolver:withRejecter:)
func purchase(fromCache: Bool, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
linkfivePurchases.fetchReceiptInfo(fromCache: fromCache) { result in
switch result {
case .failure(let error):
reject("error", error.localizedDescription, error)
case .success(let receipts):
resolve(receipts.map({ $0.asDictionary }))
}
}
}
}
public final class LinkFivePurchases: NSObject {
//#################################################################################
// MARK: - Properties
//#################################################################################
public static let shared = LinkFivePurchases()
private var apiClient: LinkFiveAPIClient?
private var totalRestoredPurchases: Int = 0
private var fetchProductsCompletion: ((Result<[SKProduct]>) -> Void)?
private var buyProductCompletion: ((Result<Bool>) -> Void)?
private var products: [SKProduct] = []
private var userDefaults = LinkFiveUserDefaults.shared
private var receipt: String? {
guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL, FileManager.default.fileExists(atPath: appStoreReceiptURL.path) else { return nil }
do {
let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
let receiptString = receiptData.base64EncodedString(options: [])
return receiptString
}
catch {
LinkFiveLogger.debug("Couldn't read receipt data with error: " + error.localizedDescription)
return nil
}
}
private var productToPurchase: SKProduct?
//#################################################################################
// MARK: - Initialization
//#################################################################################
private override init() {}
//#################################################################################
// MARK: - Public API
//#################################################################################
/// Initializes the SDK.
/// - Parameters:
/// - apiKey: Your LinkFive API key.
/// - environment: Your current environment.
public func launch(with apiKey: String,
environment: LinkFiveEnvironment = .production) {
self.apiClient = LinkFiveAPIClient(apiKey: apiKey, environment: environment)
SKPaymentQueue.default().add(self)
if let _ = receipt {
verifyReceipt()
}
}
/// Fetches and returns the available subscriptions.
/// - Parameters:
/// - completion: The completion of the subscription fetch.
public func fetchSubscriptions(completion: @escaping (Result<[SKProduct]>) -> Void) {
guard let apiClient = apiClient else {
completion(.failure(LinkFivePurchasesError.launchSdkNeeded))
return
}
fetchProductsCompletion = completion
apiClient.fetchSubscriptions(completion: { [weak self] result in
switch result {
case .failure(let error):
self?.fetchProductsCompletion?(.failure(error))
case .success(let response):
let productIds = response.subscriptionList.compactMap({ $0.sku })
if productIds.isEmpty {
self?.fetchProductsCompletion?(.failure(LinkFivePurchasesError.noProductIdsFound))
} else {
let request = SKProductsRequest(productIdentifiers: Set(productIds))
request.delegate = self
request.start()
}
}
})
}
/// Purchases the given `product`.
/// - Parameters:
/// - product: The product to purchase
/// - completion: The completion of the payment.
public func purchase(product: SKProduct, completion: @escaping (Result<Bool>) -> Void) {
buyProductCompletion = completion
guard SKPaymentQueue.canMakePayments() else {
buyProductCompletion?(.failure(LinkFivePurchasesError.cantMakePayments))
return
}
productToPurchase = product
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
/// Purchases the product for given `productId`.
/// - Parameters:
/// - product: The product to purchase
/// - completion: The completion of the payment.
public func purchase(productId: String, completion: @escaping (Result<Bool>) -> Void) {
buyProductCompletion = completion
guard SKPaymentQueue.canMakePayments() else {
buyProductCompletion?(.failure(LinkFivePurchasesError.cantMakePayments))
return
}
guard let product = products.first(where: { $0.productIdentifier == productId }) else {
buyProductCompletion?(.failure(LinkFivePurchasesError.noProductFound))
return
}
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
/// Restores any purchases if available.
/// - Parameters:
/// - completion: The completion of the restore. Returns whether the restore was successful.
public func restore(completion: @escaping (Result<Bool>) -> Void) {
buyProductCompletion = completion
totalRestoredPurchases = 0
SKPaymentQueue.default().restoreCompletedTransactions()
}
/// Fetches the receipt info from cache or from the server, depending on given `fromCache`.
/// - Parameters:
/// - fromCache: Whether to get the receipt info from cache or from the server.
/// - completion: The completion of the receiptInfo call. Returns a `LinkFiveReceiptInfo`.
public func fetchReceiptInfo(fromCache: Bool = true, completion: @escaping (Result<[LinkFiveReceipt]>) -> Void) {
if fromCache, let receipts = LinkFiveUserDefaults.shared.receipts {
completion(.success(receipts))
} else {
verifyReceipt(completion: completion)
}
}
private func verifyReceipt(completion: ((Result<[LinkFiveReceipt]>) -> Void)? = nil) {
guard let apiClient = apiClient else {
completion?(.failure(LinkFivePurchasesError.launchSdkNeeded))
return
}
guard let receipt = receipt else {
completion?(.failure(LinkFivePurchasesError.noReceiptInfo))
return
}
apiClient.verify(receipt: receipt, completion: { [weak self] result in
switch result {
case .success(let response):
let receipts = response.data.purchases
self?.userDefaults.receipts = receipts
completion?(.success(receipts))
case .failure(let error):
LinkFiveLogger.debug(error)
}
})
}
private func logPurchaseToLinkFive(transaction: SKPaymentTransaction) {
guard let product = productToPurchase else { return }
apiClient?.purchase(product: product, transaction: transaction, completion: { result in
switch result {
case .failure(let error):
LinkFiveLogger.debug(error)
case .success:
self.productToPurchase = nil
}
})
}
}
//#################################################################################
// MARK: - SKProductsRequestDelegate
//#################################################################################
extension LinkFivePurchases: SKProductsRequestDelegate {
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
guard !response.products.isEmpty else {
fetchProductsCompletion?(.failure(LinkFivePurchasesError.noProductsFound))
return
}
products = response.products
fetchProductsCompletion?(.success(response.products))
}
public func request(_ request: SKRequest, didFailWithError error: Error) {
fetchProductsCompletion?(.failure(error))
}
}
//#################################################################################
// MARK: - SKPaymentTransactionObserver
//#################################################################################
extension LinkFivePurchases: SKPaymentTransactionObserver {
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
transactions.forEach { transaction in
switch transaction.transactionState {
case .purchased:
logPurchaseToLinkFive(transaction: transaction)
buyProductCompletion?(.success(true))
SKPaymentQueue.default().finishTransaction(transaction)
verifyReceipt()
case .restored:
totalRestoredPurchases += 1
SKPaymentQueue.default().finishTransaction(transaction)
case .failed:
if let error = transaction.error as? SKError {
if error.code != .paymentCancelled {
buyProductCompletion?(.failure(error))
} else {
buyProductCompletion?(.failure(LinkFivePurchasesError.paymentWasCancelled))
}
}
SKPaymentQueue.default().finishTransaction(transaction)
case .deferred, .purchasing:
break
@unknown default:
break
}
}
}
public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
if totalRestoredPurchases != 0 {
buyProductCompletion?(.success(true))
} else {
buyProductCompletion?(.success(false))
}
}
public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
if let error = error as? SKError {
if error.code != .paymentCancelled {
buyProductCompletion?(.failure(error))
} else {
buyProductCompletion?(.failure(LinkFivePurchasesError.paymentWasCancelled))
}
}
}
}
public enum LinkFiveEnvironment: String {
case production = "PRODUCTION"
case staging = "STAGING"
/// The url for the environment.
var url: URL {
switch self {
case .production:
return URL(string: "https://api.linkfive.io/api/")!
case .staging:
return URL(string: "https://api.staging.linkfive.io/api/")!
}
}
}
public enum Result<T> {
case success(T)
case failure(Error)
/// The value of the result.
public var value: T? {
switch self {
case .success(let value):
return value
default:
return nil
}
}
/// The error of the result.
public var error: Error? {
switch self {
case .failure(let error):
return error
default:
return nil
}
}
}
struct LinkFiveLogger {
/// Prints the given `object` only in debug mode.
/// - Parameters:
/// - object: The object to print.
static func debug(_ object: Any) {
#if DEBUG
debugPrint(object)
#endif
}
}
public enum LinkFivePurchasesError: Error {
/// There are no product ids given from LinkFive.
case noProductIdsFound
/// There are no active products for the given product ids.
case noProductsFound
/// The device is not able to make payments.
case cantMakePayments
/// The user cancelled the payment
case paymentWasCancelled
/// No product found
case noProductFound
/// There is no receipt info
case noReceiptInfo
/// The SDK has to be launched first.
case launchSdkNeeded
}
struct LinkFiveUserDefaults {
//#################################################################################
// MARK: - Constants
//#################################################################################
private struct Keys {
static let receiptInfo = "linkFive.userdefaults.receiptInfo"
}
//#################################################################################
// MARK: - Properties
//#################################################################################
/// Shared instance of the `LinkFiveUserDefaults`.
static let shared = LinkFiveUserDefaults()
private let userDefaults = UserDefaults.standard
/// The current receipts.
var receipts: [LinkFiveReceipt]? {
get {
return codable(for: Keys.receiptInfo)
}
set {
saveCodable(newValue, key: Keys.receiptInfo)
}
}
//#################################################################################
// MARK: - Helpers
//#################################################################################
private func saveCodable<T: Encodable>(_ codable: T?, key: String) {
guard let codable = codable else {
userDefaults.removeObject(forKey: key)
return
}
if let encoded = try? JSONEncoder().encode(codable) {
userDefaults.set(encoded, forKey: key)
}
}
private func codable<T: Decodable>(for key: String) -> T? {
guard let codable = userDefaults.object(forKey: key) as? Data else { return nil }
return try? JSONDecoder().decode(T.self, from: codable)
}
}
class LinkFiveAPIClient {
//#################################################################################
// MARK: - Enums
//#################################################################################
enum HttpMethod: String {
case GET
case POST
}
//#################################################################################
// MARK: - Properties
//#################################################################################
private let apiKey: String
private let environment: LinkFiveEnvironment
private var header: [String: String] {
return ["Authorization": "Bearer \(apiKey)",
"X-Platform": "IOS",
"X-Country": Locale.current.regionCode ?? "",
"X-App-Version": (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String) ?? "NO_APP_VERSION"]
}
private lazy var decodingDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.000'Z'"
return dateFormatter
}()
private lazy var iso8601DateFormatter: ISO8601DateFormatter = {
let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return iso8601DateFormatter
}()
//#################################################################################
// MARK: - Initialization
//#################################################################################
/// Initializes the API Client.
/// - Parameters:
/// - apiKey: Your LinkFive API key.
/// - environment: Your current environment.
init(apiKey: String, environment: LinkFiveEnvironment) {
self.apiKey = apiKey
self.environment = environment
}
//#################################################################################
// MARK: - Public API
//#################################################################################
/// Fetches and returns the available subscriptions.
/// - Parameters:
/// - completion: The completion of the subscription fetch.
func fetchSubscriptions(completion: @escaping (Result<LinkFiveSubscriptionList>) -> Void) {
request(path: "v1/subscriptions", httpMethod: HttpMethod.GET, completion: completion)
}
/// Verifies the receipt with the given parameters.
/// - Parameters:
/// - receipt: The receipt.
func verify(receipt: String, completion: @escaping (Result<LinkFiveReceiptInfo>) -> Void) {
let body = LinkFiveReceiptInfo.Request(receipt: receipt).json
request(path: "v1/purchases/apple/verify", httpMethod: HttpMethod.POST, body: body, completion: completion)
}
/// Tells LinkFive that a product has been purchased.
/// - Parameters:
/// - product: The purchased product.
/// - transaction: The transaction..
func purchase(product: SKProduct, transaction: SKPaymentTransaction, completion: @escaping (Result<EmptyResponse>) -> Void) {
let body = LinkFivePurchase.Request(sku: product.productIdentifier,
country: product.priceLocale.regionCode ?? "",
currency: product.priceLocale.currencyCode ?? "",
price: product.price.doubleValue,
transactionId: transaction.transactionIdentifier ?? "",
originalTransactionId: transaction.original?.transactionIdentifier ?? transaction.transactionIdentifier ?? "",
purchaseDate: iso8601DateFormatter.string(from: (transaction.transactionDate ?? Date()))).json
request(path: "v1/purchases/apple", httpMethod: HttpMethod.POST, body: body, completion: completion)
}
private func request<M: Codable>(path: String,
httpMethod: HttpMethod,
body: JSON? = nil,
completion: @escaping (Result<M>) -> Void) {
var request = URLRequest(url: environment.url.appendingPathComponent(path))
request.httpMethod = httpMethod.rawValue
request.allHTTPHeaderFields = header
if let body = body {
request.updateHTTPBody(parameter: body)
}
URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
guard let self = self else { return }
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(LinkFivePurchasesAPIError.noData))
return
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(self.decodingDateFormatter)
if let httpResonse = response as? HTTPURLResponse, httpResonse.statusCode == 201 {
completion(.success(EmptyResponse() as! M))
return
}
do {
let result = try decoder.decode(M.self, from: data)
completion(.success(result))
} catch {
LinkFiveLogger.debug(error)
completion(.failure(LinkFivePurchasesAPIError.decoding))
}
}.resume()
}
}
//#################################################################################
// MARK: - LinkFivePurchasesAPIError
//#################################################################################
enum LinkFivePurchasesAPIError: Error {
/// There is no data.
case noData
/// There was a decoding error.
case decoding
}
//#################################################################################
// MARK: - Private extensions
//#################################################################################
public typealias JSON = [String: Any]
private extension Encodable {
var json: JSON {
guard let data = try? JSONEncoder().encode(self),
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? JSON else {
assertionFailure(String(describing: self) + " must be encodable to JSON")
return JSON()
}
return json
}
}
private extension URLRequest {
mutating func updateHTTPBody(parameter: [String: Any]) {
guard let jsonData: Data = try? JSONSerialization.data(withJSONObject: parameter, options: []) else {
assertionFailure("Could not serialize JSON")
return
}
setValue("application/json", forHTTPHeaderField: "Accept")
setValue("application/json", forHTTPHeaderField: "Content-Type")
setValue("\(jsonData.count)", forHTTPHeaderField: "Content-Length")
httpBody = jsonData
}
}
struct EmptyResponse: Codable {}
struct LinkFivePurchase {
struct Request: Encodable {
/// The product identifier.
let sku: String
/// The country of purchase.
let country: String
/// The currency of purchase.
let currency: String
/// The price.
let price: Double
/// The transaction id of the purchase.
let transactionId: String
/// The original transaction id of the purchase.
let originalTransactionId: String
/// The date of the purchase.
let purchaseDate: String
}
}
public struct LinkFiveSubscriptionList: Codable {
/// A List of subscriptions.
public let subscriptionList: [LinkFiveSubscription]
/// Optional custom attributes.
public let attributes: String?
private enum CodingKeys: String, CodingKey {
case data
}
private enum NestedCodingKeys: String, CodingKey {
case subscriptionList
case attributes
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let nestedContainer = try container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .data)
subscriptionList = try nestedContainer.decode([LinkFiveSubscription].self, forKey: .subscriptionList)
attributes = try nestedContainer.decode(String.self, forKey: .attributes)
}
public func encode(to encoder: Encoder) throws {
assertionFailure("Response encode not implemented yet")
}
public struct LinkFiveSubscription: Codable {
/// The sku of the subscription.
public let sku: String
/// Family name of the subscription.
public let familyName: String?
/// Additional attributes of the subscription.
public let attributes: String?
}
}
struct LinkFiveReceiptInfo: Codable {
let data: DataClass
struct DataClass: Codable {
let purchases: [LinkFiveReceipt]
}
struct Request: Encodable {
/// The receipt to send for the verification.
let receipt: String
}
}
public struct LinkFiveReceipt: Codable {
/// The identifier.
public let sku: String
/// The purchase id.
public let purchaseId: String
/// The transaction date.
public let transactionDate: Date
/// The expiration date.
public let validUntilDate: Date
/// Whether the receipt is expired.
public let isExpired: Bool
/// Whether the receipt is still in trial phase.
public let isTrial: Bool
/// The period of the subscription.
public let period: String?
/// The (optional) family name of the subscription.
public let familyName: String?
/// Optional custom attributes.
public let attributes: String?
private static var dateFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return dateFormatter
}
/// Returns the receipt as dictionary
var asDictionary: [String: Any?] {
return [
"sku": sku,
"purchaseId": purchaseId,
"transactionDate": LinkFiveReceipt.dateFormatter.string(from: transactionDate),
"validUntilDate": LinkFiveReceipt.dateFormatter.string(from: validUntilDate),
"isExpired": isExpired,
"isTrial": isTrial,
"period": period,
"familyName": familyName,
"attributes": attributes
]
}
}
extension SKProduct {
/// Returns the product as dictionary
var asDictionary: [String: Any?] {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = priceLocale
let localizedPrice = formatter.string(from: price)
let numOfUnits = UInt(subscriptionPeriod?.numberOfUnits ?? 0)
let unit = subscriptionPeriod?.unit
var periodUnitIOS = "M"
if unit == .year {
periodUnitIOS = "Y"
} else if unit == .month {
periodUnitIOS = "M"
} else if unit == .week {
periodUnitIOS = "W"
} else if unit == .day {
periodUnitIOS = "D"
}
return [
"productId" : productIdentifier,
"price" : "\(price)",
"currency" : priceLocale.currencyCode,
"title" : localizedTitle,
"description" : localizedDescription,
"localizedPrice" : localizedPrice,
"subscriptionPeriod" : "P\(numOfUnits)\(periodUnitIOS)"
]
}
}
| 34.222084 | 154 | 0.562448 |
ef6c9c9eff838d3588673303d044f2d9f0797a1b | 776 | //
// BindablePropertyTests.swift
// Bindable
//
// Created by Tim van Steenis on 15/12/2019.
//
import XCTest
import Bindable
import BindableNSObject
private class MockModel {
@Bindable var age: Int
init(age: Int) {
self.age = age
}
}
class BindablePropertyTests: XCTestCase {
func testInitialValue() {
let model = MockModel(age: 10)
XCTAssertEqual(model.age, 10)
XCTAssertEqual(model.$age.value, 10)
}
func testChange() {
let model = MockModel(age: 0)
model.age = 1
XCTAssertEqual(model.$age.value, 1)
}
func testExclusiveAccess() {
let model = MockModel(age: 0)
model.$age.subscribe { _ in
print(model.age)
}.disposed(by: disposeBag)
model.age = 1
XCTAssertEqual(model.$age.value, 1)
}
}
| 16.869565 | 45 | 0.655928 |
09134d0da079742d643c73e2934d9dbdc7237ceb | 372 | import Foundation
class Entry: Codable
{
var title: String = "Hello"
var content: String = "Abdul"
var id: String = UUID().uuidString
var createdDate: Date = Date()
init()
{
}
init(_ initialTitle: String, _ initialContent: String)
{
self.title = initialTitle
self.content = initialContent
}
}
| 16.909091 | 58 | 0.575269 |
202c0237d6a25a5b8072736bc7fc9c4e5d296ed4 | 3,788 | //
// FiltersViewController.swift
// Examples
//
// Created by Dimitri Strauneanu on 07/06/2019.
// Copyright © 2019 Streetography. All rights reserved.
//
import UIKit
protocol FiltersViewControllerDelegate: NSObjectProtocol {
func filterViewController(controller: FiltersViewController?, shouldUpdateFilters filters: [Filter])
}
class FiltersViewController: UIViewController {
private weak var tableView: UITableView?
private var filters: [Filter] = []
weak var delegate: FiltersViewControllerDelegate?
init(filters: [Filter]) {
super.init(nibName: nil, bundle: nil)
self.filters = filters.map({ $0.clone() })
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupSubviews()
self.setupSubviewsConstraints()
}
}
// MARK: - Table view data source
extension FiltersViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filters.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let filter = self.filters[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "FilterTextFieldCell", for: indexPath) as? FilterTextFieldCell ?? FilterTextFieldCell()
cell.filter = filter
cell.title = filter.type.rawValue
cell.textFieldText = filter.value
cell.textFieldPlaceholder = filter.placeholder
return cell
}
}
// MARK: - Actions
extension FiltersViewController {
@objc func touchUpInsideCancelButton() {
self.dismiss(animated: true)
}
@objc func touchUpInsideDoneButton() {
self.delegate?.filterViewController(controller: self, shouldUpdateFilters: self.filters)
self.dismiss(animated: true)
}
}
// MARK: - Subviews configuration
extension FiltersViewController {
private func setupSubviews() {
self.setupTableView()
self.setupCancelButton()
self.setupDoneButton()
}
private func setupTableView() {
let tableView = UITableView(frame: .zero, style: .plain)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.register(FilterTextFieldCell.self, forCellReuseIdentifier: "FilterTextFieldCell")
tableView.dataSource = self
tableView.allowsSelection = false
self.view.addSubview(tableView)
self.tableView = tableView
}
private func setupCancelButton() {
let button = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(FiltersViewController.touchUpInsideCancelButton))
self.navigationItem.setLeftBarButton(button, animated: false)
}
private func setupDoneButton() {
let button = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(FiltersViewController.touchUpInsideDoneButton))
self.navigationItem.setRightBarButton(button, animated: false)
}
}
// MARK: - Constraints configuration
extension FiltersViewController {
private func setupSubviewsConstraints() {
self.setupTableViewConstraints()
}
private func setupTableViewConstraints() {
self.tableView?.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.tableView?.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.tableView?.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
self.tableView?.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
}
}
| 33.522124 | 152 | 0.704593 |
89fb48e482bd53eb8a3874a99bfdf314326b28f7 | 3,909 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 cr0ss
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
import UIKit
class MasterViewController: UITableViewController {
internal var objects:Array<Double> = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(self.insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let random = Double(arc4random_uniform(25))
objects.insert(random, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
if let controller = segue.destinationViewController as? DetailViewController {
controller.objects = self.objects
controller.indexPath = indexPath
}
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = self.objects[indexPath.row]
cell.textLabel!.text = "\(object)"
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
//
}
}
}
| 39.484848 | 157 | 0.697365 |
bfec83ea3d63a9afcdf7db071b7060ed9cbdae00 | 12,894 | @testable import Kickstarter_Framework
@testable import KsApi
@testable import Library
import Prelude
internal final class DiscoveryPageViewControllerTests: TestCase {
override func setUp() {
super.setUp()
AppEnvironment.pushEnvironment(mainBundle: Bundle.framework)
UIView.setAnimationsEnabled(false)
}
override func tearDown() {
AppEnvironment.popEnvironment()
UIView.setAnimationsEnabled(true)
super.tearDown()
}
func testView_Activity_Backing() {
let backing = .template
|> Activity.lens.category .~ .backing
|> Activity.lens.id .~ 1_234
|> Activity.lens.project .~ self.cosmicSurgeryNoPhoto
|> Activity.lens.user .~ self.brandoNoAvatar
combos(Language.allLanguages, [Device.phone4_7inch, Device.phone5_8inch, Device.pad]).forEach {
language, device in
withEnvironment(
apiService: MockService(fetchActivitiesResponse: [backing]),
currentUser: User.template,
language: language,
userDefaults: MockKeyValueStore()
) {
let controller = DiscoveryPageViewController.configuredWith(sort: .magic)
controller.tableView.refreshControl = nil
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
parent.view.frame.size.height = 250
self.scheduler.run()
FBSnapshotVerifyView(parent.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
func testView_Card_Project_HasSocial() {
let project = self.anomalisaNoPhoto
|> Project.lens.personalization.friends .~ [self.brandoNoAvatar]
let discoveryResponse = .template
|> DiscoveryEnvelope.lens.projects .~ [project]
combos(Language.allLanguages, Device.allCases).forEach { language, device in
withEnvironment(
apiService: MockService(
fetchActivitiesResponse: [],
fetchDiscoveryResponse: discoveryResponse
),
config: Config.template,
currentUser: User.template,
language: language
) {
let controller = DiscoveryPageViewController.configuredWith(sort: .magic)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
parent.view.frame.size.height = device == .pad ? 700 : 550
controller.change(filter: magicParams)
self.scheduler.run()
controller.tableView.layoutIfNeeded()
controller.tableView.reloadData()
FBSnapshotVerifyView(parent.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
func testView_Card_NoMetadata() {
let project = self.anomalisaNoPhoto
|> Project.lens.dates.deadline .~ (self.dateType.init().timeIntervalSince1970 + 60 * 60 * 24 * 6)
let discoveryResponse = .template
|> DiscoveryEnvelope.lens.projects .~ [project]
combos(Language.allLanguages, [Device.phone4_7inch, Device.phone5_8inch, Device.pad])
.forEach { language, device in
withEnvironment(
apiService: MockService(
fetchActivitiesResponse: [],
fetchDiscoveryResponse: discoveryResponse
),
config: Config.template,
currentUser: User.template, language: language
) {
let controller = DiscoveryPageViewController.configuredWith(sort: .magic)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
parent.view.frame.size.height = device == .pad ? 500 : 450
controller.change(filter: magicParams)
self.scheduler.run()
controller.tableView.layoutIfNeeded()
controller.tableView.reloadData()
FBSnapshotVerifyView(parent.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
func testView_Card_Project_IsBacked() {
let backedProject = self.anomalisaNoPhoto
|> Project.lens.personalization.backing .~ Backing.template
combos(Language.allLanguages, Device.allCases).forEach { language, device in
let discoveryResponse = .template
|> DiscoveryEnvelope.lens.projects .~ [backedProject]
let apiService = MockService(fetchActivitiesResponse: [], fetchDiscoveryResponse: discoveryResponse)
withEnvironment(
apiService: apiService,
config: config,
currentUser: User.template,
language: language
) {
let controller = DiscoveryPageViewController.configuredWith(sort: .magic)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
parent.view.frame.size.height = device == .pad ? 500 : 450
controller.change(filter: magicParams)
self.scheduler.run()
controller.tableView.layoutIfNeeded()
controller.tableView.reloadData()
FBSnapshotVerifyView(
parent.view,
identifier: "backed_lang_\(language)_device_\(device)"
)
}
}
}
func testView_Card_Project_TodaySpecial() {
let mockDate = MockDate()
let featuredProj = self.anomalisaNoPhoto
|> Project.lens.category .~ Project.Category.illustration
|> Project.lens.dates.featuredAt .~ mockDate.timeIntervalSince1970
let devices = [Device.phone4_7inch, Device.phone5_8inch, Device.pad]
let config = Config.template
combos(Language.allLanguages, devices, [("featured", featuredProj)])
.forEach { language, device, labeledProj in
let discoveryResponse = .template
|> DiscoveryEnvelope.lens.projects .~ [labeledProj.1]
let apiService = MockService(fetchActivitiesResponse: [], fetchDiscoveryResponse: discoveryResponse)
withEnvironment(
apiService: apiService,
config: config,
currentUser: User.template,
dateType: MockDate.self,
language: language
) {
let controller = DiscoveryPageViewController.configuredWith(sort: .magic)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
parent.view.frame.size.height = device == .pad ? 500 : 450
controller.change(filter: magicParams)
self.scheduler.run()
controller.tableView.layoutIfNeeded()
controller.tableView.reloadData()
FBSnapshotVerifyView(
parent.view,
identifier: "\(labeledProj.0)_lang_\(language)_device_\(device)"
)
}
}
}
func testView_Card_Project() {
let projectTemplate = self.anomalisaNoPhoto
let starredParams = .defaults
|> DiscoveryParams.lens.starred .~ true
let states = [Project.State.successful, .canceled, .failed, .suspended]
let devices = [Device.phone4_7inch, Device.phone5_8inch, Device.pad]
let config = Config.template
combos(Language.allLanguages, devices, states)
.forEach { language, device, state in
let discoveryResponse = .template
|> DiscoveryEnvelope.lens.projects .~ [projectTemplate |> Project.lens.state .~ state]
let apiService = MockService(fetchActivitiesResponse: [], fetchDiscoveryResponse: discoveryResponse)
withEnvironment(
apiService: apiService,
config: config,
currentUser: User.template, language: language
) {
let controller = DiscoveryPageViewController.configuredWith(sort: .endingSoon)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
parent.view.frame.size.height = device == .pad ? 500 : 450
controller.change(filter: starredParams)
self.scheduler.run()
controller.tableView.layoutIfNeeded()
controller.tableView.reloadData()
FBSnapshotVerifyView(parent.view, identifier: "state_\(state)_lang_\(language)_device_\(device)")
}
}
}
func testView_Onboarding() {
combos(Language.allLanguages, [Device.phone4_7inch, Device.phone5_8inch, Device.pad]).forEach {
language, device in
withEnvironment(currentUser: nil, language: language) {
let controller = DiscoveryPageViewController.configuredWith(sort: .magic)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
parent.view.frame.size.height = 210
controller.change(filter: magicParams)
self.scheduler.run()
FBSnapshotVerifyView(
parent.view, identifier: "lang_\(language)_device_\(device)"
)
}
}
}
func testProjectCard_Experimental() {
let project = self.cosmicSurgeryNoPhoto
|> \.state .~ .live
|> \.staffPick .~ true
let states: [Project.State] = [.live, .successful, .failed, .canceled]
let mockOptimizelyClient = MockOptimizelyClient()
|> \.experiments .~ [
OptimizelyExperiment.Key.nativeProjectCards.rawValue:
OptimizelyExperiment.Variant.variant1.rawValue
]
combos(Language.allLanguages, Device.allCases, states).forEach { language, device, state in
let discoveryResponse = .template
|> DiscoveryEnvelope.lens.projects .~ [project |> Project.lens.state .~ state]
let apiService = MockService(fetchActivitiesResponse: [], fetchDiscoveryResponse: discoveryResponse)
withEnvironment(apiService: apiService, language: language, optimizelyClient: mockOptimizelyClient) {
let controller = DiscoveryPageViewController.configuredWith(sort: .magic)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
controller.change(filter: .defaults)
self.scheduler.run()
controller.tableView.layoutIfNeeded()
controller.tableView.reloadData()
FBSnapshotVerifyView(parent.view, identifier: "state_\(state)_lang_\(language)_device_\(device)")
}
}
}
func testProjectCard_Experimental_Backer() {
let project = self.cosmicSurgeryNoPhoto
|> \.personalization.backing .~ Backing.template
|> \.staffPick .~ true
let mockOptimizelyClient = MockOptimizelyClient()
|> \.experiments .~ [
OptimizelyExperiment.Key.nativeProjectCards.rawValue:
OptimizelyExperiment.Variant.variant1.rawValue
]
combos(Language.allLanguages, Device.allCases).forEach { language, device in
let discoveryResponse = .template
|> DiscoveryEnvelope.lens.projects .~ [project]
let apiService = MockService(fetchActivitiesResponse: [], fetchDiscoveryResponse: discoveryResponse)
withEnvironment(apiService: apiService, language: language, optimizelyClient: mockOptimizelyClient) {
let controller = DiscoveryPageViewController.configuredWith(sort: .magic)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
controller.change(filter: .defaults)
self.scheduler.run()
controller.tableView.layoutIfNeeded()
controller.tableView.reloadData()
FBSnapshotVerifyView(parent.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
func testProjectCard_Experimental_Social() {
let friend1 = User.brando
|> \.avatar.small .~ ""
let friend2 = User.template
|> \.name .~ "Alfie"
|> \.avatar.small .~ ""
let project = self.cosmicSurgeryNoPhoto
|> \.personalization.friends .~ [friend1, friend2]
let mockOptimizelyClient = MockOptimizelyClient()
|> \.experiments .~ [
OptimizelyExperiment.Key.nativeProjectCards.rawValue:
OptimizelyExperiment.Variant.variant1.rawValue
]
combos(Language.allLanguages, Device.allCases).forEach { language, device in
let discoveryResponse = .template
|> DiscoveryEnvelope.lens.projects .~ [project]
let apiService = MockService(fetchActivitiesResponse: [], fetchDiscoveryResponse: discoveryResponse)
withEnvironment(apiService: apiService, language: language, optimizelyClient: mockOptimizelyClient) {
let controller = DiscoveryPageViewController.configuredWith(sort: .magic)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller)
controller.change(filter: .defaults)
self.scheduler.run()
controller.tableView.layoutIfNeeded()
controller.tableView.reloadData()
FBSnapshotVerifyView(parent.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
fileprivate let anomalisaNoPhoto = .anomalisa
|> Project.lens.id .~ 1_111
|> Project.lens.photo.full .~ ""
fileprivate let brandoNoAvatar = User.brando
|> \.avatar.medium .~ ""
fileprivate let cosmicSurgeryNoPhoto = .cosmicSurgery
|> Project.lens.id .~ 2_222
|> Project.lens.photo.full .~ ""
fileprivate let magicParams = .defaults
|> DiscoveryParams.lens.sort .~ .magic
}
| 35.816667 | 108 | 0.679774 |
f849e5ecdb5a8c213d25650eb71890a09d8291ea | 3,596 | //
// EZTextView.swift
// EasyAtrribute
//
// Created by duzhe on 2017/10/23.
//
import UIKit
public class EZAttributeString {
public var attributeText: NSMutableAttributedString
public init(attributeText: NSMutableAttributedString) {
self.attributeText = attributeText
}
public var action: (()->())?
public var range: NSRange?
public var location: Int{
return range?.location ?? 0
}
public var length: Int {
return range?.length ?? 0
}
public func addAction(_ action:(()->())?) -> EZAttributeString{
self.action = action
return self
}
public func rangeContains(_ index: Int)->Bool{
if index >= self.location && index <= self.location+self.length {
return true
}
return false
}
}
public class EZTextView: UITextView {
public var selectedBackgroundColor: UIColor?
private var storageTexts: [EZAttributeString] = []
private var selectedAttribute: EZAttributeString?
private var originalAttributeText: NSAttributedString?
public func removeAllAttribute()->EZTextView{
text = ""
return self
}
@discardableResult
public func appendAttributedText(_ attribute: EZAttributeString) -> EZTextView{
storageTexts.append(attribute)
let location = attributedText?.length ?? 0
attribute.range = NSMakeRange(location, attribute.attributeText.length)
if let at = attributedText , at.length > 0 {
attributedText = NSMutableAttributedString(attributedString: at) + attribute.attributeText
}else{
attributedText = attribute.attributeText
}
self.originalAttributeText = attributedText
return self
}
private func indexForLocation(_ loc: CGPoint)->Int{
var location = loc
location.x -= self.textContainerInset.left
location.y -= self.textContainerInset.top
let index = layoutManager.characterIndex(for: location , in: textContainer , fractionOfDistanceBetweenInsertionPoints: nil)
return index
}
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let location = touches.first?.location(in: self) else {
return
}
let index = indexForLocation(location)
// print("\(location) , \(index)")
let realStorageTexts = storageTexts.filter{ $0.action != nil }
for item in realStorageTexts {
if item.rangeContains(index) {
self.selectedAttribute = item
if let range = item.range {
let attr = NSMutableAttributedString(attributedString: self.attributedText)
attr.addAttribute(.backgroundColor, value:self.selectedBackgroundColor ?? UIColor.lightGray, range: range)
self.attributedText = attr
}
}
}
}
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let location = touches.first?.location(in: self) else {
return
}
let index = indexForLocation(location)
if let selectedAttribute = self.selectedAttribute {
if !selectedAttribute.rangeContains(index) {
cancel()
}
}
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
finish()
}
override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
cancel()
}
func finish(){
if let ort = self.originalAttributeText {
self.attributedText = ort
self.selectedAttribute?.action?()
self.selectedAttribute = nil
}
}
func cancel(){
if let ort = self.originalAttributeText {
self.attributedText = ort
self.selectedAttribute = nil
}
}
}
| 28.314961 | 127 | 0.683815 |
6983225d116e2f18fe0b974eb5a04512dd51c63a | 291 | //
// ViewController.swift
// covidTest
//
// Created by Florian Doppler on 08.03.22.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 13.227273 | 58 | 0.628866 |
482534f52da8d00afaea19e9cd4ae1dca87c0d63 | 1,273 | import XCTest
import ConfigFile
@testable import WebAPI
class AuthAPITests: XCTestCase {
static var config = StringConfigFile("etvnet.config")
var subject = EtvnetAPI(config: config)
func testGetActivationCodes() {
let result = subject.getActivationCodes()!
let activationUrl = result.activationUrl!
let userCode = result.userCode!
print("Activation url: \(activationUrl)")
print("Activation code: \(userCode)")
XCTAssertNotNil(result.activationUrl)
XCTAssertNotNil(result.userCode)
XCTAssertNotNil(result.deviceCode)
}
func testCreateToken() {
let result = subject.authorization()
if result.userCode != "" {
let response = subject.tryCreateToken(
userCode: result.userCode,
deviceCode: result.deviceCode,
activationUrl: result.activationUrl
)!
XCTAssertNotNil(response.accessToken)
XCTAssertNotNil(response.refreshToken)
}
}
func testUpdateToken() throws {
let refreshToken = subject.config.items["refresh_token"]!
let response = subject.updateToken(refreshToken: refreshToken)
subject.config.items = response!.asDictionary()
try subject.config.save()
XCTAssertNotNil(response!.accessToken)
}
}
| 24.480769 | 66 | 0.692852 |
4a98791bc4634d6681a0ee1f12cb267cf5129006 | 18,332 | //
// paramTests.swift
// rosswiftTests
//
// Created by Thomas Gustafsson on 2018-10-30.
//
import XCTest
@testable import RosSwift
@testable import RosTime
@testable import rpcobject
let ros = Ros(argv: &CommandLine.arguments, name: "paramTests")
class paramTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
ros.param.set(key: "string", value: "test")
ros.param.set(key: "int", value: Int(10))
ros.param.set(key: "double", value: Double(10.5))
ros.param.set(key: "bool", value: false)
_ = ros.param.del(key: "/test_set_param_setThenGetStringCached")
_ = ros.param.del(key: "/test_create_parameter")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
ros.shutdown()
}
func testAllParamTypes() {
var string_param = ""
XCTAssert( ros.param.get( "string", &string_param ) )
XCTAssert( string_param == "test" )
var int_param = 0
XCTAssert( ros.param.get( "int", &int_param ) )
XCTAssert( int_param == 10 )
var double_param = 0.0
XCTAssert( ros.param.get( "double", &double_param ) )
XCTAssertEqual( double_param, 10.5 )
var bool_param = true
XCTAssert( ros.param.get( "bool", &bool_param ) )
XCTAssertFalse( bool_param )
}
@RosParameter(name: "string", ros: ros) var string_param: String
@RosParameter(name: "string", ros: ros) var string_param2: String
@RosParameter(name: "test_create_parameter", ros: ros) var param3: String
func testPropertyWrapper() {
XCTAssertEqual( string_param, "test" )
XCTAssertEqual( string_param2,"test" )
string_param = "testing"
XCTAssertEqual( string_param, "testing" )
XCTAssertEqual( string_param2, "testing" )
XCTAssertFalse( ros.param.has(key: "test_create_parameter"))
param3 = "param"
XCTAssert( ros.param.has(key: "test_create_parameter"))
XCTAssertEqual( param3, "param" )
var param = ""
XCTAssert( ros.param.get( "test_create_parameter", ¶m ) )
XCTAssertEqual( "param", param )
ros.param.set(key: "test_create_parameter", value: "new value")
XCTAssertEqual( param3, "new value" )
}
func testSetThenGetString() {
ros.param.set( key: "test_set_param", value: "asdf" )
var param = ""
XCTAssert( ros.param.get( "test_set_param", ¶m ) )
XCTAssertEqual( "asdf", param )
var v = XmlRpcValue()
XCTAssert( ros.param.get("test_set_param", &v) )
XCTAssertEqual(v, XmlRpcValue(str: "asdf") )
}
func testSetThenGetStringCached() {
_ = ros.param.del(key: "test_set_param_setThenGetStringCached")
var param = ""
XCTAssertFalse( ros.param.getCached( "test_set_param_setThenGetStringCached", ¶m) )
ros.param.set( key: "test_set_param_setThenGetStringCached", value: "asdf" )
XCTAssert( ros.param.getCached( "test_set_param_setThenGetStringCached", ¶m) )
XCTAssertEqual( "asdf", param )
}
func testSetThenGetNamespaceCached()
{
_ = ros.param.del(key: "/test_set_param_setThenGetStringCached2")
var stringParam = ""
var structParam = XmlRpcValue()
let ns = "test_set_param_setThenGetStringCached2"
XCTAssertFalse(ros.param.getCached(ns, &stringParam))
ros.param.set(key: ns, value: "a")
XCTAssert(ros.param.getCached(ns, &stringParam))
XCTAssertEqual("a", stringParam)
ros.param.set(key: ns + "/foo", value: "b")
XCTAssert(ros.param.getCached(ns + "/foo", &stringParam))
XCTAssertEqual("b", stringParam)
XCTAssert(ros.param.getCached(ns, &structParam))
XCTAssert(structParam.hasMember("foo"))
XCTAssertEqual("b", structParam["foo"]?.string)
}
func testSetThenGetCString()
{
ros.param.set( key: "test_set_param", value: "asdf" )
var param = ""
XCTAssert( ros.param.get( "test_set_param", ¶m ) )
XCTAssertEqual( "asdf", param )
}
func testsetThenGetInt()
{
ros.param.set( key: "test_set_param", value: 42)
var param = 0
XCTAssert( ros.param.get( "test_set_param", ¶m ) )
XCTAssertEqual( 42, param )
var v = XmlRpcValue()
XCTAssert(ros.param.get("test_set_param", &v))
guard case .int = v else {
XCTFail()
return
}
}
func testunknownParam()
{
var param = ""
XCTAssertFalse( ros.param.get( "this_param_really_should_not_exist", ¶m ) )
}
func testdeleteParam()
{
ros.param.set( key: "test_delete_param", value: "asdf" )
_ = ros.param.del( key: "test_delete_param" )
var param = ""
XCTAssertFalse( ros.param.get( "test_delete_param", ¶m ) )
}
func testhasParam()
{
XCTAssert( ros.param.has( key: "string" ) )
}
func testsetIntDoubleGetInt()
{
ros.param.set(key: "test_set_int_as_double", value: 1)
ros.param.set(key: "test_set_int_as_double", value: 3.0)
var i = -1
XCTAssert(ros.param.get("test_set_int_as_double", &i))
XCTAssertEqual(3, i)
var d = 0.0
XCTAssert(ros.param.get("test_set_int_as_double", &d))
XCTAssertEqual(3.0, d)
}
func testgetIntAsDouble()
{
ros.param.set(key: "int_param", value: 1)
var d = 0.0
XCTAssert(ros.param.get("int_param", &d))
XCTAssertEqual(1.0, d)
}
func testgetDoubleAsInt()
{
ros.param.set(key: "double_param", value: 2.3)
var i = -1
XCTAssert(ros.param.get("double_param", &i))
XCTAssertEqual(2, i)
ros.param.set(key: "double_param", value: 3.8)
i = -1
XCTAssert(ros.param.get("double_param", &i))
XCTAssertEqual(4, i)
}
func testsearchParam()
{
let ns = "/a/b/c/d/e/f"
var result = ""
ros.param.set(key: "/s_i", value: 1)
XCTAssert(ros.param.search(ns: ns, key: "s_i", result: &result))
XCTAssertEqual(result, "/s_i")
XCTAssert(ros.param.del(key: "/s_i"))
ros.param.set(key: "/a/b/s_i", value: 1)
XCTAssert(ros.param.search(ns: ns, key: "s_i", result: &result))
XCTAssertEqual(result, "/a/b/s_i")
XCTAssert(ros.param.del(key: "/a/b/s_i"))
ros.param.set(key: "/a/b/c/d/e/f/s_i", value: 1)
XCTAssert(ros.param.search(ns: ns, key: "s_i", result: &result))
XCTAssertEqual(result, "/a/b/c/d/e/f/s_i")
XCTAssert(ros.param.del(key: "/a/b/c/d/e/f/s_i"))
XCTAssertFalse(ros.param.search(ns: ns, key: "s_j", result: &result))
}
func testsearchParamNodeHandle()
{
guard let n = ros.createNode(ns: "/a/b/c/d/e/f") else {
XCTFail()
return
}
var result = ""
n.set(parameter: "/s_i", value: 1)
let ok = n.search(parameter: "s_i", result: &result)
XCTAssert(ok)
XCTAssertEqual(result, "/s_i")
XCTAssert(n.delete(paramter: "/s_i"))
n.set(parameter: "/a/b/s_i", value: 1)
XCTAssert(n.search(parameter: "s_i", result: &result))
XCTAssertEqual(result, "/a/b/s_i")
XCTAssert(n.delete(paramter:"/a/b/s_i"))
n.set(parameter: "/a/b/c/d/e/f/s_i", value: 1)
XCTAssert(n.search(parameter: "s_i", result: &result))
XCTAssertEqual(result, "/a/b/c/d/e/f/s_i")
XCTAssert(n.delete(paramter:"/a/b/c/d/e/f/s_i"))
XCTAssertFalse(n.search(parameter: "s_j", result: &result))
}
func testsearchParamNodeHandleWithRemapping()
{
_ = ros.param.del(key: "/s_b")
let remappings = ["s_c":"s_b"]
guard let n = ros.createNode(ns: "/a/b/c/d/e/f", remappings: remappings) else {
XCTFail()
return
}
var result = ""
n.set(parameter: "/s_c", value: 1)
XCTAssertFalse(n.search(parameter: "s_c", result: &result))
n.set(parameter: "/s_b", value: 1)
XCTAssert(n.search(parameter: "s_c", result: &result))
print("RESULT \(result)")
}
func testgetMissingXmlRpcValueParameterCachedTwice()
{
var v = XmlRpcValue()
XCTAssertFalse(ros.param.getCached("invalid_xmlrpcvalue_param", &v))
XCTAssertFalse(ros.param.getCached("invalid_xmlrpcvalue_param", &v))
}
func testdoublePrecision()
{
ros.param.set(key: "bar", value: 0.123456789123456789)
var d = 0.0
XCTAssert(ros.param.get("bar", &d))
XCTAssertEqual(d, 0.12345678912345678)
}
var vec_s = [String]()
var vec_s2 = [String]()
var vec_d = [Double]()
var vec_d2 = [Double]()
var vec_f = [Float32]()
var vec_f2 = [Float32]()
var vec_i = [Int]()
var vec_i2 = [Int]()
var vec_b = [Bool]()
var vec_b2 = [Bool]()
func testvectorStringParam()
{
let param_name = "v_param"
vec_s = ["foo","bar","baz"]
ros.param.set(key: param_name, value: vec_s)
XCTAssertFalse(ros.param.get(param_name, &vec_d))
XCTAssertFalse(ros.param.get(param_name, &vec_f))
XCTAssertFalse(ros.param.get(param_name, &vec_i))
XCTAssertFalse(ros.param.get(param_name, &vec_b))
XCTAssert(ros.param.get(param_name, &vec_s2))
XCTAssertEqual(vec_s.count, vec_s2.count)
XCTAssertEqual(vec_s, vec_s2)
// test empty vector
vec_s.removeAll()
ros.param.set(key: param_name, value: vec_s)
XCTAssert(ros.param.get(param_name, &vec_s2))
XCTAssertEqual(vec_s.count, vec_s2.count)
}
func testvectorDoubleParam()
{
let param_name = "vec_double_param"
vec_d = [-0.123456789,3,3.01,7.01]
ros.param.set(key: param_name, value: vec_d)
XCTAssertFalse(ros.param.get(param_name, &vec_s))
XCTAssert(ros.param.get(param_name, &vec_i))
XCTAssert(ros.param.get(param_name, &vec_b))
XCTAssert(ros.param.get(param_name, &vec_f))
XCTAssert(ros.param.get(param_name, &vec_d2))
XCTAssertEqual(vec_d.count, vec_d2.count)
XCTAssertEqual(vec_d, vec_d2)
XCTAssertEqual(vec_f, [-0.123456789,3,3.01,7.01])
XCTAssertEqual(vec_i, [0,3,3,7])
XCTAssertEqual(vec_b, [true,true,true,true])
}
func testvectorFloatParam()
{
let param_name = "vec_float_param"
vec_f = [-0.25, 0.0, 3, 3.25]
ros.param.set(key: param_name, value: vec_f)
XCTAssertFalse(ros.param.get(param_name, &vec_s))
XCTAssert(ros.param.get(param_name, &vec_i))
XCTAssert(ros.param.get(param_name, &vec_b))
XCTAssert(ros.param.get(param_name, &vec_d))
XCTAssertEqual(vec_b,[true,false,true,true])
XCTAssertEqual(vec_i, [0,0,3,3])
XCTAssertEqual(vec_d, [-0.25, 0.0, 3, 3.25])
XCTAssert(ros.param.get(param_name, &vec_f2))
XCTAssertEqual(vec_f.count, vec_f2.count)
XCTAssertEqual(vec_f, vec_f2)
}
func testvectorIntParam()
{
let param_name = "vec_int_param"
vec_i = [-1, 0, 1337, 2]
ros.param.set(key: param_name, value: vec_i)
XCTAssertFalse(ros.param.get(param_name, &vec_s))
XCTAssert(ros.param.get(param_name, &vec_d))
XCTAssert(ros.param.get(param_name, &vec_f))
XCTAssert(ros.param.get(param_name, &vec_b))
XCTAssertEqual(vec_b,[true,false,true,true])
XCTAssertEqual(vec_f,[-1,0,1337,2])
XCTAssertEqual(vec_d,[-1,0,1337,2])
XCTAssert(ros.param.get(param_name, &vec_i2))
XCTAssertEqual(vec_i.count, vec_i2.count)
XCTAssertEqual(vec_i, vec_i2)
}
func testvectorBoolParam()
{
let param_name = "vec_bool_param"
vec_b = [true, false, true, true]
ros.param.set(key: param_name, value: vec_b)
XCTAssertFalse(ros.param.get(param_name, &vec_s))
XCTAssert(ros.param.get(param_name, &vec_d))
XCTAssert(ros.param.get(param_name, &vec_f))
XCTAssert(ros.param.get(param_name, &vec_i))
XCTAssertEqual(vec_i,[1,0,1,1])
XCTAssertEqual(vec_d,[1,0,1,1])
XCTAssertEqual(vec_f,[1,0,1,1])
XCTAssert(ros.param.get(param_name, &vec_b2))
XCTAssertEqual(vec_b.count, vec_b2.count)
XCTAssertEqual(vec_b, vec_b2)
}
var map_s = [String:String]()
var map_s2 = [String:String]()
var map_d = [String:Double]()
var map_d2 = [String:Double]()
var map_f = [String:Float32]()
var map_f2 = [String:Float32]()
var map_i = [String:Int]()
var map_i2 = [String:Int]()
var map_b = [String:Bool]()
var map_b2 = [String:Bool]()
func testmapStringParam()
{
let param_name = "map_str_param"
map_s = ["a": "apple", "b": "blueberry", "c": "carrot"]
ros.param.set(key: param_name, value: map_s)
XCTAssertFalse(ros.param.get(param_name, &map_d))
XCTAssertFalse(ros.param.get(param_name, &map_f))
XCTAssertFalse(ros.param.get(param_name, &map_i))
XCTAssertFalse(ros.param.get(param_name, &map_b))
XCTAssert(ros.param.get(param_name, &map_s2))
XCTAssertEqual(map_s.count, map_s2.count)
XCTAssertEqual(map_s, map_s2)
}
func testmapDoubleParam()
{
let param_name = "map_double_param"
map_d = ["a":0.0,"b":-0.123456789,"c":12345678]
ros.param.set(key: param_name, value: map_d)
XCTAssertFalse(ros.param.get(param_name, &map_s))
XCTAssert(ros.param.get(param_name, &map_f))
XCTAssert(ros.param.get(param_name, &map_i))
XCTAssert(ros.param.get(param_name, &map_b))
XCTAssert(ros.param.get(param_name, &map_d2))
XCTAssertEqual(map_f, ["a":0.0,"b":-0.123456789,"c":12345678])
XCTAssertEqual(map_i, ["a":0,"b":0,"c":12345678])
XCTAssertEqual(map_b, ["a":false,"b":true,"c":true])
XCTAssertEqual(map_d.count, map_d2.count)
XCTAssertEqual(map_d, map_d2)
}
func testmapFloatParam()
{
let param_name = "map_float_param"
map_f = ["a": 0.0, "b":-0.25,"c":1234567]
ros.param.set(key: param_name, value: map_f)
XCTAssertFalse(ros.param.get(param_name, &map_s))
XCTAssert(ros.param.get(param_name, &map_d))
XCTAssert(ros.param.get(param_name, &map_i))
XCTAssert(ros.param.get(param_name, &map_b))
XCTAssertEqual(map_d, ["a":0.0,"b":-0.25,"c":1234567])
XCTAssertEqual(map_i, ["a":0,"b":0,"c":1234567])
XCTAssertEqual(map_b, ["a":false,"b":true,"c":true])
XCTAssert(ros.param.get(param_name, &map_f2))
XCTAssertEqual(map_f.count, map_f2.count)
XCTAssertEqual(map_f, map_f2)
}
func testmapIntParam()
{
let param_name = "map_int_param"
map_i = ["a":0, "b":-1, "c":1337]
ros.param.set(key: param_name, value: map_i)
XCTAssertFalse(ros.param.get(param_name, &map_s))
XCTAssert(ros.param.get(param_name, &map_d))
XCTAssert(ros.param.get(param_name, &map_f))
XCTAssert(ros.param.get(param_name, &map_b))
XCTAssertEqual(map_f, ["a":0.0,"b":-1,"c":1337])
XCTAssertEqual(map_d, ["a":0,"b":-1,"c":1337])
XCTAssertEqual(map_b, ["a":false,"b":true,"c":true])
XCTAssert(ros.param.get(param_name, &map_i2))
XCTAssertEqual(map_i.count, map_i2.count)
XCTAssertEqual(map_i, map_i2)
}
func testmapBoolParam()
{
let param_name = "map_bool_param"
map_b = ["a":true, "b":false, "c":true]
ros.param.set(key: param_name, value: map_b)
XCTAssertFalse(ros.param.get(param_name, &map_s))
XCTAssert(ros.param.get(param_name, &map_d))
XCTAssert(ros.param.get(param_name, &map_f))
XCTAssert(ros.param.get(param_name, &map_i))
XCTAssertEqual(map_i, ["a":1,"b":0, "c":1])
XCTAssertEqual(map_f, ["a":1,"b":0, "c":1])
XCTAssertEqual(map_d, ["a":1,"b":0, "c":1])
XCTAssert(ros.param.get(param_name, &map_b2))
XCTAssertEqual(map_b.count, map_b2.count)
XCTAssertEqual(map_b, map_b2)
}
func testparamTemplateFunction()
{
XCTAssertEqual( ros.param.param( name: "string", defaultValue: "" ), "test" )
XCTAssertEqual( ros.param.param( name: "gnirts", defaultValue: "test" ), "test" )
XCTAssertEqual( ros.param.param( name: "int", defaultValue: 0 ), 10 )
XCTAssertEqual( ros.param.param( name: "tni", defaultValue: 10 ), 10 )
XCTAssertEqual( ros.param.param( name: "double", defaultValue: 0.0 ), 10.5 )
XCTAssertEqual( ros.param.param( name: "elbuod", defaultValue: 10.5 ), 10.5 )
XCTAssertEqual( ros.param.param( name: "bool", defaultValue: true ), false )
XCTAssertEqual( ros.param.param( name: "loob", defaultValue: true ), true )
}
func testparamNodeHandleTemplateFunction()
{
let nh = ros.createNode()
XCTAssertEqual( nh.param( name: "string", defaultValue: "" ), "test" )
XCTAssertEqual( nh.param( name: "gnirts", defaultValue: "test" ), "test" )
XCTAssertEqual( nh.param( name: "int", defaultValue: 0 ), 10 )
XCTAssertEqual( nh.param( name: "tni", defaultValue: 10 ), 10 )
XCTAssertEqual( nh.param( name: "double", defaultValue: 0.0 ), 10.5 )
XCTAssertEqual( nh.param( name: "elbuod", defaultValue: 10.5 ), 10.5 )
XCTAssertEqual( nh.param( name: "bool", defaultValue: true ), false )
XCTAssertEqual( nh.param( name: "loob", defaultValue: true ), true )
}
// should run last, tests runs in alphabetical order (unless random order is selected)
func testZgetParamNames() {
var test_params = [String]()
let b = ros.param.getParamNames(keys: &test_params)
XCTAssert(b)
XCTAssertLessThan(10, test_params.count)
let h = try! ros.param.getParameterNames().wait()
XCTAssertLessThan(10, h.count)
print(h)
}
}
| 31.552496 | 111 | 0.606317 |
679632e0b4fb37525ae0b05ae73f5f2cde0fd1ca | 1,328 | //
// ModelObject.swift
// Gordian Seed Tool
//
// Created by Wolf McNally on 12/15/20.
//
import SwiftUI
import LifeHash
import URKit
struct ModelSubtype: Identifiable, Hashable {
var id: String
var icon: AnyView
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func ==(lhs: ModelSubtype, rhs: ModelSubtype) -> Bool {
lhs.id == rhs.id
}
}
protocol HasUR {
var ur: UR { get }
var qrData: Data { get }
}
protocol ModelObject: ObjectIdentifiable, Identifiable, ObservableObject, Hashable, HasUR {
var sizeLimitedUR: UR { get }
var urString: String { get }
var id: UUID { get }
}
extension ModelObject {
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func ==(lhs: Self, rhs: Self) -> Bool {
lhs.id == rhs.id
}
}
extension ModelObject {
var subtypes: [ModelSubtype] { [] }
var instanceDetail: String? { nil }
func printPages(model: Model) -> [AnyView] {
[
Text("No print page provided.")
.eraseToAnyView()
]
}
var urString: String {
ur.string
}
var qrData: Data {
ur.qrData
}
var sizeLimitedQRString: String {
UREncoder.encode(sizeLimitedUR).uppercased()
}
}
| 19.529412 | 91 | 0.586596 |
5d879235efc9a0a8e0e979e49a3987023987693e | 1,106 | //
// Photo.swift
//
//
// Created by Simge Çakır on 7.09.2021.
//
import Foundation
// "id": 102693,
// "sol": 1000,
// "camera": {
// "id": 20,
// "name": "FHAZ",
// "rover_id": 5,
// "full_name": "Front Hazard Avoidance Camera"
// },
// "img_src": "http://mars.jpl.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/01000/opgs/edr/fcam/FLB_486265257EDR_F0481570FHAZ00323M_.JPG",
// "earth_date": "2015-05-30",
// "rover": {
// "id": 5,
// "name": "Curiosity",
// "landing_date": "2012-08-06",
// "launch_date": "2011-11-26",
// "status": "active"
// }
// },
public struct Photo: Decodable{
public let id: Int
public let camera : Camera
public let imagePath: String
public let rover: Rover
public let earthDate: String
enum CodingKeys: String, CodingKey{
case id
case camera
case rover
case imagePath = "img_src"
case earthDate = "earth_date"
}
}
| 24.043478 | 156 | 0.509946 |
033f62748ea8b99f4fec7491b9f7d86b5974ff2d | 8,027 | //
// Scan_Vc.swift
// Pods
//
// Created by eme on 2017/3/6.
//
//
/*
owner:cy
update:2017年03月06日10:44:50
info: 扫一扫vc
*/
import UIKit
import AVFoundation
public class Scan_Vc: Base_Vc {
/****************************Storyboard UI设置区域****************************/
@IBOutlet weak var scan_Content_V: UIView!
@IBOutlet weak var footer_V: UIView!
@IBOutlet weak var bottom_Lb: UILabel!
@IBOutlet weak var scan_Line_ImgV: UIImageView!
@IBOutlet weak var light_Btn: UIButton!
@IBOutlet weak var scan_Line_HeightLc: NSLayoutConstraint!
@IBOutlet weak var content_V: UIView!
///上次扫描到的结果
var lastResultStr:String?
///保存扫到的值
public var didScanValue_Block:((_ relValue:String) -> Void)?
/*---------------------------- 自定义属性区域 ----------------------------*/
///扫描动画
var isAnimationing:Bool = true
var startY:CGFloat = 5.0
var isDown:Bool = true
/// 定时器
var timer:Timer!
// MARK: - 懒加载
// 会话
lazy var session : AVCaptureSession = AVCaptureSession()
// 拿到输入设备
lazy var deviceInput: AVCaptureDeviceInput? = {
// 获取摄像头
guard let device = AVCaptureDevice.default(for: .video) else{
return nil
}
do{
// 创建输入对象
let input = try AVCaptureDeviceInput(device: device)
return input
}catch
{
print(error)
return nil
}
}()
// 拿到输出对象
lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
// 创建预览图层
lazy var previewLayer: AVCaptureVideoPreviewLayer? = {
let layer = AVCaptureVideoPreviewLayer(session: self.session)
layer.frame = UIScreen.main.bounds
return layer
}()
/****************************Storyboard 绑定方法区域****************************/
/**************************** 以下是方法区域 ****************************/
public override func viewDidLoad() {
super.viewDidLoad()
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.lastResultStr = nil
// 2.开始扫描
startScan()
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.stepAnimation()
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
public override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier { // 检查是否 nil
switch identifier {
default: break
}
}
}
/**
界面基础设置
*/
public override func setupUI() {
self.tabBarController?.tabBar.isHidden = true
/**
* 自定义 导航栏左侧 返回按钮
*/
self.customLeftBarButtonItem()
self.tabBarController?.tabBar.isHidden = true
// 启用计时器,控制每秒执行一次tickDown方法
timer = Timer.scheduledTimer(timeInterval: 0.02,
target:self,selector:#selector(Scan_Vc.stepAnimation),
userInfo:nil,repeats:true)
}
/**
绑定到viewmodel 设置
*/
public override func bindToViewModel(){
}
}
extension Scan_Vc{
// MARK: - 扫描二维码
func startScan(){
guard let deviceInput = self.deviceInput else {
return
}
// 1.判断是否能够将输入添加到会话中
if !session.canAddInput(deviceInput)
{
return
}
// 2.判断是否能够将输出添加到会话中
if !session.canAddOutput(output)
{
return
}
// 3.将输入和输出都添加到会话中
session.addInput(deviceInput)
session.addOutput(output)
// output.rectOfInterest = cropRect
// 4.设置输出能够解析的数据类型
// 注意: 设置能够解析的数据类型, 一定要在输出对象添加到会员之后设置, 否则会报错
output.metadataObjectTypes = output.availableMetadataObjectTypes
// 5.设置输出对象的代理, 只要解析成功就会通知代理
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
// 添加预览图层,必须要插入到最下层的图层
if let previewLayer = self.previewLayer{
view.layer.insertSublayer(previewLayer, at: 0)
// 6.告诉session开始扫描
session.startRunning()
}
}
@objc func stepAnimation()
{
if (!isAnimationing) {
return;
}
let maxHeight:CGFloat = self.content_V.frame.size.height
UIView.animate(withDuration: 1.4, animations: { () -> Void in
if self.isDown == true{
self.startY += 2
if self.startY >= maxHeight - 5{
self.isDown = false
}else{
self.isDown = true
}
}else{
self.startY -= 2
if self.startY <= 5{
self.isDown = true
}else{
self.isDown = false
}
}
self.scan_Line_HeightLc.constant = self.startY
}, completion:{ (value: Bool) -> Void in
})
}
func stopStepAnimating()
{
isAnimationing = false;
}
func isGetFlash()->Bool
{
if (deviceInput != nil)
{
return true
}
return false
}
/**
------闪光灯打开或关闭
*/
func changeTorch()
{
if isGetFlash()
{
do
{
try deviceInput?.device.lockForConfiguration()
var torch = false
if deviceInput?.device.torchMode == AVCaptureDevice.TorchMode.on
{
torch = false
}
else if deviceInput?.device.torchMode == AVCaptureDevice.TorchMode.off
{
torch = true
}
self.light_Btn.isSelected = torch
deviceInput?.device.torchMode = torch ? AVCaptureDevice.TorchMode.on : AVCaptureDevice.TorchMode.off
deviceInput?.device.unlockForConfiguration()
}
catch let error as NSError {
print("device.lockForConfiguration(): \(error)")
}
}
}
}
// MARK: - AVCaptureMetadataOutputObjectsDelegate
extension Scan_Vc: AVCaptureMetadataOutputObjectsDelegate
{
// 只要解析到数据就会调用
public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection){
// 检查:metadataObjects 对象不为空,并且至少包含一个元素
if metadataObjects.count == 0 {
return
}
guard let metadataObj = metadataObjects[0] as? AVMetadataMachineReadableCodeObject else {
return
}
// 获得元数据对象
// 如果元数据是二维码,则更新二维码选框大小与 label 的文本
if let stringValue = metadataObj.stringValue {
if self.lastResultStr != stringValue{
if let didScanValue_Block = self.didScanValue_Block{
didScanValue_Block(stringValue)
}else{
if stringValue.hasPrefix("https") || stringValue.hasPrefix("http") {
_ = stringValue.openURL()
}else{
self.view.toastCompletion(stringValue){ _ in
let pasteBoard = UIPasteboard.general
pasteBoard.string = stringValue
_ = self.navigationController?.popViewController(animated: true)
}
}
}
}
self.lastResultStr = stringValue
}
}
}
| 28.066434 | 151 | 0.514763 |
0e55b40461c4d76e118dbad0798f5f9d6d538717 | 706 | //
// Strings.swift
// PravdaUIKit
//
// Created by Дмитрий Матвеенко on 26.05.2020.
// Copyright © 2020 GkFoxes. All rights reserved.
//
public enum Strings: String {
// MARK: Today Module
case todayNavigationTitle = "News"
case todayTabTitle = "Today"
case moreNewsFrom = "More news from"
case triangularBullet = "‣"
// MARK: Favorites Module
case favorite = "Favorite"
case unfavorite = "Unfavorite"
case favoritesTitle = "Favorites"
// MARK: Spotlight Module
case readFullStory = "Read Full Story"
case fullStoryNotAvailable = "Full Story is not available"
// MARK: Common
case whitespace = " "
case okCapital = "OK"
case canNotOpenWebsite = "Can not open this website"
}
| 20.171429 | 59 | 0.706799 |
6ad12574dea2b932f6bc1233991907c5ab3403f8 | 2,417 | //
// XCTestAlertViewCommand.swift
// XCTestWebdriver
//
// Created by zhaoy on 21/4/17.
// Copyright © 2017 XCTestWebdriver. All rights reserved.
//
import Foundation
import Swifter
import SwiftyJSON
internal class XCTestWDSourceController: Controller {
//MARK: Controller - Protocol
static func routes() -> [(RequestRoute, RoutingCall)] {
return [(RequestRoute("/wd/hub/session/:sessionId/source", "get"), source),
(RequestRoute("/wd/hub/source", "get"), sourceWithoutSession),
(RequestRoute("/wd/hub/session/:sessionId/accessibleSource", "get"), accessiblitySource),
(RequestRoute("/wd/hub/accessibleSource", "get"), accessiblitySourceWithoutSession)]
}
static func shouldRegisterAutomatically() -> Bool {
return false
}
//MARK: Routing Logic Specification
internal static func source(request: Swifter.HttpRequest) -> Swifter.HttpResponse {
let _application = request.session?.application;
if(_application?.state == XCUIApplication.State.runningForeground ) {
let _ = _application?.query();
_application?.resolve();
let temp = _application?.tree();
return XCTestWDResponse.response(session: request.session, value: JSON(JSON(temp).rawString() ?? ""))
}
return XCTestWDResponse.response(session: request.session, value: JSON(""));
}
internal static func sourceWithoutSession(request: Swifter.HttpRequest) -> Swifter.HttpResponse {
let temp = XCTestWDSession.activeApplication()?.tree()
return XCTestWDResponse.response(session: request.session, value: JSON(temp!))
}
internal static func accessiblitySource(request: Swifter.HttpRequest) -> Swifter.HttpResponse {
let _ = request.session?.application.query()
request.session?.application.resolve()
let temp = request.session?.application.accessibilityTree()
return XCTestWDResponse.response(session: request.session, value: JSON(JSON(temp!).rawString() ?? ""))
}
internal static func accessiblitySourceWithoutSession(request: Swifter.HttpRequest) -> Swifter.HttpResponse {
let temp = XCTestWDSessionManager.singleton.checkDefaultSession().application.accessibilityTree()
return XCTestWDResponse.response(session: request.session, value: JSON(temp!))
}
}
| 42.403509 | 113 | 0.681837 |
ff6ac09145a73dc2fa510ebf559184357bac11fe | 877 | //
// xTests.swift
// xTests
//
// Created by Caner Uçar on 6.11.2018.
// Copyright © 2018 Caner Uçar. All rights reserved.
//
import XCTest
@testable import x
class xTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.057143 | 111 | 0.643101 |
2f952c393630ab401ede33dd1fbb5526969dcc79 | 621 | //
// Date+Millis.swift
// Expenses
//
// Created by Nominalista on 12/12/2021.
//
import Foundation
extension Date {
var millisSince1970: Int {
Int((timeIntervalSince1970 * 1000.0).rounded())
}
init(millis: Int) {
self = Date(timeIntervalSince1970: TimeInterval(millis / 1000))
}
}
extension Date {
var startOfDay: Date? {
let calendar = Calendar.current
return calendar.startOfDay(for: self)
}
var endOfDay: Date? {
let calendar = Calendar.current
return calendar.date(byAdding: .second, value: -1, to: self)
}
}
| 18.818182 | 71 | 0.603865 |
6a4a2feada865deef6d9ca77950de51f602696ed | 3,960 |
// https://stackoverflow.com/a/34902501/135557
class WMFWelcomeLanguageIntrinsicTableView: UITableView {
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
}
}
class WMFWelcomeLanguageTableViewController: ThemeableViewController, WMFPreferredLanguagesViewControllerDelegate, UITableViewDataSource, UITableViewDelegate {
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
languageTableView.reloadData()
moreLanguagesButton.setTitleColor(theme.colors.link, for: .normal)
}
@IBOutlet private var languageTableView:WMFWelcomeLanguageIntrinsicTableView!
@IBOutlet private var moreLanguagesButton:UIButton!
@IBOutlet private var languagesDescriptionLabel:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
languagesDescriptionLabel.text = WMFLocalizedString("welcome-languages-description", value:"We've found the following languages on your device:", comment:"Title label describing detected languages")
languageTableView.alwaysBounceVertical = false
moreLanguagesButton.setTitle(WMFLocalizedString("welcome-languages-add-or-edit-button", value:"Add or edit preferred languages", comment:"Title for button for managing languages"), for: .normal)
languageTableView.rowHeight = UITableView.automaticDimension
languageTableView.estimatedRowHeight = 30
languageTableView.register(WMFLanguageCell.wmf_classNib(), forCellReuseIdentifier: WMFLanguageCell.wmf_nibName())
updateFonts()
view.wmf_configureSubviewsForDynamicType()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UserDefaults.standard.wmf_setShowSearchLanguageBar(MWKDataStore.shared().languageLinkController.preferredLanguages.count > 1)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return MWKDataStore.shared().languageLinkController.preferredLanguages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: WMFLanguageCell.wmf_nibName(), for: indexPath) as! WMFLanguageCell
cell.collapseSideSpacing()
let langLink = MWKDataStore.shared().languageLinkController.preferredLanguages[indexPath.row]
cell.languageName = langLink.name
cell.isPrimary = indexPath.row == 0
(cell as Themeable).apply(theme: theme)
return cell
}
@IBAction func addLanguages(withSender sender: AnyObject) {
let langsVC = WMFPreferredLanguagesViewController.preferredLanguagesViewController()
langsVC.showExploreFeedCustomizationSettings = false
langsVC.delegate = self
let navC = WMFThemeableNavigationController(rootViewController: langsVC, theme: self.theme)
present(navC, animated: true, completion: nil)
}
func languagesController(_ controller: WMFPreferredLanguagesViewController, didUpdatePreferredLanguages languages:[MWKLanguageLink]){
languageTableView.reloadData()
languageTableView.layoutIfNeeded() // Needed for the content offset reset below to work
languageTableView.contentOffset = .zero
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateFonts()
}
private func updateFonts() {
moreLanguagesButton.titleLabel?.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection)
}
}
| 46.046512 | 206 | 0.736616 |
e999f1b44bc91920d1bfb8b9e27a44efaeb7a6e6 | 1,578 | //
// SWAFNParameterConstant.swift
// SalesManNetwork
//
// Created by 谢艳 on 2018/10/30.
//
import Foundation
public struct SWLogin {
public static let username = "userAccount"
public static let password = "userPass"
public static let loginPath = "/login.do"
public static let verifyCodePath = "/sw/verify/code/sendVerifyCodeByUserPhone.do"
public static let resetPasswordPath = "/sw/verify/code/findPasswdByPhone.do"
}
public struct SWPersonal {
public static let userInfoPath = "/sw/salesman/info/data/getOne.do"
public static let balancePath = "/sw/balance/getBalance.do"
public static let customerCount = "/sw/salesman/member/getCustomerCountBySalesmanId.do"
}
public struct SWItemCateogry {
public static let categoryPath = "/sw/product/category/getAllCategory.do"
}
public struct SWCustomerManagement {
public static let groupPath = "/sw/group/dataWithOne/listByPage.do"
public static let typePath = "sys/code/fc.do?key=terminalType"
public static let statusPath = "/sys/code/fc.do?key=checkState"
public static let customerPath = "/sw/group/getAllGroupAndCustomer.do"
}
public struct SWGlobal{
public static let callBack = "callBack"
public static let message = "message"
public static let status = "status"
public static let data = "data"
}
public struct SWError{
public static let networkError = "请检查网络连接"
public static let cookieExpired = "登录信息过期了"
}
public struct SWNotification{
public static let SWCookieExpiredNotification = "swCookieExpiredNotification"
}
| 33.574468 | 92 | 0.736375 |
1a9a0fc9acf5e783d320dd17746a89ec06881120 | 2,173 | //
// AppDelegate.swift
// SpinnerKit
//
// Created by Paige Sun on 2019-06-19.
// Copyright © 2019 Paige Sun. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.234043 | 285 | 0.754717 |
034b6136c6c3b25fa37cbdb321843593a441c555 | 546 | public struct Peg {
public var id: String
public var state: Bool
public var position: Point
public var toggled: Peg {
var peg = self
peg.state = !state
return peg
}
public init(_ id: String, state: Bool, position: (x: Int, y: Int)) {
self.id = id
self.state = state
self.position = Point(x: position.x, y: position.y)
}
private init(id: String, state: Bool, point: Point) {
self.id = id
self.state = state
self.position = point
}
}
| 20.222222 | 72 | 0.554945 |
903e1f9ebe46fabdf0915f3768a5b7351257f9e2 | 4,023 | import SourceKittenFramework
public struct FunctionDefaultParameterAtEndRule: ASTRule, ConfigurationProviderRule, OptInRule, AutomaticTestableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "function_default_parameter_at_end",
name: "Function Default Parameter at End",
description: "Prefer to locate parameters with defaults toward the end of the parameter list.",
kind: .idiomatic,
nonTriggeringExamples: [
Example("func foo(baz: String, bar: Int = 0) {}"),
Example("func foo(x: String, y: Int = 0, z: CGFloat = 0) {}"),
Example("func foo(bar: String, baz: Int = 0, z: () -> Void) {}"),
Example("func foo(bar: String, z: () -> Void, baz: Int = 0) {}"),
Example("func foo(bar: Int = 0) {}"),
Example("func foo() {}"),
Example("""
class A: B {
override func foo(bar: Int = 0, baz: String) {}
"""),
Example("func foo(bar: Int = 0, completion: @escaping CompletionHandler) {}"),
Example("""
func foo(a: Int, b: CGFloat = 0) {
let block = { (error: Error?) in }
}
"""),
Example("""
func foo(a: String, b: String? = nil,
c: String? = nil, d: @escaping AlertActionHandler = { _ in }) {}
""")
],
triggeringExamples: [
Example("↓func foo(bar: Int = 0, baz: String) {}")
]
)
public func validate(file: SwiftLintFile, kind: SwiftDeclarationKind,
dictionary: SourceKittenDictionary) -> [StyleViolation] {
guard SwiftDeclarationKind.functionKinds.contains(kind),
let offset = dictionary.offset,
let bodyOffset = dictionary.bodyOffset,
!dictionary.enclosedSwiftAttributes.contains(.override) else {
return []
}
let isNotClosure = { !self.isClosureParameter(dictionary: $0) }
let params = dictionary.substructure
.flatMap { subDict -> [SourceKittenDictionary] in
guard subDict.declarationKind == .varParameter else {
return []
}
return [subDict]
}
.filter(isNotClosure)
.filter { param in
guard let paramOffset = param.offset else {
return false
}
return paramOffset < bodyOffset
}
guard !params.isEmpty else {
return []
}
let containsDefaultValue = { self.isDefaultParameter(file: file, dictionary: $0) }
let defaultParams = params.filter(containsDefaultValue)
guard !defaultParams.isEmpty else {
return []
}
let lastParameters = params.suffix(defaultParams.count)
let lastParametersWithDefaultValue = lastParameters.filter(containsDefaultValue)
guard lastParameters.count != lastParametersWithDefaultValue.count else {
return []
}
return [
StyleViolation(ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset))
]
}
private func isClosureParameter(dictionary: SourceKittenDictionary) -> Bool {
guard let typeName = dictionary.typeName else {
return false
}
return typeName.contains("->") || typeName.contains("@escaping")
}
private func isDefaultParameter(file: SwiftLintFile, dictionary: SourceKittenDictionary) -> Bool {
guard let range = dictionary.byteRange.flatMap(file.stringView.byteRangeToNSRange) else {
return false
}
return regex("=").firstMatch(in: file.contents, options: [], range: range) != nil
}
}
| 37.598131 | 119 | 0.566493 |
bb1342247925cd14c48314b0fc2fe6f504ae4680 | 3,696 | //
// Copyright (c) 2019 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
@testable import AdyenDropIn
@testable import AdyenUIHost
import XCTest
class ComponentManagerTests: XCTestCase {
let dictionary = [
"storedPaymentMethods": [
storedCreditCardDictionary,
storedCreditCardDictionary,
storedPayPalDictionary,
storedBcmcDictionary
],
"paymentMethods": [
creditCardDictionary,
issuerListDictionary,
sepaDirectDebitDictionary,
bcmcCardDictionary,
applePayDictionary,
giroPayDictionaryWithOptionalDetails,
giroPayDictionaryWithNonOptionalDetails,
weChatQRDictionary,
weChatSDKDictionary,
weChatWebDictionary,
weChatMiniProgramDictionary,
bcmcMobileQR
]
]
func testLocalizationWithCustomTableName() throws {
let paymentMethods = try Coder.decode(dictionary) as PaymentMethods
let payment = Payment(amount: Payment.Amount(value: 20, currencyCode: "EUR"), countryCode: "NL")
let config = DropInComponent.PaymentMethodsConfiguration()
config.localizationParameters = LocalizationParameters(tableName: "AdyenUIHost", keySeparator: nil)
config.applePay.merchantIdentifier = Configuration.applePayMerchantIdentifier
config.applePay.summaryItems = Configuration.applePaySummaryItems
config.card.publicKey = RandomStringGenerator.generateDummyCardPublicKey()
let sut = ComponentManager(paymentMethods: paymentMethods,
payment: payment,
configuration: config,
style: DropInComponent.Style())
XCTAssertEqual(sut.components.stored.count, 4)
XCTAssertEqual(sut.components.regular.count, 6)
XCTAssertEqual(sut.components.stored.compactMap { $0 as? Localizable }.filter { $0.localizationParameters?.tableName == "AdyenUIHost" }.count, 4)
XCTAssertEqual(sut.components.regular.compactMap { $0 as? Localizable }.filter { $0.localizationParameters?.tableName == "AdyenUIHost" }.count, 4)
}
func testLocalizationWithCustomKeySeparator() throws {
let paymentMethods = try Coder.decode(dictionary) as PaymentMethods
let payment = Payment(amount: Payment.Amount(value: 20, currencyCode: "EUR"), countryCode: "NL")
let config = DropInComponent.PaymentMethodsConfiguration()
config.localizationParameters = LocalizationParameters(tableName: "AdyenUIHostCustomSeparator", keySeparator: "_")
config.applePay.merchantIdentifier = Configuration.applePayMerchantIdentifier
config.applePay.summaryItems = Configuration.applePaySummaryItems
config.card.publicKey = RandomStringGenerator.generateDummyCardPublicKey()
let sut = ComponentManager(paymentMethods: paymentMethods,
payment: payment,
configuration: config,
style: DropInComponent.Style())
XCTAssertEqual(sut.components.stored.count, 4)
XCTAssertEqual(sut.components.regular.count, 6)
XCTAssertEqual(sut.components.stored.compactMap { $0 as? Localizable }.filter { $0.localizationParameters == config.localizationParameters }.count, 4)
XCTAssertEqual(sut.components.regular.compactMap { $0 as? Localizable }.filter { $0.localizationParameters == config.localizationParameters }.count, 4)
}
}
| 48 | 159 | 0.669643 |
e2d10ad0bb7891a0f210567c178b1304769e0466 | 2,344 | //
// Plugin.swift
// CodeBaseProject
//
// Created by HaiKaito on 24/03/2022.
//
import Foundation
/// A Moya Plugin receives callbacks to perform side effects wherever a request is sent or received.
///
/// for example, a plugin may be used to
/// - log network requests
/// - hide and show a network activity indicator
/// - inject additional information into a request
protocol PluginType {
/// Called to modify a request before sending.
func prepare(_ request: URLRequest, endpoint: Endpoint) -> URLRequest
/// Called immediately before a request is sent over the network (or stubbed).
func willSend(_ request: RequestType, endpoint: Endpoint)
/// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.
// func didReceive(_ result: Result<Moya.Response, MoyaError>, endpoint: Endpoint)
/// Called to modify a result before completion.
// func process(_ result: Result<Moya.Response, MoyaError>, endpoint: Endpoint) -> Result<Moya.Response, MoyaError>
}
extension PluginType {
func prepare(_ request: URLRequest, endpoint: Endpoint) -> URLRequest { request }
func willSend(_ request: RequestType, endpoint: Endpoint) { }
// func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) { }
// func process(_ result: Result<Moya.Response, MoyaError>, target: TargetType) -> Result<Moya.Response, MoyaError> { result }
}
/// Request type used by `willSend` plugin function.
public protocol RequestType {
// Note:
//
// We use this protocol instead of the Alamofire request to avoid leaking that abstraction.
// A plugin should not know about Alamofire at all.
/// Retrieve an `NSURLRequest` representation.
var request: URLRequest? { get }
/// Additional headers appended to the request when added to the session.
var sessionHeaders: [String: String] { get }
/// Authenticates the request with a username and password.
func authenticate(username: String, password: String, persistence: URLCredential.Persistence) -> Self
/// Authenticates the request with an `NSURLCredential` instance.
func authenticate(with credential: URLCredential) -> Self
/// cURL representation of the instance.
///
/// - Returns: The cURL equivalent of the instance.
func cURLDescription(calling handler: @escaping (String) -> Void) -> Self
}
| 37.206349 | 126 | 0.738481 |
e877cc24a4084f6f704202dbe9af83548c0a96c0 | 1,709 | //
// UIImage+Extensions.swift
// Dizzy
//
// Created by ジャティン on 2019/11/15.
// Copyright © 2019 Me. All rights reserved.
//
import UIKit
// https://stackoverflow.com/questions/27092354/rotating-uiimage-in-swift/29753437
public extension UIImage {
func rotate(radians: CGFloat) -> UIImage? {
var newSize = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: CGFloat(radians)))
.size
// Trim off the extremely small float value to prevent core graphics from rounding it up
newSize.width = floor(newSize.width)
newSize.height = floor(newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
// Move origin to middle
context.translateBy(x: newSize.width/2, y: newSize.height/2)
// Rotate around middle
context.rotate(by: CGFloat(radians))
draw(in: CGRect(x: -size.width/2, y: -size.height/2, width: size.width, height: size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
| 35.604167 | 101 | 0.653013 |
1c96b66b8c5bc021185cd61b5cc4f96f9754b1c0 | 1,128 | // swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Cluster",
platforms: [
.iOS(.v8)
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "Cluster",
targets: ["Cluster"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "Cluster",
dependencies: [],
path: "Sources"
),
.testTarget(
name: "ClusterTests",
dependencies: ["Cluster"],
path: "Tests"
)
]
)
| 31.333333 | 122 | 0.583333 |
db2fd73620815abd15add3133e7b593777c15e61 | 2,247 | //
// AppDelegate.swift
// CWLKit
//
// Created by cycweeds on 07/07/2018.
// Copyright (c) 2018 cycweeds. All rights reserved.
//
import UIKit
// 这个只要一次使用 别的地方就不需要import了 swift的私有属性
@_exported import CWLKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 40.125 | 285 | 0.750779 |
fe49a2107f0e4b71ba2eaf70c6487ebf6d451aca | 2,749 | //
// CompositeDisposable.swift
// Rx
//
// Created by Krunoslav Zaher on 2/20/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
public class CompositeDisposable : DisposeBase, Disposable {
public typealias BagKey = Bag<Disposable>.KeyType
typealias State = (
disposables: RxMutableBox<Bag<Disposable>>!,
disposed: Bool
)
var lock: Lock = Lock()
var state: State = (
disposables: RxMutableBox(Bag()),
disposed: false
)
public override init() {
}
public init(_ disposable1: Disposable, _ disposable2: Disposable) {
let bag = state.disposables
bag.value.put(disposable1)
bag.value.put(disposable2)
}
public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) {
let bag = state.disposables
bag.value.put(disposable1)
bag.value.put(disposable2)
bag.value.put(disposable3)
}
public init(disposables: [Disposable]) {
let bag = state.disposables
for disposable in disposables {
bag.value.put(disposable)
}
}
public func addDisposable(disposable: Disposable) -> BagKey? {
// this should be let
// bucause of compiler bug it's var
let key = self.lock.calculateLocked { oldState -> BagKey? in
if state.disposed {
return nil
}
else {
let key = state.disposables.value.put(disposable)
return key
}
}
if key == nil {
disposable.dispose()
}
return key
}
public var count: Int {
get {
return self.lock.calculateLocked {
self.state.disposables.value.count
}
}
}
public func removeDisposable(disposeKey: BagKey) {
let disposable = self.lock.calculateLocked { Void -> Disposable? in
return state.disposables.value.removeKey(disposeKey)
}
if let disposable = disposable {
disposable.dispose()
}
}
public func dispose() {
let oldDisposables = self.lock.calculateLocked { Void -> [Disposable] in
if state.disposed {
return []
}
let disposables = state.disposables
var allValues = disposables.value.all
state.disposed = true
state.disposables = nil
return allValues
}
for d in oldDisposables {
d.dispose()
}
}
} | 25.453704 | 98 | 0.538741 |
26b62f3f4ed9860cfc7cbf3949408d3c3f2abf90 | 415 | //
// ViewController.swift
// Toolbar
//
// Created by cemal tüysüz on 12.12.2021.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func item1OnClick(_ sender: Any) {
}
@IBAction func item2OnClick(_ sender: Any) {
}
}
| 15.37037 | 58 | 0.59759 |
2267374aa8507caf906eb5687718565838268a95 | 1,657 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Whiteboard",
platforms: [.iOS(.v10)],
products: [
.library(
name: "Whiteboard",
targets: ["Whiteboard"]),
],
dependencies: [
.package(name: "DSBridge-IOS", url: "https://github.com/vince-hz/DSBridge-IOS.git", from: .init(3, 1, 0)),
.package(name: "YYModel", url: "https://github.com/vince-hz/YYModel.git", from: .init(1, 1, 0))
],
targets: [
.target(name: "Whiteboard",
dependencies: ["YYModel", "DSBridge-IOS"],
path: "Whiteboard",
exclude: [
"Classes/Model-YYKit",
"Classes/include/cpScript.sh",
"Classes/fpa"
],
sources: ["Classes"],
resources: [
.process("Resource")
],
publicHeadersPath: "Classes/include",
cSettings: .headers
)
]
)
extension Array where Element == CSetting {
static var headers: [Element] {
[
.headerSearchPath("Classes/Converter"),
.headerSearchPath("Classes/Displayer"),
.headerSearchPath("Classes/Model"),
.headerSearchPath("Classes/NativeReplayer"),
.headerSearchPath("Classes/Object"),
.headerSearchPath("Classes/Replayer"),
.headerSearchPath("Classes/Room"),
.headerSearchPath("Classes/SDK")
]
}
}
| 32.490196 | 114 | 0.526252 |
9c85d0563da510e4656ec7c13dc1ef0cbbe00d16 | 17,879 | //
// UIAutoSuggestField.swift
// UIAutoSuggestField
//
// Created by Bahadır ARSLAN on 14.03.2021.
// Copyright © 2021 Bahadır ARSLAN. All rights reserved.
//
// The origin of this library was Shyngys Kassymov's article and Objective-C code which is located at : https://github.com/chika-kasymov/UITextField_AutoSuggestion
// I ported it to Swift and added some more functionality
import Foundation
import UIKit
let DEFAULT_MAX_NUM_OF_ROWS = 5
let DEFAULT_ROW_HEIGHT = 60.0
let INSET = 20.0
private var textFieldRectOnWindowKey = 0
private var keyboardFrameBeginRectKey = 0
@objc protocol UIAutoSuggestionFieldDataSource: NSObjectProtocol {
func autoSuggestionField(_ field: UIAutoSuggestField?, tableView: UITableView?, cellForRowAtIndexPath indexPath: IndexPath?, forText text: String?) -> UITableViewCell? // 1
func autoSuggestionField(_ field: UIAutoSuggestField?, tableView: UITableView?, numberOfRowsInSection section: Int, forText text: String?) -> Int // 2
@objc optional func autoSuggestionField(_ field: UIAutoSuggestField?, textChanged text: String?) // 3
@objc optional func autoSuggestionField(_ field: UIAutoSuggestField?, tableView: UITableView?, heightForRowAtIndexPath indexPath: IndexPath?, forText text: String?) -> CGFloat // 4
@objc optional func autoSuggestionField(_ field: UIAutoSuggestField?, tableView: UITableView?, didSelectRowAtIndexPath indexPath: IndexPath?, forText text: String?) // 5
@objc optional func newItemButtonTapped(_ field: UIAutoSuggestField)
}
open class UIAutoSuggestField : UITextField, UITableViewDataSource, UITableViewDelegate {
@IBInspectable open var TableBackgroundColor: UIColor = UIColor.lightGray
@IBInspectable open var AlphaViewColor: UIColor = UIColor.gray.withAlphaComponent(0.5)
@IBInspectable open var TableAlphaBackgroundColor : UIColor = UIColor.darkGray.withAlphaComponent(0.8)
@IBInspectable open var SpinnerColor : UIColor = UIColor.orange
@IBInspectable var leftPadding: CGFloat = 0
open var showNewItemText : Bool = false
open var newItemText : String?
var showImmediately:Bool = false
var minCharsToShow:Int = 3
var maxNumberOfRows:Int = 5
var autoSuggestionDataSource:UIAutoSuggestionFieldDataSource?
open var tintedClearImage: UIImage?
var data : [SuggestItem]?
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.setupTintColor()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.setupTintColor()
}
private var tableView:UITableView?
private var tableContainerView:UIView?
private var tableAlphaView:UIView?
private var spinner:UIActivityIndicatorView?
private var alphaView:UIView?
private var emptyView:UIView?
private var textFieldRectOnWindow:CGRect?
private var keyboardFrameBeginRect:CGRect?
private var autoSuggestionIsShowing:Bool = false
private var fieldIdentifier:String?
override open func layoutSubviews() {
super.layoutSubviews()
self.tintClearImage()
}
@objc func observeTextFieldChanges() {
layer.masksToBounds = false
NotificationCenter.default.addObserver(self, selector: #selector(self.toggleAutoSuggestion(_:)), name: UITextField.textDidBeginEditingNotification, object: self)
NotificationCenter.default.addObserver(self, selector: #selector(self.toggleAutoSuggestion(_:)), name: UITextField.textDidChangeNotification, object: self)
NotificationCenter.default.addObserver(self, selector: #selector(self.hideAutoSuggestion), name: UITextField.textDidEndEditingNotification, object: self)
NotificationCenter.default.addObserver(self, selector: #selector(self.getKeyboardHeight(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
}
@objc func getKeyboardHeight(_ notification: Notification?) {
let keyboardInfo = notification?.userInfo
let keyboardFrameBegin = keyboardInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue
keyboardFrameBeginRect = keyboardFrameBegin?.cgRectValue
}
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// 2
func createSuggestionView() {
let appDelegateWindow: UIWindow? = UIApplication.shared.keyWindow
textFieldRectOnWindow = convert(bounds, to: nil)
if !(tableContainerView != nil) {
tableContainerView = UIView()
tableContainerView!.backgroundColor = TableBackgroundColor
}
if tableView == nil {
tableView = UITableView(frame: textFieldRectOnWindow!, style: .plain)
tableView?.tableFooterView = UIView(frame: CGRect.zero)
tableView?.delegate = self
tableView?.dataSource = self
}
if !(alphaView != nil) {
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
alphaView = UIView(frame: appDelegateWindow?.bounds ?? CGRect.zero)
alphaView?.isUserInteractionEnabled = true
alphaView?.backgroundColor = AlphaViewColor
alphaView?.addGestureRecognizer(tap)
appDelegateWindow?.addSubview(alphaView!)
}
tableView?.frame = textFieldRectOnWindow!
tableContainerView?.addSubview(tableView!)
tableContainerView?.frame = textFieldRectOnWindow!
DispatchQueue.main.async {
appDelegateWindow?.addSubview(self.tableContainerView!)
}
}
// 3
func showAutoSuggestion() {
if !autoSuggestionIsShowing {
createSuggestionView()
autoSuggestionIsShowing = true
}
if (spinner == nil || (spinner != nil && spinner!.isAnimating)){
reloadContents()
}
}
func createNewItemButton() -> UIButton {
let newItemButton = UIButton(frame: (tableView?.bounds)!)
newItemButton.frame.size.height = 50
newItemButton.titleLabel?.textAlignment = .center
newItemButton.titleLabel?.font = UIFont(name: "Helvetica-Medium", size: 16.0)
newItemButton.setTitleColor(.black, for: .normal)
newItemButton.setTitle(newItemText, for: .normal)
newItemButton.addTarget(self, action: #selector(newItemButtonAction), for: .touchUpInside)
return newItemButton
}
@objc func hideAutoSuggestion() {
if autoSuggestionIsShowing {
alphaView?.removeFromSuperview()
alphaView = nil
tableView?.removeFromSuperview()
tableContainerView?.removeFromSuperview()
autoSuggestionIsShowing = false
}
}
// 6
func reloadContents() {
self.updateHeight()
updateCornerRadius()
DispatchQueue.main.async {
self.checkForEmptyState()
}
DispatchQueue.main.async {
self.tableView?.reloadData()
}
//
DispatchQueue.main.async { [self] in
if(self.showNewItemText && tableView(tableView!, numberOfRowsInSection: 0) > 0) {
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: (tableView?.frame.size.width)!, height: 50))
let btn = createNewItemButton()
footerView.addSubview(btn)
tableView?.tableFooterView = btn
}
else {
tableView?.tableFooterView = UIView(frame: CGRect.zero)
}
}
}
func updateHeight() {
let numberOfResults: Int = tableView(self.tableView!, numberOfRowsInSection: 0)
let maxRowsToShow: Int = maxNumberOfRows != 0 ? maxNumberOfRows : DEFAULT_MAX_NUM_OF_ROWS
var cellHeight = DEFAULT_ROW_HEIGHT
if (tableView?.numberOfRows(inSection: 0))! > 0 {
cellHeight = Double(tableView(tableView!, heightForRowAt: IndexPath(row: 0, section: 0)))
}
var height: CGFloat = CGFloat(Double(min(maxRowsToShow, numberOfResults)) * cellHeight) // check if numberOfResults < maxRowsToShow
height = max(height, CGFloat(cellHeight)) // if 0 results, set height = `cellHeight`
if(showNewItemText) {
height += 50
}
var frame: CGRect = textFieldRectOnWindow!
if showSuggestionViewBelow() {
let maxHeight: CGFloat = UIScreen.main.bounds.size.height - (frame.origin.y + frame.size.height) - CGFloat(INSET) - keyboardFrameBeginRect!.size.height // max possible height
height = min(height, maxHeight) // set height = `maxHeight` if it's smaller than current `height`
frame.origin.y += frame.size.height
} else {
let maxHeight: CGFloat = frame.origin.y - CGFloat(INSET) // max possible height
height = min(height, maxHeight) // set height = `maxHeight` if it's smaller than current `height`
frame.origin.y -= height
}
frame.size.height = height
tableView?.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
tableContainerView?.frame = frame
}
func updateCornerRadius() {
// code snippet from SO answer (http://stackoverflow.com/a/13163693/1760199)
var corners: UIRectCorner = [.bottomLeft, .bottomRight]
if !showSuggestionViewBelow() {
corners = [.topLeft, .topRight]
}
let maskPath = UIBezierPath(roundedRect: (tableContainerView?.bounds)!, byRoundingCorners: corners, cornerRadii: CGSize(width: 6, height: 6))
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
tableContainerView?.layer.mask = maskLayer
}
// 9
func checkForEmptyState() {
if tableView(tableView!, numberOfRowsInSection: 0) == 0 {
if (emptyView == nil) {
let bgView = UIStackView(frame: tableView!.bounds)
bgView.axis = .vertical
bgView.distribution = .fillEqually
let emptyTableLabel = UILabel(frame: CGRect(x: 0, y: 0, width: (tableView?.bounds.width)!, height: 50))
emptyTableLabel.textAlignment = .center
emptyTableLabel.font = UIFont(name: "Helvetica-Medium", size: 16.0)
emptyTableLabel.textColor = UIColor.systemGray
emptyTableLabel.text = "No matches"
bgView.addArrangedSubview(emptyTableLabel)
if(showNewItemText) {
let btn = createNewItemButton()
bgView.addArrangedSubview(btn)
}
tableView?.backgroundView = bgView
} else {
tableView?.backgroundView = emptyView
}
} else {
tableView?.backgroundView = nil
}
}
@objc func newItemButtonAction(sender: UIButton!) {
if autoSuggestionDataSource!.responds(to: #selector(autoSuggestionDataSource!.newItemButtonTapped)) {
hideAutoSuggestion()
autoSuggestionDataSource?.newItemButtonTapped?(self)
}
}
// 10
func showSuggestionViewBelow() -> Bool {
let frame: CGRect = textFieldRectOnWindow!
return frame.origin.y + frame.size.height / 2.0 < (UIScreen.main.bounds.size.height - keyboardFrameBeginRect!.size.height) / 2.0
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
// 2
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return autoSuggestionDataSource!.autoSuggestionField(self, tableView: tableView, numberOfRowsInSection: section, forText: text)
}
// 3
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let implementsDatasource: Bool = autoSuggestionDataSource!.responds(to:
#selector(autoSuggestionDataSource!.autoSuggestionField(_:tableView:cellForRowAtIndexPath:forText:)))
assert(implementsDatasource, "UITextField must implement data source before using auto suggestion.")
return autoSuggestionDataSource!.autoSuggestionField(self, tableView: tableView, cellForRowAtIndexPath: indexPath, forText: text)!
}
// 4
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if autoSuggestionDataSource!.responds(to:
#selector(autoSuggestionDataSource!.autoSuggestionField(_:tableView:heightForRowAtIndexPath:forText:)))
{
return autoSuggestionDataSource!.autoSuggestionField!(self, tableView: tableView, heightForRowAtIndexPath: indexPath, forText: text)
}
return CGFloat(DEFAULT_ROW_HEIGHT)
}
// 5
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
hideAutoSuggestion()
tableView.deselectRow(at: indexPath, animated: true)
if autoSuggestionDataSource!.responds(to: #selector(autoSuggestionDataSource!.autoSuggestionField(_:tableView:didSelectRowAtIndexPath:forText:))) {
autoSuggestionDataSource!.autoSuggestionField!(self, tableView: tableView, didSelectRowAtIndexPath: indexPath, forText: text)
}
}
// 6
@objc func toggleAutoSuggestion(_ notification: Notification?) {
if showImmediately || ((text?.count)! > 0 && (text?.count)! >= minCharsToShow) {
showAutoSuggestion()
if autoSuggestionDataSource!.responds(to: #selector(autoSuggestionDataSource!.autoSuggestionField(_:textChanged:))) {
autoSuggestionDataSource!.autoSuggestionField!(self, textChanged: text)
}
} else {
hideAutoSuggestion()
}
}
func setLoading(_ loading: Bool) {
if loading {
if !(tableAlphaView != nil) {
tableAlphaView = UIView(frame: (tableView?.bounds)!)
tableAlphaView?.backgroundColor = TableAlphaBackgroundColor
tableView?.addSubview(tableAlphaView!)
spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
spinner?.center = (tableAlphaView?.center)!
spinner?.color = self.SpinnerColor
tableAlphaView?.addSubview(spinner!)
spinner?.startAnimating()
}
} else {
if (tableAlphaView != nil) {
spinner?.startAnimating()
spinner?.removeFromSuperview()
spinner = nil
tableAlphaView?.removeFromSuperview()
tableAlphaView = nil
}
}
}
// Provides left padding for images
open override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.leftViewRect(forBounds: bounds)
textRect.origin.x += leftPadding
return textRect
}
override public func canPerformAction(_ action: Selector, withSender
sender: Any?) -> Bool {
if action == #selector(UIResponderStandardEditActions.paste(_:)) {
return false
}
return super.canPerformAction(action, withSender: sender)
}
@objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {
hideAutoSuggestion()
}
}
extension UIAutoSuggestField {
func setupTintColor() {
self.borderStyle = UITextField.BorderStyle.roundedRect
self.layer.cornerRadius = 8.0
self.layer.masksToBounds = true
self.layer.borderColor = self.tintColor.cgColor
self.layer.borderWidth = 1.5
self.backgroundColor = .clear
}
private func tintClearImage() {
for view in subviews {
if view is UIButton {
let button = view as! UIButton
if let image = button.image(for: .highlighted) {
if self.tintedClearImage == nil {
tintedClearImage = self.tintImage(image: image, color: self.tintColor)
}
button.setImage(self.tintedClearImage, for: .normal)
button.setImage(self.tintedClearImage, for: .highlighted)
}
}
}
}
private func tintImage(image: UIImage, color: UIColor) -> UIImage {
let size = image.size
UIGraphicsBeginImageContextWithOptions(size, false, image.scale)
let context = UIGraphicsGetCurrentContext()
image.draw(at: .zero, blendMode: CGBlendMode.normal, alpha:1.0)
context?.setFillColor(color.cgColor)
context?.setBlendMode(CGBlendMode.sourceIn)
context?.setAlpha(1.0)
let rect = CGRect(x: CGPoint.zero.x, y: CGPoint.zero.y, width: image.size.width, height: image.size.height)
UIGraphicsGetCurrentContext()?.fill(rect)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage ?? UIImage()
}
}
| 39.381057 | 186 | 0.626657 |
ef05e15bf8e0fe949b9652ff9869887dd8e7736d | 5,562 | import SpriteKit
import Models
import Protocols
import Extensions
public class Game: SKNode {
// game stats - single source of truth for all games
private let gameStats: GameStats
// correct traffic sign for current round
private var correctTrafficSign: TrafficSign {
didSet {
correctTrafficSignImageNode.texture = SKTexture(imageNamed: correctTrafficSign.imageName)
}
}
// current traffic signs for current round
private var currentTrafficSigns: [TrafficSign] {
didSet {
guard let randomCurrentTrafficSign = currentTrafficSigns.randomElement() else { fatalError("Could not get a random element from current traffic signs.") }
correctTrafficSign = randomCurrentTrafficSign
}
}
// user interface nodes
private var progressLabel: Label!
private var correctTrafficSignImageNode: SKSpriteNode!
private var answerPossibilities: AnswerPossibilities!
private var achievements: Achievements!
// game delegate
public weak var delegate: GameDelegate?
// init
public required init(totalRounds: Int) {
gameStats = GameStats(totalRounds: totalRounds)
// shuffle traffic signs and get first three results
let shuffledTrafficSigns = trafficSigns.shuffled()
currentTrafficSigns = Array(shuffledTrafficSigns[0..<3])
// get ramdom traffic signs from shuffled which is going to be the correct one
guard let randomCurrentTrafficSign = currentTrafficSigns.randomElement() else { fatalError("Could not get a random element from current traffic signs.") }
correctTrafficSign = randomCurrentTrafficSign
// set texture of correct traffic sign image node after its initialization
defer {
correctTrafficSignImageNode.texture = SKTexture(imageNamed: correctTrafficSign.imageName)
}
super.init()
// add progress label
progressLabel = Label(text: "Question \(gameStats.roundCount + 1) of \(gameStats.totalRounds)", font: .systemFont(ofSize: 16, weight: .bold))
progressLabel.alpha = 0.5
progressLabel.position = CGPoint(x: 0, y: 353)
addChild(progressLabel)
// add title label
let titleLabel = Label(text: "What’s the meaning of\nthis traffic sign?", font: .systemFont(ofSize: 24, weight: .bold))
titleLabel.position = CGPoint(x: 0, y: 300)
addChild(titleLabel)
// add sprite node for the current traffic sign image in order for the user to know what answer to click
correctTrafficSignImageNode = SKSpriteNode()
correctTrafficSignImageNode.size = CGSize(width: 226, height: 169)
correctTrafficSignImageNode.position = CGPoint(x: 0, y: 155)
addChild(correctTrafficSignImageNode)
// add the answer possibilities after traffic signs have been initialized
answerPossibilities = AnswerPossibilities(correctTrafficSignId: correctTrafficSign.id, currentTrafficSigns: currentTrafficSigns)
addChild(answerPossibilities)
// add achievements node to inform the user about their progress in the current game
achievements = Achievements()
achievements.position = CGPoint(x: 0, y: -325)
addChild(achievements)
// set up observers triggering a method to handle tapping on an answer from answer possibilities
NotificationCenter.default.addObserver(self, selector: #selector(answerDidChoose), name: .answerNode, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// start new game
public func startNewGame() {
alpha = 1
gameStats.newGame()
achievements.update(gameStats)
progressLabel.setText("Question \(gameStats.roundCount + 1) of \(gameStats.totalRounds)")
handleNewRound()
}
// hide the node
public func hide() {
alpha = 0
}
// handle tapping on an answer from answer possibilities
@objc private func answerDidChoose(_ notification: NSNotification) {
if let id = notification.userInfo?["id"] as? Int, id == correctTrafficSign.id {
gameStats.starsCount += 1
achievements.update(gameStats)
let sound = SKAction.playSoundFileNamed("correct.mp3", waitForCompletion: false)
run(sound)
} else {
let sound = SKAction.playSoundFileNamed("bonk.mp3", waitForCompletion: false)
run(sound)
}
gameStats.newRound()
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.handleNewRound()
}
}
// fire delegate method if total rounds have been reached, otherwise start a new round
private func handleNewRound() {
progressLabel.setText("Question \(gameStats.roundCount + 1) of \(gameStats.totalRounds)")
if gameStats.roundCount == gameStats.totalRounds {
delegate?.endGame(gameStats)
} else {
let shuffledTrafficSigns = trafficSigns.shuffled()
let newTrafficSigns = Array(shuffledTrafficSigns[0..<3])
currentTrafficSigns = newTrafficSigns
answerPossibilities.startNewRound(correctTrafficSignId: correctTrafficSign.id, newTrafficSigns: newTrafficSigns)
}
}
}
| 38.09589 | 166 | 0.65552 |
2155a136f8b9e376b9ba7541ae8059891890f428 | 2,960 | //
// Index.xcplaygroundpage
// SwiftWT
//
// Created by devedbox.
//
//: #  Swift Basic
/*:
`Swift`是`Apple`于`2014`年推出的新语言,于`2015`年开源,经过几年的发展,现在`Swift`已经越来越成熟。`Swift`不仅可以用来开发基于`CocoaTouch`的`iOS`应用,还能作为一门脚本语言和后端语言,在开源社区,已有了很多比较成熟的后端开发框架,如[`Perfect`](https://github.com/PerfectlySoft/Perfect)、[`Vapor`](https://github.com/vapor/vapor)、[`Kitura`](https://github.com/IBM-Swift/Kitura)、[`Taylor`](https://github.com/izqui/Taylor)等,但是生态发展还不成熟,而且官方的推动也需要时间;`Swift`设计就是一门脚本语言,虽然不像`Python`、`Ruby`等语言发展成熟,但是`Swift`作为脚本语言还是有很深的潜力,像现在很多工具都是`Swift`开发的,如`SwiftLint`、`Carthage`等工具.
`Swift`是一门静态语言,所有类型、属性和方法都必须在编译期确定下来;`Swift`是一门强类型语言,每一个变量、实例都有自己的类型,而且对类型特别敏感,没有类型容错;`Swift`是一门高效的语言,所有方法的分发都是在编译期确定的,没有`OC`的运行时发送消息的机制,同时,这也让`Swift`变得安全,大部分错误都能在编译期暴露出来,非常适合构建大型项目,能够很大程度的提升代码的健壮性;`Swift`还支持多种编程范式,如函数式编程、泛型编程等,这些编程范式可以大大提高开发效率;但是`Swift`也有很多诟病,从`Swift` `1.0`到现在的`Swift` `4.0`,一直在更改API和添加特性,这让`Swift`变得越来越复杂和难以理解,但是,从经验来看,很多特性确实能够节省很多的开发时间,所以,还得辩证的看待这个事情.
`Swift`拥有很多特性,上述已经列举部分,引用`Swift`官方文档,`Swift`是一门现代语言,体现在以下几点:
- 安全.
- **`Fast`**:译为高效,但是也包含字面意义的快速;对比很多脚本语言甚至主流的`Java`等语言,`Swift`在高效这个层面做得确实很到位.
- 可读、易使用:`Swift`吸取了很多语言的语法和编程习惯,大杂烩.
`Swift`除了支出很多编程语言最基本的东西之外,还引入了很多特性,如:模块化(去除头文件)、命名空间以及借鉴的其他语言的很多特性,这些特性可以帮助我们编写很多高效、优雅的代码,相比很多C(特别是OC)家族的语言,`Swift`还有如下特点:
- 函数、闭包是一等公民
- 支持元组类型和函数多返回值(`Python`)
- 泛型编程:泛型协议、泛型类型、泛型方法
- 函数式编程:标准库内建方法:`map`、`filter`、`reduce`等
- 快速简洁的集合类型遍历语法
- 结构体可以支持方法定义、类型扩展、实现协议
- 强大的错误处理机制
- 高级流程控制语法,如:`guard`、`do`、`defer`、`repeat`
*/
/*:
## 平台支持
- `MacOS`
- `Linux`
*/
/*:
- Callout(Swift.org Projects):
The Swift language is managed as a collection of projects, each with its own repositories. The current list of projects includes:
- The [Swift compiler](https://swift.org/compiler-stdlib/) command line tool
- The [standard library](https://swift.org/compiler-stdlib/) bundled as part of the language
- [Core libraries](https://swift.org/core-libraries/) that provide higher-level functionality
- The [LLDB debugger](https://swift.org/lldb/) which includes the Swift REPL
- The [Swift package manager](https://swift.org/package-manager/) for distributing and building Swift source code
- [Xcode playground support](https://swift.org/lldb/#xcode-playground-support) to enable playgrounds in Xcode.
*/
/*:
## 目录
[`Swift`基础部分](Basics)
[基本运算符](Basic%20Operators)
[字符与字符串](Strings%20and%20Characters)
[集合类型](Collection%20Types)
[控制流](Control%20Flow)
[函数](Functions)
[闭包](Closures)
[枚举](Enumerations)
[类和结构体](Structures%20and%20Classes)
[属性](Properties)
[方法](Methods)
[下标](Subscripts)
[继承](Inheritance)
[构造器](Initialization)
[销毁器](Deinitialization)
[可选链](Optional%20Chaining)
[错误处理](Error%20Handling)
[类型嵌套](Nested%20Types)
[扩展](Extensions)
[协议](Protocols)
[泛型](Generics)
[内存管理](Automatic%20Reference%20Counting)
[内存安全](Memory%20Safety)
[访问控制](Access%20Control)
[高级运算符](Advanced%20Operators)
*/
//: [下一页](@next)
| 30.204082 | 474 | 0.73277 |
1ca5ac564c3db15a139784737af9366cc7fc0cc4 | 414 |
infix operator >>>: infixl9
public func >>> <A, B, C>(_ f: @escaping (A) -> B, _ g: @escaping (B) -> C) -> (A) -> C {
return {
return g(f($0))
}
}
public func bind<A, B, C>(_ f: (A) -> Result<B, C>, _ t: Result<A, C>) -> Result<B, C> where C: Swift.Error {
switch t {
case .success(let value):
return f(value)
case .failure(let error):
return .failure(error)
}
}
| 23 | 109 | 0.509662 |
79144e003f0f00dbd0127e1f8108e89c54b05653 | 2,295 | //
// ContentView.swift
// CarBode
//
// Created by narongrit kanhanoi on 7/10/2562 BE.
// Copyright © 2562 PAM. All rights reserved.
//
import SwiftUI
import AVFoundation
public struct CBScanner: UIViewRepresentable {
public typealias OnFound = (BarcodeData)->Void
public typealias UIViewType = CameraPreview
@Binding
public var supportBarcode: [AVMetadataObject.ObjectType]
@Binding
public var torchLightIsOn:Bool
@Binding
public var scanInterval: Double
@Binding
public var cameraPosition:AVCaptureDevice.Position
@Binding
public var mockBarCode: BarcodeData
public var onFound: OnFound?
public init(supportBarcode:Binding<[AVMetadataObject.ObjectType]> ,
torchLightIsOn: Binding<Bool> = .constant(false),
scanInterval: Binding<Double> = .constant(3.0),
cameraPosition: Binding<AVCaptureDevice.Position> = .constant(.back),
mockBarCode: Binding<BarcodeData> = .constant(BarcodeData(value: "barcode value", type: .qr)),
onFound: @escaping OnFound
) {
_torchLightIsOn = torchLightIsOn
_supportBarcode = supportBarcode
_scanInterval = scanInterval
_cameraPosition = cameraPosition
_mockBarCode = mockBarCode
self.onFound = onFound
}
public func makeUIView(context: UIViewRepresentableContext<CBScanner>) -> CBScanner.UIViewType {
let view = CameraPreview()
view.scanInterval = scanInterval
view.supportBarcode = supportBarcode
view.setupScanner()
view.onFound = onFound
return view
}
public static func dismantleUIView(_ uiView: CameraPreview, coordinator: ()) {
uiView.session?.stopRunning()
}
public func updateUIView(_ uiView: CameraPreview, context: UIViewRepresentableContext<CBScanner>) {
uiView.setTorchLight(isOn: torchLightIsOn)
uiView.setCamera(position: cameraPosition)
uiView.scanInterval = scanInterval
uiView.setSupportedBarcode(supportBarcode: supportBarcode)
uiView.setContentHuggingPriority(.defaultHigh, for: .vertical)
uiView.setContentHuggingPriority(.defaultLow, for: .horizontal)
uiView.updateCameraView()
}
}
| 29.805195 | 103 | 0.684096 |
235c57e7ae5ddfd057fb45ff7c5cd7f41f7c14f6 | 7,648 | //
// TextList2View.swift
// SampleApp
//
// Created by jin kim on 2019/11/06.
// Copyright © 2019 SK Telecom Co., Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import NuguAgents
import NuguUIKit
final class TextList2View: DisplayView {
@IBOutlet private weak var textList2TableView: UITableView!
private var textList2Items: [TextList2Template.Item]?
private var badgeNumber: Bool?
private var toggleStyle: DisplayCommonTemplate.Common.ToggleStyle?
override var displayPayload: Data? {
didSet {
guard let payloadData = displayPayload,
let displayItem = try? JSONDecoder().decode(TextList2Template.self, from: payloadData) else { return }
// Set backgroundColor
backgroundColor = UIColor.backgroundColor(rgbHexString: displayItem.background?.color)
// Set title
titleView.setData(titleData: displayItem.title)
titleView.onCloseButtonClick = { [weak self] in
self?.onCloseButtonClick?()
}
// Set sub title
if let subIconUrl = displayItem.title.subicon?.sources.first?.url {
subIconImageView.loadImage(from: subIconUrl)
subIconImageView.isHidden = false
} else {
subIconImageView.isHidden = true
}
subTitleLabel.setDisplayText(displayText: displayItem.title.subtext)
subTitleContainerView.isHidden = (displayItem.title.subtext == nil)
textList2TableView.tableHeaderView = (displayItem.title.subtext == nil) ? nil : subTitleContainerView
textList2Items = displayItem.listItems
textList2TableView.reloadData()
// Set content button
contentButton.setTitle(displayItem.title.button?.text, for: .normal)
switch displayItem.title.button?.eventType {
case .elementSelected:
contentButtonEventType = .elementSelected(token: displayItem.title.button?.token, postback: displayItem.title.button?.postback)
case .textInput:
contentButtonEventType = .textInput(textInput: displayItem.title.button?.textInput)
default:
break
}
contentButtonContainerView.isHidden = (displayItem.title.button == nil)
textList2TableView.tableFooterView = (displayItem.title.button == nil) ? nil : contentButtonContainerView
// Set chips data (grammarGuide)
idleBar.chipsData = displayItem.grammarGuide?.compactMap({ (grammarGuide) -> NuguChipsButton.NuguChipsButtonType in
return .normal(text: grammarGuide)
}) ?? []
badgeNumber = displayItem.badgeNumber
toggleStyle = displayItem.toggleStyle
textList2TableView.contentInset.bottom = 60
}
}
override func loadFromXib() {
// swiftlint:disable force_cast
let view = Bundle.main.loadNibNamed("TextList2View", owner: self)?.first as! UIView
// swiftlint:enable force_cast
view.frame = bounds
addSubview(view)
textList2TableView.register(UINib(nibName: "TextList2ViewCell", bundle: nil), forCellReuseIdentifier: "TextList2ViewCell")
}
}
extension TextList2View: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return textList2Items?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// swiftlint:disable force_cast
let textList2ViewCell = tableView.dequeueReusableCell(withIdentifier: "TextList2ViewCell") as! TextList2ViewCell
// swiftlint:enable force_cast
if let badgeNumber = badgeNumber,
badgeNumber == true {
textList2ViewCell.configure(badgeNumber: String(indexPath.row + 1), item: textList2Items?[indexPath.row], toggleStyle: toggleStyle)
} else {
textList2ViewCell.configure(badgeNumber: nil, item: textList2Items?[indexPath.row], toggleStyle: toggleStyle)
}
textList2ViewCell.onToggleSelect = { [weak self] token in
self?.onItemSelect?(.elementSelected(token: token, postback: nil))
}
return textList2ViewCell
}
}
extension TextList2View: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch textList2Items?[indexPath.row].eventType {
case .elementSelected:
onItemSelect?(DisplayItemEventType.elementSelected(token: textList2Items?[indexPath.row].token, postback: nil))
case .textInput:
onItemSelect?(DisplayItemEventType.textInput(token: textList2Items?[indexPath.row].token, textInput: textList2Items?[indexPath.row].textInput))
default:
break
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
idleBar.lineViewIsHidden(hidden: Int(scrollView.contentOffset.y + scrollView.frame.size.height) >= Int(scrollView.contentSize.height))
}
}
extension TextList2View: DisplayControllable {
func visibleTokenList() -> [String]? {
return textList2TableView.visibleCells.map { [weak self] (cell) -> String? in
guard let indexPath = self?.textList2TableView.indexPath(for: cell),
let item = self?.textList2Items?[indexPath.row] else {
return nil
}
return item.token
}.compactMap { $0 }
}
func scroll(direction: DisplayControlPayload.Direction) -> Bool {
guard let textList2Items = textList2Items else {
return false
}
let visibleCellsCount = textList2TableView.visibleCells.count
switch direction {
case .previous:
guard let topCell = textList2TableView.visibleCells.first,
let topCellRowIndex = textList2TableView.indexPath(for: topCell)?.row else {
return false
}
let previousAnchorIndex = max(topCellRowIndex - visibleCellsCount, 0)
textList2TableView.scrollToRow(at: IndexPath(row: previousAnchorIndex, section: 0), at: .top, animated: true)
return true
case .next:
let lastCellRowIndex = textList2Items.count - 1
guard let lastCell = textList2TableView.visibleCells.last,
let lastVisibleCellRowIndex = textList2TableView.indexPath(for: lastCell)?.row,
lastCellRowIndex > lastVisibleCellRowIndex else {
return false
}
let nextAnchorIndex = min(lastVisibleCellRowIndex + visibleCellsCount, lastCellRowIndex)
textList2TableView.scrollToRow(at: IndexPath(row: nextAnchorIndex, section: 0), at: .bottom, animated: true)
return true
}
}
}
| 42.966292 | 155 | 0.647228 |
8fd8a3758ce3d19d28208632efc35717fa37e023 | 1,589 | //
// PaperPlaneIcon.swift
// EssentialIcons
//
// Created by Kauna Mohammed on 03/12/2018.
// Copyright © 2018 Kauna Mohammed. All rights reserved.
//
import UIKit
class PaperPlaneIcon: UIView {
public var lineWidth: CGFloat = 1 {
didSet {
iconLayer.lineWidth = lineWidth
setNeedsDisplay()
}
}
public var color: UIColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) {
didSet {
iconLayer.strokeColor = color.cgColor
setNeedsDisplay()
}
}
private lazy var iconLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.fillColor = UIColor.clear.cgColor
layer.lineJoin = .miter
return layer
}()
override func draw(_ rect: CGRect) {
super.draw(rect)
let height = rect.size.height
let width = rect.size.width
let halfHeight = height / 2
let halfWidth = width / 2
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: height))
path.addLine(to: CGPoint(x: halfWidth, y: 0))
path.addLine(to: CGPoint(x: width, y: height))
path.addLine(to: CGPoint(x: 0, y: height))
path.move(to: CGPoint(x: halfWidth, y: height))
path.addLine(to: CGPoint(x: halfWidth, y: halfHeight))
iconLayer.path = path
}
override func layoutSubviews() {
super.layoutSubviews()
layer.addSublayer(iconLayer)
transform = CGAffineTransform(rotationAngle: .pi / 4)
}
}
| 26.04918 | 84 | 0.571429 |
23bf0b273c2be0405145229f1da3b62e3b02dcff | 412 | //
// Olimar.swift
// SSBUNotes
//
// Created by maxence on 15/12/2021.
//
import UIKit
extension CharacterData
{
static let olimar = Character(
id: 42,
url_name: "olimar",
name: "Olimar",
background_color: UIColor(named: "olimar_background_color") ?? .black,
icon: UIImage(named: "olimar_icon") ?? UIImage(),
image: UIImage(named: "olimar_image") ?? UIImage(),
note: ""
)
}
| 18.727273 | 74 | 0.633495 |
ab99f14f3c5b07e81a4d55a57edfa8416c1ed081 | 6,759 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import NIOCore
import NIOPosix
import NIOTLS
import NIOSSL
class ClientSNITests: XCTestCase {
static var cert: NIOSSLCertificate!
static var key: NIOSSLPrivateKey!
override class func setUp() {
super.setUp()
let (cert, key) = generateSelfSignedCert()
NIOSSLIntegrationTest.cert = cert
NIOSSLIntegrationTest.key = key
}
private func configuredSSLContext() throws -> NIOSSLContext {
var config = TLSConfiguration.makeServerConfiguration(
certificateChain: [.certificate(NIOSSLIntegrationTest.cert)],
privateKey: .privateKey(NIOSSLIntegrationTest.key)
)
config.trustRoots = .certificates([NIOSSLIntegrationTest.cert])
let context = try NIOSSLContext(configuration: config)
return context
}
private func assertSniResult(sniField: String?, expectedResult: SNIResult) throws {
let context = try configuredSSLContext()
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
try? group.syncShutdownGracefully()
}
let sniPromise: EventLoopPromise<SNIResult> = group.next().makePromise()
let sniHandler = ByteToMessageHandler(SNIHandler {
sniPromise.succeed($0)
return group.next().makeSucceededFuture(())
})
let serverChannel = try serverTLSChannel(context: context, preHandlers: [sniHandler], postHandlers: [], group: group)
defer {
_ = try? serverChannel.close().wait()
}
let clientChannel = try clientTLSChannel(context: context,
preHandlers: [],
postHandlers: [],
group: group,
connectingTo: serverChannel.localAddress!,
serverHostname: sniField)
defer {
_ = try? clientChannel.close().wait()
}
let sniResult = try sniPromise.futureResult.wait()
XCTAssertEqual(sniResult, expectedResult)
}
func testSNIIsTransmitted() throws {
try assertSniResult(sniField: "httpbin.org", expectedResult: .hostname("httpbin.org"))
}
func testNoSNILeadsToNoExtension() throws {
try assertSniResult(sniField: nil, expectedResult: .fallback)
}
func testSNIIsRejectedForIPv4Addresses() throws {
let context = try configuredSSLContext()
let testString = "192.168.0.1"
XCTAssertThrowsError(try NIOSSLClientTLSProvider<ClientBootstrap>(context: context, serverHostname: testString)) { error in
XCTAssertEqual(.cannotUseIPAddressInSNI, error as? NIOSSLExtraError)
}
XCTAssertThrowsError(try NIOSSLClientHandler(context: context, serverHostname: testString)){ error in
XCTAssertEqual(.cannotUseIPAddressInSNI, error as? NIOSSLExtraError)
}
}
func testSNIIsRejectedForIPv6Addresses() throws {
let context = try configuredSSLContext()
let testString = "fe80::200:f8ff:fe21:67cf"
XCTAssertThrowsError(try NIOSSLClientTLSProvider<ClientBootstrap>(context: context, serverHostname: testString)) { error in
XCTAssertEqual(.cannotUseIPAddressInSNI, error as? NIOSSLExtraError)
}
XCTAssertThrowsError(try NIOSSLClientHandler(context: context, serverHostname: testString)){ error in
XCTAssertEqual(.cannotUseIPAddressInSNI, error as? NIOSSLExtraError)
}
}
func testSNIIsRejectedForEmptyHostname() throws {
let context = try configuredSSLContext()
let testString = ""
XCTAssertThrowsError(try NIOSSLClientTLSProvider<ClientBootstrap>(context: context, serverHostname: testString)) { error in
XCTAssertEqual(.invalidSNIHostname, error as? NIOSSLExtraError)
}
XCTAssertThrowsError(try NIOSSLClientHandler(context: context, serverHostname: testString)){ error in
XCTAssertEqual(.invalidSNIHostname, error as? NIOSSLExtraError)
}
}
func testSNIIsRejectedForTooLongHostname() throws {
let context = try configuredSSLContext()
let testString = String(repeating: "x", count: 256)
XCTAssertThrowsError(try NIOSSLClientTLSProvider<ClientBootstrap>(context: context, serverHostname: testString)) { error in
XCTAssertEqual(.invalidSNIHostname, error as? NIOSSLExtraError)
}
XCTAssertThrowsError(try NIOSSLClientHandler(context: context, serverHostname: testString)){ error in
XCTAssertEqual(.invalidSNIHostname, error as? NIOSSLExtraError)
}
}
func testSNIIsRejectedFor0Byte() throws {
let context = try configuredSSLContext()
let testString = String(UnicodeScalar(0)!)
XCTAssertThrowsError(try NIOSSLClientTLSProvider<ClientBootstrap>(context: context, serverHostname: testString)) { error in
XCTAssertEqual(.invalidSNIHostname, error as? NIOSSLExtraError)
}
XCTAssertThrowsError(try NIOSSLClientHandler(context: context, serverHostname: testString)) { error in
XCTAssertEqual(.invalidSNIHostname, error as? NIOSSLExtraError)
}
}
func testSNIIsNotRejectedForAnyOfTheFirst1000CodeUnits() throws {
let context = try configuredSSLContext()
for testString in (1...Int(1000)).compactMap({ UnicodeScalar($0).map({ String($0) })}) {
XCTAssertNoThrow(try NIOSSLClientHandler(context: context, serverHostname: testString))
XCTAssertNoThrow(try NIOSSLClientTLSProvider<ClientBootstrap>(context: context, serverHostname: testString))
}
}
func testSNIIsNotRejectedForVeryWeirdCharacters() throws {
let context = try configuredSSLContext()
let testString = "😎🥶💥🏴👩💻"
XCTAssertLessThanOrEqual(testString.utf8.count, 255) // just to check we didn't make this too large.
XCTAssertNoThrow(try NIOSSLClientHandler(context: context, serverHostname: testString))
XCTAssertNoThrow(try NIOSSLClientTLSProvider<ClientBootstrap>(context: context, serverHostname: testString))
}
}
| 41.722222 | 131 | 0.656458 |
4ac3ed13c44a5485b07616e84439ad0de8e0806b | 48,785 | //
// ResourceProxy.swift
// HealthSoftware
//
// Generated from FHIR 4.0.1-9346c8cc45
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
public enum ResourceProxy: FHIRType {
case account(Account)
case activityDefinition(ActivityDefinition)
case adverseEvent(AdverseEvent)
case allergyIntolerance(AllergyIntolerance)
case appointment(Appointment)
case appointmentResponse(AppointmentResponse)
case auditEvent(AuditEvent)
case basic(Basic)
case binary(Binary)
case biologicallyDerivedProduct(BiologicallyDerivedProduct)
case bodyStructure(BodyStructure)
case bundle(Bundle)
case capabilityStatement(CapabilityStatement)
case carePlan(CarePlan)
case careTeam(CareTeam)
case catalogEntry(CatalogEntry)
case chargeItem(ChargeItem)
case chargeItemDefinition(ChargeItemDefinition)
case claim(Claim)
case claimResponse(ClaimResponse)
case clinicalImpression(ClinicalImpression)
case codeSystem(CodeSystem)
case communication(Communication)
case communicationRequest(CommunicationRequest)
case compartmentDefinition(CompartmentDefinition)
case composition(Composition)
case conceptMap(ConceptMap)
case condition(Condition)
case consent(Consent)
case contract(Contract)
case coverage(Coverage)
case coverageEligibilityRequest(CoverageEligibilityRequest)
case coverageEligibilityResponse(CoverageEligibilityResponse)
case detectedIssue(DetectedIssue)
case device(Device)
case deviceDefinition(DeviceDefinition)
case deviceMetric(DeviceMetric)
case deviceRequest(DeviceRequest)
case deviceUseStatement(DeviceUseStatement)
case diagnosticReport(DiagnosticReport)
case documentManifest(DocumentManifest)
case documentReference(DocumentReference)
case domainResource(DomainResource)
case effectEvidenceSynthesis(EffectEvidenceSynthesis)
case encounter(Encounter)
case endpoint(Endpoint)
case enrollmentRequest(EnrollmentRequest)
case enrollmentResponse(EnrollmentResponse)
case episodeOfCare(EpisodeOfCare)
case eventDefinition(EventDefinition)
case evidence(Evidence)
case evidenceVariable(EvidenceVariable)
case exampleScenario(ExampleScenario)
case explanationOfBenefit(ExplanationOfBenefit)
case familyMemberHistory(FamilyMemberHistory)
case flag(Flag)
case goal(Goal)
case graphDefinition(GraphDefinition)
case group(Group)
case guidanceResponse(GuidanceResponse)
case healthcareService(HealthcareService)
case imagingStudy(ImagingStudy)
case immunization(Immunization)
case immunizationEvaluation(ImmunizationEvaluation)
case immunizationRecommendation(ImmunizationRecommendation)
case implementationGuide(ImplementationGuide)
case insurancePlan(InsurancePlan)
case invoice(Invoice)
case library(Library)
case linkage(Linkage)
case list(List)
case location(Location)
case measure(Measure)
case measureReport(MeasureReport)
case media(Media)
case medication(Medication)
case medicationAdministration(MedicationAdministration)
case medicationDispense(MedicationDispense)
case medicationKnowledge(MedicationKnowledge)
case medicationRequest(MedicationRequest)
case medicationStatement(MedicationStatement)
case medicinalProduct(MedicinalProduct)
case medicinalProductAuthorization(MedicinalProductAuthorization)
case medicinalProductContraindication(MedicinalProductContraindication)
case medicinalProductIndication(MedicinalProductIndication)
case medicinalProductIngredient(MedicinalProductIngredient)
case medicinalProductInteraction(MedicinalProductInteraction)
case medicinalProductManufactured(MedicinalProductManufactured)
case medicinalProductPackaged(MedicinalProductPackaged)
case medicinalProductPharmaceutical(MedicinalProductPharmaceutical)
case medicinalProductUndesirableEffect(MedicinalProductUndesirableEffect)
case messageDefinition(MessageDefinition)
case messageHeader(MessageHeader)
case molecularSequence(MolecularSequence)
case namingSystem(NamingSystem)
case nutritionOrder(NutritionOrder)
case observation(Observation)
case observationDefinition(ObservationDefinition)
case operationDefinition(OperationDefinition)
case operationOutcome(OperationOutcome)
case organization(Organization)
case organizationAffiliation(OrganizationAffiliation)
case parameters(Parameters)
case patient(Patient)
case paymentNotice(PaymentNotice)
case paymentReconciliation(PaymentReconciliation)
case person(Person)
case planDefinition(PlanDefinition)
case practitioner(Practitioner)
case practitionerRole(PractitionerRole)
case procedure(Procedure)
case provenance(Provenance)
case questionnaire(Questionnaire)
case questionnaireResponse(QuestionnaireResponse)
case relatedPerson(RelatedPerson)
case requestGroup(RequestGroup)
case researchDefinition(ResearchDefinition)
case researchElementDefinition(ResearchElementDefinition)
case researchStudy(ResearchStudy)
case researchSubject(ResearchSubject)
case resource(Resource)
case riskAssessment(RiskAssessment)
case riskEvidenceSynthesis(RiskEvidenceSynthesis)
case schedule(Schedule)
case searchParameter(SearchParameter)
case serviceRequest(ServiceRequest)
case slot(Slot)
case specimen(Specimen)
case specimenDefinition(SpecimenDefinition)
case structureDefinition(StructureDefinition)
case structureMap(StructureMap)
case subscription(Subscription)
case substance(Substance)
case substanceNucleicAcid(SubstanceNucleicAcid)
case substancePolymer(SubstancePolymer)
case substanceProtein(SubstanceProtein)
case substanceReferenceInformation(SubstanceReferenceInformation)
case substanceSourceMaterial(SubstanceSourceMaterial)
case substanceSpecification(SubstanceSpecification)
case supplyDelivery(SupplyDelivery)
case supplyRequest(SupplyRequest)
case task(Task)
case terminologyCapabilities(TerminologyCapabilities)
case testReport(TestReport)
case testScript(TestScript)
case valueSet(ValueSet)
case verificationResult(VerificationResult)
case visionPrescription(VisionPrescription)
case unrecognized(Resource)
public var resourceType: String {
switch self {
case .account:
return "Account"
case .activityDefinition:
return "ActivityDefinition"
case .adverseEvent:
return "AdverseEvent"
case .allergyIntolerance:
return "AllergyIntolerance"
case .appointment:
return "Appointment"
case .appointmentResponse:
return "AppointmentResponse"
case .auditEvent:
return "AuditEvent"
case .basic:
return "Basic"
case .binary:
return "Binary"
case .biologicallyDerivedProduct:
return "BiologicallyDerivedProduct"
case .bodyStructure:
return "BodyStructure"
case .bundle:
return "Bundle"
case .capabilityStatement:
return "CapabilityStatement"
case .carePlan:
return "CarePlan"
case .careTeam:
return "CareTeam"
case .catalogEntry:
return "CatalogEntry"
case .chargeItem:
return "ChargeItem"
case .chargeItemDefinition:
return "ChargeItemDefinition"
case .claim:
return "Claim"
case .claimResponse:
return "ClaimResponse"
case .clinicalImpression:
return "ClinicalImpression"
case .codeSystem:
return "CodeSystem"
case .communication:
return "Communication"
case .communicationRequest:
return "CommunicationRequest"
case .compartmentDefinition:
return "CompartmentDefinition"
case .composition:
return "Composition"
case .conceptMap:
return "ConceptMap"
case .condition:
return "Condition"
case .consent:
return "Consent"
case .contract:
return "Contract"
case .coverage:
return "Coverage"
case .coverageEligibilityRequest:
return "CoverageEligibilityRequest"
case .coverageEligibilityResponse:
return "CoverageEligibilityResponse"
case .detectedIssue:
return "DetectedIssue"
case .device:
return "Device"
case .deviceDefinition:
return "DeviceDefinition"
case .deviceMetric:
return "DeviceMetric"
case .deviceRequest:
return "DeviceRequest"
case .deviceUseStatement:
return "DeviceUseStatement"
case .diagnosticReport:
return "DiagnosticReport"
case .documentManifest:
return "DocumentManifest"
case .documentReference:
return "DocumentReference"
case .domainResource:
return "DomainResource"
case .effectEvidenceSynthesis:
return "EffectEvidenceSynthesis"
case .encounter:
return "Encounter"
case .endpoint:
return "Endpoint"
case .enrollmentRequest:
return "EnrollmentRequest"
case .enrollmentResponse:
return "EnrollmentResponse"
case .episodeOfCare:
return "EpisodeOfCare"
case .eventDefinition:
return "EventDefinition"
case .evidence:
return "Evidence"
case .evidenceVariable:
return "EvidenceVariable"
case .exampleScenario:
return "ExampleScenario"
case .explanationOfBenefit:
return "ExplanationOfBenefit"
case .familyMemberHistory:
return "FamilyMemberHistory"
case .flag:
return "Flag"
case .goal:
return "Goal"
case .graphDefinition:
return "GraphDefinition"
case .group:
return "Group"
case .guidanceResponse:
return "GuidanceResponse"
case .healthcareService:
return "HealthcareService"
case .imagingStudy:
return "ImagingStudy"
case .immunization:
return "Immunization"
case .immunizationEvaluation:
return "ImmunizationEvaluation"
case .immunizationRecommendation:
return "ImmunizationRecommendation"
case .implementationGuide:
return "ImplementationGuide"
case .insurancePlan:
return "InsurancePlan"
case .invoice:
return "Invoice"
case .library:
return "Library"
case .linkage:
return "Linkage"
case .list:
return "List"
case .location:
return "Location"
case .measure:
return "Measure"
case .measureReport:
return "MeasureReport"
case .media:
return "Media"
case .medication:
return "Medication"
case .medicationAdministration:
return "MedicationAdministration"
case .medicationDispense:
return "MedicationDispense"
case .medicationKnowledge:
return "MedicationKnowledge"
case .medicationRequest:
return "MedicationRequest"
case .medicationStatement:
return "MedicationStatement"
case .medicinalProduct:
return "MedicinalProduct"
case .medicinalProductAuthorization:
return "MedicinalProductAuthorization"
case .medicinalProductContraindication:
return "MedicinalProductContraindication"
case .medicinalProductIndication:
return "MedicinalProductIndication"
case .medicinalProductIngredient:
return "MedicinalProductIngredient"
case .medicinalProductInteraction:
return "MedicinalProductInteraction"
case .medicinalProductManufactured:
return "MedicinalProductManufactured"
case .medicinalProductPackaged:
return "MedicinalProductPackaged"
case .medicinalProductPharmaceutical:
return "MedicinalProductPharmaceutical"
case .medicinalProductUndesirableEffect:
return "MedicinalProductUndesirableEffect"
case .messageDefinition:
return "MessageDefinition"
case .messageHeader:
return "MessageHeader"
case .molecularSequence:
return "MolecularSequence"
case .namingSystem:
return "NamingSystem"
case .nutritionOrder:
return "NutritionOrder"
case .observation:
return "Observation"
case .observationDefinition:
return "ObservationDefinition"
case .operationDefinition:
return "OperationDefinition"
case .operationOutcome:
return "OperationOutcome"
case .organization:
return "Organization"
case .organizationAffiliation:
return "OrganizationAffiliation"
case .parameters:
return "Parameters"
case .patient:
return "Patient"
case .paymentNotice:
return "PaymentNotice"
case .paymentReconciliation:
return "PaymentReconciliation"
case .person:
return "Person"
case .planDefinition:
return "PlanDefinition"
case .practitioner:
return "Practitioner"
case .practitionerRole:
return "PractitionerRole"
case .procedure:
return "Procedure"
case .provenance:
return "Provenance"
case .questionnaire:
return "Questionnaire"
case .questionnaireResponse:
return "QuestionnaireResponse"
case .relatedPerson:
return "RelatedPerson"
case .requestGroup:
return "RequestGroup"
case .researchDefinition:
return "ResearchDefinition"
case .researchElementDefinition:
return "ResearchElementDefinition"
case .researchStudy:
return "ResearchStudy"
case .researchSubject:
return "ResearchSubject"
case .resource:
return "Resource"
case .riskAssessment:
return "RiskAssessment"
case .riskEvidenceSynthesis:
return "RiskEvidenceSynthesis"
case .schedule:
return "Schedule"
case .searchParameter:
return "SearchParameter"
case .serviceRequest:
return "ServiceRequest"
case .slot:
return "Slot"
case .specimen:
return "Specimen"
case .specimenDefinition:
return "SpecimenDefinition"
case .structureDefinition:
return "StructureDefinition"
case .structureMap:
return "StructureMap"
case .subscription:
return "Subscription"
case .substance:
return "Substance"
case .substanceNucleicAcid:
return "SubstanceNucleicAcid"
case .substancePolymer:
return "SubstancePolymer"
case .substanceProtein:
return "SubstanceProtein"
case .substanceReferenceInformation:
return "SubstanceReferenceInformation"
case .substanceSourceMaterial:
return "SubstanceSourceMaterial"
case .substanceSpecification:
return "SubstanceSpecification"
case .supplyDelivery:
return "SupplyDelivery"
case .supplyRequest:
return "SupplyRequest"
case .task:
return "Task"
case .terminologyCapabilities:
return "TerminologyCapabilities"
case .testReport:
return "TestReport"
case .testScript:
return "TestScript"
case .valueSet:
return "ValueSet"
case .verificationResult:
return "VerificationResult"
case .visionPrescription:
return "VisionPrescription"
case .unrecognized:
return "Resource"
}
}
// MARK: -
public init(with resource: Resource) {
switch type(of: resource).resourceType {
case .account:
self = .account(resource as! Account)
case .activityDefinition:
self = .activityDefinition(resource as! ActivityDefinition)
case .adverseEvent:
self = .adverseEvent(resource as! AdverseEvent)
case .allergyIntolerance:
self = .allergyIntolerance(resource as! AllergyIntolerance)
case .appointment:
self = .appointment(resource as! Appointment)
case .appointmentResponse:
self = .appointmentResponse(resource as! AppointmentResponse)
case .auditEvent:
self = .auditEvent(resource as! AuditEvent)
case .basic:
self = .basic(resource as! Basic)
case .binary:
self = .binary(resource as! Binary)
case .biologicallyDerivedProduct:
self = .biologicallyDerivedProduct(resource as! BiologicallyDerivedProduct)
case .bodyStructure:
self = .bodyStructure(resource as! BodyStructure)
case .bundle:
self = .bundle(resource as! Bundle)
case .capabilityStatement:
self = .capabilityStatement(resource as! CapabilityStatement)
case .carePlan:
self = .carePlan(resource as! CarePlan)
case .careTeam:
self = .careTeam(resource as! CareTeam)
case .catalogEntry:
self = .catalogEntry(resource as! CatalogEntry)
case .chargeItem:
self = .chargeItem(resource as! ChargeItem)
case .chargeItemDefinition:
self = .chargeItemDefinition(resource as! ChargeItemDefinition)
case .claim:
self = .claim(resource as! Claim)
case .claimResponse:
self = .claimResponse(resource as! ClaimResponse)
case .clinicalImpression:
self = .clinicalImpression(resource as! ClinicalImpression)
case .codeSystem:
self = .codeSystem(resource as! CodeSystem)
case .communication:
self = .communication(resource as! Communication)
case .communicationRequest:
self = .communicationRequest(resource as! CommunicationRequest)
case .compartmentDefinition:
self = .compartmentDefinition(resource as! CompartmentDefinition)
case .composition:
self = .composition(resource as! Composition)
case .conceptMap:
self = .conceptMap(resource as! ConceptMap)
case .condition:
self = .condition(resource as! Condition)
case .consent:
self = .consent(resource as! Consent)
case .contract:
self = .contract(resource as! Contract)
case .coverage:
self = .coverage(resource as! Coverage)
case .coverageEligibilityRequest:
self = .coverageEligibilityRequest(resource as! CoverageEligibilityRequest)
case .coverageEligibilityResponse:
self = .coverageEligibilityResponse(resource as! CoverageEligibilityResponse)
case .detectedIssue:
self = .detectedIssue(resource as! DetectedIssue)
case .device:
self = .device(resource as! Device)
case .deviceDefinition:
self = .deviceDefinition(resource as! DeviceDefinition)
case .deviceMetric:
self = .deviceMetric(resource as! DeviceMetric)
case .deviceRequest:
self = .deviceRequest(resource as! DeviceRequest)
case .deviceUseStatement:
self = .deviceUseStatement(resource as! DeviceUseStatement)
case .diagnosticReport:
self = .diagnosticReport(resource as! DiagnosticReport)
case .documentManifest:
self = .documentManifest(resource as! DocumentManifest)
case .documentReference:
self = .documentReference(resource as! DocumentReference)
case .domainResource:
self = .domainResource(resource as! DomainResource)
case .effectEvidenceSynthesis:
self = .effectEvidenceSynthesis(resource as! EffectEvidenceSynthesis)
case .encounter:
self = .encounter(resource as! Encounter)
case .endpoint:
self = .endpoint(resource as! Endpoint)
case .enrollmentRequest:
self = .enrollmentRequest(resource as! EnrollmentRequest)
case .enrollmentResponse:
self = .enrollmentResponse(resource as! EnrollmentResponse)
case .episodeOfCare:
self = .episodeOfCare(resource as! EpisodeOfCare)
case .eventDefinition:
self = .eventDefinition(resource as! EventDefinition)
case .evidence:
self = .evidence(resource as! Evidence)
case .evidenceVariable:
self = .evidenceVariable(resource as! EvidenceVariable)
case .exampleScenario:
self = .exampleScenario(resource as! ExampleScenario)
case .explanationOfBenefit:
self = .explanationOfBenefit(resource as! ExplanationOfBenefit)
case .familyMemberHistory:
self = .familyMemberHistory(resource as! FamilyMemberHistory)
case .flag:
self = .flag(resource as! Flag)
case .goal:
self = .goal(resource as! Goal)
case .graphDefinition:
self = .graphDefinition(resource as! GraphDefinition)
case .group:
self = .group(resource as! Group)
case .guidanceResponse:
self = .guidanceResponse(resource as! GuidanceResponse)
case .healthcareService:
self = .healthcareService(resource as! HealthcareService)
case .imagingStudy:
self = .imagingStudy(resource as! ImagingStudy)
case .immunization:
self = .immunization(resource as! Immunization)
case .immunizationEvaluation:
self = .immunizationEvaluation(resource as! ImmunizationEvaluation)
case .immunizationRecommendation:
self = .immunizationRecommendation(resource as! ImmunizationRecommendation)
case .implementationGuide:
self = .implementationGuide(resource as! ImplementationGuide)
case .insurancePlan:
self = .insurancePlan(resource as! InsurancePlan)
case .invoice:
self = .invoice(resource as! Invoice)
case .library:
self = .library(resource as! Library)
case .linkage:
self = .linkage(resource as! Linkage)
case .list:
self = .list(resource as! List)
case .location:
self = .location(resource as! Location)
case .measure:
self = .measure(resource as! Measure)
case .measureReport:
self = .measureReport(resource as! MeasureReport)
case .media:
self = .media(resource as! Media)
case .medication:
self = .medication(resource as! Medication)
case .medicationAdministration:
self = .medicationAdministration(resource as! MedicationAdministration)
case .medicationDispense:
self = .medicationDispense(resource as! MedicationDispense)
case .medicationKnowledge:
self = .medicationKnowledge(resource as! MedicationKnowledge)
case .medicationRequest:
self = .medicationRequest(resource as! MedicationRequest)
case .medicationStatement:
self = .medicationStatement(resource as! MedicationStatement)
case .medicinalProduct:
self = .medicinalProduct(resource as! MedicinalProduct)
case .medicinalProductAuthorization:
self = .medicinalProductAuthorization(resource as! MedicinalProductAuthorization)
case .medicinalProductContraindication:
self = .medicinalProductContraindication(resource as! MedicinalProductContraindication)
case .medicinalProductIndication:
self = .medicinalProductIndication(resource as! MedicinalProductIndication)
case .medicinalProductIngredient:
self = .medicinalProductIngredient(resource as! MedicinalProductIngredient)
case .medicinalProductInteraction:
self = .medicinalProductInteraction(resource as! MedicinalProductInteraction)
case .medicinalProductManufactured:
self = .medicinalProductManufactured(resource as! MedicinalProductManufactured)
case .medicinalProductPackaged:
self = .medicinalProductPackaged(resource as! MedicinalProductPackaged)
case .medicinalProductPharmaceutical:
self = .medicinalProductPharmaceutical(resource as! MedicinalProductPharmaceutical)
case .medicinalProductUndesirableEffect:
self = .medicinalProductUndesirableEffect(resource as! MedicinalProductUndesirableEffect)
case .messageDefinition:
self = .messageDefinition(resource as! MessageDefinition)
case .messageHeader:
self = .messageHeader(resource as! MessageHeader)
case .molecularSequence:
self = .molecularSequence(resource as! MolecularSequence)
case .namingSystem:
self = .namingSystem(resource as! NamingSystem)
case .nutritionOrder:
self = .nutritionOrder(resource as! NutritionOrder)
case .observation:
self = .observation(resource as! Observation)
case .observationDefinition:
self = .observationDefinition(resource as! ObservationDefinition)
case .operationDefinition:
self = .operationDefinition(resource as! OperationDefinition)
case .operationOutcome:
self = .operationOutcome(resource as! OperationOutcome)
case .organization:
self = .organization(resource as! Organization)
case .organizationAffiliation:
self = .organizationAffiliation(resource as! OrganizationAffiliation)
case .parameters:
self = .parameters(resource as! Parameters)
case .patient:
self = .patient(resource as! Patient)
case .paymentNotice:
self = .paymentNotice(resource as! PaymentNotice)
case .paymentReconciliation:
self = .paymentReconciliation(resource as! PaymentReconciliation)
case .person:
self = .person(resource as! Person)
case .planDefinition:
self = .planDefinition(resource as! PlanDefinition)
case .practitioner:
self = .practitioner(resource as! Practitioner)
case .practitionerRole:
self = .practitionerRole(resource as! PractitionerRole)
case .procedure:
self = .procedure(resource as! Procedure)
case .provenance:
self = .provenance(resource as! Provenance)
case .questionnaire:
self = .questionnaire(resource as! Questionnaire)
case .questionnaireResponse:
self = .questionnaireResponse(resource as! QuestionnaireResponse)
case .relatedPerson:
self = .relatedPerson(resource as! RelatedPerson)
case .requestGroup:
self = .requestGroup(resource as! RequestGroup)
case .researchDefinition:
self = .researchDefinition(resource as! ResearchDefinition)
case .researchElementDefinition:
self = .researchElementDefinition(resource as! ResearchElementDefinition)
case .researchStudy:
self = .researchStudy(resource as! ResearchStudy)
case .researchSubject:
self = .researchSubject(resource as! ResearchSubject)
case .resource:
self = .resource(resource)
case .riskAssessment:
self = .riskAssessment(resource as! RiskAssessment)
case .riskEvidenceSynthesis:
self = .riskEvidenceSynthesis(resource as! RiskEvidenceSynthesis)
case .schedule:
self = .schedule(resource as! Schedule)
case .searchParameter:
self = .searchParameter(resource as! SearchParameter)
case .serviceRequest:
self = .serviceRequest(resource as! ServiceRequest)
case .slot:
self = .slot(resource as! Slot)
case .specimen:
self = .specimen(resource as! Specimen)
case .specimenDefinition:
self = .specimenDefinition(resource as! SpecimenDefinition)
case .structureDefinition:
self = .structureDefinition(resource as! StructureDefinition)
case .structureMap:
self = .structureMap(resource as! StructureMap)
case .subscription:
self = .subscription(resource as! Subscription)
case .substance:
self = .substance(resource as! Substance)
case .substanceNucleicAcid:
self = .substanceNucleicAcid(resource as! SubstanceNucleicAcid)
case .substancePolymer:
self = .substancePolymer(resource as! SubstancePolymer)
case .substanceProtein:
self = .substanceProtein(resource as! SubstanceProtein)
case .substanceReferenceInformation:
self = .substanceReferenceInformation(resource as! SubstanceReferenceInformation)
case .substanceSourceMaterial:
self = .substanceSourceMaterial(resource as! SubstanceSourceMaterial)
case .substanceSpecification:
self = .substanceSpecification(resource as! SubstanceSpecification)
case .supplyDelivery:
self = .supplyDelivery(resource as! SupplyDelivery)
case .supplyRequest:
self = .supplyRequest(resource as! SupplyRequest)
case .task:
self = .task(resource as! Task)
case .terminologyCapabilities:
self = .terminologyCapabilities(resource as! TerminologyCapabilities)
case .testReport:
self = .testReport(resource as! TestReport)
case .testScript:
self = .testScript(resource as! TestScript)
case .valueSet:
self = .valueSet(resource as! ValueSet)
case .verificationResult:
self = .verificationResult(resource as! VerificationResult)
case .visionPrescription:
self = .visionPrescription(resource as! VisionPrescription)
}
}
public func get() -> Resource {
switch self {
case .account(let resource):
return resource
case .activityDefinition(let resource):
return resource
case .adverseEvent(let resource):
return resource
case .allergyIntolerance(let resource):
return resource
case .appointment(let resource):
return resource
case .appointmentResponse(let resource):
return resource
case .auditEvent(let resource):
return resource
case .basic(let resource):
return resource
case .binary(let resource):
return resource
case .biologicallyDerivedProduct(let resource):
return resource
case .bodyStructure(let resource):
return resource
case .bundle(let resource):
return resource
case .capabilityStatement(let resource):
return resource
case .carePlan(let resource):
return resource
case .careTeam(let resource):
return resource
case .catalogEntry(let resource):
return resource
case .chargeItem(let resource):
return resource
case .chargeItemDefinition(let resource):
return resource
case .claim(let resource):
return resource
case .claimResponse(let resource):
return resource
case .clinicalImpression(let resource):
return resource
case .codeSystem(let resource):
return resource
case .communication(let resource):
return resource
case .communicationRequest(let resource):
return resource
case .compartmentDefinition(let resource):
return resource
case .composition(let resource):
return resource
case .conceptMap(let resource):
return resource
case .condition(let resource):
return resource
case .consent(let resource):
return resource
case .contract(let resource):
return resource
case .coverage(let resource):
return resource
case .coverageEligibilityRequest(let resource):
return resource
case .coverageEligibilityResponse(let resource):
return resource
case .detectedIssue(let resource):
return resource
case .device(let resource):
return resource
case .deviceDefinition(let resource):
return resource
case .deviceMetric(let resource):
return resource
case .deviceRequest(let resource):
return resource
case .deviceUseStatement(let resource):
return resource
case .diagnosticReport(let resource):
return resource
case .documentManifest(let resource):
return resource
case .documentReference(let resource):
return resource
case .domainResource(let resource):
return resource
case .effectEvidenceSynthesis(let resource):
return resource
case .encounter(let resource):
return resource
case .endpoint(let resource):
return resource
case .enrollmentRequest(let resource):
return resource
case .enrollmentResponse(let resource):
return resource
case .episodeOfCare(let resource):
return resource
case .eventDefinition(let resource):
return resource
case .evidence(let resource):
return resource
case .evidenceVariable(let resource):
return resource
case .exampleScenario(let resource):
return resource
case .explanationOfBenefit(let resource):
return resource
case .familyMemberHistory(let resource):
return resource
case .flag(let resource):
return resource
case .goal(let resource):
return resource
case .graphDefinition(let resource):
return resource
case .group(let resource):
return resource
case .guidanceResponse(let resource):
return resource
case .healthcareService(let resource):
return resource
case .imagingStudy(let resource):
return resource
case .immunization(let resource):
return resource
case .immunizationEvaluation(let resource):
return resource
case .immunizationRecommendation(let resource):
return resource
case .implementationGuide(let resource):
return resource
case .insurancePlan(let resource):
return resource
case .invoice(let resource):
return resource
case .library(let resource):
return resource
case .linkage(let resource):
return resource
case .list(let resource):
return resource
case .location(let resource):
return resource
case .measure(let resource):
return resource
case .measureReport(let resource):
return resource
case .media(let resource):
return resource
case .medication(let resource):
return resource
case .medicationAdministration(let resource):
return resource
case .medicationDispense(let resource):
return resource
case .medicationKnowledge(let resource):
return resource
case .medicationRequest(let resource):
return resource
case .medicationStatement(let resource):
return resource
case .medicinalProduct(let resource):
return resource
case .medicinalProductAuthorization(let resource):
return resource
case .medicinalProductContraindication(let resource):
return resource
case .medicinalProductIndication(let resource):
return resource
case .medicinalProductIngredient(let resource):
return resource
case .medicinalProductInteraction(let resource):
return resource
case .medicinalProductManufactured(let resource):
return resource
case .medicinalProductPackaged(let resource):
return resource
case .medicinalProductPharmaceutical(let resource):
return resource
case .medicinalProductUndesirableEffect(let resource):
return resource
case .messageDefinition(let resource):
return resource
case .messageHeader(let resource):
return resource
case .molecularSequence(let resource):
return resource
case .namingSystem(let resource):
return resource
case .nutritionOrder(let resource):
return resource
case .observation(let resource):
return resource
case .observationDefinition(let resource):
return resource
case .operationDefinition(let resource):
return resource
case .operationOutcome(let resource):
return resource
case .organization(let resource):
return resource
case .organizationAffiliation(let resource):
return resource
case .parameters(let resource):
return resource
case .patient(let resource):
return resource
case .paymentNotice(let resource):
return resource
case .paymentReconciliation(let resource):
return resource
case .person(let resource):
return resource
case .planDefinition(let resource):
return resource
case .practitioner(let resource):
return resource
case .practitionerRole(let resource):
return resource
case .procedure(let resource):
return resource
case .provenance(let resource):
return resource
case .questionnaire(let resource):
return resource
case .questionnaireResponse(let resource):
return resource
case .relatedPerson(let resource):
return resource
case .requestGroup(let resource):
return resource
case .researchDefinition(let resource):
return resource
case .researchElementDefinition(let resource):
return resource
case .researchStudy(let resource):
return resource
case .researchSubject(let resource):
return resource
case .resource(let resource):
return resource
case .riskAssessment(let resource):
return resource
case .riskEvidenceSynthesis(let resource):
return resource
case .schedule(let resource):
return resource
case .searchParameter(let resource):
return resource
case .serviceRequest(let resource):
return resource
case .slot(let resource):
return resource
case .specimen(let resource):
return resource
case .specimenDefinition(let resource):
return resource
case .structureDefinition(let resource):
return resource
case .structureMap(let resource):
return resource
case .subscription(let resource):
return resource
case .substance(let resource):
return resource
case .substanceNucleicAcid(let resource):
return resource
case .substancePolymer(let resource):
return resource
case .substanceProtein(let resource):
return resource
case .substanceReferenceInformation(let resource):
return resource
case .substanceSourceMaterial(let resource):
return resource
case .substanceSpecification(let resource):
return resource
case .supplyDelivery(let resource):
return resource
case .supplyRequest(let resource):
return resource
case .task(let resource):
return resource
case .terminologyCapabilities(let resource):
return resource
case .testReport(let resource):
return resource
case .testScript(let resource):
return resource
case .valueSet(let resource):
return resource
case .verificationResult(let resource):
return resource
case .visionPrescription(let resource):
return resource
case .unrecognized(let resource):
return resource
}
}
public func get<T: Resource>(if type: T.Type) -> T? {
guard let resource = get() as? T else {
return nil
}
return resource
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case resourceType
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
switch try container.decode(String.self, forKey: .resourceType) {
case "Account":
self = .account(try Account(from: decoder))
case "ActivityDefinition":
self = .activityDefinition(try ActivityDefinition(from: decoder))
case "AdverseEvent":
self = .adverseEvent(try AdverseEvent(from: decoder))
case "AllergyIntolerance":
self = .allergyIntolerance(try AllergyIntolerance(from: decoder))
case "Appointment":
self = .appointment(try Appointment(from: decoder))
case "AppointmentResponse":
self = .appointmentResponse(try AppointmentResponse(from: decoder))
case "AuditEvent":
self = .auditEvent(try AuditEvent(from: decoder))
case "Basic":
self = .basic(try Basic(from: decoder))
case "Binary":
self = .binary(try Binary(from: decoder))
case "BiologicallyDerivedProduct":
self = .biologicallyDerivedProduct(try BiologicallyDerivedProduct(from: decoder))
case "BodyStructure":
self = .bodyStructure(try BodyStructure(from: decoder))
case "Bundle":
self = .bundle(try Bundle(from: decoder))
case "CapabilityStatement":
self = .capabilityStatement(try CapabilityStatement(from: decoder))
case "CarePlan":
self = .carePlan(try CarePlan(from: decoder))
case "CareTeam":
self = .careTeam(try CareTeam(from: decoder))
case "CatalogEntry":
self = .catalogEntry(try CatalogEntry(from: decoder))
case "ChargeItem":
self = .chargeItem(try ChargeItem(from: decoder))
case "ChargeItemDefinition":
self = .chargeItemDefinition(try ChargeItemDefinition(from: decoder))
case "Claim":
self = .claim(try Claim(from: decoder))
case "ClaimResponse":
self = .claimResponse(try ClaimResponse(from: decoder))
case "ClinicalImpression":
self = .clinicalImpression(try ClinicalImpression(from: decoder))
case "CodeSystem":
self = .codeSystem(try CodeSystem(from: decoder))
case "Communication":
self = .communication(try Communication(from: decoder))
case "CommunicationRequest":
self = .communicationRequest(try CommunicationRequest(from: decoder))
case "CompartmentDefinition":
self = .compartmentDefinition(try CompartmentDefinition(from: decoder))
case "Composition":
self = .composition(try Composition(from: decoder))
case "ConceptMap":
self = .conceptMap(try ConceptMap(from: decoder))
case "Condition":
self = .condition(try Condition(from: decoder))
case "Consent":
self = .consent(try Consent(from: decoder))
case "Contract":
self = .contract(try Contract(from: decoder))
case "Coverage":
self = .coverage(try Coverage(from: decoder))
case "CoverageEligibilityRequest":
self = .coverageEligibilityRequest(try CoverageEligibilityRequest(from: decoder))
case "CoverageEligibilityResponse":
self = .coverageEligibilityResponse(try CoverageEligibilityResponse(from: decoder))
case "DetectedIssue":
self = .detectedIssue(try DetectedIssue(from: decoder))
case "Device":
self = .device(try Device(from: decoder))
case "DeviceDefinition":
self = .deviceDefinition(try DeviceDefinition(from: decoder))
case "DeviceMetric":
self = .deviceMetric(try DeviceMetric(from: decoder))
case "DeviceRequest":
self = .deviceRequest(try DeviceRequest(from: decoder))
case "DeviceUseStatement":
self = .deviceUseStatement(try DeviceUseStatement(from: decoder))
case "DiagnosticReport":
self = .diagnosticReport(try DiagnosticReport(from: decoder))
case "DocumentManifest":
self = .documentManifest(try DocumentManifest(from: decoder))
case "DocumentReference":
self = .documentReference(try DocumentReference(from: decoder))
case "DomainResource":
self = .domainResource(try DomainResource(from: decoder))
case "EffectEvidenceSynthesis":
self = .effectEvidenceSynthesis(try EffectEvidenceSynthesis(from: decoder))
case "Encounter":
self = .encounter(try Encounter(from: decoder))
case "Endpoint":
self = .endpoint(try Endpoint(from: decoder))
case "EnrollmentRequest":
self = .enrollmentRequest(try EnrollmentRequest(from: decoder))
case "EnrollmentResponse":
self = .enrollmentResponse(try EnrollmentResponse(from: decoder))
case "EpisodeOfCare":
self = .episodeOfCare(try EpisodeOfCare(from: decoder))
case "EventDefinition":
self = .eventDefinition(try EventDefinition(from: decoder))
case "Evidence":
self = .evidence(try Evidence(from: decoder))
case "EvidenceVariable":
self = .evidenceVariable(try EvidenceVariable(from: decoder))
case "ExampleScenario":
self = .exampleScenario(try ExampleScenario(from: decoder))
case "ExplanationOfBenefit":
self = .explanationOfBenefit(try ExplanationOfBenefit(from: decoder))
case "FamilyMemberHistory":
self = .familyMemberHistory(try FamilyMemberHistory(from: decoder))
case "Flag":
self = .flag(try Flag(from: decoder))
case "Goal":
self = .goal(try Goal(from: decoder))
case "GraphDefinition":
self = .graphDefinition(try GraphDefinition(from: decoder))
case "Group":
self = .group(try Group(from: decoder))
case "GuidanceResponse":
self = .guidanceResponse(try GuidanceResponse(from: decoder))
case "HealthcareService":
self = .healthcareService(try HealthcareService(from: decoder))
case "ImagingStudy":
self = .imagingStudy(try ImagingStudy(from: decoder))
case "Immunization":
self = .immunization(try Immunization(from: decoder))
case "ImmunizationEvaluation":
self = .immunizationEvaluation(try ImmunizationEvaluation(from: decoder))
case "ImmunizationRecommendation":
self = .immunizationRecommendation(try ImmunizationRecommendation(from: decoder))
case "ImplementationGuide":
self = .implementationGuide(try ImplementationGuide(from: decoder))
case "InsurancePlan":
self = .insurancePlan(try InsurancePlan(from: decoder))
case "Invoice":
self = .invoice(try Invoice(from: decoder))
case "Library":
self = .library(try Library(from: decoder))
case "Linkage":
self = .linkage(try Linkage(from: decoder))
case "List":
self = .list(try List(from: decoder))
case "Location":
self = .location(try Location(from: decoder))
case "Measure":
self = .measure(try Measure(from: decoder))
case "MeasureReport":
self = .measureReport(try MeasureReport(from: decoder))
case "Media":
self = .media(try Media(from: decoder))
case "Medication":
self = .medication(try Medication(from: decoder))
case "MedicationAdministration":
self = .medicationAdministration(try MedicationAdministration(from: decoder))
case "MedicationDispense":
self = .medicationDispense(try MedicationDispense(from: decoder))
case "MedicationKnowledge":
self = .medicationKnowledge(try MedicationKnowledge(from: decoder))
case "MedicationRequest":
self = .medicationRequest(try MedicationRequest(from: decoder))
case "MedicationStatement":
self = .medicationStatement(try MedicationStatement(from: decoder))
case "MedicinalProduct":
self = .medicinalProduct(try MedicinalProduct(from: decoder))
case "MedicinalProductAuthorization":
self = .medicinalProductAuthorization(try MedicinalProductAuthorization(from: decoder))
case "MedicinalProductContraindication":
self = .medicinalProductContraindication(try MedicinalProductContraindication(from: decoder))
case "MedicinalProductIndication":
self = .medicinalProductIndication(try MedicinalProductIndication(from: decoder))
case "MedicinalProductIngredient":
self = .medicinalProductIngredient(try MedicinalProductIngredient(from: decoder))
case "MedicinalProductInteraction":
self = .medicinalProductInteraction(try MedicinalProductInteraction(from: decoder))
case "MedicinalProductManufactured":
self = .medicinalProductManufactured(try MedicinalProductManufactured(from: decoder))
case "MedicinalProductPackaged":
self = .medicinalProductPackaged(try MedicinalProductPackaged(from: decoder))
case "MedicinalProductPharmaceutical":
self = .medicinalProductPharmaceutical(try MedicinalProductPharmaceutical(from: decoder))
case "MedicinalProductUndesirableEffect":
self = .medicinalProductUndesirableEffect(try MedicinalProductUndesirableEffect(from: decoder))
case "MessageDefinition":
self = .messageDefinition(try MessageDefinition(from: decoder))
case "MessageHeader":
self = .messageHeader(try MessageHeader(from: decoder))
case "MolecularSequence":
self = .molecularSequence(try MolecularSequence(from: decoder))
case "NamingSystem":
self = .namingSystem(try NamingSystem(from: decoder))
case "NutritionOrder":
self = .nutritionOrder(try NutritionOrder(from: decoder))
case "Observation":
self = .observation(try Observation(from: decoder))
case "ObservationDefinition":
self = .observationDefinition(try ObservationDefinition(from: decoder))
case "OperationDefinition":
self = .operationDefinition(try OperationDefinition(from: decoder))
case "OperationOutcome":
self = .operationOutcome(try OperationOutcome(from: decoder))
case "Organization":
self = .organization(try Organization(from: decoder))
case "OrganizationAffiliation":
self = .organizationAffiliation(try OrganizationAffiliation(from: decoder))
case "Parameters":
self = .parameters(try Parameters(from: decoder))
case "Patient":
self = .patient(try Patient(from: decoder))
case "PaymentNotice":
self = .paymentNotice(try PaymentNotice(from: decoder))
case "PaymentReconciliation":
self = .paymentReconciliation(try PaymentReconciliation(from: decoder))
case "Person":
self = .person(try Person(from: decoder))
case "PlanDefinition":
self = .planDefinition(try PlanDefinition(from: decoder))
case "Practitioner":
self = .practitioner(try Practitioner(from: decoder))
case "PractitionerRole":
self = .practitionerRole(try PractitionerRole(from: decoder))
case "Procedure":
self = .procedure(try Procedure(from: decoder))
case "Provenance":
self = .provenance(try Provenance(from: decoder))
case "Questionnaire":
self = .questionnaire(try Questionnaire(from: decoder))
case "QuestionnaireResponse":
self = .questionnaireResponse(try QuestionnaireResponse(from: decoder))
case "RelatedPerson":
self = .relatedPerson(try RelatedPerson(from: decoder))
case "RequestGroup":
self = .requestGroup(try RequestGroup(from: decoder))
case "ResearchDefinition":
self = .researchDefinition(try ResearchDefinition(from: decoder))
case "ResearchElementDefinition":
self = .researchElementDefinition(try ResearchElementDefinition(from: decoder))
case "ResearchStudy":
self = .researchStudy(try ResearchStudy(from: decoder))
case "ResearchSubject":
self = .researchSubject(try ResearchSubject(from: decoder))
case "Resource":
self = .resource(try Resource(from: decoder))
case "RiskAssessment":
self = .riskAssessment(try RiskAssessment(from: decoder))
case "RiskEvidenceSynthesis":
self = .riskEvidenceSynthesis(try RiskEvidenceSynthesis(from: decoder))
case "Schedule":
self = .schedule(try Schedule(from: decoder))
case "SearchParameter":
self = .searchParameter(try SearchParameter(from: decoder))
case "ServiceRequest":
self = .serviceRequest(try ServiceRequest(from: decoder))
case "Slot":
self = .slot(try Slot(from: decoder))
case "Specimen":
self = .specimen(try Specimen(from: decoder))
case "SpecimenDefinition":
self = .specimenDefinition(try SpecimenDefinition(from: decoder))
case "StructureDefinition":
self = .structureDefinition(try StructureDefinition(from: decoder))
case "StructureMap":
self = .structureMap(try StructureMap(from: decoder))
case "Subscription":
self = .subscription(try Subscription(from: decoder))
case "Substance":
self = .substance(try Substance(from: decoder))
case "SubstanceNucleicAcid":
self = .substanceNucleicAcid(try SubstanceNucleicAcid(from: decoder))
case "SubstancePolymer":
self = .substancePolymer(try SubstancePolymer(from: decoder))
case "SubstanceProtein":
self = .substanceProtein(try SubstanceProtein(from: decoder))
case "SubstanceReferenceInformation":
self = .substanceReferenceInformation(try SubstanceReferenceInformation(from: decoder))
case "SubstanceSourceMaterial":
self = .substanceSourceMaterial(try SubstanceSourceMaterial(from: decoder))
case "SubstanceSpecification":
self = .substanceSpecification(try SubstanceSpecification(from: decoder))
case "SupplyDelivery":
self = .supplyDelivery(try SupplyDelivery(from: decoder))
case "SupplyRequest":
self = .supplyRequest(try SupplyRequest(from: decoder))
case "Task":
self = .task(try Task(from: decoder))
case "TerminologyCapabilities":
self = .terminologyCapabilities(try TerminologyCapabilities(from: decoder))
case "TestReport":
self = .testReport(try TestReport(from: decoder))
case "TestScript":
self = .testScript(try TestScript(from: decoder))
case "ValueSet":
self = .valueSet(try ValueSet(from: decoder))
case "VerificationResult":
self = .verificationResult(try VerificationResult(from: decoder))
case "VisionPrescription":
self = .visionPrescription(try VisionPrescription(from: decoder))
default:
self = .unrecognized(try Resource(from: decoder))
}
}
public func encode(to encoder: Encoder) throws {
try get().encode(to: encoder)
}
} | 34.771917 | 98 | 0.768248 |
9c49a1bdcedfd66285661375a1fd70b4a58d3f92 | 3,056 | //
// CollapsibleTableViewController.swift
// ios-swift-collapsible-table-section
//
// Created by Yong Su on 5/30/16.
// Copyright © 2016 Yong Su. All rights reserved.
//
import UIKit
//
// MARK: - View Controller
//
class CollapsibleTableViewController: UITableViewController {
var sections = sectionsData
override func viewDidLoad() {
super.viewDidLoad()
// Auto resizing the height of the cell
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableView.automaticDimension
self.title = "Apple Products"
}
}
//
// MARK: - View Controller DataSource and Delegate
//
extension CollapsibleTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].collapsed ? 0 : sections[section].items.count
}
// Cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CollapsibleTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as? CollapsibleTableViewCell ??
CollapsibleTableViewCell(style: .default, reuseIdentifier: "cell")
let item: Item = sections[indexPath.section].items[indexPath.row]
cell.nameLabel.text = item.name
cell.detailLabel.text = item.detail
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
// Header
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as? CollapsibleTableViewHeader ?? CollapsibleTableViewHeader(reuseIdentifier: "header")
header.titleLabel.text = sections[section].name
header.arrowLabel.text = ">"
header.setCollapsed(sections[section].collapsed)
header.section = section
header.delegate = self
return header
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44.0
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1.0
}
}
//
// MARK: - Section Header Delegate
//
extension CollapsibleTableViewController: CollapsibleTableViewHeaderDelegate {
func toggleSection(_ header: CollapsibleTableViewHeader, section: Int) {
let collapsed = !sections[section].collapsed
// Toggle collapse
sections[section].collapsed = collapsed
header.setCollapsed(collapsed)
tableView.reloadSections(NSIndexSet(index: section) as IndexSet, with: .automatic)
}
}
| 30.56 | 176 | 0.675065 |
389a79fa749d803e7598cdf095856dab81957137 | 14,537 | /**
* (C) Copyright IBM Corp. 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
RuntimeEntityInterpretation.
*/
public struct RuntimeEntityInterpretation: Codable, Equatable {
/**
The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity.
*/
public enum Granularity: String {
case day = "day"
case fortnight = "fortnight"
case hour = "hour"
case instant = "instant"
case minute = "minute"
case month = "month"
case quarter = "quarter"
case second = "second"
case week = "week"
case weekend = "weekend"
case year = "year"
}
/**
The calendar used to represent a recognized date (for example, `Gregorian`).
*/
public var calendarType: String?
/**
A unique identifier used to associate a recognized time and date. If the user input contains a date and time that
are mentioned together (for example, `Today at 5`, the same **datetime_link** value is returned for both the
`@sys-date` and `@sys-time` entities).
*/
public var datetimeLink: String?
/**
A locale-specific holiday name (such as `thanksgiving` or `christmas`). This property is included when a
`@sys-date` entity is recognized based on a holiday name in the user input.
*/
public var festival: String?
/**
The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity.
*/
public var granularity: String?
/**
A unique identifier used to associate multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that
are recognized as a range of values in the user's input (for example, `from July 4 until July 14` or `from 20 to
25`).
*/
public var rangeLink: String?
/**
The word in the user input that indicates that a `sys-date` or `sys-time` entity is part of an implied range where
only one date or time is specified (for example, `since` or `until`).
*/
public var rangeModifier: String?
/**
A recognized mention of a relative day, represented numerically as an offset from the current date (for example,
`-1` for `yesterday` or `10` for `in ten days`).
*/
public var relativeDay: Double?
/**
A recognized mention of a relative month, represented numerically as an offset from the current month (for example,
`1` for `next month` or `-3` for `three months ago`).
*/
public var relativeMonth: Double?
/**
A recognized mention of a relative week, represented numerically as an offset from the current week (for example,
`2` for `in two weeks` or `-1` for `last week).
*/
public var relativeWeek: Double?
/**
A recognized mention of a relative date range for a weekend, represented numerically as an offset from the current
weekend (for example, `0` for `this weekend` or `-1` for `last weekend`).
*/
public var relativeWeekend: Double?
/**
A recognized mention of a relative year, represented numerically as an offset from the current year (for example,
`1` for `next year` or `-5` for `five years ago`).
*/
public var relativeYear: Double?
/**
A recognized mention of a specific date, represented numerically as the date within the month (for example, `30`
for `June 30`.).
*/
public var specificDay: Double?
/**
A recognized mention of a specific day of the week as a lowercase string (for example, `monday`).
*/
public var specificDayOfWeek: String?
/**
A recognized mention of a specific month, represented numerically (for example, `7` for `July`).
*/
public var specificMonth: Double?
/**
A recognized mention of a specific quarter, represented numerically (for example, `3` for `the third quarter`).
*/
public var specificQuarter: Double?
/**
A recognized mention of a specific year (for example, `2016`).
*/
public var specificYear: Double?
/**
A recognized numeric value, represented as an integer or double.
*/
public var numericValue: Double?
/**
The type of numeric value recognized in the user input (`integer` or `rational`).
*/
public var subtype: String?
/**
A recognized term for a time that was mentioned as a part of the day in the user's input (for example, `morning` or
`afternoon`).
*/
public var partOfDay: String?
/**
A recognized mention of a relative hour, represented numerically as an offset from the current hour (for example,
`3` for `in three hours` or `-1` for `an hour ago`).
*/
public var relativeHour: Double?
/**
A recognized mention of a relative time, represented numerically as an offset in minutes from the current time (for
example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`).
*/
public var relativeMinute: Double?
/**
A recognized mention of a relative time, represented numerically as an offset in seconds from the current time (for
example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`).
*/
public var relativeSecond: Double?
/**
A recognized specific hour mentioned as part of a time value (for example, `10` for `10:15 AM`.).
*/
public var specificHour: Double?
/**
A recognized specific minute mentioned as part of a time value (for example, `15` for `10:15 AM`.).
*/
public var specificMinute: Double?
/**
A recognized specific second mentioned as part of a time value (for example, `30` for `10:15:30 AM`.).
*/
public var specificSecond: Double?
/**
A recognized time zone mentioned as part of a time value (for example, `EST`).
*/
public var timezone: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case calendarType = "calendar_type"
case datetimeLink = "datetime_link"
case festival = "festival"
case granularity = "granularity"
case rangeLink = "range_link"
case rangeModifier = "range_modifier"
case relativeDay = "relative_day"
case relativeMonth = "relative_month"
case relativeWeek = "relative_week"
case relativeWeekend = "relative_weekend"
case relativeYear = "relative_year"
case specificDay = "specific_day"
case specificDayOfWeek = "specific_day_of_week"
case specificMonth = "specific_month"
case specificQuarter = "specific_quarter"
case specificYear = "specific_year"
case numericValue = "numeric_value"
case subtype = "subtype"
case partOfDay = "part_of_day"
case relativeHour = "relative_hour"
case relativeMinute = "relative_minute"
case relativeSecond = "relative_second"
case specificHour = "specific_hour"
case specificMinute = "specific_minute"
case specificSecond = "specific_second"
case timezone = "timezone"
}
/**
Initialize a `RuntimeEntityInterpretation` with member variables.
- parameter calendarType: The calendar used to represent a recognized date (for example, `Gregorian`).
- parameter datetimeLink: A unique identifier used to associate a recognized time and date. If the user input
contains a date and time that are mentioned together (for example, `Today at 5`, the same **datetime_link** value
is returned for both the `@sys-date` and `@sys-time` entities).
- parameter festival: A locale-specific holiday name (such as `thanksgiving` or `christmas`). This property is
included when a `@sys-date` entity is recognized based on a holiday name in the user input.
- parameter granularity: The precision or duration of a time range specified by a recognized `@sys-time` or
`@sys-date` entity.
- parameter rangeLink: A unique identifier used to associate multiple recognized `@sys-date`, `@sys-time`, or
`@sys-number` entities that are recognized as a range of values in the user's input (for example, `from July 4
until July 14` or `from 20 to 25`).
- parameter rangeModifier: The word in the user input that indicates that a `sys-date` or `sys-time` entity is
part of an implied range where only one date or time is specified (for example, `since` or `until`).
- parameter relativeDay: A recognized mention of a relative day, represented numerically as an offset from the
current date (for example, `-1` for `yesterday` or `10` for `in ten days`).
- parameter relativeMonth: A recognized mention of a relative month, represented numerically as an offset from
the current month (for example, `1` for `next month` or `-3` for `three months ago`).
- parameter relativeWeek: A recognized mention of a relative week, represented numerically as an offset from the
current week (for example, `2` for `in two weeks` or `-1` for `last week).
- parameter relativeWeekend: A recognized mention of a relative date range for a weekend, represented
numerically as an offset from the current weekend (for example, `0` for `this weekend` or `-1` for `last
weekend`).
- parameter relativeYear: A recognized mention of a relative year, represented numerically as an offset from the
current year (for example, `1` for `next year` or `-5` for `five years ago`).
- parameter specificDay: A recognized mention of a specific date, represented numerically as the date within the
month (for example, `30` for `June 30`.).
- parameter specificDayOfWeek: A recognized mention of a specific day of the week as a lowercase string (for
example, `monday`).
- parameter specificMonth: A recognized mention of a specific month, represented numerically (for example, `7`
for `July`).
- parameter specificQuarter: A recognized mention of a specific quarter, represented numerically (for example,
`3` for `the third quarter`).
- parameter specificYear: A recognized mention of a specific year (for example, `2016`).
- parameter numericValue: A recognized numeric value, represented as an integer or double.
- parameter subtype: The type of numeric value recognized in the user input (`integer` or `rational`).
- parameter partOfDay: A recognized term for a time that was mentioned as a part of the day in the user's input
(for example, `morning` or `afternoon`).
- parameter relativeHour: A recognized mention of a relative hour, represented numerically as an offset from the
current hour (for example, `3` for `in three hours` or `-1` for `an hour ago`).
- parameter relativeMinute: A recognized mention of a relative time, represented numerically as an offset in
minutes from the current time (for example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`).
- parameter relativeSecond: A recognized mention of a relative time, represented numerically as an offset in
seconds from the current time (for example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`).
- parameter specificHour: A recognized specific hour mentioned as part of a time value (for example, `10` for
`10:15 AM`.).
- parameter specificMinute: A recognized specific minute mentioned as part of a time value (for example, `15`
for `10:15 AM`.).
- parameter specificSecond: A recognized specific second mentioned as part of a time value (for example, `30`
for `10:15:30 AM`.).
- parameter timezone: A recognized time zone mentioned as part of a time value (for example, `EST`).
- returns: An initialized `RuntimeEntityInterpretation`.
*/
public init(
calendarType: String? = nil,
datetimeLink: String? = nil,
festival: String? = nil,
granularity: String? = nil,
rangeLink: String? = nil,
rangeModifier: String? = nil,
relativeDay: Double? = nil,
relativeMonth: Double? = nil,
relativeWeek: Double? = nil,
relativeWeekend: Double? = nil,
relativeYear: Double? = nil,
specificDay: Double? = nil,
specificDayOfWeek: String? = nil,
specificMonth: Double? = nil,
specificQuarter: Double? = nil,
specificYear: Double? = nil,
numericValue: Double? = nil,
subtype: String? = nil,
partOfDay: String? = nil,
relativeHour: Double? = nil,
relativeMinute: Double? = nil,
relativeSecond: Double? = nil,
specificHour: Double? = nil,
specificMinute: Double? = nil,
specificSecond: Double? = nil,
timezone: String? = nil
)
{
self.calendarType = calendarType
self.datetimeLink = datetimeLink
self.festival = festival
self.granularity = granularity
self.rangeLink = rangeLink
self.rangeModifier = rangeModifier
self.relativeDay = relativeDay
self.relativeMonth = relativeMonth
self.relativeWeek = relativeWeek
self.relativeWeekend = relativeWeekend
self.relativeYear = relativeYear
self.specificDay = specificDay
self.specificDayOfWeek = specificDayOfWeek
self.specificMonth = specificMonth
self.specificQuarter = specificQuarter
self.specificYear = specificYear
self.numericValue = numericValue
self.subtype = subtype
self.partOfDay = partOfDay
self.relativeHour = relativeHour
self.relativeMinute = relativeMinute
self.relativeSecond = relativeSecond
self.specificHour = specificHour
self.specificMinute = specificMinute
self.specificSecond = specificSecond
self.timezone = timezone
}
}
| 43.918429 | 121 | 0.667813 |
21f54ea523e84218a72ec8db187d4e566974dccf | 32,551 | //
// VideoEditor+PhotoTools.swift
// HXPHPicker
//
// Created by Slience on 2021/12/2.
//
import UIKit
import AVKit
extension PhotoTools {
/// 导出编辑视频
/// - Parameters:
/// - avAsset: 视频对应的 AVAsset 数据
/// - outputURL: 指定视频导出的地址,为nil时默认为临时目录
/// - timeRang: 需要裁剪的时间区域,没有传 .zero
/// - stickerInfos: 贴纸数组
/// - audioURL: 需要添加的音频地址
/// - audioVolume: 需要添加的音频音量
/// - originalAudioVolume: 视频原始音频音量
/// - exportPreset: 导出的分辨率
/// - videoQuality: 导出的质量
/// - completion: 导出完成
@discardableResult
static func exportEditVideo(
for avAsset: AVAsset,
outputURL: URL? = nil,
timeRang: CMTimeRange,
cropSizeData: VideoEditorCropSizeData,
audioURL: URL?,
audioVolume: Float,
originalAudioVolume: Float,
exportPreset: ExportPreset,
videoQuality: Int,
completion: ((URL?, Error?) -> Void)?
) -> AVAssetExportSession? {
var timeRang = timeRang
let exportPresets = AVAssetExportSession.exportPresets(compatibleWith: avAsset)
if exportPresets.contains(exportPreset.name) {
do {
guard let videoTrack = avAsset.tracks(withMediaType: .video).first else {
throw NSError(domain: "Video track is nil", code: 500, userInfo: nil)
}
let videoTotalSeconds = videoTrack.timeRange.duration.seconds
if timeRang.start.seconds + timeRang.duration.seconds > videoTotalSeconds {
timeRang = CMTimeRange(
start: timeRang.start,
duration: CMTime(
seconds: videoTotalSeconds - timeRang.start.seconds,
preferredTimescale: timeRang.start.timescale
)
)
}
let videoURL = outputURL ?? PhotoTools.getVideoTmpURL()
let mixComposition = try mixComposition(
for: avAsset,
videoTrack: videoTrack
)
var addVideoComposition = false
let animationBeginTime: CFTimeInterval
if timeRang == .zero {
animationBeginTime = AVCoreAnimationBeginTimeAtZero
}else {
animationBeginTime = timeRang.start.seconds == 0 ?
AVCoreAnimationBeginTimeAtZero :
timeRang.start.seconds
}
let videoComposition = try videoComposition(
for: avAsset,
videoTrack: videoTrack,
mixComposition: mixComposition,
cropSizeData: cropSizeData,
animationBeginTime: animationBeginTime,
videoDuration: timeRang == .zero ? videoTrack.timeRange.duration.seconds : timeRang.duration.seconds
)
if videoComposition.renderSize.width > 0 {
addVideoComposition = true
}
let audioMix = try audioMix(
for: avAsset,
videoTrack: videoTrack,
mixComposition: mixComposition,
timeRang: timeRang,
audioURL: audioURL,
audioVolume: audioVolume,
originalAudioVolume: originalAudioVolume
)
if let exportSession = AVAssetExportSession(
asset: mixComposition,
presetName: exportPreset.name
) {
let supportedTypeArray = exportSession.supportedFileTypes
exportSession.outputURL = videoURL
if supportedTypeArray.contains(AVFileType.mp4) {
exportSession.outputFileType = .mp4
}else if supportedTypeArray.isEmpty {
completion?(nil, PhotoError.error(type: .exportFailed, message: "不支持导出该类型视频"))
return nil
}else {
exportSession.outputFileType = supportedTypeArray.first
}
exportSession.shouldOptimizeForNetworkUse = true
if addVideoComposition {
exportSession.videoComposition = videoComposition
}
if !audioMix.inputParameters.isEmpty {
exportSession.audioMix = audioMix
}
if timeRang != .zero {
exportSession.timeRange = timeRang
}
if videoQuality > 0 {
let seconds = timeRang != .zero ? timeRang.duration.seconds : videoTotalSeconds
exportSession.fileLengthLimit = exportSessionFileLengthLimit(
seconds: seconds,
exportPreset: exportPreset,
videoQuality: videoQuality
)
}
exportSession.exportAsynchronously(completionHandler: {
DispatchQueue.main.async {
switch exportSession.status {
case .completed:
completion?(videoURL, nil)
case .failed, .cancelled:
completion?(nil, exportSession.error)
default: break
}
}
})
return exportSession
}else {
completion?(nil, PhotoError.error(type: .exportFailed, message: "不支持导出该类型视频"))
}
} catch {
completion?(nil, PhotoError.error(type: .exportFailed, message: "导出失败:" + error.localizedDescription))
}
}else {
completion?(nil, PhotoError.error(type: .exportFailed, message: "设备不支持导出:" + exportPreset.name))
}
return nil
}
static func mixComposition(
for videoAsset: AVAsset,
videoTrack: AVAssetTrack
) throws -> AVMutableComposition {
let mixComposition = AVMutableComposition()
let videoTimeRange = CMTimeRangeMake(
start: .zero,
duration: videoTrack.timeRange.duration
)
let compositionVideoTrack = mixComposition.addMutableTrack(
withMediaType: .video,
preferredTrackID: kCMPersistentTrackID_Invalid
)
compositionVideoTrack?.preferredTransform = videoTrack.preferredTransform
try compositionVideoTrack?.insertTimeRange(
videoTimeRange,
of: videoTrack,
at: .zero
)
return mixComposition
}
static func audioMix(
for videoAsset: AVAsset,
videoTrack: AVAssetTrack,
mixComposition: AVMutableComposition,
timeRang: CMTimeRange,
audioURL: URL?,
audioVolume: Float,
originalAudioVolume: Float
) throws -> AVMutableAudioMix {
let duration = videoTrack.timeRange.duration
let videoTimeRange = CMTimeRangeMake(
start: .zero,
duration: duration
)
let audioMix = AVMutableAudioMix()
var newAudioInputParams: AVMutableAudioMixInputParameters?
if let audioURL = audioURL {
// 添加背景音乐
let audioAsset = AVURLAsset(
url: audioURL
)
let newAudioTrack = mixComposition.addMutableTrack(
withMediaType: .audio,
preferredTrackID: kCMPersistentTrackID_Invalid
)
if let audioTrack = audioAsset.tracks(withMediaType: .audio).first {
newAudioTrack?.preferredTransform = audioTrack.preferredTransform
let audioDuration = audioAsset.duration.seconds
let videoDuration: Double
let startTime: Double
if timeRang == .zero {
startTime = 0
videoDuration = duration.seconds
}else {
startTime = timeRang.start.seconds
videoDuration = timeRang.duration.seconds
}
if audioDuration < videoDuration {
let audioTimeRange = CMTimeRangeMake(
start: .zero,
duration: audioTrack.timeRange.duration
)
let divisor = Int(videoDuration / audioDuration)
var atTime = CMTimeMakeWithSeconds(
startTime,
preferredTimescale: audioAsset.duration.timescale
)
for index in 0..<divisor {
try newAudioTrack?.insertTimeRange(
audioTimeRange,
of: audioTrack,
at: atTime
)
atTime = CMTimeMakeWithSeconds(
startTime + Double(index + 1) * audioDuration,
preferredTimescale: audioAsset.duration.timescale
)
}
let remainder = videoDuration.truncatingRemainder(
dividingBy: audioDuration
)
if remainder > 0 {
let seconds = videoDuration - audioDuration * Double(divisor)
try newAudioTrack?.insertTimeRange(
CMTimeRange(
start: .zero,
duration: CMTimeMakeWithSeconds(
seconds,
preferredTimescale: audioAsset.duration.timescale
)
),
of: audioTrack,
at: atTime
)
}
}else {
let audioTimeRange: CMTimeRange
let atTime: CMTime
if timeRang != .zero {
audioTimeRange = CMTimeRangeMake(
start: .zero,
duration: timeRang.duration
)
atTime = timeRang.start
}else {
audioTimeRange = CMTimeRangeMake(
start: .zero,
duration: videoTimeRange.duration
)
atTime = .zero
}
try newAudioTrack?.insertTimeRange(
audioTimeRange,
of: audioTrack,
at: atTime
)
}
}
newAudioInputParams = AVMutableAudioMixInputParameters(
track: newAudioTrack
)
newAudioInputParams?.setVolumeRamp(
fromStartVolume: audioVolume,
toEndVolume: audioVolume,
timeRange: CMTimeRangeMake(
start: .zero,
duration: duration
)
)
newAudioInputParams?.trackID = newAudioTrack?.trackID ?? kCMPersistentTrackID_Invalid
}
if let audioTrack = videoAsset.tracks(withMediaType: .audio).first,
let originalVoiceTrack = mixComposition.addMutableTrack(
withMediaType: .audio,
preferredTrackID: kCMPersistentTrackID_Invalid
) {
originalVoiceTrack.preferredTransform = audioTrack.preferredTransform
try originalVoiceTrack.insertTimeRange(videoTimeRange, of: audioTrack, at: .zero)
let volume: Float = originalAudioVolume
let originalAudioInputParams = AVMutableAudioMixInputParameters(track: originalVoiceTrack)
originalAudioInputParams.setVolumeRamp(
fromStartVolume: volume,
toEndVolume: volume,
timeRange: CMTimeRangeMake(
start: .zero,
duration: duration
)
)
originalAudioInputParams.trackID = originalVoiceTrack.trackID
if let newAudioInputParams = newAudioInputParams {
audioMix.inputParameters = [newAudioInputParams, originalAudioInputParams]
}else {
audioMix.inputParameters = [originalAudioInputParams]
}
}else {
if let newAudioInputParams = newAudioInputParams {
audioMix.inputParameters = [newAudioInputParams]
}
}
return audioMix
}
static func videoComposition(
for videoAsset: AVAsset,
videoTrack: AVAssetTrack,
mixComposition: AVMutableComposition,
cropSizeData: VideoEditorCropSizeData,
animationBeginTime: CFTimeInterval,
videoDuration: TimeInterval
) throws -> AVMutableVideoComposition {
let videoComposition = videoFixed(
composition: mixComposition,
assetOrientation: videoAsset.videoOrientation
)
let renderSize = videoComposition.renderSize
cropVideoSize(videoComposition, cropSizeData)
let overlaySize = videoComposition.renderSize
videoComposition.customVideoCompositorClass = VideoFilterCompositor.self
// https://stackoverflow.com/a/45013962
// renderSize = CGSize(
// width: floor(renderSize.width / 16) * 16,
// height: floor(renderSize.height / 16) * 16
// )
let stickerInfos = cropSizeData.stickerInfos
var drawImage: UIImage?
if let image = cropSizeData.drawLayer?.convertedToImage() {
cropSizeData.drawLayer?.contents = nil
drawImage = image
}
var watermarkLayerTrackID: CMPersistentTrackID?
if !stickerInfos.isEmpty || drawImage != nil {
let bounds = CGRect(origin: .zero, size: renderSize)
let overlaylayer = CALayer()
let bgLayer = CALayer()
if let drawImage = drawImage {
let drawLayer = CALayer()
drawLayer.contents = drawImage.cgImage
drawLayer.frame = bounds
drawLayer.contentsScale = UIScreen.main.scale
bgLayer.addSublayer(drawLayer)
}
for info in stickerInfos {
let center = CGPoint(
x: info.centerScale.x * bounds.width,
y: info.centerScale.y * bounds.height
)
let size = CGSize(
width: info.sizeScale.width * bounds.width,
height: info.sizeScale.height * bounds.height
)
let transform = stickerLayerOrientation(cropSizeData, info)
if let music = info.music,
let subMusic = music.music {
let textLayer = textAnimationLayer(
music: subMusic,
size: size,
fontSize: music.fontSizeScale * bounds.width,
animationScale: bounds.width / info.viewSize.width,
animationSize: CGSize(
width: music.animationSizeScale.width * bounds.width,
height: music.animationSizeScale.height * bounds.height
),
beginTime: animationBeginTime,
videoDuration: videoDuration
)
textLayer.frame = CGRect(origin: .zero, size: size)
textLayer.position = center
bgLayer.addSublayer(textLayer)
textLayer.transform = transform
}else {
let imageLayer = animationLayer(
image: info.image,
beginTime: animationBeginTime,
videoDuration: videoDuration
)
imageLayer.frame = CGRect(origin: .zero, size: size)
imageLayer.position = center
imageLayer.shadowOpacity = 0.4
imageLayer.shadowOffset = CGSize(width: 0, height: -1)
bgLayer.addSublayer(imageLayer)
imageLayer.transform = transform
}
}
if cropSizeData.canReset {
let contentLayer = CALayer()
let width = renderSize.width * cropSizeData.cropRect.width
let height = renderSize.height * cropSizeData.cropRect.height
let x = renderSize.width * cropSizeData.cropRect.minX
let y = renderSize.height * cropSizeData.cropRect.minY
bgLayer.frame = .init(
x: -x, y: -y,
width: bounds.width, height: bounds.height
)
contentLayer.addSublayer(bgLayer)
contentLayer.frame = .init(
x: -(width - overlaySize.width) * 0.5,
y: -(height - overlaySize.height) * 0.5,
width: width, height: height
)
overlaylayer.addSublayer(contentLayer)
layerOrientation(contentLayer, cropSizeData)
}else {
bgLayer.frame = bounds
overlaylayer.addSublayer(bgLayer)
}
overlaylayer.isGeometryFlipped = true
overlaylayer.frame = .init(origin: .zero, size: overlaySize)
let trackID = videoAsset.unusedTrackID()
videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(
additionalLayer: overlaylayer,
asTrackID: trackID
)
watermarkLayerTrackID = trackID
}
var newInstructions: [AVVideoCompositionInstructionProtocol] = []
for instruction in videoComposition.instructions where instruction is AVVideoCompositionInstruction {
let videoInstruction = instruction as! AVVideoCompositionInstruction
let layerInstructions = videoInstruction.layerInstructions
var sourceTrackIDs: [NSValue] = []
for layerInstruction in layerInstructions {
sourceTrackIDs.append(layerInstruction.trackID as NSValue)
}
let newInstruction = CustomVideoCompositionInstruction(
sourceTrackIDs: sourceTrackIDs,
watermarkTrackID: watermarkLayerTrackID,
timeRange: instruction.timeRange,
videoOrientation: videoAsset.videoOrientation,
cropSizeData: cropSizeData.canReset ? cropSizeData : nil,
filterInfo: cropSizeData.filter,
filterValue: cropSizeData.filterValue
)
newInstructions.append(newInstruction)
}
if newInstructions.isEmpty {
var sourceTrackIDs: [NSValue] = []
sourceTrackIDs.append(videoTrack.trackID as NSValue)
let newInstruction = CustomVideoCompositionInstruction(
sourceTrackIDs: sourceTrackIDs,
watermarkTrackID: watermarkLayerTrackID,
timeRange: videoTrack.timeRange,
videoOrientation: videoAsset.videoOrientation,
cropSizeData: cropSizeData.canReset ? cropSizeData : nil,
filterInfo: cropSizeData.filter,
filterValue: cropSizeData.filterValue
)
newInstructions.append(newInstruction)
}
videoComposition.instructions = newInstructions
videoComposition.renderScale = 1
videoComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
return videoComposition
}
static func cropVideoSize(
_ videoComposition: AVMutableVideoComposition,
_ cropSizeData: VideoEditorCropSizeData
) {
if !cropSizeData.canReset {
return
}
let width = videoComposition.renderSize.width * cropSizeData.cropRect.width
let height = videoComposition.renderSize.height * cropSizeData.cropRect.height
let orientation = cropOrientation(cropSizeData)
switch orientation {
case .up, .upMirrored, .down, .downMirrored:
videoComposition.renderSize = .init(width: width, height: height)
default:
videoComposition.renderSize = .init(width: height, height: width)
}
}
private static func layerOrientation(
_ layer: CALayer,
_ cropSizeData: VideoEditorCropSizeData
) {
if cropSizeData.canReset {
let orientation = cropOrientation(cropSizeData)
switch orientation {
case .upMirrored:
layer.transform = CATransform3DMakeScale(-1, 1, 1)
case .left:
layer.transform = CATransform3DMakeRotation(-CGFloat.pi * 0.5, 0, 0, 1)
case .leftMirrored:
var transform = CATransform3DMakeScale(-1, 1, 1)
transform = CATransform3DRotate(transform, -CGFloat.pi * 0.5, 0, 0, 1)
layer.transform = transform
case .right:
layer.transform = CATransform3DMakeRotation(CGFloat.pi * 0.5, 0, 0, 1)
case .rightMirrored:
var transform = CATransform3DMakeRotation(CGFloat.pi * 0.5, 0, 0, 1)
transform = CATransform3DScale(transform, 1, -1, 1)
layer.transform = transform
case .down:
layer.transform = CATransform3DMakeRotation(CGFloat.pi, 0, 0, 1)
case .downMirrored:
layer.transform = CATransform3DMakeScale(1, -1, 1)
default:
break
}
}
}
private static func stickerLayerOrientation(
_ cropSizeData: VideoEditorCropSizeData,
_ info: EditorStickerInfo
) -> CATransform3D {
var transform: CATransform3D
switch stickerOrientation(info) {
case .upMirrored:
transform = CATransform3DMakeScale(-info.scale, info.scale, 1)
case .leftMirrored:
transform = CATransform3DMakeScale(-info.scale, info.scale, 1)
case .rightMirrored:
transform = CATransform3DMakeScale(info.scale, -info.scale, 1)
case .downMirrored:
transform = CATransform3DMakeScale(-info.scale, info.scale, 1)
default:
transform = CATransform3DMakeScale(info.scale, info.scale, 1)
}
transform = CATransform3DRotate(transform, info.angel, 0, 0, 1)
return transform
}
static func textAnimationLayer(
music: VideoEditorMusic,
size: CGSize,
fontSize: CGFloat,
animationScale: CGFloat,
animationSize: CGSize,
beginTime: CFTimeInterval,
videoDuration: TimeInterval
) -> CALayer {
var textSize = size
let bgLayer = CALayer()
for (index, lyric) in music.lyrics.enumerated() {
let textLayer = CATextLayer()
textLayer.string = lyric.lyric
let font = UIFont.boldSystemFont(ofSize: fontSize)
let lyricHeight = lyric.lyric.height(ofFont: font, maxWidth: size.width)
if textSize.height < lyricHeight {
textSize.height = lyricHeight + 1
}
textLayer.font = font
textLayer.fontSize = fontSize
textLayer.isWrapped = true
textLayer.truncationMode = .end
textLayer.contentsScale = UIScreen.main.scale
textLayer.alignmentMode = .left
textLayer.foregroundColor = UIColor.white.cgColor
textLayer.frame = CGRect(origin: .zero, size: textSize)
textLayer.shadowOpacity = 0.4
textLayer.shadowOffset = CGSize(width: 0, height: -1)
if index > 0 || lyric.startTime > 0 {
textLayer.opacity = 0
}else {
textLayer.opacity = 1
}
bgLayer.addSublayer(textLayer)
if lyric.startTime > videoDuration {
continue
}
let startAnimation: CABasicAnimation?
if index > 0 || lyric.startTime > 0 {
startAnimation = CABasicAnimation(keyPath: "opacity")
startAnimation?.fromValue = 0
startAnimation?.toValue = 1
startAnimation?.duration = 0.01
if lyric.startTime == 0 {
startAnimation?.beginTime = beginTime
}else {
startAnimation?.beginTime = beginTime + lyric.startTime
}
startAnimation?.isRemovedOnCompletion = false
startAnimation?.fillMode = .forwards
}else {
startAnimation = nil
}
if lyric.endTime + 0.01 > videoDuration {
if let start = startAnimation {
textLayer.add(start, forKey: nil)
}
continue
}
let endAnimation = CABasicAnimation(keyPath: "opacity")
endAnimation.fromValue = 1
endAnimation.toValue = 0
endAnimation.duration = 0.01
if lyric.endTime == 0 {
endAnimation.beginTime = AVCoreAnimationBeginTimeAtZero
}else {
if lyric.endTime + 0.01 < videoDuration {
endAnimation.beginTime = beginTime + lyric.endTime
}else {
endAnimation.beginTime = beginTime + videoDuration
}
}
endAnimation.isRemovedOnCompletion = false
endAnimation.fillMode = .forwards
if let time = music.time, time < videoDuration {
let group = CAAnimationGroup()
if let start = startAnimation {
group.animations = [start, endAnimation]
}else {
group.animations = [endAnimation]
}
group.beginTime = beginTime
group.isRemovedOnCompletion = false
group.fillMode = .forwards
group.duration = time
group.repeatCount = MAXFLOAT
textLayer.add(group, forKey: nil)
}else {
if let start = startAnimation {
textLayer.add(start, forKey: nil)
}
textLayer.add(endAnimation, forKey: nil)
}
}
let animationLayer = VideoEditorMusicAnimationLayer(
hexColor: "#ffffff",
scale: animationScale
)
animationLayer.animationBeginTime = beginTime
animationLayer.frame = CGRect(
x: 2 * animationScale,
y: -(8 * animationScale + animationSize.height),
width: animationSize.width,
height: animationSize.height
)
animationLayer.startAnimation()
bgLayer.contentsScale = UIScreen.main.scale
bgLayer.shadowOpacity = 0.4
bgLayer.shadowOffset = CGSize(width: 0, height: -1)
bgLayer.addSublayer(animationLayer)
return bgLayer
}
static func animationLayer(
image: UIImage,
beginTime: CFTimeInterval,
videoDuration: TimeInterval
) -> CALayer {
let animationLayer = CALayer()
animationLayer.contentsScale = UIScreen.main.scale
animationLayer.contents = image.cgImage
guard let gifResult = image.animateCGImageFrame() else {
return animationLayer
}
let frames = gifResult.0
if frames.isEmpty {
return animationLayer
}
let delayTimes = gifResult.1
var currentTime: Double = 0
var animations = [CAAnimation]()
for (index, frame) in frames.enumerated() {
let delayTime = delayTimes[index]
let animation = CABasicAnimation(keyPath: "contents")
animation.toValue = frame
animation.duration = 0.001
animation.beginTime = AVCoreAnimationBeginTimeAtZero + currentTime
animation.isRemovedOnCompletion = false
animation.fillMode = .forwards
animations.append(animation)
currentTime += delayTime
if currentTime + 0.01 > videoDuration {
break
}
}
let group = CAAnimationGroup()
group.animations = animations
group.beginTime = beginTime
group.isRemovedOnCompletion = false
group.fillMode = .forwards
group.duration = currentTime + 0.01
group.repeatCount = MAXFLOAT
animationLayer.add(group, forKey: nil)
return animationLayer
}
static func videoFixed(
composition: AVMutableComposition,
assetOrientation: AVCaptureVideoOrientation
) -> AVMutableVideoComposition {
let videoComposition = AVMutableVideoComposition(propertiesOf: composition)
guard assetOrientation != .landscapeRight else {
return videoComposition
}
guard let videoTrack = composition.tracks(withMediaType: .video).first else {
return videoComposition
}
let naturalSize = videoTrack.naturalSize
if assetOrientation == .portrait {
// 顺时针旋转90°
videoComposition.renderSize = CGSize(width: naturalSize.height, height: naturalSize.width)
} else if assetOrientation == .landscapeLeft {
// 顺时针旋转180°
videoComposition.renderSize = CGSize(width: naturalSize.width, height: naturalSize.height)
} else if assetOrientation == .portraitUpsideDown {
// 顺时针旋转270°
videoComposition.renderSize = CGSize(width: naturalSize.height, height: naturalSize.width)
}
return videoComposition
}
static func createPixelBuffer(_ size: CGSize) -> CVPixelBuffer? {
var pixelBuffer: CVPixelBuffer?
let pixelBufferAttributes = [kCVPixelBufferIOSurfacePropertiesKey: [:]]
CVPixelBufferCreate(
nil,
Int(size.width),
Int(size.height),
kCVPixelFormatType_32BGRA,
pixelBufferAttributes as CFDictionary,
&pixelBuffer
)
return pixelBuffer
}
static func cropOrientation1(
_ cropSizeData: VideoEditorCropSizeData
) -> UIImage.Orientation {
getOrientation(
cropSizeData.angle,
cropSizeData.mirrorType
)
}
static func stickerOrientation(
_ info: EditorStickerInfo
) -> UIImage.Orientation {
getOrientation(
info.initialAngle,
info.initialMirrorType
)
}
private static func getOrientation(
_ angle: CGFloat,
_ mirrorType: EditorImageResizerView.MirrorType
) -> UIImage.Orientation {
var rotate = CGFloat.pi * angle / 180
if rotate != 0 {
rotate = CGFloat.pi * 2 + rotate
}
let isHorizontal = mirrorType == .horizontal
if rotate > 0 || isHorizontal {
let angle = Int(angle)
switch angle {
case 0, 360, -360:
if isHorizontal {
return .upMirrored
}
case 90, -270:
if !isHorizontal {
return .right
}else {
return .rightMirrored
}
case 180, -180:
if !isHorizontal {
return .down
}else {
return .downMirrored
}
case 270, -90:
if !isHorizontal {
return .left
}else {
return .leftMirrored
}
default:
break
}
}
return .up
}
}
| 41.572158 | 120 | 0.538601 |
e9db9abb1ca8c0170cad86ab6f87a693d52fad2e | 2,159 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
#if compiler(>=5.5) && canImport(_Concurrency)
import SotoCore
// MARK: Waiters
@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
extension DocDB {
public func waitUntilDBInstanceAvailable(
_ input: DescribeDBInstancesMessage,
maxWaitTime: TimeAmount? = nil,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil
) async throws {
let waiter = AWSClient.Waiter(
acceptors: [
.init(state: .success, matcher: try! JMESAllPathMatcher("dbInstances[].dBInstanceStatus", expected: "available")),
.init(state: .failure, matcher: try! JMESAnyPathMatcher("dbInstances[].dBInstanceStatus", expected: "deleted")),
.init(state: .failure, matcher: try! JMESAnyPathMatcher("dbInstances[].dBInstanceStatus", expected: "deleting")),
.init(state: .failure, matcher: try! JMESAnyPathMatcher("dbInstances[].dBInstanceStatus", expected: "failed")),
.init(state: .failure, matcher: try! JMESAnyPathMatcher("dbInstances[].dBInstanceStatus", expected: "incompatible-restore")),
.init(state: .failure, matcher: try! JMESAnyPathMatcher("dbInstances[].dBInstanceStatus", expected: "incompatible-parameters")),
],
minDelayTime: .seconds(30),
command: describeDBInstances
)
return try await self.client.waitUntil(input, waiter: waiter, maxWaitTime: maxWaitTime, logger: logger, on: eventLoop)
}
}
#endif // compiler(>=5.5) && canImport(_Concurrency)
| 44.061224 | 144 | 0.6239 |
38c4703d735cff9b330de58a169b928b33c80698 | 7,324 | import Foundation
import CoreBluetooth
import RxSwift
/// RxBluetoothKit specific logging class which gives access to its settings.
public class RxBluetoothKitLog: ReactiveCompatible {
fileprivate static let subject = PublishSubject<String>()
/// Set new log level.
/// - Parameter logLevel: New log level to be applied.
public static func setLogLevel(_ logLevel: RxBluetoothKitLog.LogLevel) {
RxBluetoothKitLogger.defaultLogger.setLogLevel(logLevel)
}
/// Get current log level.
/// - Returns: Currently set log level.
public static func getLogLevel() -> RxBluetoothKitLog.LogLevel {
return RxBluetoothKitLogger.defaultLogger.getLogLevel()
}
private init() {
}
/// Log levels for internal logging mechanism.
public enum LogLevel: UInt8 {
/// Logging is disabled
case none = 255
/// All logs are monitored.
case verbose = 0
/// Only debug logs and of higher importance are logged.
case debug = 1
/// Only info logs and of higher importance are logged.
case info = 2
/// Only warning logs and of higher importance are logged.
case warning = 3
/// Only error logs and of higher importance are logged.
case error = 4
}
fileprivate static func log(
with logLevel: LogLevel,
message: @autoclosure () -> String,
file: StaticString,
function: StaticString,
line: UInt
) {
let loggedMessage = message()
RxBluetoothKitLogger.defaultLogger.log(
loggedMessage,
level: logLevel,
file: file,
function: function,
line: line
)
if getLogLevel() <= logLevel {
subject.onNext(loggedMessage)
}
}
static func v(
_ message: @autoclosure () -> String,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line
) {
log(with: .verbose, message: message(), file: file, function: function, line: line)
}
static func d(
_ message: @autoclosure () -> String,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line
) {
log(with: .debug, message: message(), file: file, function: function, line: line)
}
static func i(
_ message: @autoclosure () -> String,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line
) {
log(with: .info, message: message(), file: file, function: function, line: line)
}
static func w(
_ message: @autoclosure () -> String,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line
) {
log(with: .warning, message: message(), file: file, function: function, line: line)
}
static func e(
_ message: @autoclosure () -> String,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line
) {
log(with: .error, message: message(), file: file, function: function, line: line)
}
}
extension RxBluetoothKitLog.LogLevel: Comparable {
public static func < (lhs: RxBluetoothKitLog.LogLevel, rhs: RxBluetoothKitLog.LogLevel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
public static func <= (lhs: RxBluetoothKitLog.LogLevel, rhs: RxBluetoothKitLog.LogLevel) -> Bool {
return lhs.rawValue <= rhs.rawValue
}
public static func > (lhs: RxBluetoothKitLog.LogLevel, rhs: RxBluetoothKitLog.LogLevel) -> Bool {
return lhs.rawValue > rhs.rawValue
}
public static func >= (lhs: RxBluetoothKitLog.LogLevel, rhs: RxBluetoothKitLog.LogLevel) -> Bool {
return lhs.rawValue >= rhs.rawValue
}
public static func == (lhs: RxBluetoothKitLog.LogLevel, rhs: RxBluetoothKitLog.LogLevel) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
protocol Loggable {
var logDescription: String { get }
}
extension Data: Loggable {
var logDescription: String {
return map { String(format: "%02x", $0) }.joined()
}
}
extension BluetoothState: Loggable {
var logDescription: String {
switch self {
case .unknown: return "unknown"
case .resetting: return "resetting"
case .unsupported: return "unsupported"
case .unauthorized: return "unauthorized"
case .poweredOff: return "poweredOff"
case .poweredOn: return "poweredOn"
}
}
}
extension CBCharacteristicWriteType: Loggable {
var logDescription: String {
switch self {
case .withResponse: return "withResponse"
case .withoutResponse: return "withoutResponse"
@unknown default:
return "unknown write type"
}
}
}
extension UUID: Loggable {
var logDescription: String {
return uuidString
}
}
extension CBUUID: Loggable {
@objc var logDescription: String {
return uuidString
}
}
extension CBCentralManager: Loggable {
@objc var logDescription: String {
return "CentralManager(\(UInt(bitPattern: ObjectIdentifier(self))))"
}
}
extension CBPeripheral: Loggable {
@objc var logDescription: String {
return "Peripheral(uuid: \(uuidIdentifier), name: \(String(describing: name)))"
}
}
extension CBCharacteristic: Loggable {
@objc var logDescription: String {
return "Characteristic(uuid: \(uuid), id: \((UInt(bitPattern: ObjectIdentifier(self)))))"
}
}
extension CBService: Loggable {
@objc var logDescription: String {
return "Service(uuid: \(uuid), id: \((UInt(bitPattern: ObjectIdentifier(self)))))"
}
}
extension CBDescriptor: Loggable {
@objc var logDescription: String {
return "Descriptor(uuid: \(uuid), id: \((UInt(bitPattern: ObjectIdentifier(self)))))"
}
}
extension CBPeripheralManager: Loggable {
@objc var logDescription: String {
return "PeripheralManager(\(UInt(bitPattern: ObjectIdentifier(self))))"
}
}
extension CBATTRequest: Loggable {
@objc var logDescription: String {
return "ATTRequest(\(UInt(bitPattern: ObjectIdentifier(self)))"
}
}
extension CBCentral: Loggable {
@objc var logDescription: String {
return "CBCentral(uuid: \(uuidIdentifier))"
}
}
@available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *)
extension CBL2CAPChannel: Loggable {
@objc var logDescription: String {
return "CBL2CAPChannel(\(UInt(bitPattern: ObjectIdentifier(self)))"
}
}
extension Array where Element: Loggable {
var logDescription: String {
return "[\(map { $0.logDescription }.joined(separator: ", "))]"
}
}
extension Reactive where Base == RxBluetoothKitLog {
/**
* This is continuous value, which emits before a log is printed to standard output.
*
* - it never fails
* - it delivers events on `MainScheduler.instance`
* - `share(scope: .whileConnected)` sharing strategy
*/
public var log: Observable<String> {
return RxBluetoothKitLog.subject.asObserver()
.observe(on: MainScheduler.instance)
.catchAndReturn("")
.share(scope: .whileConnected)
}
}
| 29.179283 | 102 | 0.629984 |
23a09781751280e1cade03c2e05ea404be126db9 | 2,167 | //
// AppDelegate.swift
// SouthPoleFun
//
// Created by 근성가이 on 2017. 1. 22..
// Copyright © 2017년 근성가이. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.106383 | 285 | 0.754038 |
72b2f2950bfea291739de24c8ec84a2694815433 | 602 | //
// MovieVideoCellViewModel.swift
// UpcomingMovies
//
// Created by Alonso on 2/9/19.
// Copyright © 2019 Alonso. All rights reserved.
//
import Foundation
import UpcomingMoviesDomain
protocol MovieVideoCellViewModelProtocol {
var name: String { get }
var key: String { get }
var thumbnailURL: URL? { get }
}
final class MovieVideoCellViewModel: MovieVideoCellViewModelProtocol {
let name: String
let key: String
let thumbnailURL: URL?
init(_ video: Video) {
name = video.name
key = video.key
thumbnailURL = video.thumbnailURL
}
}
| 18.242424 | 70 | 0.67608 |
f946878beb3df17a1f60cdc1f325748546537beb | 798 | //
// UIViewController+Ext.swift
// GitHub Followers
//
// Created by Michael Doctor on 2021-06-06.
//
import UIKit
import SafariServices
extension UIViewController {
func presentGFAlertOnMainThread(title: String, message: String, buttonTitle: String) {
DispatchQueue.main.async {
let alertVC = GFAlertVC(title: title, message: message, buttonTitle: buttonTitle)
alertVC.modalPresentationStyle = .overFullScreen
alertVC.modalTransitionStyle = .crossDissolve
self.present(alertVC, animated: true)
}
}
func presentSafariVC(with url: URL) {
let safariVC = SFSafariViewController(url: url)
safariVC.preferredControlTintColor = .systemGreen
present(safariVC, animated: true)
}
}
| 27.517241 | 93 | 0.672932 |
75a41b3d1cda2504c5cefe9b610720f1ce95500e | 1,011 | //
// GiftViewCell.swift
// HHTV
//
// Created by aStudyer on 2019/10/1.
// Copyright © 2019 aStudyer. All rights reserved.
//
import UIKit
class GiftViewCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var subjectLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
var giftModel : GiftModel? {
didSet {
iconImageView.setImage(giftModel?.img2, "room_btn_gift")
subjectLabel.text = giftModel?.subject
priceLabel.text = "\(giftModel?.coin ?? 0)"
}
}
override func awakeFromNib() {
super.awakeFromNib()
let selectedView = UIView()
selectedView.layer.cornerRadius = 5
selectedView.layer.masksToBounds = true
selectedView.layer.borderWidth = 1
selectedView.layer.borderColor = UIColor.orange.cgColor
selectedView.backgroundColor = UIColor.black
selectedBackgroundView = selectedView
}
}
| 26.605263 | 68 | 0.64095 |
9b9cac1e28e8694f809f96ade423572b3eaef2b1 | 617 | //
// ConversationEmailEventTopicJourneyAction.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class ConversationEmailEventTopicJourneyAction: Codable {
public var _id: String?
public var actionMap: ConversationEmailEventTopicJourneyActionMap?
public init(_id: String?, actionMap: ConversationEmailEventTopicJourneyActionMap?) {
self._id = _id
self.actionMap = actionMap
}
public enum CodingKeys: String, CodingKey {
case _id = "id"
case actionMap
}
}
| 18.69697 | 88 | 0.682334 |
4865b13504d5c833dfcee1e8c2c6320b263436b6 | 609 | //
// JTAppleCollectionReusableView.swift
// Pods
//
// Created by JayT on 2016-05-11.
//
//
/// The header view class of the calendar
open class JTAppleCollectionReusableView: UICollectionReusableView {
/// Initializes and returns a newly allocated view object with the specified frame rectangle.
public override init(frame: CGRect) {
super.init(frame: frame)
}
/// Returns an object initialized from data in a given unarchiver.
/// self, initialized using the data in decoder.
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 27.681818 | 97 | 0.699507 |
91ca8b842e0387cd552163b86a09acd843e00d55 | 712 | //
// CLLayer+Extention.swift
// TestDemo
//
// Created by fuyongYU on 2018/5/28.
// Copyright © 2018年 YeMaoZi. All rights reserved.
//
import UIKit
extension CALayer {
var shadowUIColor: UIColor? {
get {
if let cgColor = shadowColor {
return UIColor(cgColor: cgColor)
}
return nil
}
set {
shadowColor = newValue?.cgColor
}
}
var borderUIColor: UIColor? {
get {
if let cgColor = borderColor {
return UIColor(cgColor: cgColor)
}
return nil
}
set {
borderColor = newValue?.cgColor
}
}
}
| 17.8 | 51 | 0.488764 |
21428624001f8605fb973778c6faf744010ef772 | 43,726 |
import UIKit
import Flutter
//import FirebaseCore
//import FirebaseMessaging
import BackgroundTasks
import UserNotifications
public class SwiftAwesomeNotificationsPlugin: NSObject, FlutterPlugin, UNUserNotificationCenterDelegate/*, MessagingDelegate*/ {
private static var _instance:SwiftAwesomeNotificationsPlugin?
static let TAG = "AwesomeNotificationsPlugin"
static var registrar:FlutterPluginRegistrar?
static var firebaseEnabled:Bool = false
static var firebaseDeviceToken:String?
static var appLifeCycle:NotificationLifeCycle {
get { return LifeCycleManager.getLifeCycle(referenceKey: "currentlifeCycle") }
set (newValue) { LifeCycleManager.setLifeCycle(referenceKey: "currentlifeCycle", lifeCycle: newValue) }
}
var flutterChannel:FlutterMethodChannel?
public static var instance:SwiftAwesomeNotificationsPlugin? {
get { return _instance }
}
private static func checkGooglePlayServices() -> Bool {
return true
}
/*
public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) -> Bool {
do {
if let contentJsonData:String = userInfo[Definitions.PUSH_NOTIFICATION_CONTENT] as? String {
var mapData:[String:Any?] = [:]
mapData[Definitions.PUSH_NOTIFICATION_CONTENT] = JsonUtils.fromJson(contentJsonData)
if let scheduleJsonData:String = userInfo[Definitions.PUSH_NOTIFICATION_SCHEDULE] as? String {
mapData[Definitions.PUSH_NOTIFICATION_SCHEDULE] = JsonUtils.fromJson(scheduleJsonData)
}
if let buttonsJsonData:String = userInfo[Definitions.PUSH_NOTIFICATION_BUTTONS] as? String {
mapData[Definitions.PUSH_NOTIFICATION_BUTTONS] = JsonUtils.fromJsonArr(buttonsJsonData)
}
var pushSource:NotificationSource?
if userInfo["gcm.message_id"] != nil {
pushSource = NotificationSource.Firebase
}
if pushSource == nil {
completionHandler(UIBackgroundFetchResult.failed)
return false
}
if #available(iOS 10.0, *) {
if let pushNotification = PushNotification().fromMap(arguments: mapData) as? PushNotification {
try NotificationSenderAndScheduler().send(
createdSource: pushSource!,
pushNotification: pushNotification,
completion: { sent, content, error in
}
)
}
}
}
} catch {
completionHandler(UIBackgroundFetchResult.failed)
return false
}
completionHandler(UIBackgroundFetchResult.newData)
return true
}
*/
public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
/*
Messaging.messaging().apnsToken = deviceToken
if let token = requestFirebaseToken() {
flutterChannel?.invokeMethod(Definitions.CHANNEL_METHOD_NEW_FCM_TOKEN, arguments: token)
}
*/
}
/*
// For Firebase Messaging versions older than 7.0
// https://github.com/rafaelsetragni/awesome_notifications/issues/39
public func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
didReceiveRegistrationToken(messaging, fcmToken: fcmToken)
}
public func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
if let unwrapped = fcmToken {
didReceiveRegistrationToken(messaging, fcmToken: unwrapped)
}
}
private func didReceiveRegistrationToken(_ messaging: Messaging, fcmToken: String){
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
flutterChannel?.invokeMethod(Definitions.CHANNEL_METHOD_NEW_FCM_TOKEN, arguments: fcmToken)
}
*/
@available(iOS 10.0, *)
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
var userText:String?
if let textResponse = response as? UNTextInputNotificationResponse {
userText = textResponse.userText
}
guard let jsonData:String = response.notification.request.content.userInfo[Definitions.NOTIFICATION_JSON] as? String else {
print("Received an invalid notification content")
completionHandler()
return;
}
receiveAction(
jsonData: jsonData,
actionKey: response.actionIdentifier,
userText: userText
)
completionHandler()
}
@available(iOS 10.0, *)
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
receiveNotification(content: notification.request.content, withCompletionHandler: completionHandler)
}
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [AnyHashable : Any] = [:]) -> Bool {
UNUserNotificationCenter.current().delegate = self
//enableFirebase(application)
enableScheduler(application)
return true
}
var backgroundSessionCompletionHandler: (() -> Void)?
var backgroundSynchTask: UIBackgroundTaskIdentifier = .invalid
public func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) -> Bool {
rescheduleLostNotifications()
backgroundSessionCompletionHandler = completionHandler
return true
}
/*
private func requestFirebaseToken() -> String? {
if let token = SwiftAwesomeNotificationsPlugin.firebaseDeviceToken ?? Messaging.messaging().fcmToken {
SwiftAwesomeNotificationsPlugin.firebaseDeviceToken = token
return token
}
return nil
}
*/
private func enableScheduler(_ application: UIApplication){
if !SwiftUtils.isRunningOnExtension() {
if #available(iOS 13.0, *) {
BGTaskScheduler.shared.register(
forTaskWithIdentifier: Definitions.IOS_BACKGROUND_SCHEDULER,
using: nil//DispatchQueue.global()//DispatchQueue.global(qos: .background).async
){ (task) in
Log.d("BG Schedule","My backgroundTask is executed NOW: \(Date().toString() ?? "")")
self.handleAppSchedules(task: task as! BGAppRefreshTask)
}
} else {
Log.d("BG Schedule","iOS < 13 Registering for Background duty")
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
}
}
}
private func startBackgroundScheduler(){
SwiftAwesomeNotificationsPlugin.rescheduleBackgroundTask()
}
private func stopBackgroundScheduler(){
if #available(iOS 13.0, *) {
BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: Definitions.IOS_BACKGROUND_SCHEDULER)
}
}
public static func rescheduleBackgroundTask(){
if #available(iOS 13.0, *) {
if SwiftAwesomeNotificationsPlugin.appLifeCycle != .Foreground {
let earliestDate:Date? = ScheduleManager.getEarliestDate()
if earliestDate != nil {
let request = BGAppRefreshTaskRequest(identifier: Definitions.IOS_BACKGROUND_SCHEDULER)
request.earliestBeginDate = earliestDate!
do {
try BGTaskScheduler.shared.submit(request)
Log.d(TAG, "(\(Date().toString()!)) BG Scheduled created: "+earliestDate!.toString()!)
} catch {
print("Could not schedule next notification: \(error)")
}
}
}
}
}
@available(iOS 13.0, *)
private func handleAppSchedules(task: BGAppRefreshTask){
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
queue.addOperation(runScheduler)
task.expirationHandler = {
queue.cancelAllOperations()
}
let lastOperation = queue.operations.last
lastOperation?.completionBlock = {
task.setTaskCompleted(success: !(lastOperation?.isCancelled ?? false))
}
}
@available(iOS 13.0, *)
private func runScheduler(){
rescheduleLostNotifications()
SwiftAwesomeNotificationsPlugin.rescheduleBackgroundTask()
}
/*
private func enableFirebase(_ application: UIApplication){
guard let firebaseConfigPath = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist") else {
return
}
let fileManager = FileManager.default
if fileManager.fileExists(atPath: firebaseConfigPath) {
if FirebaseApp.app() == nil {
FirebaseApp.configure()
}
SwiftAwesomeNotificationsPlugin.firebaseEnabled = true
}
}
*/
@available(iOS 10.0, *)
private func receiveNotification(content:UNNotificationContent, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void){
let jsonData:String? = content.userInfo[Definitions.NOTIFICATION_JSON] as? String
guard let pushNotification:PushNotification = NotificationBuilder.jsonToPushNotification(jsonData: jsonData)
else {
Log.d("receiveNotification","notification discarted")
completionHandler([])
return
}
/*
if(content.userInfo["updated"] == nil){
let pushData = pushNotification.toMap()
let updatedJsonData = JsonUtils.toJson(pushData)
let content:UNMutableNotificationContent =
UNMutableNotificationContent().copyContent(from: content)
content.userInfo[Definitions.NOTIFICATION_JSON] = updatedJsonData
content.userInfo["updated"] = true
let request = UNNotificationRequest(identifier: pushNotification!.content!.id!.description, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
{
error in // called when message has been sent
if error != nil {
debugPrint("Error: \(error.debugDescription)")
}
}
completionHandler([])
return
}
*/
let notificationReceived:NotificationReceived? = NotificationReceived(pushNotification.content)
if(notificationReceived != nil){
pushNotification.content!.displayedLifeCycle = SwiftAwesomeNotificationsPlugin.appLifeCycle
let channel:NotificationChannelModel? = ChannelManager.getChannelByKey(channelKey: pushNotification.content!.channelKey!)
alertOnlyOnceNotification(
channel?.onlyAlertOnce,
notificationReceived: notificationReceived!,
completionHandler: completionHandler
)
if CreatedManager.getCreatedByKey(id: notificationReceived!.id!) != nil {
SwiftAwesomeNotificationsPlugin.createEvent(notificationReceived: notificationReceived!)
}
DisplayedManager.reloadLostSchedulesDisplayed(referenceDate: Date())
SwiftAwesomeNotificationsPlugin.displayEvent(notificationReceived: notificationReceived!)
/*
if(pushNotification.schedule != nil){
do {
try NotificationSenderAndScheduler().send(
createdSource: pushNotification.content!.createdSource!,
pushNotification: pushNotification,
completion: { sent, content, error in
}
)
} catch {
// Fallback on earlier versions
}
}
*/
}
}
@available(iOS 10.0, *)
private func alertOnlyOnceNotification(_ alertOnce:Bool?, notificationReceived:NotificationReceived, completionHandler: @escaping (UNNotificationPresentationOptions) -> Void){
if(alertOnce ?? false){
UNUserNotificationCenter.current().getDeliveredNotifications { (notifications) in
for notification in notifications {
if notification.request.identifier == String(notificationReceived.id!) {
self.shouldDisplay(
notificationReceived: notificationReceived,
options: [.alert, .badge],
completionHandler: completionHandler
)
return
}
}
}
}
self.shouldDisplay(
notificationReceived: notificationReceived,
options: [.alert, .badge, .sound],
completionHandler: completionHandler
)
}
@available(iOS 10.0, *)
private func shouldDisplay(notificationReceived:NotificationReceived, options:UNNotificationPresentationOptions, completionHandler: @escaping (UNNotificationPresentationOptions) -> Void){
let currentLifeCycle = SwiftAwesomeNotificationsPlugin.appLifeCycle
if(
(notificationReceived.displayOnForeground! && currentLifeCycle == .Foreground)
||
(notificationReceived.displayOnBackground! && currentLifeCycle == .Background)
){
completionHandler(options)
}
completionHandler([])
}
private func receiveAction(jsonData: String?, actionKey:String?, userText:String?){
Log.d(SwiftAwesomeNotificationsPlugin.TAG, "NOTIFICATION RECEIVED")
if(SwiftAwesomeNotificationsPlugin.appLifeCycle == .AppKilled){
fireBackgroundLostEvents()
}
if #available(iOS 10.0, *) {
let actionReceived:ActionReceived? = NotificationBuilder.buildNotificationActionFromJson(jsonData: jsonData, actionKey: actionKey, userText: userText)
if actionReceived?.dismissedDate == nil {
Log.d(SwiftAwesomeNotificationsPlugin.TAG, "NOTIFICATION RECEIVED")
flutterChannel?.invokeMethod(Definitions.CHANNEL_METHOD_RECEIVED_ACTION, arguments: actionReceived?.toMap())
}
else {
Log.d(SwiftAwesomeNotificationsPlugin.TAG, "NOTIFICATION DISMISSED")
flutterChannel?.invokeMethod(Definitions.CHANNEL_METHOD_NOTIFICATION_DISMISSED, arguments: actionReceived?.toMap())
}
} else {
// Fallback on earlier versions
}
}
@available(iOS 10.0, *)
public static func processNotificationContent(_ notification: UNNotification) -> UNNotification{
print("processNotificationContent SwiftAwesomeNotificationsPlugin")
return notification
}
public static func createEvent(notificationReceived:NotificationReceived){
//Log.d(SwiftAwesomeNotificationsPlugin.TAG, "NOTIFICATION CREATED")
let lifecycle = SwiftAwesomeNotificationsPlugin.appLifeCycle
if(SwiftUtils.isRunningOnExtension() || lifecycle == .AppKilled){
CreatedManager.saveCreated(received: notificationReceived)
} else {
_ = CreatedManager.removeCreated(id: notificationReceived.id!)
SwiftAwesomeNotificationsPlugin.instance?.flutterChannel?.invokeMethod(Definitions.CHANNEL_METHOD_NOTIFICATION_CREATED, arguments: notificationReceived.toMap())
}
}
public static func displayEvent(notificationReceived:NotificationReceived){
//Log.d(SwiftAwesomeNotificationsPlugin.TAG, "NOTIFICATION DISPLAYED")
let lifecycle = SwiftAwesomeNotificationsPlugin.appLifeCycle
if(SwiftUtils.isRunningOnExtension() || lifecycle == .AppKilled){
DisplayedManager.saveDisplayed(received: notificationReceived)
} else {
_ = DisplayedManager.removeDisplayed(id: notificationReceived.id!)
SwiftAwesomeNotificationsPlugin.instance?.flutterChannel?.invokeMethod(Definitions.CHANNEL_METHOD_NOTIFICATION_DISPLAYED, arguments: notificationReceived.toMap())
}
}
private static var didIRealyGoneBackground:Bool = true
public func applicationDidBecomeActive(_ application: UIApplication) {
//debugPrint("applicationDidBecomeActive")
SwiftAwesomeNotificationsPlugin.appLifeCycle = NotificationLifeCycle.Foreground
if(SwiftAwesomeNotificationsPlugin.didIRealyGoneBackground){
fireBackgroundLostEvents()
}
SwiftAwesomeNotificationsPlugin.didIRealyGoneBackground = false
}
public func applicationWillResignActive(_ application: UIApplication) {
//debugPrint("applicationWillResignActive")
// applicationWillTerminate is not always get called, so the Background state is not correct defined in this cases
//SwiftAwesomeNotificationsPlugin.appLifeCycle = NotificationLifeCycle.Foreground
SwiftAwesomeNotificationsPlugin.appLifeCycle = NotificationLifeCycle.Background
SwiftAwesomeNotificationsPlugin.didIRealyGoneBackground = false
}
public func applicationDidEnterBackground(_ application: UIApplication) {
//debugPrint("applicationDidEnterBackground")
// applicationWillTerminate is not always get called, so the AppKilled state is not correct defined in this cases
//SwiftAwesomeNotificationsPlugin.appLifeCycle = NotificationLifeCycle.Background
SwiftAwesomeNotificationsPlugin.appLifeCycle = NotificationLifeCycle.AppKilled
SwiftAwesomeNotificationsPlugin.didIRealyGoneBackground = true
startBackgroundScheduler()
}
public func applicationWillEnterForeground(_ application: UIApplication) {
//debugPrint("applicationWillEnterForeground")
SwiftAwesomeNotificationsPlugin.appLifeCycle = NotificationLifeCycle.Background
stopBackgroundScheduler()
rescheduleLostNotifications()
}
public func applicationWillTerminate(_ application: UIApplication) {
//debugPrint("applicationWillTerminate")
SwiftAwesomeNotificationsPlugin.appLifeCycle = NotificationLifeCycle.AppKilled
SwiftAwesomeNotificationsPlugin.rescheduleBackgroundTask()
}
private static func requestPermissions() -> Bool {
if #available(iOS 10.0, *) {
NotificationBuilder.requestPermissions(completion: { authorized in
debugPrint( authorized ? "Notifications authorized" : "Notifications not authorized" )
})
}
return true
}
public func rescheduleLostNotifications(){
let referenceDate = Date()
let lostSchedules = ScheduleManager.listPendingSchedules(referenceDate: referenceDate)
for pushNotification in lostSchedules {
do {
if #available(iOS 10.0, *) {
try NotificationSenderAndScheduler().send(
createdSource: pushNotification.content!.createdSource!,
pushNotification: pushNotification,
completion: { sent, content, error in
}
)
}
} catch {
// Fallback on earlier versions
}
}
}
public func fireBackgroundLostEvents(){
let lostCreated = CreatedManager.listCreated()
for createdNotification in lostCreated {
SwiftAwesomeNotificationsPlugin.createEvent(notificationReceived: createdNotification)
}
DisplayedManager.reloadLostSchedulesDisplayed(referenceDate: Date())
let lostDisplayed = DisplayedManager.listDisplayed()
for displayedNotification in lostDisplayed {
SwiftAwesomeNotificationsPlugin.displayEvent(notificationReceived: displayedNotification)
}
}
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: Definitions.CHANNEL_FLUTTER_PLUGIN, binaryMessenger: registrar.messenger())
let instance = SwiftAwesomeNotificationsPlugin()
instance.initializeFlutterPlugin(registrar: registrar, channel: channel)
SwiftAwesomeNotificationsPlugin._instance = instance
}
private func initializeFlutterPlugin(registrar: FlutterPluginRegistrar, channel: FlutterMethodChannel) {
self.flutterChannel = channel
registrar.addMethodCallDelegate(self, channel: self.flutterChannel!)
registrar.addApplicationDelegate(self)
SwiftAwesomeNotificationsPlugin.registrar = registrar
/*
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
if(SwiftAwesomeNotificationsPlugin.firebaseEnabled){
Messaging.messaging().delegate = self
}
}
*/
if !SwiftUtils.isRunningOnExtension() {
UIApplication.shared.registerForRemoteNotifications()
}
if #available(iOS 10.0, *) {
let categoryObject = UNNotificationCategory(
identifier: Definitions.DEFAULT_CATEGORY_IDENTIFIER,
actions: [],
intentIdentifiers: [],
options: .customDismissAction
)
UNUserNotificationCenter.current().setNotificationCategories([categoryObject])
}
SwiftAwesomeNotificationsPlugin.appLifeCycle = NotificationLifeCycle.AppKilled
debugPrint("Awesome Notifications - App Group : "+Definitions.USER_DEFAULT_TAG)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case Definitions.CHANNEL_METHOD_INITIALIZE:
channelMethodInitialize(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_GET_DRAWABLE_DATA:
channelMethodGetDrawableData(call: call, result: result)
return;
case Definitions.CHANNEL_METHOD_IS_FCM_AVAILABLE:
channelMethodIsFcmAvailable(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_GET_FCM_TOKEN:
channelMethodGetFcmToken(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_IS_NOTIFICATION_ALLOWED:
channelMethodIsNotificationAllowed(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_REQUEST_NOTIFICATIONS:
channelMethodRequestNotification(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_CREATE_NOTIFICATION:
channelMethodCreateNotification(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_SET_NOTIFICATION_CHANNEL:
channelMethodSetChannel(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_REMOVE_NOTIFICATION_CHANNEL:
channelMethodRemoveChannel(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_GET_BADGE_COUNT:
channelMethodGetBadgeCounter(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_SET_BADGE_COUNT:
channelMethodSetBadgeCounter(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_RESET_BADGE:
channelMethodResetBadge(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_CANCEL_NOTIFICATION:
channelMethodCancelNotification(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_CANCEL_SCHEDULE:
channelMethodCancelSchedule(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_CANCEL_ALL_SCHEDULES:
channelMethodCancelAllSchedules(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_GET_NEXT_DATE:
channelMethodGetNextDate(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_CANCEL_ALL_NOTIFICATIONS:
channelMethodCancelAllNotifications(call: call, result: result)
return
case Definitions.CHANNEL_METHOD_LIST_ALL_SCHEDULES:
channelMethodListAllSchedules(call: call, result: result)
return
default:
result(FlutterError.init(code: "methodNotFound", message: "method not found", details: call.method));
return
}
}
private func channelMethodGetNextDate(call: FlutterMethodCall, result: @escaping FlutterResult) {
do {
let platformParameters:[String:Any?] = call.arguments as? [String:Any?] ?? [:]
//let fixedDate:String? = platformParameters[Definitions.NOTIFICATION_INITIAL_FIXED_DATE] as? String
guard let scheduleData:[String : Any?] = platformParameters[Definitions.PUSH_NOTIFICATION_SCHEDULE] as? [String : Any?]
else { result(nil); return }
var convertedDate:String?
if(scheduleData[Definitions.NOTIFICATION_SCHEDULE_INTERVAL] != nil){
guard let scheduleModel:NotificationScheduleModel =
NotificationIntervalModel().fromMap(arguments: scheduleData) as? NotificationScheduleModel
else { result(nil); return }
guard let trigger:UNTimeIntervalNotificationTrigger = scheduleModel.getUNNotificationTrigger() as? UNTimeIntervalNotificationTrigger
else { result(nil); return }
guard let nextValidDate:Date = trigger.nextTriggerDate()
else { result(nil); return }
convertedDate = DateUtils.dateToString(nextValidDate)
}
else {
guard let scheduleModel:NotificationScheduleModel =
NotificationCalendarModel().fromMap(arguments: scheduleData) as? NotificationScheduleModel
else { result(nil); return }
guard let trigger:UNCalendarNotificationTrigger = scheduleModel.getUNNotificationTrigger() as? UNCalendarNotificationTrigger
else { result(nil); return }
guard let nextValidDate:Date = trigger.nextTriggerDate()
else { result(nil); return }
convertedDate = DateUtils.dateToString(nextValidDate)
}
result(convertedDate)
} catch {
result(
FlutterError.init(
code: "\(error)",
message: "Invalid schedule data",
details: error.localizedDescription
)
)
result(nil)
}
}
private func channelMethodListAllSchedules(call: FlutterMethodCall, result: @escaping FlutterResult) {
//do {
let schedules = ScheduleManager.listSchedules()
var serializeds:[[String:Any?]] = []
if(!ListUtils.isEmptyLists(schedules)){
for pushNotification in schedules {
let serialized:[String:Any?] = pushNotification.toMap()
serializeds.append(serialized)
}
}
result(serializeds)
/*
} catch {
result(
FlutterError.init(
code: "\(error)",
message: "Could not list notifications",
details: error.localizedDescription
)
)
result(nil)
}*/
}
private func channelMethodSetChannel(call: FlutterMethodCall, result: @escaping FlutterResult) {
//do {
let channelData:[String:Any?] = call.arguments as! [String:Any?]
let channel:NotificationChannelModel = NotificationChannelModel().fromMap(arguments: channelData) as! NotificationChannelModel
ChannelManager.saveChannel(channel: channel)
Log.d(SwiftAwesomeNotificationsPlugin.TAG, "Channel updated")
result(true)
/*
} catch {
result(
FlutterError.init(
code: "\(error)",
message: "Invalid channel",
details: error.localizedDescription
)
)
}
result(false)*/
}
private func channelMethodRemoveChannel(call: FlutterMethodCall, result: @escaping FlutterResult) {
//do {
let channelKey:String? = call.arguments as? String
if (channelKey == nil){
result(
FlutterError.init(
code: "Empty channel key",
message: "Empty channel key",
details: channelKey
)
)
}
else {
let removed:Bool = ChannelManager.removeChannel(channelKey: channelKey!)
if removed {
Log.d(SwiftAwesomeNotificationsPlugin.TAG, "Channel removed")
result(removed)
}
else {
Log.d(SwiftAwesomeNotificationsPlugin.TAG, "Channel '\(channelKey!)' not found")
result(removed)
}
}
/*
} catch {
result(
FlutterError.init(
code: "\(error)",
message: "Invalid channel",
details: error.localizedDescription
)
)
}
result(false)*/
}
private func channelMethodInitialize(call: FlutterMethodCall, result: @escaping FlutterResult) {
do {
let platformParameters:[String:Any?] = call.arguments as? [String:Any?] ?? [:]
let defaultIconPath:String? = platformParameters[Definitions.DEFAULT_ICON] as? String
let channelsData:[Any] = platformParameters[Definitions.INITIALIZE_CHANNELS] as? [Any] ?? []
try setDefaultConfigurations(
defaultIconPath,
channelsData
)
Log.d(SwiftAwesomeNotificationsPlugin.TAG, "Awesome Notification service initialized")
fireBackgroundLostEvents()
result(true)
} catch {
result(result(
FlutterError.init(
code: "\(error)",
message: "Awesome Notification service could not beeing initialized",
details: error.localizedDescription
)
))
}
}
private func channelMethodGetDrawableData(call: FlutterMethodCall, result: @escaping FlutterResult) {
//do {
let bitmapReference:String = call.arguments as! String
let image:UIImage = BitmapUtils.getBitmapFromSource(bitmapPath: bitmapReference)!
let data:Data? = UIImage.pngData(image)()
if(data == nil){
result(nil)
}
else {
let uInt8ListBytes:FlutterStandardTypedData = FlutterStandardTypedData.init(bytes: data!)
result(uInt8ListBytes)
}/*
}
catch {
result(FlutterError.init(
code: "\(error)",
message: "Image couldnt be loaded",
details: error.localizedDescription
))
}*/
}
private func channelMethodGetFcmToken(call: FlutterMethodCall, result: @escaping FlutterResult) {
/*
result(FlutterError.init(
code: "Method deprecated",
message: "Method deprecated",
details: "channelMethodGetFcmToken"
))
let token = requestFirebaseToken()
result(token)
*/
result(nil)
}
private func channelMethodIsFcmAvailable(call: FlutterMethodCall, result: @escaping FlutterResult) {
result(FlutterError.init(
code: "Method deprecated",
message: "Method deprecated",
details: "channelMethodGetFcmToken"
))
/*
let token = requestFirebaseToken()
result(!StringUtils.isNullOrEmpty(token))
*/
}
private func channelMethodIsNotificationAllowed(call: FlutterMethodCall, result: @escaping FlutterResult) {
if #available(iOS 10.0, *) {
NotificationBuilder.isNotificationAllowed(completion: { (allowed) in
result(allowed)
})
}
else {
result(nil)
}
}
private func channelMethodRequestNotification(call: FlutterMethodCall, result: @escaping FlutterResult) {
if #available(iOS 10.0, *) {
NotificationBuilder.requestPermissions { (allowed) in
result(allowed)
}
}
else {
result(nil)
}
}
private func channelMethodGetBadgeCounter(call: FlutterMethodCall, result: @escaping FlutterResult) {
if #available(iOS 10.0, *) {
result(NotificationBuilder.getBadge().intValue)
}
else {
result(0)
}
}
private func channelMethodSetBadgeCounter(call: FlutterMethodCall, result: @escaping FlutterResult) {
let platformParameters:[String:Any?] = call.arguments as? [String:Any?] ?? [:]
let value:Int? = platformParameters[Definitions.NOTIFICATION_CHANNEL_SHOW_BADGE] as? Int
//let channelKey:String? = platformParameters[Definitions.NOTIFICATION_CHANNEL_KEY] as? String
if #available(iOS 10.0, *), value != nil {
NotificationBuilder.setBadge(value!)
}
result(nil)
}
private func channelMethodResetBadge(call: FlutterMethodCall, result: @escaping FlutterResult) {
if #available(iOS 10.0, *) {
NotificationBuilder.resetBadge()
}
result(nil)
}
private func channelMethodCancelNotification(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let notificationId:Int = call.arguments as? Int else {
result(false); return
}
if #available(iOS 10.0, *) {
result(NotificationSenderAndScheduler.cancelNotification(id: notificationId))
return
} else {
// Fallback on earlier versions
}
result(false)
}
private func channelMethodCancelSchedule(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let notificationId:Int = call.arguments as? Int else {
result(false); return
}
if #available(iOS 10.0, *) {
result(NotificationSenderAndScheduler.cancelSchedule(id: notificationId))
return
} else {
// Fallback on earlier versions
}
result(false)
}
private func channelMethodCancelAllSchedules(call: FlutterMethodCall, result: @escaping FlutterResult) {
if #available(iOS 10.0, *) {
result(NotificationSenderAndScheduler.cancelAllSchedules())
return
} else {
// Fallback on earlier versions
}
result(false)
}
private func channelMethodCancelAllNotifications(call: FlutterMethodCall, result: @escaping FlutterResult) {
if #available(iOS 10.0, *) {
result(NotificationSenderAndScheduler.cancelAllNotifications())
return
} else {
// Fallback on earlier versions
}
result(false)
}
private func channelMethodCreateNotification(call: FlutterMethodCall, result: @escaping FlutterResult) {
do {
let pushData:[String:Any?] = call.arguments as? [String:Any?] ?? [:]
let pushNotification:PushNotification? = PushNotification().fromMap(arguments: pushData) as? PushNotification
if(pushNotification != nil){
if #available(iOS 10.0, *) {
try NotificationSenderAndScheduler().send(
createdSource: NotificationSource.Local,
pushNotification: pushNotification,
completion: { sent, content, error in
if sent {
Log.d(SwiftAwesomeNotificationsPlugin.TAG, "Notification sent")
}
if error != nil {
let flutterError:FlutterError?
if let notificationError = error as? PushNotificationError {
switch notificationError {
case PushNotificationError.notificationNotAuthorized:
flutterError = FlutterError.init(
code: "notificationNotAuthorized",
message: "Notifications are disabled",
details: nil
)
case PushNotificationError.cronException:
flutterError = FlutterError.init(
code: "cronException",
message: notificationError.localizedDescription,
details: nil
)
default:
flutterError = FlutterError.init(
code: "exception",
message: "Unknow error",
details: notificationError.localizedDescription
)
}
}
else {
flutterError = FlutterError.init(
code: error.debugDescription,
message: error?.localizedDescription,
details: nil
)
}
result(flutterError)
return
}
else {
result(sent)
return
}
}
)
} else {
// Fallback on earlier versions
Log.d(SwiftAwesomeNotificationsPlugin.TAG, "Notification sent");
result(true)
return
}
}
else {
result(
FlutterError.init(
code: "Invalid parameters",
message: "Notification content is invalid",
details: nil
)
)
return
}
} catch {
result(
FlutterError.init(
code: "\(error)",
message: "Awesome Notification service could not beeing initialized",
details: error.localizedDescription
)
)
return
}
result(nil)
}
private func setDefaultConfigurations(_ defaultIconPath:String?, _ channelsData:[Any]) throws {
for anyData in channelsData {
if let channelData = anyData as? [String : Any?] {
let channel:NotificationChannelModel? = (NotificationChannelModel().fromMap(arguments: channelData) as? NotificationChannelModel)
if(channel != nil){
ChannelManager.saveChannel(channel: channel!)
}
}
}
}
}
| 38.729849 | 214 | 0.566665 |
294af1449c57409be085847bc487f72695f7582f | 2,149 | //
// ChatListTableView.swift
// PoseFinder
//
// Created by 三浦将太 on 2020/11/04.
// Copyright © 2020 Apple. All rights reserved.
//
import UIKit
class ChatListTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
var onDidSelect: ((User) -> Void)?
private var chatViewModel: ChatViewModel = ChatViewModel()
var nickName: String?
override func awakeFromNib() {
super.awakeFromNib()
tableViewConfiguartion()
configureViewModel()
}
private func tableViewConfiguartion() {
self.register(UINib(nibName: "ChatListTableViewCell", bundle: nil), forCellReuseIdentifier: "ChatListTableViewCell")
self.dataSource = self
self.delegate = self
}
private func configureViewModel() {
guard let name = nickName else {
return
}
chatViewModel.arrUsers.subscribe {[weak self] (result: [User]) in
guard let self = self else {
return
}
self.reloadData()
}
chatViewModel.fetchParticipantList(name)
}
}
// MARK: - Table view data source
extension ChatListTableView {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ChatListTableViewCell") as? ChatListTableViewCell else {
return UITableView.emptyCell()
}
let user: User = chatViewModel.arrUsers.value[indexPath.row]
cell.configureCell(user)
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chatViewModel.arrUsers.value.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user: User = chatViewModel.arrUsers.value[indexPath.row]
onDidSelect?(user)
}
}
| 26.207317 | 128 | 0.612378 |
3993c851b9a3b5769e08d384c9fe61f3e1acf6b2 | 1,765 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
extension NSObject {
func observeNotification(_ name: String, selector: Selector?) {
if let selector = selector {
NotificationCenter.default.addObserver(self, selector: selector, name: NSNotification.Name(rawValue: name), object: nil)
} else {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: name), object: nil)
}
}
func notification(_ name: String, object: AnyObject? = nil) {
if let dict = object as? NSDictionary {
NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: nil, userInfo: dict as? [AnyHashable : Any])
} else if let object: AnyObject = object {
NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: nil, userInfo: ["object": object])
} else {
NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: nil, userInfo: nil)
}
}
}
| 42.02381 | 137 | 0.627195 |
f5141f6225d54169c38d84d95a9016e2416a3b10 | 5,802 | //
// ParseLaunchJSON.swift
// SA
//
// Created by ming on 2019/10/26.
// Copyright © 2019 ming. All rights reserved.
//
import Foundation
public struct LaunchItem {
public let name: String // 调用方法
public var ph: String // B 代表开始、E 代表结束、BE 代表合并后的 Item、其它代表描述
public var ts: String // 时间戳,开始时间
public var cost: Int // 耗时 ms
public var times: Int // 执行次数
public var subItem: [LaunchItem] // 子 item
public var parentItem:[LaunchItem] // 父 item
}
public class ParseLaunchJSON {
private enum State {
case normal
case startName
case startPh
case startTs
}
private var tks: [JSONToken]
private var allLaunchItem: [LaunchItem]
private var state: State
private var classBundle: [String:String]
public init(input: String) {
tks = ParseJSONTokens(input: input).parse()
allLaunchItem = [LaunchItem]()
state = .normal
classBundle = [String:String]()
}
public func parse() -> [LaunchItem] {
// 获取类和 bundle 的映射表
classBundle = loadClassBundle()
// 开始解析
var currentName = ""
var currentPh = ""
var currentTs = ""
func addItem() {
allLaunchItem.append(LaunchItem(name: currentName, ph: currentPh, ts: currentTs, cost: 0, times: 1, subItem: [LaunchItem](), parentItem: [LaunchItem]()))
currentName = ""
currentPh = ""
currentTs = ""
state = .normal
}
for tk in tks {
// 结束一个 item
if tk.type == .endDic {
addItem()
continue
}
// key
if tk.type == .key {
if tk.value == "name" {
state = .startName
}
if tk.value == "ph" {
state = .startPh
}
if tk.value == "ts" {
state = .startTs
}
continue
}
if tk.type == .value {
if state == .startName {
currentName = tk.value
let s1 = currentName.components(separatedBy: "[")[1]
let s2 = s1.components(separatedBy: "]")[0]
currentName = "[\(classBundle[s2] ?? "other")]\(currentName)"
state = .normal
}
if state == .startPh {
currentPh = tk.value
state = .normal
}
if state == .startTs {
currentTs = tk.value
state = .normal
}
continue
}
}
return allLaunchItem
}
private func loadClassBundle() -> [String:String] {
let path = Bundle.main.path(forResource: "ClassBundle1015", ofType: "csv")
let oPath = path ?? ""
let content = FileHandle.fileContent(path: oPath)
let tokens = Lexer(input: content, type: .plain).allTkFast(operaters: ",")
var allTks = [[Token]]()
var currentTks = [Token]()
for tk in tokens {
if tk == .newLine {
allTks.append(currentTks)
currentTks = [Token]()
continue
}
if tk == .id(",") {
continue
}
currentTks.append(tk)
}
var classBundleDic = [String:String]()
for tks in allTks {
var i = 0
var currentKey = ""
for tk in tks {
if i == 0 {
currentKey = tk.des()
}
if i == 1 {
classBundleDic[currentKey] = tk.des()
}
i += 1
}
}
return classBundleDic
}
private func parseClassAndBundle() {
let path = Bundle.main.path(forResource: "ClassAndBundle", ofType: "csv")
let oPath = path ?? ""
let content = FileHandle.fileContent(path: oPath)
let contentWithoutWhiteSpace = content.replacingOccurrences(of: " ", with: "")
let tokens = Lexer(input: contentWithoutWhiteSpace, type: .plain).allTkFast(operaters: ",")
var allTks = [[Token]]()
var currentTks = [Token]()
for tk in tokens {
if tk == .newLine {
allTks.append(currentTks)
currentTks = [Token]()
continue
}
if tk == .id(",") {
continue
}
currentTks.append(tk)
}
//print(allTks)
allTks.remove(at: 0)
var classBundleDic = [String:String]()
for tks in allTks {
var i = 0
var currentKey = ""
for tk in tks {
if i == 2 {
let className = tk.des()
let classNameS1 = className.replacingOccurrences(of: "\"[\"\"", with: "")
let classNameS2 = classNameS1.replacingOccurrences(of: "\"\"]\"", with: "")
currentKey = classNameS2
}
if i == 4 {
classBundleDic[currentKey] = tk.des()
}
i += 1
}
}
var str = ""
for (k,v) in classBundleDic {
str.append("\(k),\(v)\n")
}
try! str.write(toFile: "\(Config.downloadPath.rawValue)classBundle1015.csv", atomically: true, encoding: String.Encoding.utf8)
}
}
| 28.581281 | 165 | 0.448121 |
61ae8ec6804540f7603f585d3c23e465db6edd92 | 1,560 | //
// UIView+ActionTapGesture.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2017-12-12.
// Copyright © 2017 Daniel Saidi. All rights reserved.
//
// Reference: https://medium.com/@sdrzn/adding-gesture-recognizers-with-closures-instead-of-selectors-9fb3e09a8f0b
//
import UIKit
public extension UIView {
typealias TapAction = () -> Void
/**
Add a tap gesture recognizer to the view.
*/
func addTapAction(numberOfTapsRequired: Int = 1, action: @escaping TapAction) {
tapAction = action
isUserInteractionEnabled = true
let recognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapAction))
recognizer.numberOfTapsRequired = numberOfTapsRequired
addGestureRecognizer(recognizer)
}
/**
Remove all repeating gesture recognizers from the view.
*/
func removeTapAction() {
gestureRecognizers?
.filter { $0 is UITapGestureRecognizer }
.forEach { removeGestureRecognizer($0) }
}
}
private extension UIView {
struct Key { static var id = "tapAction" }
var tapAction: TapAction? {
get {
objc_getAssociatedObject(self, &Key.id) as? TapAction
}
set {
guard let value = newValue else { return }
let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
objc_setAssociatedObject(self, &Key.id, value, policy)
}
}
@objc func handleTapAction(sender: UITapGestureRecognizer) {
tapAction?()
}
}
| 27.368421 | 115 | 0.645513 |
f40c76a2e0ea56c9f240255bcfc55c7327f1adb8 | 250 | //
// Gender.swift
// Petbulb
//
// Created by MACPRO on 2017-10-20.
// Copyright © 2017 Petbulb Corp. All rights reserved.
//
import Foundation
enum Gender : String {
case male = "Male"
case female = "Female"
case none = ""
}
| 14.705882 | 55 | 0.608 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.