label
int64 0
1
| text
stringlengths 0
2.8M
|
---|---|
0 | //
// KeychainManager.swift
// CoatCode
//
// Created by 강민석 on 2020/10/05.
// Copyright © 2020 MinseokKang. All rights reserved.
//
import Foundation
import KeychainAccess
class KeychainManager {
static let shared = KeychainManager()
fileprivate let usernameKey = "usernameKey"
private init() { }
let keychain = Keychain(service: Configs.App.bundleIdentifier)
var username: String? {
get {
return keychain[usernameKey]
}
set {
keychain[usernameKey] = "\(newValue!)"
}
}
}
|
0 | //
// PreviewUI.swift
// ReformTools
//
// Created by Laszlo Korte on 30.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
public final class MaskUI {
public enum State {
case disabled
case clip(x: Double, y: Double, width: Double, height: Double)
}
public var state : State = .disabled
public init() {}
}
|
0 | import Foundation
import UIKit
/**
A view controller that supports interaction to start removing transiton.
It works as a wrapper for another view controller or using with subclassing.
If you have already implementation of view controller and want to get flexibility, you can use this class as a wrapper.
```swift
let yourController = YourViewController()
let fluidController = FluidViewController(
bodyViewController: yourController,
...
)
```
You may specify ``AnyRemovingInteraction``
*/
open class FluidGestureHandlingViewController: FluidTransitionViewController, UIGestureRecognizerDelegate {
// MARK: - Properties
@available(*, unavailable, message: "Unsupported")
open override var navigationController: UINavigationController? {
super.navigationController
}
public private(set) lazy var fluidPanGesture: FluidPanGestureRecognizer = FluidPanGestureRecognizer(
target: self,
action: #selector(handlePanGesture)
)
public private(set) lazy var fluidScreenEdgePanGesture: UIScreenEdgePanGestureRecognizer = _EdgePanGestureRecognizer(
target: self,
action: #selector(handleEdgeLeftPanGesture)
)
private var registeredGestures: [UIGestureRecognizer] = []
public var removingInteraction: AnyRemovingInteraction? {
didSet {
guard isViewLoaded else { return }
setupGestures()
}
}
// MARK: - Initializers
public init(
content: FluidWrapperViewController.Content?,
addingTransition: AnyAddingTransition?,
removingTransition: AnyRemovingTransition?,
removingInteraction: AnyRemovingInteraction?
) {
self.removingInteraction = removingInteraction
super.init(
content: content,
addingTransition: addingTransition,
removingTransition: removingTransition
)
}
deinit {
Log.debug(.fluidController, "Deinit \(self)")
}
@available(*, unavailable)
public required init?(
coder: NSCoder
) {
fatalError()
}
// MARK: - Functions
open override func viewDidLoad() {
super.viewDidLoad()
setupGestures()
}
private func setupGestures() {
assert(Thread.isMainThread)
registeredGestures.forEach {
view.removeGestureRecognizer($0)
}
registeredGestures = []
guard let interaction = removingInteraction else {
return
}
for handler in interaction.handlers {
switch handler {
case .gestureOnLeftEdge:
let created = fluidScreenEdgePanGesture
created.edges = .left
view.addGestureRecognizer(created)
created.delegate = self
registeredGestures.append(created)
case .gestureOnScreen:
let created = fluidPanGesture
view.addGestureRecognizer(created)
created.delegate = self
registeredGestures.append(created)
}
}
fluidPanGesture.require(toFail: fluidScreenEdgePanGesture)
}
@objc
private func handleEdgeLeftPanGesture(_ gesture: _EdgePanGestureRecognizer) {
guard let interaction = removingInteraction else {
return
}
for handler in interaction.handlers {
if case .gestureOnLeftEdge(_, let handler) = handler {
handler(gesture, .init(viewController: self))
}
}
}
@objc
private func handlePanGesture(_ gesture: FluidPanGestureRecognizer) {
guard let removingInteraction = removingInteraction else {
return
}
for handler in removingInteraction.handlers {
if case .gestureOnScreen(_, let handler) = handler {
handler(gesture, .init(viewController: self))
}
}
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
switch gestureRecognizer {
case fluidPanGesture, fluidScreenEdgePanGesture:
let isDirectDescendant = parent is FluidStackController
return isDirectDescendant
default:
assertionFailure()
return true
}
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
switch gestureRecognizer {
case fluidPanGesture:
if let removingInteraction = removingInteraction {
for handler in removingInteraction.handlers {
if case .gestureOnScreen(let condition, _) = handler {
var resultPlaceholder: Bool = false
condition(
fluidPanGesture, .shouldBeRequiredToFailBy(
otherGestureRecognizer: otherGestureRecognizer,
completion: { result in
// non-escaping
resultPlaceholder = result
}
)
)
return resultPlaceholder
}
}
}
case fluidScreenEdgePanGesture:
if let removingInteraction = removingInteraction {
for handler in removingInteraction.handlers {
if case .gestureOnLeftEdge(let condition, _) = handler {
var resultPlaceholder: Bool = false
condition(
fluidScreenEdgePanGesture,
.shouldBeRequiredToFailBy(
otherGestureRecognizer: otherGestureRecognizer,
completion: { result in
// non-escaping
resultPlaceholder = result
}
)
)
return resultPlaceholder
}
}
}
default:
break
}
return false
}
public func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
) -> Bool {
switch gestureRecognizer {
case fluidPanGesture:
if let removingInteraction = removingInteraction {
for handler in removingInteraction.handlers {
if case .gestureOnScreen(let condition, _) = handler {
var resultPlaceholder: Bool = false
condition(
fluidPanGesture, .shouldRecognizeSimultaneouslyWith(
otherGestureRecognizer: otherGestureRecognizer,
completion: { result in
// non-escaping
resultPlaceholder = result
}
)
)
return resultPlaceholder
}
}
}
case fluidScreenEdgePanGesture:
if let removingInteraction = removingInteraction {
for handler in removingInteraction.handlers {
if case .gestureOnLeftEdge(let condition, _) = handler {
var resultPlaceholder: Bool = false
condition(
fluidScreenEdgePanGesture,
.shouldRecognizeSimultaneouslyWith(
otherGestureRecognizer: otherGestureRecognizer,
completion: { result in
// non-escaping
resultPlaceholder = result
}
)
)
return resultPlaceholder
}
}
}
default:
break
}
return true
}
}
final class _EdgePanGestureRecognizer: UIScreenEdgePanGestureRecognizer {
weak var trackingScrollView: UIScrollView?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
trackingScrollView = event.findScrollView()
super.touchesBegan(touches, with: event)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesEnded(touches, with: event)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesCancelled(touches, with: event)
}
}
public final class FluidPanGestureRecognizer: UIPanGestureRecognizer {
public private(set) weak var trackingScrollView: UIScrollView?
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
trackingScrollView = event.findScrollView()
super.touchesBegan(touches, with: event)
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesEnded(touches, with: event)
}
public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesCancelled(touches, with: event)
}
}
extension UIEvent {
fileprivate func findScrollView() -> UIScrollView? {
guard
let firstTouch = allTouches?.first,
let targetView = firstTouch.view
else { return nil }
let scrollView = sequence(first: targetView, next: \.next).map { $0 }
.first {
guard let scrollView = $0 as? UIScrollView else {
return false
}
func isScrollable(scrollView: UIScrollView) -> Bool {
let contentInset: UIEdgeInsets
if #available(iOS 11.0, *) {
contentInset = scrollView.adjustedContentInset
} else {
contentInset = scrollView.contentInset
}
return
(scrollView.bounds.width - (contentInset.right + contentInset.left)
<= scrollView.contentSize.width)
|| (scrollView.bounds.height - (contentInset.top + contentInset.bottom)
<= scrollView.contentSize.height)
}
return isScrollable(scrollView: scrollView)
}
return (scrollView as? UIScrollView)
}
}
|
0 | import Foundation
import MapKit
protocol Region {
// Internal representation
var points:[CLLocationCoordinate2D] { get }
var title:String { get }
// Map presentation
var annotations:[MKAnnotation] { get }
var overlays:[MKOverlay] { get }
// Serialization
func toJSON() -> String
static func fromJSON(json:String) -> Region?
}
func regionsAsJSON(regions:[Region]) -> String {
let list = regions.map({$0.toJSON()})
return "[\(list.joinWithSeparator(","))]"
}
|
0 | //
// UIColor+TweaksTests.swift
// SwiftTweaks
//
// Created by Bryan Clark on 11/20/15.
// Copyright © 2015 Khan Academy. All rights reserved.
//
import XCTest
@testable import SwiftTweaks
class UIColor_TweaksTests: XCTestCase {
// MARK: Hex-To-Color
private struct HexToColorTestCase {
let string: String
let expectedColor: UIColor?
static func verify(testCase: HexToColorTestCase) {
if let generatedColor = UIColor.colorWithHexString(testCase.string) {
if let expectedColor = testCase.expectedColor {
XCTAssertEqual(generatedColor.hexString, expectedColor.hexString, "Generated color with hex \(generatedColor.hexString) from test string \(testCase.string), but expected color with hex \(expectedColor.hexString)")
} else {
XCTFail("Generated a color from hex string \(testCase.string), but expected no color.")
}
} else if let expectedColor = testCase.expectedColor {
XCTFail("Failed to generate expected color: \(expectedColor.hexString) from hex string \(testCase.string)")
}
}
}
func testHexToColor() {
let testCases = [
HexToColorTestCase(string: "FF0000", expectedColor: UIColor(red: 1, green: 0, blue: 0, alpha: 1)),
HexToColorTestCase(string: "00FF00", expectedColor: UIColor(red: 0, green: 1, blue: 0, alpha: 1)),
HexToColorTestCase(string: "0000FF", expectedColor: UIColor(red: 0, green: 0, blue: 1, alpha: 1)),
HexToColorTestCase(string: "000000", expectedColor: UIColor(red: 0, green: 0, blue: 0, alpha: 1)),
HexToColorTestCase(string: "FFFFFF", expectedColor: UIColor(red: 1, green: 1, blue: 1, alpha: 1)),
HexToColorTestCase(string: "FFFF00", expectedColor: UIColor(red: 1, green: 1, blue: 0, alpha: 1)),
HexToColorTestCase(string: "E6A55E", expectedColor: UIColor(red:0.905, green:0.649, blue:0.369, alpha:1.000)),
// While we *accept* colors with alpha values in their hex codes, we don't *generate* hexes with alpha.
HexToColorTestCase(string: "00000000", expectedColor: UIColor(red: 0, green: 0, blue: 0, alpha: 0)),
HexToColorTestCase(string: "000000FF", expectedColor: UIColor(red: 0, green: 0, blue: 0, alpha: 1)),
// Invalid strings
HexToColorTestCase(string: "Hello", expectedColor: nil),
HexToColorTestCase(string: "blue", expectedColor: nil),
HexToColorTestCase(string: "", expectedColor: nil),
// Three-letter test cases (not yet supported, though I'd like them to be someday!)
HexToColorTestCase(string: "f00", expectedColor: nil),
HexToColorTestCase(string: "aaa", expectedColor: nil),
HexToColorTestCase(string: "111", expectedColor: nil),
]
testCases.forEach { HexToColorTestCase.verify($0) }
// Re-run tests, prepending a "#" to each string.
testCases
.map { return HexToColorTestCase(string: "#"+$0.string, expectedColor: $0.expectedColor) }
.forEach { HexToColorTestCase.verify($0) }
}
// MARK: Color-To-Hex
private struct ColorToHexTestCase {
let color: UIColor
let expectedHex: String
static func verify(testCase: ColorToHexTestCase) {
XCTAssertEqual(testCase.color.hexString, testCase.expectedHex, "Expected color \(testCase.color) to generate #\(testCase.expectedHex)")
}
}
func testColorToHex() {
let testCases = [
ColorToHexTestCase(color: UIColor.redColor(), expectedHex: "#FF0000"),
ColorToHexTestCase(color: UIColor.greenColor(), expectedHex: "#00FF00"),
ColorToHexTestCase(color: UIColor.blueColor(), expectedHex: "#0000FF"),
ColorToHexTestCase(color: UIColor.whiteColor(), expectedHex: "#FFFFFF"),
ColorToHexTestCase(color: UIColor.blackColor(), expectedHex: "#000000"),
// Our UI ignores the alpha component of a hex code - so we expect a 6-character hex even when alpha's present
ColorToHexTestCase(color: UIColor.redColor().colorWithAlphaComponent(0), expectedHex: "#FF0000"),
ColorToHexTestCase(color: UIColor.blackColor().colorWithAlphaComponent(0.234), expectedHex: "#000000"),
ColorToHexTestCase(color: UIColor.whiteColor().colorWithAlphaComponent(1.0), expectedHex: "#FFFFFF")
]
testCases.forEach { ColorToHexTestCase.verify($0) }
}
}
|
0 | // 378. Kth Smallest Element in a Sorted Matrix
/**
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
*/
func kthSmallest(_ matrix: [[Int]], _ k: Int) -> Int {
guard matrix.count > 0 && matrix[0].count > 0 else { return 0 }
var indexArray = Array(repeating: 0, count: matrix.count)
var k = k
while k > 0 {
// find smallest value and save rowNumber
var smallRow = 0
var smallValue = Int.max
for i in 0..<matrix.count {
if indexArray[i] < matrix[0].count {
if matrix[i][indexArray[i]] <= smallValue {
smallValue = min(smallValue, matrix[i][indexArray[i]])
smallRow = i
}
}
}
k -= 1
if k == 0 {
return matrix[smallRow][indexArray[smallRow]]
}
indexArray[smallRow] += 1
}
return 0
} |
0 | //
// FilterViewController.swift
// Ookami
//
// Created by Maka on 22/2/17.
// Copyright © 2017 Mikunj Varsani. All rights reserved.
//
import UIKit
import Cartography
//A View controller for displaying a list of filters
class FilterViewController: UIViewController {
//The table view
lazy var tableView: UITableView = {
let t = UITableView(frame: .zero, style: .grouped)
t.cellLayoutMarginsFollowReadableWidth = false
t.delegate = self
t.dataSource = self
t.tableFooterView = UIView(frame: .zero)
t.backgroundColor = Theme.ControllerTheme().backgroundColor
return t
}()
//The filters we want to show
var filters: [FilterGroup] {
didSet {
tableView.reloadData()
}
}
/// Create a filter view controller.
///
/// - Parameter filters: An array of filter groups to display
init(filters: [FilterGroup] = []) {
self.filters = filters
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("use init(filters:) instead")
}
override func viewDidLoad() {
super.viewDidLoad()
//Add the tableview
self.view.addSubview(tableView)
constrain(tableView) { view in
view.edges == view.superview!.edges
}
}
}
//MARK:- Data source
extension FilterViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return filters.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filters[section].filters.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .value1, reuseIdentifier: "FilterValueCell")
cell.tintColor = Theme.Colors().secondary
let filter = filters[indexPath.section].filters[indexPath.row]
cell.textLabel?.text = filter.name.capitalized
cell.detailTextLabel?.text = filter.secondaryText
cell.accessoryType = filter.accessory
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return filters[section].name
}
}
//MARK:- Delegate
extension FilterViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let filter = filters[indexPath.section].filters[indexPath.row]
filter.onTap(self, tableView, tableView.cellForRow(at: indexPath))
}
}
|
0 | //
// ViewController.swift
// transitions
//
// Created by Daniel Alpizar on 4/9/21.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func SegueTapped(_ sender: Any) {
let mainStoryBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
guard let greenViewController = mainStoryBoard.instantiateViewController(
withIdentifier: "GreenViewController") as?
GreenViewController else{
print("Couldn’t find the view controller")
return
}
//navigationController?.pushViewController(greenViewController, animated: true)
greenViewController.modalTransitionStyle = .coverVertical
present(greenViewController, animated: true, completion: nil)
}
}
|
0 | //
// TLStoryOverlayControlView.swift
// TLStoryCamera
//
// Created by GarryGuo on 2017/5/31.
// Copyright © 2017年 GarryGuo. All rights reserved.
//
import UIKit
protocol TLStoryOverlayControlDelegate: NSObjectProtocol {
func storyOverlayCameraRecordingStart()
func storyOverlayCameraRecordingFinish(type:TLStoryType, recordTime: TimeInterval)
func storyOverlayCameraZoom(distance:CGFloat)
func storyOverlayCameraFlashChange() -> AVCaptureDevice.TorchMode
func storyOverlayCameraSwitch()
func storyOverlayCameraFocused(point:CGPoint)
func storyOverlayCameraClose()
}
class TLStoryOverlayControlView: UIView {
public weak var delegate:TLStoryOverlayControlDelegate?
fileprivate lazy var cameraBtn = TLStoryCameraButton.init(frame: CGRect.init(x: 0, y: 0, width: 80, height: 80))
fileprivate lazy var flashBtn:TLButton = {
let btn = TLButton.init(type: UIButton.ButtonType.custom)
btn.showsTouchWhenHighlighted = true
btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_auto"), for: .normal)
btn.addTarget(self, action: #selector(flashAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var switchBtn:TLButton = {
let btn = TLButton.init(type: UIButton.ButtonType.custom)
btn.showsTouchWhenHighlighted = true
btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_cam_turn"), for: .normal)
btn.addTarget(self, action: #selector(switchAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var closeBtn:TLButton = {
let btn = TLButton.init(type: UIButton.ButtonType.custom)
btn.showsTouchWhenHighlighted = true
btn.setImage(UIImage.tl_imageWithNamed(named: "story_icon_close"), for: .normal)
btn.addTarget(self, action: #selector(closeAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var cameraBtnHintLabel: UILabel = {
let l = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 20))
l.font = UIFont.systemFont(ofSize: 15)
l.textColor = UIColor.init(colorHex: 0xffffff, alpha: 0.8)
l.text = TLStoryConfiguration.restrictMediaType == nil ? TLStoryCameraResource.string(key: "tl_photo_video_hint") :
(TLStoryConfiguration.restrictMediaType == .photo ? TLStoryCameraResource.string(key: "tl_photo_hint") : TLStoryCameraResource.string(key: "tl_video_hint"))
l.sizeToFit()
return l
}()
fileprivate var photoLibraryHintView:TLPhotoLibraryHintView?
fileprivate var tapGesture:UITapGestureRecognizer?
fileprivate var doubleTapGesture:UITapGestureRecognizer?
override init(frame: CGRect) {
super.init(frame: frame)
closeBtn.sizeToFit()
closeBtn.center = CGPoint.init(x: self.width - closeBtn.width / 2 - 15, y: closeBtn.height / 2 + 15)
addSubview(closeBtn)
cameraBtn.center = CGPoint.init(x: self.center.x, y: self.bounds.height - 52 - 40)
cameraBtn.delegete = self
addSubview(cameraBtn)
if (TLStoryConfiguration.showCameraBtnHint) {
cameraBtnHintLabel.center = CGPoint.init(x: self.center.x, y: cameraBtn.centerY - cameraBtn.height / 2 - 20 / 2 - 5)
addSubview(cameraBtnHintLabel)
}
flashBtn.sizeToFit()
flashBtn.center = CGPoint.init(x: cameraBtn.centerX - 100, y: cameraBtn.centerY)
addSubview(flashBtn)
switchBtn.sizeToFit()
switchBtn.center = CGPoint.init(x: cameraBtn.centerX + 100, y: cameraBtn.centerY)
addSubview(switchBtn)
photoLibraryHintView = TLPhotoLibraryHintView.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: 50))
photoLibraryHintView?.center = CGPoint.init(x: self.self.width / 2, y: self.height - 25)
addSubview(photoLibraryHintView!)
tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(tapAction))
tapGesture?.delegate = self
tapGesture!.numberOfTapsRequired = 1
self.addGestureRecognizer(tapGesture!)
doubleTapGesture = UITapGestureRecognizer.init(target: self, action: #selector(doubleTapAction))
doubleTapGesture?.delegate = self
doubleTapGesture!.numberOfTapsRequired = 2
self.addGestureRecognizer(doubleTapGesture!)
tapGesture!.require(toFail: doubleTapGesture!)
}
public func dismiss() {
self.isHidden = true
self.cameraBtn.reset()
self.photoLibraryHintView?.isHidden = false
self.cameraBtnHintLabel.isHidden = false
}
public func display() {
self.isHidden = false
self.cameraBtn.show()
}
public func beginHintAnim () {
photoLibraryHintView?.startAnim()
}
@objc fileprivate func tapAction(sender:UITapGestureRecognizer) {
let point = sender.location(in: self)
self.delegate?.storyOverlayCameraFocused(point: point)
}
@objc fileprivate func doubleTapAction(sender:UITapGestureRecognizer) {
self.delegate?.storyOverlayCameraSwitch()
}
@objc fileprivate func closeAction() {
self.delegate?.storyOverlayCameraClose()
}
@objc fileprivate func flashAction(sender: UIButton) {
let mode = self.delegate?.storyOverlayCameraFlashChange()
let imgs = [AVCaptureDevice.TorchMode.on:UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_on"),
AVCaptureDevice.TorchMode.off:UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_off"),
AVCaptureDevice.TorchMode.auto:UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_auto")]
sender.setImage(imgs[mode!]!, for: .normal)
}
@objc fileprivate func switchAction(sender: UIButton) {
UIView.animate(withDuration: 0.3, animations: {
sender.transform = sender.transform.rotated(by: CGFloat(Double.pi))
}) { (x) in
self.delegate?.storyOverlayCameraSwitch()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TLStoryOverlayControlView: UIGestureRecognizerDelegate {
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
let point = gestureRecognizer.location(in: self)
if self.cameraBtn.frame.contains(point) {
return false
}
return true
}
}
extension TLStoryOverlayControlView: TLStoryCameraButtonDelegate {
internal func cameraStart(hoopButton: TLStoryCameraButton) {
self.delegate?.storyOverlayCameraRecordingStart()
photoLibraryHintView?.isHidden = true
cameraBtnHintLabel.isHidden = true
}
internal func cameraDrag(hoopButton: TLStoryCameraButton, offsetY: CGFloat) {
self.delegate?.storyOverlayCameraZoom(distance: offsetY)
}
internal func cameraComplete(hoopButton: TLStoryCameraButton, type: TLStoryType) {
self.delegate?.storyOverlayCameraRecordingFinish(type: type, recordTime: hoopButton.progress)
self.isHidden = true
}
}
class TLPhotoLibraryHintView: UIView {
fileprivate lazy var hintLabel:UILabel = {
let label = UILabel.init()
label.textColor = UIColor.init(colorHex: 0xffffff, alpha: 0.8)
label.font = UIFont.systemFont(ofSize: 12)
label.text = TLStoryCameraResource.string(key: "tl_swipe_up_open_album")
label.layer.shadowColor = UIColor.black.cgColor
label.layer.shadowOffset = CGSize.init(width: 1, height: 1)
label.layer.shadowRadius = 2
label.layer.shadowOpacity = 0.7
return label
}()
fileprivate lazy var arrowIco = UIImageView.init(image: UIImage.tl_imageWithNamed(named: "story_icon_up"))
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(hintLabel)
hintLabel.sizeToFit()
hintLabel.center = CGPoint.init(x: self.width / 2, y: self.height - 10 - hintLabel.height / 2)
self.addSubview(arrowIco)
arrowIco.sizeToFit()
arrowIco.center = CGPoint.init(x: self.width / 2, y: 10 + arrowIco.height / 2)
}
public func startAnim() {
UIView.animate(withDuration: 0.8, delay: 0, options: [.repeat,.autoreverse], animations: {
self.arrowIco.centerY = 5 + self.arrowIco.height / 2
}, completion: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
0 | //
// SettingsTableViewController.swift
// WeatherApp
//
// Created by Suraj Shandil on 7/29/21.
//
import UIKit
class SettingsTableViewController: UITableViewController {
@IBOutlet weak var unitsSegment: UISegmentedControl!
@IBOutlet weak var mapTypeSegment: UISegmentedControl!
@IBOutlet weak var resetBookmarkSwitch: UISwitch!
var settingsManager = SettingsManager.sharedInstance
// MARK: - View Life Cycles -
override func viewDidLoad() {
super.viewDidLoad()
self.setupNavbar()
self.configureSegmentControlsAndSwitchAppearance()
self.setupDefaultSettings()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Private Method Implementation -
private func configureSegmentControlsAndSwitchAppearance() {
unitsSegment.selectedSegmentTintColor = .systemTeal
mapTypeSegment.selectedSegmentTintColor = .systemTeal
resetBookmarkSwitch.onTintColor = .systemTeal
}
private func setupDefaultSettings() {
unitsSegment.selectedSegmentIndex = settingsManager.unitType == 0 ? 0 : 1
resetBookmarkSwitch.isOn = settingsManager.resetBookMark == false ? false : true
mapTypeSegment.selectedSegmentIndex = settingsManager.mapType == 0 ? 0 : 1
}
private func setupNavbar() {
title = "Settings"
let leftBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "arrowtriangle.backward.fill"), style: .plain, target: self, action: #selector(goBack))
leftBarButtonItem.tintColor = .white
navigationItem.leftBarButtonItem = leftBarButtonItem
navigationController?.navigationBar.barTintColor = .systemGray2
}
@objc private func goBack() {
debugPrint(self.navigationController?.viewControllers as Any)
self.navigationController?.popViewController(animated: true)
}
private func reloadTableViewData() {
tableView.reloadData()
}
// MARK: - Table view data source -
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
// MARK: - UIButton Action -
@IBAction func unitSegmentIndexChanged(_ sender: Any) {
let segment = sender as! UISegmentedControl
if segment.selectedSegmentIndex == 1 {
settingsManager.unitType = 1
} else {
settingsManager.unitType = 0
}
self.reloadTableViewData()
}
@IBAction func mapSegmentIndexChanged(_ sender: Any) {
let segment = sender as! UISegmentedControl
if segment.selectedSegmentIndex == 1 {
settingsManager.mapType = 1
} else {
settingsManager.mapType = 0
}
self.reloadTableViewData()
}
@IBAction func resetBookmarkValueChanged(_ sender: Any) {
let bookmarkSwitch = sender as! UISwitch
if bookmarkSwitch.isOn {
settingsManager.resetBookMark = true
} else {
settingsManager.resetBookMark = false
}
self.reloadTableViewData()
}
}
|
0 | //
// LogsTool.swift
// Baymax
//
// Created by Simon Mitchell on 01/04/2020.
// Copyright © 2020 3 SIDED CUBE. All rights reserved.
//
import Foundation
/// A tool for displaying logs collated using `Logger` objects
public class LogsTool: DiagnosticTool {
/// Disables or enables Baymax logging
public static var loggingEnabled: Bool {
get {
return UserDefaults.standard.baymaxLoggingEnabled
}
set {
UserDefaults.standard.baymaxLoggingEnabled = newValue
}
}
/// Instructs Baymax logging to either be on or off by default,
/// defaults to `false`
public static var loggingEnabledByDefault: Bool = false
/// Can be provided to override how logs are shared by default
///
/// You will be handed an array of log files, and the sender if you return false, indicating
/// that you weren't able to share them, then they will continue to be shared
/// using the default mechanism!
public static var shareHandler: (([LogFile], Any) -> Bool)?
public var displayName: String {
return "Logs"
}
public func launchUI(in navigationController: UINavigationController) {
let view = LogsTableViewController(style: .grouped)
navigationController.show(view, sender: self)
}
}
|
0 | //
// ViewController.swift
// Chambas
//
// Created by David Velarde on 11/3/16.
// Copyright © 2016 Area51. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var arrayEmpresas = [Empresa]()
var empresaSeleccionada : Empresa?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let empresa1 = Empresa()
empresa1.nombre = "Amazon"
empresa1.imagen = "amazon"
empresa1.descripcion = "Empresa que vende cosas"
empresa1.numeroEmpleados = 2500
empresa1.ceo = "Jorge Espinoza"
empresa1.direccion = "Av. Republica de Panama 2476"
//empresa1.localizacion = CGPoint(x: 35.787873, y: -121.8860108)
let localizacion1 = [ "latitud" : 35.0, "longitud":40.0]
let localizacion2 = [ "latitud" : 40.0, "longitud":-10.0]
let localizacion3 = [ "latitud" : 45.0, "longitud":-40.0]
let localizacion4 = [ "latitud" : 50.0, "longitud":-100.0]
empresa1.localizacion.append(localizacion1)
empresa1.localizacion.append(localizacion2)
empresa1.localizacion.append(localizacion3)
empresa1.localizacion.append(localizacion4)
arrayEmpresas.append(empresa1)
arrayEmpresas.append(empresa1)
arrayEmpresas.append(empresa1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayEmpresas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! EmpresaCell
let empresa = arrayEmpresas[indexPath.row] as Empresa
cell.imgEmpresa.image = UIImage(named: empresa.imagen)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
empresaSeleccionada = arrayEmpresas[indexPath.row]
performSegue(withIdentifier: "fromMainToDetail", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! DetalleViewController
vc.empresaRecibida = empresaSeleccionada
}
}
|
0 | //
// Character.swift
// GOT-Challenge-Swift
//
// Created by Conrado Mateu Gisbert on 08/03/17.
// Copyright © 2017 conradomateu. All rights reserved.
//
import Foundation
@testable import GOT_Challenge_Swift
extension GOT_Challenge_Swift.Character: Equatable {
}
public func == (lhs: GOT_Challenge_Swift.Character, rhs: GOT_Challenge_Swift.Character) -> Bool {
return lhs.id == rhs.id
}
|
0 | import Syft
enum SongExpressionError: Error {
case unknown
}
protocol SongExpression {
func evaluate() -> String
}
struct SongNumber: SongExpression {
let value: Int
func evaluate() -> String {
return "\(value)"
}
}
//func song() -> Pipeline<SongExpression> {
//// let input = "[].length() = 0\n[_|y].length() = 1.+(y.length())"
// let input = ""
// return Pipeline(defaultInput: input, parser: makeParser(), transformer: makeTransformer()) { ast in
// let result = ast.evaluate()
// return "\(result)"
// }
//}
|
0 | //
// FontMetrics.swift
// Capable
//
// Created by Christoph Wendt on 31.03.18.
//
import Foundation
import UIKit
class FontMetrics: FontMetricsProtocol {
var osVersionProvider: OsVersionProviderProtocol
init() {
self.osVersionProvider = OsVersionProvider()
}
var scaler: CGFloat {
get {
return UIFont.preferredFont(forTextStyle: .body).pointSize / 17.0
}
}
func scaledFont(for font: UIFont) -> UIFont {
if(self.osVersionProvider.isOsVersionPrior11()) {
return self.scaledFontPriorIOS11(for: font)
} else {
return self.scaledFontSinceIOS11(for: font)
}
}
func scaledFontPriorIOS11(for font: UIFont) -> UIFont {
let scaledFontSize = font.pointSize * self.scaler
return font.withSize(scaledFontSize)
}
func scaledFontSinceIOS11(for font: UIFont) -> UIFont {
if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) {
let fontMetrics = UIFontMetrics.default
return fontMetrics.scaledFont(for: font)
}
fatalError()
}
}
|
0 | //
// FunctionalSwiftExampleUITests.swift
// FunctionalSwiftExampleUITests
//
// Created by Daniel Mandea on 06/05/2019.
// Copyright © 2019 Daniel Mandea. All rights reserved.
//
import XCTest
class FunctionalSwiftExampleUITests: XCTestCase {
override func setUp() {
// 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
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// 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 tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
|
0 | //
// RSSItem.swift
// SwiftRSS_Example
//
// Created by Thibaut LE LEVIER on 28/09/2014.
// Copyright (c) 2014 Thibaut LE LEVIER. All rights reserved.
//
import UIKit
class RSSItem: NSObject, NSCoding {
var title: String?
var link: NSURL?
func setLink(let linkString: String!)
{
link = NSURL(string: linkString)
}
var guid: String?
var pubDate: NSDate?
func setPubDate(let dateString: String!)
{
pubDate = NSDate.dateFromInternetDateTimeString(dateString)
}
var itemDescription: String?
var content: String?
// Wordpress specifics
var commentsLink: NSURL?
func setCommentsLink(let linkString: String!)
{
commentsLink = NSURL(string: linkString)
}
var commentsCount: Int?
var commentRSSLink: NSURL?
func setCommentRSSLink(let linkString: String!)
{
commentRSSLink = NSURL(string: linkString)
}
var author: String?
var categories: [String]! = [String]()
var imagesFromItemDescription: [NSURL]! {
if let itemDescription = self.itemDescription?
{
return itemDescription.imageLinksFromHTMLString
}
return [NSURL]()
}
var imagesFromContent: [NSURL]! {
if let content = self.content?
{
return content.imageLinksFromHTMLString
}
return [NSURL]()
}
override init()
{
super.init()
}
// MARK: NSCoding
required init(coder aDecoder: NSCoder)
{
super.init()
title = aDecoder.decodeObjectForKey("title") as? String
link = aDecoder.decodeObjectForKey("link") as? NSURL
guid = aDecoder.decodeObjectForKey("guid") as? String
pubDate = aDecoder.decodeObjectForKey("pubDate") as? NSDate
itemDescription = aDecoder.decodeObjectForKey("description") as? NSString
content = aDecoder.decodeObjectForKey("content") as? NSString
commentsLink = aDecoder.decodeObjectForKey("commentsLink") as? NSURL
commentsCount = aDecoder.decodeObjectForKey("commentsCount") as? Int
commentRSSLink = aDecoder.decodeObjectForKey("commentRSSLink") as? NSURL
author = aDecoder.decodeObjectForKey("author") as? String
categories = aDecoder.decodeObjectForKey("categories") as? [String]
}
func encodeWithCoder(aCoder: NSCoder)
{
if let title = self.title?
{
aCoder.encodeObject(title, forKey: "title")
}
if let link = self.link?
{
aCoder.encodeObject(link, forKey: "link")
}
if let guid = self.guid?
{
aCoder.encodeObject(guid, forKey: "guid")
}
if let pubDate = self.pubDate?
{
aCoder.encodeObject(pubDate, forKey: "pubDate")
}
if let itemDescription = self.itemDescription?
{
aCoder.encodeObject(itemDescription, forKey: "description")
}
if let content = self.content?
{
aCoder.encodeObject(content, forKey: "content")
}
if let commentsLink = self.commentsLink?
{
aCoder.encodeObject(commentsLink, forKey: "commentsLink")
}
if let commentsCount = self.commentsCount?
{
aCoder.encodeObject(commentsCount, forKey: "commentsCount")
}
if let commentRSSLink = self.commentRSSLink?
{
aCoder.encodeObject(commentRSSLink, forKey: "commentRSSLink")
}
if let author = self.author?
{
aCoder.encodeObject(author, forKey: "author")
}
aCoder.encodeObject(categories, forKey: "categories")
}
} |
0 | //
// AddItemViewController.swift
// ToDoList
//
// Created by Alex Paul on 1/9/19.
// Copyright © 2019 Alex Paul. All rights reserved.
//
import UIKit
class AddItemViewController: UIViewController {
@IBOutlet weak var titleTextView: UITextView!
@IBOutlet weak var descriptionTextView: UITextView!
private let titleTextViewPlaceholder = "Title"
private let descriptionTextViewPlaceholder = "Item Description"
override func viewDidLoad() {
super.viewDidLoad()
titleTextView.delegate = self
descriptionTextView.delegate = self
titleTextView.textColor = .lightGray
titleTextView.text = titleTextViewPlaceholder
descriptionTextView.textColor = .lightGray
descriptionTextView.text = descriptionTextViewPlaceholder
}
@IBAction func cancel(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
@IBAction func addItem(_ sender: UIBarButtonItem) {
guard let itemTitle = titleTextView.text,
let itemDescription = descriptionTextView.text else {
// handle case
return
}
// create an instance of the Item object
let date = Date()
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.formatOptions = [.withInternetDateTime, .withFullDate, .withFullTime, .withDashSeparatorInDate, .withTimeZone]
let timestamp = isoDateFormatter.string(from: date)
let item = Item(title: itemTitle, description: itemDescription, createdAt: timestamp)
// save to disk
ItemsModel.saveItem(item: item)
dismiss(animated: true, completion: nil)
}
}
extension AddItemViewController: UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.text == titleTextViewPlaceholder || textView.text == descriptionTextViewPlaceholder {
textView.textColor = .black
textView.text = ""
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView == titleTextView {
if textView.text == "" {
textView.textColor = .lightGray
textView.text = titleTextViewPlaceholder
}
} else if textView == descriptionTextView {
if textView.text == "" {
textView.textColor = .lightGray
textView.text = descriptionTextViewPlaceholder
}
}
}
}
|
0 | //
// Cache+Switch.swift
// George Tsifrikas
//
// Created by George Tsifrikas on 12/06/2017.
// Copyright © 2017 George Tsifrikas. All rights reserved.
//
import Foundation
public enum CacheSwitchResult {
/// The first Cache of the switch
case cacheA
/// The second Cache of the switch
case cacheB
}
public func switchCache<A: Cache, B: Cache>(cacheA: A,
cacheB: B,
switchClosure: @escaping (_ key: A.Key) -> CacheSwitchResult)
-> CompositeCache<A.Key, A.Value> where A.Key == B.Key, A.Value == B.Value {
return CompositeCache(
get: { key in
switch switchClosure(key) {
case .cacheA:
return cacheA.get(key)
case .cacheB:
return cacheB.get(key)
}
},
set: { (value, key) in
switch switchClosure(key) {
case .cacheA:
return cacheA.set(value, for: key)
case .cacheB:
return cacheB.set(value, for: key)
}
},
clear: {
cacheA.clear()
cacheB.clear()
}
)
}
|
0 | //
// RegisterViewController.swift
// register_login_template
//
// Created by Sarvad shetty on 1/18/18.
// Copyright © 2018 Sarvad shetty. All rights reserved.
//
import UIKit
import Firebase
class RegisterViewController: UIViewController {
//MARK: Outlets
@IBOutlet weak var regButton: UIButton!
@IBOutlet weak var emailId: UITextField!
@IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: Registering..
@IBAction func regPressed(_ sender: Any) {
regButton.isEnabled = false
Auth.auth().createUser(withEmail: emailId.text!, password: password.text!) { (user, error) in
if error != nil {
print("error registering , \(error!)")
}
else{
print("registration successfull")
self.performSegue(withIdentifier: "goToChat", sender: self)
self.regButton.isEnabled = true
}
}
}
}
|
0 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 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
//
//===----------------------------------------------------------------------===//
public protocol NIOHTTP2Error: Equatable, Error { }
/// Errors that NIO raises when handling HTTP/2 connections.
public enum NIOHTTP2Errors {
/// NIO's upgrade handler encountered a successful upgrade to a protocol that it
/// does not recognise.
public struct InvalidALPNToken: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to issue a write on a stream that does not exist.
public struct NoSuchStream: NIOHTTP2Error {
/// The stream ID that was used that does not exist.
public var streamID: HTTP2StreamID
public init(streamID: HTTP2StreamID) {
self.streamID = streamID
}
}
/// A stream was closed.
public struct StreamClosed: NIOHTTP2Error {
/// The stream ID that was closed.
public var streamID: HTTP2StreamID
/// The error code associated with the closure.
public var errorCode: HTTP2ErrorCode
public init(streamID: HTTP2StreamID, errorCode: HTTP2ErrorCode) {
self.streamID = streamID
self.errorCode = errorCode
}
}
public struct BadClientMagic: NIOHTTP2Error {
public init() {}
}
/// A stream state transition was attempted that was not valid.
public struct BadStreamStateTransition: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to change the flow control window size, either via
/// SETTINGS or WINDOW_UPDATE, but this change would move the flow control
/// window size out of bounds.
public struct InvalidFlowControlWindowSize: NIOHTTP2Error {
/// The delta being applied to the flow control window.
public var delta: Int
/// The size of the flow control window before the delta was applied.
public var currentWindowSize: Int
public init(delta: Int, currentWindowSize: Int) {
self.delta = delta
self.currentWindowSize = currentWindowSize
}
}
/// A frame was sent or received that violates HTTP/2 flow control rules.
public struct FlowControlViolation: NIOHTTP2Error {
public init() { }
}
/// A SETTINGS frame was sent or received with an invalid setting.
public struct InvalidSetting: NIOHTTP2Error {
/// The invalid setting.
public var setting: HTTP2Setting
public init(setting: HTTP2Setting) {
self.setting = setting
}
}
/// An attempt to perform I/O was made on a connection that is already closed.
public struct IOOnClosedConnection: NIOHTTP2Error {
public init() { }
}
/// A SETTINGS frame was received that is invalid.
public struct ReceivedBadSettings: NIOHTTP2Error {
public init() { }
}
/// A violation of SETTINGS_MAX_CONCURRENT_STREAMS occurred.
public struct MaxStreamsViolation: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to use a stream ID that is too small.
public struct StreamIDTooSmall: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to send a frame without having previously sent a connection preface!
public struct MissingPreface: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to create a stream after a GOAWAY frame has forbidden further
/// stream creation.
public struct CreatedStreamAfterGoaway: NIOHTTP2Error {
public init() { }
}
/// A peer has attempted to create a stream with a stream ID it is not permitted to use.
public struct InvalidStreamIDForPeer: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to send a new GOAWAY frame whose lastStreamID is higher than the previous value.
public struct RaisedGoawayLastStreamID: NIOHTTP2Error {
public init() { }
}
/// The size of the window increment is invalid.
public struct InvalidWindowIncrementSize: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to push a stream, even though the settings forbid it.
public struct PushInViolationOfSetting: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to use a currently unsupported feature.
public struct Unsupported: NIOHTTP2Error {
public var info: String
public init(info: String) {
self.info = info
}
}
public struct UnableToSerializeFrame: NIOHTTP2Error {
public init() { }
}
public struct UnableToParseFrame: NIOHTTP2Error {
public init() { }
}
}
/// This enum covers errors that are thrown internally for messaging reasons. These should
/// not leak.
internal enum InternalError: Error {
case attemptedToCreateStream
case codecError(code: HTTP2ErrorCode)
}
|
0 | //
// Selfinfo.swift
// FeedMyFit
//
// Created by 祁汝鑫 on 2020/8/6.
//
import Foundation
// MARK: - Request
// Id=xxxxxxx&Token=xxxxxxx
// MARK: - Return
struct Selfinfo: Codable {
var Phonenumber: String
var Avatar: String?
var Username: String
var Sex: String
var Height: Double
var Weight: Double
var BirthDate: String?
var City: String
var SkinType: Int
var HeatQuantityDemand: Int
var ProteinDemand: Int
var CarbohydratesDemand: Int
var FatDemand: Int
var VitaminADemand: Int
var VitaminB1Demand: Int
var VitaminB2Demand: Int
var VitaminB6Demand: Int
var VitaminB12Demand: Int
var VitaminCDemand: Int
var VitaminDDemand: Int
var VitaminEDemand: Int
var VitaminKDemand: Int
}
|
0 | //
// StringEx.swift
// AppSpawnKey
//
// Created by TKOxff on 2021/03/14.
//
import Foundation
extension String {
// App Name.app -> App Name
var splitedAppName : String {
let substrings = self.split(separator: ".")
return String(substrings.first ?? "")
}
}
|
0 | //
// storage.swift
// NebulaeCommission
//
// Created by Mayur.Patel.653 on 07/07/21.
//
import Foundation
public class Storage{
static let shared = Storage()
private let defaults = UserDefaults.standard
var notificationToken : String? = nil
// func setConnectionMode(cMode :ConnectionMode){
// let encoder = JSONEncoder()
// if let encoded = try? encoder.encode(cMode) {
//
// defaults.set(encoded, forKey: "ConnectionMode")
// }
// }
//
// func getConnectionMode() -> ConnectionMode?{
// if let cMode = defaults.object(forKey: "ConnectionMode") as? Data {
//
// let decoder = JSONDecoder()
// if let cMode = try? decoder.decode(ConnectionMode.self, from: cMode) {
//
// return cMode
// }
// }
// return nil
// }
//
// func setNetworkInfo(networkInfo :NetworkInfo){
// let encoder = JSONEncoder()
// if let encoded = try? encoder.encode(networkInfo) {
//
// defaults.set(encoded, forKey: "NetworkInfo")
// }
// }
//
// func getNetworkInfo() -> NetworkInfo?{
// if let cMode = defaults.object(forKey: "NetworkInfo") as? Data {
//
// let decoder = JSONDecoder()
// if let networkInfo = try? decoder.decode(NetworkInfo.self, from: cMode) {
//
// return networkInfo
// }
// }
// return nil
// }
//
//
//
// func clearAllStorage(){
//
// //defaults.removeObject(forKey: "SLEEPDATE")
// defaults.removeObject(forKey: "ConnectionMode")
// }
}
|
0 | //
// ATHMPurchaseResponse.swift
// athmovil-checkout
//
// Created by Hansy Enrique on 7/19/20.
// Copyright © 2020 Evertec. All rights reserved.
//
import Foundation
@objc(ATHMPaymentResponse)
final public class ATHMPaymentResponse: NSObject {
/// Current payment, it is the same object that the client have been sent in the request
@objc public let payment: ATHMPayment
/// Status of the payment completed, expired o cancelled and other purchase's properties
@objc public let status: ATHMPaymentStatus
/// ATH Móvil's customer
@objc public let customer: ATHMCustomer
@objc public override var description: String {
"""
Response:
\n
\(payment.description)
\n
\(customer.description)
\n
\(status.description)
"""
}
required init(payment: ATHMPayment, status: ATHMPaymentStatus, customer: ATHMCustomer) {
self.payment = payment
self.customer = customer
self.status = status
}
}
|
0 | import Foundation
import Shared
public struct SPM {
public struct Package: Decodable {
public static func load() throws -> Self {
let shell = Shell()
let jsonString = try shell.exec(["swift", "package", "describe", "--type", "json"], stderr: false)
guard let jsonData = jsonString.data(using: .utf8) else {
throw PeripheryError.packageError(message: "Failed to read swift package description.")
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return try decoder.decode(Package.self, from: jsonData)
}
public let name: String
public let path: String
public let targets: [Target]
public var swiftTargets: [Target] {
targets.filter { $0.moduleType == "SwiftTarget" }
}
}
public struct Target: Decodable {
public let name: String
public let path: String
public let sources: [String]
public let moduleType: String
func build() throws {
let shell = Shell()
try shell.exec(["swift", "build", "--enable-test-discovery", "--target", name])
}
}
}
|
0 | //
// ViewController.swift
// TwilioTest
//
// Created by fawad on 22/01/2017.
// Copyright © 2017 fawad. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func availableNumbersButtonAciton(_ sender: Any) {
print("availableNumbersButtonAciton")
TwilioManager.shared.availableNumbers(countryISO: "US", areaCode: "510", inRegion: nil) { (phoneNumbers, errorMsg) in
print(phoneNumbers ?? "no numbers")
}
}
@IBAction func IncomingNumbersButtonAciton(_ sender: Any) {
print("IncomingNumbersButtonAciton")
TwilioManager.shared.IncomingNumbers { (phoneNumbers, errorMsg) in
print(phoneNumbers ?? "no numbers")
}
}
@IBAction func sendMessageButtonAciton(_ sender: Any) {
print("sendMessageButtonAciton")
TwilioManager.shared.sendMessage(from: "+17606643093", to: "+14156105816", body: "Hello from Twilio, Rishi") { (response, errorMsg) in
//print("error: \(success)")
print("response: \(response)")
}
}
@IBAction func buyNumberButtonAciton(_ sender: Any) {
print("buyNumberButtonAciton")
// TODO: USE TwilioManager
// let url = "https://api.twilio.com/2010-04-01/Accounts/\(K.Twilio.SID)/IncomingPhoneNumbers.json"
//
// let params = ["AreaCode": "510"]
// //let params = ["PhoneNumber": "+15103691691"]
//
// postRequest(url: url, method: .post, params: params)
}
@IBAction func messageListOutgoingButtonAciton(_ sender: Any) {
TwilioManager.shared.messageList(phoneNo: myTwilioNumber,phoneDirection: .to) { (messageHistoryList, errorMsg) in
guard let histories = messageHistoryList else {
print("Error")
return
}
print(histories)
}
}
@IBAction func messageListIncomingButtonAciton(_ sender: Any) {
TwilioManager.shared.messageList(phoneNo: myTwilioNumber,phoneDirection: .from) { (messageHistoryList, errorMsg) in
guard let histories = messageHistoryList else {
print("Error")
return
}
print(histories)
}
}
}
|
0 | import UIKit
class GameView: UIView {
weak var delegate: GameViewDelegate?
init() {
super.init(frame: .zero)
backgroundColor = UIColor(color: .darkPurple383357)
addSubviews()
setupLayout()
configurePauseButtonAction()
configureRestartButtonAction()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(score: Int) {
scoreNumberLabel.text = "\(score)"
}
// MARK: Actions
func configurePauseButtonAction() {
pauseButton.buttonActionClosure = { [weak self] in
guard let sself = self else { return }
sself.delegate?.gameViewDidTapPause(sself)
}
}
func configureRestartButtonAction() {
restartButton.buttonActionClosure = { [weak self] in
guard let sself = self else { return }
sself.delegate?.gameViewDidTapRestart(sself)
}
}
// MARK: Subviews
private func addSubviews() {
addSubview(topView)
topView.addSubview(pauseButton)
topView.addSubview(restartButton)
topView.addSubview(scoreView)
scoreView.addSubview(scoreTextLabel)
scoreView.addSubview(scoreNumberLabel)
addSubview(boardContainerView)
}
private let topView: UIView = {
let view = UIView(frame: .zero)
view.backgroundColor = .clear
return view
}()
private let pauseButton = Button(image: UIImage(asset: .pause))
private let restartButton = Button(image: UIImage(asset: .restartIcon))
private let scoreView: UIView = {
let view = UIView(frame: .zero)
view.backgroundColor = .clear
return view
}()
private let scoreTextLabel: UILabel = {
let label = UILabel(frame: .zero)
label.text = score.localized
label.font = UIFont(font: FontFamily.BebasNeue.bold, size: 17)
label.textColor = UIColor(color: .lightPurple7D75C7)
return label
}()
private let scoreNumberLabel: UILabel = {
let label = UILabel(frame: .zero)
label.text = "0"
label.font = UIFont(font: FontFamily.BebasNeue.bold, size: 46)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
label.textColor = UIColor(color: .white)
return label
}()
let boardContainerView: UIView = {
let view = UIView(frame: .zero)
view.backgroundColor = .clear
return view
}()
var boardView: GameBoardView? {
didSet {
if let oldValue = oldValue {
oldValue.removeFromSuperview()
}
if let boardView = boardView {
configureBoardView(boardView)
}
}
}
// MARK: Layout
private func setupLayout() {
topView.snp.makeConstraints {
guard let topViewSuperview = topView.superview else { return }
$0.top.equalTo(20)
$0.left.equalTo(16)
$0.right.equalTo(-16)
$0.height.greaterThanOrEqualTo(72)
$0.height.equalTo(topViewSuperview).multipliedBy(0.15).priority(.low)
}
pauseButton.snp.makeConstraints {
$0.left.equalToSuperview()
$0.centerYWithinMargins.equalToSuperview()
}
pauseButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal)
scoreView.snp.makeConstraints {
$0.centerWithinMargins.equalToSuperview()
$0.left.greaterThanOrEqualTo(pauseButton.snp.right).offset(16)
$0.right.lessThanOrEqualTo(restartButton.snp.left).offset(-16)
}
scoreNumberLabel.snp.makeConstraints {
$0.top.equalToSuperview()
$0.centerXWithinMargins.equalToSuperview()
$0.left.greaterThanOrEqualTo(0)
$0.right.lessThanOrEqualTo(0)
}
scoreTextLabel.snp.makeConstraints {
$0.top.equalTo(scoreNumberLabel.snp.bottom)
$0.centerXWithinMargins.equalToSuperview()
$0.left.greaterThanOrEqualTo(0)
$0.right.lessThanOrEqualTo(0)
$0.bottom.equalToSuperview()
}
restartButton.snp.makeConstraints {
$0.right.equalToSuperview()
$0.centerYWithinMargins.equalToSuperview()
}
restartButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal)
boardContainerView.snp.makeConstraints {
$0.top.equalTo(topView.snp.bottom)
$0.left.equalTo(16)
$0.right.equalTo(-16)
$0.bottom.equalTo(-16)
}
}
private func configureBoardView(_ boardView: GameBoardView) {
boardView.delegate = self
boardContainerView.addSubview(boardView)
boardView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
}
|
0 | //
// AppDelegate.swift
// AppStoreReviews
//
// Created by Dmitrii Ivanov on 21/07/2020.
// Copyright © 2020 ING. All rights reserved.
//
import Foundation
struct Review: Codable {
let author: String
let version: String
let rating: Int
let title: String
let id: String
let content: String
func ratingVersionText() -> String {
return "\(String(repeating:"⭐️", count: rating)) (ver: \(version))"
}
}
extension Review: CustomStringConvertible {
var description: String {
return title + " " + content
}
}
extension Review {
init(entry: Entry) {
self.init(author: entry.author.name.label,
version: entry.imVersion.label,
rating: Int(entry.imRating.label)!,
title: entry.title.label,
id: entry.id.label,
content: entry.content.label)
}
}
|
0 | //
// SelectionTypeModule.swift
// UsbongKit
//
// Created by Chris Amanse on 26/05/2016.
// Copyright © 2016 Usbong Social Systems, Inc. All rights reserved.
//
import Foundation
/// Protocol for selection type
public protocol SelectionTypeModule: Module {
var selectedIndices: [Int] { get }
func selectIndex(_ index: Int)
func deselectIndex(_ index: Int)
func toggleIndex(_ index: Int)
}
|
0 | //
// ChartAxisValuesGeneratorNice.swift
// SwiftCharts
//
// Created by ischuetz on 04/08/16.
// Copyright © 2016 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartAxisValuesGeneratorNice: ChartAxisGeneratorMultiplier {
open override var first: Double? {
return Double(minValue)
}
open override var last: Double? {
return Double(maxValue)
}
fileprivate var minValue: Double
fileprivate var maxValue: Double
fileprivate let minSpace: CGFloat
fileprivate let preferredDividers: Int
fileprivate let maxTextSize: CGFloat
public init(minValue: Double, maxValue: Double, preferredDividers: Int, minSpace: CGFloat, maxTextSize: CGFloat, multiplierUpdateMode: ChartAxisGeneratorMultiplierUpdateMode = .halve) {
self.minValue = minValue
self.maxValue = maxValue
self.preferredDividers = preferredDividers
self.minSpace = minSpace
self.maxTextSize = maxTextSize
super.init(DBL_MAX, multiplierUpdateMode: multiplierUpdateMode)
}
func niceRangeAndMultiplier(_ dividers: Int) -> (minValue: Double, maxValue: Double, multiplier: Double) {
let niceLength = ChartNiceNumberCalculator.niceNumber(maxValue - minValue, round: true)
let niceMultiplier = ChartNiceNumberCalculator.niceNumber(niceLength / (Double(dividers) - 1), round: true)
let niceMinValue = floor(minValue / niceMultiplier) * niceMultiplier
let niceMaxValue = ceil(maxValue / niceMultiplier) * niceMultiplier
return (niceMinValue, niceMaxValue, niceMultiplier)
}
open override func axisInitialized(_ axis: ChartAxis) {
var dividers = preferredDividers
var cont = true
while dividers > 1 && cont {
let nice = niceRangeAndMultiplier(dividers)
if requiredLengthForDividers(dividers) < axis.screenLength {
minValue = nice.minValue
maxValue = nice.maxValue
multiplier = nice.multiplier
cont = false
} else {
dividers -= 1
}
}
}
fileprivate func requiredLengthForDividers(_ dividers: Int) -> CGFloat {
return minSpace + ((maxTextSize + minSpace) * CGFloat(dividers))
}
}
|
0 | import XCTest
@testable import WordPress
class DashboardStatsViewModelTests: XCTestCase {
func testReturnCorrectDataFromAPIResponse() {
// Given
let statsData = BlogDashboardRemoteEntity.BlogDashboardStats(views: 1, visitors: 2, likes: 3, comments: 0)
let apiResponse = BlogDashboardRemoteEntity(posts: nil, todaysStats: statsData)
let viewModel = DashboardStatsViewModel(apiResponse: apiResponse)
// When & Then
XCTAssertEqual(viewModel.todaysViews, "1")
XCTAssertEqual(viewModel.todaysVisitors, "2")
XCTAssertEqual(viewModel.todaysLikes, "3")
}
func testReturnedDataIsFormattedCorrectly() {
// Given
let statsData = BlogDashboardRemoteEntity.BlogDashboardStats(views: 10000, visitors: 200000, likes: 3000000, comments: 0)
let apiResponse = BlogDashboardRemoteEntity(posts: nil, todaysStats: statsData)
let viewModel = DashboardStatsViewModel(apiResponse: apiResponse)
// When & Then
XCTAssertEqual(viewModel.todaysViews, "10,000")
XCTAssertEqual(viewModel.todaysVisitors, "200.0K")
XCTAssertEqual(viewModel.todaysLikes, "3.0M")
}
func testReturnZeroIfAPIResponseIsEmpty() {
// Given
let statsData = BlogDashboardRemoteEntity.BlogDashboardStats(views: nil, visitors: nil, likes: nil, comments: nil)
let apiResponse = BlogDashboardRemoteEntity(posts: nil, todaysStats: statsData)
let viewModel = DashboardStatsViewModel(apiResponse: apiResponse)
// When & Then
XCTAssertEqual(viewModel.todaysViews, "0")
XCTAssertEqual(viewModel.todaysVisitors, "0")
XCTAssertEqual(viewModel.todaysLikes, "0")
}
func testReturnTrueIfAllTodaysStatsAreZero() {
// Given
let statsData = BlogDashboardRemoteEntity.BlogDashboardStats(views: 0, visitors: 0, likes: 0, comments: 0)
let apiResponse = BlogDashboardRemoteEntity(posts: nil, todaysStats: statsData)
let viewModel = DashboardStatsViewModel(apiResponse: apiResponse)
// When & Then
XCTAssertEqual(viewModel.shouldDisplayNudge, true)
}
func testReturnFalseIfNotAllTodaysStatsAreZero() {
// Given
let statsData = BlogDashboardRemoteEntity.BlogDashboardStats(views: 1, visitors: 0, likes: 0, comments: 0)
let apiResponse = BlogDashboardRemoteEntity(posts: nil, todaysStats: statsData)
let viewModel = DashboardStatsViewModel(apiResponse: apiResponse)
// When & Then
XCTAssertEqual(viewModel.shouldDisplayNudge, false)
}
}
|
0 | /// The declaration of a nominal type.
public protocol NominalTypeDecl: NamedDecl {
/// The semantic type represented by the declaration.
var type: BareType? { get }
}
|
0 | //
// Foundation+Tips.swift
// RxTips
//
// Created by Yu Sugawara on 2019/11/07.
// Copyright © 2019 Yu Sugawara. All rights reserved.
//
import Foundation
import Then
extension JSONEncoder: Then {}
extension JSONEncoder {
static var `default`: JSONEncoder {
return JSONEncoder().then {
$0.dateEncodingStrategy = .iso8601
}
}
}
extension JSONDecoder: Then {}
extension JSONDecoder {
static var `default`: JSONDecoder {
return JSONDecoder().then {
$0.dateDecodingStrategy = .iso8601
}
}
}
|
0 | //
// GenericProtocolTest.swift
// Cuckoo
//
// Created by Matyáš Kříž on 26/11/2018.
//
import XCTest
import Cuckoo
private class GenericProtocolConformerClass<C: AnyObject, V>: GenericProtocol {
let readOnlyPropertyC: C
var readWritePropertyV: V
let constant: Int = 0
var optionalProperty: V?
required init(theC: C, theV: V) {
readOnlyPropertyC = theC
readWritePropertyV = theV
}
func callSomeC(theC: C) -> Int {
return 1
}
func callSomeV(theV: V) -> Int {
switch theV {
case let int as Int:
return int
case let string as String:
return Int(string) ?? 8008135
default:
return 0
}
}
func compute(classy: C, value: V) -> C {
guard let testyClassy = classy as? TestedClass else { return classy }
switch value {
case let int as Int:
testyClassy.readWriteProperty = int
case _ as String:
testyClassy.optionalProperty = nil
default:
break
}
return testyClassy as! C
}
func noReturn() {}
}
private struct GenericProtocolConformerStruct<C: AnyObject, V>: GenericProtocol {
let readOnlyPropertyC: C
var readWritePropertyV: V
let constant: Int = 0
var optionalProperty: V?
init(theC: C, theV: V) {
readOnlyPropertyC = theC
readWritePropertyV = theV
}
func callSomeC(theC: C) -> Int {
return 1
}
func callSomeV(theV: V) -> Int {
return 0
}
func compute(classy: C, value: V) -> C {
return classy
}
func noReturn() {}
}
class GenericProtocolTest: XCTestCase {
private func createMock<V>(value: V) -> MockGenericProtocol<MockTestedClass, V> {
let classy = MockTestedClass()
return MockGenericProtocol(theC: classy, theV: value)
}
func testReadOnlyProperty() {
let mock = createMock(value: 10)
stub(mock) { mock in
when(mock.readOnlyPropertyC.get).thenReturn(MockTestedClass())
}
_ = mock.readOnlyPropertyC
verify(mock).readOnlyPropertyC.get()
}
func testReadWriteProperty() {
let mock = createMock(value: 10)
stub(mock) { mock in
when(mock.readWritePropertyV.get).then { 11 }
when(mock.readWritePropertyV.set(anyInt())).thenDoNothing()
}
mock.readWritePropertyV = 42
XCTAssertEqual(mock.readWritePropertyV, 11)
verify(mock).readWritePropertyV.get()
verify(mock).readWritePropertyV.set(42)
}
func testOptionalProperty() {
let mock = createMock(value: false)
var called = false
stub(mock) { mock in
when(mock.optionalProperty.get).thenReturn(true)
when(mock.optionalProperty.set(any())).then { _ in called = true }
when(mock.optionalProperty.set(isNil())).then { _ in called = true }
}
mock.optionalProperty = nil
mock.optionalProperty = false
XCTAssertTrue(mock.optionalProperty == true)
XCTAssertTrue(called)
verify(mock).optionalProperty.get()
verify(mock).optionalProperty.set(equal(to: false))
verify(mock, times(2)).optionalProperty.set(any())
verify(mock).optionalProperty.set(isNil())
}
func testNoReturn() {
let mock = createMock(value: "Hello. Sniffing through tests? If you're having trouble with Cuckoo, shoot us a message!")
var called = false
stub(mock) { mock in
when(mock.noReturn()).then { _ in called = true }
}
mock.noReturn()
XCTAssertTrue(called)
verify(mock).noReturn()
}
func testModification() {
let mock = createMock(value: ["EXTERMINATE!": "EXTERMINATE!!", "EXTERMINATE!!!": "EXTERMINATE!!!!"])
let original = GenericProtocolConformerClass(theC: MockTestedClass(), theV: ["Sir, may I help you?": "Nope, just lookin' 👀"])
mock.enableDefaultImplementation(original)
original.readWritePropertyV["Are you sure?"] = "Yeah, I'm just waiting for my wife."
XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀", "Are you sure?": "Yeah, I'm just waiting for my wife."])
original.readWritePropertyV["Alright, have a nice weekend!"] = "Thanks, you too."
XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀",
"Are you sure?": "Yeah, I'm just waiting for my wife.",
"Alright, have a nice weekend!": "Thanks, you too."])
verify(mock, times(2)).readWritePropertyV.get()
}
// the next two test cases show using a struct as the default implementation and changing its state:
// - NOTE: This only applies for `struct`s, not `class`es.
// using: `enableDefaultImplementation(mutating:)` reflects the original's state at all times
func testStructModification() {
let mock = createMock(value: ["EXTERMINATE!": "EXTERMINATE!!", "EXTERMINATE!!!": "EXTERMINATE!!!!"])
var original = GenericProtocolConformerStruct(theC: MockTestedClass(), theV: ["Sir, may I help you?": "Nope, just lookin' 👀"])
mock.enableDefaultImplementation(mutating: &original)
original.readWritePropertyV["Are you sure?"] = "Yeah, I'm just waiting for my wife."
XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀", "Are you sure?": "Yeah, I'm just waiting for my wife."])
original.readWritePropertyV["Alright, have a nice weekend!"] = "Thanks, you too."
XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀",
"Are you sure?": "Yeah, I'm just waiting for my wife.",
"Alright, have a nice weekend!": "Thanks, you too."])
verify(mock, times(2)).readWritePropertyV.get()
}
// using: `enableDefaultImplementation(_:)` reflects the original's state at the time of enabling default implementation with the struct
//
func testStructNonModification() {
let mock = createMock(value: ["EXTERMINATE!": "EXTERMINATE!!", "EXTERMINATE!!!": "EXTERMINATE!!!!"])
var original = GenericProtocolConformerStruct(theC: MockTestedClass(), theV: ["Sir, may I help you?": "Nope, just lookin' 👀"])
mock.enableDefaultImplementation(original)
original.readWritePropertyV["Are you sure?"] = "Yeah, I'm just waiting for my wife."
XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀"])
XCTAssertEqual(original.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀", "Are you sure?": "Yeah, I'm just waiting for my wife."])
original.readWritePropertyV["Alright, have a nice weekend!"] = "Thanks, you too."
XCTAssertEqual(mock.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀"])
XCTAssertEqual(original.readWritePropertyV, ["Sir, may I help you?": "Nope, just lookin' 👀",
"Are you sure?": "Yeah, I'm just waiting for my wife.",
"Alright, have a nice weekend!": "Thanks, you too."])
verify(mock, times(2)).readWritePropertyV.get()
}
}
|
0 |
import UIKit
extension String {
public var CGColor: CGColorRef {
return self.CGColor(1)
}
public var UIColor: UIKit.UIColor {
return self.UIColor(1)
}
public func CGColor (alpha: CGFloat) -> CGColorRef {
return self.UIColor(alpha).CGColor
}
public func UIColor (alpha: CGFloat) -> UIKit.UIColor {
var hex = self
if hex.hasPrefix("#") { // Strip leading "#" if it exists
hex = hex.substringFromIndex(hex.startIndex.successor())
}
switch hex.characters.count {
case 1: // Turn "f" into "ffffff"
hex = hex._repeat(6)
case 2: // Turn "ff" into "ffffff"
hex = hex._repeat(3)
case 3: // Turn "123" into "112233"
hex = hex[0]._repeat(2) + hex[1]._repeat(2) + hex[2]._repeat(2)
default:
break
}
assert(hex.characters.count == 6, "Invalid hex value")
var r: UInt32 = 0
var g: UInt32 = 0
var b: UInt32 = 0
NSScanner(string: "0x" + hex[0...1]).scanHexInt(&r)
NSScanner(string: "0x" + hex[2...3]).scanHexInt(&g)
NSScanner(string: "0x" + hex[4...5]).scanHexInt(&b)
let red = CGFloat(Int(r)) / CGFloat(255.0)
let green = CGFloat(Int(g)) / CGFloat(255.0)
let blue = CGFloat(Int(b)) / CGFloat(255.0)
return UIKit.UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
private extension String {
func _repeat (count: Int) -> String {
return "".stringByPaddingToLength((self as NSString).length * count, withString: self, startingAtIndex:0)
}
subscript (i: Int) -> String {
return String(Array(arrayLiteral: self)[i])
}
subscript (r: Range<Int>) -> String {
return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex)))
}
}
|
0 | //
// PieChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
/// View that represents a pie chart. Draws cake like slices.
open class PieChartView: PieRadarChartViewBase
{
/// rect object that represents the bounds of the piechart, needed for drawing the circle
fileprivate var _circleBox = CGRect()
/// array that holds the width of each pie-slice in degrees
fileprivate var _drawAngles = [CGFloat]()
/// array that holds the absolute angle in degrees of each slice
fileprivate var _absoluteAngles = [CGFloat]()
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
internal override func initialize()
{
super.initialize()
renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
}
open override func draw(_ rect: CGRect)
{
super.draw(rect)
if (_dataNotSet)
{
return
}
let context = UIGraphicsGetCurrentContext()!
renderer!.drawData(context: context)
if (valuesToHighlight())
{
renderer!.drawHighlighted(context: context, indices: _indicesToHightlight)
}
renderer!.drawExtras(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
}
internal override func calculateOffsets()
{
super.calculateOffsets()
// prevent nullpointer when no data set
if (_dataNotSet)
{
return
}
let radius = diameter / 2.0
let c = centerOffsets
// create the circle box that will contain the pie-chart (the bounds of the pie-chart)
_circleBox.origin.x = c.x - radius
_circleBox.origin.y = c.y - radius
_circleBox.size.width = radius * 2.0
_circleBox.size.height = radius * 2.0
}
internal override func calcMinMax()
{
super.calcMinMax()
calcAngles()
}
open override func getMarkerPosition(entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
/// PieChart does not support MarkerView
return CGPoint(x: 0.0, y: 0.0)
}
/// calculates the needed angles for the chart slices
fileprivate func calcAngles()
{
_drawAngles = [CGFloat]()
_absoluteAngles = [CGFloat]()
_drawAngles.reserveCapacity(_data.yValCount)
_absoluteAngles.reserveCapacity(_data.yValCount)
var dataSets = _data.dataSets
var cnt = 0
for i in 0 ..< _data.dataSetCount
{
let set = dataSets[i]
var entries = set.yVals
for j in 0 ..< entries.count
{
_drawAngles.append(calcAngle(abs(entries[j].value)))
if (cnt == 0)
{
_absoluteAngles.append(_drawAngles[cnt])
}
else
{
_absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt])
}
cnt += 1
}
}
}
/// checks if the given index in the given DataSet is set for highlighting or not
open func needsHighlight(xIndex: Int, dataSetIndex: Int) -> Bool
{
// no highlight
if (!valuesToHighlight() || dataSetIndex < 0)
{
return false
}
for i in 0 ..< _indicesToHightlight.count
{
// check if the xvalue for the given dataset needs highlight
if (_indicesToHightlight[i].xIndex == xIndex
&& _indicesToHightlight[i].dataSetIndex == dataSetIndex)
{
return true
}
}
return false
}
/// calculates the needed angle for a given value
fileprivate func calcAngle(_ value: Double) -> CGFloat
{
return CGFloat(value) / CGFloat(_data.yValueSum) * 360.0
}
open override func indexForAngle(_ angle: CGFloat) -> Int
{
// take the current angle of the chart into consideration
let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle)
for i in 0 ..< _absoluteAngles.count
{
if (_absoluteAngles[i] > a)
{
return i
}
}
return -1; // return -1 if no index found
}
/// Returns the index of the DataSet this x-index belongs to.
open func dataSetIndexForIndex(_ xIndex: Int) -> Int
{
var dataSets = _data.dataSets
for i in 0 ..< dataSets.count
{
if (dataSets[i].entryForXIndex(xIndex) !== nil)
{
return i
}
}
return -1
}
/// returns an integer array of all the different angles the chart slices
/// have the angles in the returned array determine how much space (of 360°)
/// each slice takes
open var drawAngles: [CGFloat]
{
return _drawAngles
}
/// returns the absolute angles of the different chart slices (where the
/// slices end)
open var absoluteAngles: [CGFloat]
{
return _absoluteAngles
}
/// Sets the color for the hole that is drawn in the center of the PieChart (if enabled).
/// NOTE: Use holeTransparent with holeColor = nil to make the hole transparent.
open var holeColor: UIColor?
{
get
{
return (renderer as! PieChartRenderer).holeColor!
}
set
{
(renderer as! PieChartRenderer).holeColor = newValue
setNeedsDisplay()
}
}
/// Set the hole in the center of the PieChart transparent
open var holeTransparent: Bool
{
get
{
return (renderer as! PieChartRenderer).holeTransparent
}
set
{
(renderer as! PieChartRenderer).holeTransparent = newValue
setNeedsDisplay()
}
}
/// Returns true if the hole in the center of the PieChart is transparent, false if not.
open var isHoleTransparent: Bool
{
return (renderer as! PieChartRenderer).holeTransparent
}
/// true if the hole in the center of the pie-chart is set to be visible, false if not
open var drawHoleEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawHoleEnabled
}
set
{
(renderer as! PieChartRenderer).drawHoleEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if the hole in the center of the pie-chart is set to be visible, false if not
open var isDrawHoleEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawHoleEnabled
}
}
/// the text that is displayed in the center of the pie-chart. By default, the text is "Total value + sum of all values"
open var centerText: String!
{
get
{
return (renderer as! PieChartRenderer).centerText
}
set
{
(renderer as! PieChartRenderer).centerText = newValue
setNeedsDisplay()
}
}
/// true if drawing the center text is enabled
open var drawCenterTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawCenterTextEnabled
}
set
{
(renderer as! PieChartRenderer).drawCenterTextEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing the center text is enabled
open var isDrawCenterTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawCenterTextEnabled
}
}
internal override var requiredBottomOffset: CGFloat
{
return _legend.font.pointSize * 2.0
}
internal override var requiredBaseOffset: CGFloat
{
return 0.0
}
open override var radius: CGFloat
{
return _circleBox.width / 2.0
}
/// returns the circlebox, the boundingbox of the pie-chart slices
open var circleBox: CGRect
{
return _circleBox
}
/// returns the center of the circlebox
open var centerCircleBox: CGPoint
{
return CGPoint(x: _circleBox.midX, y: _circleBox.midY)
}
/// Sets the font of the center text of the piechart.
open var centerTextFont: UIFont
{
get
{
return (renderer as! PieChartRenderer).centerTextFont
}
set
{
(renderer as! PieChartRenderer).centerTextFont = newValue
setNeedsDisplay()
}
}
/// Sets the color of the center text of the piechart.
open var centerTextColor: UIColor
{
get
{
return (renderer as! PieChartRenderer).centerTextColor
}
set
{
(renderer as! PieChartRenderer).centerTextColor = newValue
setNeedsDisplay()
}
}
/// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart)
/// :default: 0.5 (50%) (half the pie)
open var holeRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).holeRadiusPercent
}
set
{
(renderer as! PieChartRenderer).holeRadiusPercent = newValue
setNeedsDisplay()
}
}
/// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart)
/// :default: 0.55 (55%) -> means 5% larger than the center-hole by default
open var transparentCircleRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).transparentCircleRadiusPercent
}
set
{
(renderer as! PieChartRenderer).transparentCircleRadiusPercent = newValue
setNeedsDisplay()
}
}
/// set this to true to draw the x-value text into the pie slices
open var drawSliceTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawXLabelsEnabled
}
set
{
(renderer as! PieChartRenderer).drawXLabelsEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing x-values is enabled, false if not
open var isDrawSliceTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawXLabelsEnabled
}
}
/// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent.
open var usePercentValuesEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).usePercentValuesEnabled
}
set
{
(renderer as! PieChartRenderer).usePercentValuesEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing x-values is enabled, false if not
open var isUsePercentValuesEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).usePercentValuesEnabled
}
}
/// the line break mode for center text.
/// note that different line break modes give different performance results - Clipping being the fastest, WordWrapping being the slowst.
open var centerTextLineBreakMode: NSLineBreakMode
{
get
{
return (renderer as! PieChartRenderer).centerTextLineBreakMode
}
set
{
(renderer as! PieChartRenderer).centerTextLineBreakMode = newValue
setNeedsDisplay()
}
}
/// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole
open var centerTextRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).centerTextRadiusPercent
}
set
{
(renderer as! PieChartRenderer).centerTextRadiusPercent = newValue
setNeedsDisplay()
}
}
}
|
0 | //
// InfoView.swift
// Pods
//
// Created by Anatoliy Voropay on 5/11/16.
//
//
import UIKit
/**
Position of arrow in a view
- Parameter None: View will be without arrow
- Parameter Automatic: We will try to select most suitable position
- Parameter Left, Right, Top, Bottom: Define view side that will contain an errow
*/
public enum InfoViewArrowPosition {
case None
case Automatic
case Left, Right, Top, Bottom
}
/**
Appearance animation
- Parameter None: View will appear without animation
- Parameter FadeIn: FadeIn animation will happen
- Parameter FadeInAndScale: FadeIn and Scale animation will happen
*/
public enum InfoViewAnimation {
case None
case FadeIn
case FadeInAndScale
}
/**
Delegate that can handle events from InfoView appearance.
*/
@objc public protocol InfoViewDelegate {
optional func infoViewWillShow(view: InfoView)
optional func infoViewDidShow(view: InfoView)
optional func infoViewWillHide(view: InfoView)
optional func infoViewDidHide(view: InfoView)
}
/**
View to show small text information blocks with arrow pointed to another view.
In most cases it will be a button that was pressed.
**Simple appearance**
```
let infoView = InfoView(text: "Your information here")
infoView.show(onView: view, centerView: button)
```
**Delegation**
You can set a delegate and get events when view ill appear/hide:
```
infoView.delegate = self
// In your delegate class
func infoViewDidShow(view: InfoView) {
print("Now visible")
}
```
**Customization**
Set arrow position:
```
infoView.arrowPosition = .Left
```
Set animation:
```
infoView.animation = InfoViewAnimation.None // Without animation
infoView.animation = InfoViewAnimation.FadeIn // FadeIn animation
infoView.animation = InfoViewAnimation.FadeInAndScale // FadeIn and Scale animation
```
Set custom font:
```
infoView.font = UIFont(name: "AvenirNextCondensed-Regular", size: 16)
```
Set custom text color:
```
infoView.textColor = UIColor.grayColor()
```
Set custom background color:
```
infoView.backgroundColor = UIColor.blackColor()
```
Set custom layer properties:
```
infoView.layer.shadowColor = UIColor.whiteColor().CGColor
infoView.layer.cornerRadius = 15
infoView.layer.shadowRadius = 5
infoView.layer.shadowOffset = CGPoint(x: 2, y: 2)
infoView.layer.shadowOpacity = 0.5
```
**Auto hide**
Hide InfoView after delay automatically
```
infoView.hideAfterDelay = 2
```
*/
public class InfoView: UIView {
/// Arrow position
public var arrowPosition: InfoViewArrowPosition = .Automatic
/// Animation
public var animation: InfoViewAnimation = .FadeIn
/// InfoViewDelegate delegate
public weak var delegate: InfoViewDelegate?
/// Text message
public var text: String?
/// Autohide after delay
public var hideAfterDelay: CGFloat? {
didSet {
if let hideAfterDelay = hideAfterDelay {
timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(hideAfterDelay), target: self, selector: #selector(InfoView.hide), userInfo: nil, repeats: false)
} else {
timer?.invalidate()
timer = nil
}
}
}
/// Text padding
public var textInsets: UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
/// Text label font
public var font: UIFont?
/// Text label color
public var textColor: UIColor?
private lazy var label: UILabel = {
let label = UILabel()
label.numberOfLines = 0
self.backgroundView.insertSubview(label, aboveSubview: self.placeholderView)
return label
}()
private lazy var placeholderView: PlaceholderView = {
let placeholderView = PlaceholderView()
placeholderView.color = self.backgroundColor
self.backgroundView.addSubview(placeholderView)
return placeholderView
}()
private lazy var backgroundView: BackgroundView = {
let backgroundView = BackgroundView()
backgroundView.backgroundColor = .clearColor()
backgroundView.autoresizingMask = [ .FlexibleWidth, .FlexibleHeight ]
backgroundView.delegate = self
return backgroundView
}()
override public var autoresizingMask: UIViewAutoresizing {
didSet {
placeholderView.autoresizingMask = autoresizingMask
label.autoresizingMask = autoresizingMask
}
}
private weak var onView: UIView?
private weak var centerView: UIView?
private var timer: NSTimer?
// MARK: Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
customizeAppearance()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
customizeAppearance()
}
public convenience init(text: String, delegate: InfoViewDelegate) {
self.init(text: text, arrowPosition: .Automatic, animation: .FadeIn, delegate: delegate)
}
public convenience init(text: String) {
self.init(text: text, arrowPosition: .Automatic, animation: .FadeIn, delegate: nil)
}
public init(text: String, arrowPosition: InfoViewArrowPosition, animation: InfoViewAnimation, delegate: InfoViewDelegate?) {
super.init(frame: CGRect.zero)
self.text = text
self.animation = animation
self.arrowPosition = arrowPosition
self.delegate = delegate
customizeAppearance()
}
// MARK: Appearance
public func show(onView view: UIView, centerView: UIView) {
self.onView = view
self.centerView = centerView
var (suitableRect, suitableOffset) = self.suitableRect()
var labelRect = CGRect(x: suitableRect.origin.x + textInsets.left, y: suitableRect.origin.y + textInsets.top, width: suitableRect.width - textInsets.left - textInsets.right, height: suitableRect.height - textInsets.bottom - textInsets.top)
switch correctArrowPosition() {
case .Left:
labelRect.size.width -= PlaceholderView.Constants.TriangleSize.height
labelRect.origin.x += PlaceholderView.Constants.TriangleSize.height
case .Right:
labelRect.size.width -= PlaceholderView.Constants.TriangleSize.height
labelRect.origin.x -= PlaceholderView.Constants.TriangleSize.height
suitableRect.origin.x -= PlaceholderView.Constants.TriangleSize.height
case .Top:
labelRect.size.height -= PlaceholderView.Constants.TriangleSize.height
labelRect.origin.y += PlaceholderView.Constants.TriangleSize.height
case .Bottom:
labelRect.size.height -= PlaceholderView.Constants.TriangleSize.height
labelRect.origin.y -= PlaceholderView.Constants.TriangleSize.height
suitableRect.origin.y -= PlaceholderView.Constants.TriangleSize.height
default:
break
}
backgroundView.frame = view.bounds
placeholderView.frame = suitableRect
placeholderView.triangleOffset = suitableOffset
placeholderView.arrowPosition = correctArrowPosition()
placeholderView.color = backgroundColor
placeholderView.layer.cornerRadius = self.layer.cornerRadius
placeholderView.layer.shadowColor = self.layer.shadowColor
placeholderView.layer.shadowRadius = self.layer.shadowRadius
placeholderView.layer.shadowOffset = self.layer.shadowOffset
placeholderView.layer.shadowOpacity = self.layer.shadowOpacity
placeholderView.alpha = 0
label.frame = labelRect
label.text = text
label.font = font
label.textColor = textColor
label.textAlignment = textAlignment()
label.alpha = 0
view.addSubview(backgroundView)
animateAppearance()
}
func hide() {
timer?.invalidate()
timer = nil
animateDisappearance()
}
// MARK: Animation
private func animateAppearance() {
delegate?.infoViewWillShow?(self)
switch self.animation {
case .FadeInAndScale:
placeholderView.transform = scaleTransform(placeholderView.transform)
label.transform = scaleTransform(label.transform)
default:
break
}
UIView.animateWithDuration(duration(), animations: {
self.label.alpha = 1
self.placeholderView.alpha = 1
switch self.animation {
case .FadeInAndScale:
self.placeholderView.transform = CGAffineTransformIdentity
self.label.transform = CGAffineTransformIdentity
default:
break
}
}, completion: { (complete) in
self.delegate?.infoViewDidShow?(self)
})
}
private func animateDisappearance() {
self.delegate?.infoViewWillHide?(self)
UIView.animateWithDuration(duration(), animations: {
self.label.alpha = 0
self.placeholderView.alpha = 0
switch self.animation {
case .FadeIn, .None:
break
case .FadeInAndScale:
self.placeholderView.transform = self.scaleTransform(self.placeholderView.transform)
self.label.transform = self.scaleTransform(self.label.transform)
}
}, completion: { (complete) in
self.backgroundView.removeFromSuperview()
self.delegate?.infoViewDidHide?(self)
})
}
private func duration() -> NSTimeInterval {
return animation == .None ? 0 : 0.2
}
private func scaleTransform(t: CGAffineTransform) -> CGAffineTransform {
return CGAffineTransformScale(t, 0.5, 0.5)
}
// MARK: Helpers
/// Return correct arrow position. It will detect correct position for Automatic also.
private func correctArrowPosition() -> InfoViewArrowPosition {
if arrowPosition == .Automatic {
guard let view = onView else { return .Left }
guard let centerView = centerView else { return .Left }
let centerRect = view.convertRect(centerView.frame, toView: view)
let width1 = view.frame.width
let height1 = centerRect.origin.y
let width2 = view.frame.width - centerRect.origin.x - centerRect.size.width
let height2 = view.frame.height
let width3 = view.frame.width
let height3 = view.frame.height - centerRect.origin.y - centerRect.size.height
let width4 = centerRect.origin.x
let height4 = view.frame.height
let area1: CGFloat = width1 * height1
let area2: CGFloat = width2 * height2
let area3: CGFloat = width3 * height3
let area4: CGFloat = width4 * height4
let max: CGFloat = CGFloat(fmaxf(fmaxf(Float(area1), Float(area2)), fmaxf(Float(area3), Float(area4))))
if max == area1 {
return .Bottom
} else if max == area2 {
return .Left
} else if max == area3 {
return .Top
} else {
return .Right
}
} else {
return arrowPosition
}
}
private func textAlignment() -> NSTextAlignment {
switch correctArrowPosition() {
case .Left: return .Left
case .Right: return .Right
case .Top, .Bottom, .Automatic, .None: return .Center
}
}
/// Return customized label with settings
private func customizedLabel() -> UILabel {
let label = UILabel()
label.text = text
label.font = font
label.textColor = textColor
label.numberOfLines = 0
return label
}
}
// MARK: Discover best rect to show view
extension InfoView {
/// Return maximum allowed rect according to preferences
private func visibleRect() -> CGRect {
guard let view = onView else { return CGRect.zero }
guard let centerView = centerView else { return CGRect.zero }
let centerRect = view.convertRect(centerView.frame, toView: view)
var visibleRect = CGRect.zero
switch correctArrowPosition() {
case .Left:
visibleRect = CGRect(origin: CGPoint(x: centerRect.origin.x + centerRect.size.width, y: 0), size: CGSize(width: view.frame.width - centerRect.origin.x - centerRect.size.width, height: view.frame.height))
case .Right:
visibleRect = CGRect(origin: CGPoint.zero, size: CGSize(width: centerRect.origin.x, height: view.frame.height))
case .Bottom:
visibleRect = CGRect(origin: CGPoint.zero, size: CGSize(width: view.frame.width, height: centerRect.origin.y))
case .Top:
visibleRect = CGRect(origin: CGPoint(x: 0, y: centerRect.origin.y + centerRect.size.height), size: CGSize(width: view.frame.width, height: view.frame.height - centerRect.origin.y - centerRect.size.height))
default:
break
}
return visibleRect
}
/// Return allowed rect for final label according with textInsets
private func allowedRect(inRect rect: CGRect) -> CGRect {
let size = CGSize(width: rect.width - textInsets.left - textInsets.right, height: rect.height - textInsets.bottom - textInsets.top)
let origin = CGPoint(x: rect.origin.x + textInsets.left, y: rect.origin.y + textInsets.top)
return CGRect(origin: origin, size: size)
}
/// Return suitable rect for final label
private func labelRect(inRect rect: CGRect) -> CGRect {
var allowedRect = self.allowedRect(inRect: rect)
allowedRect.size.height = CGFloat.max
allowedRect.size.width *= ( UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 0.5 : 0.8 )
let label = customizedLabel()
label.frame = allowedRect
label.sizeToFit()
return label.frame
}
/// Return final rect for our placeholderView
/// CGPoint is offset for triangle
private func suitableRect() -> (CGRect, CGPoint) {
guard let view = onView else { return (CGRect.zero, CGPoint.zero) }
guard let centerView = centerView else { return (CGRect.zero, CGPoint.zero) }
let visibleRect = self.visibleRect()
let centerRect = view.convertRect(centerView.frame, toView: view)
var finalRect = labelRect(inRect: visibleRect)
var finalOffset = CGPoint.zero
switch correctArrowPosition() {
case .Left:
finalRect.origin.y = centerRect.origin.y + centerView.frame.size.height / 2 - finalRect.size.height / 2
finalRect.origin.x = visibleRect.origin.x + textInsets.left
finalRect.size.width += PlaceholderView.Constants.TriangleSize.height
case .Right:
finalRect.origin.y = centerRect.origin.y + centerView.frame.size.height / 2 - finalRect.size.height / 2
finalRect.origin.x = centerRect.origin.x - finalRect.size.width - textInsets.right
finalRect.size.width += PlaceholderView.Constants.TriangleSize.height
case .Top:
finalRect.origin.x = centerRect.origin.x + centerView.frame.size.width / 2 - finalRect.size.width / 2
finalRect.origin.y = centerRect.origin.y + centerRect.size.height + textInsets.top
finalRect.size.height += PlaceholderView.Constants.TriangleSize.height
case .Bottom:
finalRect.origin.x = centerRect.origin.x + centerView.frame.size.width / 2 - finalRect.size.width / 2
finalRect.origin.y = centerRect.origin.y - finalRect.size.height - textInsets.bottom
finalRect.size.height += PlaceholderView.Constants.TriangleSize.height
default:
break
}
finalRect.origin.x -= textInsets.left
finalRect.origin.y -= textInsets.top
finalRect.size.width += textInsets.left + textInsets.right
finalRect.size.height += textInsets.top + textInsets.bottom
let borderOffset: CGFloat = 5
if finalRect.origin.x < 0 {
finalOffset.x = finalRect.origin.x - borderOffset
finalRect.origin.x = borderOffset
} else if finalRect.origin.x + finalRect.size.width > view.frame.width {
finalOffset.x = (finalRect.origin.x + finalRect.size.width) - view.frame.width + borderOffset
finalRect.origin.x -= finalOffset.x
} else if finalRect.origin.y < 0 {
finalOffset.y = finalRect.origin.y - borderOffset
finalRect.origin.y = borderOffset
} else if finalRect.origin.y + finalRect.size.height > view.frame.height {
finalOffset.y = (finalRect.origin.y + finalRect.size.height) - view.frame.height + borderOffset
finalRect.origin.y -= finalOffset.y
}
return (finalRect, finalOffset)
}
}
// MARK: Appearance customization
extension InfoView {
private func customizeAppearance() {
font = .systemFontOfSize(14)
textColor = .blackColor()
backgroundColor = .whiteColor()
layer.cornerRadius = 5
layer.shadowOpacity = 0.5
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowRadius = 2
layer.shadowOffset = CGSize(width: 0, height: 0)
}
}
extension InfoView: BackgroundViewDelegate {
func pressedBackgorund(view: BackgroundView) {
hide()
}
}
|
0 | // 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: "nickdonald-boilerplate",
platforms: [
.macOS(.v12)
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "nickdonald-boilerplate",
targets: ["nickdonald-boilerplate"]),
],
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 this package depends on.
.target(
name: "nickdonald-boilerplate",
dependencies: []),
// .testTarget(
// name: "nickdonald-boilerplateTests",
// dependencies: ["nickdonald-boilerplate"]),
]
)
|
0 | //
// Objects.swift
// Notes
//
// Created by Eric Saba on 1/31/16.
// Copyright © 2016 Eric Saba. All rights reserved.
//
import Foundation
import MapKit
import QuartzCore
let ACCENT_COLOR: UIColor = UIColor(red: 14.0 / 255, green: 127.0 / 255, blue: 255.0 / 255, alpha: 1.0)
let SCENERY_COLOR: UIColor = UIColor(red: 12.0 / 255, green: 208.0 / 255, blue: 0, alpha: 1.0)
let CAUTION_COLOR: UIColor = UIColor(red: 255.0 / 255, green: 5.0 / 255, blue: 34.0 / 255, alpha: 1.0)
let PERSONAL_COLOR: UIColor = UIColor(red: 130.0 / 255, green: 52.0 / 255, blue: 255.0 / 255, alpha: 1.0)
let RESTAURANT_COLOR: UIColor = UIColor(red: 255.0 / 255, green: 255.0 / 255, blue: 0, alpha: 1.0)
let FIND_RADIUS: Double = 50.0
let CAMERA_ZOOM: Float = 19.8
let BUTTON_SIZE: CGFloat = 60.0
let TYPE_SIZE: CGFloat = 40.0
let Y_INSET: CGFloat = 80.0
let POPOVER_INSET: CGFloat = 20.0
class Note: NSObject {
var noteObj: PFObject?
var lat: Double?
var long: Double?
var text: String?
var dist: Double?
var dir: Double?
var image: UIImage?
var type: String?
var username: String = ""
init(noteObj: PFObject, userLat: Double, userLong: Double) {
super.init()
self.noteObj = noteObj
lat = (noteObj.objectForKey("location") as! PFGeoPoint).latitude
long = (noteObj.objectForKey("location") as! PFGeoPoint).longitude
text = noteObj.objectForKey("note") as? String
type = noteObj.objectForKey("type") as? String
dist = CallHandler().findDistance(userLat, long1: userLong, lat2: lat!, long2: long!)
dir = CallHandler().findDirection(userLat, long1: userLong, lat2: lat!, long2: long!)
}
func setNoteUsername(completion: (reload: Bool, selfPosted: Bool) -> Void) {
if username == "" {
CallHandler().getUserForNote(self.noteObj!, completion: { (success, username) in
if success {
if self.type == "personal" {
self.username = username
completion(reload: true, selfPosted: false)
}
else if username == PFUser.currentUser()?.username {
self.username = username
completion(reload: true, selfPosted: true)
}
else {
completion(reload: false, selfPosted: false)
}
}
else {
completion(reload: false, selfPosted: false)
}
})
}
else {
if self.username == PFUser.currentUser()?.username {
completion(reload: true, selfPosted: true)
}
else {
completion(reload: true, selfPosted: false)
}
}
}
// init(note: String, latitude: Double, longitude: Double, userLat: Double, userLong: Double, noteType: String) {
// super.init()
// text = note
// lat = latitude
// long = longitude
// dist = CallHandler().findDistance(userLat, long1: userLong, lat2: latitude, long2: longitude)
// dir = CallHandler().findDirection(userLat, long1: userLong, lat2: latitude, long2: longitude)
// type = noteType
// }
func getDistText() -> String {
return String(format: "%.0f", dist!)
}
func getDirText() -> String {
var ret = ""
if (dir > 292.5 || dir <= 67.5) {
ret.appendContentsOf("N")
}
if (dir > 112.5 && dir <= 247.5) {
ret.appendContentsOf("S")
}
if (dir > 22.5 && dir <= 157.5) {
ret.appendContentsOf("E")
}
if (dir > 202.5 && dir <= 337.5) {
ret.appendContentsOf("W")
}
return ret
}
func setLocation(latitude: Double, longitude: Double) {
lat = latitude
long = longitude
}
func setNote(note: String) {
text = note
}
func updateDistance(userLat: Double, userLong: Double) {
dist = CallHandler().findDistance(userLat, long1: userLong, lat2: lat!, long2: long!)
dir = CallHandler().findDirection(userLat, long1: userLong, lat2: lat!, long2: long!)
}
func setNoteType(noteType: String) {
type = noteType
}
}
class MapNote: NSObject, MKAnnotation {
let title: String?
let coordinate: CLLocationCoordinate2D
init(title: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.coordinate = coordinate
super.init()
}
var subtitle: String? {
return ""
}
}
class Contact: NSObject {
let name: String?
let user: PFUser?
var requested: Bool = false
init(name: String, user: PFUser) {
self.name = name
self.user = user
super.init()
}
}
class Update: NSObject {
let title: String
let desc: String
let seen: Bool
init(title: String, desc: String, seen: Bool) {
self.title = title
self.desc = desc
self.seen = seen
super.init()
}
override init() {
self.title = ""
self.desc = ""
self.seen = true
super.init()
}
}
class SegueFromLeft: UIStoryboardSegue {
override func perform() {
let src: UIViewController = self.sourceViewController
let dst: UIViewController = self.destinationViewController
let transition: CATransition = CATransition()
let timeFunc : CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.duration = 0.25
transition.timingFunction = timeFunc
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromLeft
if (src.isMemberOfClass(ListTableViewController)) {
transition.subtype = kCATransitionFromRight
}
src.navigationController!.view.layer.addAnimation(transition, forKey: kCATransition)
src.navigationController!.pushViewController(dst, animated: false)
}
}
class SegueFromRight: UIStoryboardSegue {
override func perform() {
let src: UIViewController = self.sourceViewController
let dst: UIViewController = self.destinationViewController
let transition: CATransition = CATransition()
let timeFunc : CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.duration = 0.25
transition.timingFunction = timeFunc
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromRight
if (src.isMemberOfClass(ListTableViewController)) {
transition.subtype = kCATransitionFromRight
}
src.navigationController!.view.layer.addAnimation(transition, forKey: kCATransition)
src.navigationController!.pushViewController(dst, animated: false)
}
} |
0 | import XCTest
import Combine
@testable import Bitkub
final class BitkubTests: XCTestCase {
var cancellables: Set<AnyCancellable> = Set<AnyCancellable>()
func testLoadCoins() {
let expectation = XCTestExpectation(description: "Coin values recovered from Bitkub")
let controller = BitkubController()
controller.loadCoins()
controller.$coins.drop(while: { $0.count == 0 }).sink { (coins) in
expectation.fulfill()
}
.store(in: &cancellables)
wait(for: [expectation], timeout: 5)
}
func testLoadBalance() {
let key = ProcessInfo.processInfo.environment["KEY"]
let secret = ProcessInfo.processInfo.environment["SECRET"]
XCTAssertNotNil(key)
XCTAssertNotNil(secret)
let controller = BitkubController(apiKey: key!, secret: secret!)
let expectation = XCTestExpectation(description: "Balance retrieved from Bitkub")
try! controller.loadBalance()
controller.$balances.drop(while: {$0.count == 0}).sink { (balances) in
expectation.fulfill()
}
.store(in: &cancellables)
wait(for: [expectation], timeout: 5)
}
func testWrongCredentials() {
let key = "abcd"
let secret = "efgh"
let controller = BitkubController(apiKey: key, secret: secret)
let expectation = XCTestExpectation(description: "Credentials are marked as invalid")
try! controller.loadBalance()
controller.$validCredentials.drop(while: { $0 }).sink { (validCredentials) in
if validCredentials == false {
expectation.fulfill()
}
}.store(in: &cancellables)
wait(for: [expectation], timeout: 5)
}
func testLoadBalanceThrowsWithoutCredentials() {
let controller = BitkubController()
XCTAssertThrowsError(try controller.loadBalance()) { error in
XCTAssertEqual(error as! BitkubError, BitkubError.missingCredentials)
}
}
static var allTests = [
("testLoadCoins", testLoadCoins),
]
}
|
0 | //
// FVRecognitionTrainController.swift
// FaceTrainerPackageDescription
//
// Created by Arman Galstyan on 12/17/17.
//
import Foundation
import LASwift
import AppKit
public final class FVPerson {
private var _faceID: String!
public var faceID: String {
return _faceID
}
public init(id: String) {
self._faceID = id
}
}
public final class FVRecognitionTrainController {
typealias MeanValuesVector = Vector
private let normalEigensPercenteage: Int = 15
private var facesBitArraysCollection = [TrainFaceBitArray]()
private var meanValuesVector = MeanValuesVector()
private var averageVectors: Matrix!
private var transposeOfAverageVectors: Matrix!
private var transposeOfCovarianseMatrix: Matrix!
private var eigenVectors: Matrix!
private var eigensMatrixTranspose: Matrix!
private var porjectionMatrix: Matrix!
private var personsList = [FVPerson]()
public init() {
}
public func startTrain() {
self.countMeanValuesVector()
self.countAverageVectors()
self.countCovariance()
self.findEigens()
}
public func appendFace(forImage faceImage: NSImage) throws -> FVPerson {
do {
let recognitionImageBitsArray = try FVRecognitionImage(image: faceImage).getBitArray()
self.facesBitArraysCollection.append(recognitionImageBitsArray)
let person = FVPerson(id: UUID().uuidString)
personsList.append(person)
return person
} catch (let error) {
throw error
}
}
private func countMeanValuesVector() {
let faceCollectionCount = facesBitArraysCollection.count
meanValuesVector = sum(Matrix(facesBitArraysCollection.map({ $0.bitArray })),.Column)
meanValuesVector = rdivide(meanValuesVector, Double(faceCollectionCount))
}
private func countAverageVectors() {
transposeOfAverageVectors = Matrix(facesBitArraysCollection.map({ $0.bitArray - meanValuesVector }))
averageVectors = transpose(transposeOfAverageVectors)
}
private func countCovariance() {
transposeOfCovarianseMatrix = mtimes(transposeOfAverageVectors, averageVectors)
}
private func findEigens() {
let temporaryEigens = eigen(transposeOfCovarianseMatrix)
let normalCount = getNormalEigensCount(fromCount: temporaryEigens.count)
print(normalCount)
var sortedEigens = temporaryEigens.sorted(by: >)
let normalEigens = sortedEigens[0..<normalCount]
let eigensArray = normalEigens.map({ mtimes(averageVectors, $0.vectorMatrix)[col: 0] })
let normalizedEigensArray = eigensArray.map({ $0.normalized() })
self.eigensMatrixTranspose = Matrix(normalizedEigensArray)
self.eigensMatrixTranspose = plus(eigensMatrixTranspose, meanValuesVector)
self.porjectionMatrix = mtimes(self.eigensMatrixTranspose, averageVectors)
}
private func getNormalEigensCount(fromCount count: Int) -> Int {
let normalCount = Double((count * normalEigensPercenteage)) / 100.0
if Int(normalCount) > 0 {
return Int(normalCount)
}
return count
}
public func verify(face: FVRecognitionImage) -> FVPerson {
let faceBitMap = face.getBitArray().bitArray
var faceMatrix = zeros(faceBitMap.count, 1)
faceMatrix = insert(faceMatrix, col: faceBitMap - meanValuesVector, at: 0)
let weightMatrix = mtimes(eigensMatrixTranspose, faceMatrix)
let weightVector = weightMatrix[col: 0]
//////
var trainFaceVectors = [Vector]()
for colIndex in 0..<self.porjectionMatrix.cols {
trainFaceVectors.append(self.porjectionMatrix[col: colIndex])
}
let dividingVectors = trainFaceVectors.map({ sum(abs($0 - weightVector))})
let personIndex = mini(dividingVectors)
print("personindex \(personIndex)")
return personsList[personIndex]
}
}
|
0 | /*:
# Closures
Closures are self-contained blocks of functionality that can be passed around
and used in your code.
Functions are actually special cases of closures. Closures take one of three forms:
- Global functions are closures that **have a name** and do not capture any values.
- Nested functions are closures that _have a name_ and can **capture values**
from their enclosing function.
- Closure expressions are **unnamed closures** written in a lightweight syntax
that can capture values from their surrounding context.
*/
/*:
## The type of functions and closures
*/
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
func multiply(_ a: Int, _ b: Int) -> Int {
return a * b
}
/*:
This above example defines two simple mathematical functions called `add` and `multiply`.
These functions take two `Int` values, and return an `Int` value. So the type of these functions is
`(Int, Int) -> Int`.
This can be read as:
“A function type that has two parameters, both of type Int, and that returns a value of type Int.”
*/
let someArithmeticFunction: (Int, Int) -> Int = add(_:_:)
someArithmeticFunction(1, 2)
/*:
## Use function as arguments
*/
func reduce(numbers: [Int], reducer: (Int, Int) -> Int) -> Int? {
guard !numbers.isEmpty else {
return nil
}
// This array is not empty, so it’s okay to use `!` to get the first element as result.
var result = numbers.first!
// Then, enumerate the rest part of this array
for number in numbers[1..<numbers.count] {
result = reducer(result, number)
}
return result
}
reduce(numbers: [1, 2, 3, 4], reducer: add(_:_:))
reduce(numbers: [1, 2, 3, 4], reducer: multiply(_:_:))
reduce(numbers: [2, 3, 4, 5], reducer: +)
//: > Yes, operatos are functions in Swift.
//: --------------------------------------------------------------------------------------------------------------------
/*:
## Use closure as anonymous functions
In the above example, each time when I use the `reduce(numbers:reducer:)` function,
I have to create a reducer function first, and then pass the function as the argument.
Closures can make the syntax of this pattern easier, like:
*/
reduce(numbers: [1, 2, 3, 4], reducer: { (a: Int, b: Int) -> Int in
return (a + b) * 2
})
/*:
Closure expression syntax has the following general form:
```
{ (<parameter1>: <Type1>, <parameter2>: <Type2>, ...) -> <ReturnType> in
<closure body>
}
```
And it can be simplified as following syntaxes:
*/
// The full form
reduce(numbers: [1, 2, 3, 4], reducer: { (a: Int, b: Int) -> Int in
return a + b
})
// Inferring Type From Context
reduce(numbers: [1, 2, 3, 4], reducer: { a, b in
return a + b
})
// Shorthand Argument Names
reduce(numbers: [1, 2, 3, 4], reducer: {
return $0 + $1
})
// Implicit Returns from Single-Expression Closures
reduce(numbers: [1, 2, 3, 4], reducer: { a, b in
a + b
})
reduce(numbers: [1, 2, 3, 4], reducer: { a, b in a + b })
reduce(numbers: [1, 2, 3, 4], reducer: {
$0 + $1
})
reduce(numbers: [1, 2, 3, 4], reducer: { $0 + $1 })
/*:
## Trailing Closures
If you need to pass a closure expression to a function as the function's final argument and
the closure expression is long, it can be useful to write it as a trailing closure instead.
A trailing closure is written after the function call's parentheses, even though it is still
an argument to the function. When you use the trailing closure syntax, you don’t write
the argument label for the closure as part of the function call.
*/
reduce(numbers: [1, 2, 3, 4]) { (a: Int, b: Int) -> Int in
return a + b
}
// Or even ...
reduce(numbers: [1, 2, 3, 4]) { a, b in return a + b }
reduce(numbers: [1, 2, 3, 4]) { return $0 + $1 }
reduce(numbers: [1, 2, 3, 4]) { $0 + $1 }
//: --------------------------------------------------------------------------------------------------------------------
/*:
## Capturing Values
A closure can capture constants and variables from the surrounding context
in which it is defined. The closure can then refer to and modify the values
of those constants and variables from within its body,
even if the original scope that defined the constants and variables no longer exists.
*/
func makeIncrementer(forIncrement amount: Int) -> (() -> Int) {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
let oneStepIncrementer = makeIncrementer(forIncrement: 1)
let tenStepsIncrementer = makeIncrementer(forIncrement: 10)
oneStepIncrementer()
oneStepIncrementer()
oneStepIncrementer()
tenStepsIncrementer()
oneStepIncrementer()
tenStepsIncrementer()
/*:
We can find that there are different `runningTotal` vairables **captured** by the two incremeneter.
So their value are separated and won't affect each other.
And also, although the scope of `runnintTotal` is end, but it still avaialbe
inside the incremeneter closure. _(Because it has been captured by closures.)_
*/
//: ---
//:
//: [<- Previous](@previous) | [Next ->](@next)
//:
|
0 | import UIKit
import LoyaltyStation
class ViewController: UIViewController {
@IBOutlet weak var views: UIView!
@IBAction func open(_ sender: Any) {
LoyaltyStation.open(on: self)
}
@IBAction func login(_ sender: Any) {
LoyaltyStation.login(user: User(id: "test-id", firstName: "Riyad", lastName: "Yahya", country: nil, referral: nil, hash: "237ccb1812cf2c893e341788921ec62515ca6d0507d7e4577055b25b794f831c"))
}
}
|
0 | import UIKit
import StorageKit
import RxSwift
public class Kit {
private static let supportedCurrencies = [
Currency(code: "AUD", symbol: "A$", decimal: 2),
Currency(code: "BRL", symbol: "R$", decimal: 2),
Currency(code: "CAD", symbol: "C$", decimal: 2),
Currency(code: "CHF", symbol: "₣", decimal: 2),
Currency(code: "CNY", symbol: "¥", decimal: 2),
Currency(code: "EUR", symbol: "€", decimal: 2),
Currency(code: "GBP", symbol: "£", decimal: 2),
Currency(code: "HKD", symbol: "HK$", decimal: 2),
Currency(code: "ILS", symbol: "₪", decimal: 2),
Currency(code: "JPY", symbol: "¥", decimal: 2),
Currency(code: "RUB", symbol: "₽", decimal: 2),
Currency(code: "SGD", symbol: "S$", decimal: 2),
Currency(code: "USD", symbol: "$", decimal: 2),
Currency(code: "BTC", symbol: "₿", decimal: 8),
Currency(code: "ETH", symbol: "Ξ", decimal: 8),
Currency(code: "BNB", symbol: "BNB", decimal: 8),
]
private let currencyManager: CurrencyManager
public init(localStorage: ILocalStorage) {
currencyManager = CurrencyManager(currencies: Kit.supportedCurrencies, localStorage: localStorage)
}
}
extension Kit {
public var baseCurrency: Currency {
get {
currencyManager.baseCurrency
}
set {
currencyManager.baseCurrency = newValue
}
}
public var currencies: [Currency] {
currencyManager.currencies
}
public var baseCurrencyUpdatedObservable: Observable<Currency> {
currencyManager.baseCurrencyUpdatedObservable
}
public static func currencyIcon(code: String) -> UIImage? {
CurrencyKit.image(named: code)
}
}
|
0 | //
// AppDelegate.swift
// HaroldExample
//
// Created by Lacy Rhoades on 6/28/17.
// Copyright © 2017 Lacy Rhoades. All rights reserved.
//
import UIKit
import Harold
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var scanner: Harold?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.scanner = Harold()
if let mainMenu = self.window?.rootViewController as? ViewController {
self.scanner?.loggingDelegate = mainMenu
self.scanner?.addListener(mainMenu)
}
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.
scanner?.pauseScanning()
}
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.
scanner?.startScanning()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
0 | //
// BaseController.swift
// NewToday
//
// Created by 吴腾通 on 2020/3/2.
// Copyright © 2020 FL SMART. All rights reserved.
//
import UIKit
class BaseController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
}
extension BaseController {
// 重写 当调用模态视图时,展示全屏
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
viewControllerToPresent.modalPresentationStyle = .fullScreen
super .present(viewControllerToPresent, animated: flag, completion: completion)
}
}
|
0 | extension PhotoEditorController: UITextViewDelegate {
public func textViewDidChange(_ textView: UITextView) {
let rotation = atan2(textView.transform.b, textView.transform.a)
if rotation == 0 {
let oldFrame = textView.frame
let sizeToFit = textView.sizeThatFits(CGSize(width: oldFrame.width, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: oldFrame.width, height: sizeToFit.height)
}
}
public func textViewDidBeginEditing(_ textView: UITextView) {
isTyping = true
activeTextView = textView
textView.superview?.bringSubviewToFront(textView)
textView.font = UIFont.systemFont(ofSize: 24)
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
doneButtonTapped()
editedSomething = true
return true
}
return true
}
public func textViewDidEndEditing(_ textView: UITextView) {
activeTextView = nil
}
private func doneButtonTapped() {
view.endEditing(true)
canvasImageView.isUserInteractionEnabled = true
isTyping = false
}
@objc func onKeyboardHide() {
view.endEditing(true)
canvasImageView.isUserInteractionEnabled = true
isTyping = false
}
}
|
0 | //
// AppDelegate.swift
// YiMaiPatient
//
// Created by ios-dev on 16/8/13.
// Copyright © 2016年 yimai. All rights reserved.
//
import UIKit
import CoreData
import UMSocialCore
import UMSocialNetwork
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate {
var window: UIWindow?
var NotifyCationProcession = false
func RegisterNotification(app: UIApplication) {
let types = UIUserNotificationType(rawValue: UIUserNotificationType.Badge.rawValue | UIUserNotificationType.Sound.rawValue | UIUserNotificationType.Alert.rawValue)
let notificationSetting = UIUserNotificationSettings(forTypes: types, categories: nil)
app.registerUserNotificationSettings(notificationSetting)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
YMVar.DeviceToken = deviceToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
YMVar.DeviceToken = YMVar.DeviceToken.stringByReplacingOccurrencesOfString(" ", withString: "")
UMessage.registerDeviceToken(deviceToken)
print("remote push register success \(YMVar.DeviceToken)")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("remote push register failed")
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
completionHandler(UIBackgroundFetchResult.NewData)
UMessage.setAutoAlert(false)
if(0 == YMVar.MyInfo.count) {
application.applicationIconBadgeNumber = 0
return
}
let action = userInfo["action"] as? String
if(nil == action) {
application.applicationIconBadgeNumber = 0
return
}
let ctrl = window?.rootViewController as? UINavigationController
if(nil == ctrl) {
application.applicationIconBadgeNumber = 0
return
}
if(application.applicationState != UIApplicationState.Active) {
YMNotificationHandler.HandlerMap[action!]?(ctrl!, userInfo)
completionHandler(UIBackgroundFetchResult.NewData)
} else {
completionHandler(UIBackgroundFetchResult.NoData)
}
application.applicationIconBadgeNumber = 0
}
func GoToBroadCast() {
// if(NotifyCationProcession) {
// return
// }
if(0 == YMVar.MyInfo.count) {
return
}
//
// NotifyCationProcession = true
// if(YMCommonStrings.CS_PAGE_INDEX_NAME != YMCurrentPage.CurrentPage) {
// YMDelay(0.5, closure: {
// self.GoToBroadCast()
// })
// }
// NotifyCationProcession = false
let ctrl = window?.rootViewController as? UINavigationController
PageJumpActions(navController: ctrl).DoJump(YMCommonStrings.CS_PAGE_SYS_BROADCAST)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
YMCoreDataEngine.EngineInitialize()
WXApi.registerApp("wx2097e8b109f9dc35", withDescription: "YiMaiPatient-1.0")
UMessage.startWithAppkey("amgk5dbz4onk136msjkax7e3og4kadqz", launchOptions: launchOptions)
UMessage.registerForRemoteNotifications()
UMessage.setLogEnabled(true)
// RegisterNotification(application)
application.applicationIconBadgeNumber = 0
UMSocialManager.defaultManager().openLog(true)
UMSocialManager.defaultManager().umSocialAppkey = "58073c2ae0f55a4ac00023e4"
UMSocialManager.defaultManager().setPlaform(UMSocialPlatformType.WechatSession,
appKey: "wx2097e8b109f9dc35", appSecret: "9zbnr31s8rijwrn5676ll9xhz8k56brn",
redirectURL: "https://www.medi-link.cn")
UMSocialManager.defaultManager().setPlaform(UMSocialPlatformType.Sina,
appKey: "1075290971", appSecret: "ebd03c962864546d7b5e854f2b4a8dc1",
redirectURL: "https://www.medi-link.cn")
UIDevice.currentDevice()
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.yimai.patient.YiMaiPatient" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("YiMaiPatient", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
print("openURL:\(url.absoluteString)")
if (url.scheme == "wx2097e8b109f9dc35") {
return WXApi.handleOpenURL(url, delegate: self)
}
return false
}
//wx pay callback
func onResp(resp: BaseResp!) {
let ctrl = window?.rootViewController as? UINavigationController
let targetCtrl = ctrl?.viewControllers.last
if resp.isKindOfClass(PayResp) {
switch resp.errCode {
case 0 :
targetCtrl?.YMUpdateStateFromWXPay()
default:
targetCtrl?.YMShowErrorFromWXPay()
}
}
}
}
func YMDelay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
|
0 | //
// TriggerActionHandler.swift
//
// Created by ToKoRo on 2017-09-03.
//
import HomeKit
protocol TriggerActionHandler {
func handleRemove(_ trigger: HMTrigger)
}
|
0 | //
// HighlightableRoundedButtonTests.swift
// AHDownloadButton_Tests
//
// Created by Amer Hukic on 28/01/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import XCTest
@testable import AHDownloadButton
class HighlightableRoundedButtonTests: XCTestCase {
var highlightableRoundedButton: HighlightableRoundedButton!
override func setUp() {
highlightableRoundedButton = HighlightableRoundedButton()
}
override func tearDown() {
highlightableRoundedButton = nil
}
func testSettingIsHighlightedShouldUpdateButtonColors() {
highlightableRoundedButton.isHighlighted = true
XCTAssertTrue(highlightableRoundedButton.backgroundColor == highlightableRoundedButton.highlightedBackgroundColor)
XCTAssertTrue(highlightableRoundedButton.titleColor(for: .normal) == highlightableRoundedButton.highlightedTitleColor)
highlightableRoundedButton.isHighlighted = false
XCTAssertTrue(highlightableRoundedButton.backgroundColor == highlightableRoundedButton.nonhighlightedBackgroundColor)
XCTAssertTrue(highlightableRoundedButton.titleColor(for: .normal) == highlightableRoundedButton.nonhighlightedTitleColor)
}
func testLayoutSubviewsShouldUpdateCornerRadius() {
highlightableRoundedButton.layoutSubviews()
XCTAssertTrue(highlightableRoundedButton.layer.cornerRadius == highlightableRoundedButton.frame.height / 2)
}
}
|
0 | //
// CreateContestCoordinator.swift
// lily
//
// Created by Nathan Chan on 9/13/17.
// Copyright © 2017 Nathan Chan. All rights reserved.
//
import UIKit
protocol CreateContestCoordinatorDelegate: class {
func createContestCoordinatorDelegateDidCancel(_ createContestCoordinator: CreateContestCoordinator)
func createContestCoordinator(_ createContestCoordinator: CreateContestCoordinator, didCreateContest contest: Contest)
}
class CreateContestCoordinator: NavigationCoordinator {
var navigationController: UINavigationController
var childCoordinators: [Coordinator] = []
weak var delegate: CreateContestCoordinatorDelegate?
var createContestViewModel: CreateContestViewModel
required init(navigationController: UINavigationController) {
self.navigationController = navigationController
createContestViewModel = CreateContestViewModel()
}
func start() {
showCreateContestSelectMediaViewController()
}
private func showCreateContestSelectMediaViewController() {
let createContestSelectMediaViewController = CreateContestSelectMediaViewController(viewModel: createContestViewModel)
createContestViewModel.delegate = self
self.navigationController.pushViewController(createContestSelectMediaViewController, animated: true)
}
fileprivate func showCreateContestViewController(_ media: Media) {
let createContestViewController = CreateContestViewController(viewModel: createContestViewModel)
createContestViewModel.delegate = self
createContestViewModel.selectedMedia = media
self.navigationController.pushViewController(createContestViewController, animated: true)
}
}
extension CreateContestCoordinator: CreateContestViewModelDelegate {
func createContestViewDidClickCancel(_ createContestViewModel: CreateContestViewModel) {
self.delegate?.createContestCoordinatorDelegateDidCancel(self)
}
func createContestView(_ createContestViewModel: CreateContestViewModel, didSelectMedia media: Media) {
showCreateContestViewController(media)
}
func createContestView(_ createContestViewModel: CreateContestViewModel, didCreateContest contest: Contest) {
self.delegate?.createContestCoordinator(self, didCreateContest: contest)
}
func createContestView(_ createContestViewModel: CreateContestViewModel, didClickViewOnIG media: Media) {
self.openMedia(media)
}
}
|
0 | //
// Utils.swift
// App
//
// Created by Luis Vasquez on 19/05/20.
// Copyright © 2020 Cisco. All rights reserved.
//
import UIKit
class Utils: NSObject {
static func showAlert(controller: UIViewController, title: String, message: String){
let alert = UIAlertController(title: "Network Error", message: "Not able to access the internet. Please check your network connectivity", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
controller.present(alert, animated: true, completion: nil)
}
static func showNetworkAlertError(controller: UIViewController){
showAlert(controller: controller, title: "Network Error", message: "Not able to access the internet. Please check your network connectivity")
}
}
|
0 | //
// SCDefinitionDisplayView.swift
// AussieDataHelper
//
// Created by Stephen Cao on 29/6/19.
// Copyright © 2019 Stephencao Cao. All rights reserved.
//
import UIKit
protocol SCDefinitionDisplayViewDelegate: NSObjectProtocol {
func didClickKeyboardSearchKey(view: SCDefinitionDisplayView)
func didScrollToBottom(view: SCDefinitionDisplayView)
func didSelectedCell(view: SCDefinitionDisplayView, definitionText: String?)
}
private let reuseIdentifier = "definitions_cell"
class SCDefinitionDisplayView: UIView {
weak var delegate: SCDefinitionDisplayViewDelegate?
var viewModel: SCDefinitionsViewModel?
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var textField: UITextField!
var currentPage = 1
var shouldPullUp: Bool = false
class func displayView()->SCDefinitionDisplayView{
let nib = UINib(nibName: "SCDefinitionDisplayView", bundle: nil)
let v = nib.instantiate(withOwner: self, options: nil)[0] as! SCDefinitionDisplayView
v.frame = UIScreen.main.bounds
return v
}
override func awakeFromNib() {
super.awakeFromNib()
textField.delegate = self
textField.returnKeyType = .search
tableView.estimatedRowHeight = 140
tableView.rowHeight = UITableView.automaticDimension
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "SCDefinitionsTableViewCell", bundle: nil), forCellReuseIdentifier: reuseIdentifier)
}
@IBAction func clickClearTextFieldButton(_ sender: Any) {
textField.text?.removeAll()
textField.resignFirstResponder()
}
}
extension SCDefinitionDisplayView: UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
delegate?.didClickKeyboardSearchKey(view: self)
return false
}
}
extension SCDefinitionDisplayView: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.separatorStyle = (viewModel?.definitionsData?.content?.count ?? 0) > 0 ? UITableViewCell.SeparatorStyle.singleLine : .none
return viewModel?.definitionsData?.content?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! SCDefinitionsTableViewCell
cell.cententItem = viewModel?.definitionsData?.content?[indexPath.row].content
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let row = indexPath.row
// let currentSection == indexPath.section
let section = tableView.numberOfSections - 1
if row < 0 || section < 0{
return
}
let rowCount = tableView.numberOfRows(inSection: section)
// && currentSection == section
if row == (rowCount - 1) && !shouldPullUp{
shouldPullUp = true
currentPage += 1
delegate?.didScrollToBottom(view: self)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.didSelectedCell(view: self, definitionText: viewModel?.definitionsData?.content?[indexPath.row].content?.definition)
}
}
|
0 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei (vvkpx@example.com)
//
// 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 UIKit
class SPPermissionDialogView: UIView {
let titleLabel = UILabel()
let subtitleLabel = UILabel()
var views: [SPPermissionDialogLineView] = []
let descriptionLabel = UILabel()
var layoutWidth: CGFloat = 0 {
didSet {
self.setWidth(self.layoutWidth)
self.layoutSubviews()
}
}
var layoutHeight: CGFloat = 0
var sideInset: CGFloat {
return 22
}
init() {
super.init(frame: .zero)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit() {
self.backgroundColor = SPNativeStyleKit.Colors.white
self.layer.cornerRadius = 17
self.subtitleLabel.text = "".uppercased()
self.subtitleLabel.numberOfLines = 0
self.subtitleLabel.textColor = SPNativeStyleKit.Colors.gray
self.subtitleLabel.font = UIFont.system(type: .DemiBold, size: 15)
self.addSubview(self.subtitleLabel)
self.titleLabel.text = ""
self.titleLabel.numberOfLines = 0
self.titleLabel.textColor = SPNativeStyleKit.Colors.black
self.titleLabel.font = UIFont.system(type: .Bold, size: 27)
self.addSubview(self.titleLabel)
self.descriptionLabel.text = ""
self.descriptionLabel.numberOfLines = 0
self.descriptionLabel.textColor = SPNativeStyleKit.Colors.gray
self.descriptionLabel.font = UIFont.system(type: .Regular, size: 11)
self.addSubview(self.descriptionLabel)
}
func add(view: SPPermissionDialogLineView) {
view.updateStyle()
self.addSubview(view)
self.views.append(view)
}
override func layoutSubviews() {
super.layoutSubviews()
self.subtitleLabel.frame = CGRect.init(x: self.sideInset, y: 0, width: self.layoutWidth - self.sideInset * 2, height: 0)
self.subtitleLabel.sizeToFit()
if SPDevice.Orientation.isPortrait {
self.subtitleLabel.frame.origin.y = 27
} else {
self.subtitleLabel.frame.origin.y = 17
}
self.titleLabel.frame = CGRect.init(x: self.sideInset, y: self.subtitleLabel.frame.bottomYPosition + 2, width: self.frame.width - self.sideInset * 2, height: 0)
self.titleLabel.sizeToFit()
var currentYPosition: CGFloat = 0
if SPDevice.Orientation.isPortrait {
currentYPosition = self.titleLabel.frame.bottomYPosition + 20
} else {
currentYPosition = self.titleLabel.frame.bottomYPosition - 2
}
for view in self.views {
view.frame = CGRect.init(x: self.sideInset, y: currentYPosition, width: self.layoutWidth - sideInset * 2, height: 10)
view.layoutSubviews()
currentYPosition += view.frame.height
}
if let view = self.views.last {
view.separatorView.isHidden = true
}
if SPDevice.Orientation.isPortrait {
self.descriptionLabel.frame = CGRect.init(x: self.sideInset, y: currentYPosition + 20, width: self.layoutWidth - self.sideInset * 2, height: 0)
self.descriptionLabel.sizeToFit()
SPAnimation.animate(0.2, animations: {
self.descriptionLabel.alpha = 1
})
self.layoutHeight = self.descriptionLabel.frame.bottomYPosition + 22
} else {
SPAnimation.animate(0.2, animations: {
self.descriptionLabel.alpha = 0
})
self.layoutHeight = currentYPosition + 2
}
let shadowPath = UIBezierPath.init(
roundedRect: CGRect.init(x: 0, y: 9, width: self.layoutWidth, height: self.layoutHeight),
cornerRadius: self.layer.cornerRadius
)
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize.zero
self.layer.shadowOpacity = Float(0.07)
self.layer.shadowRadius = 17
self.layer.masksToBounds = false
self.layer.shadowPath = shadowPath.cgPath
}
}
class SPPermissionDialogLineView: UIView {
let titleLabel = UILabel()
let subtitleLabel = UILabel()
var iconView: SPGolubevIconView = SPGolubevIconView.init()
var imageView = UIImageView()
var button = SPAppStoreActionButton()
var separatorView = UIView()
var permission: SPPermissionType
private var allowTitle: String
private var allowedTitle: String
init(permission: SPPermissionType, title: String, subtitle: String, allowTitle: String, allowedTitle: String, image: UIImage? = nil) {
self.permission = permission
self.allowTitle = allowTitle
self.allowedTitle = allowedTitle
super.init(frame: .zero)
self.titleLabel.text = title
self.subtitleLabel.text = subtitle
self.imageView.isHidden = true
if let image = image {
self.imageView.contentMode = .scaleAspectFit
self.imageView.image = image
self.iconView.isHidden = true
self.imageView.isHidden = false
} else {
switch permission {
case .calendar:
self.iconView.type = .calendar
case .camera:
self.iconView.type = .camera
case .contacts:
self.iconView.type = .book
case .microphone:
self.iconView.type = .micro
case .notification:
self.iconView.type = .ball
case .photoLibrary:
self.iconView.type = .photoLibrary
case .reminders:
self.iconView.type = .calendar
case .speech:
self.iconView.type = .micro
case .locationWhenInUse:
self.iconView.type = .compass
case .locationAlways:
self.iconView.type = .compass
case .locationWithBackground:
self.iconView.type = .compass
case .mediaLibrary:
self.iconView.type = .headphones
}
}
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
self.permission = .notification
self.allowTitle = "Allow"
self.allowedTitle = "Allowed"
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit() {
self.backgroundColor = SPNativeStyleKit.Colors.white
self.addSubview(self.imageView)
self.addSubview(self.iconView)
self.titleLabel.numberOfLines = 1
self.titleLabel.textColor = SPNativeStyleKit.Colors.black
self.titleLabel.font = UIFont.system(type: .DemiBold, size: 15)
self.addSubview(self.titleLabel)
self.subtitleLabel.numberOfLines = 2
self.subtitleLabel.textColor = SPNativeStyleKit.Colors.gray
self.subtitleLabel.font = UIFont.system(type: .Regular, size: 13)
self.addSubview(self.subtitleLabel)
self.button.setTitle(self.allowTitle)
self.button.style = .base
self.addSubview(self.button)
self.separatorView.backgroundColor = SPNativeStyleKit.Colors.gray.withAlphaComponent(0.3)
self.addSubview(self.separatorView)
}
func updateStyle() {
if SPPermission.isAllow(self.permission) {
SPAnimation.animate(0.2, animations: {
self.button.setTitle(self.allowedTitle)
self.button.style = .main
self.button.sizeToFit()
})
} else {
SPAnimation.animate(0.2, animations: {
self.button.setTitle(self.allowTitle)
self.button.style = .base
self.button.sizeToFit()
})
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.setHeight(79)
self.iconView.frame = CGRect.init(x: 0, y: 0, width: 45, height: 45)
self.iconView.center.y = self.frame.height / 2
self.imageView.frame = self.iconView.frame
self.button.sizeToFit()
self.button.frame.bottomXPosition = self.frame.width
self.button.center.y = self.frame.height / 2
let titleInset: CGFloat = 15
let titlesWidth: CGFloat = self.button.frame.origin.x - self.iconView.frame.bottomXPosition - titleInset * 2
self.titleLabel.frame = CGRect.init(x: 0, y: 8, width: titlesWidth, height: 0)
self.titleLabel.sizeToFit()
self.titleLabel.setWidth(titlesWidth)
self.titleLabel.frame.origin.x = self.iconView.frame.bottomXPosition + titleInset
self.subtitleLabel.frame = CGRect.init(x: self.titleLabel.frame.origin.x + titleInset, y: 0, width: titlesWidth, height: 0)
self.subtitleLabel.sizeToFit()
self.subtitleLabel.setWidth(titlesWidth)
self.subtitleLabel.frame.origin.x = self.iconView.frame.bottomXPosition + titleInset
let allHeight = self.titleLabel.frame.height + 2 + self.subtitleLabel.frame.height
self.titleLabel.frame.origin.y = (self.frame.height - allHeight) / 2
self.subtitleLabel.frame.origin.y = self.titleLabel.frame.bottomYPosition + 2
self.separatorView.frame = CGRect.init(x: self.subtitleLabel.frame.origin.x, y: self.frame.height - 0.7, width: self.button.frame.bottomXPosition - self.subtitleLabel.frame.origin.x, height: 0.7)
self.separatorView.round()
/*self.setHeight(75)
self.iconView.frame = CGRect.init(x: 0, y: 0, width: 45, height: 45)
self.iconView.center.y = self.frame.width / 2
self.button.sizeToFit()
self.button.frame.bottomXPosition = self.frame.width
self.button.center.y = self.frame.height / 2
let titleInset: CGFloat = 15
let titlesWidth: CGFloat = self.button.frame.origin.x - self.iconView.frame.bottomXPosition - titleInset * 2
self.titleLabel.frame = CGRect.init(x: self.iconView.frame.bottomXPosition + titleInset, y: 8, width: titlesWidth, height: 0)
self.titleLabel.sizeToFit()
self.subtitleLabel.frame = CGRect.init(x: self.iconView.frame.bottomXPosition + titleInset, y: self.titleLabel.frame.bottomYPosition + 2, width: titlesWidth, height: 0)
self.subtitleLabel.setHeight(self.frame.height - 12 - self.subtitleLabel.frame.origin.y)
//self.subtitleLabel.sizeToFit()
//let height = (self.iconView.frame.bottomYPosition + 12) > (self.subtitleLabel.frame.bottomYPosition + 12) ? self.iconView.frame.bottomYPosition + 12 : self.subtitleLabel.frame.bottomYPosition + 12
//self.setHeight(75)
self.separatorView.frame = CGRect.init(x: self.subtitleLabel.frame.origin.x, y: self.frame.height - 0.7, width: self.button.frame.bottomXPosition - self.subtitleLabel.frame.origin.x, height: 0.7)
self.separatorView.round()*/
}
}
|
0 | //
// SceneDelegate.swift
// BetterReads
//
// Created by Ciara Beitel on 4/16/20.
// Copyright © 2020 Labs23. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window`
// to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be
// initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are
// new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily
// discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
|
0 | //
// ModifierMatchController.swift
// MonTennis
//
// Created by Thomas Luquet on 01/07/2015.
// Copyright (c) 2015 Thomas Luquet. All rights reserved.
//
import UIKit
class ModifierMatchController: UITableViewController {
internal var match: Match!
internal var id: Int!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
var rows : Int
switch section {
case 0:
rows = 4
case 1:
rows = 3
default:
rows = 0
}
return rows
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell
switch indexPath.section {
case 0:
cell = tableView.dequeueReusableCellWithIdentifier("detailModifier", forIndexPath: indexPath)
switch indexPath.row {
case 0:
cell.textLabel?.text = "Résultat"
if(match.resultat){
cell.detailTextLabel?.text = "Victoire"
}else{
cell.detailTextLabel?.text="Défaite"
}
case 1:
cell.textLabel?.text = "WO"
if(match.wo){
cell.detailTextLabel?.text = "Oui"
}else{
cell.detailTextLabel?.text = "Non"
}
case 2:
cell.textLabel?.text = "Format"
if(match.coef == 1.0){
cell.detailTextLabel?.text = "Normal"
}else{
cell.detailTextLabel?.text = "Court"
}
case 3:
cell.textLabel?.text = "Bonus championnat"
if(match.bonus){
cell.detailTextLabel?.text = "Oui"
}else{
cell.detailTextLabel?.text = "Non"
}
default:
cell.textLabel?.text = ""
cell.detailTextLabel?.text = ""
}
case 1:
switch indexPath.row {
case 0:
cell = tableView.dequeueReusableCellWithIdentifier("detailModifierText", forIndexPath: indexPath)
cell.textLabel?.text = "Nom"
cell.detailTextLabel?.text = match.lastName
case 1:
cell = tableView.dequeueReusableCellWithIdentifier("detailModifierText", forIndexPath: indexPath)
cell.textLabel?.text = "Prénom"
cell.detailTextLabel?.text = match.firstName
case 2:
cell = tableView.dequeueReusableCellWithIdentifier("detailModifier", forIndexPath: indexPath)
cell.textLabel?.text = "Classement"
cell.detailTextLabel?.text = match.classement.string
default:
cell = tableView.dequeueReusableCellWithIdentifier("detailModifier", forIndexPath: indexPath)
cell.textLabel?.text = ""
cell.detailTextLabel?.text = ""
}
default:
cell = tableView.dequeueReusableCellWithIdentifier("detailModifier", forIndexPath: indexPath)
cell.textLabel?.text = ""
cell.detailTextLabel?.text = ""
}
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = ""
switch section {
case 0:
title = "Match"
case 1:
title = "Infos Adversaire"
default:
title = ""
}
return title
}
@IBAction func saveMatchChanges(segue:UIStoryboardSegue){
self.tableView.reloadData()
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if let cell = sender as? UITableViewCell {
if(segue.identifier == "modifierChoix"){
let controller = segue.destinationViewController as! ModifierChoixController
controller.choixType = cell.textLabel?.text
controller.match = match
controller.id = id
}
else if(segue.identifier == "modifierText"){
let controller = segue.destinationViewController as! ModifierTextController
controller.textValue = cell.detailTextLabel?.text
controller.textType = cell.textLabel?.text
controller.match = match
controller.id = id
}
}
else if(segue.identifier == "deleteMatch"){
if(match.resultat){
barCtrl.user.victoires.removeAtIndex(id)
}else{
barCtrl.user.defaites.removeAtIndex(id)
}
barCtrl.clearCoreData()
barCtrl.fillCoreData()
}
}
}
|
0 | //
// AUParamsApp
// AudioUnitViewController.swift
//
// last build: macOS 10.13, Swift 4.0
//
// Created by Gene De Lisa on 5/25/18.
// Copyright ©(c) 2018 Gene De Lisa. All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//
// In addition:
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// 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 CoreAudioKit
public class AudioUnitViewController: AUViewController, AUAudioUnitFactory {
/*
When this view controller is instantiated within the Containing App, its
audio unit is created independently, and passed to the view controller here.
*/
public var audioUnit: AUAudioUnit? {
didSet {
/*
We may be on a dispatch worker queue processing an XPC request at
this time, and quite possibly the main queue is busy creating the
view. To be thread-safe, dispatch onto the main queue.
It's also possible that we are already on the main queue, so to
protect against deadlock in that case, dispatch asynchronously.
*/
NSLog("got the audio unit \(String(describing: audioUnit))")//
DispatchQueue.main.async {
if self.isViewLoaded {
self.connectUIToAudioUnit()
}
}
}
}
var intervalAUParameter: AUParameter?
var parameterObserverToken: AUParameterObserverToken?
@IBOutlet weak var intervalSegmentedControl: UISegmentedControl!
@IBOutlet weak var intervalLabel: UILabel!
public override func viewDidLoad() {
super.viewDidLoad()
NSLog("\(#function)")
if audioUnit == nil {
return
}
connectUIToAudioUnit()
}
public func createAudioUnit(with componentDescription: AudioComponentDescription) throws -> AUAudioUnit {
NSLog("\(#function)")
audioUnit = try AUParamsPresetsAudioUnit(componentDescription: componentDescription, options: [])
// Check if the UI has been loaded
// if self.isViewLoaded {
// NSLog("\(#function) connecting UI in create audio unit")
// connectUIToAudioUnit()
// }
return audioUnit!
}
func connectUIToAudioUnit() {
NSLog("\(#function)")
guard let paramTree = audioUnit?.parameterTree else {
NSLog("The audio unit has no parameters!")
return
}
// get the parameter
self.intervalAUParameter = paramTree.value(forKey: "intervalParameter") as? AUParameter
NSLog("interauparameter \(String(describing: intervalAUParameter))");
// or
// if let theUnit = audioUnit as? AUParamsPresetsAudioUnit {
// if let param = theUnit.parameterTree?.parameter(withAddress: AUParameterAddress(intervalParameter)) {
// NSLog("connectUIToAudioUnit intervalParam: \(String(describing: param))")
// self.intervalAUParameter = param
//
// DispatchQueue.main.async { [weak self] in
// guard let strongSelf = self else { return }
// NSLog("connectUIToAudioUnit new value: \(param.value) will sub 1")
// strongSelf.intervalSegmentedControl.selectedSegmentIndex = Int(param.value - 1)
// strongSelf.intervalLabel.text = strongSelf.intervalAUParameter!.string(fromValue: nil)
// }
// }
// }
parameterObserverToken = paramTree.token(byAddingParameterObserver: { [weak self] address, value in
guard let strongSelf = self else {
NSLog("self is nil; returning")
return
}
DispatchQueue.main.async {
if address == strongSelf.intervalAUParameter!.address {
NSLog("connectUIToAudioUnit2 observed new value: \(value)")
strongSelf.intervalSegmentedControl.selectedSegmentIndex = Int(value - 1)
strongSelf.intervalLabel.text = strongSelf.intervalAUParameter!.string(fromValue: nil)
}
}
})
self.intervalLabel.text = self.intervalAUParameter!.string(fromValue: nil)
self.intervalSegmentedControl.selectedSegmentIndex = Int(self.intervalAUParameter!.value - 1)
}
// if I had a slider
@IBAction func intervalSliderValueChangedAction(_ sender: UISlider) {
guard let theAudioUnit = audioUnit as? AUParamsPresetsAudioUnit,
let intervalParameter =
theAudioUnit.parameterTree?.parameter(withAddress: AUParameterAddress(intervalParameter))
else {
NSLog("could not get the audio unit or the parameter in \(#function)")
return
}
intervalParameter.setValue(sender.value, originator: parameterObserverToken)
}
@IBAction func intervalValueChanged(_ sender: UISegmentedControl) {
var interval: AUValue = 0
switch sender.selectedSegmentIndex {
case 0: interval = 1
case 1: interval = 2
case 2: interval = 3
case 3: interval = 4
case 4: interval = 5
case 5: interval = 6
case 6: interval = 7
case 7: interval = 8
case 8: interval = 9
case 9: interval = 10
case 10: interval = 11
case 11: interval = 12
default: break
}
//or self.intervalAUParameter?.value = interval
self.intervalAUParameter?.setValue(interval, originator: parameterObserverToken)
// just debugging
if let p = self.intervalAUParameter {
NSLog("intervalParam: \(String(describing: p))")
let s = p.string(fromValue: &p.value)
NSLog("value string: \(s)")
NSLog("final value: \(p.value)")
} else {
NSLog("oops self.intervalAUParameter is nil")
}
}
}
|
0 | //
// CLLocationManager+Rx.swift
// MyRx
//
// Created by Maple on 2017/8/30.
// Copyright © 2017年 Maple. All rights reserved.
//
import UIKit
import CoreLocation
import RxSwift
import RxCocoa
extension Reactive where Base: CLLocationManager {
/**
Reactive wrapper for `delegate`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var delegate: DelegateProxy {
return RxCLLocationManagerDelegateProxy.proxyForObject(base)
}
// MARK: Responding to Authorization Changes
/**
Reactive wrapper for `delegate` message.
*/
public var didChangeAuthorizationStatus: Observable<CLAuthorizationStatus> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didChangeAuthorization:)))
.map { a in
let number = try castOrThrow(NSNumber.self, a[1])
return CLAuthorizationStatus( rawValue: Int32(number.intValue)) ?? .notDetermined
}
}
// MARK: Responding to Location Events
/**
Reactive wrapper for `delegate` message.
*/
public var didUpdateLocations: Observable<[CLLocation]> {
return (delegate as! RxCLLocationManagerDelegateProxy).didUpdateLocationsSubject.asObservable()
}
/**
Reactive wrapper for `delegate` message.
*/
public var didFailWithError: Observable<Error> {
return (delegate as! RxCLLocationManagerDelegateProxy).didFailWithErrorSubject.asObservable()
}
}
fileprivate func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
|
0 | //
// PDFError.swift
// TPPDF
//
// Created by Philip Niedertscheider on 13/06/2017.
//
import Foundation
/**
List of errors which can occur during using this framework
*/
public enum PDFError: Error {
/**
TODO: Documentation
*/
case tableContentInvalid(value: Any?)
/**
TODO: Documentation
*/
case tableIsEmpty
/**
TODO: Documentation
*/
case tableStructureInvalid(message: String)
/**
TODO: Documentation
*/
case tableIndexOutOfBounds(index: Int, length: Int)
/**
TODO: Documentation
*/
case tableCellWeakReferenceBroken
/**
TODO: Documentation
*/
case textObjectIsNil
/**
TODO: Documentation
*/
case textObjectNotCalculated
/**
TODO: Documentation
*/
case invalidHexLength(length: Int)
/**
TODO: Documentation
*/
case invalidHex(hex: String)
/**
TODO: Documentation
*/
case copyingFailed
/**
TODO: Documentation
*/
case externalDocumentURLInvalid(url: URL)
/**
TODO: Documentation
*/
case pageOutOfBounds(index: Int)
/**
TODO: Documentation
*/
public var localizedDescription: String {
switch self {
case .tableContentInvalid(let value):
return "Table content is invalid: " + value.debugDescription
case .tableIsEmpty:
return "Table is empty"
case .tableStructureInvalid(let message):
return "Table structure invalid: " + message
case .tableIndexOutOfBounds(let index, let length):
return "Table index out of bounds: <index: \(index), length: \(length)>"
case .tableCellWeakReferenceBroken:
return "Weak reference in table cell is broken"
case .textObjectIsNil:
return "No text object has been set"
case .textObjectNotCalculated:
return "Text object is missing string, maybe not calculated?"
case .invalidHexLength(let length):
return "Hex color string has invalid length: \(length)"
case .invalidHex(let hex):
return "Invalid hexdecimal string: " + hex
case .copyingFailed:
return "Failed to create a copy of an object"
case .externalDocumentURLInvalid(let url):
return "Could not open PDF document at url: " + url.absoluteString
case .pageOutOfBounds(let index):
return "Page \(index) in external document is out of bounds"
}
}
}
|
0 | //
// ManageNodesViewController.swift
// navigatAR
//
// Created by Michael Gira on 2/3/18.
// Copyright © 2018 MICDS Programming. All rights reserved.
//
import CodableFirebase
import Firebase
import UIKit
class ManageNodesViewController: UIViewControllerWithBuilding, UITableViewDataSource {
@IBOutlet weak var nodeTable: UITableView!
@IBAction func unwindToManageNodes(unwindSegue: UIStoryboardSegue) { }
var nodes: [Node] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navigationItem.prompt = forBuilding.1.name
nodeTable.dataSource = self
let ref = Database.database().reference()
// Continuously update `nodes` from database
ref.child("nodes").queryOrdered(byChild: "building").queryEqual(toValue: forBuilding.0).observe(.value, with: { snapshot in
guard snapshot.exists(), let value = snapshot.value else { return }
do {
//guard let currentBuilding = Building.current(root: snapshot) else { print(""); return }
self.nodes = Array((try FirebaseDecoder().decode([FirebasePushKey: Node].self, from: value)).values)//.filter({ $0.building == currentBuilding.id })
self.nodeTable.reloadData()
} catch let error {
print(error) // TODO: properly handle error
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: TableView functions
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nodes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = nodeTable.dequeueReusableCell(withIdentifier: "NodeCell", for: indexPath) as UITableViewCell
let node = nodes[indexPath.row]
cell.textLabel?.text = node.name
cell.detailTextLabel?.text = String(describing: node.type)
return cell
}
}
|
0 | //
// CustomView.swift
// CoreData001
//
// Created by Ankit Kumar Bharti on 24/07/18.
// Copyright © 2018 Exilant. All rights reserved.
//
import Cocoa
@IBDesignable
class CustomView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// allow layer-backed
wantsLayer = true
// Create Text Layer
let textLayer = CATextLayer()
textLayer.frame = NSRect(origin: .zero, size: CGSize(width: dirtyRect.size.width, height: 20.0))
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
let attributes: [NSAttributedStringKey: Any] = [.font: NSFont.systemFont(ofSize: 14.0), .foregroundColor: NSColor.black, .paragraphStyle: paragraph]
let attrubutesString = NSAttributedString(string: "Hello User", attributes: attributes)
textLayer.string = attrubutesString
layer?.addSublayer(textLayer)
// Create image layer
let imageLayer = CALayer()
imageLayer.contents = NSImage(named: NSImage.Name(rawValue: "user"))
imageLayer.frame = NSRect(x: 0.0, y: 20.0, width: dirtyRect.size.width, height: dirtyRect.size.height - 20.0)
layer?.addSublayer(imageLayer)
}
}
|
0 | //
// BolusEntryViewModelTests.swift
// LoopTests
//
// Created by Rick Pasetto on 9/28/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import HealthKit
import LoopCore
import LoopKit
import LoopKitUI
import SwiftUI
import XCTest
@testable import Loop
class BolusEntryViewModelTests: XCTestCase {
// Some of the tests depend on a date on the hour
static let now = ISO8601DateFormatter().date(from: "2020-03-11T07:00:00-0700")!
static let exampleStartDate = now - .hours(2)
static let exampleEndDate = now - .hours(1)
static fileprivate let exampleGlucoseValue = MockGlucoseValue(quantity: exampleManualGlucoseQuantity, startDate: exampleStartDate)
static let exampleManualGlucoseQuantity = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 123.4)
static let exampleManualGlucoseSample =
HKQuantitySample(type: HKQuantityType.quantityType(forIdentifier: .bloodGlucose)!,
quantity: exampleManualGlucoseQuantity,
start: exampleStartDate,
end: exampleEndDate)
static let exampleManualStoredGlucoseSample = StoredGlucoseSample(sample: exampleManualGlucoseSample)
static let exampleCGMGlucoseQuantity = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 100.4)
static let exampleCGMGlucoseSample =
HKQuantitySample(type: HKQuantityType.quantityType(forIdentifier: .bloodGlucose)!,
quantity: exampleCGMGlucoseQuantity,
start: exampleStartDate,
end: exampleEndDate)
static let exampleCarbQuantity = HKQuantity(unit: .gram(), doubleValue: 234.5)
static let exampleBolusQuantity = HKQuantity(unit: .internationalUnit(), doubleValue: 1.0)
static let noBolus = HKQuantity(unit: .internationalUnit(), doubleValue: 0.0)
static let mockUUID = UUID()
static let exampleScheduleOverrideSettings = TemporaryScheduleOverrideSettings(unit: .millimolesPerLiter, targetRange: nil, insulinNeedsScaleFactor: nil)
static let examplePreMealOverride = TemporaryScheduleOverride(context: .preMeal, settings: exampleScheduleOverrideSettings, startDate: exampleStartDate, duration: .indefinite, enactTrigger: .local, syncIdentifier: mockUUID)
static let exampleCustomScheduleOverride = TemporaryScheduleOverride(context: .custom, settings: exampleScheduleOverrideSettings, startDate: exampleStartDate, duration: .indefinite, enactTrigger: .local, syncIdentifier: mockUUID)
var bolusEntryViewModel: BolusEntryViewModel!
fileprivate var delegate: MockBolusEntryViewModelDelegate!
var now: Date = BolusEntryViewModelTests.now
let mockOriginalCarbEntry = StoredCarbEntry(uuid: UUID(), provenanceIdentifier: "provenanceIdentifier", syncIdentifier: "syncIdentifier", syncVersion: 0, startDate: BolusEntryViewModelTests.exampleStartDate, quantity: BolusEntryViewModelTests.exampleCarbQuantity, foodType: "foodType", absorptionTime: 1, createdByCurrentApp: true, userCreatedDate: BolusEntryViewModelTests.now, userUpdatedDate: BolusEntryViewModelTests.now)
let mockPotentialCarbEntry = NewCarbEntry(quantity: BolusEntryViewModelTests.exampleCarbQuantity, startDate: BolusEntryViewModelTests.exampleStartDate, foodType: "foodType", absorptionTime: 1)
let mockFinalCarbEntry = StoredCarbEntry(uuid: UUID(), provenanceIdentifier: "provenanceIdentifier", syncIdentifier: "syncIdentifier", syncVersion: 1, startDate: BolusEntryViewModelTests.exampleStartDate, quantity: BolusEntryViewModelTests.exampleCarbQuantity, foodType: "foodType", absorptionTime: 1, createdByCurrentApp: true, userCreatedDate: BolusEntryViewModelTests.now, userUpdatedDate: BolusEntryViewModelTests.now)
let mockUUID = BolusEntryViewModelTests.mockUUID.uuidString
let queue = DispatchQueue(label: "BolusEntryViewModelTests")
var saveAndDeliverSuccess = false
override func setUpWithError() throws {
now = Self.now
delegate = MockBolusEntryViewModelDelegate()
delegate.mostRecentGlucoseDataDate = now
delegate.mostRecentPumpDataDate = now
saveAndDeliverSuccess = false
setUpViewModel()
}
func setUpViewModel(originalCarbEntry: StoredCarbEntry? = nil, potentialCarbEntry: NewCarbEntry? = nil, selectedCarbAbsorptionTimeEmoji: String? = nil) {
bolusEntryViewModel = BolusEntryViewModel(delegate: delegate,
now: { self.now },
screenWidth: 512,
debounceIntervalMilliseconds: 0,
uuidProvider: { self.mockUUID },
timeZone: TimeZone(abbreviation: "GMT")!,
originalCarbEntry: originalCarbEntry,
potentialCarbEntry: potentialCarbEntry,
selectedCarbAbsorptionTimeEmoji: selectedCarbAbsorptionTimeEmoji)
bolusEntryViewModel.authenticate = authenticateOverride
bolusEntryViewModel.maximumBolus = HKQuantity(unit: .internationalUnit(), doubleValue: 10)
}
var authenticateOverrideCompletion: ((Swift.Result<Void, Error>) -> Void)?
private func authenticateOverride(_ message: String, _ completion: @escaping (Swift.Result<Void, Error>) -> Void) {
authenticateOverrideCompletion = completion
}
func testInitialConditions() throws {
XCTAssertEqual(0, bolusEntryViewModel.glucoseValues.count)
XCTAssertEqual(0, bolusEntryViewModel.predictedGlucoseValues.count)
XCTAssertEqual(.milligramsPerDeciliter, bolusEntryViewModel.glucoseUnit)
XCTAssertNil(bolusEntryViewModel.activeCarbs)
XCTAssertNil(bolusEntryViewModel.activeInsulin)
XCTAssertNil(bolusEntryViewModel.targetGlucoseSchedule)
XCTAssertNil(bolusEntryViewModel.preMealOverride)
XCTAssertNil(bolusEntryViewModel.scheduleOverride)
XCTAssertFalse(bolusEntryViewModel.isManualGlucoseEntryEnabled)
XCTAssertNil(bolusEntryViewModel.enteredManualGlucose)
XCTAssertNil(bolusEntryViewModel.recommendedBolus)
XCTAssertEqual(HKQuantity(unit: .internationalUnit(), doubleValue: 0), bolusEntryViewModel.enteredBolus)
XCTAssertNil(bolusEntryViewModel.activeAlert)
XCTAssertNil(bolusEntryViewModel.activeNotice)
XCTAssertFalse(bolusEntryViewModel.isRefreshingPump)
}
func testChartDateInterval() throws {
// TODO: Test different screen widths
// TODO: Test different insulin models
// TODO: Test different chart history settings
let expected = DateInterval(start: now - .hours(2), duration: .hours(8))
XCTAssertEqual(expected, bolusEntryViewModel.chartDateInterval)
}
// MARK: updating state
func testUpdateDisableManualGlucoseEntryIfNecessary() throws {
bolusEntryViewModel.isManualGlucoseEntryEnabled = true
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
try triggerLoopStateUpdated(with: MockLoopState())
XCTAssertFalse(bolusEntryViewModel.isManualGlucoseEntryEnabled)
XCTAssertNil(bolusEntryViewModel.enteredManualGlucose)
XCTAssertEqual(.glucoseNoLongerStale, bolusEntryViewModel.activeAlert)
}
func testUpdateDisableManualGlucoseEntryIfNecessaryStaleGlucose() throws {
delegate.mostRecentGlucoseDataDate = Date.distantPast
bolusEntryViewModel.isManualGlucoseEntryEnabled = true
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
try triggerLoopStateUpdated(with: MockLoopState())
XCTAssertTrue(bolusEntryViewModel.isManualGlucoseEntryEnabled)
XCTAssertEqual(Self.exampleManualGlucoseQuantity, bolusEntryViewModel.enteredManualGlucose)
XCTAssertNil(bolusEntryViewModel.activeAlert)
}
func testUpdateGlucoseValues() throws {
XCTAssertEqual(0, bolusEntryViewModel.glucoseValues.count)
try triggerLoopStateUpdatedWithDataAndWait()
XCTAssertEqual(1, bolusEntryViewModel.glucoseValues.count)
XCTAssertEqual([100.4], bolusEntryViewModel.glucoseValues.map {
return $0.quantity.doubleValue(for: .milligramsPerDeciliter)
})
}
func testUpdateGlucoseValuesWithManual() throws {
XCTAssertEqual(0, bolusEntryViewModel.glucoseValues.count)
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
try triggerLoopStateUpdatedWithDataAndWait()
XCTAssertEqual([100.4, 123.4], bolusEntryViewModel.glucoseValues.map {
return $0.quantity.doubleValue(for: .milligramsPerDeciliter)
})
}
func testManualEntryClearsEnteredBolus() throws {
bolusEntryViewModel.enteredBolus = Self.exampleBolusQuantity
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
XCTAssertEqual(Self.exampleBolusQuantity, bolusEntryViewModel.enteredBolus)
waitOnMain()
XCTAssertEqual(HKQuantity(unit: .internationalUnit(), doubleValue: 0), bolusEntryViewModel.enteredBolus)
}
func testUpdatePredictedGlucoseValues() throws {
let mockLoopState = MockLoopState()
mockLoopState.predictGlucoseValueResult = [PredictedGlucoseValue(startDate: Self.exampleStartDate, quantity: Self.exampleCGMGlucoseQuantity)]
try triggerLoopStateUpdated(with: mockLoopState)
waitOnMain()
XCTAssertEqual(mockLoopState.predictGlucoseValueResult,
bolusEntryViewModel.predictedGlucoseValues.map {
PredictedGlucoseValue(startDate: $0.startDate, quantity: $0.quantity)
})
}
func testUpdatePredictedGlucoseValuesWithManual() throws {
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
let mockLoopState = MockLoopState()
mockLoopState.predictGlucoseValueResult = [PredictedGlucoseValue(startDate: Self.exampleStartDate, quantity: Self.exampleCGMGlucoseQuantity)]
try triggerLoopStateUpdated(with: mockLoopState)
waitOnMain()
XCTAssertEqual(mockLoopState.predictGlucoseValueResult,
bolusEntryViewModel.predictedGlucoseValues.map {
PredictedGlucoseValue(startDate: $0.startDate, quantity: $0.quantity)
})
}
func testUpdateSettings() throws {
XCTAssertNil(bolusEntryViewModel.preMealOverride)
XCTAssertNil(bolusEntryViewModel.scheduleOverride)
XCTAssertNil(bolusEntryViewModel.targetGlucoseSchedule)
XCTAssertEqual(.milligramsPerDeciliter, bolusEntryViewModel.glucoseUnit)
let newGlucoseTargetRangeSchedule = GlucoseRangeSchedule(unit: .millimolesPerLiter, dailyItems: [
RepeatingScheduleValue(startTime: TimeInterval(0), value: DoubleRange(minValue: 100, maxValue: 110)),
RepeatingScheduleValue(startTime: TimeInterval(28800), value: DoubleRange(minValue: 90, maxValue: 100)),
RepeatingScheduleValue(startTime: TimeInterval(75600), value: DoubleRange(minValue: 100, maxValue: 110))
], timeZone: .utcTimeZone)!
var newSettings = LoopSettings(dosingEnabled: true,
glucoseTargetRangeSchedule: newGlucoseTargetRangeSchedule,
maximumBasalRatePerHour: 1.0,
maximumBolus: 10.0,
suspendThreshold: GlucoseThreshold(unit: .milligramsPerDeciliter, value: 100.0))
let settings = TemporaryScheduleOverrideSettings(unit: .millimolesPerLiter, targetRange: nil, insulinNeedsScaleFactor: nil)
newSettings.preMealOverride = TemporaryScheduleOverride(context: .preMeal, settings: settings, startDate: Self.exampleStartDate, duration: .indefinite, enactTrigger: .local, syncIdentifier: UUID())
newSettings.scheduleOverride = TemporaryScheduleOverride(context: .custom, settings: settings, startDate: Self.exampleStartDate, duration: .indefinite, enactTrigger: .local, syncIdentifier: UUID())
delegate.settings = newSettings
try triggerLoopStateUpdatedWithDataAndWait()
waitOnMain()
XCTAssertEqual(newSettings.preMealOverride, bolusEntryViewModel.preMealOverride)
XCTAssertEqual(newSettings.scheduleOverride, bolusEntryViewModel.scheduleOverride)
XCTAssertEqual(newGlucoseTargetRangeSchedule, bolusEntryViewModel.targetGlucoseSchedule)
XCTAssertEqual(.milligramsPerDeciliter, bolusEntryViewModel.glucoseUnit)
}
func testUpdateSettingsWithCarbs() throws {
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: mockPotentialCarbEntry)
XCTAssertNil(bolusEntryViewModel.preMealOverride)
XCTAssertNil(bolusEntryViewModel.scheduleOverride)
XCTAssertNil(bolusEntryViewModel.targetGlucoseSchedule)
XCTAssertEqual(.milligramsPerDeciliter, bolusEntryViewModel.glucoseUnit)
let newGlucoseTargetRangeSchedule = GlucoseRangeSchedule(unit: .millimolesPerLiter, dailyItems: [
RepeatingScheduleValue(startTime: TimeInterval(0), value: DoubleRange(minValue: 100, maxValue: 110)),
RepeatingScheduleValue(startTime: TimeInterval(28800), value: DoubleRange(minValue: 90, maxValue: 100)),
RepeatingScheduleValue(startTime: TimeInterval(75600), value: DoubleRange(minValue: 100, maxValue: 110))
], timeZone: .utcTimeZone)!
var newSettings = LoopSettings(dosingEnabled: true,
glucoseTargetRangeSchedule: newGlucoseTargetRangeSchedule,
maximumBasalRatePerHour: 1.0,
maximumBolus: 10.0,
suspendThreshold: GlucoseThreshold(unit: .milligramsPerDeciliter, value: 100.0))
newSettings.preMealOverride = Self.examplePreMealOverride
newSettings.scheduleOverride = Self.exampleCustomScheduleOverride
delegate.settings = newSettings
try triggerLoopStateUpdatedWithDataAndWait()
waitOnMain()
// Pre-meal override should be ignored if we have carbs (LOOP-1964), and cleared in settings
XCTAssertEqual(newSettings.scheduleOverride, bolusEntryViewModel.scheduleOverride)
XCTAssertEqual(newGlucoseTargetRangeSchedule, bolusEntryViewModel.targetGlucoseSchedule)
XCTAssertEqual(.milligramsPerDeciliter, bolusEntryViewModel.glucoseUnit)
// ... but restored if we cancel without bolusing
bolusEntryViewModel = nil
}
func testManualGlucoseChangesPredictedGlucoseValues() throws {
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
let mockLoopState = MockLoopState()
mockLoopState.predictGlucoseValueResult = [PredictedGlucoseValue(startDate: Self.exampleStartDate, quantity: Self.exampleCGMGlucoseQuantity)]
waitOnMain()
try triggerLoopStateUpdatedWithDataAndWait(with: mockLoopState)
waitOnMain()
XCTAssertEqual(mockLoopState.predictGlucoseValueResult,
bolusEntryViewModel.predictedGlucoseValues.map {
PredictedGlucoseValue(startDate: $0.startDate, quantity: $0.quantity)
})
}
func testUpdateInsulinOnBoard() throws {
delegate.insulinOnBoardResult = .success(InsulinValue(startDate: Self.exampleStartDate, value: 1.5))
XCTAssertNil(bolusEntryViewModel.activeInsulin)
try triggerLoopStateUpdatedWithDataAndWait()
XCTAssertEqual(HKQuantity(unit: .internationalUnit(), doubleValue: 1.5), bolusEntryViewModel.activeInsulin)
}
func testUpdateCarbsOnBoard() throws {
delegate.carbsOnBoardResult = .success(CarbValue(startDate: Self.exampleStartDate, endDate: Self.exampleEndDate, quantity: Self.exampleCarbQuantity))
XCTAssertNil(bolusEntryViewModel.activeCarbs)
try triggerLoopStateUpdatedWithDataAndWait()
XCTAssertEqual(Self.exampleCarbQuantity, bolusEntryViewModel.activeCarbs)
}
func testUpdateCarbsOnBoardFailure() throws {
delegate.carbsOnBoardResult = .failure(CarbStore.CarbStoreError.notConfigured)
try triggerLoopStateUpdatedWithDataAndWait()
XCTAssertNil(bolusEntryViewModel.activeCarbs)
}
func testUpdateRecommendedBolusNoNotice() throws {
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: mockPotentialCarbEntry)
let mockState = MockLoopState()
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
mockState.bolusRecommendationResult = ManualBolusRecommendation(amount: 1.234, pendingInsulin: 4.321)
try triggerLoopStateUpdatedWithDataAndWait(with: mockState)
XCTAssertTrue(bolusEntryViewModel.isBolusRecommended)
let recommendedBolus = bolusEntryViewModel.recommendedBolus
XCTAssertNotNil(recommendedBolus)
XCTAssertEqual(mockState.bolusRecommendationResult?.amount, recommendedBolus?.doubleValue(for: .internationalUnit()))
let consideringPotentialCarbEntryPassed = try XCTUnwrap(mockState.consideringPotentialCarbEntryPassed)
XCTAssertEqual(mockPotentialCarbEntry, consideringPotentialCarbEntryPassed)
let replacingCarbEntryPassed = try XCTUnwrap(mockState.replacingCarbEntryPassed)
XCTAssertEqual(mockOriginalCarbEntry, replacingCarbEntryPassed)
XCTAssertNil(bolusEntryViewModel.activeNotice)
}
func testUpdateRecommendedBolusWithNotice() throws {
let mockState = MockLoopState()
delegate.settings.suspendThreshold = GlucoseThreshold(unit: .milligramsPerDeciliter, value: Self.exampleCGMGlucoseQuantity.doubleValue(for: .milligramsPerDeciliter))
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
mockState.bolusRecommendationResult = ManualBolusRecommendation(amount: 1.234, pendingInsulin: 4.321, notice: BolusRecommendationNotice.glucoseBelowSuspendThreshold(minGlucose: Self.exampleGlucoseValue))
try triggerLoopStateUpdatedWithDataAndWait(with: mockState)
XCTAssertTrue(bolusEntryViewModel.isBolusRecommended)
let recommendedBolus = bolusEntryViewModel.recommendedBolus
XCTAssertNotNil(recommendedBolus)
XCTAssertEqual(mockState.bolusRecommendationResult?.amount, recommendedBolus?.doubleValue(for: .internationalUnit()))
XCTAssertEqual(BolusEntryViewModel.Notice.predictedGlucoseBelowSuspendThreshold(suspendThreshold: Self.exampleCGMGlucoseQuantity), bolusEntryViewModel.activeNotice)
}
func testUpdateRecommendedBolusWithNoticeMissingSuspendThreshold() throws {
let mockState = MockLoopState()
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
mockState.bolusRecommendationResult = ManualBolusRecommendation(amount: 1.234, pendingInsulin: 4.321, notice: BolusRecommendationNotice.glucoseBelowSuspendThreshold(minGlucose: Self.exampleGlucoseValue))
try triggerLoopStateUpdatedWithDataAndWait(with: mockState)
XCTAssertTrue(bolusEntryViewModel.isBolusRecommended)
let recommendedBolus = bolusEntryViewModel.recommendedBolus
XCTAssertNotNil(recommendedBolus)
XCTAssertEqual(mockState.bolusRecommendationResult?.amount, recommendedBolus?.doubleValue(for: .internationalUnit()))
XCTAssertNil(bolusEntryViewModel.activeNotice)
}
func testUpdateRecommendedBolusWithOtherNotice() throws {
let mockState = MockLoopState()
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
mockState.bolusRecommendationResult = ManualBolusRecommendation(amount: 1.234, pendingInsulin: 4.321, notice: BolusRecommendationNotice.currentGlucoseBelowTarget(glucose: Self.exampleGlucoseValue))
try triggerLoopStateUpdatedWithDataAndWait(with: mockState)
XCTAssertTrue(bolusEntryViewModel.isBolusRecommended)
let recommendedBolus = bolusEntryViewModel.recommendedBolus
XCTAssertNotNil(recommendedBolus)
XCTAssertEqual(mockState.bolusRecommendationResult?.amount, recommendedBolus?.doubleValue(for: .internationalUnit()))
XCTAssertNil(bolusEntryViewModel.activeNotice)
}
func testUpdateRecommendedBolusThrowsMissingDataError() throws {
let mockState = MockLoopState()
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
mockState.bolusRecommendationError = LoopError.missingDataError(.glucose)
try triggerLoopStateUpdatedWithDataAndWait(with: mockState)
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
let recommendedBolus = bolusEntryViewModel.recommendedBolus
XCTAssertNil(recommendedBolus)
XCTAssertEqual(.staleGlucoseData, bolusEntryViewModel.activeNotice)
}
func testUpdateRecommendedBolusThrowsPumpDataTooOld() throws {
let mockState = MockLoopState()
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
mockState.bolusRecommendationError = LoopError.pumpDataTooOld(date: now)
try triggerLoopStateUpdatedWithDataAndWait(with: mockState)
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
let recommendedBolus = bolusEntryViewModel.recommendedBolus
XCTAssertNil(recommendedBolus)
XCTAssertEqual(.stalePumpData, bolusEntryViewModel.activeNotice)
}
func testUpdateRecommendedBolusThrowsOtherError() throws {
let mockState = MockLoopState()
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
mockState.bolusRecommendationError = LoopError.invalidData(details: "")
try triggerLoopStateUpdatedWithDataAndWait(with: mockState)
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
let recommendedBolus = bolusEntryViewModel.recommendedBolus
XCTAssertNil(recommendedBolus)
XCTAssertNil(bolusEntryViewModel.activeNotice)
}
func testUpdateRecommendedBolusWithManual() throws {
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: mockPotentialCarbEntry)
let mockState = MockLoopState()
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
XCTAssertFalse(bolusEntryViewModel.isBolusRecommended)
mockState.bolusRecommendationResult = ManualBolusRecommendation(amount: 1.234, pendingInsulin: 4.321)
try triggerLoopStateUpdatedWithDataAndWait(with: mockState)
XCTAssertTrue(bolusEntryViewModel.isBolusRecommended)
let recommendedBolus = bolusEntryViewModel.recommendedBolus
XCTAssertNotNil(recommendedBolus)
XCTAssertEqual(mockState.bolusRecommendationResult?.amount, recommendedBolus?.doubleValue(for: .internationalUnit()))
let consideringPotentialCarbEntryPassed = try XCTUnwrap(mockState.consideringPotentialCarbEntryPassed)
XCTAssertEqual(mockPotentialCarbEntry, consideringPotentialCarbEntryPassed)
let replacingCarbEntryPassed = try XCTUnwrap(mockState.replacingCarbEntryPassed)
XCTAssertEqual(mockOriginalCarbEntry, replacingCarbEntryPassed)
XCTAssertNil(bolusEntryViewModel.activeNotice)
}
func testUpdateDoesNotRefreshPumpIfDataIsFresh() throws {
XCTAssertFalse(bolusEntryViewModel.isRefreshingPump)
try triggerLoopStateUpdatedWithDataAndWait()
XCTAssertFalse(bolusEntryViewModel.isRefreshingPump)
XCTAssertNil(delegate.ensureCurrentPumpDataCompletion)
}
func testUpdateIsRefreshingPump() throws {
delegate.mostRecentPumpDataDate = Date.distantPast
XCTAssertFalse(bolusEntryViewModel.isRefreshingPump)
try triggerLoopStateUpdatedWithDataAndWait()
XCTAssertTrue(bolusEntryViewModel.isRefreshingPump)
let completion = try XCTUnwrap(delegate.ensureCurrentPumpDataCompletion)
completion()
// Need to once again trigger loop state
try triggerLoopStateResult(with: MockLoopState())
// then wait on main again (sigh)
waitOnMain()
XCTAssertFalse(bolusEntryViewModel.isRefreshingPump)
}
func testRecommendedBolusSetsEnteredBolus() throws {
XCTAssertNil(bolusEntryViewModel.recommendedBolus)
bolusEntryViewModel.enteredBolus = Self.exampleBolusQuantity
let mockState = MockLoopState()
mockState.bolusRecommendationResult = ManualBolusRecommendation(amount: 1.234, pendingInsulin: 4.321)
try triggerLoopStateUpdatedWithDataAndWait(with: mockState)
// Now, through the magic of `observeRecommendedBolusChanges` and the recommendedBolus publisher it should update to 1.234. But we have to wait twice on main to make this reliable...
waitOnMain()
waitOnMain()
XCTAssertEqual(HKQuantity(unit: .internationalUnit(), doubleValue: 1.234), bolusEntryViewModel.enteredBolus)
}
// MARK: save data and bolus delivery
func testDeliverBolusOnly() throws {
bolusEntryViewModel.enteredBolus = Self.exampleBolusQuantity
var success = false
bolusEntryViewModel.saveAndDeliver {
success = true
}
// Pretend authentication succeeded
let authenticateOverrideCompletion = try XCTUnwrap(self.authenticateOverrideCompletion)
authenticateOverrideCompletion(.success(()))
XCTAssertEqual(1.0, delegate.enactedBolusUnits)
XCTAssertEqual(false, delegate.enactedBolusAutomatic)
XCTAssertTrue(success)
XCTAssertTrue(delegate.glucoseSamplesAdded.isEmpty)
XCTAssertTrue(delegate.carbEntriesAdded.isEmpty)
XCTAssertEqual(1, delegate.bolusDosingDecisionsAdded.count)
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.0, BolusDosingDecision(requestedBolus: 1.0))
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.1, now)
}
struct MockError: Error {}
func testDeliverBolusAuthFail() throws {
bolusEntryViewModel.enteredBolus = Self.exampleBolusQuantity
var success = false
bolusEntryViewModel.saveAndDeliver {
success = true
}
// Pretend authentication succeeded
let authenticateOverrideCompletion = try XCTUnwrap(self.authenticateOverrideCompletion)
authenticateOverrideCompletion(.failure(MockError()))
XCTAssertNil(delegate.enactedBolusUnits)
XCTAssertNil(delegate.enactedBolusAutomatic)
XCTAssertFalse(success)
XCTAssertTrue(delegate.glucoseSamplesAdded.isEmpty)
XCTAssertTrue(delegate.carbEntriesAdded.isEmpty)
XCTAssertTrue(delegate.bolusDosingDecisionsAdded.isEmpty)
}
private func saveAndDeliver(_ bolus: HKQuantity, file: StaticString = #file, line: UInt = #line) throws {
bolusEntryViewModel.enteredBolus = bolus
bolusEntryViewModel.saveAndDeliver { self.saveAndDeliverSuccess = true }
if bolus != BolusEntryViewModelTests.noBolus {
let authenticateOverrideCompletion = try XCTUnwrap(self.authenticateOverrideCompletion, file: file, line: line)
authenticateOverrideCompletion(.success(()))
}
}
func testSaveManualGlucoseNoBolus() throws {
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
// manualGlucoseSample updates asynchronously on main
waitOnMain()
try saveAndDeliver(BolusEntryViewModelTests.noBolus)
let expectedGlucoseSample = NewGlucoseSample(date: now, quantity: Self.exampleManualGlucoseQuantity, isDisplayOnly: false, wasUserEntered: true, syncIdentifier: mockUUID)
XCTAssertEqual([expectedGlucoseSample], delegate.glucoseSamplesAdded)
delegate.addGlucoseCompletion?(.success([Self.exampleManualStoredGlucoseSample]))
waitOnMain()
XCTAssertTrue(delegate.carbEntriesAdded.isEmpty)
XCTAssertEqual(1, delegate.bolusDosingDecisionsAdded.count)
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.0, BolusDosingDecision(manualGlucose: Self.exampleManualStoredGlucoseSample,
requestedBolus: 0.0))
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.1, now)
XCTAssertNil(delegate.enactedBolusUnits)
XCTAssertNil(delegate.enactedBolusAutomatic)
XCTAssertTrue(saveAndDeliverSuccess)
}
func testSaveCarbGlucoseNoBolus() throws {
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: mockPotentialCarbEntry)
try saveAndDeliver(BolusEntryViewModelTests.noBolus)
delegate.addGlucoseCompletion?(.success([Self.exampleManualStoredGlucoseSample]))
waitOnMain()
let addCarbEntryCompletion = try XCTUnwrap(delegate.addCarbEntryCompletion)
addCarbEntryCompletion(.success(mockFinalCarbEntry))
waitOnMain()
XCTAssertTrue(delegate.glucoseSamplesAdded.isEmpty)
XCTAssertEqual(1, delegate.carbEntriesAdded.count)
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.0, BolusDosingDecision(originalCarbEntry: mockOriginalCarbEntry,
carbEntry: mockFinalCarbEntry,
requestedBolus: 0.0))
XCTAssertEqual(mockOriginalCarbEntry, delegate.carbEntriesAdded.first?.1)
XCTAssertEqual(1, delegate.bolusDosingDecisionsAdded.count)
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.0, BolusDosingDecision(originalCarbEntry: mockOriginalCarbEntry,
carbEntry: mockFinalCarbEntry,
requestedBolus: 0.0))
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.1, now)
XCTAssertNil(delegate.enactedBolusUnits)
XCTAssertNil(delegate.enactedBolusAutomatic)
XCTAssertTrue(saveAndDeliverSuccess)
}
func testSaveManualGlucoseAndBolus() throws {
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
// manualGlucoseSample updates asynchronously on main
waitOnMain()
try saveAndDeliver(BolusEntryViewModelTests.exampleBolusQuantity)
let expectedGlucoseSample = NewGlucoseSample(date: now, quantity: Self.exampleManualGlucoseQuantity, isDisplayOnly: false, wasUserEntered: true, syncIdentifier: mockUUID)
XCTAssertEqual([expectedGlucoseSample], delegate.glucoseSamplesAdded)
delegate.addGlucoseCompletion?(.success([Self.exampleManualStoredGlucoseSample]))
waitOnMain()
XCTAssertTrue(delegate.carbEntriesAdded.isEmpty)
XCTAssertEqual(1, delegate.bolusDosingDecisionsAdded.count)
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.0, BolusDosingDecision(manualGlucose: Self.exampleManualStoredGlucoseSample,
requestedBolus: 1.0))
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.1, now)
XCTAssertEqual(1.0, delegate.enactedBolusUnits)
XCTAssertEqual(false, delegate.enactedBolusAutomatic)
XCTAssertTrue(saveAndDeliverSuccess)
}
func testSaveCarbAndBolus() throws {
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: mockPotentialCarbEntry)
// manualGlucoseSample updates asynchronously on main
waitOnMain()
try saveAndDeliver(BolusEntryViewModelTests.exampleBolusQuantity)
let addCarbEntryCompletion = try XCTUnwrap(delegate.addCarbEntryCompletion)
addCarbEntryCompletion(.success(mockFinalCarbEntry))
waitOnMain()
XCTAssertTrue(delegate.glucoseSamplesAdded.isEmpty)
XCTAssertEqual(1, delegate.carbEntriesAdded.count)
XCTAssertEqual(mockPotentialCarbEntry, delegate.carbEntriesAdded.first?.0)
XCTAssertEqual(mockOriginalCarbEntry, delegate.carbEntriesAdded.first?.1)
XCTAssertEqual(1, delegate.bolusDosingDecisionsAdded.count)
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.0, BolusDosingDecision(originalCarbEntry: mockOriginalCarbEntry,
carbEntry: mockFinalCarbEntry,
requestedBolus: 1.0))
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.1, now)
XCTAssertEqual(1.0, delegate.enactedBolusUnits)
XCTAssertEqual(false, delegate.enactedBolusAutomatic)
XCTAssertTrue(saveAndDeliverSuccess)
}
func testSaveCarbAndBolusClearsSavedPreMealOverride() throws {
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: mockPotentialCarbEntry)
// set up user specified pre-meal override
let newGlucoseTargetRangeSchedule = GlucoseRangeSchedule(unit: .millimolesPerLiter, dailyItems: [
RepeatingScheduleValue(startTime: TimeInterval(0), value: DoubleRange(minValue: 100, maxValue: 110)),
RepeatingScheduleValue(startTime: TimeInterval(28800), value: DoubleRange(minValue: 90, maxValue: 100)),
RepeatingScheduleValue(startTime: TimeInterval(75600), value: DoubleRange(minValue: 100, maxValue: 110))
], timeZone: .utcTimeZone)!
var newSettings = LoopSettings(dosingEnabled: true,
glucoseTargetRangeSchedule: newGlucoseTargetRangeSchedule,
maximumBasalRatePerHour: 1.0,
maximumBolus: 10.0,
suspendThreshold: GlucoseThreshold(unit: .milligramsPerDeciliter, value: 100.0))
newSettings.preMealOverride = Self.examplePreMealOverride
newSettings.scheduleOverride = Self.exampleCustomScheduleOverride
delegate.settings = newSettings
try triggerLoopStateUpdatedWithDataAndWait()
waitOnMain()
try saveAndDeliver(BolusEntryViewModelTests.exampleBolusQuantity)
let addCarbEntryCompletion = try XCTUnwrap(delegate.addCarbEntryCompletion)
addCarbEntryCompletion(.success(mockFinalCarbEntry))
waitOnMain()
XCTAssertTrue(saveAndDeliverSuccess)
// ... make sure the "restoring" of the saved pre-meal override does not happen
bolusEntryViewModel = nil
}
func testSaveManualGlucoseAndCarbAndBolus() throws {
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: mockPotentialCarbEntry)
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
// manualGlucoseSample updates asynchronously on main
waitOnMain()
try saveAndDeliver(BolusEntryViewModelTests.exampleBolusQuantity)
let expectedGlucoseSample = NewGlucoseSample(date: now, quantity: Self.exampleManualGlucoseQuantity, isDisplayOnly: false, wasUserEntered: true, syncIdentifier: mockUUID)
XCTAssertEqual([expectedGlucoseSample], delegate.glucoseSamplesAdded)
delegate.addGlucoseCompletion?(.success([Self.exampleManualStoredGlucoseSample]))
waitOnMain()
let addCarbEntryCompletion = try XCTUnwrap(delegate.addCarbEntryCompletion)
addCarbEntryCompletion(.success(mockFinalCarbEntry))
waitOnMain()
XCTAssertEqual(1, delegate.carbEntriesAdded.count)
XCTAssertEqual(mockPotentialCarbEntry, delegate.carbEntriesAdded.first?.0)
XCTAssertEqual(mockOriginalCarbEntry, delegate.carbEntriesAdded.first?.1)
XCTAssertEqual(1, delegate.bolusDosingDecisionsAdded.count)
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.0, BolusDosingDecision(manualGlucose: Self.exampleManualStoredGlucoseSample,
originalCarbEntry: mockOriginalCarbEntry,
carbEntry: mockFinalCarbEntry,
requestedBolus: 1.0))
XCTAssertEqual(delegate.bolusDosingDecisionsAdded.first?.1, now)
XCTAssertEqual(1.0, delegate.enactedBolusUnits)
XCTAssertEqual(false, delegate.enactedBolusAutomatic)
XCTAssertTrue(saveAndDeliverSuccess)
}
// MARK: Display strings
func testEnteredBolusAmountString() throws {
XCTAssertEqual("0", bolusEntryViewModel.enteredBolusAmountString)
}
func testMaximumBolusAmountString() throws {
XCTAssertEqual("10", bolusEntryViewModel.maximumBolusAmountString)
}
func testCarbEntryAmountAndEmojiStringNil() throws {
XCTAssertNil(bolusEntryViewModel.carbEntryAmountAndEmojiString)
}
func testCarbEntryAmountAndEmojiString() throws {
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: mockPotentialCarbEntry)
XCTAssertEqual("234 g foodType", bolusEntryViewModel.carbEntryAmountAndEmojiString)
}
func testCarbEntryAmountAndEmojiStringNoFoodType() throws {
let potentialCarbEntry = NewCarbEntry(quantity: BolusEntryViewModelTests.exampleCarbQuantity, startDate: Self.exampleStartDate, foodType: nil, absorptionTime: 1)
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: potentialCarbEntry)
XCTAssertEqual("234 g", bolusEntryViewModel.carbEntryAmountAndEmojiString)
}
func testCarbEntryAmountAndEmojiStringWithEmoji() throws {
let potentialCarbEntry = NewCarbEntry(quantity: BolusEntryViewModelTests.exampleCarbQuantity, startDate: Self.exampleStartDate, foodType: nil, absorptionTime: 1)
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: potentialCarbEntry, selectedCarbAbsorptionTimeEmoji: "😀")
XCTAssertEqual("234 g 😀", bolusEntryViewModel.carbEntryAmountAndEmojiString)
}
func testCarbEntryDateAndAbsorptionTimeStringNil() throws {
XCTAssertNil(bolusEntryViewModel.carbEntryDateAndAbsorptionTimeString)
}
func testCarbEntryDateAndAbsorptionTimeString() throws {
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: mockPotentialCarbEntry)
XCTAssertEqual("12:00 PM + 0m", bolusEntryViewModel.carbEntryDateAndAbsorptionTimeString)
}
func testCarbEntryDateAndAbsorptionTimeString2() throws {
let potentialCarbEntry = NewCarbEntry(quantity: BolusEntryViewModelTests.exampleCarbQuantity, startDate: Self.exampleStartDate, foodType: nil, absorptionTime: nil)
setUpViewModel(originalCarbEntry: mockOriginalCarbEntry, potentialCarbEntry: potentialCarbEntry)
XCTAssertEqual("12:00 PM", bolusEntryViewModel.carbEntryDateAndAbsorptionTimeString)
}
func testIsManualGlucosePromptVisible() throws {
XCTAssertFalse(bolusEntryViewModel.isManualGlucosePromptVisible)
bolusEntryViewModel.activeNotice = .staleGlucoseData
bolusEntryViewModel.isManualGlucoseEntryEnabled = true
XCTAssertFalse(bolusEntryViewModel.isManualGlucosePromptVisible)
bolusEntryViewModel.activeNotice = .staleGlucoseData
bolusEntryViewModel.isManualGlucoseEntryEnabled = false
XCTAssertTrue(bolusEntryViewModel.isManualGlucosePromptVisible)
}
func testIsNoticeVisible() throws {
XCTAssertFalse(bolusEntryViewModel.isNoticeVisible)
bolusEntryViewModel.activeNotice = .stalePumpData
XCTAssertTrue(bolusEntryViewModel.isNoticeVisible)
bolusEntryViewModel.activeNotice = .staleGlucoseData
bolusEntryViewModel.isManualGlucoseEntryEnabled = false
XCTAssertTrue(bolusEntryViewModel.isNoticeVisible)
bolusEntryViewModel.isManualGlucoseEntryEnabled = true
XCTAssertFalse(bolusEntryViewModel.isNoticeVisible)
}
// MARK: action button tests
func testPrimaryButtonDefault() {
XCTAssertEqual(.actionButton, bolusEntryViewModel.primaryButton)
}
func testPrimaryButtonBolusEntry() {
bolusEntryViewModel.enteredBolus = Self.exampleBolusQuantity
XCTAssertEqual(.actionButton, bolusEntryViewModel.primaryButton)
}
func testPrimaryButtonManual() {
bolusEntryViewModel.activeNotice = .staleGlucoseData
bolusEntryViewModel.isManualGlucoseEntryEnabled = false
XCTAssertEqual(.manualGlucoseEntry, bolusEntryViewModel.primaryButton)
}
func testPrimaryButtonManualPrompt() {
bolusEntryViewModel.isManualGlucoseEntryEnabled = true
XCTAssertEqual(.actionButton, bolusEntryViewModel.primaryButton)
}
func testActionButtonDefault() {
XCTAssertEqual(.enterBolus, bolusEntryViewModel.actionButtonAction)
}
func testActionButtonManualGlucose() {
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
XCTAssertEqual(.saveWithoutBolusing, bolusEntryViewModel.actionButtonAction)
}
func testActionButtonPotentialCarbEntry() {
setUpViewModel(potentialCarbEntry: mockPotentialCarbEntry)
XCTAssertEqual(.saveWithoutBolusing, bolusEntryViewModel.actionButtonAction)
}
func testActionButtonManualGlucoseAndPotentialCarbEntry() {
setUpViewModel(potentialCarbEntry: mockPotentialCarbEntry)
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
XCTAssertEqual(.saveWithoutBolusing, bolusEntryViewModel.actionButtonAction)
}
func testActionButtonDeliverOnly() {
bolusEntryViewModel.enteredBolus = Self.exampleBolusQuantity
XCTAssertEqual(.deliver, bolusEntryViewModel.actionButtonAction)
}
func testActionButtonSaveAndDeliverManualGlucose() {
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
bolusEntryViewModel.enteredBolus = Self.exampleBolusQuantity
XCTAssertEqual(.saveAndDeliver, bolusEntryViewModel.actionButtonAction)
}
func testActionButtonSaveAndDeliverPotentialCarbEntry() {
setUpViewModel(potentialCarbEntry: mockPotentialCarbEntry)
bolusEntryViewModel.enteredBolus = Self.exampleBolusQuantity
XCTAssertEqual(.saveAndDeliver, bolusEntryViewModel.actionButtonAction)
}
func testActionButtonSaveAndDeliverBothManualGlucoseAndPotentialCarbEntry() {
setUpViewModel(potentialCarbEntry: mockPotentialCarbEntry)
bolusEntryViewModel.enteredManualGlucose = Self.exampleManualGlucoseQuantity
bolusEntryViewModel.enteredBolus = Self.exampleBolusQuantity
XCTAssertEqual(.saveAndDeliver, bolusEntryViewModel.actionButtonAction)
}
}
// MARK: utilities
extension BolusEntryViewModelTests {
func triggerLoopStateUpdatedWithDataAndWait(with state: LoopState = MockLoopState(), function: String = #function) throws {
delegate.getGlucoseSamplesResponse = [StoredGlucoseSample(sample: Self.exampleCGMGlucoseSample)]
try triggerLoopStateUpdated(with: state)
waitOnMain()
}
func triggerLoopStateUpdated(with state: LoopState, function: String = #function) throws {
NotificationCenter.default.post(name: .LoopDataUpdated, object: nil)
try triggerLoopStateResult(with: state, function: function)
}
func triggerLoopStateResult(with state: LoopState, function: String = #function) throws {
let exp = expectation(description: function)
let block = try XCTUnwrap(delegate.loopStateCallBlock)
queue.async {
block(state)
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
}
}
fileprivate class MockLoopState: LoopState {
var carbsOnBoard: CarbValue?
var error: Error?
var insulinCounteractionEffects: [GlucoseEffectVelocity] = []
var predictedGlucose: [PredictedGlucoseValue]?
var predictedGlucoseIncludingPendingInsulin: [PredictedGlucoseValue]?
var recommendedAutomaticDose: (recommendation: AutomaticDoseRecommendation, date: Date)?
var recommendedBolus: (recommendation: ManualBolusRecommendation, date: Date)?
var retrospectiveGlucoseDiscrepancies: [GlucoseChange]?
var totalRetrospectiveCorrection: HKQuantity?
var predictGlucoseValueResult: [PredictedGlucoseValue] = []
func predictGlucose(using inputs: PredictionInputEffect, potentialBolus: DoseEntry?, potentialCarbEntry: NewCarbEntry?, replacingCarbEntry replacedCarbEntry: StoredCarbEntry?, includingPendingInsulin: Bool) throws -> [PredictedGlucoseValue] {
return predictGlucoseValueResult
}
func predictGlucoseFromManualGlucose(_ glucose: NewGlucoseSample, potentialBolus: DoseEntry?, potentialCarbEntry: NewCarbEntry?, replacingCarbEntry replacedCarbEntry: StoredCarbEntry?, includingPendingInsulin: Bool) throws -> [PredictedGlucoseValue] {
return predictGlucoseValueResult
}
var bolusRecommendationResult: ManualBolusRecommendation?
var bolusRecommendationError: Error?
var consideringPotentialCarbEntryPassed: NewCarbEntry??
var replacingCarbEntryPassed: StoredCarbEntry??
func recommendBolus(consideringPotentialCarbEntry potentialCarbEntry: NewCarbEntry?, replacingCarbEntry replacedCarbEntry: StoredCarbEntry?) throws -> ManualBolusRecommendation? {
consideringPotentialCarbEntryPassed = potentialCarbEntry
replacingCarbEntryPassed = replacedCarbEntry
if let error = bolusRecommendationError { throw error }
return bolusRecommendationResult
}
func recommendBolusForManualGlucose(_ glucose: NewGlucoseSample, consideringPotentialCarbEntry potentialCarbEntry: NewCarbEntry?, replacingCarbEntry replacedCarbEntry: StoredCarbEntry?) throws -> ManualBolusRecommendation? {
consideringPotentialCarbEntryPassed = potentialCarbEntry
replacingCarbEntryPassed = replacedCarbEntry
if let error = bolusRecommendationError { throw error }
return bolusRecommendationResult
}
}
fileprivate class MockBolusEntryViewModelDelegate: BolusEntryViewModelDelegate {
func insulinActivityDuration(for type: InsulinType?) -> TimeInterval {
return .hours(6) + .minutes(10)
}
var pumpInsulinType: InsulinType?
var loggedBolusUnits: Double?
var loggedDate: Date?
var loggedDoseModel: InsulinType?
func logOutsideInsulinDose(startDate: Date, units: Double, insulinType: InsulinType?) {
loggedBolusUnits = units
loggedDate = startDate
loggedDoseModel = insulinType
}
var loopStateCallBlock: ((LoopState) -> Void)?
func withLoopState(do block: @escaping (LoopState) -> Void) {
loopStateCallBlock = block
}
var glucoseSamplesAdded = [NewGlucoseSample]()
var addGlucoseCompletion: ((Swift.Result<[StoredGlucoseSample], Error>) -> Void)?
func addGlucoseSamples(_ samples: [NewGlucoseSample], completion: ((Swift.Result<[StoredGlucoseSample], Error>) -> Void)?) {
glucoseSamplesAdded.append(contentsOf: samples)
addGlucoseCompletion = completion
}
var carbEntriesAdded = [(NewCarbEntry, StoredCarbEntry?)]()
var addCarbEntryCompletion: ((Result<StoredCarbEntry>) -> Void)?
func addCarbEntry(_ carbEntry: NewCarbEntry, replacing replacingEntry: StoredCarbEntry?, completion: @escaping (Result<StoredCarbEntry>) -> Void) {
carbEntriesAdded.append((carbEntry, replacingEntry))
addCarbEntryCompletion = completion
}
var bolusDosingDecisionsAdded = [(BolusDosingDecision, Date)]()
func storeBolusDosingDecision(_ bolusDosingDecision: BolusDosingDecision, withDate date: Date) {
bolusDosingDecisionsAdded.append((bolusDosingDecision, date))
}
var enactedBolusUnits: Double?
var enactedBolusAutomatic: Bool?
func enactBolus(units: Double, automatic: Bool, completion: @escaping (Error?) -> Void) {
enactedBolusUnits = units
enactedBolusAutomatic = automatic
}
var getGlucoseSamplesResponse: [StoredGlucoseSample] = []
func getGlucoseSamples(start: Date?, end: Date?, completion: @escaping (Swift.Result<[StoredGlucoseSample], Error>) -> Void) {
completion(.success(getGlucoseSamplesResponse))
}
var insulinOnBoardResult: DoseStoreResult<InsulinValue>?
func insulinOnBoard(at date: Date, completion: @escaping (DoseStoreResult<InsulinValue>) -> Void) {
if let insulinOnBoardResult = insulinOnBoardResult {
completion(insulinOnBoardResult)
}
}
var carbsOnBoardResult: CarbStoreResult<CarbValue>?
func carbsOnBoard(at date: Date, effectVelocities: [GlucoseEffectVelocity]?, completion: @escaping (CarbStoreResult<CarbValue>) -> Void) {
if let carbsOnBoardResult = carbsOnBoardResult {
completion(carbsOnBoardResult)
}
}
var ensureCurrentPumpDataCompletion: (() -> Void)?
func ensureCurrentPumpData(completion: @escaping () -> Void) {
ensureCurrentPumpDataCompletion = completion
}
var mostRecentGlucoseDataDate: Date?
var mostRecentPumpDataDate: Date?
var isPumpConfigured: Bool = true
var preferredGlucoseUnit: HKUnit = .milligramsPerDeciliter
var insulinModel: InsulinModel? = MockInsulinModel()
var settings: LoopSettings = LoopSettings()
}
fileprivate struct MockInsulinModel: InsulinModel {
func percentEffectRemaining(at time: TimeInterval) -> Double { 0 }
var effectDuration: TimeInterval = 0
var delay: TimeInterval = 0
var debugDescription: String = ""
}
fileprivate struct MockGlucoseValue: GlucoseValue {
var quantity: HKQuantity
var startDate: Date
}
fileprivate extension TimeInterval {
static func milliseconds(_ milliseconds: Double) -> TimeInterval {
return milliseconds / 1000
}
}
extension BolusDosingDecision: Equatable {
init(manualGlucose: GlucoseValue? = nil, originalCarbEntry: StoredCarbEntry? = nil, carbEntry: StoredCarbEntry? = nil, requestedBolus: Double? = nil) {
self.init()
self.manualGlucose = manualGlucose
self.originalCarbEntry = originalCarbEntry
self.carbEntry = carbEntry
self.requestedBolus = requestedBolus
}
public static func ==(lhs: BolusDosingDecision, rhs: BolusDosingDecision) -> Bool {
return lhs.insulinOnBoard == rhs.insulinOnBoard &&
lhs.carbsOnBoard == rhs.carbsOnBoard &&
lhs.scheduleOverride == rhs.scheduleOverride &&
lhs.glucoseTargetRangeSchedule == rhs.glucoseTargetRangeSchedule &&
lhs.effectiveGlucoseTargetRangeSchedule == rhs.effectiveGlucoseTargetRangeSchedule &&
lhs.predictedGlucoseIncludingPendingInsulin == rhs.predictedGlucoseIncludingPendingInsulin &&
lhs.manualGlucose?.startDate == rhs.manualGlucose?.startDate &&
lhs.manualGlucose?.endDate == rhs.manualGlucose?.endDate &&
lhs.manualGlucose?.quantity == rhs.manualGlucose?.quantity &&
lhs.originalCarbEntry == rhs.originalCarbEntry &&
lhs.carbEntry == rhs.carbEntry &&
lhs.recommendedBolus == rhs.recommendedBolus &&
lhs.requestedBolus == rhs.requestedBolus
}
}
|
0 | //
// BottomButtonsView.swift
// xApiIos
//
// Created by Douglas Adams on 7/28/20.
// Copyright © 2020 Douglas Adams. All rights reserved.
//
import SwiftUI
import xClient
struct BottomButtonsView: View {
@ObservedObject var tester: Tester
@ObservedObject var radioManager: RadioManager
@Environment(\.openURL) var openURL
var body: some View {
VStack(alignment: .leading) {
HStack {
Stepper("Font Size", value: $tester.fontSize, in: 8...24).frame(width: 175)
Spacer()
HStack {
Toggle("Clear on Connect", isOn: $tester.clearAtConnect).frame(width: 190)
Toggle("Clear on Disconnect", isOn: $tester.clearAtDisconnect).frame(width: 215)
}
Spacer()
Button("Clear Now", action: {tester.clearObjectsAndMessages()})
}
}
}
}
struct BottomButtonsView_Previews: PreviewProvider {
static var previews: some View {
BottomButtonsView(tester: Tester(), radioManager: RadioManager(delegate: Tester() as RadioManagerDelegate))
.previewDevice("iPad (8th generation)")
.previewLayout(.fixed(width: 2160 / 2.0, height: 1620 / 2.0))
}
}
|
0 | //
// ViewControllerExtension.swift
// MovieSearch
//
// Created by Kirill G on 7/22/18.
// Copyright © 2018 ns-ios. All rights reserved.
//
import Foundation
import UIKit
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedMovie = movies[indexPath.row]
ref.child(Constants.folderName).childByAutoId().setValue(["movie-title":selectedMovie]) // Save selected movie into firebase
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "movieCell")
cell?.textLabel?.text = movies[indexPath.row]
return cell!
}
}
|
0 | //
// JSONDescribing.swift
// VergeCore
//
// Created by muukii on 2020/02/19.
// Copyright © 2020 muukii. All rights reserved.
//
import Foundation
public protocol JSONDescribing {
func jsonDescriptor() -> [String : Any]?
}
|
0 | import Foundation
internal extension OperationQueue {
@discardableResult func addOperationAndWaitUntilFinished<T>(_ block: @escaping () -> T) -> T {
var output: T!
let operation = BlockOperation(block: {
output = block()
})
addOperations([operation], waitUntilFinished: true)
return output
}
}
|
0 | //
// SectionedPhoneBookCVC.swift
// iOS_Example
//
// Created by Seyed Samad Gholamzadeh on 9/8/18.
// Copyright © 2018 Seyed Samad Gholamzadeh. All rights reserved.
//
import UIKit
import ModelAssistant
private let reuseIdentifier = "Cell"
class SectionedPhoneBookCVC: SortablePhoneBookCVC {
override init() {
super.init()
(self.collectionViewLayout as! UICollectionViewFlowLayout).headerReferenceSize.height = 40
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
#if swift(>=4.2)
let supplementaryKind = UICollectionView.elementKindSectionHeader
#else
let supplementaryKind = UICollectionElementKindSectionHeader
#endif
self.collectionView?.register(UINib(nibName: "CollectionReusableView", bundle: nil), forSupplementaryViewOfKind: supplementaryKind, withReuseIdentifier: "header")
super.viewDidLoad()
self.title = "Sectioned Phone Book"
}
override func configureModelAssistant(sectionKey: String?) {
super.configureModelAssistant(sectionKey: "firstName")
self.assistant.sortSections = { $0.name < $1.name }
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! CollectionReusableView
let section = self.assistant[indexPath.section]
headerView.titleLabel.text = section?.name
return headerView
}
override func sortBarButtonAction(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(title: nil, message: "Sort by", preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "Section A-Z", style: .default, handler: { (action) in
self.assistant.sortSections(by: { $0.name < $1.name }, completion: nil)
}))
alertController.addAction(UIAlertAction(title: "Section Z-A", style: .default, handler: { (action) in
self.assistant.sortSections(by: { $0.name > $1.name }, completion: nil)
}))
alertController.addAction(UIAlertAction(title: "First Name A-Z", style: .default, handler: { (action) in
self.assistant.sortEntities = { $0.firstName < $1.firstName }
self.assistant.reorderEntities(completion: nil)
}))
alertController.addAction(UIAlertAction(title: "First Name Z-A", style: .default, handler: { (action) in
self.assistant.sortEntities = { $0.firstName > $1.firstName }
self.assistant.reorderEntities(completion: nil)
}))
alertController.addAction(UIAlertAction(title: "Last Name A-Z", style: .default, handler: { (action) in
self.assistant.sortEntities = { $0.lastName < $1.lastName }
self.assistant.reorderEntities(completion: nil)
}))
alertController.addAction(UIAlertAction(title: "Last Name Z-A", style: .default, handler: { (action) in
self.assistant.sortEntities = { $0.lastName > $1.lastName }
self.assistant.reorderEntities(completion: nil)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) in
//...
}))
self.present(alertController, animated: true, completion: nil)
}
}
|
0 | //
// UserDefaultsRegistrationBuilder.swift
// CodeMonkeyApple
//
// Created by Kyle Hughes on 3/29/22.
//
import Foundation
public struct UserDefaultsRegistrationBuilder {
private var registrations: [String: Any]
// MARK: Public Initialization
public init() {
registrations = [:]
}
// MARK: Public Instance Interface
public func adding<Value>(_ key: StorageKey<Value>) -> UserDefaultsRegistrationBuilder {
var copy = self
copy.registrations[key.id] = key.defaultValue.encodeForStorage()
return copy
}
public func adding<Value>(_ key: StorageKey<Value?>) -> UserDefaultsRegistrationBuilder {
var copy = self
if let encodedValue = key.defaultValue.encodeForStorage() {
copy.registrations[key.id] = encodedValue
}
return copy
}
public func adding<Value>(_ key: DebugStorageKey<Value>) -> UserDefaultsRegistrationBuilder {
#if DEBUG
var copy = self
copy.registrations[key.id] = key.defaultValue.encodeForStorage()
return copy
#else
self
#endif
}
public func adding<Value>(_ key: DebugStorageKey<Value?>) -> UserDefaultsRegistrationBuilder {
#if DEBUG
var copy = self
if let encodedValue = key.defaultValue.encodeForStorage() {
copy.registrations[key.id] = encodedValue
}
return copy
#else
self
#endif
}
public func build() -> [String: Any] {
registrations
}
}
// MARK: - Extension for UserDefaults
extension UserDefaults {
// MARK: Public Instance Interface
@inlinable
public func register(builder: (UserDefaultsRegistrationBuilder) -> UserDefaultsRegistrationBuilder) {
register(defaults: builder(.init()).build())
}
}
|
0 | struct Sivukartta {
var text = "Hello, World!"
}
|
0 | //
// Scout
// Copyright (c) 2020-present Alexis Bridoux
// MIT license, see LICENSE file for details
import Scout
import Parsing
extension PathAndValue {
enum ValueParsers {}
}
extension PathAndValue.ValueParsers {
static let forbiddenCharacters: [Character] = ["[", "]", ",", ":", "{", "}"]
static var keyName: Parser<ValueType> {
Parsers.string(forbiddenCharacters: "#").enclosed(by: "#").map(ValueType.keyName)
}
static var real: Parser<ValueType> {
Parsers.string(forbiddenCharacters: "~").enclosed(by: "~").map(ValueType.real)
}
static var string: Parser<ValueType> {
Parsers.string(forbiddenCharacters: "/").enclosed(by: "/").map(ValueType.string)
<|>
Parsers.string(forbiddenCharacters: "'").enclosed(by: "'").map(ValueType.string)
}
static var automatic: Parser<ValueType> {
Parsers.string(forbiddenCharacters: forbiddenCharacters)
.map(ValueType.automatic)
}
static var dictionaryKey: Parser<String> {
Parsers.string(stoppingAt: "'", forbiddenCharacters: ["'"])
.enclosed(by: "'").surrounded(by: .whiteSpacesOrNewLines)
<|>
Parsers.string(stoppingAt: ":", forbiddenCharacters: forbiddenCharacters)
.trimming(in: .whitespacesAndNewlines)
}
static var dictionaryElement: Parser<(key: String, value: ValueType)> {
curry { key, _, value in (key, value) }
<^> dictionaryKey
<*> .character(":")
<*> .lazy(parser.surrounded(by: .whiteSpacesOrNewLines))
}
static var emptyDictionary: Parser<ValueType> {
Parsers.string("{}").map { _ in ValueType.dictionary([:]) }
}
static var dictionary: Parser<ValueType> {
(dictionaryElement <* Parsers.character(",").optional)
.many1
.parenthesisedCurl
.map { elements -> ValueType in
if let duplicate = elements.map(\.key).duplicate() {
let dictDescription = elements.map { "\($0.key): \($0.value.description)" }.joined(separator: ", ")
let description = "Duplicate key '\(duplicate)' in the dictionary {\(dictDescription)}"
return .error(description)
}
let dict = Dictionary(uniqueKeysWithValues: elements)
return .dictionary(dict)
}
}
static var arrayElement: Parser<ValueType> {
.lazy(parser.surrounded(by: .whiteSpacesOrNewLines))
}
static var emptyArray: Parser<ValueType> {
Parsers.string("[]").map { _ in ValueType.array([]) }
}
static var array: Parser<ValueType> {
(arrayElement <* Parsers.character(",").optional)
.many1
.parenthesisedSquare
.map(ValueType.array)
}
static var error: Parser<ValueType> {
Parser<ValueType> { input in
guard !input.isEmpty else { return nil }
let description = "Parsing error in value '\(input)'"
return (ValueType.error(description), "")
}
}
static var parser: Parser<ValueType> {
keyName
<|> real
<|> string
<|> automatic
<|> emptyArray
<|> emptyDictionary
<|> array
<|> dictionary
}
}
extension PathAndValue.ValueParsers {
static var zshAutomatic: Parser<ValueType> {
Parsers.string(forbiddenCharacters: [" ", "]", "}"]).map(ValueType.automatic)
}
static var zshArrayElement: Parser<ValueType> {
real
<|> string
<|> zshAutomatic
}
static var zshArray: Parser<ValueType> {
(zshArrayElement <* Parsers.character(" ").optional)
.many1
.parenthesisedSquare
.map(ValueType.array)
}
static var zshAssociativeArray: Parser<ValueType> {
(zshArrayElement <* Parsers.character(" ").optional)
.many1
.parenthesisedCurl
.map { elements -> ValueType in
guard elements.count.isMultiple(of: 2) else {
return .error("Invalid associative array with non even count")
}
var dict: [String: ValueType] = [:]
for index in stride(from: 0, to: elements.count - 1, by: 2) {
guard let key = elements[index].string else {
return .error("String \(elements[index]) is not a valid key")
}
let value = elements[index + 1]
dict[key] = value
}
return .dictionary(dict)
}
}
static var zshGroup: Parser<ValueType> {
zshArray <|> zshAssociativeArray
}
}
infix operator <^>: SequencePrecedence
extension PathAndValue {
static var parser: Parser<(pathElements: [PathElement], value: ValueType)> {
curry { path, _, value in (path, value) }
<^> Path.parser(separator: ".", keyForbiddenCharacters: ["="])
<*> .character("=")
<*> (ValueParsers.parser <|> ValueParsers.zshGroup <|> ValueParsers.error)
}
}
extension ValueType: CustomStringConvertible {
public var description: String {
switch self {
case .automatic(let string): return string
case .keyName(let keyName): return "#\(keyName)#"
case .real(let string): return "~\(string)~"
case .string(let string): return "'\(string)'"
case .dictionary(let dict):
let keysAndValues = dict.map { "\($0.key): \($0.value.description)" }.joined(separator: ", ")
return "[\(keysAndValues)]"
case .array(let array):
let values = array.map { $0.description }.joined(separator: ", ")
return "[\(values)]"
case .error(let description): return "Error: \(description)"
}
}
}
|
0 | //
// CurrencyPairsAddPairHeaderView.swift
// CurrenVerter
//
// Created by Tabriz Dzhavadov on 14/04/2019.
// Copyright © 2019 Tabriz Dzhavadov. All rights reserved.
//
import UIKit
typealias CPAddPairHeaderBlock = () -> Void
class CurrencyPairsAddPairHeaderView: UIView {
var block: CPAddPairHeaderBlock?
class func fromNib(onClick closure: @escaping CPAddPairHeaderBlock) -> CurrencyPairsAddPairHeaderView? {
let view = Bundle.main.loadNibNamed(CurrencyPairsAddPairHeaderView.identifier,
owner: self,
options: nil)?.first as? CurrencyPairsAddPairHeaderView
view?.block = closure
return view
}
override func awakeFromNib() {
super.awakeFromNib()
let recognizer = UITapGestureRecognizer(target: self, action: #selector(onClick))
self.addGestureRecognizer(recognizer)
}
@objc func onClick() {
guard let block = self.block else { return }
block()
}
}
|
0 | // RUN: %target-swift-frontend -swift-version 4 -parse-stdlib -Xllvm -sil-disable-pass=FunctionSignatureOpts -Xllvm -sil-disable-pass=GenericSpecializer -emit-ir -O %s | %FileCheck %s
//
// Check that the -O pipeline always preserves the runtime calls for Builtin access markers and that the KeyPath implementation is fully inlined.
@_silgen_name("marker1")
func marker1() -> ()
@_silgen_name("marker2")
func marker2() -> ()
@_silgen_name("marker3")
func marker3() -> ()
// IR-LABEL: define {{.*}}swiftcc void @"$S20preserve_exclusivity11beginAccessyyBp_BpxmtlF"(i8*, i8*, %swift.type*{{.*}}, %swift.type*{{.*}} %T1)
// IR: call void @swift_beginAccess
// IR-NEXT: ret void
public func beginAccess<T1>(_ address: Builtin.RawPointer, _ scratch: Builtin.RawPointer, _ ty1: T1.Type) {
marker1()
Builtin.beginUnpairedModifyAccess(address, scratch, ty1);
}
// CHECK-LABEL: define {{.*}}swiftcc void @"$S20preserve_exclusivity9endAccessyyBpF"(i8*{{.*}})
// CHECK: call void @swift_endAccess
// CHECK-NEXT: ret void
public func endAccess(_ address: Builtin.RawPointer) {
marker2()
Builtin.endUnpairedAccess(address)
}
// CHECK-LABEL: define {{.*}}swiftcc void @"$S20preserve_exclusivity10readAccessyyBp_xmtlF"(i8*, %swift.type*{{.*}}, %swift.type*{{.*}} %T1)
// CHECK: call void @swift_beginAccess
// CHECK: ret void
public func readAccess<T1>(_ address: Builtin.RawPointer, _ ty1: T1.Type) {
marker3()
Builtin.performInstantaneousReadAccess(address, ty1);
}
// Make sure testAccess properly inlines in our functions.
//
// CHECK-LABEL: define {{.*}}swiftcc void @"$S20preserve_exclusivity10testAccessyyBpF"(i8*)
// CHECK: call swiftcc void @marker1
// CHECK: call void @swift_beginAccess
// CHECK: call swiftcc void @marker2
// CHECK: call void @swift_endAccess
// CHECK: call swiftcc void @marker3
// CHECK: call void @swift_beginAccess
// CHECK: ret void
public func testAccess(_ k1: Builtin.RawPointer) {
beginAccess(k1, k1, Builtin.RawPointer.self)
endAccess(k1)
readAccess(k1, Builtin.RawPointer.self)
}
|
0 | //
// TextFieldExample.swift
// SwiftUI-Text
//
// Created by pgq on 2020/3/18.
// Copyright © 2020 pq. All rights reserved.
//
import SwiftUI
struct TextFieldExample: View {
@State var text: String
var body: some View {
VStack {
Text("\(text)")
.foregroundColor(.gray)
.background(Color.red)
TextField("account", text: $text)
/**
DefaultTextFieldStyle 啥都没有
PlainTextFieldStyle 这个和上面的一样
RoundedBorderTextFieldStyle 圆角边框
SquareBorderTextFieldStyle 不可以用在iOS上面
*/
.textFieldStyle(RoundedBorderTextFieldStyle())
// 添加阴影
.shadow(color: .gray, radius: 10)
.accessibility(hint: Text("事实上"))
Spacer()
}.padding()
.navigationBarTitle(Text("输入框"))
.navigationViewStyle(DoubleColumnNavigationViewStyle())
}
}
struct TextFieldExample_Previews: PreviewProvider {
static var previews: some View {
TextFieldExample(text: "")
}
}
|
0 | //
// ApplicationCoordinator.swift
// WordGame
//
// Created by Harshal Wani on 26/12/19.
// Copyright © 2019 Harshal Wani. All rights reserved.
//
import UIKit
final class ApplicationCoordinator: Coordinator {
private let window: UIWindow
private let rootViewController: UINavigationController
private var dashboardCoordinator: DashboardCoordinator?
init(window: UIWindow) {
self.window = window
rootViewController = UINavigationController()
rootViewController.navigationBar.barStyle = .black
dashboardCoordinator = DashboardCoordinator(presenter: rootViewController)
}
func start() {
window.rootViewController = rootViewController
dashboardCoordinator?.start()
window.makeKeyAndVisible()
}
}
|
0 | //
// SegueNavigationRow.swift
// Provenance
//
// Created by Joseph Mattiello on 12/25/18.
// Copyright © 2018 Provenance Emu. All rights reserved.
//
import Foundation
final class SegueNavigationRow: NavigationRow<SystemSettingsCell> {
weak var viewController: UIViewController?
required init(text: String,
detailText: DetailText = .none,
icon: Icon? = nil,
viewController: UIViewController,
segue: String,
customization: ((UITableViewCell, Row & RowStyle) -> Void)? = nil) {
self.viewController = viewController
#if os(tvOS)
super.init(text: text, detailText: detailText, icon: icon, customization: customization) { [weak viewController] _ in
guard let viewController = viewController else { return }
viewController.performSegue(withIdentifier: segue, sender: nil)
}
#else
super.init(text: text, detailText: detailText, icon: icon, customization: customization, action: { [weak viewController] _ in
guard let viewController = viewController else { return }
viewController.performSegue(withIdentifier: segue, sender: nil)
})
#endif
}
}
|
0 | //
// DefaultSearchMediaUseCaseTests.swift
// WhatToWatchTests
//
// Created by Denis Novitsky on 22.04.2021.
//
import XCTest
@testable import WhatToWatch
final class DefaultSearchMediaUseCaseTests: XCTestCase {
// MARK: - Prepare
private var sut: DefaultSearchMediaUseCase!
private var mediaRepository: MockMediaRepository!
override func setUp() {
super.setUp()
mediaRepository = MockMediaRepository()
sut = DefaultSearchMediaUseCase(mediaRepository: mediaRepository)
}
override func tearDown() {
sut = nil
mediaRepository = nil
super.tearDown()
}
// MARK: - Tests
func testSearchMediaSuccessShouldReturnMediaPage() {
let expectation = self.expectation(description: "Should return media page")
let media: Media = .movie(.init(id: 1,
title: "Bar",
overview: "Baz",
releaseDate: nil,
rating: nil,
posterPath: nil,
backdropPath: nil,
runtime: nil,
credit: nil,
genres: nil,
productionCountries: nil))
let expectedMediaPage = MediaPage(page: 2, totalPages: 3, media: [media])
mediaRepository.result = .success(expectedMediaPage)
_ = sut.searchMedia(type: .movie, query: "Foo", page: 4) { result in
do {
let mediaPage = try result.get()
XCTAssertEqual(mediaPage, expectedMediaPage)
expectation.fulfill()
} catch {
XCTFail("Failed to search media")
}
}
wait(for: [expectation], timeout: 0.1)
XCTAssertEqual(mediaRepository.receivedQuery, "Foo")
XCTAssertEqual(mediaRepository.receivedPage, 4)
}
func testSearchMediaFailureShouldThrowError() {
let expectation = self.expectation(description: "Should throw error")
mediaRepository.result = .failure(MockError.error)
_ = sut.searchMedia(type: .movie, query: "Foo", page: 1) { result in
do {
_ = try result.get()
XCTFail("Should not happen")
} catch {
if case MockError.error = error {
expectation.fulfill()
} else {
XCTFail("Wrong error")
}
}
}
wait(for: [expectation], timeout: 0.1)
}
}
// MARK: - Mock Error
private enum MockError: Error {
case error
}
// MARK: - Mock Media Repository
private final class MockMediaRepository: MediaRepository {
var result: Result<MediaPage, Error>!
private(set) var receivedQuery: String?
private(set) var receivedPage: Int?
func fetchTrends(type: MediaType,
timeWindow: TimeWindow,
page: Int,
completion: @escaping CompletionHandler<MediaPage>) -> Cancellable? {
return nil
}
func fetchMediaList(type: MediaType,
query: String,
page: Int,
completion: @escaping CompletionHandler<MediaPage>) -> Cancellable? {
receivedQuery = query
receivedPage = page
completion(result)
return nil
}
func fetchMedia(type: MediaType,
id: Int,
completion: @escaping CompletionHandler<Media>) -> Cancellable? {
return nil
}
}
|
0 | //
// FileLoggerManager.swift
//
//
// Created by Martin Troup on 24.09.2021.
//
import Foundation
import Zip
/// LogFileManager manages all necessary operations for FileLogger.
class FileLoggerManager {
/// The class is used as a Singleton, thus should be accesed via instance property !!!
static let shared = FileLoggerManager()
let logDirUrl: URL? = {
do {
let fileManager = FileManager.default
let documentDirUrl = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let logDirUrl = documentDirUrl.appendingPathComponent("logs")
if !fileManager.fileExists(atPath: logDirUrl.path) {
try fileManager.createDirectory(at: logDirUrl, withIntermediateDirectories: true, attributes: nil)
}
print("File log directory: \(logDirUrl).")
return logDirUrl
} catch let error {
assertionFailure("Failed to create log directory within init() with error: \(error).")
return nil
}
}()
var logFilesRecords: [LogFileRecord] {
guard let logDirUrl = logDirUrl else {
return []
}
return (0..<numOfLogFiles).reduce(into: [LogFileRecord]()) { result, index in
let logFileNumber = (currentLogFileNumber + index) % numOfLogFiles
let logFileUrl = logDirUrl.appendingPathComponent("\(logFileNumber)").appendingPathExtension("log")
guard let logFileRecords = gettingRecordsFromLogFile(at: logFileUrl) else {
return
}
result.append(contentsOf: logFileRecords)
}
}
private(set) var currentLogFileNumber: Int = 0 {
didSet {
// Check if currentLogFileNumber got updated, if not - do nothing, thus keep the currentWritableFileHandle opened
if oldValue == currentLogFileNumber {
if currentWritableFileHandle == nil {
assignNewFileHandle()
}
}
UserDefaults.standard.set(currentLogFileNumber, forKey: Constants.UserDefaultsKeys.currentLogFileNumber)
// Check if new currentLogFileUrl is available (only a safety check, because its part - logDirUrl is Optional
guard let currentLogFileUrl = currentLogFileUrl else {
assertionFailure("New currentLogFileUrl not available while trying to open appropriate currentWritableFileHandler.")
return
}
// Delete the file that is about to be used (it is overriden in a file cycle)
deleteLogFile(at: currentLogFileUrl)
// Open new fileHandle and assign it to currentWritableFileHandle
assignNewFileHandle()
}
}
var currentLogFileUrl: URL? {
logDirUrl?.appendingPathComponent("\(currentLogFileNumber)").appendingPathExtension("log")
}
private var currentWritableFileHandle: FileHandle? {
willSet {
guard currentWritableFileHandle != newValue else { return }
currentWritableFileHandle?.closeFile()
}
}
private var dateOfLastLog: Date = Date() {
didSet {
UserDefaults.standard.set(dateOfLastLog, forKey: Constants.UserDefaultsKeys.dateOfLastLog)
}
}
var numOfLogFiles: Int = 4 {
willSet(newNumOfLogFiles) {
if newNumOfLogFiles == 0 {
assertionFailure("There must be at least 1 log file so FileLogger can be used.")
}
if numOfLogFiles > newNumOfLogFiles {
deleteAllLogFiles()
}
}
didSet {
UserDefaults.standard.set(numOfLogFiles, forKey: Constants.UserDefaultsKeys.numOfLogFiles)
}
}
// private func createArchiveURL(fileName: String) -> Archive? {
// guard let logDirUrl = logDirUrl else {
// print("\(#function) - logDirUrl is nil.")
// return nil
// }
// let archiveUrl = logDirUrl.appendingPathComponent(fileName)
//
// do {
// let fileManager = FileManager.default
// try fileManager.removeItem(atPath: archiveUrl.path)
// } catch {}
//
// guard Archive(url: archiveUrl, accessMode: .create) != nil else {
// print("\(#function) - failed to create the archive.")
// return nil
// }
//
// guard let archive = Archive(url: archiveUrl, accessMode: .update) else {
// print("\(#function) - failed to open the archive for update.")
// return nil
// }
// return archive
// }
// Zip file size (in bytes)
var archivedLogFilesSize: Int? {
do {
let resources = try archivedLogFilesUrl?.resourceValues(forKeys: [.fileSizeKey])
let fileSize = resources?.fileSize
return fileSize
} catch {
return nil
}
}
// // Url of the zip file containing all log files.
// var archivedLogFilesUrl: URL? {
// archivedLogFiles
// }
// Zip file containing log files
var archivedLogFilesUrl: URL? {
// Open newly created archive for update
// guard let archive = createArchive(fileName: "log_files_archive.zip") else {
// print("\(#function) - failed to open the archive for update.")
// return nil
// }
// Get all log files to the archive
guard let allLogFiles = gettingAllLogFiles(), !allLogFiles.isEmpty else {
print("\(#function) - no log files.")
return nil
}
// // Add all log files to the archive
// do {
// try allLogFiles.forEach { logFileUrl in
// var logFileUrlVar = logFileUrl
// logFileUrlVar.deleteLastPathComponent()
// try archive.addEntry(with: logFileUrl.lastPathComponent, relativeTo: logFileUrlVar, compressionMethod: .deflate)
// }
// } catch let error {
// print("\(#function) - failed to add a log file to the archive with error \(error).")
// return nil
// }
// return archive
do {
return try Zip.quickZipFiles(allLogFiles, fileName: "log_files_archive.zip")
} catch let error {
print("\(#function) - failed to zip log files with error: \(error).")
return nil
}
}
private init() {
if let dateOfLastLog = UserDefaults.standard.object(forKey: Constants.UserDefaultsKeys.dateOfLastLog) as? Date {
self.dateOfLastLog = dateOfLastLog
} else {
UserDefaults.standard.set(dateOfLastLog, forKey: Constants.UserDefaultsKeys.dateOfLastLog)
}
if let currentLogFileNumber = UserDefaults.standard.object(forKey: Constants.UserDefaultsKeys.currentLogFileNumber) as? Int {
self.currentLogFileNumber = currentLogFileNumber
} else {
UserDefaults.standard.set(currentLogFileNumber, forKey: Constants.UserDefaultsKeys.currentLogFileNumber)
}
if let numOfLogFiles = UserDefaults.standard.object(forKey: Constants.UserDefaultsKeys.numOfLogFiles) as? Int {
self.numOfLogFiles = numOfLogFiles
} else {
UserDefaults.standard.set(numOfLogFiles, forKey: Constants.UserDefaultsKeys.numOfLogFiles)
}
}
/// Method to reset properties that control the correct flow of storing log files.
/// - "currentLogFileNumber" represents the current logging file number
/// - "dateTimeOfLastLog" represents the last date the logger was used
/// - "numOfLogFiles" represents the number of files that are used for logging, can be set by a user
func resetPropertiesToDefaultValues() {
currentWritableFileHandle = nil
currentLogFileNumber = 0
dateOfLastLog = Date()
numOfLogFiles = 4
}
/// Method to remove all log files from dedicated log folder. These files are detected by its ".log" suffix.
func deleteAllLogFiles() {
guard let aLogFiles = gettingAllLogFiles() else { return }
aLogFiles.forEach { aLogFileUrl in
deleteLogFile(at: aLogFileUrl)
}
resetPropertiesToDefaultValues()
}
/// Method to delete a specific log file from dedicated log folder.
///
/// - Parameter fileUrlToDelete: fileName of the log file to be removed
func deleteLogFile(at fileUrlToDelete: URL) {
if !FileManager.default.fileExists(atPath: fileUrlToDelete.path) {
return
}
do {
try FileManager.default.removeItem(at: fileUrlToDelete)
} catch {
assertionFailure("Failed to remove log file with error: \(error)")
}
}
/// Method to create a specific log file from dedicated log folder.
///
/// - Parameter fileUrlToAdd: fileName of the log file to be added
private func createLogFile(at fileUrlToAdd: URL) {
if FileManager.default.fileExists(atPath: fileUrlToAdd.path) {
return
}
if !FileManager.default.createFile(atPath: fileUrlToAdd.path, contents: nil) {
assertionFailure("Creating new log file failed.")
}
}
/// Method to open a new file descriptor and assign it to currentWritableFileHandle
///
/// - Parameter fileUrl: fileName of the log file to open file descriptor on
private func assignNewFileHandle() {
guard let currentLogFileUrl = currentLogFileUrl else {
assertionFailure("Unavailable currentLogFileUrl while trying to assign new currentWritableFileHandle.")
return
}
// Create the file that is about to be used and open its FileHandle (assign it to current WritableFileHandle) if not exists yet.
createLogFile(at: currentLogFileUrl)
// Open new file descriptor (FileHandle)
do {
currentWritableFileHandle = try FileHandle(forWritingTo: currentLogFileUrl)
} catch let error {
assertionFailure("Failed to get FileHandle instance (writable file descriptor) for currentLogFileUrl with error: \(error).")
}
}
/// Method to get all log file names from dedicated log folder. These files are detected by its ".log" suffix.
///
/// - Returns: Array of log file names
func gettingAllLogFiles() -> [URL]? {
guard let logDirUrl = logDirUrl else { return nil }
do {
let directoryContent = try FileManager.default.contentsOfDirectory(at: logDirUrl, includingPropertiesForKeys: nil, options: [])
let logFiles = directoryContent.filter({ file -> Bool in
file.pathExtension == "log"
})
return logFiles
} catch let error {
assertionFailure("Failed to get log directory content with error: \(error).")
}
return nil
}
/// Method to write a log message into the current log file.
///
/// - Parameters:
/// - message: String logging message
/// - withMessageHeader: Log message unified header
/// - onLevel: Level of the logging message
func writeToLogFile(message: String, withMessageHeader messageHeader: String, onLevel level: Level) {
guard logDirUrl != nil, currentLogFileUrl != nil else {
assertionFailure("logDirUrl or currentLogFileUrl not available while trying to write a message (log) in it.")
return
}
refreshCurrentLogFileStatus()
let contentToAppend = "\(Constants.FileLogger.logFileRecordSeparator) \(messageHeader) \(message)\n"
currentWritableFileHandle?.seekToEndOfFile()
if let contentToAppend = contentToAppend.data(using: .utf8) {
currentWritableFileHandle?.write(contentToAppend)
}
}
/// Method to refresh/set "currentLogFileNumber" and "dateTimeOfLastLog" properties. It is called at the beginning
/// of writeToLogFile(_, _) method.
private func refreshCurrentLogFileStatus() {
let currentDate = Date()
if currentDate.toFullDateString() != dateOfLastLog.toFullDateString() {
currentLogFileNumber = (currentLogFileNumber + 1) % numOfLogFiles
dateOfLastLog = currentDate
}
if currentWritableFileHandle == nil {
assignNewFileHandle()
}
}
/// Method to get String content of a specific log file from dedicated log folder.
///
/// - Parameter fileUrlToRead: fileName of the log file to be read from
/// - Returns: content of the log file
func readingContentFromLogFile(at fileUrlToRead: URL) -> String? {
if !FileManager.default.fileExists(atPath: fileUrlToRead.path) {
return nil
}
do {
return try String(contentsOf: fileUrlToRead, encoding: .utf8)
} catch let error {
assertionFailure("Failed to read \(fileUrlToRead.path) with error: \(error).")
}
return nil
}
/// Method that parses a log file content into an array of LogFileRecord instances
///
/// - Parameter fileUrlToRead: fileName of a log file to parse
/// - Returns: array of LogFileRecord instances
func gettingRecordsFromLogFile(at fileUrlToRead: URL) -> [LogFileRecord]? {
let logFileContent = readingContentFromLogFile(at: fileUrlToRead)
guard let logFileContent = logFileContent else { return nil }
var arrayOflogFileRecords = logFileContent.components(separatedBy: Constants.FileLogger.logFileRecordSeparator)
arrayOflogFileRecords.remove(at: 0)
let logFileRecords = arrayOflogFileRecords.map { logFileRecordInString -> LogFileRecord in
let headerTrimmed = logFileRecordInString
.prefix(while: { $0 != "]" })
.dropFirst()
let header = headerTrimmed.string + "]"
let body = logFileRecordInString
.suffix(from: headerTrimmed.endIndex)
.dropFirst(2)
.string
return LogFileRecord(header: header, body: body)
}
return logFileRecords
}
}
// MARK: - Substring + helpers
private extension Substring {
var string: String {
String(self)
}
}
|
0 | //
// SettingRepositoryType.swift
// Lunarrr
//
// Created by hb1love on 2019/11/27.
// Copyright © 2019 podo. All rights reserved.
//
protocol SettingRepositoryType {
var current: Settings? { get }
func updateSync(type: CalendarProviderType, sync: Bool) -> Bool
}
|
0 | //
// NSString+Helper.swift
// SwiftTemplet
//
// Created by Bin Shang on 2018/8/28.
// Copyright © 2018年 BN. All rights reserved.
//
#if os(macOS)
import AppKit
#else
import UIKit
#endif
import Foundation
import CommonCrypto
public extension String{
/// md5字符串
var md5: String {
guard let data = self.data(using: .utf8) else { return ""}
let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return hash.map { String(format: "%02x", $0) }.joined()
}
var base64: String {
let strData = self.data(using: .utf8)
let base64String = strData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return base64String ?? ""
}
var base64Decode: String {
let decodedData = NSData(base64Encoded: self, options: NSData.Base64DecodingOptions.init(rawValue: 0))
let decodedString = NSString(data: decodedData! as Data, encoding: String.Encoding.utf8.rawValue)
return (decodedString ?? "") as String
}
var sha1: String {
guard let data = self.data(using: .utf8) else { return ""}
var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
CC_SHA1([UInt8](data), CC_LONG(data.count), &digest)
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return hexBytes.joined()
}
var sha256: String{
guard let data = self.data(using: .utf8) else { return ""}
return String.hexString(from: String.digest(data: data as NSData))
}
static func digest(data: NSData) -> NSData {
let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
var hash = [UInt8](repeating: 0, count: digestLength)
CC_SHA256(data.bytes, UInt32(data.length), &hash)
return NSData(bytes: hash, length: digestLength)
}
static func hexString(from data: NSData) -> String {
var bytes = [UInt8](repeating: 0, count: data.length)
data.getBytes(&bytes, length: data.length)
var hexString = ""
for byte in bytes {
hexString += String(format:"%02x", UInt8(byte))
}
return hexString
}
/// md5字符串
var RMB: String {
if (self.count <= 0) {
return "-"
}
if self.cgFloatValue == 0.0 {
return "¥0.00元"
}
return "¥\(self.cgFloatValue * 0.01)元"
}
///以千为单位的描述
var thousandDes: String {
if self.isEmpty {
return "0"
}
if self.intValue <= 1000 {
return self
}
let result = String(format: "%.2fk", Float(self.intValue)/1000)
return result
}
/// Int
var intValue: Int {
return Int((self as NSString).integerValue)
}
/// Float
var floatValue: Float {
return (self as NSString).floatValue
}
/// CGFloat
var cgFloatValue: CGFloat {
return CGFloat(self.floatValue)
}
/// Double
var doubleValue: Double {
return (self as NSString).doubleValue
}
var boolValue: Bool? {
let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
switch selfLowercased {
case "true", "yes", "1":
return true
case "false", "no", "0":
return false
default:
return nil
}
}
/// d字符串翻转
var reverse: String {
return String(self.reversed())
}
/// ->Data
var jsonData: Data? {
guard let data = self.data(using: .utf8) else { return nil }
return data
}
/// 字符串->数组/字典
var objValue: Any? {
guard let data = self.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data, options: [])
else { return nil }
return json
}
///移除两端空白
var trimmed: String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
var urlDecoded: String {
return removingPercentEncoding ?? self
}
var urlEncoded: String {
// return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
return addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
}
var isValidUrl: Bool {
return URL(string: self) != nil
}
var isValidHttpUrl: Bool {
guard let url = URL(string: self) else { return false }
return url.scheme == "http" || url.scheme == "https"
}
var isValidFileUrl: Bool {
return URL(string: self)?.isFileURL ?? false
}
///以1开头的11位数字
var isValidPhone: Bool{
let pattern = "^1[0-9]{10}$"
let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)
return predicate.evaluate(with: self)
}
///验证邮箱
var isValidEmail: Bool {
if self.count == 0 {
return false
}
let regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluate(with: self)
}
var isIPAddress: Bool {
let regex: String = "^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"
let pre: NSPredicate = NSPredicate(format: "SELF MATCHES %@", regex)
let rc: Bool = pre.evaluate(with: self)
if rc {
let componds: [String] = components(separatedBy: ",")
var v: Bool = true
for s in componds {
if s.intValue > 255 {
v = false
break
}
}
return v
}
return false
}
var isImageSuffix: Bool {
var result = false;
for e in ["BMP", "JPG", "JPEG", "PNG", "GIF"] {
result = self.hasSuffix(".\(e)") || self.hasSuffix(".\(e.lowercased())")
if result == true {
break
}
}
return result
}
///****-**-** 00:00:00
var dayBegin: String{
return (self as NSString).dayBegin
}
///****-**-** 23:59:59
var dayEnd: String{
return (self as NSString).dayEnd
}
func hasPrefixs(_ prefixs: [String]) -> Bool{
var result = false;
for e in prefixs {
result = self.hasPrefix("\(e)") || self.hasPrefix("\(e.lowercased())")
if result == true {
break
}
}
return result
}
func hasSuffixs(_ suffixs: [String]) -> Bool{
var result = false;
for e in suffixs {
result = self.hasSuffix("\(e)") || self.hasSuffix("\(e.lowercased())")
if result == true {
break
}
}
return result
}
/// (填充字符到最大长度)padding [value] to [width]
func padLeft(_ width: Int, _ padding: String = " ") -> String {
if width <= self.count {
return self
}
return String(repeating: padding, count: width - count) + self
}
/// (填充字符到最大长度)padding [value] to [width]
func padRight(_ width: Int, _ padding: String = " ") -> String {
if width <= self.count {
return self
}
return self + String(repeating: padding, count: width - count)
}
/// 字符串开始到第index
func substringTo(_ index: Int) -> String {
guard index < self.count else {
assertionFailure("index beyound the length of the string")
return ""
}
let theIndex = self.index(self.startIndex, offsetBy: index)
return String(self[startIndex...theIndex])
}
/// 从第index个开始到结尾的字符
func substringFrom(_ index: Int) -> String {
guard index < self.count else {
assertionFailure("index beyound the length of the string")
return ""
}
guard index >= 0 else {
assertionFailure("index can't be lower than 0")
return ""
}
let theIndex = self.index(self.endIndex, offsetBy: index - self.count)
return String(self[theIndex..<endIndex])
}
func isValidByRegex(_ regex: String) -> Bool {
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluate(with: self)
}
///移除两端对应的字符
func trimmedBy(_ string: String) -> String {
return trimmingCharacters(in: CharacterSet(charactersIn: string))
}
func replacingOccurrences(of targets: [String], replacement: String) -> String {
var result = self
targets.forEach { (value) in
result = result.replacingOccurrences(of: value, with: replacement)
}
return result
}
/// 计算高度
func size(with width: CGFloat, font: Font = Font.systemFont(ofSize: 17)) -> CGSize {
return (self as NSString).size(with: width, font: font)
}
// MARK: -funtions
func substring(_ location: Int, length: Int) -> String {
let result = (self as NSString).substring(with: NSMakeRange(location, length))
return result
}
/// range转换为NSRange
func nsRange(from range: Range<String.Index>) -> NSRange {
return NSRange(range, in: self)
}
/// NSRange转化为range
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self)
else { return nil }
return from ..< to
}
///获取两个字符串中间的部分(含这两部分)
func substring(_ prefix: String, subfix: String, isContain: Bool = false) -> String {
return (self as NSString).substring(prefix, subfix: subfix, isContain: isContain)
}
//使用正则表达式替换
func pregReplace(pattern: String, with: String, options: NSRegularExpression.Options = []) -> String {
let regex = try! NSRegularExpression(pattern: pattern, options: options)
return regex.stringByReplacingMatches(in: self, options: [],
range: NSMakeRange (0, self.count),
withTemplate: with)
}
/// 通过集合字符的字母分割字符串
func componentsSeparatedByCharacters(_ aString: String) -> [String]{
let result = self.components(separatedBy: CharacterSet(charactersIn: aString))
return result
}
func filterHTML() -> String {
var html = self
let scanner = Scanner(string: html)
var text: NSString?
while scanner.isAtEnd == false {
scanner.scanUpTo("<", into: nil)
scanner.scanUpTo(">", into: &text)
html = html.replacingOccurrences(of: "\(text ?? "")>", with: "")
}
return html
}
/// 大于version
func isBig(_ value: String) -> Bool {
return (self as NSString).isBig(value)
}
/// 小于version
func isSmall(_ value: String) -> Bool {
return (self as NSString).isSmall(value)
}
/// 汉字转为拼音
func transformToPinyin() -> String {
return (self as NSString).transformToPinyin()
}
/// 汉字链接处理
func handleHanzi() -> String {
var charSet = CharacterSet.urlQueryAllowed
charSet.insert(charactersIn: "#")
let encodingURL = self.addingPercentEncoding(withAllowedCharacters: charSet)
return encodingURL ?? ""
}
/// 整形判断
func isPureInteger() -> Bool{
return (self as NSString).isPureInteger()
}
/// 浮点形判断
func isPureFloat() -> Bool{
return (self as NSString).isPureFloat()
}
func replacingOccurrences(_ loc: Int, _ len: Int, with replacement: String) -> String{
if self.count < loc + len {
return self
}
var tmp = (self as NSString).substring(with: NSRange(location: loc, length: len))
tmp = replacingOccurrences(of: tmp, with: replacement)
return tmp
}
func replacingCharacters(_ loc: Int, _ len: Int, with replacement: String) -> String{
if self.count < loc + len {
return self
}
let result = (self as NSString).replacingCharacters(in: NSRange(location: loc, length: len), with: replacement)
return result
}
func substring(from: Int) -> String{
return (self as NSString).substring(from: from)
}
func substring(to: Int) -> String{
if self.count < to {
return self
}
return (self as NSString).substring(to: to)
}
func substring(with range: NSRange) -> String{
return (self as NSString).substring(with: range)
}
func substring(_ loc: Int, _ len: Int) -> String{
if self.count < loc {
return self
}
return (self as NSString).substring(with: NSRange(location: loc, length: len))
}
subscript (i: Int) -> Character {
return self[index(startIndex, offsetBy: i)]
}
subscript (bounds: CountableRange<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[start ..< end]
}
subscript (bounds: CountableClosedRange<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[start ... end]
}
subscript (bounds: CountablePartialRangeFrom<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(endIndex, offsetBy: -1)
return self[start ... end]
}
subscript (bounds: PartialRangeThrough<Int>) -> Substring {
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[startIndex ... end]
}
subscript (bounds: PartialRangeUpTo<Int>) -> Substring {
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[startIndex ..< end]
}
}
public extension Substring {
subscript (i: Int) -> Character {
return self[index(startIndex, offsetBy: i)]
}
subscript (bounds: CountableRange<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[start ..< end]
}
subscript (bounds: CountableClosedRange<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[start ... end]
}
subscript (bounds: CountablePartialRangeFrom<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(endIndex, offsetBy: -1)
return self[start ... end]
}
subscript (bounds: PartialRangeThrough<Int>) -> Substring {
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[startIndex ... end]
}
subscript (bounds: PartialRangeUpTo<Int>) -> Substring {
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[startIndex ..< end]
}
}
public extension String{
static func * (lhs: String, rhs: Int) -> String {
guard rhs > 0 else { return "" }
return String(repeating: lhs, count: rhs)
}
static func *= (lhs: inout String, rhs: Int) -> String {
guard rhs > 0 else { return "" }
return String(repeating: lhs, count: rhs)
}
}
//Range/nsRange 相互转换
// let string = "Hello USA 🇺🇸 !!! Hello World !!!"
// if let nsRange = string.range(of: "Hello World")?.nsRange(in: string) {
// (string as NSString).substring(with: nsRange) // "Hello World"
// }
//
// if let nsRange = string.nsRange(of: "Hello World") {
// (string as NSString).substring(with: nsRange) // "Hello World"
// }
// let nsRanges = string.nsRanges(of: "Hello")
// print(nsRanges) // "[{0, 5}, {19, 5}]\n"
//
public extension RangeExpression where Bound == String.Index {
func nsRange<S: StringProtocol>(in string: S) -> NSRange { .init(self, in: string) }
}
public extension StringProtocol {
func nsRange<S: StringProtocol>(of string: S, options: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil) -> NSRange? {
self.range(of: string,
options: options,
range: range ?? startIndex..<endIndex,
locale: locale ?? .current)?
.nsRange(in: self)
}
func nsRanges<S: StringProtocol>(of string: S, options: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil) -> [NSRange] {
var start = range?.lowerBound ?? startIndex
let end = range?.upperBound ?? endIndex
var ranges: [NSRange] = []
while start < end,
let range = self.range(of: string,
options: options,
range: start..<end,
locale: locale ?? .current) {
ranges.append(range.nsRange(in: self))
start = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return ranges
}
}
@objc public extension NSString{
var isEmpty: Bool {
let tmp = self.trimmingCharacters(in: .whitespacesAndNewlines)
let result = ["", "nil", "null"].contains(tmp.lowercased())
return result
}
var md5: String {
return (self as String).md5
}
var base64: String {
return (self as String).base64
}
var base64Decode: String {
return (self as String).base64Decode
}
var sha1: String{
return (self as String).sha1
}
var sha256: String{
return (self as String).sha256
}
var RMB: String {
return (self as String).RMB
}
var thousandDes: String {
return (self as String).thousandDes
}
///移除两端空白
var trimmed: String {
return (self as String).trimmed
}
var urlDecoded: String {
return (self as String).urlDecoded
}
var urlEncoded: String {
return (self as String).urlEncoded
}
var isValidUrl: Bool {
return (self as String).isValidUrl
}
var isValidHttpUrl: Bool {
return (self as String).isValidHttpUrl
}
var isValidFileUrl: Bool {
return (self as String).isValidFileUrl
}
///以1开头的11位数字
var isValidPhone: Bool{
return (self as String).isValidPhone
}
///验证邮箱
var isValidEmail: Bool {
return (self as String).isValidEmail
}
///验证IP
var isIPAddress: Bool {
return (self as String).isIPAddress
}
///****-**-** 00:00:00
var dayBegin: String{
if length != 19 || !contains(":") {
return self as String
}
let result = self.substring(to: 10).appending(" 00:00:00")
return result
}
///****-**-** 23:59:59
var dayEnd: String{
if length != 19 || !contains(":") {
return self as String
}
let result = self.substring(to: 10).appending(" 23:59:59")
return result
}
var objValue: Any? {
return (self as String).objValue
}
func isValidByRegex(_ regex: String) -> Bool {
return (self as String).isValidByRegex(regex)
}
///移除两端对应的字符
func trimmedBy(_ string: String) -> String {
return (self as String).trimmedBy(string)
}
/// 获取子字符串
func substring(loc: Int, len: Int) -> String {
return self.substring(with: NSRange(location: loc, length: len))
}
/// 通过集合字符的字母分割字符串
func componentsSeparatedByCharacters(_ aString: String) -> [String]{
let result = self.components(separatedBy: CharacterSet(charactersIn: aString))
return result
}
/// 取代索引处字符
func replacingCharacter(_ aString: String, at index: Int) -> String{
assert(self.length > 0)
let result = self.replacingCharacters(in: NSMakeRange(index, 1), with: aString)
return result
}
///获取两个字符串中间的部分(含这两部分)
func substring(_ prefix: String, subfix: String, isContain: Bool = false) -> String {
let beginLocation = self.range(of: prefix).location
let endLocation = self.range(of: subfix, options: .backwards).location
if beginLocation == NSNotFound || endLocation == NSNotFound {
return self as String
}
let beginIdx = isContain == true ? beginLocation : beginLocation + 1
let endIdx = isContain == true ? endLocation - beginLocation + 1 : endLocation - beginLocation
let result = self.substring(with: NSRange(location: beginIdx, length: endIdx))
return result
}
func filterHTML() -> String {
return (self as String).filterHTML()
}
/// 大于version
func isBig(_ value: String) -> Bool {
return compare(value, options: .numeric) == .orderedDescending
}
/// 小于version
func isSmall(_ value: String) -> Bool {
return compare(value, options: .numeric) == .orderedAscending
}
/// 转为拼音
func transformToPinyin() -> String {
let chinese: String = self as String
let mutableStr = NSMutableString(string: chinese) as CFMutableString
let canTransform: Bool = CFStringTransform(mutableStr, nil, kCFStringTransformToLatin, false) &&
CFStringTransform(mutableStr, nil, kCFStringTransformStripCombiningMarks, false)
if canTransform == true {
return mutableStr as String
}
return ""
}
/// 判断是否时间戳字符串
func isTimeStamp() -> Bool{
if [" ", "-", ":"].contains(self) {
return false
}
if isPureInteger() == false || doubleValue < NSDate().timeIntervalSince1970 {
return false
}
return true
}
/// 整形判断
func isPureInteger() -> Bool{
let scan = Scanner(string: self as String)
var val: Int = 0
return (scan.scanInt(&val) && scan.isAtEnd)
}
/// 浮点形判断
func isPureFloat() -> Bool{
let scan = Scanner(string: self as String)
var val: Float = 0.0
return (scan.scanFloat(&val) && scan.isAtEnd)
}
/// (短时间)yyyy-MM-dd
func toDateShort() -> String{
if length <= 10 {
return self as String
}
return self.substring(to: 10)
}
/// 起始时间( 00:00:00时间戳)
func toTimestampShort() -> String{
assert(self.length >= 10)
let tmp = self.substring(to: 10) + " 00:00:00"
let result = DateFormatter.intervalFromDateStr(tmp, fmt: kDateFormatBegin)
return result
}
/// 截止时间( 23:59:59时间戳)
func toTimestampFull() -> String{
assert(self.length >= 10)
let tmp = self.substring(to: 10) + " 23:59:59"
let result = DateFormatter.intervalFromDateStr(tmp, fmt: kDateFormatEnd)
return result
}
///截止到天
func timeToDay() -> String {
if self.contains(" ") == false {
return self as String
}
if let result = self.components(separatedBy: " ").first as String?{
return result
}
return ""
}
/// 过滤特殊字符集
func filter(_ string: String) -> String{
assert(self.length > 0)
let chartSet = NSCharacterSet(charactersIn: string).inverted
let result = addingPercentEncoding(withAllowedCharacters: chartSet)
return result!
}
/// 通过集合字符的字母分割字符串
func componentsSeparatedByCharactersInString(_ aString: String) -> [String]{
let result = (self as NSString).components(separatedBy: CharacterSet(charactersIn: aString))
return result
}
/// 删除首尾空白字符
func deleteWhiteSpaceBeginEnd() -> String{
assert(self.length > 0)
let chartSet = NSCharacterSet.whitespacesAndNewlines
let result = self.trimmingCharacters(in: chartSet)
return result
}
/// 取代索引处字符
func replacingCharacter(_ index: Int) -> String{
assert(self.length > 0)
let result = self.replacingCharacters(in: NSMakeRange(index, 1), with: self as String)
return result
}
func isValidEmailAddress() -> Bool {
let emailID: String = self as String
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: emailID)
}
///计算高度
func size(with width: CGFloat, font: Font = Font.systemFont(ofSize: 17)) -> CGSize {
let attDic = [NSAttributedString.Key.font: font,]
var size = self.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attDic,
context: nil).size
size.width = ceil(size.width)
size.height = ceil(size.height)
return size
}
}
|
0 | // Copyright 2016 LinkedIn Corp.
// 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.
import UIKit
import LayoutKit
open class ProfileCardLayout: StackLayout<UIView> {
public init(name: String, connectionDegree: String, headline: String, timestamp: String, profileImageName: String) {
let labelConfig = { (label: UILabel) in
label.backgroundColor = UIColor.yellow
}
let nameAndConnectionDegree = StackLayout(
axis: .horizontal,
spacing: 4,
sublayouts: [
LabelLayout(text: name, viewReuseId: "name", config: labelConfig),
LabelLayout(text: connectionDegree, viewReuseId: "connectionDegree", config: { label in
label.backgroundColor = UIColor.gray
}),
]
)
let headline = LabelLayout(text: headline, numberOfLines: 2, viewReuseId: "headline", config: labelConfig)
let timestamp = LabelLayout(text: timestamp, numberOfLines: 2, viewReuseId: "timestamp", config: labelConfig)
let verticalLabelStack = StackLayout(
axis: .vertical,
spacing: 2,
alignment: Alignment(vertical: .center, horizontal: .leading),
sublayouts: [nameAndConnectionDegree, headline, timestamp]
)
let profileImage = SizeLayout<UIImageView>(
size: CGSize(width: 50, height: 50),
viewReuseId: "profileImage",
config: { imageView in
imageView.image = UIImage(named: profileImageName)
}
)
super.init(
axis: .horizontal,
spacing: 4,
sublayouts: [
profileImage,
verticalLabelStack
]
)
}
}
|
0 | //
// CustomDataSource.swift
// MyProduct
//
// Created by 王雪慧 on 2020/2/5.
// Copyright © 2020 王雪慧. All rights reserved.
//
import Foundation
import UIKit
/// - Tag: CustomDataSource
class CustomDataSource: NSObject, UICollectionViewDataSource, UICollectionViewDataSourcePrefetching {
// MARK: Properties
struct Model {
var id = UUID()
// Add additional properties for your own model here.
}
/// Example data identifiers.
private let models = (1...1000).map { _ in
return Model()
}
/// An `AsyncFetcher` that is used to asynchronously fetch `DisplayData` objects.
private let asyncFetcher = CollectionAsyncFetcher()
// MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return models.count
}
/// - Tag: CellForItemAt
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewPrefetchCell.reuseIdentifier, for: indexPath) as? CollectionViewPrefetchCell else {
fatalError("Expected `\(CollectionViewPrefetchCell.self)` type for reuseIdentifier \(CollectionViewPrefetchCell.reuseIdentifier). Check the configuration in Main.storyboard.")
}
let model = models[indexPath.row]
let id = model.id
cell.representedId = id
// Check if the `asyncFetcher` has already fetched data for the specified identifier.
if let fetchedData = asyncFetcher.fetchedData(for: id) {
// The data has already been fetched and cached; use it to configure the cell.
cell.configure(with: fetchedData)
} else {
// There is no data available; clear the cell until we've fetched data.
cell.configure(with: nil)
// Ask the `asyncFetcher` to fetch data for the specified identifier.
asyncFetcher.fetchAsync(id) { fetchedData in
DispatchQueue.main.async {
/*
The `asyncFetcher` has fetched data for the identifier. Before
updating the cell, check if it has been recycled by the
collection view to represent other data.
*/
guard cell.representedId == id else { return }
// Configure the cell with the fetched image.
cell.configure(with: fetchedData)
}
}
}
return cell
}
// MARK: UICollectionViewDataSourcePrefetching
/// - Tag: Prefetching
func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
// Begin asynchronously fetching data for the requested index paths.
for indexPath in indexPaths {
let model = models[indexPath.row]
asyncFetcher.fetchAsync(model.id)
}
}
/// - Tag: CancelPrefetching
func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) {
// Cancel any in-flight requests for data for the specified index paths.
for indexPath in indexPaths {
let model = models[indexPath.row]
asyncFetcher.cancelFetch(model.id)
}
}
}
|
0 | //
// DownloadManager.swift
// PocketCards
//
// Created by macmini on 2022/04/28.
//
import Alamofire
import Foundation
class DownloadManager {
public static var `default` = DownloadManager()
private var manager = FileManager.default
private var docsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
func downloadRequest(path: String?) -> DownloadRequest? {
// validation
guard let filepath = path else { return nil }
// validation
if filepath.isEmpty {
return nil
}
// file exist
if fileExists(filepath: filepath) {
return nil
}
// download
let destination: DownloadRequest.Destination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent(filepath)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
return AF.download(DOMAIN_HOST + filepath, to: destination)
}
func downloadFile(path: String?) {
let request = downloadRequest(path: path)
_ = request?.serializingDownloadedFileURL()
}
private func fileExists(filepath: String) -> Bool {
let destinationUrl = docsUrl?.appendingPathComponent(filepath)
if let destinationUrl = destinationUrl {
if FileManager().fileExists(atPath: destinationUrl.path) {
return true
}
}
return false
}
private func folderExists(folder: String) {
if folder.isEmpty { return }
guard let dir = docsUrl?.appendingPathComponent(folder) else { return }
var isDir: ObjCBool = true
// folder exist
if manager.fileExists(atPath: dir.path, isDirectory: &isDir) {
return
}
// create folder
try? manager.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)
}
}
|
0 | //
// PersonalAccessToken.swift
// GitBlamePR
//
// Created by Makoto Aoyama on 2020/05/20.
// Copyright © 2020 dev.aoyama. All rights reserved.
//
import Foundation
struct PersonalAccessToken {
let rawValue: String
init?(_ rawValue: String) {
if rawValue.count < 1 {
return nil
}
self.rawValue = rawValue
}
}
|
0 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _Node {
@inlinable @inline(__always)
internal static func _emptyNode() -> _Node {
_Node(storage: _emptySingleton, count: 0)
}
@inlinable
internal static func _collisionNode(
_ hash: _Hash,
_ item1: __owned Element,
_ item2: __owned Element
) -> _Node {
let node = _Node.allocateCollision(count: 2, hash) { items in
items.initializeElement(at: 1, to: item1)
items.initializeElement(at: 0, to: item2)
}.node
node._invariantCheck()
return node
}
@inlinable
internal static func _collisionNode(
_ hash: _Hash,
_ item1: __owned Element,
_ inserter2: (UnsafeMutablePointer<Element>) -> Void
) -> _Node {
let node = _Node.allocateCollision(count: 2, hash) { items in
items.initializeElement(at: 1, to: item1)
inserter2(items.baseAddress.unsafelyUnwrapped)
}.node
node._invariantCheck()
return node
}
@inlinable
internal static func _regularNode(
_ item: __owned Element,
_ bucket: _Bucket
) -> _Node {
let r = _Node.allocate(
itemMap: _Bitmap(bucket),
childMap: .empty,
count: 1
) { children, items in
assert(items.count == 1 && children.count == 0)
items.initializeElement(at: 0, to: item)
}
r.node._invariantCheck()
return r.node
}
@inlinable
internal static func _regularNode(
_ item1: __owned Element,
_ bucket1: _Bucket,
_ item2: __owned Element,
_ bucket2: _Bucket
) -> _Node {
_regularNode(
item1, bucket1,
{ $0.initialize(to: item2) }, bucket2).node
}
@inlinable
internal static func _regularNode(
_ item1: __owned Element,
_ bucket1: _Bucket,
_ inserter2: (UnsafeMutablePointer<Element>) -> Void,
_ bucket2: _Bucket
) -> (node: _Node, slot1: _Slot, slot2: _Slot) {
assert(bucket1 != bucket2)
let r = _Node.allocate(
itemMap: _Bitmap(bucket1, bucket2),
childMap: .empty,
count: 2
) { children, items -> (_Slot, _Slot) in
assert(items.count == 2 && children.count == 0)
let i1 = bucket1 < bucket2 ? 1 : 0
let i2 = 1 &- i1
items.initializeElement(at: i1, to: item1)
inserter2(items.baseAddress.unsafelyUnwrapped + i2)
return (_Slot(i2), _Slot(i1)) // Note: swapped
}
r.node._invariantCheck()
return (r.node, r.result.0, r.result.1)
}
@inlinable
internal static func _regularNode(
_ child: __owned _Node,
_ bucket: _Bucket
) -> _Node {
let r = _Node.allocate(
itemMap: .empty,
childMap: _Bitmap(bucket),
count: child.count
) { children, items in
assert(items.count == 0 && children.count == 1)
children.initializeElement(at: 0, to: child)
}
r.node._invariantCheck()
return r.node
}
@inlinable
internal static func _regularNode(
_ item: __owned Element,
_ itemBucket: _Bucket,
_ child: __owned _Node,
_ childBucket: _Bucket
) -> _Node {
_regularNode(
{ $0.initialize(to: item) }, itemBucket,
child, childBucket)
}
@inlinable
internal static func _regularNode(
_ inserter: (UnsafeMutablePointer<Element>) -> Void,
_ itemBucket: _Bucket,
_ child: __owned _Node,
_ childBucket: _Bucket
) -> _Node {
assert(itemBucket != childBucket)
let r = _Node.allocate(
itemMap: _Bitmap(itemBucket),
childMap: _Bitmap(childBucket),
count: child.count &+ 1
) { children, items in
assert(items.count == 1 && children.count == 1)
inserter(items.baseAddress.unsafelyUnwrapped)
children.initializeElement(at: 0, to: child)
}
r.node._invariantCheck()
return r.node
}
@inlinable
internal static func _regularNode(
_ child1: __owned _Node,
_ child1Bucket: _Bucket,
_ child2: __owned _Node,
_ child2Bucket: _Bucket
) -> _Node {
assert(child1Bucket != child2Bucket)
let r = _Node.allocate(
itemMap: .empty,
childMap: _Bitmap(child1Bucket, child2Bucket),
count: child1.count &+ child2.count
) { children, items in
assert(items.count == 0 && children.count == 2)
children.initializeElement(at: 0, to: child1)
children.initializeElement(at: 1, to: child2)
}
r.node._invariantCheck()
return r.node
}
}
extension _Node {
@inlinable
internal static func build(
level: _Level,
item1: __owned Element,
_ hash1: _Hash,
item2 inserter2: (UnsafeMutablePointer<Element>) -> Void,
_ hash2: _Hash
) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) {
assert(hash1.isEqual(to: hash2, upTo: level.ascend()))
if hash1 == hash2 {
let top = _collisionNode(hash1, item1, inserter2)
return (top, top.unmanaged, _Slot(0), _Slot(1))
}
let r = _build(
level: level, item1: item1, hash1, item2: inserter2, hash2)
return (r.top, r.leaf, r.slot1, r.slot2)
}
@inlinable
internal static func _build(
level: _Level,
item1: __owned Element,
_ hash1: _Hash,
item2 inserter2: (UnsafeMutablePointer<Element>) -> Void,
_ hash2: _Hash
) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) {
assert(hash1 != hash2)
let b1 = hash1[level]
let b2 = hash2[level]
guard b1 == b2 else {
let r = _regularNode(item1, b1, inserter2, b2)
return (r.node, r.node.unmanaged, r.slot1, r.slot2)
}
let r = _build(
level: level.descend(),
item1: item1, hash1,
item2: inserter2, hash2)
return (_regularNode(r.top, b1), r.leaf, r.slot1, r.slot2)
}
@inlinable
internal static func build(
level: _Level,
item1 inserter1: (UnsafeMutablePointer<Element>) -> Void,
_ hash1: _Hash,
child2: __owned _Node,
_ hash2: _Hash
) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) {
assert(child2.isCollisionNode)
assert(hash1 != hash2)
let b1 = hash1[level]
let b2 = hash2[level]
if b1 == b2 {
let node = build(
level: level.descend(),
item1: inserter1, hash1,
child2: child2, hash2)
return (_regularNode(node.top, b1), node.leaf, node.slot1, node.slot2)
}
let node = _regularNode(inserter1, hash1[level], child2, hash2[level])
return (node, node.unmanaged, .zero, .zero)
}
@inlinable
internal static func build(
level: _Level,
child1: __owned _Node,
_ hash1: _Hash,
child2: __owned _Node,
_ hash2: _Hash
) -> _Node {
assert(child1.isCollisionNode)
assert(child2.isCollisionNode)
assert(hash1 != hash2)
let b1 = hash1[level]
let b2 = hash2[level]
guard b1 == b2 else {
return _regularNode(child1, b1, child2, b2)
}
let node = build(
level: level.descend(),
child1: child1, hash1,
child2: child2, hash2)
return _regularNode(node, b1)
}
}
|
0 | // swift-tools-version:4.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "RoutingTable",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "RoutingTable",
targets: ["RoutingTable"]),
],
dependencies: [
// 💧 A server-side Swift web framework.
.package(url: "https://github.com/vapor/vapor.git", from: "3.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: "RoutingTable",
dependencies: [
"Vapor"
]),
.testTarget(
name: "RoutingTableTests",
dependencies: ["RoutingTable"]),
]
)
|
0 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func x(n: Sequence, k : (T) -> U {
}
protocol b {
func a(object1, Bool], y: a {
class func b: T, AnyObject, V>] = "\()
typealias f : a {
|
0 | //
// Dealer.swift
// BlackJack
//
// Created by RENO1 on 2020/08/04.
// Copyright © 2020 RENO1. All rights reserved.
//
import Foundation
class Dealer: CardHolder, DealerAble {
override init() {
// generate Card
var initCardList = [Card]()
for suit in Card.Suit.allCases {
for rank in Card.Rank.allCases {
initCardList.append(Card(suit: suit, rank: rank))
}
}
super.init(cardList: initCardList)
}
// shuffle Card
func shuffle() {
cardList.shuffled()
}
func getCard() -> Card? {
if(cardList.count > 0) {
let cardIdx = Int.random(in: 0..<cardList.count)
let card = cardList[cardIdx]
cardList.remove(at: cardIdx)
return card
} else {
return nil
}
}
func giveCard(cardHolder: CardHolder) {
let card = self.getCard()
if (card != nil) {
cardHolder.addCard(card: card!)
}
}
}
protocol DealerAble {
func shuffle()
func getCard() -> Card?
func giveCard(cardHolder: CardHolder)
}
|
0 | import XCTest
@testable import CacheKitTests
XCTMain([
testCase(CacheKitTests.allTests),
])
|
0 | // Copyright 2019 Google LLC
//
// 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.
/// A mutator that changes the input variables of instructions in a program.
public class InputMutator: BaseInstructionMutator {
public init() {
super.init(maxSimultaneousMutations: defaultMaxSimultaneousMutations)
}
public override func canMutate(_ instr: Instruction) -> Bool {
return instr.numInputs > 0 && instr.isMutable
}
public override func mutate(_ instr: Instruction, _ b: ProgramBuilder) {
var inouts = b.adopt(instr.inouts)
// Replace one input
let selectedInput = Int.random(in: 0..<instr.numInputs)
b.trace("Mutating input \(selectedInput)")
inouts[selectedInput] = b.randVar()
b.append(Instruction(instr.op, inouts: inouts))
}
}
|
0 | //
// OAuthViewController.swift
// sina
//
// Created by GMY on 2017/3/15.
// Copyright © 2017年 Mingk. All rights reserved.
//
import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// GMYHTTPSessionManager.shareManager.gmy_get(URLString: "http://httpbin.org/get?", parameters: ["abc": "123"], progress: nil, success: { (dataTask: URLSessionDataTask, responseObject: Any?) in
// print(responseObject)
// }) { (dataTask: URLSessionDataTask?, error: Error) in
// print(error)
// }
// AFHTTPSessionManager().get("http://httpbin.org/get?", parameters: ["abc": "123"], progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
//
// print(responseObject as AnyObject)
// }) { (dataTask: URLSessionDataTask?, error: Error) in
// print(error)
// }
title = "授权"
automaticallyAdjustsScrollViewInsets = false
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "close", style: .plain, target: self, action: #selector(OAuthViewController.closeClick))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "add", style: .plain, target: self, action: #selector(OAuthViewController.addClick))
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
guard let url = URL(string: urlString) else {
return
}
let request = URLRequest(url: url)
webView.loadRequest(request)
// "https://api.weibo.com/oauth2/authorize?client_id=2014705515&redirect_uri=http://www.baidu.com"
}
@objc private func closeClick() {
SVProgressHUD.dismiss()
dismiss(animated: true, completion: nil)
}
@objc private func addClick() {
let jsCode = "document.getElementById('userId').value='sokhk@example.com';document.getElementById('passwd').value='pP456852'"
webView.stringByEvaluatingJavaScript(from: jsCode)
}
func webViewDidStartLoad(_ webView: UIWebView) {
SVProgressHUD.show()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
SVProgressHUD.dismiss()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
SVProgressHUD.dismiss()
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
guard let url = request.url else {
return true
}
let urlString = url.absoluteString
guard urlString.contains("code=") else {
return true
}
let code = urlString.components(separatedBy: "code=").last!
loadAccessToken(code: code)
return false
}
private func loadAccessToken(code: String) {
let para = ["client_id": app_key,
"client_secret": app_secret,
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect_uri]
GMYHTTPSessionManager.shareManager.gmy_post(URLString: "https://api.weibo.com/oauth2/access_token", parameters: para, progress: nil, success: { (dataTask: URLSessionDataTask, responseObject: Any?) in
guard let responseObject = responseObject as? [String: AnyObject] else {
return
}
let account = UserAccountModel(dict: responseObject)
self.loadUserInfo(account: account)
}) { (dataTask: URLSessionDataTask?, error: Error) in
print(error)
}
}
private func loadUserInfo(account: UserAccountModel) {
guard let access_token = account.access_token else {
return
}
guard let uid = account.uid else {
return
}
let para = ["access_token": access_token,
"uid": uid]
GMYHTTPSessionManager.shareManager.gmy_get(URLString: "https://api.weibo.com/2/users/show.json", parameters: para, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
guard let responseObject = responseObject as? [String: AnyObject] else {
return
}
account.avatar_large = responseObject["avatar_large"] as? String
account.screen_name = responseObject["screen_name"] as? String
NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.shareUserAccount.accountPath)
UserAccountViewModel.shareUserAccount.account = account;
self.dismiss(animated: false, completion: {
UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
})
}) { (task: URLSessionDataTask?, error: Error) in
print(error)
}
}
}
|
0 | //
// VideoView.swift
// VideoEdit
//
// Created by Bruno Serrano dos Santos on 07/04/20.
// Copyright © 2020 EagleSoft. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class VideoView: UIView {
var playerLayer: AVPlayerLayer?
var player: AVPlayer?
var isLoop = false
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func configure(url: URL) {
player = AVPlayer(url: url)
playerLayer = AVPlayerLayer(player: player)
playerLayer?.frame = bounds
playerLayer?.videoGravity = .resizeAspectFill
if let playerLayer = self.playerLayer {
layer.addSublayer(playerLayer)
}
NotificationCenter.default.addObserver(self, selector: #selector(reachTheEndOfTheVideo(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
}
func play() {
if player?.timeControlStatus != .playing {
player?.play()
}
}
func pause() {
player?.pause()
}
func stop() {
player?.pause()
player?.seek(to: .zero)
}
@objc func reachTheEndOfTheVideo(_ notification: Notification) {
if isLoop {
player?.pause()
player?.seek(to: .zero)
player?.play()
}
}
}
|
0 | //
// CVFRCDelegate.swift
// Pods
//
// Created by Jordan Zucker on 1/30/17.
//
//
import UIKit
import CoreData
public class CVFRCDelegate: NSObject, NSFetchedResultsControllerDelegate {
private weak var collectionView: UICollectionView?
public init(collectionView: UICollectionView) {
self.collectionView = collectionView
}
public func deinitActions() {
fetchedResultsChange = nil
fetchedResultsQueue.cancelAllOperations()
}
deinit {
deinitActions()
}
private var fetchedResultsQueue: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .userInteractive
return queue
} ()
private var fetchedResultsChange: BatchUpdate?
// MARK: - NSFetchedResultsControllerDelegate
public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
fetchedResultsChange = BatchUpdate(collectionView: self.collectionView)
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
fetchedResultsChange?.addChange(change: .object(indexPath, newIndexPath, type))
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
fetchedResultsChange?.addChange(change: .section(sectionIndex, type))
}
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
guard let existingFetchedResultsChange = self.fetchedResultsChange else {
return
}
self.fetchedResultsQueue.addOperation(existingFetchedResultsChange)
self.fetchedResultsChange = nil
}
}
|
0 | import Foundation
import Metal
public class ComputePipelineState: MetalRepresentable, Configurable {
public struct Config: Configuration {
public init(library: Library, pipelineConfigurator: Configurator)throws {
self.library = library
self.descritpor = try CreatePipeline(configurator: pipelineConfigurator)
}
public var library: Library
public var descritpor: MTLComputePipelineDescriptor!
public typealias Configurator = (MTLComputePipelineDescriptor, Library)throws -> ()
func CreatePipeline(configurator: Configurator)throws ->MTLComputePipelineDescriptor {
let pipelineDescriptor = MTLComputePipelineDescriptor()
try configurator(pipelineDescriptor,library)
return pipelineDescriptor
}
}
public required init(with settings: Config) throws {
library = settings.library
mtlItem = try library.mtlItem.device.makeComputePipelineState(descriptor: settings.descritpor,options: [], reflection: nil)
}
public let library: Library
public var mtlItem: MTLComputePipelineState
}
|
0 | //
// UITableViewDelegate+Ex.swift
// WPCommand
//
// Created by WenPing on 2021/8/18.
//
import UIKit
private var WPTableViewDelegatePointer = "WPTableViewDelegatePointer"
extension UITableView {
var wp_delegate: WPTableViewDelegate {
set {
WPRunTime.set(self, newValue, &WPTableViewDelegatePointer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
delegate = newValue
}
get {
guard let wp_delegate: WPTableViewDelegate = WPRunTime.get(self, &WPTableViewDelegatePointer) else {
let wp_delegate = WPTableViewDelegate()
self.wp_delegate = wp_delegate
return wp_delegate
}
return wp_delegate
}
}
}
public extension WPSpace where Base: UITableView {
/// 桥接代理
var delegate: WPTableViewDelegate {
return base.wp_delegate
}
}
public class WPTableViewDelegate: WPScrollViewDelegate {
/// 选中一行掉用
var didSelectRowAt: ((UITableView, IndexPath) -> Void)?
/// 每一行的高度
var heightForRowAt: ((UITableView, IndexPath) -> CGFloat)?
/// 编辑按钮的点击时间
var commitEditingStyle: ((UITableView, IndexPath) -> Void)?
/// 这一组header高度
var heightForHeaderInSection: ((UITableView, Int) -> CGFloat)?
/// 这一组footer高度
var heightForFooterInSection: ((UITableView, Int) -> CGFloat)?
/// 这一组的headerView
var viewForHeaderInSection: ((UITableView, Int) -> UIView?)?
/// 这一组的footerView
var viewForFooterInSection: ((UITableView, Int) -> UIView?)?
/// cell即将显示
var willDisplayCell: ((UITableView, UITableViewCell, IndexPath) -> Void)?
/// 这一组headerView即将显示
var willDisplayHeaderView: ((UITableView, UIView, Int) -> Void)?
/// 这一组foogerView即将显示
var willDisplayFooterView: ((UITableView, UIView, Int) -> Void)?
}
extension WPTableViewDelegate: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let item = tableView.wp_source.groups.wp_get(of: indexPath.section)?.items.wp_get(of: indexPath.row)
if heightForRowAt != nil {
return heightForRowAt!(tableView, indexPath)
} else if item != nil {
return item!.cellHeight
} else {
return 0
}
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
let group = tableView.wp_source.groups.wp_get(of: indexPath.section)
if let item = group?.items.wp_get(of: indexPath.row) {
item.didCommitEditBlock?(item, group!)
}
commitEditingStyle?(tableView, indexPath)
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let group = tableView.wp_source.groups.wp_get(of: section)
if heightForHeaderInSection != nil {
return heightForHeaderInSection!(tableView, section)
} else if group != nil {
return group!.headerHeight
} else {
return 0.01
}
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let group = tableView.wp_source.groups.wp_get(of: section)
if heightForFooterInSection != nil {
return heightForFooterInSection!(tableView, section)
} else if group != nil {
return group!.footerHeight
} else {
return 0.01
}
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if viewForHeaderInSection != nil {
return viewForHeaderInSection!(tableView, section)
} else if let group = tableView.wp_source.groups.wp_get(of: section) {
var headView: UITableViewHeaderFooterView?
if let idStr = group.headViewReuseIdentifier {
headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: idStr)
if headView == nil {
tableView.register(group.headViewClass, forHeaderFooterViewReuseIdentifier: idStr)
headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: idStr)
}
headView?.group = group
headView?.reloadGroup(group: group)
}
return headView
}
return nil
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if viewForFooterInSection != nil {
return viewForFooterInSection!(tableView, section)
} else if let group = tableView.wp_source.groups.wp_get(of: section) {
var foodView: UITableViewHeaderFooterView?
if let idStr = group.footViewReuseIdentifier {
foodView = tableView.dequeueReusableHeaderFooterView(withIdentifier: idStr)
if foodView == nil {
tableView.register(group.footViewClass, forHeaderFooterViewReuseIdentifier: idStr)
foodView = tableView.dequeueReusableHeaderFooterView(withIdentifier: idStr)
}
foodView?.group = group
foodView?.reloadGroup(group: group)
}
return foodView
}
return nil
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
didSelectRowAt?(tableView, indexPath)
if let item = tableView.wp_source.groups.wp_get(of: indexPath.section)?.items.wp_get(of: indexPath.row) {
let cell = tableView.cellForRow(at: indexPath)
item.didSelectedBlock?(cell!)
}
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
willDisplayCell?(tableView, cell, indexPath)
if let item = tableView.wp_source.groups.wp_get(of: indexPath.section)?.items.wp_get(of: indexPath.row) {
cell.separatorInset = item.separatorInset
item.willDisplay?(cell)
cell.didSetItemInfo(info: item.info)
}
}
public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
willDisplayHeaderView?(tableView, view, section)
if let group = tableView.wp_source.groups.wp_get(of: section) {
let headerView = view as! UITableViewHeaderFooterView
headerView.reloadGroup(group: group)
group.headWillDisplayBlock?(headerView)
}
}
public func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
willDisplayFooterView?(tableView, view, section)
if let group = tableView.wp_source.groups.wp_get(of: section) {
let footerView = view as! UITableViewHeaderFooterView
footerView.reloadGroup(group: group)
group.headWillDisplayBlock?(footerView)
}
}
}
|
0 | //
// ProductDetailViewController.swift
// OpenFoodFacts
//
// Created by Andrés Pizá Bückmann on 14/04/2017.
// Copyright © 2017 Andrés Pizá Bückmann. All rights reserved.
//
import UIKit
import XLPagerTabStrip
class ProductDetailViewController: ButtonBarPagerTabStripViewController, DataManagerClient {
var hideSummary: Bool = false
var product: Product!
var latestRobotoffQuestions: [RobotoffQuestion] = []
var dataManager: DataManagerProtocol!
private var notificationCentertoken: NotificationCenterToken?
override func viewDidLoad() {
super.viewDidLoad()
buttonBarView.register(UINib(nibName: "ButtonBarView", bundle: nil), forCellWithReuseIdentifier: "Cell")
if #available(iOS 13.0, *) {
buttonBarView.backgroundColor = .systemBackground
settings.style.selectedBarBackgroundColor = .secondarySystemBackground
} else {
buttonBarView.backgroundColor = .white
settings.style.selectedBarBackgroundColor = .white
}
buttonBarView.selectedBar.backgroundColor = self.view.tintColor
if let tbc = tabBarController {
if let items = tbc.tabBar.items {
for (index, item) in items.enumerated() {
switch index {
case 0: item.accessibilityIdentifier = AccessibilityIdentifiers.Product.detailSummaryView
case 1: item.accessibilityIdentifier = AccessibilityIdentifiers.Product.detailIngredientsView
case 2: item.accessibilityIdentifier = AccessibilityIdentifiers.Product.detailNutritionView
default: break
}
}
}
}
setUserAgent()
notificationCentertoken = NotificationCenter.default.observe(
name: .productChangesUploaded,
object: nil,
queue: .main
) { [weak self] notif in
guard let barcode = notif.userInfo?["barcode"] as? String else {
return
}
if barcode == self?.product.barcode {
self?.refreshProduct {}
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//TODO: Answers.logContentView(withName: "Product's detail", contentType: "product_detail", contentId: product.barcode, customAttributes: ["product_name": product.name ?? ""])
if let parentVc = parent as? UINavigationController {
parentVc.navigationBar.isTranslucent = false
let shareButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(didTapShareButton(_:)))
var buttons: [UIBarButtonItem] = navigationItem.rightBarButtonItems ?? []
buttons.insert(shareButton, at: 0)
navigationItem.rightBarButtonItems = buttons
}
self.refreshLatestRobotoffQuestion()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.isTranslucent = true
if var buttons = navigationItem.rightBarButtonItems, !buttons.isEmpty {
buttons.remove(at: 0)
navigationItem.rightBarButtonItems = buttons
}
}
fileprivate func refreshLatestRobotoffQuestion() {
self.latestRobotoffQuestions = []
if let barcode = self.product.barcode {
dataManager.getLatestRobotoffQuestions(forBarcode: barcode) { [weak self] (questions: [RobotoffQuestion]) in
guard let zelf = self else {
return
}
zelf.latestRobotoffQuestions = questions
zelf.updateForms(with: zelf.product)
}
}
}
private func setUserAgent() {
var userAgentString = ""
if let validAppName = Bundle.main.infoDictionary![kCFBundleNameKey as String] as? String {
userAgentString = validAppName
}
if let validVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
userAgentString += "; version " + validVersion
}
if let validBuild = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as? String {
userAgentString += "; build " + validBuild + " - product"
}
UserDefaults.standard.register(defaults: ["UserAgent": userAgentString])
}
// MARK: - Product pages
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
var vcs = [UIViewController]()
vcs.append(getSummaryVC())
vcs.append(getIngredientsVC())
if let nutritionVC = getNutritionVC() {
vcs.append(nutritionVC)
}
if let environmentImpactVC = getEnvironmentImpactVC() {
vcs.append(environmentImpactVC)
}
return vcs
}
fileprivate func getSummaryVC() -> UIViewController {
let form = createSummaryForm()
let summaryFormTableVC = SummaryFormTableViewController(with: form, dataManager: dataManager)
summaryFormTableVC.delegate = self
summaryFormTableVC.hideSummary = hideSummary
return summaryFormTableVC
}
fileprivate func getIngredientsVC() -> UIViewController {
let form = createIngredientsForm()
let ingredientsFormTableVC = IngredientsFormTableViewController(with: form, dataManager: dataManager)
ingredientsFormTableVC.delegate = self
return ingredientsFormTableVC
}
fileprivate func getNutritionVC() -> UIViewController? {
guard let form = createNutritionForm() else { return nil }
let nutritionTableFormTableVC = NutritionTableFormTableViewController(with: form, dataManager: dataManager)
nutritionTableFormTableVC.delegate = self
return nutritionTableFormTableVC
}
fileprivate func getEnvironmentImpactVC() -> UIViewController? {
if product.environmentImpactLevelTags?.isEmpty == false, let infoCard = product.environmentInfoCard, infoCard.isEmpty == false {
let environmentImpactFormTableVC = EnvironmentImpactTableFormTableViewController()
environmentImpactFormTableVC.product = product
return environmentImpactFormTableVC
}
return nil
}
// MARK: - Form creation methods
private func updateForms(with updatedProduct: Product) {
self.product = updatedProduct
for (index, viewController) in viewControllers.enumerated() {
if let vc0 = viewController as? FormTableViewController {
switch index {
case 0:
vc0.form = createSummaryForm()
vc0.view.accessibilityIdentifier = AccessibilityIdentifiers.Product.detailSummaryView
case 1:
vc0.form = createIngredientsForm()
vc0.view.accessibilityIdentifier = AccessibilityIdentifiers.Product.detailIngredientsView
case 2:
vc0.form = createNutritionForm()
vc0.view.accessibilityIdentifier = AccessibilityIdentifiers.Product.detailNutritionView
default: break
}
} else if let vc1 = viewController as? EnvironmentImpactTableFormTableViewController {
vc1.product = product
}
}
}
private func createSummaryForm() -> Form {
var rows = [FormRow]()
// Header
rows.append(FormRow(value: product as Any, cellType: SummaryHeaderCell.self))
if !UserDefaults.standard.bool(forKey: UserDefaultsConstants.disableRobotoffWhenNotLoggedIn), !latestRobotoffQuestions.isEmpty {
createFormRow(with: &rows, item: latestRobotoffQuestions, cellType: RobotoffQuestionTableViewCell.self)
}
createIngredientsAnalysisRows(rows: &rows)
createNutrientsRows(rows: &rows)
createAdditivesRows(with: &rows, product: product)
// Rows
createFormRow(with: &rows, item: product.barcode, label: InfoRowKey.barcode.localizedString, isCopiable: true)
createFormRow(with: &rows, item: product.genericName, label: InfoRowKey.genericName.localizedString, isCopiable: true)
createFormRow(with: &rows, item: product.packaging, label: InfoRowKey.packaging.localizedString)
createFormRow(with: &rows, item: product.manufacturingPlaces, label: InfoRowKey.manufacturingPlaces.localizedString)
createFormRow(with: &rows, item: product.origins, label: InfoRowKey.origins.localizedString)
createFormRow(with: &rows, item: product.categoriesTags?.map({ (categoryTag: String) -> NSAttributedString in
if let category = dataManager.category(forTag: categoryTag) {
if let name = Tag.choose(inTags: Array(category.names)) {
return NSAttributedString(string: name.value, attributes: [NSAttributedString.Key.link: OFFUrlsHelper.url(forCategory: category)])
}
}
return NSAttributedString(string: categoryTag)
}), label: InfoRowKey.categories.localizedString)
createFormRow(with: &rows, item: product.labelsTags?.map({ (labelTag: String) -> NSAttributedString in
if let label = dataManager.label(forTag: labelTag) {
if let name = Tag.choose(inTags: Array(label.names)) {
return NSAttributedString(string: name.value, attributes: [NSAttributedString.Key.link : OFFUrlsHelper.url(forLabel: label)])
}
}
return NSAttributedString(string: labelTag)
}), label: InfoRowKey.labels.localizedString)
createFormRow(with: &rows, item: product.citiesTags, label: InfoRowKey.citiesTags.localizedString)
createFormRow(with: &rows, item: product.embCodesTags?.map({ (tag: String) -> NSAttributedString in
return NSAttributedString(string: tag.uppercased().replacingOccurrences(of: "-", with: " "),
attributes: [NSAttributedString.Key.link: OFFUrlsHelper.url(forEmbCodeTag: tag)])
}), label: InfoRowKey.embCodes.localizedString)
createFormRow(with: &rows, item: product.stores, label: InfoRowKey.stores.localizedString)
createFormRow(with: &rows, item: product.countriesTags?.map({ (tag: String) -> NSAttributedString in
if let country = dataManager.country(forTag: tag) {
if let name = Tag.choose(inTags: Array(country.names)) {
return NSAttributedString(string: name.value, attributes: [NSAttributedString.Key.link: OFFUrlsHelper.url(for: country)])
}
}
return NSAttributedString(string: tag)
}), label: InfoRowKey.countries.localizedString)
// Footer
rows.append(FormRow(value: product as Any, cellType: SummaryFooterCell.self))
let summaryTitle = "product-detail.page-title.summary".localized
return Form(title: summaryTitle, rows: rows)
}
// swiftlint:disable function_body_length
private func createIngredientsForm() -> Form {
var rows = [FormRow]()
// Header
rows.append(FormRow(value: product as Any, cellType: HostedViewCell.self))
// Rows
if let ingredientsList = product.ingredientsList {
createFormRow(with: &rows, item: "\n" + ingredientsList, label: InfoRowKey.ingredientsList.localizedString)
}
createFormRow(with: &rows, item: product.allergens?.map({ (allergen: Tag) -> NSAttributedString in
if let allergen = dataManager.allergen(forTag: allergen) {
if let name = Tag.choose(inTags: Array(allergen.names)) {
return NSAttributedString(string: name.value, attributes: [NSAttributedString.Key.link: OFFUrlsHelper.url(forAllergen: allergen)])
}
}
return NSAttributedString(string: allergen.value.capitalized)
}), label: InfoRowKey.allergens.localizedString)
if dataManager.listAllergies().isEmpty == false {
if product.states?.contains("en:ingredients-to-be-completed") == true {
if product.allergens == nil || product.allergens?.isEmpty == true {
createFormRow(with: &rows, item: "⚠️ " + "product-detail.ingredients.allergens-list.missing-infos".localized, label: InfoRowKey.allergens.localizedString)
}
}
}
createFormRow(with: &rows, item: product.traces?.map({ (trace: Tag) -> NSAttributedString in
if let trace = dataManager.allergen(forTag: trace) {
if let name = Tag.choose(inTags: Array(trace.names)) {
return NSAttributedString(string: name.value, attributes: [NSAttributedString.Key.link: OFFUrlsHelper.url(forAllergen: trace)])
}
}
return NSAttributedString(string: trace.value.capitalized)
}), label: InfoRowKey.traces.localizedString)
createFormRow(with: &rows, item: product.vitamins?.map({ (vitamin: Tag) -> NSAttributedString in
if let vitamin = dataManager.vitamin(forTag: vitamin) {
if let name = Tag.choose(inTags: Array(vitamin.names)) {
return NSAttributedString(string: name.value, attributes: [NSAttributedString.Key.link: OFFUrlsHelper.url(forVitamin: vitamin)])
}
}
return NSAttributedString(string: vitamin.value.capitalized)
}), label: InfoRowKey.vitamins.localizedString)
createFormRow(with: &rows, item: product.minerals?.map({ (mineral: Tag) -> NSAttributedString in
if let mineral = dataManager.mineral(forTag: mineral) {
if let name = Tag.choose(inTags: Array(mineral.names)) {
return NSAttributedString(string: name.value, attributes: [NSAttributedString.Key.link: OFFUrlsHelper.url(forMineral: mineral)])
}
}
return NSAttributedString(string: mineral.value.capitalized)
}), label: InfoRowKey.minerals.localizedString)
createFormRow(with: &rows, item: product.nucleotides?.map({ (nucleotide: Tag) -> NSAttributedString in
if let nucleotide = dataManager.nucleotide(forTag: nucleotide) {
if let name = Tag.choose(inTags: Array(nucleotide.names)) {
return NSAttributedString(string: name.value, attributes: [NSAttributedString.Key.link: OFFUrlsHelper.url(forNucleotide: nucleotide)])
}
}
return NSAttributedString(string: nucleotide.value.capitalized)
}), label: InfoRowKey.nucleotidesList.localizedString)
createFormRow(with: &rows, item: product.otherNutrients?.map({ (other: Tag) -> NSAttributedString in
if let other = dataManager.allergen(forTag: other) {
if let name = Tag.choose(inTags: Array(other.names)) {
return NSAttributedString(string: name.value, attributes: [NSAttributedString.Key.link: URL(string: "https:world-en.openfoodfacts.org")!])
}
}
return NSAttributedString(string: other.value.capitalized)
}), label: InfoRowKey.otherNutritionalSubstances.localizedString)
//createFormRow(with: &rows, item: product.traces, label: InfoRowKey.traces.localizedString)
createAdditivesRows(with: &rows, product: product)
createFormRow(with: &rows, item: product.possiblePalmOilIngredients, label: InfoRowKey.possiblePalmOilIngredients.localizedString)
let summaryTitle = "product-detail.page-title.ingredients".localized
return Form(title: summaryTitle, rows: rows)
}
// swiftlint:enable function_body_length
fileprivate func createAdditivesRows(with rows: inout [FormRow], product: Product) {
guard let additives = product.additives, additives.isEmpty == false else {
return
}
var items: [Any] = []
items.append(NSAttributedString(string: " ")) //to have the first carriage return from the join with separator
items.append(contentsOf: additives.map({ (additive: Tag) -> NSAttributedString in
if let additive = dataManager.additive(forTag: additive) {
if let name = Tag.choose(inTags: Array(additive.names)) {
return NSAttributedString(string: name.value, attributes: [NSAttributedString.Key.link: OFFUrlsHelper.url(forAdditive: additive)])
}
}
return NSAttributedString(string: additive.value.uppercased())
}))
createFormRow(with: &rows, item: items, label: InfoRowKey.additives.localizedString, separator: "\n ")
}
private func createNutritionForm() -> Form? {
var rows = [FormRow]()
// Nutriscore cell
if product.nutriscore != nil {
// created to pass on the delegate with the nutriscore
let headerRow = NutritionScoreTableRow(
delegate as? NutritionHeaderTableViewCellDelegate,
nutriscore: product.nutriscore,
noFiberWarning: product.nutriscoreWarningNoFiber,
noFruitsVegetablesNutsWarning: product.nutriscoreWarningNoFruitsVegetablesNuts)
createFormRow(with: &rows, item: headerRow, cellType: NutritionHeaderTableViewCell.self)
}
// Info rows
if let carbonFootprint = product.nutriments?.carbonFootprint, let unit = product.nutriments?.carbonFootprintUnit {
createFormRow(with: &rows, item: "\(carbonFootprint) \(unit)", label: InfoRowKey.carbonFootprint.localizedString)
}
createNutrientsRows(rows: &rows)
if let validStates = product.states,
validStates.contains("en:nutrition-facts-completed") {
createNutritionTableWebViewRow(rows: &rows)
//createNutritionTableRows(rows: &rows)
} else {
createFormRow(with: &rows, item: product, cellType: HostedViewCell.self)
createFormRow(with: &rows, item: "product-detail.nutrition-table.missing".localized, label: InfoRowKey.nutritionalTableHeader.localizedString, isCopiable: true)
}
if rows.isEmpty {
return nil
}
return Form(title: "product-detail.page-title.nutrition".localized, rows: rows)
}
fileprivate func createIngredientsAnalysisRows(rows: inout [FormRow]) {
let analysisDetails = self.dataManager.ingredientsAnalysis(forProduct: product)
if !analysisDetails.isEmpty {
product.ingredientsAnalysisDetails = analysisDetails
createFormRow(with: &rows, item: product, cellType: IngredientsAnalysisTableViewCell.self)
}
}
fileprivate func createNutrientsRows(rows: inout [FormRow]) {
// Nutrition levels
if product.nutritionLevels != nil {
createFormRow(with: &rows, item: product, cellType: NutritionLevelsTableViewCell.self)
}
}
fileprivate func createNutritionTableWebViewRow(rows: inout [FormRow]) {
guard let html = product.nutritionTableHtml else {
return
}
createFormRow(with: &rows, item: product, cellType: HostedViewCell.self)
createFormRow(with: &rows, item: html, label: nil, cellType: ProductDetailWebViewTableViewCell.self, isCopiable: false)
}
// swiftlint:disable:next cyclomatic_complexity
fileprivate func createNutritionTableRows(rows: inout [FormRow]) {
// Header
createFormRow(with: &rows, item: product, cellType: HostedViewCell.self)
if product.nutriments != nil || product.servingSize != nil {
// Nutrition table rows
let headerRow = NutritionTableRow(label: "",
perSizeValue: "product-detail.nutrition-table.100g".localized,
perServingValue: "product-detail.nutrition-table.serving".localized)
createFormRow(with: &rows, item: headerRow, cellType: NutritionTableRowTableViewCell.self)
}
if let energy = product.nutriments?.energyKJ, let nutritionTableRow = energy.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
if let energy = product.nutriments?.energyKcal, let nutritionTableRow = energy.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
if let fats = product.nutriments?.fats {
for item in fats {
if let nutritionTableRow = item.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
}
}
if let carbohydrates = product.nutriments?.carbohydrates {
for item in carbohydrates {
if let nutritionTableRow = item.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
}
}
if let fiber = product.nutriments?.fiber, let nutritionTableRow = fiber.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
if let proteins = product.nutriments?.proteins {
for item in proteins {
if let nutritionTableRow = item.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
}
}
if let salt = product.nutriments?.salt, let nutritionTableRow = salt.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
if let sodium = product.nutriments?.sodium, let nutritionTableRow = sodium.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
if let alcohol = product.nutriments?.alcohol, let nutritionTableRow = alcohol.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
if let vitamins = product.nutriments?.vitamins {
for item in vitamins {
if let nutritionTableRow = item.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
}
}
if let minerals = product.nutriments?.minerals {
for item in minerals {
if let nutritionTableRow = item.nutritionTableRow {
createFormRow(with: &rows, item: nutritionTableRow, cellType: NutritionTableRowTableViewCell.self)
}
}
}
}
private func createFormRow(with array: inout [FormRow], item: Any?, label: String? = nil, cellType: ProductDetailBaseCell.Type = InfoRowTableViewCell.self, isCopiable: Bool = false, separator: String = ", ") {
// Check item has a value, if so add to the array of rows.
switch item {
case let value as String:
// Check if it's empty here insted of doing 'case let value as String where !value.isEmpty' because an empty String ("") would not match this case but the default one
if !value.isEmpty {
array.append(FormRow(label: label, value: value, cellType: cellType, isCopiable: isCopiable, separator: separator))
}
case let value as [Any]:
if !value.isEmpty {
array.append(FormRow(label: label, value: value, cellType: cellType, isCopiable: isCopiable, separator: separator))
}
default:
if let value = item {
array.append(FormRow(label: label, value: value, cellType: cellType, isCopiable: isCopiable, separator: separator))
}
}
}
// MARK: - Nav bar button
@objc func didTapShareButton(_ sender: UIBarButtonItem) {
SharingManager.shared.shareLink(name: product.name, string: URLs.urlForProduct(with: product.barcode), sender: sender, presenter: self)
}
}
// MARK: - Refresh delegate
protocol ProductDetailRefreshDelegate: class {
func refreshProduct(completion: () -> Void)
}
extension ProductDetailViewController: ProductDetailRefreshDelegate {
func refreshProduct(completion: () -> Void) {
if let barcode = self.product.barcode {
dataManager.getProduct(byBarcode: barcode, isScanning: false, isSummary: false, onSuccess: { [weak self] response in
if let updatedProduct = response {
self?.updateForms(with: updatedProduct)
self?.refreshLatestRobotoffQuestion()
}
}, onError: { [weak self] error in
// No error should be thrown here, as the product was loaded previously
AnalyticsManager.record(error: error)
self?.navigationController?.popToRootViewController(animated: true)
})
}
completion()
}
}
extension ProductDetailViewController: NutritionHeaderTableViewCellDelegate {
// function to let the delegate know that the switch changed
//func tagListViewAddImageTableViewCell(_ sender: TagListViewAddImageTableViewCell, receivedDoubleTapOn tagListView:TagListView)
public func nutritionHeaderTableViewCellDelegate(_ sender: NutritionHeaderTableViewCell, receivedTapOn button: UIButton) {
if let url = URL(string: URLs.NutriScore) {
openUrlInApp(url)
} else if let url = URL(string: URLs.SupportOpenFoodFacts) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
|
0 | //
// CalendarDateRangePickerCell.swift
// CalendarDateRangePickerViewController
//
// Created by Miraan on 15/10/2017.
// Copyright © 2017 Miraan. All rights reserved.
//
import UIKit
class CalendarDateRangePickerCell: UICollectionViewCell {
private let defaultTextColor = UIColor.darkGray
var highlightedColor = UIColor(red: 15/255.0, green: 147/255.0, blue: 189/255.0, alpha: 1.0)
private let disabledColor = UIColor.lightGray
var selectedColor: UIColor!
var date: Date?
var selectedView: UIView?
var halfBackgroundView: UIView?
var roundHighlightView: UIView?
var label: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
initLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
initLabel()
}
func initLabel() {
label = UILabel(frame: frame)
label.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
if #available(iOS 8.2, *) {
label.font = UIFont.systemFont(ofSize: 17.0, weight: .semibold)
} else {
// Fallback on earlier versions
}
label.textColor = UIColor.black
label.textAlignment = NSTextAlignment.center
self.addSubview(label)
}
func reset() {
self.backgroundColor = UIColor.clear
label.textColor = defaultTextColor
label.backgroundColor = UIColor.clear
if selectedView != nil {
selectedView?.removeFromSuperview()
selectedView = nil
}
if halfBackgroundView != nil {
halfBackgroundView?.removeFromSuperview()
halfBackgroundView = nil
}
if roundHighlightView != nil {
roundHighlightView?.removeFromSuperview()
roundHighlightView = nil
}
}
func select() {
let width = self.frame.size.width
let height = self.frame.size.height
selectedView = UIView(frame: CGRect(x: (width - height) / 2, y: 0, width: height, height: height))
selectedView?.backgroundColor = selectedColor
selectedView?.layer.cornerRadius = height / 2
self.addSubview(selectedView!)
self.sendSubview(toBack: selectedView!)
label.textColor = UIColor.white
}
func highlightRight() {
// This is used instead of highlight() when we need to highlight cell with a rounded edge on the left
let width = self.frame.size.width
let height = self.frame.size.height
halfBackgroundView = UIView(frame: CGRect(x: width / 2, y: 0, width: width / 2, height: height))
halfBackgroundView?.backgroundColor = highlightedColor
self.addSubview(halfBackgroundView!)
self.sendSubview(toBack: halfBackgroundView!)
label.textColor = UIColor.white
addRoundHighlightView()
}
func highlightLeft() {
// This is used instead of highlight() when we need to highlight the cell with a rounded edge on the right
let width = self.frame.size.width
let height = self.frame.size.height
halfBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: width / 2, height: height))
halfBackgroundView?.backgroundColor = highlightedColor
self.addSubview(halfBackgroundView!)
self.sendSubview(toBack: halfBackgroundView!)
label.textColor = UIColor.white
addRoundHighlightView()
}
func addRoundHighlightView() {
let width = self.frame.size.width
let height = self.frame.size.height
roundHighlightView = UIView(frame: CGRect(x: (width - height) / 2, y: 0, width: height, height: height))
roundHighlightView?.backgroundColor = highlightedColor
roundHighlightView?.layer.cornerRadius = height / 2
self.addSubview(roundHighlightView!)
self.sendSubview(toBack: roundHighlightView!)
label.textColor = UIColor.white
}
func highlight() {
self.backgroundColor = highlightedColor
label.textColor = UIColor.white
}
func singleDatehighlight() {
self.backgroundColor = highlightedColor
label.textColor = UIColor.white
self.layer.cornerRadius = self.frame.height / 2
}
func disable() {
label.textColor = disabledColor
}
}
|
0 | //
// JSMGoodsDetailModel.swift
// JSMachine
// 商品详情model
// Created by gouyz on 2018/12/11.
// Copyright © 2018 gouyz. All rights reserved.
//
import UIKit
@objcMembers
class JSMGoodsDetailModel: LHSBaseModel {
/// 商品model
var goodsModel: JSMGoodsModel?
/// 图片地址
var goodImgList: [String] = [String]()
/// 图文详情url地址
var image_text_url: String? = ""
/// 产品参数url
var parameter_url: String? = ""
/// 关注 0:未关注,1:已关注
var follow: String? = "0"
override func setValue(_ value: Any?, forKey key: String) {
if key == "good_img"{
guard let datas = value as? [[String : String]] else { return }
for dict in datas {
goodImgList.append(dict["pic"]!)
}
}else if key == "shop_name"{
guard let datas = value as? [String : Any] else { return }
goodsModel = JSMGoodsModel(dict: datas)
}else {
super.setValue(value, forKey: key)
}
}
}
|
0 | //
// CustomView.swift
// CoreLocationTask
//
// Created by 양중창 on 2020/01/09.
// Copyright © 2020 didwndckd. All rights reserved.
//
import UIKit
class CustomView: UIView {
init() {
super.init(frame: .zero)
backgroundColor = .systemBackground
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
0 | //
// RealmHelper.swift
// iTax
//
// Created by Kamil Kowalski on 15.06.2016.
// Copyright © 2016 Kamil Kowalski. All rights reserved.
//
import Foundation
import RealmSwift
class RealmHelper {
/// Kolejkuje migrację dla bazy danych Realm
static func configureMigrations() {
let config = Realm.Configuration(
schemaVersion: 3,
migrationBlock: { migration, oldSchemaVersion in
})
Realm.Configuration.defaultConfiguration = config
}
} |