repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
wikimedia/wikipedia-ios
Wikipedia/Code/NotificationsCenterView.swift
1
9610
import UIKit final class NotificationsCenterView: SetupView { // MARK: - Nested Types enum EmptyOverlayStrings { static let noUnreadMessages = WMFLocalizedString("notifications-center-empty-no-messages", value: "You have no messages", comment: "Text displayed when no Notifications Center notifications are available.") static let notSubscribed = WMFLocalizedString("notifications-center-empty-not-subscribed", value: "You are not currently subscribed to any Wikipedia Notifications", comment: "Text displayed when user has not subscribed to any Wikipedia notifications.") static let checkingForNotifications = WMFLocalizedString("notifications-center-empty-checking-for-notifications", value: "Checking for notifications...", comment: "Text displayed when Notifications Center is checking for notifications.") } // MARK: - Properties lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: .zero, collectionViewLayout: tableStyleLayout()) collectionView.register(NotificationsCenterCell.self, forCellWithReuseIdentifier: NotificationsCenterCell.reuseIdentifier) collectionView.alwaysBounceVertical = true collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.refreshControl = refreshControl return collectionView }() lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.layer.zPosition = -100 return refreshControl }() private lazy var emptyScrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.isUserInteractionEnabled = false scrollView.showsVerticalScrollIndicator = false scrollView.contentInsetAdjustmentBehavior = .never scrollView.isHidden = true return scrollView }() private lazy var emptyOverlayStack: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.distribution = .equalSpacing stackView.alignment = .center stackView.spacing = 15 return stackView }() private lazy var emptyStateImageView: UIImageView = { let image = UIImage(named: "notifications-center-empty") let imageView = UIImageView(image: image) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit return imageView }() private lazy var emptyOverlayHeaderLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.wmf_font(.mediumBody, compatibleWithTraitCollection: traitCollection) label.adjustsFontForContentSizeCategory = true label.textAlignment = .center label.numberOfLines = 0 return label }() private lazy var emptyOverlaySubheaderLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection) label.adjustsFontForContentSizeCategory = true label.textAlignment = .center label.numberOfLines = 0 label.isUserInteractionEnabled = true return label }() // MARK: - Lifecycle override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory { emptyOverlayHeaderLabel.font = UIFont.wmf_font(.mediumBody, compatibleWithTraitCollection: traitCollection) emptyOverlaySubheaderLabel.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection) calculatedCellHeight = nil } if previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass { calculatedCellHeight = nil } } override func layoutSubviews() { super.layoutSubviews() // If the stack view content is approaching or greater than the visible view's height, allow scrolling to read all content emptyScrollView.alwaysBounceVertical = emptyOverlayStack.bounds.height > emptyScrollView.bounds.height - 100 } // MARK: - Setup override func setup() { backgroundColor = .white wmf_addSubviewWithConstraintsToEdges(collectionView) wmf_addSubviewWithConstraintsToEdges(emptyScrollView) emptyOverlayStack.addArrangedSubview(emptyStateImageView) emptyOverlayStack.addArrangedSubview(emptyOverlayHeaderLabel) emptyOverlayStack.addArrangedSubview(emptyOverlaySubheaderLabel) emptyScrollView.addSubview(emptyOverlayStack) NSLayoutConstraint.activate([ emptyScrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: emptyScrollView.frameLayoutGuide.widthAnchor), emptyScrollView.contentLayoutGuide.heightAnchor.constraint(greaterThanOrEqualTo: emptyScrollView.frameLayoutGuide.heightAnchor), emptyOverlayStack.centerXAnchor.constraint(equalTo: emptyScrollView.contentLayoutGuide.centerXAnchor), emptyOverlayStack.centerYAnchor.constraint(equalTo: emptyScrollView.contentLayoutGuide.centerYAnchor), emptyOverlayStack.topAnchor.constraint(greaterThanOrEqualTo: emptyScrollView.contentLayoutGuide.topAnchor, constant: 100), emptyOverlayStack.leadingAnchor.constraint(greaterThanOrEqualTo: emptyScrollView.contentLayoutGuide.leadingAnchor, constant: 25), emptyOverlayStack.trailingAnchor.constraint(lessThanOrEqualTo: emptyScrollView.contentLayoutGuide.trailingAnchor, constant: -25), emptyOverlayStack.bottomAnchor.constraint(lessThanOrEqualTo: emptyScrollView.contentLayoutGuide.bottomAnchor, constant: -100), emptyStateImageView.heightAnchor.constraint(equalToConstant: 185), emptyStateImageView.widthAnchor.constraint(equalToConstant: 185), emptyOverlayHeaderLabel.widthAnchor.constraint(equalTo: emptyOverlayStack.widthAnchor, multiplier: 3/4), emptyOverlaySubheaderLabel.widthAnchor.constraint(equalTo: emptyOverlayStack.widthAnchor, multiplier: 4/5) ]) } // MARK: - Public private var subheaderTapGR: UITapGestureRecognizer? func addSubheaderTapGestureRecognizer(target: Any, action: Selector) { let tap = UITapGestureRecognizer(target: target, action: action) self.subheaderTapGR = tap emptyOverlaySubheaderLabel.addGestureRecognizer(tap) } func updateEmptyVisibility(visible: Bool) { emptyScrollView.isHidden = !visible emptyScrollView.isUserInteractionEnabled = visible } func updateEmptyContent(headerText: String = "", subheaderText: String = "", subheaderAttributedString: NSAttributedString?) { emptyOverlayHeaderLabel.text = headerText if let subheaderAttributedString = subheaderAttributedString { emptyOverlaySubheaderLabel.attributedText = subheaderAttributedString subheaderTapGR?.isEnabled = true } else { emptyOverlaySubheaderLabel.text = subheaderText subheaderTapGR?.isEnabled = false } } func updateCalculatedCellHeightIfNeeded() { guard let firstCell = collectionView.visibleCells.first else { return } if self.calculatedCellHeight == nil { let calculatedCellHeight = firstCell.frame.size.height self.calculatedCellHeight = calculatedCellHeight } } // MARK: Private private var calculatedCellHeight: CGFloat? { didSet { if oldValue != calculatedCellHeight { collectionView.setCollectionViewLayout(tableStyleLayout(calculatedCellHeight: calculatedCellHeight), animated: false) } } } private func tableStyleLayout(calculatedCellHeight: CGFloat? = nil) -> UICollectionViewLayout { let heightDimension: NSCollectionLayoutDimension if let calculatedCellHeight = calculatedCellHeight { heightDimension = NSCollectionLayoutDimension.absolute(calculatedCellHeight) } else { heightDimension = NSCollectionLayoutDimension.estimated(150) } let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),heightDimension: heightDimension) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),heightDimension: heightDimension) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,subitems: [item]) let section = NSCollectionLayoutSection(group: group) let layout = UICollectionViewCompositionalLayout(section: section) return layout } } extension NotificationsCenterView: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground collectionView.backgroundColor = theme.colors.paperBackground refreshControl.tintColor = theme.colors.refreshControlTint emptyOverlayHeaderLabel.textColor = theme.colors.primaryText emptyOverlaySubheaderLabel.textColor = theme.colors.primaryText } }
mit
9058f900c10f5083d48e3077d2bce315
44.330189
260
0.730697
6.586703
false
false
false
false
superk589/DereGuide
DereGuide/Common/CGSSLiveFilter.swift
2
2572
// // CGSSLiveFilter.swift // DereGuide // // Created by zzk on 16/9/5. // Copyright © 2016 zzk. All rights reserved. // import UIKit struct CGSSLiveFilter: CGSSFilter { var liveTypes: CGSSLiveTypes var eventTypes: CGSSLiveEventTypes var difficultyTypes: CGSSLiveDifficultyTypes var searchText: String = "" init(typeMask: UInt, eventMask: UInt, difficultyMask: UInt) { liveTypes = CGSSLiveTypes.init(rawValue: typeMask) eventTypes = CGSSLiveEventTypes.init(rawValue: eventMask) difficultyTypes = CGSSLiveDifficultyTypes.init(rawValue: difficultyMask) } func filter(_ list: [CGSSLive]) -> [CGSSLive] { let result = list.filter { (v: CGSSLive) -> Bool in let r1: Bool = searchText == "" ? true : { let comps = searchText.components(separatedBy: " ") for comp in comps { if comp == "" { continue } let b1 = v.name.lowercased().contains(comp.lowercased()) if b1 { continue } else { return false } } return true }() let r2: Bool = { if liveTypes.contains(v.filterType) && eventTypes.contains(v.eventFilterType) { v.difficultyTypes = difficultyTypes if difficultyTypes == .masterPlus { if v.beatmapCount == 4 { return false } } return true } return false }() return r1 && r2 } return result } func save(to path: String) { toDictionary().write(toFile: path, atomically: true) } func toDictionary() -> NSDictionary { let dict = ["typeMask": liveTypes.rawValue, "eventMask": eventTypes.rawValue, "difficultyMask": difficultyTypes.rawValue] as NSDictionary return dict } init?(fromFile path: String) { guard let dict = NSDictionary.init(contentsOfFile: path) else { return nil } guard let typeMask = dict.object(forKey: "typeMask") as? UInt, let eventMask = dict.object(forKey: "eventMask") as? UInt, let difficultyMask = dict.object(forKey: "difficultyMask") as? UInt else { return nil } self.init(typeMask: typeMask, eventMask: eventMask, difficultyMask: difficultyMask) } }
mit
cbf20cf8db09d51c128b366934878d49
33.743243
204
0.539479
4.906489
false
false
false
false
podverse/podverse-ios
Podverse/FiltersTableHeaderView.swift
1
13097
// // FiltersTableHeaderView.swift // Podverse // // Created by Creon Creonopoulos on 10/3/17. // Copyright © 2017 Podverse LLC. All rights reserved. // import UIKit protocol FilterSelectionProtocol { func filterButtonTapped() func sortingButtonTapped() func sortByRecent() func sortByTop() func sortByTopWithTimeRange(timeRange: SortingTimeRange) } class FiltersTableHeaderView: UIView { var delegate:FilterSelectionProtocol? var filterTitle = "" { didSet { DispatchQueue.main.async { self.filterButton.setTitle(self.filterTitle + kDropdownCaret, for: .normal) } } } var sortingTitle = "" { didSet { DispatchQueue.main.async { self.sortingButton.setTitle(self.sortingTitle + kDropdownCaret, for: .normal) } } } let filterButton = UIButton() let sortingButton = UIButton() let topBorder = UIView() let bottomBorder = UIView() func setupViews(isBlackBg: Bool = false) { let titleColor:UIColor = isBlackBg ? .white : .black let borderColor:UIColor = isBlackBg ? .darkGray : .lightGray self.translatesAutoresizingMaskIntoConstraints = false self.filterButton.translatesAutoresizingMaskIntoConstraints = false self.sortingButton.translatesAutoresizingMaskIntoConstraints = false self.topBorder.translatesAutoresizingMaskIntoConstraints = false self.bottomBorder.translatesAutoresizingMaskIntoConstraints = false self.filterButton.setTitle(filterTitle, for: .normal) self.filterButton.setTitleColor(titleColor, for: .normal) self.filterButton.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold) self.filterButton.contentHorizontalAlignment = .left self.filterButton.addTarget(self, action: #selector(FiltersTableHeaderView.filterButtonTapped), for: .touchUpInside) self.addSubview(filterButton) let filterLeading = NSLayoutConstraint(item: self.filterButton, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 12) let filterTop = NSLayoutConstraint(item: self.filterButton, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) let filterHeight = NSLayoutConstraint(item: self.filterButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 44) let filterWidth = NSLayoutConstraint(item: self.filterButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 140) self.sortingButton.setTitle(sortingTitle, for: .normal) self.sortingButton.setTitleColor(titleColor, for: .normal) self.sortingButton.titleLabel?.font = UIFont.systemFont(ofSize: 16) self.sortingButton.contentHorizontalAlignment = .right self.sortingButton.addTarget(self, action: #selector(FiltersTableHeaderView.sortingButtonTapped), for: .touchUpInside) let sortingLeading = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: self.sortingButton, attribute: .trailing, multiplier: 1, constant: 12) let sortingTop = NSLayoutConstraint(item: self.sortingButton, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) let sortingHeight = NSLayoutConstraint(item: self.sortingButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 44) let sortingWidth = NSLayoutConstraint(item: self.sortingButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 140) self.addSubview(self.sortingButton) self.topBorder.backgroundColor = borderColor let topBorderLeading = NSLayoutConstraint(item: self.topBorder, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) let topBorderTop = NSLayoutConstraint(item: self.topBorder, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) let topBorderTrailing = NSLayoutConstraint(item: self.topBorder, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) let topBorderHeight = NSLayoutConstraint(item: self.topBorder, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0.5) self.addSubview(self.topBorder) self.bottomBorder.backgroundColor = borderColor let bottomBorderLeading = NSLayoutConstraint(item: self.bottomBorder, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) let bottomBorderBottom = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.bottomBorder, attribute: .bottom, multiplier: 1, constant: 0) let bottomBorderTrailing = NSLayoutConstraint(item: self.bottomBorder, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) let bottomBorderHeight = NSLayoutConstraint(item: self.bottomBorder, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0.5) self.addSubview(self.bottomBorder) self.addConstraints([filterLeading, filterTop, filterHeight, filterWidth, sortingLeading, sortingTop, sortingHeight, sortingWidth, topBorderLeading, topBorderTop, topBorderTrailing, topBorderHeight, bottomBorderLeading, bottomBorderBottom, bottomBorderTrailing, bottomBorderHeight]) } func showSortByMenu(vc: Any) { let alert = UIAlertController(title: "Sort By", message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: SortByOptions.top.text, style: .default, handler: { action in self.delegate?.sortByTop() })) alert.addAction(UIAlertAction(title: SortByOptions.recent.text, style: .default, handler: { action in self.delegate?.sortByRecent() })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) if let vc = vc as? UIViewController { vc.present(alert, animated: true, completion: nil) } } func showSortByTimeRangeMenu(vc: Any) { let alert = UIAlertController(title: "Time Range", message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: SortingTimeRange.day.text, style: .default, handler: { action in self.sortByTopWithTimeRange(timeRange: .day) })) alert.addAction(UIAlertAction(title: SortingTimeRange.week.text, style: .default, handler: { action in self.sortByTopWithTimeRange(timeRange: .week) })) alert.addAction(UIAlertAction(title: SortingTimeRange.month.text, style: .default, handler: { action in self.sortByTopWithTimeRange(timeRange: .month) })) alert.addAction(UIAlertAction(title: SortingTimeRange.year.text, style: .default, handler: { action in self.sortByTopWithTimeRange(timeRange: .year) })) alert.addAction(UIAlertAction(title: SortingTimeRange.allTime.text, style: .default, handler: { action in self.sortByTopWithTimeRange(timeRange: .allTime) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) if let vc = vc as? UIViewController { vc.present(alert, animated: true, completion: nil) } } func sortByRecent() { self.delegate?.sortByRecent() } func sortByTop() { self.delegate?.sortByTop() } func sortByTopWithTimeRange(timeRange: SortingTimeRange) { self.delegate?.sortByTopWithTimeRange(timeRange: timeRange) } @objc func filterButtonTapped() { self.delegate?.filterButtonTapped() } @objc func sortingButtonTapped() { self.delegate?.sortingButtonTapped() } }
agpl-3.0
4a651a6a161f51a5c314b7201a482377
45.439716
290
0.441814
7.168035
false
false
false
false
nuclearace/SwiftDiscord
Sources/SwiftDiscord/Guild/DiscordEmoji.swift
1
2530
// The MIT License (MIT) // Copyright (c) 2016 Erik Little // 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. /// Represents an Emoji. public struct DiscordEmoji { // MARK: Properties /// The snowflake id of the emoji. Nil if the emoji is a unicode emoji public let id: EmojiID? /// Whether this is a managed emoji. public let managed: Bool /// The name of the emoji or unicode representation if it's a unicode emoji. public let name: String /// Whether this emoji requires colons. public let requireColons: Bool /// An array of role snowflake ids this emoji is active for. public let roles: [RoleID] init(emojiObject: [String: Any]) { id = Snowflake(emojiObject["id"] as? String) managed = emojiObject.get("managed", or: false) name = emojiObject.get("name", or: "") requireColons = emojiObject.get("require_colons", or: false) roles = (emojiObject["roles"] as? [String])?.compactMap(Snowflake.init) ?? [] } static func emojisFromArray(_ emojiArray: [[String: Any]]) -> [EmojiID: DiscordEmoji] { var emojis = [EmojiID: DiscordEmoji]() for emoji in emojiArray { let emoji = DiscordEmoji(emojiObject: emoji) if let emojiID = emoji.id { emojis[emojiID] = emoji } else { DefaultDiscordLogger.Logger.debug("EmojisFromArray used on array with non-custom emoji", type: "DiscordEmoji") } } return emojis } }
mit
ebdf7e2154674409b38a304ada76238a
41.881356
126
0.687747
4.509804
false
false
false
false
DragonCherry/HFSwipeView
Example/HFSwipeView/AutoSlideController.swift
1
4147
// // AutoSlideController.swift // HFSwipeView // // Created by DragonCherry on 8/29/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import HFSwipeView import TinyLog class AutoSlideController: UIViewController { fileprivate let sampleCount: Int = 3 fileprivate var didSetupConstraints: Bool = false fileprivate lazy var swipeView: HFSwipeView = { let view = HFSwipeView.newAutoLayout() view.isDebug = true view.autoAlignEnabled = true view.circulating = true view.dataSource = self view.delegate = self view.pageControlHidden = true view.currentPage = 0 view.autoAlignEnabled = true return view }() fileprivate var currentView: UIView? fileprivate var itemSize: CGSize { return CGSize(width: 100, height: 100) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.automaticallyAdjustsScrollViewInsets = false } override func viewDidLoad() { super.viewDidLoad() view.addSubview(swipeView) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) swipeView.startAutoSlide(forTimeInterval: 5) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) swipeView.stopAutoSlide() } override func updateViewConstraints() { if !didSetupConstraints { swipeView.autoSetDimension(.height, toSize: itemSize.height) swipeView.autoPinEdge(toSuperviewEdge: .leading) swipeView.autoPinEdge(toSuperviewEdge: .trailing) swipeView.autoAlignAxis(toSuperviewAxis: .horizontal) didSetupConstraints = true } super.updateViewConstraints() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.swipeView.setBorder(0.5, color: .black) } func updateCellView(_ view: UIView, indexPath: IndexPath, isCurrent: Bool) { if let label = view as? UILabel { if isCurrent { // old view currentView?.backgroundColor = .white currentView = label currentView?.backgroundColor = .yellow } else { label.backgroundColor = .white } label.textAlignment = .center label.text = "\(indexPath.row)" label.setBorder(1, color: .black) } else { assertionFailure("failed to retrieve UILabel for index: \(indexPath.row)") } } } // MARK: - HFSwipeViewDelegate extension AutoSlideController: HFSwipeViewDelegate { func swipeView(_ swipeView: HFSwipeView, didFinishScrollAtIndexPath indexPath: IndexPath) { log("HFSwipeView(\(swipeView.tag)) -> \(indexPath.row)") } func swipeView(_ swipeView: HFSwipeView, didSelectItemAtPath indexPath: IndexPath) { log("HFSwipeView(\(swipeView.tag)) -> \(indexPath.row)") } func swipeView(_ swipeView: HFSwipeView, didChangeIndexPath indexPath: IndexPath, changedView view: UIView) { log("HFSwipeView(\(swipeView.tag)) -> \(indexPath.row)") } } // MARK: - HFSwipeViewDataSource extension AutoSlideController: HFSwipeViewDataSource { func swipeViewItemSize(_ swipeView: HFSwipeView) -> CGSize { return itemSize } func swipeViewItemCount(_ swipeView: HFSwipeView) -> Int { return sampleCount } func swipeView(_ swipeView: HFSwipeView, viewForIndexPath indexPath: IndexPath) -> UIView { return UILabel(frame: CGRect(origin: .zero, size: itemSize)) } func swipeView(_ swipeView: HFSwipeView, needUpdateViewForIndexPath indexPath: IndexPath, view: UIView) { updateCellView(view, indexPath: indexPath, isCurrent: false) } func swipeView(_ swipeView: HFSwipeView, needUpdateCurrentViewForIndexPath indexPath: IndexPath, view: UIView) { updateCellView(view, indexPath: indexPath, isCurrent: true) } }
mit
801fbc98fe78e8b6bd3fac2536468f83
32.168
116
0.644235
5.248101
false
false
false
false
bradhilton/Table
Table/UIViewController.swift
1
5470
// // UIViewController.swift // Table // // Created by Bradley Hilton on 2/16/18. // Copyright © 2018 Brad Hilton. All rights reserved. // extension Optional { mutating func pop() -> Wrapped? { defer { self = .none } return self } } extension Sequence { func first<U>(where hasValue: (Element) -> U?) -> U? { for element in self { if let value = hasValue(element) { return value } } return nil } } let swizzleViewControllerMethods: () -> () = { method_exchangeImplementations( class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewDidLoad))!, class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewDidLoad))! ) method_exchangeImplementations( class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewWillAppear))!, class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewWillAppear))! ) method_exchangeImplementations( class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewDidAppear))!, class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewDidAppear))! ) method_exchangeImplementations( class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewWillDisappear))!, class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewWillDisappear))! ) method_exchangeImplementations( class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewDidLayoutSubviews))!, class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewDidLayoutSubviews))! ) return {} }() extension UIViewController { public func firstSubview<T : UIView>(class: T.Type = T.self, key: AnyHashable? = nil) -> T? { return view.firstSubview(class: T.self, key: key) ?? children.first { $0.firstSubview(class: T.self, key: key) } } var configureView: ((UIViewController) -> ())? { get { return storage[\.configureView] } set { swizzleViewControllerMethods() if viewIsVisible && storage[\.configureView] == nil { storage[\.configureView] = newValue newValue?(self) } else { storage[\.configureView] = newValue } } } var previousViewFrame: CGRect { get { return storage[\.previousViewFrame, default: .zero] } set { storage[\.previousViewFrame] = newValue } } var updateViewOnLayout: Bool { get { return storage[\.updateViewOnLayout, default: false] } set { storage[\.updateViewOnLayout] = newValue } } var updateView: ((UIViewController) -> ())? { get { return storage[\.updateView] } set { swizzleViewControllerMethods() if viewIsVisible { storage[\.updateView] = updateViewOnLayout ? newValue : nil newValue?(self) } else { storage[\.updateView] = newValue } } } var updateNavigationItem: ((UIViewController) -> ())? { get { return storage[\.updateNavigationItem] } set { swizzleViewControllerMethods() if viewIsVisible { storage[\.updateNavigationItem] = nil newValue?(self) } else { storage[\.updateNavigationItem] = newValue } } } var viewIsVisible: Bool { return viewIfLoaded?.window != nil } var viewHasAppeared: Bool { get { return storage[\.viewHasAppeared, default: false] } set { storage[\.viewHasAppeared] = newValue } } @objc func swizzledViewDidLoad() { self.swizzledViewDidLoad() UIView.performWithoutAnimation { configureView?(self) if !updateViewOnLayout { updateView.pop()?(self) } } } @objc func swizzledViewWillAppear(animated: Bool) { self.swizzledViewWillAppear(animated: animated) UIView.performWithoutAnimation { if !updateViewOnLayout { updateView.pop()?(self) } updateNavigationItem.pop()?(self) } } @objc func swizzledViewDidLayoutSubviews() { self.swizzledViewDidLayoutSubviews() if updateViewOnLayout && view.frame != previousViewFrame { if previousViewFrame == .zero { UIView.performWithoutAnimation { updateView?(self) } } else { updateView?(self) } } previousViewFrame = view.frame } @objc func swizzledViewDidAppear(animated: Bool) { self.swizzledViewDidAppear(animated: animated) viewHasAppeared = true presentController() } @objc func swizzledViewWillDisappear(animated: Bool) { self.swizzledViewWillDisappear(animated: animated) viewHasAppeared = false } }
mit
aa67aea6112eae56e6993d3658111bd3
28.885246
115
0.581642
5.580612
false
false
false
false
bradhilton/Table
Table/UISplitViewController.swift
1
6986
// // UISplitViewController.swift // AlertBuilder // // Created by Bradley Hilton on 3/14/18. // //private class NavigationControllerDelegate : NSObject, UINavigationControllerDelegate { // // func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { // if let splitViewController = navigationController.splitViewController, !(viewController is UINavigationController) { // splitViewController.state?.willPopDetail() // } // } // //} // //private class SplitViewControllerDelegate : NSObject, UISplitViewControllerDelegate { // // func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool { // return !(splitViewController.state?.collapseDetailOntoMaster ?? false) // } // // func splitViewController(_ splitViewController: UISplitViewController, separateSecondaryFrom primaryViewController: UIViewController) -> UIViewController? { // return splitViewController.detailViewController ?? splitViewController.state?.detail.newViewController() // } // //} extension UISplitViewController { // public struct State { // public let master: Controller // public let detail: Controller // public let collapseDetailOntoMaster: Bool // public let willPopDetail: () -> () // public init(master: Controller, detail: Controller, collapseDetailOntoMaster: Bool, willPopDetail: @escaping () -> ()) { // self.master = master // self.detail = detail // self.collapseDetailOntoMaster = collapseDetailOntoMaster // self.willPopDetail = willPopDetail // } // } // // public var state: State? { // get { // return storage[\.state] // } // set { // storage[\.state] = newValue // delegate = defaultDelegate // guard let state = state else { return } // let masterViewController = self.masterViewController.flatMap { viewController in // guard viewController.type == state.master.type else { return nil } // viewController.update = state.master.update // return viewController // } ?? state.master.newViewController() // let detailViewController = self.detailViewController.flatMap { viewController in // guard viewController.type == state.detail.type else { return nil } // viewController.update = update // return viewController // } ?? state.detail.newViewController() // switch (isCollapsed, state.collapseDetailOntoMaster) { // case (true, true): // if !detailIsCollapsedOntoMaster { // viewControllers = [masterViewController] // showDetailViewController(detailViewController, sender: nil) // detailViewController.navigationController?.delegate = navigationControllerDelegate // } // case (true, false): // if detailIsCollapsedOntoMaster { // // } // viewControllers = [masterViewController] // case (false, _): // viewControllers = [masterViewController, detailViewController] // } // } // } // // var masterViewController: UIViewController? { // return viewControllers.first // } // // var detailViewController: UIViewController? { // return viewControllers.count == 2 ? viewControllers[1] : nil // } // // var detailIsCollapsedOntoMaster: Bool { // return (masterViewController as? UINavigationController)?.viewControllers.last.map { $0 is UINavigationController } ?? false // } // // private var defaultDelegate: SplitViewControllerDelegate { // return storage[\.defaultDelegate, default: SplitViewControllerDelegate()] // } // // private var navigationControllerDelegate: NavigationControllerDelegate { // return storage[\.navigationControllerDelegate, default: NavigationControllerDelegate()] // } } public class SplitNavigationController : UISplitViewController, UISplitViewControllerDelegate { public typealias State = (master: NavigationItem, detail: NavigationItem, showDetailWhenCompact: Bool) public var state: State { didSet { detailNavigationController.root = state.detail update(isCompact: traitCollection.horizontalSizeClass == .compact) } } public let masterNavigationController: UINavigationController public let detailNavigationController: UINavigationController public init() { state = (NavigationItem { _ in }, NavigationItem { _ in }, false) masterNavigationController = UINavigationController() detailNavigationController = UINavigationController() super.init(nibName: nil, bundle: nil) preferredDisplayMode = .allVisible masterNavigationController.root = state.master detailNavigationController.root = state.detail delegate = self } public override func viewDidLoad() { super.viewDidLoad() viewControllers = [masterNavigationController, detailNavigationController] } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool { update(isCompact: true) return true } public func splitViewController(_ splitViewController: UISplitViewController, separateSecondaryFrom primaryViewController: UIViewController) -> UIViewController? { update(isCompact: false) return detailNavigationController } private var willPop: (() -> ())? func update(isCompact: Bool) { if isCompact, state.showDetailWhenCompact { state.detail.willPop = state.detail.willPop ?? willPop if !state.master.stack.contains(where: { $0 === state.detail }) { state.master.stack.last?.next = state.detail } masterNavigationController.root = state.master } else { if let item = state.master.stack.first(where: { $0.next === state.detail }) { willPop = state.detail.willPop.pop() item.next = nil } masterNavigationController.root = state.master // MARK: Performance equality check if viewControllers != [masterNavigationController, detailNavigationController] { viewControllers = [masterNavigationController, detailNavigationController] } } } }
mit
e5f7be872d7da106378c8bb34bead334
40.583333
198
0.653593
5.665856
false
false
false
false
kickstarter/ios-ksapi
KsApi/models/lenses/UpdateLenses.swift
1
4097
import Prelude extension Update { public enum lens { public static let body = Lens<Update, String?>( view: { $0.body }, set: { Update(body: $0, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id, isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId, publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user, visible: $1.visible) } ) public static let commentsCount = Lens<Update, Int?>( view: { $0.commentsCount }, set: { Update(body: $1.body, commentsCount: $0, hasLiked: $1.hasLiked, id: $1.id, isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId, publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user, visible: $1.visible) } ) public static let id = Lens<Update, Int>( view: { $0.id }, set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $0, isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId, publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user, visible: $1.visible) } ) public static let likesCount = Lens<Update, Int?>( view: { $0.likesCount }, set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id, isPublic: $1.isPublic, likesCount: $0, projectId: $1.projectId, publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user, visible: $1.visible) } ) public static let projectId = Lens<Update, Int>( view: { $0.projectId }, set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id, isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $0, publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user, visible: $1.visible) } ) public static let publishedAt = Lens<Update, TimeInterval?>( view: { $0.publishedAt }, set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id, isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId, publishedAt: $0, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user, visible: $1.visible) } ) public static let sequence = Lens<Update, Int>( view: { $0.sequence }, set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id, isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId, publishedAt: $1.publishedAt, sequence: $0, title: $1.title, urls: $1.urls, user: $1.user, visible: $1.visible) } ) public static let title = Lens<Update, String>( view: { $0.title }, set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id, isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId, publishedAt: $1.publishedAt, sequence: $1.sequence, title: $0, urls: $1.urls, user: $1.user, visible: $1.visible) } ) public static let user = Lens<Update, User?>( view: { $0.user }, set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id, isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId, publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $0, visible: $1.visible) } ) public static let isPublic = Lens<Update, Bool>( view: { $0.isPublic }, set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id, isPublic: $0, likesCount: $1.likesCount, projectId: $1.projectId, publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user, visible: $1.visible) } ) } }
apache-2.0
62069dd8efc649f7f63883438c244da3
47.2
106
0.620698
3.312045
false
false
false
false
takeo-asai/math-puzzle
problems/47.swift
1
4328
struct Board: Hashable { let values: [[Bool]] init(_ values: [[Bool]]) { self.values = values } init(n: Int, var values: [Bool]) { var vs: [[Bool]] = [] while !values.isEmpty { vs += [Array(values[0..<n])] values = Array(values[n..<values.count]) } self.values = vs } func counts() -> [Int] { var cs: [Int] = [] for v in values { cs += [v.reduce(0) {$0 + ($1 ? 1 : 0)}] } for j in 0 ..< values[0].count { var c = 0 for i in 0 ..< values.count { c += values[i][j] ? 1 : 0 } cs += [c] } return cs } var hashValue: Int { get { return counts().description.hashValue } } } func == (lhs: Board, rhs: Board) -> Bool { return lhs.hashValue == rhs.hashValue } extension Array { // ExSwift // // Created by pNre on 03/06/14. // Copyright (c) 2014 pNre. All rights reserved. // // https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift // https://github.com/pNre/ExSwift/blob/master/LICENSE /** - parameter length: The length of each permutation - returns: All permutations of a given length within an array */ func permutation (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } else if length == 0 { return [[]] } else { var permutations: [[Element]] = [] let combinations = combination(length) for combination in combinations { var endArray: [[Element]] = [] var mutableCombination = combination permutations += self.permutationHelper(length, array: &mutableCombination, endArray: &endArray) } return permutations } } private func permutationHelper(n: Int, inout array: [Element], inout endArray: [[Element]]) -> [[Element]] { if n == 1 { endArray += [array] } for var i = 0; i < n; i++ { permutationHelper(n - 1, array: &array, endArray: &endArray) let j = n % 2 == 0 ? i : 0 let temp: Element = array[j] array[j] = array[n - 1] array[n - 1] = temp } return endArray } func combination (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } var indexes: [Int] = (0..<length).reduce([]) {$0 + [$1]} var combinations: [[Element]] = [] let offset = self.count - indexes.count while true { var combination: [Element] = [] for index in indexes { combination.append(self[index]) } combinations.append(combination) var i = indexes.count - 1 while i >= 0 && indexes[i] == i + offset { i-- } if i < 0 { break } i++ let start = indexes[i-1] + 1 for j in (i-1)..<indexes.count { indexes[j] = start + j - i + 1 } } return combinations } /** - parameter length: The length of each permutations - returns: All of the permutations of this array of a given length, allowing repeats */ func repeatedPermutation(length: Int) -> [[Element]] { if length < 1 { return [] } var indexes: [[Int]] = [] indexes.repeatedPermutationHelper([], length: length, arrayLength: self.count, indexes: &indexes) return indexes.map({ $0.map({ i in self[i] }) }) } private func repeatedPermutationHelper(seed: [Int], length: Int, arrayLength: Int, inout indexes: [[Int]]) { if seed.count == length { indexes.append(seed) return } for i in (0..<arrayLength) { var newSeed: [Int] = seed newSeed.append(i) self.repeatedPermutationHelper(newSeed, length: length, arrayLength: arrayLength, indexes: &indexes) } } } let n = 4 var cache: [Board: Int] = [: ] for v in [true, false].repeatedPermutation(n*n) { let b = Board(n: n, values: v) if let c = cache[b] { cache[b] = c + 1 } else { cache[b] = 1 } } let f = cache.filter {_, value in value == 1} print(f.count)
mit
320817c3fff8da860de5b9a1c6c74047
29.055556
112
0.512015
3.860839
false
false
false
false
Dean151/TDPeopleStackView
TDPeopleStackView/Classes/TDPeopleStackView.swift
1
7426
// // TDPeopleStackView.swift // Pods // // Created by Thomas Durand on 01/05/2016. // // import UIKit // MARK: - Data Source @objc public protocol TDPeopleStackViewDataSource: class { func numberOfPeopleInStackView(peopleStackView: TDPeopleStackView) -> Int optional func peopleStackView(peopleStackView: TDPeopleStackView, imageAtIndex index: Int) -> UIImage? optional func peopleStackView(peopleStackView: TDPeopleStackView, placeholderTextAtIndex index: Int) -> String? } // MARK: - Delegate @objc public protocol TDPeopleStackViewDelegate: class { /** Should return the button to show in the button for the peopleStackView. - parameter peopleStackView: the instance of `TDPeopleStackView` for the button - returns: A button to show in the peopleStackView */ optional func buttonForPeopleStackView(peopleStackView: TDPeopleStackView) -> UIButton? /** The text to show in the button for the peopleStackView. Will not be called when `buttonForPeopleStackView(_:)` is called - parameter peopleStackView: the instance of `TDPeopleStackView` for the button - returns: A String to show in the button */ optional func titleForButtonInPeopleStackView(peopleStackView: TDPeopleStackView) -> String? /** Will be called when the button from an instance of a `TDPeopleStackView` is pressed - parameter button: The button that have been pressed - parameter peopleStackView: the instance of `TDPeopleStackView` that received the press event */ optional func peopleStackViewButtonPressed(button: UIButton, peopleStackView: TDPeopleStackView) } // MARK: - Public properties @objc public class TDPeopleStackView: UIView { /** Constant that allow to set the space between circles. Below 1, there will be an overlap between circles Default value is 0.75 */ public var overlapConstant: CGFloat = 0.75 { didSet { if !firstLayoutDone { return } reloadData() } } /** The maximum number of circle to show before folding. Set to 0 for unlimited */ public var maxNumberOfCircles: Int = 0 { didSet { if !firstLayoutDone { return } reloadData() } } /** The color of the people circle's background when there is no image to show */ public var placeholderBackgroundColor = UIColor.lightGrayColor() { didSet { if !firstLayoutDone { return } reloadData() } } /** The color of the people circle's text when there is no image to show */ public var placeholderTextColor = UIColor.whiteColor() { didSet { if !firstLayoutDone { return } reloadData() } } /** The font of the people circle's text when there is no image to show */ public var placeholderTextFont: UIFont = UIFont.systemFontOfSize(24) { didSet { if !firstLayoutDone { return } reloadData() } } /** The data source for this `PeopleStackView` instance */ public var dataSource: TDPeopleStackViewDataSource? /** The delegate for this `PeopleStackView` instance */ public var delegate: TDPeopleStackViewDelegate? private var firstLayoutDone = false public override func layoutSubviews() { super.layoutSubviews() firstLayoutDone = true reloadData() } @objc private func buttonPressed(sender: UIButton) { self.delegate?.peopleStackViewButtonPressed?(sender, peopleStackView: self) } } // MARK: - Drawing extension TDPeopleStackView { public func reloadData() { // Remove all subviews subviews.forEach({ $0.removeFromSuperview() }) // Create the show more button if needed var button: UIButton? if let fullButton = delegate?.buttonForPeopleStackView?(self) { button = fullButton } else if let buttonText = delegate?.titleForButtonInPeopleStackView?(self) { button = UIButton(type: .System) button?.setTitle(buttonText, forState: .Normal) button?.sizeToFit() } if let button = button { button.frame = CGRectMake(bounds.width - button.bounds.width, (bounds.height-button.bounds.height)/2, button.bounds.width, button.bounds.height) button.addTarget(self, action: #selector(TDPeopleStackView.buttonPressed(_:)), forControlEvents: .TouchUpInside) addSubview(button) } // Calculate the size of circles let circleDiameter = min(bounds.width, bounds.height) let circleSize = CGSizeMake(circleDiameter, circleDiameter) for index in 0..<(dataSource?.numberOfPeopleInStackView(self) ?? 0) { let origin = CGPointMake(circleDiameter * CGFloat(index) * overlapConstant, 0) let rect = CGRect(origin: origin, size: circleSize) // Calculate next circule to know when we should stop the loop let nextOrigin = CGPointMake(circleDiameter * CGFloat(index+1) * overlapConstant, 0) let nextRect = CGRect(origin: nextOrigin, size: circleSize) let willDrawLastCircle = nextRect.origin.x + nextRect.width > (bounds.width - (button?.bounds.width ?? 0) ) || (maxNumberOfCircles > 0 && index+1 > maxNumberOfCircles) var circleView: UIView! if let image = dataSource?.peopleStackView?(self, imageAtIndex: index) where !willDrawLastCircle { // We have an image, and it's not the last to be drawn let imageView = UIImageView(frame: rect) imageView.image = image imageView.contentMode = .ScaleAspectFill circleView = imageView } else { // We create a label to show initials or the number of people for the last circle let label = UILabel(frame: rect) label.textColor = placeholderTextColor label.textAlignment = .Center if willDrawLastCircle { if #available(iOS 8.2, *) { label.font = UIFont.systemFontOfSize(30, weight: UIFontWeightThin) } else { label.font = UIFont(name: "HelveticaNeue-Thin", size: 30)! } label.text = "\(dataSource?.numberOfPeopleInStackView(self) ?? 0)" } else { label.font = placeholderTextFont label.text = dataSource?.peopleStackView?(self, placeholderTextAtIndex: index) } circleView = label } circleView.layer.cornerRadius = circleDiameter/2 circleView.clipsToBounds = true circleView.layer.borderColor = UIColor.whiteColor().CGColor circleView.layer.borderWidth = 1.0 circleView.backgroundColor = self.placeholderBackgroundColor addSubview(circleView) if willDrawLastCircle { break; } } setNeedsDisplay() } }
mit
7c29f4db9b0fe5d8a677c22e3497f900
34.701923
156
0.610288
5.448276
false
false
false
false
firebase/firebase-ios-sdk
scripts/health_metrics/generate_code_coverage_report/Sources/Utils/MetricsServiceRequest.swift
1
2852
/* * Copyright 2021 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif public func sendMetricsServiceRequest(repo: String, commits: String, jsonContent: Data, token: String, is_presubmit: Bool, branch: String?, pullRequest: Int?, pullRequestNote: String?, baseCommit: String?) { var request: URLRequest var semaphore = DispatchSemaphore(value: 0) let endpoint = "https://api.firebase-sdk-health-metrics.com/repos/\(repo)/commits/\(commits)/reports?" var pathPara: [String] = [] if is_presubmit { guard let pr = pullRequest else { print( "The pull request number should be specified for an API pull-request request to the Metrics Service." ) return } guard let bc = baseCommit else { print( "Base commit hash should be specified for an API pull-request request to the Metrics Service." ) return } pathPara.append("pull_request=\(String(pr))") if let note = pullRequestNote { let compatible_url_format_note = note .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! pathPara.append("note=\(compatible_url_format_note))") } pathPara.append("base_commit=\(bc)") } else { guard let branch = branch else { print("Targeted merged branch should be specified.") return } pathPara.append("branch=\(branch)") } let webURL = endpoint + pathPara.joined(separator: "&") guard let metricsServiceURL = URL(string: webURL) else { print("URL Path \(webURL) is not valid.") return } request = URLRequest(url: metricsServiceURL, timeoutInterval: Double.infinity) request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" request.httpBody = jsonContent let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data else { print(String(describing: error)) return } print(String(data: data, encoding: .utf8)!) semaphore.signal() } task.resume() semaphore.wait() }
apache-2.0
ab5c045284509f77e9966987a8caa45e
33.361446
109
0.669705
4.505529
false
false
false
false
danielsaidi/KeyboardKit
Tests/KeyboardKitTests/Layout/Providers/StandardKeyboardLayoutProviderTests.swift
1
3068
// // StandardKeyboardLayoutProviderTests.swift // KeyboardKit // // Created by Daniel Saidi on 2021-02-17. // Copyright © 2021 Daniel Saidi. All rights reserved. // import Quick import Nimble import KeyboardKit class StandardKeyboardLayoutProviderTests: QuickSpec { override func spec() { var provider: StandardKeyboardLayoutProvider! var inputProvider: MockKeyboardInputSetProvider! var context: MockKeyboardContext! var device: MockDevice! beforeEach { context = MockKeyboardContext() device = MockDevice() context.device = device inputProvider = MockKeyboardInputSetProvider() inputProvider.alphabeticInputSetValue = AlphabeticKeyboardInputSet(rows: KeyboardInputRows([["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]])) inputProvider.numericInputSetValue = NumericKeyboardInputSet(rows: KeyboardInputRows([["1", "2", "3"], ["1", "2", "3"], ["1", "2", "3"]])) inputProvider.symbolicInputSetValue = SymbolicKeyboardInputSet(rows: KeyboardInputRows([[",", ".", "-"], [",", ".", "-"], [",", ".", "-"]])) provider = StandardKeyboardLayoutProvider( inputSetProvider: inputProvider, dictationReplacement: .go) } describe("keyboard layout for context") { it("is phone layout if context device is phone") { device.userInterfaceIdiomValue = .phone let layout = provider.keyboardLayout(for: context) let phoneLayout = provider.iPhoneProvider.keyboardLayout(for: context) let padLayout = provider.iPadProvider.keyboardLayout(for: context) expect(layout.items).to(equal(phoneLayout.items)) expect(layout.items).toNot(equal(padLayout.items)) } it("is pad layout if context device is pad") { device.userInterfaceIdiomValue = .pad let layout = provider.keyboardLayout(for: context) let phoneLayout = provider.iPhoneProvider.keyboardLayout(for: context) let padLayout = provider.iPadProvider.keyboardLayout(for: context) expect(layout.items).toNot(equal(phoneLayout.items)) expect(layout.items).to(equal(padLayout.items)) } } describe("registering input set provider") { it("changes the provider instance for all providers") { let newInputProvider = MockKeyboardInputSetProvider() provider.register(inputSetProvider: newInputProvider) expect(provider.inputSetProvider).toNot(be(inputProvider)) expect(provider.inputSetProvider).to(be(newInputProvider)) expect(provider.iPhoneProvider.inputSetProvider).to(be(newInputProvider)) expect(provider.iPadProvider.inputSetProvider).to(be(newInputProvider)) } } } }
mit
161592f8d7ad1d13653e06c080cc141a
43.449275
156
0.606782
5.154622
false
false
false
false
loudnate/LoopKit
LoopKitUI/Views/SuspendResumeTableViewCell.swift
1
2276
// // SuspendResumeTableViewCell.swift // LoopKitUI // // Created by Pete Schwamb on 11/16/18. // Copyright © 2018 LoopKit Authors. All rights reserved. // import LoopKit public class SuspendResumeTableViewCell: TextButtonTableViewCell { public enum Action { case suspend case resume } public var shownAction: Action { switch basalDeliveryState { case .active, .suspending, .tempBasal, .cancelingTempBasal, .initiatingTempBasal: return .suspend case .suspended, .resuming: return .resume } } private func updateTextLabel() { switch self.basalDeliveryState { case .active, .tempBasal: textLabel?.text = LocalizedString("Suspend Delivery", comment: "Title text for button to suspend insulin delivery") case .suspending: self.textLabel?.text = LocalizedString("Suspending", comment: "Title text for button when insulin delivery is in the process of being stopped") case .suspended: textLabel?.text = LocalizedString("Resume Delivery", comment: "Title text for button to resume insulin delivery") case .resuming: self.textLabel?.text = LocalizedString("Resuming", comment: "Title text for button when insulin delivery is in the process of being resumed") case .initiatingTempBasal: self.textLabel?.text = LocalizedString("Starting Temp Basal", comment: "Title text for suspend resume button when temp basal starting") case .cancelingTempBasal: self.textLabel?.text = LocalizedString("Canceling Temp Basal", comment: "Title text for suspend resume button when temp basal canceling") } } private func updateLoadingState() { self.isLoading = { switch self.basalDeliveryState { case .suspending, .resuming, .initiatingTempBasal, .cancelingTempBasal: return true default: return false } }() self.isEnabled = !self.isLoading } public var basalDeliveryState: PumpManagerStatus.BasalDeliveryState = .active(Date()) { didSet { updateTextLabel() updateLoadingState() } } }
mit
7596c1c068bb2c5670e24dd401cebd79
35.111111
155
0.642198
5.290698
false
false
false
false
raphaelmor/GeoJSON
GeoJSONTests/Geometry/PolygonTests.swift
1
5922
// PolygonTests.swift // // The MIT License (MIT) // // Copyright (c) 2014 Raphaël Mor // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import XCTest import GeoJSON class PolygonTests: XCTestCase { var geoJSON: GeoJSON! var twoRingPolygon: Polygon! override func setUp() { super.setUp() geoJSON = geoJSONfromString("{ \"type\": \"Polygon\", \"coordinates\": [ [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [0.0, 0.0]] ] }") let firstRing = LineString(points:[ Point(coordinates:[0.0,0.0])!, Point(coordinates:[1.0,1.0])!, Point(coordinates:[2.0,2.0])!, Point(coordinates:[0.0,0.0])! ])! let secondRing = LineString(points: [ Point(coordinates:[10.0,10.0])!, Point(coordinates:[11.0,11.0])!, Point(coordinates:[12.0,12.0])!, Point(coordinates:[10.0,10.0])! ])! twoRingPolygon = Polygon(linearRings: [firstRing, secondRing]) } override func tearDown() { geoJSON = nil twoRingPolygon = nil super.tearDown() } // MARK: - Nominal cases // MARK: Decoding func testBasicPolygonShouldBeRecognisedAsSuch() { XCTAssertEqual(geoJSON.type, GeoJSONType.Polygon) } func testPolygonShouldBeAGeometry() { XCTAssertTrue(geoJSON.isGeometry()) } func testEmptyPolygonShouldBeParsedCorrectly() { geoJSON = geoJSONfromString("{ \"type\": \"Polygon\", \"coordinates\": [] }") if let geoPolygon = geoJSON.polygon { XCTAssertEqual(geoPolygon.linearRings.count, 0) } else { XCTFail("Polygon not parsed properly") } } func testBasicPolygonShouldBeParsedCorrectly() { if let geoPolygon = geoJSON.polygon { XCTAssertEqual(geoPolygon.linearRings.count, 1) XCTAssertTrue(geoPolygon.linearRings[0].isLinearRing()) XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][0].longitude, 0.0, 0.000001) XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][0].latitude, 0.0, 0.000001) XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][1].longitude, 1.0, 0.000001) XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][1].latitude, 1.0, 0.000001) XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][2].longitude, 2.0, 0.000001) XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][2].latitude, 2.0, 0.000001) XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][3].longitude, 0.0, 0.000001) XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][3].latitude, 0.0, 0.000001) } else { XCTFail("Polygon not parsed Properly") } } // MARK: Encoding func testBasicPolygonShouldBeEncoded() { XCTAssertNotNil(twoRingPolygon,"Valid Polygon should be encoded properly") if let jsonString = stringFromJSON(twoRingPolygon.json()) { XCTAssertEqual(jsonString, "[[[0,0],[1,1],[2,2],[0,0]],[[10,10],[11,11],[12,12],[10,10]]]") } else { XCTFail("Valid Polygon should be encoded properly") } } func testZeroRingPolygonShouldBeValid() { let zeroRingPolygon = Polygon(linearRings:[])! if let jsonString = stringFromJSON(zeroRingPolygon.json()) { XCTAssertEqual(jsonString, "[]") }else { XCTFail("Empty Polygon should be encoded properly") } } func testPolygonShouldHaveTheRightPrefix() { XCTAssertEqual(twoRingPolygon.prefix,"coordinates") } func testBasicPolygonInGeoJSONShouldBeEncoded() { let geoJSON = GeoJSON(polygon: twoRingPolygon) if let jsonString = stringFromJSON(geoJSON.json()) { checkForSubstring("\"coordinates\":[[[0,0],[1,1],[2,2],[0,0]],[[10,10],[11,11],[12,12],[10,10]]]", jsonString) checkForSubstring("\"type\":\"Polygon\"", jsonString) } else { XCTFail("Valid Polygon in GeoJSON should be encoded properly") } } // MARK: - Error cases // MARK: Decoding func testPolygonWithoutCoordinatesShouldRaiseAnError() { geoJSON = geoJSONfromString("{ \"type\": \"Polygon\"}") if let error = geoJSON.error { XCTAssertEqual(error.domain, GeoJSONErrorDomain) XCTAssertEqual(error.code, GeoJSONErrorInvalidGeoJSONObject) } else { XCTFail("Invalid Polygon should raise an invalid object error") } } func testPolygonWithAnInvalidLinearRingShouldRaiseAnError() { geoJSON = geoJSONfromString("{ \"type\": \"Polygon\", \"coordinates\": [ [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]] ] }") if let error = geoJSON.error { XCTAssertEqual(error.domain, GeoJSONErrorDomain) XCTAssertEqual(error.code, GeoJSONErrorInvalidGeoJSONObject) } else { XCTFail("Invalid Polygon should raise an invalid object error") } } func testIllFormedMultiLineStringShouldRaiseAnError() { geoJSON = geoJSONfromString("{ \"type\": \"Polygon\", \"coordinates\": [ [0.0, 1.0], {\"invalid\" : 2.0} ] }") if let error = geoJSON.error { XCTAssertEqual(error.domain, GeoJSONErrorDomain) XCTAssertEqual(error.code, GeoJSONErrorInvalidGeoJSONObject) } else { XCTFail("Invalid Polygon should raise an invalid object error") } } // MARK: Encoding }
mit
7b340dfb0ed7dc9bdbab8b0f7ca6d173
32.642045
129
0.708833
3.780971
false
true
false
false
devpunk/cartesian
cartesian/View/DrawProject/Size/VDrawProjectSizeDimension.swift
1
3412
import UIKit class VDrawProjectSizeDimension:UIView { private(set) weak var textField:UITextField! private let kLabelHeight:CGFloat = 45 private let kLabelBottom:CGFloat = -5 private let kFieldMargin:CGFloat = 19 private let kFieldTop:CGFloat = 25 private let kCornerRadius:CGFloat = 4 private let kBackgroundMargin:CGFloat = 9 private let kBorderWidth:CGFloat = 1 init(title:String) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.textAlignment = NSTextAlignment.center label.font = UIFont.regular(size:16) label.textColor = UIColor.black label.text = title let textField:UITextField = UITextField() textField.borderStyle = UITextBorderStyle.none textField.translatesAutoresizingMaskIntoConstraints = false textField.clipsToBounds = true textField.backgroundColor = UIColor.clear textField.placeholder = NSLocalizedString("VDrawProjectSizeDimension_placeholder", comment:"") textField.keyboardType = UIKeyboardType.numbersAndPunctuation textField.keyboardAppearance = UIKeyboardAppearance.light textField.spellCheckingType = UITextSpellCheckingType.no textField.autocorrectionType = UITextAutocorrectionType.no textField.autocapitalizationType = UITextAutocapitalizationType.none textField.clearButtonMode = UITextFieldViewMode.never textField.returnKeyType = UIReturnKeyType.next textField.tintColor = UIColor.black textField.textColor = UIColor.black textField.font = UIFont.numeric(size:20) self.textField = textField let background:UIView = UIView() background.backgroundColor = UIColor.white background.translatesAutoresizingMaskIntoConstraints = false background.clipsToBounds = true background.isUserInteractionEnabled = false background.layer.cornerRadius = kCornerRadius background.layer.borderColor = UIColor(white:0, alpha:0.1).cgColor background.layer.borderWidth = kBorderWidth addSubview(label) addSubview(background) addSubview(textField) NSLayoutConstraint.bottomToBottom( view:label, toView:self, constant:kLabelBottom) NSLayoutConstraint.height( view:label, constant:kLabelHeight) NSLayoutConstraint.equalsHorizontal( view:label, toView:self) NSLayoutConstraint.topToTop( view:textField, toView:self, constant:kFieldTop) NSLayoutConstraint.bottomToTop( view:textField, toView:label) NSLayoutConstraint.equalsHorizontal( view:textField, toView:self, margin:kFieldMargin) NSLayoutConstraint.equals( view:textField, toView:background, margin:kBackgroundMargin) } required init?(coder:NSCoder) { return nil } }
mit
d775280a9f17412ffdbaf3765c7dc852
35.297872
102
0.666471
6.017637
false
false
false
false
sunshineclt/NKU-Helper
NKU Helper/功能/评教/CourseToEvaluate.swift
1
647
// // CourseToEvaluate.swift // NKU Helper // // Created by 陈乐天 on 1/21/16. // Copyright © 2016 陈乐天. All rights reserved. // import Foundation class CourseToEvaluate { var className: String var teacherName: String var hasEvaluated: Bool var index: Int init(className: String, teacherName: String, hasEvaluated: String, index: Int) { self.className = className self.teacherName = teacherName if hasEvaluated == "未评价" { self.hasEvaluated = false } else { self.hasEvaluated = true } self.index = index } }
gpl-3.0
7d8a76fe13dab8371f1611d13a9bfa65
19.933333
84
0.593949
4.131579
false
false
false
false
RaviDesai/RSDRestServices
Pod/Classes/ResponseParsers/APIJSONSerializableResponseParser.swift
1
3063
// // JSONResponseParser.swift // CEVFoundation // // Created by Ravi Desai on 6/10/15. // Copyright (c) 2015 CEV. All rights reserved. // import Foundation import RSDSerialization public class APIJSONSerializableResponseParser<T: SerializableFromJSON> : APIResponseParserProtocol { public init() { self.acceptTypes = ["application/json"] } public init(versionRepresentation: ModelResourceVersionRepresentation, vendor: String, version: String) { if (versionRepresentation == ModelResourceVersionRepresentation.CustomContentType) { self.acceptTypes = ["application/\(vendor).v\(version)+json"] } else { self.acceptTypes = ["application/json"] } } public init(acceptTypes: [String]) { self.acceptTypes = acceptTypes } public private(set) var acceptTypes: [String]? public class func convertToSerializable(response: NetworkResponse) -> (T?, NSError?) { let (jsonOptional, error) = response.getJSON() if let json:JSON = jsonOptional { if let obj = T.createFromJSON(json) { return (obj, nil) } else { let userInfo = [NSLocalizedDescriptionKey: "JSON deserialization error", NSLocalizedFailureReasonErrorKey: "JSON deserialization error"] let jsonError = NSError(domain: "com.careevolution.direct", code: 48103001, userInfo: userInfo) return (nil, jsonError) } } else { return (nil, error) } } public class func convertToSerializableArray(response: NetworkResponse) -> ([T]?, NSError?) { let (jsonOptional, error) = response.getJSON() if let json:JSON = jsonOptional { if let objArray = ModelFactory<T>.createFromJSONArray(json) { return (objArray.map { $0 }, nil) } else { let userInfo = [NSLocalizedDescriptionKey: "JSON deserialization error", NSLocalizedFailureReasonErrorKey: "JSON deserialization error"] let jsonError = NSError(domain: "com.careevolution.direct", code: 48103001, userInfo: userInfo) return (nil, jsonError) } } else { return (nil, error) } } public func Parse(response: NetworkResponse) -> (T?, NSError?) { let (jsonOptional, jsonError) = response.getJSON() if (jsonOptional != nil) { return APIJSONSerializableResponseParser.convertToSerializable(response) } let responseError = response.getError() ?? jsonError; return (nil, responseError) } public func ParseToArray(response: NetworkResponse) -> ([T]?, NSError?) { let (jsonOptional, jsonError) = response.getJSON() if (jsonOptional != nil) { return APIJSONSerializableResponseParser.convertToSerializableArray(response) } let responseError = response.getError() ?? jsonError; return (nil, responseError) } }
mit
a861fdd28dc76cab7963a10a5ca11427
37.3
152
0.62096
5.06281
false
false
false
false
Syniverse/Push-Notification-SDK
ios/demo/Downloader/NotificationService.swift
1
3765
// // NotificationService.swift // Downloader // // Created by Slav Sarafski on 26/10/16. // Copyright © 2016 softavail. All rights reserved. // import UserNotifications import SCGPushSDK import MobileCoreServices @available(iOSApplicationExtension 10.0, *) class NotificationService: UNNotificationServiceExtension { var hasApppId: Bool = false var hasToken: Bool = false var hasBaseUrl: Bool = false override init () { super.init() if let defaults:UserDefaults = UserDefaults(suiteName: "group.com.syniverse.scg.push.demo") { if let appId = defaults.string(forKey: "scg-push-appid") as String! { debugPrint("Info: [SCGPush] successfully assigned appid") SCGPush.sharedInstance().appID = appId self.hasApppId = true } if let token = defaults.string(forKey: "scg-push-token") as String! { debugPrint("Info: [SCGPush] successfully assigned acces token") SCGPush.sharedInstance().accessToken = token self.hasToken = true } if let baseUrl = defaults.string(forKey: "scg-push-baseurl") as String! { debugPrint("Info: [SCGPush] successfully assigned baseurl") SCGPush.sharedInstance().callbackURI = baseUrl self.hasBaseUrl = true } } else { debugPrint("Error: [SCGPush] could not access defaults with suite group.com.syniverse.scg.push.demo") } } override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { if !self.hasToken || !self.hasApppId || !self.hasBaseUrl { debugPrint("Error: [SCGPush] wont load attachment cause baseurl, accesstoken or appid is missing") contentHandler(request.content.copy() as! UNNotificationContent) } else if let attachmentID = request.content.userInfo["scg-attachment-id"] as? String, let messageID = request.content.userInfo["scg-message-id"] as? String { // Download the attachment debugPrint("Notice: [SCGPush] will try to load attachment \(attachmentID) for message \(messageID)") SCGPush.sharedInstance().loadAttachment(withMessageId: messageID, andAttachmentId: attachmentID, completionBlock: { (contentUrl, contentType) in debugPrint("Info: [SCGPush] successfully loaded attachment with content-type: \(contentType)") let bestAttemptContent:UNMutableNotificationContent = request.content.mutableCopy() as! UNMutableNotificationContent let options = [UNNotificationAttachmentOptionsTypeHintKey: contentType] if let attachment = try? UNNotificationAttachment(identifier: attachmentID, url: contentUrl, options: options) { bestAttemptContent.attachments = [attachment] } else { debugPrint("Error: [SCGPush] could not create attachment with content-type: \(contentType)") } contentHandler(bestAttemptContent) }, failureBlock: { (error) in debugPrint("Error: [SCGPush] failed to load attachment: \(attachmentID)") contentHandler(request.content.mutableCopy() as! UNMutableNotificationContent) }) } else { debugPrint("Error: [SCGPush] wont load attachment cause accesstoken or appid is missing") contentHandler(request.content.copy() as! UNNotificationContent) } } override func serviceExtensionTimeWillExpire() { // No best attempt from us } }
mit
4ec3005165427d44a63f3c0ded22deee
44.349398
166
0.63762
5.220527
false
false
false
false
Jamnitzer/MBJ_ImageProcessing
MBJ_ImageProcessing/MBJ_ImageProcessing/MBJContext.swift
1
1330
// // MBEContext.m // ImageProcessing // // Created by Warren Moore on 10/8/14. // Copyright (c) 2014 Metal By Example. All rights reserved. //------------------------------------------------------------------------ // converted to Swift by Jamnitzer (Jim Wrenholt) //------------------------------------------------------------------------ import Foundation import Metal //------------------------------------------------------------------------------ class MBJContext { var device:MTLDevice! = nil var library:MTLLibrary! = nil var commandQueue:MTLCommandQueue! = nil //------------------------------------------------------------------------ init(device:MTLDevice?) { if (device != nil) { self.device = device } else { self.device = MTLCreateSystemDefaultDevice() } self.library = self.device!.newDefaultLibrary() self.commandQueue = self.device!.newCommandQueue() } //------------------------------------------------------------------------ class func newContext() -> MBJContext { return MBJContext(device:nil) } //------------------------------------------------------------------------ } //------------------------------------------------------------------------------
mit
5c7e9e350830184510830439fc7aa36b
31.439024
80
0.357895
6.363636
false
false
false
false
AmirDaliri/BaboonProject
Baboon/Baboon/TableViewController.swift
1
908
// // TableViewController.swift // Baboon // // Created by Amir Daliri on 3/22/17. // Copyright © 2017 Baboon. All rights reserved. // import UIKit class TableViewController: UITableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let detail = segue.destination as? DetailViewController, let selectedIndexPath = tableView.indexPathForSelectedRow { detail.detailText = "Item #\(selectedIndexPath.row)" } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = "Item #\(indexPath.row)" return cell } }
mit
908d6b2f6e6c8cd407c9bf0e668afe7b
29.233333
109
0.68247
4.902703
false
false
false
false
tripleCC/GanHuoCode
GanHuo/Models/GanHuoObject.swift
1
4631
// // GanHuoObject.swift // // // Created by tripleCC on 16/3/4. // // import Foundation import CoreData import SwiftyJSON //@objc(GanHuoObject) /* http://stackoverflow.com/questions/25076276/unable-to-find-specific-subclass-of-nsmanagedobject */ public final class GanHuoObject: NSManagedObject ,TPCCoreDataHelper { public typealias RawType = [String : JSON] static var queryString = "" static var sortString = "publishedAt" static var ascending = false static var fetchOffset = 0 static var fetchLimit = TPCLoadGanHuoDataOnce static var request: NSFetchRequest { let fetchRequest = NSFetchRequest(entityName: entityName) fetchRequest.fetchLimit = fetchLimit fetchRequest.fetchBatchSize = 20; fetchRequest.fetchOffset = fetchOffset if queryString.characters.count > 0 { let predicate = NSPredicate(format: queryString) fetchRequest.predicate = predicate } fetchRequest.sortDescriptors = [NSSortDescriptor(key: sortString, ascending: ascending)] return fetchRequest } init(context: NSManagedObjectContext, dict: RawType) { let entity = NSEntityDescription.entityForName(GanHuoObject.entityName, inManagedObjectContext: context)! super.init(entity: entity, insertIntoManagedObjectContext: context) initializeWithRawType(dict) } @objc private override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } static func insertObjectInBackgroundContext(dict: RawType) -> GanHuoObject { if let id = dict["_id"]?.stringValue { let results = fetchById(id) if let ganhuo = results.first { ganhuo.initializeWithRawType(dict) return ganhuo } } return GanHuoObject(dict: dict) } // static func insertObjectToContext(context: NSManagedObjectContext, dict: RawType) { // let ganhuo = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as! GanHuoObject // ganhuo.initializeWithRawType(dict) // } convenience init(dict: RawType) { self.init(context: TPCCoreDataManager.shareInstance.backgroundManagedObjectContext, dict: dict) } func initializeWithRawType(dict: RawType) { who = dict["who"]?.stringValue ?? "" publishedAt = dict["publishedAt"]?.stringValue ?? "" objectId = dict["_id"]?.stringValue ?? "" used = dict["used"]?.numberValue ?? NSNumber() type = dict["type"]?.stringValue ?? "" createdAt = dict["createdAt"]?.stringValue ?? "" desc = TPCTextParser.shareTextParser.parseOriginString(dict["desc"]?.stringValue ?? "") url = dict["url"]?.stringValue ?? "" TPCInAppSearchUtil.indexedItemWithType(type!, who: who!, contentDescription: desc!, uniqueIdentifier: url!) calculateCellHeight() } private func calculateCellHeight() { cellHeight = TPCCategoryTableViewCell.cellHeightWithGanHuo(self) } } typealias GanHuoObjectFetch = GanHuoObject extension GanHuoObjectFetch { static func fetchByTime(time: (year: Int, month: Int, day: Int)) -> [GanHuoObject] { queryString = String(format: "publishedAt CONTAINS '%04ld-%02ld-%02ld'", time.year, time.month, time.day) return fetchInBackgroundContext() } static func fetchById(id: String) -> [GanHuoObject] { queryString = "objectId == '\(id)'" return fetchInBackgroundContext() } static func fetchByCategory(category: String?, offset: Int) -> [GanHuoObject] { if let category = category { queryString = "type == '\(category)'" } else { queryString = "" } fetchOffset = offset fetchLimit = TPCLoadGanHuoDataOnce return fetchInBackgroundContext() } static func fetchFavorite() -> [GanHuoObject] { queryString = "favorite == \(NSNumber(bool: true))" sortString = "favoriteAt" fetchLimit = 1000 return fetchInBackgroundContext() } static func fetchSearchResultsByKey(key: String) -> [GanHuoObject] { queryString = "desc CONTAINS '\(key)' " fetchLimit = 1000 return fetchInBackgroundContext() } } infix operator !? { } func !?<T: StringLiteralConvertible> (wrapped: T?, @autoclosure failureText: ()->String) -> T { assert(wrapped != nil, failureText) return wrapped ?? "" }
mit
2ed0238482034ee96fe246b5128d4c4b
36.959016
136
0.662276
5.055677
false
false
false
false
bingoogolapple/SwiftNote-PartOne
多个自定义单元格-Storyboard/多个自定义单元格-Storyboard/ViewController.swift
1
2022
// // ViewController.swift // 多个自定义单元格-Storyboard // // Created by bingoogol on 14/9/27. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ViewController: UITableViewController { var dataList:NSArray! let MY_CELL_ID = "MyCell" let HER_CELL_ID = "HerCell" override func viewDidLoad() { super.viewDidLoad() var path = NSBundle.mainBundle().pathForResource("messages", ofType: "plist") dataList = NSArray(contentsOfFile: path!) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataList.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var dict = dataList[indexPath.row] as NSDictionary var fromSelf = dict["fromSelf"]!.boolValue as Bool var cell:UITableViewCell var button:UIButton if fromSelf { cell = tableView.dequeueReusableCellWithIdentifier(MY_CELL_ID) as UITableViewCell button = cell.viewWithTag(100) as UIButton button.setBackgroundImage(UIImage(named: "chatto_bg_normal.png"), forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "chatto_bg_focused.png"), forState: UIControlState.Highlighted) } else { cell = tableView.dequeueReusableCellWithIdentifier(HER_CELL_ID) as UITableViewCell button = cell.viewWithTag(100) as UIButton button.setBackgroundImage(UIImage(named: "chatfrom_bg_normal.png"), forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "chatfrom_bg_focused.png"), forState: UIControlState.Highlighted) } button.titleLabel?.text = dict["content"] as NSString return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } }
apache-2.0
f282e8471773250e2549a476d1c00ef1
37.557692
118
0.68014
4.887805
false
false
false
false
salemoh/GoldenQuraniOS
GoldenQuranSwift/GoldenQuranSwift/SearchViewController.swift
1
7180
// // SearchViewController.swift // GoldenQuranSwift // // Created by Omar Fraiwan on 4/13/17. // Copyright © 2017 Omar Fraiwan. All rights reserved. // import UIKit enum SearchType:Int { case verse = 1 case topic case mojam } class SearchViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var segmntedControl: GQSegmentedControl! var currentSearchType:SearchType = .verse var searchResults = [SearchResult]() override func viewDidLoad() { super.viewDidLoad() let closeBtnItem = UIBarButtonItem(title:NSLocalizedString("CLOSE", comment: ""),style:.plain , target:self , action:#selector(self.closePressed)) self.navigationItem.setLeftBarButtonItems([closeBtnItem], animated: true) // Do any additional setup after loading the view. self.title = NSLocalizedString("SEARCH_TITLE", comment: "") tableView.keyboardDismissMode = .onDrag tableView.estimatedRowHeight = 50 tableView.estimatedSectionHeaderHeight = 40 self.searchBar.becomeFirstResponder() segmntedControl.setTitle(NSLocalizedString("SEARCH_MUSHAF_VERSES_SEGMENT", comment: "") , forSegmentAt: 0) segmntedControl.setTitle(NSLocalizedString("SEARCH_MUSHAF_TOPICS_SEGMENT", comment: ""), forSegmentAt: 1) segmntedControl.setTitle(NSLocalizedString("SEARCH_MUSHAF_MO3JAM_SEGMENT", comment: ""), forSegmentAt: 2) updateToNewSearchMethod() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func closePressed(){ self.searchBar.resignFirstResponder() self.dismiss(animated: true, completion: nil) } @IBAction func searchSegmentChanged(_ sender: GQSegmentedControl) { switch sender.selectedSegmentIndex { case 0: currentSearchType = .verse case 1: currentSearchType = .topic case 2: currentSearchType = .mojam default: currentSearchType = .verse } updateToNewSearchMethod() } func updateToNewSearchMethod(){ switch currentSearchType { case .verse: currentSearchType = .verse self.searchBar.placeholder = NSLocalizedString("SEARCH_MUSHAF_VERSES_PLACEHOLDER", comment: "") case .topic: currentSearchType = .topic self.searchBar.placeholder = NSLocalizedString("SEARCH_MUSHAF_TOPICS_PLACEHOLDER", comment: "") case .mojam: currentSearchType = .mojam self.searchBar.placeholder = NSLocalizedString("SEARCH_MUSHAF_MO3JAM_PLACEHOLDER", comment: "") } doSearch() } func doSearch(){ guard let query = self.searchBar.text, query.characters.count > 0 else { return } switch currentSearchType { case .verse: searchResults = DBManager.shared.searchMushafVerse(keyword: query); case .topic: searchResults = DBManager.shared.searchMushafByTopic(keyword: query); case .mojam: searchResults = DBManager.shared.searchMushafMo3jam(keyword: query); } self.tableView.reloadData() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension SearchViewController:UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.characters.count >= 3 { doSearch() } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { if let _ = searchBar.text { doSearch() } searchBar.resignFirstResponder() } } extension SearchViewController:UITableViewDelegate{ func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { /// Navigate to search data } } extension SearchViewController:UITableViewDataSource { //SearchVerseTableViewCell //SearchTopicTableViewCell func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let cell = tableView.dequeueReusableCell(withIdentifier: "SearchHeaderTableViewCell") as! SearchHeaderTableViewCell let formatter = NumberFormatter() formatter.numberStyle = .decimal let str = String(formatter.string(from: NSNumber(value: searchResults.count))!) cell.lblResultsCount.text = String(format: NSLocalizedString("SEARCH_RESULTS_%@", comment: ""), str!).correctLanguageNumbers() return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return searchResults.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ switch currentSearchType { case .topic: let cell = tableView.dequeueReusableCell(withIdentifier: "SearchTopicTableViewCell") as! SearchTopicTableViewCell let searchResult = searchResults[indexPath.row] let sora = String(format:"Sora%d" , searchResult.soraNo!) cell.lblTo.text = NSLocalizedString("SEARCH_TO", comment: "") cell.lblSora.text = NSLocalizedString( sora , comment: "") cell.lblFromVerse.text = String(format:"%d", searchResult.fromVerse!).correctLanguageNumbers() cell.lblToVerse.text = String(format:"%d", searchResult.toVerse!).correctLanguageNumbers() cell.lblSearchContent.text = searchResult.content // cell.setNeedsLayout() return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: "SearchVerseTableViewCell") as! SearchVerseTableViewCell let searchResult = searchResults[indexPath.row] let sora = String(format:"Sora%d" , searchResult.soraNo!) cell.lblSearchSora.text = NSLocalizedString( sora , comment: "") cell.lblSearchVerse.text = String(format:"%d", searchResult.fromVerse!).correctLanguageNumbers() cell.lblSearchContent.text = searchResult.content // cell.setNeedsLayout() return cell } } }
mit
309230e2c6e843a69fb827d5010d6310
33.849515
154
0.644937
5.361464
false
false
false
false
LockLight/Weibo_Demo
SinaWeibo/SinaWeibo/Classes/View/PhotoBrowser(图片浏览器)/WBPhotoBrowserController.swift
1
2982
// // WBPhotoBrowserController.swift // SinaWeibo // // Created by locklight on 17/4/9. // Copyright © 2017年 LockLight. All rights reserved. // import UIKit class WBPhotoBrowserController: UIViewController { //当前展示图片的index var index:Int = 0 //图片的url数组 var pic_urlArr:[String] = [] //重载构造函数,设置所需参数 init(index:Int, pic_urlArr:[String]){ super.init(nibName: nil, bundle: nil) self.index = index self.pic_urlArr = pic_urlArr } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.randomColor() setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension WBPhotoBrowserController{ func setupUI(){ //创建分页控制器 let pageVC = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [UIPageViewControllerOptionInterPageSpacingKey:20]) //添加到当前控制器 self.addChildViewController(pageVC) self.view.addSubview(pageVC.view) pageVC.didMove(toParentViewController: self) //设置分页控制器的子控制器 let photoViewerVC = WBPhotoViewerController(index: index, pic_urlArr: pic_urlArr) pageVC.setViewControllers([photoViewerVC], direction: .forward, animated: true, completion: nil) pageVC.dataSource = self let tap = UITapGestureRecognizer(target: self, action: #selector(back)) self.view.addGestureRecognizer(tap) } func back(){ self.dismiss(animated: false, completion: nil) } } //MARK - 分页控制器的数据源方法 extension WBPhotoBrowserController:UIPageViewControllerDataSource{ func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let currentIndex = (viewController as! WBPhotoViewerController).index //到头 if(currentIndex == 0){ return nil } let photoViewer = WBPhotoViewerController(index: currentIndex - 1, pic_urlArr: pic_urlArr) return photoViewer } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let currentIndex = (viewController as! WBPhotoViewerController).index //到尾 if(currentIndex == pic_urlArr.count - 1){ return nil } let photoViewer = WBPhotoViewerController(index: currentIndex + 1, pic_urlArr: pic_urlArr) return photoViewer } }
mit
0579cc1cfc10d624a49b374bd46d065d
28.968421
164
0.655778
4.985989
false
false
false
false
MaxHasADHD/TraktKit
Tests/TraktKitTests/ScrobbleTests.swift
1
3673
// // ScrobbleTests.swift // TraktKitTests // // Created by Maximilian Litteral on 3/29/18. // Copyright © 2018 Maximilian Litteral. All rights reserved. // import XCTest @testable import TraktKit class ScrobbleTests: XCTestCase { let session = MockURLSession() lazy var traktManager = TestTraktManager(session: session) override func tearDown() { super.tearDown() session.nextData = nil session.nextStatusCode = StatusCodes.Success session.nextError = nil } // MARK: - Start func test_start_watching_in_media_center() { session.nextData = jsonData(named: "test_start_watching_in_media_center") session.nextStatusCode = StatusCodes.SuccessNewResourceCreated let expectation = XCTestExpectation(description: "Start watching in media center") let scrobble = TraktScrobble(movie: SyncId(trakt: 12345), progress: 1.25) try! traktManager.scrobbleStart(scrobble) { result in if case .success(let response) = result { XCTAssertEqual(response.action, "start") XCTAssertEqual(response.progress, 1.25) XCTAssertNotNil(response.movie) expectation.fulfill() } } let result = XCTWaiter().wait(for: [expectation], timeout: 1) XCTAssertEqual(session.lastURL?.absoluteString, "https://api.trakt.tv/scrobble/start") switch result { case .timedOut: XCTFail("Something isn't working") default: break } } // MARK: - Pause func test_pause_watching_in_media_center() { session.nextData = jsonData(named: "test_pause_watching_in_media_center") session.nextStatusCode = StatusCodes.SuccessNewResourceCreated let expectation = XCTestExpectation(description: "Pause watching in media center") let scrobble = TraktScrobble(movie: SyncId(trakt: 12345), progress: 75) try! traktManager.scrobblePause(scrobble) { result in if case .success(let response) = result { XCTAssertEqual(response.action, "pause") XCTAssertEqual(response.progress, 75) XCTAssertNotNil(response.movie) expectation.fulfill() } } let result = XCTWaiter().wait(for: [expectation], timeout: 1) XCTAssertEqual(session.lastURL?.absoluteString, "https://api.trakt.tv/scrobble/pause") switch result { case .timedOut: XCTFail("Something isn't working") default: break } } // MARK: - Stop func test_stop_watching_in_media_center() { session.nextData = jsonData(named: "test_stop_watching_in_media_center") session.nextStatusCode = StatusCodes.SuccessNewResourceCreated let expectation = XCTestExpectation(description: "Stop watching in media center") let scrobble = TraktScrobble(movie: SyncId(trakt: 12345), progress: 99.9) try! traktManager.scrobbleStop(scrobble) { result in if case .success(let response) = result { XCTAssertEqual(response.action, "scrobble") XCTAssertEqual(response.progress, 99.9) XCTAssertNotNil(response.movie) expectation.fulfill() } } let result = XCTWaiter().wait(for: [expectation], timeout: 1) XCTAssertEqual(session.lastURL?.absoluteString, "https://api.trakt.tv/scrobble/stop") switch result { case .timedOut: XCTFail("Something isn't working") default: break } } }
mit
b606fc2e20b637688393c719402ec42a
34.307692
94
0.622821
4.689655
false
true
false
false
abdullah-chhatra/iDispatch
iDispatch/iDispatch/DispatchGroup.swift
1
3450
// // DispatchGroup.swift // DispatchQueue // // Created by Abdulmunaf Chhatra on 4/3/15. // Copyright (c) 2015 Abdulmunaf Chhatra. All rights reserved. // import Foundation /** Represents a dispatch group. */ public class DispatchGroup { let group: dispatch_group_t var asyncQueue: DispatchQueue? /** Designated initializer that creates a new GCD dispatch group. */ public init() { group = dispatch_group_create() } /** Designated initializer that creates a new GCD dispatch group. The queue passed to it will be used to executes async block for this group. :param: asyncQueue This queue will be used to execute async blocks for this group. */ public init(asyncQueue: DispatchQueue) { group = dispatch_group_create() self.asyncQueue = asyncQueue } public func enter() { dispatch_group_enter(group) } public func leave() { dispatch_group_leave(group) } /** Executes the block synchronously on the current thread. It will enter group before executing the block and leave group after the block is finished. :param: block Block to be executed. */ public func dispatchSync(block: dispatch_block_t) { enter() block() leave() } /** Dispatches the block asynchronously on its designated async queue. :param: block Block to be executed. */ public func dispatchAsync(block: dispatch_block_t) { if let queue = asyncQueue { dispatch_group_async(group, queue.queue, block) } else { assertionFailure("No async queue is set for this group") } } /** Dispatches the block asynchronously on specified queue. :param: block Block to be executed. */ public func dispatchAsyncOnQueue(queue: DispatchQueue, block: dispatch_block_t) { dispatch_group_async(group, queue.queue, block) } /** Waits for number of seconds for the group to finish. :param: seconds Nubmer of seconds to wait for the group to finish. :returns: True if group returns before specified seconds, false otherwise. */ public func waitForSeconds(seconds: UInt) -> Bool { return dispatch_group_wait(group, SecondsFromNow(seconds)) == 0 } /** Waits forever for the group to finish. */ public func waitForever() -> Bool { return dispatch_group_wait(group, DISPATCH_TIME_FOREVER) == 0 } /** Schedules a block to be submitted to specified queue when the group finishes. :param: queue Queue on wich the block is to be submitted. :param: block Completion block that is to be called. */ public func notifyOnQueue(queue: DispatchQueue, block: dispatch_block_t) { dispatch_group_notify(group, queue.queue, block) } /** Schedules a block to be submitted to designated async queue when the group finishes. :param: block Completion block that is to be called. */ public func notify(block: dispatch_block_t) { if let queue = asyncQueue { dispatch_group_notify(group, queue.queue, block) } else { assertionFailure("No async queue is set for this group") } } }
mit
e6f5569316dabed9a09f35441a489ca8
27.286885
101
0.612174
4.612299
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/PageIssuesTableViewController.swift
2
2710
import UIKit @objc(WMFPageIssuesTableViewController) class PageIssuesTableViewController: UITableViewController { static let defaultViewCellReuseIdentifier = "org.wikimedia.default" fileprivate var theme = Theme.standard @objc var issues = [String]() override func viewDidLoad() { super.viewDidLoad() self.title = WMFLocalizedString("page-issues", value: "Page issues", comment: "Label for the button that shows the \"Page issues\" dialog, where information about the imperfections of the current page is provided (by displaying the warning/cleanup templates). {{Identical|Page issue}}") self.tableView.estimatedRowHeight = 90.0 self.tableView.rowHeight = UITableView.automaticDimension self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: PageIssuesTableViewController.defaultViewCellReuseIdentifier) let xButton = UIBarButtonItem.wmf_buttonType(WMFButtonType.X, target: self, action: #selector(closeButtonPressed)) self.navigationItem.leftBarButtonItem = xButton apply(theme: self.theme) } @objc func closeButtonPressed() { self.presentingViewController?.dismiss(animated: true, completion: nil) } // MARK: - Table view data source override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: PageIssuesTableViewController.defaultViewCellReuseIdentifier, for: indexPath) cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping cell.textLabel?.text = issues[indexPath.row] cell.isUserInteractionEnabled = false cell.backgroundColor = self.theme.colors.paperBackground cell.selectedBackgroundView = UIView() cell.selectedBackgroundView?.backgroundColor = self.theme.colors.midBackground cell.textLabel?.textColor = self.theme.colors.primaryText return cell } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return issues.count } } extension PageIssuesTableViewController: Themeable { public func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } self.tableView.backgroundColor = theme.colors.baseBackground self.tableView.reloadData() } }
mit
6abe2e86a2cdc88a9811c6b269712863
37.169014
294
0.705166
5.599174
false
false
false
false
AnyPresence/justapis-swift-sdk
Source/CompositedGateway.swift
1
15898
// // CompositedGateway.swift // JustApisSwiftSDK // // Created by Andrew Palumbo on 12/9/15. // Copyright © 2015 AnyPresence. All rights reserved. // import Foundation /// /// Invoked by the CompositedGateway to prepare a request before sending. /// /// Common use cases of a RequestPreparer might be to: /// - add default headers /// - add default query parameters /// - rewrite a path /// - serialize data as JSON or XML /// public protocol RequestPreparer { func prepareRequest(request:Request) -> Request } /// /// Invoked by the CompositedGateway to process a request after its received /// /// Common use cases of a ResponseProcessor might be to: /// - validate the type of a response /// - interpret application-level error messages /// - deserialize JSON or XML responses /// public protocol ResponseProcessor { func processResponse(response:Response, callback:ResponseProcessorCallback) } public typealias ResponseProcessorCallback = ((response:Response, error:ErrorType?) -> Void) /// /// Invoked by the CompositedGateway to send the request along the wire /// /// Common use cases of a NetworkAdapter might be to: /// - Use a specific network library (Foundation, AFNetworking, etc) /// - Mock responses /// - Reference a cache before using network resources /// public protocol NetworkAdapter { func submitRequest(request:Request, gateway:CompositedGateway) } /// /// Invoked by the CompositedGateway to save and retrieve responses locally cached responses /// public protocol CacheProvider { /// Called to retrieve a Response from the cache. Should call the callback with nil or the retrieved response func cachedResponseForIdentifier(identifier:String, callback:CacheProviderCallback) /// Called to save a Response to the cache. The expiration should be considered a preference, not a guarantee. func setCachedResponseForIdentifier(identifier:String, response:ResponseProperties, expirationSeconds:UInt) } public typealias CacheProviderCallback = ((ResponseProperties?) -> Void) /// /// A Cache Provider implementation that does nothing. Useful to disable caching without changing your request logic /// public class NullCacheProvider : CacheProvider { public func cachedResponseForIdentifier(identifier: String, callback: CacheProviderCallback) { return callback(nil) } public func setCachedResponseForIdentifier(identifier: String, response: ResponseProperties, expirationSeconds: UInt) { return } } /// /// Convenience object for configuring a composited gateway. Can be passed into Gateway initializer /// public struct CompositedGatewayConfiguration { var baseUrl:NSURL var sslCertificate:SSLCertificate? = nil var defaultRequestProperties:DefaultRequestPropertySet? = nil var networkAdapter:NetworkAdapter? = nil var cacheProvider:CacheProvider? = nil var requestPreparer:RequestPreparer? = nil var responseProcessor:ResponseProcessor? = nil public init(baseUrl:NSURL, sslCertificate:SSLCertificate? = nil, defaultRequestProperties:DefaultRequestPropertySet? = nil, requestPreparer:RequestPreparer? = nil, responseProcessor:ResponseProcessor? = nil, cacheProvider:CacheProvider? = nil, networkAdapter:NetworkAdapter? = nil) { self.baseUrl = baseUrl self.sslCertificate = sslCertificate self.defaultRequestProperties = defaultRequestProperties self.requestPreparer = requestPreparer self.responseProcessor = responseProcessor self.cacheProvider = cacheProvider self.networkAdapter = networkAdapter } } /// /// Implementation of Gateway protocol that dispatches most details to /// helper classes. /// public class CompositedGateway : Gateway { public let baseUrl:NSURL public let sslCertificate:SSLCertificate? public let defaultRequestProperties:DefaultRequestPropertySet private let networkAdapter:NetworkAdapter private let cacheProvider:CacheProvider private let requestPreparer:RequestPreparer? private let responseProcessor:ResponseProcessor? private let contentTypeParser:ContentTypeParser private var requests:InternalRequestQueue = InternalRequestQueue() public var pendingRequests:[Request] { return self.requests.pendingRequests } public var isPaused:Bool { return _isPaused } private var _isPaused:Bool = true /// TODO: Make this configurable? public var maxActiveRequests:Int = 2 /// /// Designated initializer /// public init( baseUrl:NSURL, sslCertificate:SSLCertificate? = nil, defaultRequestProperties:DefaultRequestPropertySet? = nil, requestPreparer:RequestPreparer? = nil, responseProcessor:ResponseProcessor? = nil, cacheProvider:CacheProvider? = nil, networkAdapter:NetworkAdapter? = nil ) { self.baseUrl = baseUrl self.sslCertificate = sslCertificate // Use the GatewayDefaultRequestProperties if none were provided self.defaultRequestProperties = defaultRequestProperties ?? GatewayDefaultRequestProperties() self.requestPreparer = requestPreparer self.responseProcessor = responseProcessor self.contentTypeParser = ContentTypeParser() // Use the InMemory Cache Provider if none was provided self.cacheProvider = cacheProvider ?? InMemoryCacheProvider() // Use the Foundation Network Adapter if none was provided self.networkAdapter = networkAdapter ?? FoundationNetworkAdapter(sslCertificate: sslCertificate) self.resume() } /// /// Convenience initializer for use with CompositedGatewayConfiguration /// public convenience init(configuration:CompositedGatewayConfiguration) { self.init( baseUrl:configuration.baseUrl, sslCertificate:configuration.sslCertificate, defaultRequestProperties:configuration.defaultRequestProperties, requestPreparer:configuration.requestPreparer, responseProcessor:configuration.responseProcessor, cacheProvider:configuration.cacheProvider, networkAdapter:configuration.networkAdapter ) } /// /// Pauses the gateway. No more pending requests will be processed until resume() is called. /// public func pause() { self._isPaused = true // Now that the } /// /// Unpauses the gateway. Pending requests will continue being processed. /// public func resume() { self._isPaused = false self.conditionallyProcessRequestQueue() } /// /// Removes a request from this gateway's pending request queue /// public func cancelRequest(request: Request) -> Bool { guard let internalRequest = request as? InternalRequest where internalRequest.gateway === self else { /// Do nothing. This request wasn't associated with this gateway. return false } return self.requests.cancelPendingRequest(internalRequest) } /// /// Takes a Request from the queue and begins processing it if conditions are met // private func conditionallyProcessRequestQueue() { // If not paused, not already at max active requests, and if there are requests pending if (false == self._isPaused && self.requests.numberActive < self.maxActiveRequests && self.requests.numberPending > 0) { self.processNextInternalRequest() } } /// /// Sets a ResponseProcessor to run when the given contentType is encountered in a response /// public func setParser(parser:ResponseProcessor?, contentType:String) { if (parser != nil) { self.contentTypeParser.contentTypes[contentType] = parser } else { self.contentTypeParser.contentTypes.removeValueForKey(contentType) } } public func submitRequest(request:RequestProperties, callback:RequestCallback?) { let request = self.internalizeRequest(request) self.submitInternalRequest(request, callback: callback) } /// /// Called by CacheProvider or NetworkAdapter once a response is ready /// public func fulfillRequest(request:Request, response:ResponseProperties?, error:ErrorType?, fromCache:Bool = false) { guard let request = request as? InternalRequest else { // TODO: THROW serious error. The Request was corrupted! return } // Build the result object let response:InternalResponse? = (response != nil) ? self.internalizeResponse(response!) : nil var result:RequestResult = (request:request, response:response?.retreivedFromCache(fromCache), error:error) // Check if there was an error guard error == nil else { self.requests.fulfillRequest(request, result: result) return } // Check if there was no response; that's an error itself! guard response != nil else { // TODO: create meaningful error result.error = createError(0, context:nil, description:"") self.requests.fulfillRequest(request, result: result) return } // Compound 0+ response processors for this response let compoundResponseProcessor = CompoundResponseProcessor() // Add the content type parser if request.applyContentTypeParsing { compoundResponseProcessor.responseProcessors.append(contentTypeParser) } // Add any all-response processor if let responseProcessor = self.responseProcessor { compoundResponseProcessor.responseProcessors.append(responseProcessor) } // Run the compound processor in a dispatch group let responseProcessingDispatchGroup = dispatch_group_create() dispatch_group_enter(responseProcessingDispatchGroup) compoundResponseProcessor.processResponse(result.response!, callback: { (response:Response, error:ErrorType?) in result = (request:request, response:response, error:error) dispatch_group_leave(responseProcessingDispatchGroup) } ) // When the dispatch group is emptied, cache the response and run the callback dispatch_group_notify(responseProcessingDispatchGroup, dispatch_get_main_queue(), { if result.error == nil // There's no error && result.response != nil // And there is a response && !fromCache // And the response isn't already from the cache && request.cacheResponseWithExpiration > 0 // And we're supposed to cache it { // Cache the response self.cacheProvider.setCachedResponseForIdentifier(request.cacheIdentifier, response: result.response!, expirationSeconds:request.cacheResponseWithExpiration) } // Pass result back to caller self.requests.fulfillRequest(request, result: result) // Keep the processor running, if appropriate self.conditionallyProcessRequestQueue() }) } /// /// Wraps raw ResponseProperties as an InternalResponse /// internal func internalizeResponse(response:ResponseProperties) -> InternalResponse { // Downcast to an InternalResponse, or wrap externally prepared properties var internalResponse:InternalResponse = (response as? InternalResponse) ?? InternalResponse(self, response:response) if (internalResponse.gateway !== self) { // response was prepared for another gateway. Associate it with this one! internalResponse = internalResponse.gateway(self) } return internalResponse } /// /// Prepares RequestProperties as an InteralRequest and performs preflight prep /// internal func internalizeRequest(request:RequestProperties) -> InternalRequest { // Downcast to an InternalRequest, or wrap externally prepared properties var internalRequest:InternalRequest = (request as? InternalRequest) ?? InternalRequest(self, request:request) if (internalRequest.gateway !== self) { // request was prepared for another gateway. Associate it with this one! internalRequest = internalRequest.gateway(self) } return internalRequest } /// /// Checks CacheProvider for matching Response or submits InternalRequest to NetworkAdapter /// private func submitInternalRequest(request:InternalRequest, callback:RequestCallback?) { var request = request // Prepare the request if a preparer is available if let requestPreparer = self.requestPreparer { // TODO?: change interface to something async; may need to do something complex request = requestPreparer.prepareRequest(request) as! InternalRequest } // Add the request to the queue self.requests.appendRequest(request, callback: callback) // Keep the queue moving, if appropriate self.conditionallyProcessRequestQueue() } /// /// [Background] Starts processing the next request from the queue /// private func processNextInternalRequest() { guard let request = self.requests.nextRequest() else { // No request to process return } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { if request.allowCachedResponse { // Check the cache self.cacheProvider.cachedResponseForIdentifier(request.cacheIdentifier, callback: { (response:ResponseProperties?) in if let response = response { // There was a subitably fresh response in the cache. Use it self.fulfillRequest(request, response: response, error: nil, fromCache:true) } else { // Otherwise, send the request to the network adapter self.networkAdapter.submitRequest(request, gateway:self) } }) } else { // Ignore anything in the cache, and send the request to the network adapter immediately self.networkAdapter.submitRequest(request, gateway:self) } }) } } /// /// Convenience subclass of CompositedGateway that uses the JsonResponseProcessor. /// public class JsonGateway : CompositedGateway { public override init(baseUrl: NSURL, sslCertificate:SSLCertificate? = nil, defaultRequestProperties:DefaultRequestPropertySet? = nil, requestPreparer: RequestPreparer? = nil, responseProcessor:ResponseProcessor? = nil, cacheProvider:CacheProvider? = nil, networkAdapter: NetworkAdapter? = nil) { super.init(baseUrl: baseUrl, defaultRequestProperties: defaultRequestProperties, requestPreparer:requestPreparer, responseProcessor:responseProcessor, networkAdapter:networkAdapter) super.setParser(JsonResponseProcessor(), contentType: "application/json") } }
mit
3b890eae4050822eae9ce53d9a15a341
35.379863
297
0.65937
5.693768
false
false
false
false
SwiftKit/Cuckoo
Source/Matching/Matchable.swift
2
4478
// // Matchable.swift // Cuckoo // // Created by Tadeas Kriz on 16/01/16. // Copyright © 2016 Brightify. All rights reserved. // /** Matchable can be anything that can produce its own parameter matcher. It is used instead of concrete value for stubbing and verification. */ public protocol Matchable { associatedtype MatchedType /// Matcher for this instance. This should be an equalTo type of a matcher, but it is not required. var matcher: ParameterMatcher<MatchedType> { get } } public protocol OptionalMatchable { associatedtype OptionalMatchedType var optionalMatcher: ParameterMatcher<OptionalMatchedType?> { get } } public extension Matchable { func or<M>(_ otherMatchable: M) -> ParameterMatcher<MatchedType> where M: Matchable, M.MatchedType == MatchedType { return ParameterMatcher { return self.matcher.matches($0) || otherMatchable.matcher.matches($0) } } func and<M>(_ otherMatchable: M) -> ParameterMatcher<MatchedType> where M: Matchable, M.MatchedType == MatchedType { return ParameterMatcher { return self.matcher.matches($0) && otherMatchable.matcher.matches($0) } } } extension Optional: Matchable where Wrapped: Matchable, Wrapped.MatchedType == Wrapped { public typealias MatchedType = Wrapped? public var matcher: ParameterMatcher<Wrapped?> { return ParameterMatcher<Wrapped?> { other in switch (self, other) { case (.none, .none): return true case (.some(let lhs), .some(let rhs)): return lhs.matcher.matches(rhs) default: return false } } } } extension Optional: OptionalMatchable where Wrapped: OptionalMatchable, Wrapped.OptionalMatchedType == Wrapped { public typealias OptionalMatchedType = Wrapped public var optionalMatcher: ParameterMatcher<Wrapped?> { return ParameterMatcher<Wrapped?> { other in switch (self, other) { case (.none, .none): return true case (.some(let lhs), .some(let rhs)): return lhs.optionalMatcher.matches(rhs) default: return false } } } } extension Matchable where Self: Equatable { public var matcher: ParameterMatcher<Self> { return equal(to: self) } } extension OptionalMatchable where OptionalMatchedType == Self, Self: Equatable { public var optionalMatcher: ParameterMatcher<OptionalMatchedType?> { return ParameterMatcher { other in return Optional(self) == other } } } extension Bool: Matchable {} extension Bool: OptionalMatchable { public typealias OptionalMatchedType = Bool } extension String: Matchable {} extension String: OptionalMatchable { public typealias OptionalMatchedType = String } extension Float: Matchable {} extension Float: OptionalMatchable { public typealias OptionalMatchedType = Float } extension Double: Matchable {} extension Double: OptionalMatchable { public typealias OptionalMatchedType = Double } extension Character: Matchable {} extension Character: OptionalMatchable { public typealias OptionalMatchedType = Character } extension Int: Matchable {} extension Int: OptionalMatchable { public typealias OptionalMatchedType = Int } extension Int8: Matchable {} extension Int8: OptionalMatchable { public typealias OptionalMatchedType = Int8 } extension Int16: Matchable {} extension Int16: OptionalMatchable { public typealias OptionalMatchedType = Int16 } extension Int32: Matchable {} extension Int32: OptionalMatchable { public typealias OptionalMatchedType = Int32 } extension Int64: Matchable {} extension Int64: OptionalMatchable { public typealias OptionalMatchedType = Int64 } extension UInt: Matchable {} extension UInt: OptionalMatchable { public typealias OptionalMatchedType = UInt } extension UInt8: Matchable {} extension UInt8: OptionalMatchable { public typealias OptionalMatchedType = UInt8 } extension UInt16: Matchable {} extension UInt16: OptionalMatchable { public typealias OptionalMatchedType = UInt16 } extension UInt32: Matchable {} extension UInt32: OptionalMatchable { public typealias OptionalMatchedType = UInt32 } extension UInt64: Matchable {} extension UInt64: OptionalMatchable { public typealias OptionalMatchedType = UInt64 }
mit
edfb23323f8c55b1463196808e4cef70
26.807453
120
0.698235
5.0875
false
false
false
false
mcrollin/safecaster
safecaster/SCRSafecastAPIRouter.swift
1
3406
// // SCRSafecastAPIRouter.swift // safecaster // // Created by Marc Rollin on 3/24/15. // Copyright (c) 2015 safecast. All rights reserved. // import Foundation import Alamofire enum SCRSafecastAPIRouter: URLRequestConvertible { static let baseURLString = "https://api.safecast.org/en-US" case Dashboard() case SignIn(String, String) case SignOut() case User(Int) case Imports(Int, Int) case Import(Int) case CreateImport(String) case EditImportMetadata(Int, String, String, String) case SubmitImport(Int, String) var method: Alamofire.Method { switch self { case .Dashboard: return .GET case .SignIn: return .POST case .SignOut: return .GET case .User: return .GET case .Imports: return .GET case .Import: return .GET case .CreateImport: return .POST case .EditImportMetadata: return .PUT case .SubmitImport: return .PUT } } var path: String { switch self { case .Dashboard: return "" case .SignIn: return "/users/sign_in" case .SignOut: return "/logout" case .User(let id): return "/users/\(id).json" case .Imports: return "/bgeigie_imports.json" case .Import(let id): return "/bgeigie_imports/\(id).json" case .CreateImport: return "/bgeigie_imports.json" case .EditImportMetadata(let id, _, _, _): return "/bgeigie_imports/\(id)" case .SubmitImport(let id, _): return "/bgeigie_imports/\(id)/submit" } } var parameters: [String: AnyObject] { switch self { case .Dashboard: return [:] case .SignIn(let email, let password): return ["user[email]": email, "user[password]": password] case .SignOut: return [:] case .User: return [:] case .Imports(let id, let page): return ["by_user_id": id, "page": page, "order": "created_at"] case .Import: return [:] case .CreateImport: return [:] case .EditImportMetadata(_, let key, let credits, let cities): return ["api_key": key, "bgeigie_import[credits]": credits, "bgeigie_import[cities]": cities] case .SubmitImport(_, let key): return ["api_key": key] } } var URLRequest: NSMutableURLRequest { let mutableURLRequest:NSMutableURLRequest! let URL = NSURL(string: SCRSafecastAPIRouter.baseURLString)! let encoding = Alamofire.ParameterEncoding.URL mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path)) mutableURLRequest.HTTPMethod = method.rawValue switch self { case .CreateImport(let boundaryConstant): let contentType = "multipart/form-data; boundary=" + boundaryConstant mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") return encoding.encode(mutableURLRequest, parameters: parameters).0 default: return encoding.encode(mutableURLRequest, parameters: parameters).0 } } }
cc0-1.0
d52ce19a072c66c23f38cec23f7cd17d
29.684685
105
0.568996
4.69146
false
false
false
false
functionaldude/XLPagerTabStrip
Sources/BaseButtonBarPagerTabStripViewController.swift
3
18195
// BaseButtonBarPagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.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 Foundation open class BaseButtonBarPagerTabStripViewController<ButtonBarCellType: UICollectionViewCell>: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource { public var settings = ButtonBarPagerTabStripSettings() public var buttonBarItemSpec: ButtonBarItemSpec<ButtonBarCellType>! public var changeCurrentIndex: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ animated: Bool) -> Void)? public var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)? @IBOutlet public weak var buttonBarView: ButtonBarView! lazy private var cachedCellWidths: [CGFloat]? = { [unowned self] in return self.calculateWidths() }() public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) delegate = self datasource = self } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self datasource = self } open override func viewDidLoad() { super.viewDidLoad() let buttonBarViewAux = buttonBarView ?? { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .horizontal flowLayout.sectionInset = UIEdgeInsets(top: 0, left: settings.style.buttonBarLeftContentInset ?? 35, bottom: 0, right: settings.style.buttonBarRightContentInset ?? 35) let buttonBarHeight = settings.style.buttonBarHeight ?? 44 let buttonBar = ButtonBarView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: buttonBarHeight), collectionViewLayout: flowLayout) buttonBar.backgroundColor = .orange buttonBar.selectedBar.backgroundColor = .black buttonBar.autoresizingMask = .flexibleWidth var newContainerViewFrame = containerView.frame newContainerViewFrame.origin.y = buttonBarHeight newContainerViewFrame.size.height = containerView.frame.size.height - (buttonBarHeight - containerView.frame.origin.y) containerView.frame = newContainerViewFrame return buttonBar }() buttonBarView = buttonBarViewAux if buttonBarView.superview == nil { view.addSubview(buttonBarView) } if buttonBarView.delegate == nil { buttonBarView.delegate = self } if buttonBarView.dataSource == nil { buttonBarView.dataSource = self } buttonBarView.scrollsToTop = false let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast flowLayout.scrollDirection = .horizontal flowLayout.minimumInteritemSpacing = settings.style.buttonBarMinimumInteritemSpacing ?? flowLayout.minimumInteritemSpacing flowLayout.minimumLineSpacing = settings.style.buttonBarMinimumLineSpacing ?? flowLayout.minimumLineSpacing let sectionInset = flowLayout.sectionInset flowLayout.sectionInset = UIEdgeInsets(top: sectionInset.top, left: settings.style.buttonBarLeftContentInset ?? sectionInset.left, bottom: sectionInset.bottom, right: settings.style.buttonBarRightContentInset ?? sectionInset.right) buttonBarView.showsHorizontalScrollIndicator = false buttonBarView.backgroundColor = settings.style.buttonBarBackgroundColor ?? buttonBarView.backgroundColor buttonBarView.selectedBar.backgroundColor = settings.style.selectedBarBackgroundColor buttonBarView.selectedBarHeight = settings.style.selectedBarHeight // register button bar item cell switch buttonBarItemSpec! { case .nibFile(let nibName, let bundle, _): buttonBarView.register(UINib(nibName: nibName, bundle: bundle), forCellWithReuseIdentifier:"Cell") case .cellClass: buttonBarView.register(ButtonBarCellType.self, forCellWithReuseIdentifier:"Cell") } //- } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) buttonBarView.layoutIfNeeded() isViewAppearing = true } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) isViewAppearing = false } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard isViewAppearing || isViewRotating else { return } // Force the UICollectionViewFlowLayout to get laid out again with the new size if // a) The view is appearing. This ensures that // collectionView:layout:sizeForItemAtIndexPath: is called for a second time // when the view is shown and when the view *frame(s)* are actually set // (we need the view frame's to have been set to work out the size's and on the // first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s) // aren't set correctly) // b) The view is rotating. This ensures that // collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views // *new* frame so that the buttonBarView cell's actually get resized correctly cachedCellWidths = calculateWidths() buttonBarView.collectionViewLayout.invalidateLayout() // When the view first appears or is rotated we also need to ensure that the barButtonView's // selectedBar is resized and its contentOffset/scroll is set correctly (the selected // tab/cell may end up either skewed or off screen after a rotation otherwise) buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .scrollOnlyIfOutOfScreen) buttonBarView.selectItem(at: IndexPath(item: currentIndex, section: 0), animated: false, scrollPosition: []) } // MARK: - View Rotation open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) } // MARK: - Public Methods open override func reloadPagerTabStripView() { super.reloadPagerTabStripView() guard isViewLoaded else { return } buttonBarView.reloadData() cachedCellWidths = calculateWidths() buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes) } open func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat { var numberOfLargeCells = 0 var totalWidthOfLargeCells: CGFloat = 0 for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth { totalWidthOfLargeCells += minimumCellWidthValue numberOfLargeCells += 1 } guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth } let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right let numberOfCells = minimumCellWidths.count let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing let numberOfSmallCells = numberOfCells - numberOfLargeCells let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells) return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells) } open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) { guard shouldUpdateButtonBarView else { return } buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes) if let changeCurrentIndex = changeCurrentIndex { let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType changeCurrentIndex(oldCell, newCell, true) } } open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) { guard shouldUpdateButtonBarView else { return } buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes) if let changeCurrentIndexProgressive = changeCurrentIndexProgressive { let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true) } } // MARK: - UICollectionViewDelegateFlowLayut @objc open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { guard let cellWidthValue = cachedCellWidths?[indexPath.row] else { fatalError("cachedCellWidths for \(indexPath.row) must not be nil") } return CGSize(width: cellWidthValue, height: collectionView.frame.size.height) } open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard indexPath.item != currentIndex else { return } buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes) shouldUpdateButtonBarView = false let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType let newCell = buttonBarView.cellForItem(at: IndexPath(item: indexPath.item, section: 0)) as? ButtonBarCellType if pagerBehaviour.isProgressiveIndicator { if let changeCurrentIndexProgressive = changeCurrentIndexProgressive { changeCurrentIndexProgressive(oldCell, newCell, 1, true, true) } } else { if let changeCurrentIndex = changeCurrentIndex { changeCurrentIndex(oldCell, newCell, true) } } moveToViewController(at: indexPath.item) } // MARK: - UICollectionViewDataSource open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewControllers.count } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ButtonBarCellType else { fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell") } let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider // swiftlint:disable:this force_cast let indicatorInfo = childController.indicatorInfo(for: self) configure(cell: cell, for: indicatorInfo) if pagerBehaviour.isProgressiveIndicator { if let changeCurrentIndexProgressive = changeCurrentIndexProgressive { changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false) } } else { if let changeCurrentIndex = changeCurrentIndex { changeCurrentIndex(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, false) } } return cell } // MARK: - UIScrollViewDelegate open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { super.scrollViewDidEndScrollingAnimation(scrollView) guard scrollView == containerView else { return } shouldUpdateButtonBarView = true } open func configure(cell: ButtonBarCellType, for indicatorInfo: IndicatorInfo) { fatalError("You must override this method to set up ButtonBarView cell accordingly") } private func calculateWidths() -> [CGFloat] { let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast let numberOfCells = viewControllers.count var minimumCellWidths = [CGFloat]() var collectionViewContentWidth: CGFloat = 0 for viewController in viewControllers { let childController = viewController as! IndicatorInfoProvider // swiftlint:disable:this force_cast let indicatorInfo = childController.indicatorInfo(for: self) switch buttonBarItemSpec! { case .cellClass(let widthCallback): let width = widthCallback(indicatorInfo) minimumCellWidths.append(width) collectionViewContentWidth += width case .nibFile(_, _, let widthCallback): let width = widthCallback(indicatorInfo) minimumCellWidths.append(width) collectionViewContentWidth += width } } let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing collectionViewContentWidth += cellSpacingTotal let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right if !settings.style.buttonBarItemsShouldFillAvailableWidth || collectionViewAvailableVisibleWidth < collectionViewContentWidth { return minimumCellWidths } else { let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells) let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0) var stretchedCellWidths = [CGFloat]() for minimumCellWidthValue in minimumCellWidths { let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth stretchedCellWidths.append(cellWidth) } return stretchedCellWidths } } private var shouldUpdateButtonBarView = true } open class ExampleBaseButtonBarPagerTabStripViewController: BaseButtonBarPagerTabStripViewController<ButtonBarViewCell> { public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } open func initialize() { var bundle = Bundle(for: ButtonBarViewCell.self) if let resourcePath = bundle.path(forResource: "XLPagerTabStrip", ofType: "bundle") { if let resourcesBundle = Bundle(path: resourcePath) { bundle = resourcesBundle } } buttonBarItemSpec = .nibFile(nibName: "ButtonCell", bundle: bundle, width: { [weak self] (childItemInfo) -> CGFloat in let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = self?.settings.style.buttonBarItemFont ?? label.font label.text = childItemInfo.title let labelSize = label.intrinsicContentSize return labelSize.width + CGFloat(self?.settings.style.buttonBarItemLeftRightMargin ?? 8 * 2) }) } open override func configure(cell: ButtonBarViewCell, for indicatorInfo: IndicatorInfo) { cell.label.text = indicatorInfo.title cell.accessibilityLabel = indicatorInfo.accessibilityLabel if let image = indicatorInfo.image { cell.imageView.image = image } if let highlightedImage = indicatorInfo.highlightedImage { cell.imageView.highlightedImage = highlightedImage } } }
mit
d4b157d59d01f85337c8eabfca19068d
50.690341
239
0.713328
5.865571
false
false
false
false
ReactiveKit/ReactiveGitter
Networking/Client.swift
1
1760
// // Client.swift // ReactiveGitter // // Created by Srdan Rasic on 14/01/2017. // Copyright © 2017 ReactiveKit. All rights reserved. // import Entities import Client import ReactiveKit private let GitterAPIBaseURL = "https://api.gitter.im/v1" private let GitterAPIBaseStreamURL = "https://stream.gitter.im/v1" private let GitterAuthorizationBaseURL = "https://gitter.im/login/oauth/authorize" private let GitterAuthenticationAPIBaseURL = "https://gitter.im/login/oauth" public class APIClient: Client { public init(token: Token) { super.init(baseURL: GitterAPIBaseURL) defaultHeaders = ["Authorization": "Bearer \(token.accessToken)"] } } public class AuthenticationAPIClient: Client { public init() { super.init(baseURL: GitterAuthenticationAPIBaseURL) } public static func authorizationURL(clientID: String, redirectURI: String) -> URL { return URL(string: "\(GitterAuthorizationBaseURL)?client_id=\(clientID)&response_type=code&redirect_uri=\(redirectURI)")! } } extension Client { public func response<Resource, Error: Swift.Error>(for request: Request<Resource, Error>) -> Signal<Resource, Client.Error> { return Signal { observer in let task = self.perform(request) { (result) in switch result { case .success(let resource): observer.completed(with: resource) case .failure(let error): observer.failed(error) } } return BlockDisposable { task.cancel() } } } } extension Request { public func response(using client: Client) -> Signal<Resource, Client.Error> { return client.response(for: self) } }
mit
9c3af6fc517a7305aef069fbdee57d5a
27.370968
129
0.654349
4.269417
false
false
false
false
qualaroo/QualarooSDKiOS
Qualaroo/Network/SimpleRequest/SimpleRequestScheduler.swift
1
5853
// // SimpleRequestScheduler.swift // QualarooSDKiOS // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation class SimpleRequestScheduler { /// Queue that is used to execute operations which send responses. var privateQueue: OperationQueue /// Reachability object that contain logic for checking internet availability. private let reachability: Reachability? /// Saves and loades data. private let storage: ReportRequestMemoryProtocol init(reachability: Reachability?, storage: ReportRequestMemoryProtocol) { self.storage = storage self.reachability = reachability privateQueue = OperationQueue() privateQueue.name = "com.qualaroo.sendresponsequeue" privateQueue.maxConcurrentOperationCount = 4 privateQueue.qualityOfService = .background addObservers() retryStoredAnswers() } deinit { removeObservers() } /// Resume executing requests. private func resumeQueue() { privateQueue.isSuspended = false } /// Stops executing requests. private func pauseQueue() { privateQueue.isSuspended = true } private func cleanQueue() { privateQueue.cancelAllOperations() } // MARK: - Notifications func addObservers() { observeForEnteringBackground() observeForEnteringForeground() observeForInternetAvailability() } func removeObservers() { stopObservingForEnteringBackground() stopObservingForEnteringForeground() stopObservingInternetAvailability() } // MARK: - Saving answers private func observeForEnteringBackground() { NotificationCenter.default.addObserver(self, selector: #selector(handleEnteredBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) } private func stopObservingForEnteringBackground() { NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil) } private func observeForEnteringForeground() { NotificationCenter.default.addObserver(self, selector: #selector(handleEnteringForeground), name: UIApplication.willEnterForegroundNotification, object: nil) } private func stopObservingForEnteringForeground() { NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil) } @objc func handleEnteredBackground() { pauseQueue() cleanQueue() } @objc func handleEnteringForeground() { retryStoredAnswers() if isInternetAvailable() { resumeQueue() } } func retryStoredAnswers() { let requests = storage.getAllRequests() for url in requests { scheduleRequest(URL(string: url)!) } } private class ReportRequestOperation: Operation { let maxRetryCount = 3 let url: URL let storage: ReportRequestMemoryProtocol init(url: URL, storage: ReportRequestMemoryProtocol) { self.url = url self.storage = storage } override func main() { var success: Bool = false var tries = 0 repeat { success = call(url, tries) tries += 1 } while tries <= maxRetryCount && !success if success { storage.remove(reportRequest: url.absoluteString) } } private func call(_ url: URL, _ retryNum: Int) -> Bool { let timeToWait = pow(2, retryNum) - 1 sleep(NSDecimalNumber(decimal: timeToWait).uint32Value) let request = ReportRequest(url) let result = request.call() return result.isSuccessful() } } } // MARK: - Internet extension SimpleRequestScheduler { /// Call it to start observing internet status. private func observeForInternetAvailability() { NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(_:)), name: reachabilityModified, object: reachability) do { try reachability?.startNotifier() } catch { pauseQueue() } } /// Use it to stop observing internet status. Should be used when class is being deallocated. private func stopObservingInternetAvailability() { NotificationCenter.default.removeObserver(self, name: reachabilityModified, object: reachability) } /// Function called when access to internet status changed while it's observed. /// /// - Parameter notification: notification that contain new reachability status. @objc func reachabilityChanged(_ notification: Notification) { guard (notification.object as? Reachability) != nil else { return } if isInternetAvailable() { resumeQueue() } else { pauseQueue() } } /// Check if devise have access to internet. /// /// - Returns: True if there is access of false if there isn't. private func isInternetAvailable() -> Bool { guard let reachability = reachability else { return false } return reachability.currentReachabilityStatus != .notReachable } } extension SimpleRequestScheduler: ReportRequestProtocol { func scheduleRequest(_ url: URL) { let operation = ReportRequestOperation(url: url, storage: storage) privateQueue.addOperation(operation) } }
mit
2da5eeb7474964edec170c62ca4f7b16
29.170103
101
0.640697
5.526912
false
false
false
false
mattjgalloway/emoncms-ios
EmonCMSiOS/ViewModel/FeedListViewModel.swift
1
2757
// // FeedListViewModel.swift // EmonCMSiOS // // Created by Matt Galloway on 12/09/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import Foundation import RxSwift import RxCocoa import RxDataSources import Realm import RealmSwift import RxRealm final class FeedListViewModel { struct ListItem { let feedId: String let name: String let value: String } typealias Section = SectionModel<String, ListItem> private let account: Account private let api: EmonCMSAPI private let realm: Realm private let feedUpdateHelper: FeedUpdateHelper private let disposeBag = DisposeBag() // Inputs let active = Variable<Bool>(false) let refresh = ReplaySubject<()>.create(bufferSize: 1) // Outputs private(set) var feeds: Driver<[Section]> private(set) var isRefreshing: Driver<Bool> init(account: Account, api: EmonCMSAPI) { self.account = account self.api = api self.realm = account.createRealm() self.feedUpdateHelper = FeedUpdateHelper(account: account, api: api) self.feeds = Driver.never() self.isRefreshing = Driver.never() self.feeds = Observable.arrayFrom(self.realm.objects(Feed.self)) .map(self.feedsToSections) .asDriver(onErrorJustReturn: []) let isRefreshing = ActivityIndicator() self.isRefreshing = isRefreshing.asDriver() let becameActive = self.active.asObservable() .distinctUntilChanged() .filter { $0 == true } .becomeVoid() Observable.of(self.refresh, becameActive) .merge() .flatMapLatest { [weak self] () -> Observable<()> in guard let strongSelf = self else { return Observable.empty() } return strongSelf.feedUpdateHelper.updateFeeds() .catchErrorJustReturn(()) .trackActivity(isRefreshing) } .subscribe() .addDisposableTo(self.disposeBag) } private func feedsToSections(_ feeds: [Feed]) -> [Section] { var sectionBuilder: [String:[Feed]] = [:] for feed in feeds { let sectionFeeds: [Feed] if let existingFeeds = sectionBuilder[feed.tag] { sectionFeeds = existingFeeds } else { sectionFeeds = [] } sectionBuilder[feed.tag] = sectionFeeds + [feed] } var sections: [Section] = [] for section in sectionBuilder.keys.sorted() { let items = sectionBuilder[section]! .map { feed in return ListItem(feedId: feed.id, name: feed.name, value: feed.value.prettyFormat()) } sections.append(Section(model: section, items: items)) } return sections } func feedChartViewModel(forItem item: ListItem) -> FeedChartViewModel { return FeedChartViewModel(account: self.account, api: self.api, feedId: item.feedId) } }
mit
3ddd9fbbcf53baa60da0307bde51c827
25.5
93
0.672714
4.30625
false
false
false
false
icapps/ios_objective_c_workshop
Teacher/ObjcTextInput/Pods/Faro/Sources/Request/URLComponentsSerialization.swift
5
1004
// // Query.swift // Monizze // // Created by Stijn Willems on 21/04/2017. // Copyright © 2017 iCapps. All rights reserved. // import Foundation public protocol URLQueryParameterStringConvertible { var queryParameters: String {get} } extension Dictionary : URLQueryParameterStringConvertible { /** This computed property returns a query parameters string from the given NSDictionary. For example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output string will be @"day=Tuesday&month=January". @return The computed parameters string. */ public var queryParameters: String { var parts: [String] = [] for (key, value) in self { let part = String(format: "%@=%@", String(describing: key).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!, String(describing: value).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) parts.append(part as String) } return parts.joined(separator: "&") } }
mit
c97a3d8e61052905b868235e430157da
29.393939
111
0.701894
4.060729
false
false
false
false
mathcamp/Carlos
Tests/Fakes/CacheLevelFake.swift
1
2127
import Foundation import Carlos import PiedPiper class CacheLevelFake<A, B>: CacheLevel { typealias KeyType = A typealias OutputType = B init() {} var queueUsedForTheLastCall: UnsafeMutablePointer<Void>! var numberOfTimesCalledGet = 0 var didGetKey: KeyType? var cacheRequestToReturn: Future<OutputType>? var promisesReturned: [Promise<OutputType>] = [] func get(key: KeyType) -> Future<OutputType> { numberOfTimesCalledGet++ didGetKey = key queueUsedForTheLastCall = currentQueueSpecific() let returningPromise: Promise<OutputType> let returningFuture: Future<OutputType> if let requestToReturn = cacheRequestToReturn { returningFuture = requestToReturn returningPromise = Promise<OutputType>().mimic(requestToReturn) } else { returningPromise = Promise<OutputType>() returningFuture = returningPromise.future } promisesReturned.append(returningPromise) return returningFuture } var numberOfTimesCalledSet = 0 var didSetValue: OutputType? var didSetKey: KeyType? func set(value: OutputType, forKey key: KeyType) { numberOfTimesCalledSet++ didSetKey = key didSetValue = value queueUsedForTheLastCall = currentQueueSpecific() } var numberOfTimesCalledClear = 0 func clear() { numberOfTimesCalledClear++ queueUsedForTheLastCall = currentQueueSpecific() } var numberOfTimesCalledOnMemoryWarning = 0 func onMemoryWarning() { numberOfTimesCalledOnMemoryWarning++ queueUsedForTheLastCall = currentQueueSpecific() } } class FetcherFake<A, B>: Fetcher { typealias KeyType = A typealias OutputType = B var queueUsedForTheLastCall: UnsafeMutablePointer<Void>! init() {} var numberOfTimesCalledGet = 0 var didGetKey: KeyType? var cacheRequestToReturn: Future<OutputType>? func get(key: KeyType) -> Future<OutputType> { numberOfTimesCalledGet++ didGetKey = key queueUsedForTheLastCall = currentQueueSpecific() return cacheRequestToReturn ?? Promise<OutputType>().future } }
mit
f10dd0324039dff558041ee8f266c8fc
23.45977
69
0.713681
5.510363
false
false
false
false
CoderST/STScrolPlay
STScrolPlay/STScrolPlay/Class/Model/STPlayerToolModel.swift
1
3022
// // STPlayerToolModel.swift // STPlayerExample // // Created by xiudou on 2017/7/26. // Copyright © 2017年 CoderST. All rights reserved. // 画虚线 import UIKit fileprivate let navHeight : CGFloat = NavAndStatusTotalHei fileprivate let tabHeight : CGFloat = TabbarHei class STPlayerToolModel: NSObject { // 虚线区域View lazy var tableViewRange : UIView = self.generateTableViewRange() let generateTableViewRange = { () -> UIView in let tableViewRange = UIView(frame: CGRect(x: 0, y: navHeight, width: screenSize.width, height: screenSize.height-navHeight-tabHeight)) tableViewRange.isUserInteractionEnabled = false tableViewRange.backgroundColor = UIColor.clear tableViewRange.isHidden = true return tableViewRange } lazy var dictOfVisiableAndNotPlayCells : Dictionary<String, Int> = { return ["4" : 1, "3" : 1, "2" : 0] }() // The number of cells cannot stop in screen center. var maxNumCannotPlayVideoCells: Int { let radius = screenSize.height / RowHei let maxNumOfVisiableCells = Int(ceilf(Float(radius))) if maxNumOfVisiableCells >= 3 { return dictOfVisiableAndNotPlayCells["\(maxNumOfVisiableCells)"]! } return 0 } func displayCollectionViewRange(centerView : UIView, view : UIView){ view.insertSubview(tableViewRange, aboveSubview: centerView) addDashLineToTableViewRange() } func addDashLineToTableViewRange() { let linePath1 = UIBezierPath() linePath1.move(to: CGPoint(x: 1, y: 1)) linePath1.addLine(to: CGPoint(x: screenSize.width-1, y: 1)) linePath1.addLine(to: CGPoint(x: screenSize.width-1, y: screenSize.height-navHeight-1-tabHeight)) linePath1.addLine(to: CGPoint(x: 1, y: screenSize.height-navHeight-1-tabHeight)) linePath1.addLine(to: CGPoint(x: 1, y: 1)) let layer1 = CAShapeLayer() let drawColor1 = UIColor(colorLiteralRed: 1, green: 0, blue: 0, alpha: 1) layer1.path = linePath1.cgPath layer1.strokeColor = drawColor1.cgColor layer1.fillColor = UIColor.clear.cgColor layer1.lineWidth = 1 layer1.lineDashPattern = [6, 3] layer1.lineCap = "round" tableViewRange.layer.addSublayer(layer1) let linePath2 = UIBezierPath() linePath2.move(to: CGPoint(x: 1, y: 0.5*(screenSize.height-navHeight-1-tabHeight))) linePath2.addLine(to: CGPoint(x: screenSize.width-1, y: 0.5*(screenSize.height-navHeight-1-tabHeight))) let layer2 = CAShapeLayer() let drawColor2 = UIColor(colorLiteralRed: 0, green: 0.98, blue: 0, alpha: 1) layer2.path = linePath2.cgPath layer2.strokeColor = drawColor2.cgColor layer2.fillColor = UIColor.clear.cgColor layer2.lineWidth = 1 layer2.lineDashPattern = [6, 3] layer2.lineCap = "round" tableViewRange.layer.addSublayer(layer2) } }
mit
b78e454b41dd74680045078399fce484
36.5625
142
0.659235
4.105191
false
false
false
false
zom/Zom-iOS
Zom/Zom/Classes/View Controllers/ZomComposeViewController.swift
1
12063
// // ZomComposeViewController.swift // Zom // // Created by N-Pex on 2015-11-24. // // import UIKit import ChatSecureCore open class ZomComposeViewController: OTRComposeViewController { typealias ObjcYapDatabaseViewSortingWithObjectBlock = @convention(block) (YapDatabaseReadTransaction, String, String, String, Any, String, String, Any) -> ComparisonResult typealias ObjcYapDatabaseViewGroupingWithObjectBlock = @convention(block) (YapDatabaseReadTransaction, String, String, Any) -> String? static var extensionName:String = "Zom" + OTRAllBuddiesDatabaseViewExtensionName static var filteredExtensionName:String = "Zom" + OTRArchiveFilteredBuddiesName open static var openInGroupMode:Bool = false var wasOpenedInGroupMode = false static let imageActionButtonCellIdentifier = "imageActionCell" static let imageActionCreateGroupIdentifier = "imageActionCellCreateGroup" static let imageActionAddFriendIdentifier = "imageActionCellAddFriend" open override func viewDidLoad() { super.viewDidLoad() self.tableView.register(OTRBuddyApprovalCell.self, forCellReuseIdentifier: OTRBuddyApprovalCell.reuseIdentifier()) if (ZomComposeViewController.openInGroupMode) { ZomComposeViewController.openInGroupMode = false self.wasOpenedInGroupMode = true self.groupButtonPressed(self) navigationItem.title = "" } else { navigationItem.title = NSLocalizedString("Choose a Friend", comment: "When selecting friend") let nib = UINib(nibName: "ImageActionButtonCell", bundle: OTRAssets.resourcesBundle) self.tableView.register(nib, forCellReuseIdentifier: ZomComposeViewController.imageActionButtonCellIdentifier) if let cell = self.tableView.dequeueReusableCell(withIdentifier: ZomComposeViewController.imageActionButtonCellIdentifier) as? ZomImageActionButtonCell { cell.actionLabel.text = NSLocalizedString("Create a Group", comment: "Cell text for creating a group") cell.iconLabel.backgroundColor = UIColor(netHex: 0xff7ed321) self.tableViewHeader.addStackedSubview(cell, identifier: ZomComposeViewController.imageActionCreateGroupIdentifier, gravity: .bottom, height: OTRBuddyInfoCellHeight, callback: { self.groupButtonPressed(cell) }) cell.translatesAutoresizingMaskIntoConstraints = true cell.contentView.translatesAutoresizingMaskIntoConstraints = true } if let cell = self.tableView.dequeueReusableCell(withIdentifier: ZomComposeViewController.imageActionButtonCellIdentifier) as? ZomImageActionButtonCell { cell.actionLabel.text = ADD_BUDDY_STRING() cell.iconLabel.text = "" cell.iconLabel.backgroundColor = GlobalTheme.shared.mainThemeColor self.tableViewHeader.addStackedSubview(cell, identifier: ZomComposeViewController.imageActionAddFriendIdentifier, gravity: .bottom, height: OTRBuddyInfoCellHeight, callback: { let accounts = OTRAccountsManager.allAccounts() self.addBuddy(accounts) }) cell.translatesAutoresizingMaskIntoConstraints = true cell.contentView.translatesAutoresizingMaskIntoConstraints = true } // Remove the "create group" option from navigation bar self.navigationItem.rightBarButtonItems = nil } } override open func didSetupMappings(_ handler: OTRYapViewHandler) { super.didSetupMappings(handler) if (handler == self.viewHandler) { // If we have not done so, register our extension and change the viewHandler to our own. if registerZomSortedView() { useZomSortedView() } } } override open func viewDidLayoutSubviews() { // Hide the upstream add friends option let hideAddFriends = !(parent is UINavigationController) self.tableViewHeader.setView(ADD_BUDDY_STRING(), hidden: true) self.tableViewHeader.setView(JOIN_GROUP_STRING(), hidden: true) self.tableViewHeader.setView(ZomComposeViewController.imageActionCreateGroupIdentifier, hidden: hideAddFriends) self.tableViewHeader.setView(ZomComposeViewController.imageActionAddFriendIdentifier, hidden: hideAddFriends) } override open func updateInboxArchiveFilteringAndShowArchived(_ showArchived: Bool) { super.updateInboxArchiveFilteringAndShowArchived(showArchived) OTRDatabaseManager.shared.writeConnection?.asyncReadWrite({ (transaction) in if let fvt = transaction.ext(ZomComposeViewController.filteredExtensionName) as? YapDatabaseFilteredViewTransaction { fvt.setFiltering(self.getFilteringBlock(showArchived), versionTag:NSUUID().uuidString) } }) self.view.setNeedsLayout() } func registerZomSortedView() -> Bool { // This sets up a database view that is identical to the original "OTRAllBuddiesDatabaseView" but // with the difference that XMPPBuddies that are avaiting approval are ordered to the top of the list. // if OTRDatabaseManager.shared.database?.registeredExtension(ZomComposeViewController.extensionName) == nil { if let originalView:YapDatabaseAutoView = OTRDatabaseManager.sharedInstance().database?.registeredExtension(OTRAllBuddiesDatabaseViewExtensionName) as? YapDatabaseAutoView { let sorting = YapDatabaseViewSorting.withObjectBlock({ (transaction, group, collection1, group1, object1, collection2, group2, object2) -> ComparisonResult in let askingApproval1 = (object1 as? OTRXMPPBuddy)?.askingForApproval ?? false let askingApproval2 = (object2 as? OTRXMPPBuddy)?.askingForApproval ?? false if (askingApproval1 && !askingApproval2) { return .orderedAscending } else if (!askingApproval1 && askingApproval2) { return .orderedDescending } let pendingApproval1 = (object1 as? OTRXMPPBuddy)?.pendingApproval ?? false let pendingApproval2 = (object2 as? OTRXMPPBuddy)?.pendingApproval ?? false if (pendingApproval1 && !pendingApproval2) { return .orderedAscending } else if (!pendingApproval1 && pendingApproval2) { return .orderedDescending } if let buddy1 = (object1 as? OTRXMPPBuddy), let buddy2 = (object2 as? OTRXMPPBuddy) { let name1 = (buddy1.displayName.count > 0) ? buddy1.displayName : buddy1.username let name2 = (buddy2.displayName.count > 0) ? buddy2.displayName : buddy2.username return name1.caseInsensitiveCompare(name2) } let blockObject:AnyObject = originalView.sorting.block as AnyObject let originalBlock = unsafeBitCast(blockObject, to: ObjcYapDatabaseViewSortingWithObjectBlock.self) return originalBlock(transaction, group, collection1, group1, object1, collection2, group2, object2) }) let grouping = YapDatabaseViewGrouping.withObjectBlock({ (transaction, collection, key, object) -> String? in let blockObject:AnyObject = originalView.grouping.block as AnyObject let originalBlock = unsafeBitCast(blockObject, to: ObjcYapDatabaseViewGroupingWithObjectBlock.self) var group = originalBlock(transaction, collection, key, object) if group == nil, let buddy = object as? OTRXMPPBuddy, buddy.askingForApproval { group = OTRBuddyGroup } return group }) let options = YapDatabaseViewOptions() options.isPersistent = false let newView = YapDatabaseAutoView(grouping: grouping, sorting: sorting, versionTag: NSUUID().uuidString, options: options) OTRDatabaseManager.sharedInstance().database?.register(newView, withName: ZomComposeViewController.extensionName) } } if OTRDatabaseManager.shared.database?.registeredExtension(ZomComposeViewController.filteredExtensionName) == nil, OTRDatabaseManager.shared.database?.registeredExtension(OTRArchiveFilteredBuddiesName) != nil { let options = YapDatabaseViewOptions() options.isPersistent = false let filtering = getFilteringBlock(false) let filteredView = YapDatabaseFilteredView(parentViewName: ZomComposeViewController.extensionName, filtering: filtering, versionTag: NSUUID().uuidString, options: options) OTRDatabaseManager.sharedInstance().database?.register(filteredView, withName: ZomComposeViewController.filteredExtensionName) return true } return false } func useZomSortedView() { self.viewHandler = OTRYapViewHandler(databaseConnection: OTRDatabaseManager.shared.longLivedReadOnlyConnection!, databaseChangeNotificationName: DatabaseNotificationName.LongLivedTransactionChanges) if let viewHandler = self.viewHandler { viewHandler.delegate = self as? OTRYapViewHandlerDelegateProtocol viewHandler.setup(ZomComposeViewController.filteredExtensionName, groups: [OTRBuddyGroup]) } } open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let threadOwner = super.threadOwner(at: indexPath, with: tableView) as? OTRXMPPBuddy, threadOwner.askingForApproval { let cell = tableView.dequeueReusableCell(withIdentifier: OTRBuddyApprovalCell.reuseIdentifier(), for: indexPath) if let cell = cell as? OTRBuddyApprovalCell { cell.actionBlock = { (cell:OTRBuddyApprovalCell?, approved:Bool) -> Void in //TODO Fixme: quick hack to get going if let tabController = self.tabBarController as? ZomMainTabbedViewController { if let conversationController = tabController.viewControllers?[0] as? OTRConversationViewController { conversationController.handleSubscriptionRequest(threadOwner, approved: approved) } } } cell.selectionStyle = .none cell.avatarImageView.layer.cornerRadius = (80.0-2.0*OTRBuddyImageCellPadding)/2.0 cell.setThread(threadOwner) } return cell } return super.tableView(tableView, cellForRowAt: indexPath) } open override func addBuddy(_ accountsAbleToAddBuddies: [OTRAccount]?) { if let accounts = accountsAbleToAddBuddies { if (accounts.count > 0) { ZomNewBuddyViewController.addBuddyToDefaultAccount(self.navigationController) } } } open override func groupButtonPressed(_ sender: Any!) { let storyboard = UIStoryboard(name: "OTRComposeGroup", bundle: OTRAssets.resourcesBundle) if let vc = storyboard.instantiateInitialViewController() as? OTRComposeGroupViewController { vc.delegate = self as? OTRComposeGroupViewControllerDelegate self.navigationController?.pushViewController(vc, animated: (sender as? UIViewController != self)) } } override open func groupSelectionCancelled(_ composeViewController: OTRComposeGroupViewController!) { if composeViewController != nil && wasOpenedInGroupMode { dismiss(animated: true, completion: nil) } } }
mpl-2.0
48012136b9dc2af383283486ae15b35f
57.2657
218
0.672166
5.724252
false
false
false
false
xdliu002/TAC_communication
20160407/LoginAndRegister/LoginAndRegister/LoginViewController.swift
1
6715
// // LoginViewController.swift // LoginAndRegister // // Created by FOWAFOLO on 16/4/7. // Copyright © 2016年 TAC. All rights reserved. // import UIKit import SnapKit class LoginViewController: UIViewController { //MARK: - UI Components var superView = UIView() let backgroundImage = UIImageView() let logoImage = UIImageView() let logoLabel = UILabel() let userIcon = UIImageView() let userText = UITextField() let passIcon = UIImageView() let passText = UITextField() let loginButton = UIButton() let wechatButton = UIButton() let weboButton = UIButton() override func viewDidLoad() { super.viewDidLoad() superView = self.view //TODO: configure UI configeUI() } //MARK: - Functions func configeUI() { //MARK: backgroundImage backgroundImage.image = UIImage(named: "loginBack") superView.addSubview(backgroundImage) backgroundImage.snp_makeConstraints { (make) in // make.left.right.top.bottom.equalTo(superView) make.size.equalTo(superView) make.center.equalTo(superView) } //MARK: logoImage logoImage.image = UIImage(named: "Logo-LoginView") superView.addSubview(logoImage) logoImage.snp_makeConstraints { (make) in make.top.equalTo(superView).offset(61) make.width.height.equalTo(140) make.centerX.equalTo(superView) } // superView.bringSubviewToFront(logoImage) //MARK: logoLabel logoLabel.text = "Carols" logoLabel.textColor = UIColor.GlobalRedColor() logoLabel.font = UIFont.systemFontOfSize(30) superView.addSubview(logoLabel) logoLabel.snp_makeConstraints { (make) in make.top.equalTo(logoImage.snp_bottom).offset(3) make.centerX.equalTo(superView) } userIcon.image = UIImage(named: "user") passIcon.image = UIImage(named: "lock") // userText.placeholder = "Phone Number" userText.attributedPlaceholder = NSAttributedString(string: "Phone Number", attributes: [NSForegroundColorAttributeName: UIColor.GlobalGray()]) userText.textAlignment = .Center superView.addSubview(userText) userText.snp_makeConstraints { (make) in make.top.equalTo(logoLabel.snp_bottom).offset(51) make.centerX.equalTo(superView) make.left.equalTo(superView).offset(100) make.right.equalTo(superView).offset(-100) } superView.addSubview(userIcon) userIcon.snp_makeConstraints { (make) in make.width.height.equalTo(24) make.right.equalTo(userText.snp_left).offset(-5) make.centerY.equalTo(userText) } let line1 = UIView() line1.backgroundColor = UIColor.GlobalRedColor() superView.addSubview(line1) line1.snp_makeConstraints { (make) in make.height.equalTo(1.5) make.left.equalTo(userIcon).offset(-5) make.right.equalTo(userText).offset(5) make.top.equalTo(userIcon.snp_bottom).offset(5) } // passText.placeholder = "Password" passText.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.GlobalGray()]) passText.textAlignment = .Center superView.addSubview(passText) passText.snp_makeConstraints { (make) in make.top.equalTo(line1.snp_bottom).offset(26) make.centerX.equalTo(superView) make.left.equalTo(superView).offset(100) make.right.equalTo(superView).offset(-100) } superView.addSubview(passIcon) passIcon.snp_makeConstraints { (make) in make.width.height.equalTo(24) make.right.equalTo(userText.snp_left).offset(-5) make.centerY.equalTo(passText) } let line2 = UIView() line2.backgroundColor = UIColor.GlobalRedColor() superView.addSubview(line2) line2.snp_makeConstraints { (make) in make.height.width.centerX.equalTo(line1) make.top.equalTo(passIcon.snp_bottom).offset(5) } loginButton.setTitle("Login", forState: .Normal) loginButton.layer.cornerRadius = 20 loginButton.backgroundColor = UIColor.GlobalRedColor() loginButton.addTarget(self, action: #selector(LoginViewController.loginButtonClicked), forControlEvents: .TouchUpInside) superView.addSubview(loginButton) loginButton.snp_makeConstraints { (make) in make.top.equalTo(line2.snp_bottom).offset(70) make.centerX.equalTo(superView) make.height.equalTo(35) make.width.equalTo(119) } let jumpButton = UIButton() jumpButton.setTitle("Jump to Register", forState: .Normal) jumpButton.addTarget(self, action: #selector(LoginViewController.jumpButtonClicked), forControlEvents: .TouchUpInside) superView.addSubview(jumpButton) jumpButton.snp_makeConstraints { (make) in make.top.equalTo(line2.snp_bottom).offset(5) make.centerX.equalTo(superView) } let loginDescription = UILabel() loginDescription.text = "Login By" loginDescription.textColor = UIColor.grayColor() superView.addSubview(loginDescription) loginDescription.snp_makeConstraints { (make) in make.top.equalTo(loginButton.snp_bottom).offset(44) make.centerX.equalTo(superView) } wechatButton.setImage(UIImage(named: "wechat"), forState: .Normal) superView.addSubview(wechatButton) wechatButton.snp_makeConstraints { (make) in make.right.equalTo(superView.snp_centerX).offset(-7.5) make.top.equalTo(loginDescription.snp_bottom).offset(36) make.height.equalTo(44) make.width.equalTo(55) } weboButton.setImage(UIImage(named: "weibo"), forState: .Normal) superView.addSubview(weboButton) weboButton.snp_makeConstraints { (make) in make.height.width.top.equalTo(wechatButton) make.left.equalTo(superView.snp_centerX).offset(7.5) } } func loginButtonClicked() { print("loginButtonClicked") } func jumpButtonClicked() { let destination = SingUpViewController() self.presentViewController(destination, animated: true, completion: nil) } }
mit
a3f2be6dacbdeef7a751ab26ab1b2d30
35.478261
151
0.628725
4.606726
false
false
false
false
bmichotte/HSTracker
HSTracker/Utility/Algorithm.swift
2
4018
// // Algorithm.swift // HSTracker // // Created by Istvan Fehervari on 20/03/2017. // Copyright © 2017 Benjamin Michotte. All rights reserved. // import Foundation /// integer power function operator precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } infix operator ^^ : PowerPrecedence func ^^ (radix: Int, power: Int) -> Int { return Int(pow(Double(radix), Double(power))) } // MARK: - Data structures /// Data structure that handles element in a LIFO way public class Stack<T> { private var data = [T]() public var count: Int { return data.count } public func push(_ element: T) { data.append(element) } public func peek() -> T? { return data.last } public func pop() -> T? { if self.count == 0 { return nil } return data.removeLast() } } /// Node for linked list containers public class Node<T> { var value: T var next: Node<T>? weak var previous: Node<T>? init(value: T) { self.value = value } } /// Data structure that stores element in a linked list public class LinkedList<T> { fileprivate var head: Node<T>? private var tail: Node<T>? private var _count: Int = 0 public var isEmpty: Bool { return head == nil } public var first: Node<T>? { return head } public var last: Node<T>? { return tail } public func append(_ value: T) { let newNode = Node(value: value) if let tailNode = tail { newNode.previous = tailNode tailNode.next = newNode } else { head = newNode } tail = newNode _count += 1 } public func appendAll(_ collection: [T]) { for i in collection { self.append(i) } } public func nodeAt(index: Int) -> Node<T>? { if self._count <= index { return nil } if index >= 0 { var node = head var i = index while node != nil { if i == 0 { return node } i -= 1 node = node!.next } } return nil } public func clear() { head = nil tail = nil _count = 0 } public func remove(node: Node<T>) -> T { let prev = node.previous let next = node.next if let prev = prev { prev.next = next } else { head = next } next?.previous = prev if next == nil { tail = prev } self._count -= 1 node.previous = nil node.next = nil return node.value } public func remove(at: Int) { if let node = nodeAt(index: at) { _ = remove(node: node) } } public var count: Int { return self._count } } /** * Thread-safe queue implementation */ public class ConcurrentQueue<T> { private var elements = LinkedList<T>() private let accessQueue = DispatchQueue(label: "be.michotte.hstracker.concurrentQueue") public func enqueue(value: T) { self.accessQueue.sync { self.elements.append(value) } } public func enqueueAll(collection: [T]) { self.accessQueue.sync { self.elements.appendAll(collection) } } public func dequeue() -> T? { var result: T? self.accessQueue.sync { if let head = self.elements.first { result = self.elements.remove(node: head) } } return result } public var count: Int { var result = 0 self.accessQueue.sync { result = self.elements.count } return result } public func clear() { self.accessQueue.sync { self.elements.clear() } } }
mit
e2290b53dec48373236032a7a4f67c73
19.287879
91
0.510082
4.250794
false
false
false
false
LKY769215561/KYHandMade
KYHandMade/Pods/DynamicColor/Sources/DynamicColor+Mixing.swift
1
5654
/* * DynamicColor * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.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. * */ #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #elseif os(OSX) import AppKit #endif // MARK: Mixing Colors public extension DynamicColor { /** Mixes the given color object with the receiver. Specifically, takes the average of each of the RGB components, optionally weighted by the given percentage. - Parameter color: A color object to mix with the receiver. - Parameter weight: The weight specifies the amount of the given color object (between 0 and 1). The default value is 0.5, which means that half the given color and half the receiver color object should be used. 0.25 means that a quarter of the given color object and three quarters of the receiver color object should be used. - Parameter colorspace: The color space used to mix the colors. By default it uses the RBG color space. - Returns: A color object corresponding to the two colors object mixed together. */ public final func mixed(withColor color: DynamicColor, weight: CGFloat = 0.5, inColorSpace colorspace: DynamicColorSpace = .rgb) -> DynamicColor { let normalizedWeight = clip(weight, 0, 1) switch colorspace { case .lab: return mixedLab(withColor: color, weight: normalizedWeight) case .hsl: return mixedHSL(withColor: color, weight: normalizedWeight) case .hsb: return mixedHSB(withColor: color, weight: normalizedWeight) case .rgb: return mixedRGB(withColor: color, weight: normalizedWeight) } } /** Creates and returns a color object corresponding to the mix of the receiver and an amount of white color, which increases lightness. - Parameter amount: Float between 0.0 and 1.0. The default amount is equal to 0.2. - Returns: A lighter DynamicColor. */ public final func tinted(amount: CGFloat = 0.2) -> DynamicColor { return mixed(withColor: .white, weight: amount) } /** Creates and returns a color object corresponding to the mix of the receiver and an amount of black color, which reduces lightness. - Parameter amount: Float between 0.0 and 1.0. The default amount is equal to 0.2. - Returns: A darker DynamicColor. */ public final func shaded(amount: CGFloat = 0.2) -> DynamicColor { return mixed(withColor: DynamicColor(red:0, green:0, blue: 0, alpha:1), weight: amount) } // MARK: - Convenient Internal Methods func mixedLab(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor { let c1 = toLabComponents() let c2 = color.toLabComponents() let L = c1.L + weight * (c2.L - c1.L) let a = c1.a + weight * (c2.a - c1.a) let b = c1.b + weight * (c2.b - c1.b) let alpha = alphaComponent + weight * (color.alphaComponent - alphaComponent) return DynamicColor(L: L, a: a, b: b, alpha: alpha) } func mixedHSL(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor { let c1 = toHSLComponents() let c2 = color.toHSLComponents() let h = c1.h + weight * mixedHue(source: c1.h, target: c2.h) let s = c1.s + weight * (c2.s - c1.s) let l = c1.l + weight * (c2.l - c1.l) let alpha = alphaComponent + weight * (color.alphaComponent - alphaComponent) return DynamicColor(hue: h, saturation: s, lightness: l, alpha: alpha) } func mixedHSB(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor { let c1 = toHSBComponents() let c2 = color.toHSBComponents() let h = c1.h + weight * mixedHue(source: c1.h, target: c2.h) let s = c1.s + weight * (c2.s - c1.s) let b = c1.b + weight * (c2.b - c1.b) let alpha = alphaComponent + weight * (color.alphaComponent - alphaComponent) return DynamicColor(hue: h, saturation: s, brightness: b, alpha: alpha) } func mixedRGB(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor { let c1 = toRGBAComponents() let c2 = color.toRGBAComponents() let red = c1.r + weight * (c2.r - c1.r) let green = c1.g + weight * (c2.g - c1.g) let blue = c1.b + weight * (c2.b - c1.b) let alpha = alphaComponent + weight * (color.alphaComponent - alphaComponent) return DynamicColor(red: red, green: green, blue: blue, alpha: alpha) } func mixedHue(source: CGFloat, target: CGFloat) -> CGFloat { if target > source && target - source > 180 { return target - source + 360 } else if target < source && source - target > 180 { return target + 360 - source } return target - source } }
apache-2.0
7457b029283de27903d2708c6e508f29
38.538462
148
0.689247
3.912803
false
false
false
false
OneBestWay/EasyCode
Example/touchMeIn-completed/TouchMeIn/MasterViewController.swift
1
7358
/* * Copyright (c) 2017 Razeware LLC * * 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 import CoreData class MasterViewController: UIViewController, UITableViewDelegate { @IBOutlet var tableView: UITableView! var isAuthenticated = false var managedObjectContext: NSManagedObjectContext! var didReturnFromBackground = false override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = editButtonItem view.alpha = 0 let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:))) navigationItem.rightBarButtonItem = addButton NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive(_:)), name: .UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive(_:)), name: .UIApplicationDidBecomeActive, object: nil) } @IBAction func unwindSegue(_ segue: UIStoryboardSegue) { isAuthenticated = true view.alpha = 1.0 } func appWillResignActive(_ notification : Notification) { view.alpha = 0 isAuthenticated = false didReturnFromBackground = true } func appDidBecomeActive(_ notification : Notification) { if didReturnFromBackground { showLoginView() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) showLoginView() } func showLoginView() { if !isAuthenticated { performSegue(withIdentifier: "loginView", sender: self) } } func insertNewObject(_ sender: AnyObject) { let context = fetchedResultsController.managedObjectContext guard let entityName = fetchedResultsController.fetchRequest.entity?.name else { return } let newNote = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! Note newNote.date = Date() newNote.noteText = "New Note" do { try context.save() } catch { print("Error inserting data \(error)") } } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { guard let indexPath = tableView.indexPathForSelectedRow else { return } let note = fetchedResultsController.object(at: indexPath) (segue.destination as! DetailViewController).note = note } } // MARK: - Table View @IBAction func logoutAction(_ sender: AnyObject) { isAuthenticated = false performSegue(withIdentifier: "loginView", sender: self) } // MARK: - Fetched results controller lazy var fetchedResultsController: NSFetchedResultsController<Note> = { let fetchRequest = Note.fetchRequest() as! NSFetchRequest<Note> fetchRequest.fetchBatchSize = 20 let sortDescriptor = NSSortDescriptor(key: "date", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master") fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() } catch let error { print(error) } return fetchedResultsController }() } // MARK: - UITableViewDelegate extension MasterViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell let note = self.fetchedResultsController.object(at: indexPath) configure(cell, with: note) return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let context = self.fetchedResultsController.managedObjectContext context.delete(self.fetchedResultsController.object(at: indexPath)) do { try context.save() } catch let error1 as NSError { print("Error editing the table \(error1)") abort() } } } func configure(_ cell: UITableViewCell, with note: Note) { cell.textLabel!.text = note.noteText.description } } extension MasterViewController: NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: tableView.insertSections([sectionIndex], with: .fade) case .delete: tableView.deleteSections([sectionIndex], with: .fade) default: return } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) case .update: guard let cell = tableView.cellForRow(at: indexPath!), let note = anObject as? Note else { return } configure(cell, with: note) case .move: tableView.deleteRows(at: [indexPath!], with: .fade) tableView.insertRows(at: [newIndexPath!], with: .fade) } } }
mit
4beba5a8da40467de978fff34488fa77
30.715517
207
0.696793
5.38259
false
false
false
false
hughbe/swift
stdlib/public/core/Mirror.swift
4
34763
//===--- Mirror.swift -----------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // FIXME: ExistentialCollection needs to be supported before this will work // without the ObjC Runtime. /// Representation of the sub-structure and optional "display style" /// of any arbitrary subject instance. /// /// Describes the parts---such as stored properties, collection /// elements, tuple elements, or the active enumeration case---that /// make up a particular instance. May also supply a "display style" /// property that suggests how this structure might be rendered. /// /// Mirrors are used by playgrounds and the debugger. public struct Mirror { /// Representation of descendant classes that don't override /// `customMirror`. /// /// Note that the effect of this setting goes no deeper than the /// nearest descendant class that overrides `customMirror`, which /// in turn can determine representation of *its* descendants. internal enum _DefaultDescendantRepresentation { /// Generate a default mirror for descendant classes that don't /// override `customMirror`. /// /// This case is the default. case generated /// Suppress the representation of descendant classes that don't /// override `customMirror`. /// /// This option may be useful at the root of a class cluster, where /// implementation details of descendants should generally not be /// visible to clients. case suppressed } /// Representation of ancestor classes. /// /// A `CustomReflectable` class can control how its mirror will /// represent ancestor classes by initializing the mirror with a /// `AncestorRepresentation`. This setting has no effect on mirrors /// reflecting value type instances. public enum AncestorRepresentation { /// Generate a default mirror for all ancestor classes. /// /// This case is the default. /// /// - Note: This option generates default mirrors even for /// ancestor classes that may implement `CustomReflectable`'s /// `customMirror` requirement. To avoid dropping an ancestor class /// customization, an override of `customMirror` should pass /// `ancestorRepresentation: .Customized(super.customMirror)` when /// initializing its `Mirror`. case generated /// Use the nearest ancestor's implementation of `customMirror` to /// create a mirror for that ancestor. Other classes derived from /// such an ancestor are given a default mirror. /// /// The payload for this option should always be /// "`{ super.customMirror }`": /// /// var customMirror: Mirror { /// return Mirror( /// self, /// children: ["someProperty": self.someProperty], /// ancestorRepresentation: .Customized({ super.customMirror })) // <== /// } case customized(() -> Mirror) /// Suppress the representation of all ancestor classes. The /// resulting `Mirror`'s `superclassMirror` is `nil`. case suppressed } /// Reflect upon the given `subject`. /// /// If the dynamic type of `subject` conforms to `CustomReflectable`, /// the resulting mirror is determined by its `customMirror` property. /// Otherwise, the result is generated by the language. /// /// - Note: If the dynamic type of `subject` has value semantics, /// subsequent mutations of `subject` will not observable in /// `Mirror`. In general, though, the observability of such /// mutations is unspecified. public init(reflecting subject: Any) { if case let customized as CustomReflectable = subject { self = customized.customMirror } else { self = Mirror( legacy: _reflect(subject), subjectType: type(of: subject)) } } /// An element of the reflected instance's structure. The optional /// `label` may be used when appropriate, e.g. to represent the name /// of a stored property or of an active `enum` case, and will be /// used for lookup when `String`s are passed to the `descendant` /// method. public typealias Child = (label: String?, value: Any) /// The type used to represent sub-structure. /// /// Depending on your needs, you may find it useful to "upgrade" /// instances of this type to `AnyBidirectionalCollection` or /// `AnyRandomAccessCollection`. For example, to display the last /// 20 children of a mirror if they can be accessed efficiently, you /// might write: /// /// if let b = AnyBidirectionalCollection(someMirror.children) { /// var i = xs.index(b.endIndex, offsetBy: -20, /// limitedBy: b.startIndex) ?? b.startIndex /// while i != xs.endIndex { /// print(b[i]) /// b.formIndex(after: &i) /// } /// } public typealias Children = AnyCollection<Child> /// A suggestion of how a `Mirror`'s `subject` is to be interpreted. /// /// Playgrounds and the debugger will show a representation similar /// to the one used for instances of the kind indicated by the /// `DisplayStyle` case name when the `Mirror` is used for display. public enum DisplayStyle { case `struct`, `class`, `enum`, tuple, optional, collection case dictionary, `set` } static func _noSuperclassMirror() -> Mirror? { return nil } /// Returns the legacy mirror representing the part of `subject` /// corresponding to the superclass of `staticSubclass`. internal static func _legacyMirror( _ subject: AnyObject, asClass targetSuperclass: AnyClass) -> _Mirror? { // get a legacy mirror and the most-derived type var cls: AnyClass = type(of: subject) var clsMirror = _reflect(subject) // Walk up the chain of mirrors/classes until we find staticSubclass while let superclass: AnyClass = _getSuperclass(cls) { guard let superclassMirror = clsMirror._superMirror() else { break } if superclass == targetSuperclass { return superclassMirror } clsMirror = superclassMirror cls = superclass } return nil } @_semantics("optimize.sil.specialize.generic.never") @inline(never) @_versioned internal static func _superclassIterator<Subject>( _ subject: Subject, _ ancestorRepresentation: AncestorRepresentation ) -> () -> Mirror? { if let subjectClass = Subject.self as? AnyClass, let superclass = _getSuperclass(subjectClass) { switch ancestorRepresentation { case .generated: return { self._legacyMirror(_unsafeDowncastToAnyObject(fromAny: subject), asClass: superclass).map { Mirror(legacy: $0, subjectType: superclass) } } case .customized(let makeAncestor): return { Mirror(_unsafeDowncastToAnyObject(fromAny: subject), subjectClass: superclass, ancestor: makeAncestor()) } case .suppressed: break } } return Mirror._noSuperclassMirror } /// Represent `subject` with structure described by `children`, /// using an optional `displayStyle`. /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .customized({ super.customMirror }) /// /// - Note: The traversal protocol modeled by `children`'s indices /// (`ForwardIndex`, `BidirectionalIndex`, or /// `RandomAccessIndex`) is captured so that the resulting /// `Mirror`'s `children` may be upgraded later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject, C : Collection>( _ subject: Subject, children: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) where C.Element == Child // FIXME(ABI) (Revert Where Clauses): Remove these , C.SubSequence : Collection, C.SubSequence.Indices : Collection, C.Indices : Collection { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) self.children = Children(children) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Represent `subject` with child values given by /// `unlabeledChildren`, using an optional `displayStyle`. The /// result's child labels will all be `nil`. /// /// This initializer is especially useful for the mirrors of /// collections, e.g.: /// /// extension MyArray : CustomReflectable { /// var customMirror: Mirror { /// return Mirror(self, unlabeledChildren: self, displayStyle: .collection) /// } /// } /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .Customized({ super.customMirror }) /// /// - Note: The traversal protocol modeled by `children`'s indices /// (`ForwardIndex`, `BidirectionalIndex`, or /// `RandomAccessIndex`) is captured so that the resulting /// `Mirror`'s `children` may be upgraded later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject, C : Collection>( _ subject: Subject, unlabeledChildren: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) // FIXME(ABI) (Revert Where Clauses): Remove these two clauses where C.SubSequence : Collection, C.Indices : Collection { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) let lazyChildren = unlabeledChildren.lazy.map { Child(label: nil, value: $0) } self.children = Children(lazyChildren) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Represent `subject` with labeled structure described by /// `children`, using an optional `displayStyle`. /// /// Pass a dictionary literal with `String` keys as `children`. Be /// aware that although an *actual* `Dictionary` is /// arbitrarily-ordered, the ordering of the `Mirror`'s `children` /// will exactly match that of the literal you pass. /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .customized({ super.customMirror }) /// /// - Note: The resulting `Mirror`'s `children` may be upgraded to /// `AnyRandomAccessCollection` later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject>( _ subject: Subject, children: DictionaryLiteral<String, Any>, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) } self.children = Children(lazyChildren) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// The static type of the subject being reflected. /// /// This type may differ from the subject's dynamic type when `self` /// is the `superclassMirror` of another mirror. public let subjectType: Any.Type /// A collection of `Child` elements describing the structure of the /// reflected subject. public let children: Children /// Suggests a display style for the reflected subject. public let displayStyle: DisplayStyle? public var superclassMirror: Mirror? { return _makeSuperclassMirror() } internal let _makeSuperclassMirror: () -> Mirror? internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation } /// A type that explicitly supplies its own mirror. /// /// You can create a mirror for any type using the `Mirror(reflect:)` /// initializer, but if you are not satisfied with the mirror supplied for /// your type by default, you can make it conform to `CustomReflectable` and /// return a custom `Mirror` instance. public protocol CustomReflectable { /// The custom mirror for this instance. /// /// If this type has value semantics, the mirror should be unaffected by /// subsequent mutations of the instance. var customMirror: Mirror { get } } /// A type that explicitly supplies its own mirror, but whose /// descendant classes are not represented in the mirror unless they /// also override `customMirror`. public protocol CustomLeafReflectable : CustomReflectable {} //===--- Addressing -------------------------------------------------------===// /// A protocol for legitimate arguments to `Mirror`'s `descendant` /// method. /// /// Do not declare new conformances to this protocol; they will not /// work as expected. // FIXME(ABI)#49 (Sealed Protocols): this protocol should be "non-open" and you shouldn't be able to // create conformances. public protocol MirrorPath {} extension Int : MirrorPath {} extension String : MirrorPath {} extension Mirror { internal struct _Dummy : CustomReflectable { var mirror: Mirror var customMirror: Mirror { return mirror } } /// Return a specific descendant of the reflected subject, or `nil` /// Returns a specific descendant of the reflected subject, or `nil` /// if no such descendant exists. /// /// A `String` argument selects the first `Child` with a matching label. /// An integer argument *n* select the *n*th `Child`. For example: /// /// var d = Mirror(reflecting: x).descendant(1, "two", 3) /// /// is equivalent to: /// /// var d = nil /// let children = Mirror(reflecting: x).children /// if let p0 = children.index(children.startIndex, /// offsetBy: 1, limitedBy: children.endIndex) { /// let grandChildren = Mirror(reflecting: children[p0].value).children /// SeekTwo: for g in grandChildren { /// if g.label == "two" { /// let greatGrandChildren = Mirror(reflecting: g.value).children /// if let p1 = greatGrandChildren.index( /// greatGrandChildren.startIndex, /// offsetBy: 3, limitedBy: greatGrandChildren.endIndex) { /// d = greatGrandChildren[p1].value /// } /// break SeekTwo /// } /// } /// } /// /// As you can see, complexity for each element of the argument list /// depends on the argument type and capabilities of the collection /// used to initialize the corresponding subject's parent's mirror. /// Each `String` argument results in a linear search. In short, /// this function is suitable for exploring the structure of a /// `Mirror` in a REPL or playground, but don't expect it to be /// efficient. public func descendant( _ first: MirrorPath, _ rest: MirrorPath... ) -> Any? { var result: Any = _Dummy(mirror: self) for e in [first] + rest { let children = Mirror(reflecting: result).children let position: Children.Index if case let label as String = e { position = children.index { $0.label == label } ?? children.endIndex } else if let offset = (e as? Int).map({ IntMax($0) }) ?? (e as? IntMax) { position = children.index(children.startIndex, offsetBy: offset, limitedBy: children.endIndex) ?? children.endIndex } else { _preconditionFailure( "Someone added a conformance to MirrorPath; that privilege is reserved to the standard library") } if position == children.endIndex { return nil } result = children[position].value } return result } } //===--- Legacy _Mirror Support -------------------------------------------===// extension Mirror.DisplayStyle { /// Construct from a legacy `_MirrorDisposition` internal init?(legacy: _MirrorDisposition) { switch legacy { case .`struct`: self = .`struct` case .`class`: self = .`class` case .`enum`: self = .`enum` case .tuple: self = .tuple case .aggregate: return nil case .indexContainer: self = .collection case .keyContainer: self = .dictionary case .membershipContainer: self = .`set` case .container: preconditionFailure("unused!") case .optional: self = .optional case .objCObject: self = .`class` } } } internal func _isClassSuperMirror(_ t: Any.Type) -> Bool { #if _runtime(_ObjC) return t == _ClassSuperMirror.self || t == _ObjCSuperMirror.self #else return t == _ClassSuperMirror.self #endif } extension _Mirror { internal func _superMirror() -> _Mirror? { if self.count > 0 { let childMirror = self[0].1 if _isClassSuperMirror(type(of: childMirror)) { return childMirror } } return nil } } /// When constructed using the legacy reflection infrastructure, the /// resulting `Mirror`'s `children` collection will always be /// upgradable to `AnyRandomAccessCollection` even if it doesn't /// exhibit appropriate performance. To avoid this pitfall, convert /// mirrors to use the new style, which only present forward /// traversal in general. internal extension Mirror { /// An adapter that represents a legacy `_Mirror`'s children as /// a `Collection` with integer `Index`. Note that the performance /// characteristics of the underlying `_Mirror` may not be /// appropriate for random access! To avoid this pitfall, convert /// mirrors to use the new style, which only present forward /// traversal in general. internal struct LegacyChildren : RandomAccessCollection { typealias Indices = CountableRange<Int> init(_ oldMirror: _Mirror) { self._oldMirror = oldMirror } var startIndex: Int { return _oldMirror._superMirror() == nil ? 0 : 1 } var endIndex: Int { return _oldMirror.count } subscript(position: Int) -> Child { let (label, childMirror) = _oldMirror[position] return (label: label, value: childMirror.value) } internal let _oldMirror: _Mirror } /// Initialize for a view of `subject` as `subjectClass`. /// /// - parameter ancestor: A Mirror for a (non-strict) ancestor of /// `subjectClass`, to be injected into the resulting hierarchy. /// /// - parameter legacy: Either `nil`, or a legacy mirror for `subject` /// as `subjectClass`. internal init( _ subject: AnyObject, subjectClass: AnyClass, ancestor: Mirror, legacy legacyMirror: _Mirror? = nil ) { if ancestor.subjectType == subjectClass || ancestor._defaultDescendantRepresentation == .suppressed { self = ancestor } else { let legacyMirror = legacyMirror ?? Mirror._legacyMirror( subject, asClass: subjectClass)! self = Mirror( legacy: legacyMirror, subjectType: subjectClass, makeSuperclassMirror: { _getSuperclass(subjectClass).map { Mirror( subject, subjectClass: $0, ancestor: ancestor, legacy: legacyMirror._superMirror()) } }) } } internal init( legacy legacyMirror: _Mirror, subjectType: Any.Type, makeSuperclassMirror: (() -> Mirror?)? = nil ) { if let makeSuperclassMirror = makeSuperclassMirror { self._makeSuperclassMirror = makeSuperclassMirror } else if let subjectSuperclass = _getSuperclass(subjectType) { self._makeSuperclassMirror = { legacyMirror._superMirror().map { Mirror(legacy: $0, subjectType: subjectSuperclass) } } } else { self._makeSuperclassMirror = Mirror._noSuperclassMirror } self.subjectType = subjectType self.children = Children(LegacyChildren(legacyMirror)) self.displayStyle = DisplayStyle(legacy: legacyMirror.disposition) self._defaultDescendantRepresentation = .generated } } //===--- QuickLooks -------------------------------------------------------===// /// The sum of types that can be used as a Quick Look representation. public enum PlaygroundQuickLook { /// Plain text. case text(String) /// An integer numeric value. case int(Int64) /// An unsigned integer numeric value. case uInt(UInt64) /// A single precision floating-point numeric value. case float(Float32) /// A double precision floating-point numeric value. case double(Float64) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// An image. case image(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A sound. case sound(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A color. case color(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A bezier path. case bezierPath(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// An attributed string. case attributedString(Any) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A rectangle. case rectangle(Float64, Float64, Float64, Float64) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A point. case point(Float64, Float64) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A size. case size(Float64, Float64) /// A boolean value. case bool(Bool) // FIXME: Uses explicit values to avoid coupling a particular Cocoa type. /// A range. case range(Int64, Int64) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A GUI view. case view(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A graphical sprite. case sprite(Any) /// A Uniform Resource Locator. case url(String) /// Raw data that has already been encoded in a format the IDE understands. case _raw([UInt8], String) } extension PlaygroundQuickLook { /// Initialize for the given `subject`. /// /// If the dynamic type of `subject` conforms to /// `CustomPlaygroundQuickLookable`, returns the result of calling /// its `customPlaygroundQuickLook` property. Otherwise, returns /// a `PlaygroundQuickLook` synthesized for `subject` by the /// language. Note that in some cases the result may be /// `.Text(String(reflecting: subject))`. /// /// - Note: If the dynamic type of `subject` has value semantics, /// subsequent mutations of `subject` will not observable in /// `Mirror`. In general, though, the observability of such /// mutations is unspecified. public init(reflecting subject: Any) { if let customized = subject as? CustomPlaygroundQuickLookable { self = customized.customPlaygroundQuickLook } else if let customized = subject as? _DefaultCustomPlaygroundQuickLookable { self = customized._defaultCustomPlaygroundQuickLook } else { if let q = _reflect(subject).quickLookObject { self = q } else { self = .text(String(reflecting: subject)) } } } } /// A type that explicitly supplies its own playground Quick Look. /// /// A Quick Look can be created for an instance of any type by using the /// `PlaygroundQuickLook(reflecting:)` initializer. If you are not satisfied /// with the representation supplied for your type by default, you can make it /// conform to the `CustomPlaygroundQuickLookable` protocol and provide a /// custom `PlaygroundQuickLook` instance. public protocol CustomPlaygroundQuickLookable { /// A custom playground Quick Look for this instance. /// /// If this type has value semantics, the `PlaygroundQuickLook` instance /// should be unaffected by subsequent mutations. var customPlaygroundQuickLook: PlaygroundQuickLook { get } } // A workaround for <rdar://problem/26182650> // FIXME(ABI)#50 (Dynamic Dispatch for Class Extensions) though not if it moves out of stdlib. public protocol _DefaultCustomPlaygroundQuickLookable { var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { get } } //===--- General Utilities ------------------------------------------------===// // This component could stand alone, but is used in Mirror's public interface. /// A lightweight collection of key-value pairs. /// /// Use a `DictionaryLiteral` instance when you need an ordered collection of /// key-value pairs and don't require the fast key lookup that the /// `Dictionary` type provides. Unlike key-value pairs in a true dictionary, /// neither the key nor the value of a `DictionaryLiteral` instance must /// conform to the `Hashable` protocol. /// /// You initialize a `DictionaryLiteral` instance using a Swift dictionary /// literal. Besides maintaining the order of the original dictionary literal, /// `DictionaryLiteral` also allows duplicates keys. For example: /// /// let recordTimes: DictionaryLiteral = ["Florence Griffith-Joyner": 10.49, /// "Evelyn Ashford": 10.76, /// "Evelyn Ashford": 10.79, /// "Marlies Gohr": 10.81] /// print(recordTimes.first!) /// // Prints "("Florence Griffith-Joyner", 10.49)" /// /// Some operations that are efficient on a dictionary are slower when using /// `DictionaryLiteral`. In particular, to find the value matching a key, you /// must search through every element of the collection. The call to /// `index(where:)` in the following example must traverse the whole /// collection to find the element that matches the predicate: /// /// let runner = "Marlies Gohr" /// if let index = recordTimes.index(where: { $0.0 == runner }) { /// let time = recordTimes[index].1 /// print("\(runner) set a 100m record of \(time) seconds.") /// } else { /// print("\(runner) couldn't be found in the records.") /// } /// // Prints "Marlies Gohr set a 100m record of 10.81 seconds." /// /// Dictionary Literals as Function Parameters /// ------------------------------------------ /// /// When calling a function with a `DictionaryLiteral` parameter, you can pass /// a Swift dictionary literal without causing a `Dictionary` to be created. /// This capability can be especially important when the order of elements in /// the literal is significant. /// /// For example, you could create an `IntPairs` structure that holds a list of /// two-integer tuples and use an initializer that accepts a /// `DictionaryLiteral` instance. /// /// struct IntPairs { /// var elements: [(Int, Int)] /// /// init(_ elements: DictionaryLiteral<Int, Int>) { /// self.elements = Array(elements) /// } /// } /// /// When you're ready to create a new `IntPairs` instance, use a dictionary /// literal as the parameter to the `IntPairs` initializer. The /// `DictionaryLiteral` instance preserves the order of the elements as /// passed. /// /// let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1]) /// print(pairs.elements) /// // Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]" public struct DictionaryLiteral<Key, Value> : ExpressibleByDictionaryLiteral { /// Creates a new `DictionaryLiteral` instance from the given dictionary /// literal. /// /// The order of the key-value pairs is kept intact in the resulting /// `DictionaryLiteral` instance. public init(dictionaryLiteral elements: (Key, Value)...) { self._elements = elements } internal let _elements: [(Key, Value)] } /// `Collection` conformance that allows `DictionaryLiteral` to /// interoperate with the rest of the standard library. extension DictionaryLiteral : RandomAccessCollection { public typealias Indices = CountableRange<Int> /// The position of the first element in a nonempty collection. /// /// If the `DictionaryLiteral` instance is empty, `startIndex` is equal to /// `endIndex`. public var startIndex: Int { return 0 } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// If the `DictionaryLiteral` instance is empty, `endIndex` is equal to /// `startIndex`. public var endIndex: Int { return _elements.endIndex } // FIXME(ABI)#174 (Type checker): a typealias is needed to prevent <rdar://20248032> /// The element type of a `DictionaryLiteral`: a tuple containing an /// individual key-value pair. public typealias Element = (key: Key, value: Value) /// Accesses the element at the specified position. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// - Returns: The key-value pair at position `position`. public subscript(position: Int) -> Element { return _elements[position] } } extension String { /// Creates a string representing the given value. /// /// Use this initializer to convert an instance of any type to its preferred /// representation as a `String` instance. The initializer creates the /// string representation of `instance` in one of the following ways, /// depending on its protocol conformance: /// /// - If `instance` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `instance.write(to: s)` on an empty /// string `s`. /// - If `instance` conforms to the `CustomStringConvertible` protocol, the /// result is `instance.description`. /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `instance.debugDescription`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(describing: p)) /// // Prints "Point(x: 21, y: 30)" /// /// After adding `CustomStringConvertible` conformance by implementing the /// `description` property, `Point` provides its own custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(String(describing: p)) /// // Prints "(21, 30)" public init<Subject>(describing instance: Subject) { self.init() _print_unlocked(instance, &self) } /// Creates a string with a detailed representation of the given value, /// suitable for debugging. /// /// Use this initializer to convert an instance of any type to its custom /// debugging representation. The initializer creates the string /// representation of `instance` in one of the following ways, depending on /// its protocol conformance: /// /// - If `subject` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `subject.debugDescription`. /// - If `subject` conforms to the `CustomStringConvertible` protocol, the /// result is `subject.description`. /// - If `subject` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `subject.write(to: s)` on an empty /// string `s`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "p: Point = { /// // x = 21 /// // y = 30 /// // }" /// /// After adding `CustomDebugStringConvertible` conformance by implementing /// the `debugDescription` property, `Point` provides its own custom /// debugging representation. /// /// extension Point: CustomDebugStringConvertible { /// var debugDescription: String { /// return "Point(x: \(x), y: \(y))" /// } /// } /// /// print(String(reflecting: p)) /// // Prints "Point(x: 21, y: 30)" public init<Subject>(reflecting subject: Subject) { self.init() _debugPrint_unlocked(subject, &self) } } /// Reflection for `Mirror` itself. extension Mirror : CustomStringConvertible { public var description: String { return "Mirror for \(self.subjectType)" } } extension Mirror : CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: [:]) } } @available(*, unavailable, renamed: "MirrorPath") public typealias MirrorPathType = MirrorPath
apache-2.0
dc753cb51985f7b392d1e5730d6ba403
36.37957
106
0.662917
4.707244
false
false
false
false
ryanglobus/Augustus
Augustus/Augustus/AppDelegate.swift
1
2883
// // AppDelegate.swift // Augustus // // Created by Ryan Globus on 6/22/15. // Copyright (c) 2015 Ryan Globus. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { let log = AULog.instance func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application // TODO make below queue proper UI queue/execute in UI queue // TODO test below // TODO is below even needed? self.alertIfEventStorePermissionDenied() NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: AUModel.notificationName), object: nil, queue: nil, using: { (notification: Notification) -> Void in DispatchQueue.main.async { self.alertIfEventStorePermissionDenied() } }) log.info("did finish launching") } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application log.info("will terminate") } func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } fileprivate func alertIfEventStorePermissionDenied() { if AUModel.eventStore.permission == .denied { let alert = NSAlert() alert.addButton(withTitle: "Go to System Preferences...") alert.addButton(withTitle: "Quit") alert.messageText = "Please grant Augustus access to your calendars." alert.informativeText = "You must grant Augustus access to your calendars in order to see or create events. To do so, go to System Preferences. Select Calendars in the left pane. Then, in the center pane, click the checkbox next to Augustus. Then restart Augustus." alert.alertStyle = NSAlertStyle.warning let response = alert.runModal() if response == NSAlertFirstButtonReturn { let scriptSource = "tell application \"System Preferences\"\n" + "set securityPane to pane id \"com.apple.preference.security\"\n" + "tell securityPane to reveal anchor \"Privacy\"\n" + "set the current pane to securityPane\n" + "activate\n" + "end tell" let script = NSAppleScript(source: scriptSource) let error: AutoreleasingUnsafeMutablePointer<NSDictionary?>? = nil self.log.info("About to go to System Preferences") if script?.executeAndReturnError(error) == nil { self.log.error(error.debugDescription) } // TODO now what? } else { NSApplication.shared().terminate(self) } } } }
gpl-2.0
e8285ed351c56f98476e8975613bc27f
39.041667
277
0.61984
5.348794
false
false
false
false
felipedemetrius/WatchMe
WatchMeTests/SerieModelTests.swift
1
2106
// // SerieModelTests.swift // WatchMe // // Created by Felipe Silva on 1/23/17. // Copyright © 2017 Felipe Silva . All rights reserved. // import XCTest @testable import WatchMe class SerieModelTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSerieUpdate() { let wait = expectation(description: "nt") SerieRepository.nextTrending { series in if let serie = series?.first{ serie.update(value: true, key: "watching") serie.update(value: false, key: "watching") serie.remove() } XCTAssertNotNil(series) wait.fulfill() } waitForExpectations(timeout: 4.0, handler: nil) } func testSerieAddRemoveEpisode() { let wait = expectation(description: "saddrm") SerieRepository.searchSeries(text: "oa") { series in if let serie = series?.first{ EpisodeRepository.getEpisodeDetail(slug: "the-oa", season: 1, episode: 1) { episode in if let episode = episode{ serie.addEpisode(episode: episode) serie.removeEpisode(episode: episode) serie.addEpisode(episode: episode) if let serie = SerieRepository.getLocal(slug: "the-oa") { serie.remove() } } wait.fulfill() } } } waitForExpectations(timeout: 6.0, handler: nil) } }
mit
34198a1a9f8df8416499a8af7b197c3e
28.236111
111
0.489786
5.34264
false
true
false
false
gb-6k-house/YsSwift
Sources/Peacock/Utils/SwiftUserDefaults.swift
1
15213
// // SwiftyUserDefaults // // Copyright (c) 2015-2016 Radosław Pietruszewski // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public extension UserDefaults { class Proxy { fileprivate let defaults: UserDefaults fileprivate let key: String fileprivate init(_ defaults: UserDefaults, _ key: String) { self.defaults = defaults self.key = key } // MARK: Getters public var object: Any? { return defaults.object(forKey: key) } public var string: String? { return defaults.string(forKey: key) } public var array: [Any]? { return defaults.array(forKey: key) } public var dictionary: [String: Any]? { return defaults.dictionary(forKey: key) } public var data: Data? { return defaults.data(forKey: key) } public var date: Date? { return object as? Date } public var number: NSNumber? { return defaults.numberForKey(key) } public var int: Int? { return number?.intValue } public var double: Double? { return number?.doubleValue } public var bool: Bool? { return number?.boolValue } // MARK: Non-Optional Getters public var stringValue: String { return string ?? "" } public var arrayValue: [Any] { return array ?? [] } public var dictionaryValue: [String: Any] { return dictionary ?? [:] } public var dataValue: Data { return data ?? Data() } public var numberValue: NSNumber { return number ?? 0 } public var intValue: Int { return int ?? 0 } public var doubleValue: Double { return double ?? 0 } public var boolValue: Bool { return bool ?? false } } /// `NSNumber` representation of a user default func numberForKey(_ key: String) -> NSNumber? { return object(forKey: key) as? NSNumber } /// Returns getter proxy for `key` public subscript(key: String) -> Proxy { return Proxy(self, key) } /// Sets value for `key` public subscript(key: String) -> Any? { get { // return untyped Proxy // (make sure we don't fall into infinite loop) let proxy: Proxy = self[key] return proxy } set { guard let newValue = newValue else { removeObject(forKey: key) return } switch newValue { // @warning This should always be on top of Int because a cast // from Double to Int will always succeed. case let v as Double: self.set(v, forKey: key) case let v as Int: self.set(v, forKey: key) case let v as Bool: self.set(v, forKey: key) case let v as URL: self.set(v, forKey: key) default: self.set(newValue, forKey: key) } } } /// Returns `true` if `key` exists public func hasKey(_ key: String) -> Bool { return object(forKey: key) != nil } /// Removes value for `key` public func remove(_ key: String) { removeObject(forKey: key) } /// Removes all keys and values from user defaults /// Use with caution! /// - Note: This method only removes keys on the receiver `UserDefaults` object. /// System-defined keys will still be present afterwards. public func removeAll() { for (key, _) in dictionaryRepresentation() { removeObject(forKey: key) } } } /// Global shortcut for `UserDefaults.standard` /// /// **Pro-Tip:** If you want to use shared user defaults, just /// redefine this global shortcut in your app target, like so: /// ~~~ /// var Defaults = UserDefaults(suiteName: "com.my.app")! /// ~~~ public let Defaults = UserDefaults.standard // MARK: - Static keys /// Extend this class and add your user defaults keys as static constants /// so you can use the shortcut dot notation (e.g. `Defaults[.yourKey]`) open class DefaultsKeys { fileprivate init() {} } /// Base class for static user defaults keys. Specialize with value type /// and pass key name to the initializer to create a key. open class DefaultsKey<ValueType>: DefaultsKeys { // TODO: Can we use protocols to ensure ValueType is a compatible type? public let _key: String public init(_ key: String) { self._key = key super.init() } } extension UserDefaults { /// This function allows you to create your own custom Defaults subscript. Example: [Int: String] public func set<T>(_ key: DefaultsKey<T>, _ value: Any?) { self[key._key] = value } } extension UserDefaults { /// Returns `true` if `key` exists public func hasKey<T>(_ key: DefaultsKey<T>) -> Bool { return object(forKey: key._key) != nil } /// Removes value for `key` public func remove<T>(_ key: DefaultsKey<T>) { removeObject(forKey: key._key) } } // MARK: Subscripts for specific standard types // TODO: Use generic subscripts when they become available extension UserDefaults { public subscript(key: DefaultsKey<String?>) -> String? { get { return string(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<String>) -> String { get { return string(forKey: key._key) ?? "" } set { set(key, newValue) } } public subscript(key: DefaultsKey<Int?>) -> Int? { get { return numberForKey(key._key)?.intValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Int>) -> Int { get { return numberForKey(key._key)?.intValue ?? 0 } set { set(key, newValue) } } public subscript(key: DefaultsKey<Double?>) -> Double? { get { return numberForKey(key._key)?.doubleValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Double>) -> Double { get { return numberForKey(key._key)?.doubleValue ?? 0.0 } set { set(key, newValue) } } public subscript(key: DefaultsKey<Bool?>) -> Bool? { get { return numberForKey(key._key)?.boolValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Bool>) -> Bool { get { return numberForKey(key._key)?.boolValue ?? false } set { set(key, newValue) } } public subscript(key: DefaultsKey<Any?>) -> Any? { get { return object(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<Data?>) -> Data? { get { return data(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<Data>) -> Data { get { return data(forKey: key._key) ?? Data() } set { set(key, newValue) } } public subscript(key: DefaultsKey<Date?>) -> Date? { get { return object(forKey: key._key) as? Date } set { set(key, newValue) } } public subscript(key: DefaultsKey<URL?>) -> URL? { get { return url(forKey: key._key) } set { set(key, newValue) } } // TODO: It would probably make sense to have support for statically typed dictionaries (e.g. [String: String]) public subscript(key: DefaultsKey<[String: Any]?>) -> [String: Any]? { get { return dictionary(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[String: Any]>) -> [String: Any] { get { return dictionary(forKey: key._key) ?? [:] } set { set(key, newValue) } } } // MARK: Static subscripts for array types extension UserDefaults { public subscript(key: DefaultsKey<[Any]?>) -> [Any]? { get { return array(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Any]>) -> [Any] { get { return array(forKey: key._key) ?? [] } set { set(key, newValue) } } } // We need the <T: AnyObject> and <T: _ObjectiveCBridgeable> variants to // suppress compiler warnings about NSArray not being convertible to [T] // AnyObject is for NSData and NSDate, _ObjectiveCBridgeable is for value // types bridge-able to Foundation types (String, Int, ...) extension UserDefaults { public func getArray<T: _ObjectiveCBridgeable>(_ key: DefaultsKey<[T]>) -> [T] { return array(forKey: key._key) as NSArray? as? [T] ?? [] } public func getArray<T: _ObjectiveCBridgeable>(_ key: DefaultsKey<[T]?>) -> [T]? { return array(forKey: key._key) as NSArray? as? [T] } public func getArray<T: Any>(_ key: DefaultsKey<[T]>) -> [T] { return array(forKey: key._key) as NSArray? as? [T] ?? [] } public func getArray<T: Any>(_ key: DefaultsKey<[T]?>) -> [T]? { return array(forKey: key._key) as NSArray? as? [T] } } extension UserDefaults { public subscript(key: DefaultsKey<[String]?>) -> [String]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[String]>) -> [String] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Int]?>) -> [Int]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Int]>) -> [Int] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Double]?>) -> [Double]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Double]>) -> [Double] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Bool]?>) -> [Bool]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Bool]>) -> [Bool] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Data]?>) -> [Data]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Data]>) -> [Data] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Date]?>) -> [Date]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Date]>) -> [Date] { get { return getArray(key) } set { set(key, newValue) } } } // MARK: - Archiving custom types // MARK: RawRepresentable extension UserDefaults { // TODO: Ensure that T.RawValue is compatible public func archive<T: RawRepresentable>(_ key: DefaultsKey<T>, _ value: T) { set(key, value.rawValue) } public func archive<T: RawRepresentable>(_ key: DefaultsKey<T?>, _ value: T?) { if let value = value { set(key, value.rawValue) } else { remove(key) } } public func unarchive<T: RawRepresentable>(_ key: DefaultsKey<T?>) -> T? { return object(forKey: key._key).flatMap { T(rawValue: $0 as! T.RawValue) } } public func unarchive<T: RawRepresentable>(_ key: DefaultsKey<T>) -> T? { return object(forKey: key._key).flatMap { T(rawValue: $0 as! T.RawValue) } } } // MARK: NSCoding extension UserDefaults { // TODO: Can we simplify this and ensure that T is NSCoding compliant? public func archive<T>(_ key: DefaultsKey<T>, _ value: T) { set(key, NSKeyedArchiver.archivedData(withRootObject: value)) } public func archive<T>(_ key: DefaultsKey<T?>, _ value: T?) { if let value = value { set(key, NSKeyedArchiver.archivedData(withRootObject: value)) } else { remove(key) } } public func unarchive<T>(_ key: DefaultsKey<T>) -> T? { return data(forKey: key._key).flatMap { NSKeyedUnarchiver.unarchiveObject(with: $0) } as? T } public func unarchive<T>(_ key: DefaultsKey<T?>) -> T? { return data(forKey: key._key).flatMap { NSKeyedUnarchiver.unarchiveObject(with: $0) } as? T } } // MARK: - Deprecations infix operator ?= : AssignmentPrecedence /// If key doesn't exist, sets its value to `expr` /// - Deprecation: This will be removed in a future release. /// Please migrate to static keys and use this gist: https://gist.github.com/radex/68de9340b0da61d43e60 /// - Note: This isn't the same as `Defaults.registerDefaults`. This method saves the new value to disk, whereas `registerDefaults` only modifies the defaults in memory. /// - Note: If key already exists, the expression after ?= isn't evaluated @available(*, deprecated:1, message:"Please migrate to static keys and use this gist: https://gist.github.com/radex/68de9340b0da61d43e60") public func ?= (proxy: UserDefaults.Proxy, expr: @autoclosure() -> Any) { if !proxy.defaults.hasKey(proxy.key) { proxy.defaults[proxy.key] = expr() } } /// Adds `b` to the key (and saves it as an integer) /// If key doesn't exist or isn't a number, sets value to `b` @available(*, deprecated:1, message:"Please migrate to static keys to use this.") public func += (proxy: UserDefaults.Proxy, b: Int) { let a = proxy.defaults[proxy.key].intValue proxy.defaults[proxy.key] = a + b } @available(*, deprecated:1, message:"Please migrate to static keys to use this.") public func += (proxy: UserDefaults.Proxy, b: Double) { let a = proxy.defaults[proxy.key].doubleValue proxy.defaults[proxy.key] = a + b } /// Icrements key by one (and saves it as an integer) /// If key doesn't exist or isn't a number, sets value to 1 @available(*, deprecated:1, message:"Please migrate to static keys to use this.") public postfix func ++ (proxy: UserDefaults.Proxy) { proxy += 1 }
mit
a5449aee64083bbb09a4376328e99e41
29.18254
169
0.600513
4.128087
false
false
false
false
Johennes/firefox-ios
Client/Frontend/Share/ShareExtensionHelper.swift
1
6253
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import OnePasswordExtension private let log = Logger.browserLogger class ShareExtensionHelper: NSObject { private weak var selectedTab: Tab? private let selectedURL: NSURL private var onePasswordExtensionItem: NSExtensionItem! private let activities: [UIActivity] init(url: NSURL, tab: Tab?, activities: [UIActivity]) { self.selectedURL = url self.selectedTab = tab self.activities = activities } func createActivityViewController(completionHandler: (completed: Bool, activityType: String?) -> Void) -> UIActivityViewController { var activityItems = [AnyObject]() let printInfo = UIPrintInfo(dictionary: nil) let absoluteString = selectedTab?.url?.absoluteString ?? selectedURL.absoluteString if let absoluteString = absoluteString { printInfo.jobName = absoluteString } printInfo.outputType = .General activityItems.append(printInfo) if let tab = selectedTab { activityItems.append(TabPrintPageRenderer(tab: tab)) } if let title = selectedTab?.title { activityItems.append(TitleActivityItemProvider(title: title)) } activityItems.append(self) let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: activities) // Hide 'Add to Reading List' which currently uses Safari. // We would also hide View Later, if possible, but the exclusion list doesn't currently support // third-party activity types (rdar://19430419). activityViewController.excludedActivityTypes = [ UIActivityTypeAddToReadingList, ] // This needs to be ready by the time the share menu has been displayed and // activityViewController(activityViewController:, activityType:) is called, // which is after the user taps the button. So a million cycles away. if (ShareExtensionHelper.isPasswordManagerExtensionAvailable()) { findLoginExtensionItem() } activityViewController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in if !completed { completionHandler(completed: completed, activityType: activityType) return } if self.isPasswordManagerActivityType(activityType) { if let logins = returnedItems { self.fillPasswords(logins) } } completionHandler(completed: completed, activityType: activityType) } return activityViewController } } extension ShareExtensionHelper: UIActivityItemSource { func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject { if let displayURL = selectedTab?.displayURL { return displayURL } return selectedURL } func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? { if isPasswordManagerActivityType(activityType) { return onePasswordExtensionItem } else { // Return the URL for the selected tab. If we are in reader view then decode // it so that we copy the original and not the internal localhost one. if let url = selectedTab?.displayURL where ReaderModeUtils.isReaderModeURL(url) { return ReaderModeUtils.decodeURL(url) } return selectedTab?.displayURL ?? selectedURL } } func activityViewController(activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: String?) -> String { // Because of our UTI declaration, this UTI now satisfies both the 1Password Extension and the usual NSURL for Share extensions. return "org.appextension.fill-browser-action" } } private extension ShareExtensionHelper { static func isPasswordManagerExtensionAvailable() -> Bool { return OnePasswordExtension.sharedExtension().isAppExtensionAvailable() } func isPasswordManagerActivityType(activityType: String?) -> Bool { if (!ShareExtensionHelper.isPasswordManagerExtensionAvailable()) { return false } // A 'password' substring covers the most cases, such as pwsafe and 1Password. // com.agilebits.onepassword-ios.extension // com.app77.ios.pwsafe2.find-login-action-password-actionExtension // If your extension's bundle identifier does not contain "password", simply submit a pull request by adding your bundle identifier. return (activityType?.rangeOfString("password") != nil) || (activityType == "com.lastpass.ilastpass.LastPassExt") } func findLoginExtensionItem() { guard let selectedWebView = selectedTab?.webView else { return } if selectedWebView.URL?.absoluteString == nil { return } // Add 1Password to share sheet OnePasswordExtension.sharedExtension().createExtensionItemForWebView(selectedWebView, completion: {(extensionItem, error) -> Void in if extensionItem == nil { log.error("Failed to create the password manager extension item: \(error).") return } // Set the 1Password extension item property self.onePasswordExtensionItem = extensionItem }) } func fillPasswords(returnedItems: [AnyObject]) { guard let selectedWebView = selectedTab?.webView else { return } OnePasswordExtension.sharedExtension().fillReturnedItems(returnedItems, intoWebView: selectedWebView, completion: { (success, returnedItemsError) -> Void in if !success { log.error("Failed to fill item into webview: \(returnedItemsError).") } }) } }
mpl-2.0
1a1ada7a216c11c6ab7f82bf751d85d5
39.083333
164
0.671997
5.915799
false
false
false
false
xedin/swift
test/TypeDecoder/nominal_types.swift
3
3218
// RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-executable %s -g -o %t/nominal_types -emit-module // RUN: sed -ne '/\/\/ *DEMANGLE-TYPE: /s/\/\/ *DEMANGLE-TYPE: *//p' < %s > %t/input // RUN: %lldb-moduleimport-test-with-sdk %t/nominal_types -type-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-TYPE // RUN: sed -ne '/\/\/ *DEMANGLE-DECL: /s/\/\/ *DEMANGLE-DECL: *//p' < %s > %t/input // RUN: %lldb-moduleimport-test-with-sdk %t/nominal_types -decl-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-DECL struct Outer { enum Inner { case a init() { fatalError() } } enum GenericInner<T, U> { case a init() { fatalError() } } } enum GenericOuter<T, U> { case a init() { fatalError() } struct Inner {} struct GenericInner<T, U> {} } func blackHole(_: Any...) {} do { let x1 = Outer() let x2 = Outer.Inner() let x3 = Outer.GenericInner<Int, String>() blackHole(x1, x2, x3) } do { let x1 = GenericOuter<Int, String>() let x2 = GenericOuter<Int, String>.Inner() let x3 = GenericOuter<Int, String>.GenericInner<Float, Double>() blackHole(x1, x2, x3) } protocol P {} struct Constrained<T : P> {} func generic<T>(_: Constrained<T>) {} // DEMANGLE-TYPE: $s13nominal_types5OuterVD // CHECK-TYPE: Outer // DEMANGLE-TYPE: $s13nominal_types5OuterV5InnerOD // CHECK-TYPE: Outer.Inner // DEMANGLE-TYPE: $s13nominal_types5OuterV12GenericInnerOy_SiSSGD // DEMANGLE-TYPE: $s13nominal_types5OuterV12GenericInnerOy_xq_GD // CHECK-TYPE: Outer.GenericInner<Int, String> // CHECK-TYPE: Outer.GenericInner<τ_0_0, τ_0_1> // DEMANGLE-TYPE: $s13nominal_types12GenericOuterO5InnerVyxq__GD // DEMANGLE-TYPE: $s13nominal_types12GenericOuterO0C5InnerVyxq__qd__qd_0_GD // CHECK-TYPE: GenericOuter<τ_0_0, τ_0_1>.Inner // CHECK-TYPE: GenericOuter<τ_0_0, τ_0_1>.GenericInner<τ_1_0, τ_1_1> // DEMANGLE-TYPE: $s13nominal_types12GenericOuterO5InnerVySiSS_GD // DEMANGLE-TYPE: $s13nominal_types12GenericOuterO0C5InnerVySiSS_SfSdGD // CHECK-TYPE: GenericOuter<Int, String>.Inner // CHECK-TYPE: GenericOuter<Int, String>.GenericInner<Float, Double> // DEMANGLE-TYPE: $s13nominal_types12GenericOuterOyxq_GD // DEMANGLE-TYPE: $s13nominal_types12GenericOuterOySiSSGD // CHECK-TYPE: GenericOuter<τ_0_0, τ_0_1> // CHECK-TYPE: GenericOuter<Int, String> // DEMANGLE-TYPE: $s13nominal_types11ConstrainedVyxGD // CHECK-TYPE: Constrained<τ_0_0> // DEMANGLE-DECL: $s13nominal_types5OuterV // DEMANGLE-DECL: $s13nominal_types5OuterV5InnerO // DEMANGLE-DECL: $s13nominal_types5OuterV12GenericInnerO // DEMANGLE-DECL: $s13nominal_types12GenericOuterO // DEMANGLE-DECL: $s13nominal_types12GenericOuterO5InnerV // DEMANGLE-DECL: $s13nominal_types12GenericOuterO0C5InnerV // DEMANGLE-DECL: $s13nominal_types1PP // DEMANGLE-DECL: $s13nominal_types11ConstrainedV // CHECK-DECL: nominal_types.(file).Outer // CHECK-DECL: nominal_types.(file).Outer.Inner // CHECK-DECL: nominal_types.(file).Outer.GenericInner // CHECK-DECL: nominal_types.(file).GenericOuter // CHECK-DECL: nominal_types.(file).GenericOuter.Inner // CHECK-DECL: nominal_types.(file).GenericOuter.GenericInner // CHECK-DECL: nominal_types.(file).P // CHECK-DECL: nominal_types.(file).Constrained
apache-2.0
4fbc3bd13b2829d80923df7a5d46ca27
31.07
127
0.715622
3.016933
false
false
false
false
Esri/tips-and-tricks-ios
DevSummit2015_TipsAndTricksDemos/Tips-And-Tricks/CustomCallout/CustomCalloutVC.swift
1
10088
// Copyright 2015 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import UIKit import ArcGIS class CustomCalloutVC: UIViewController, AGSMapViewTouchDelegate, AGSCalloutDelegate, AGSLayerCalloutDelegate, AGSPopupsContainerDelegate { @IBOutlet weak var mapView: AGSMapView! @IBOutlet weak var toggleControl: UISegmentedControl! var graphicsLayer: AGSGraphicsLayer! var graphic: AGSGraphic! var calloutMapView: AGSMapView! var popupsContainerVC: AGSPopupsContainerViewController! override func viewDidLoad() { super.viewDidLoad() // set touch delegate self.mapView.touchDelegate = self // add base layer to map let streetMapUrl = NSURL(string: "http://services.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer") let tiledLayer = AGSTiledMapServiceLayer(URL: streetMapUrl); self.mapView.addMapLayer(tiledLayer, withName:"Tiled Layer") // zoom to envelope let envelope = AGSEnvelope.envelopeWithXmin(-12973339.119440766, ymin:4004738.947715673, xmax:-12972574.749157893, ymax:4006095.704967771, spatialReference: AGSSpatialReference.webMercatorSpatialReference()) as AGSEnvelope self.mapView.zoomToEnvelope(envelope, animated: true) // map view callout is selected by default self.toggleCustomCallout(self.toggleControl) // add observer to visibleAreaEnvelope self.mapView.addObserver(self, forKeyPath: "visibleAreaEnvelope", options: NSKeyValueObservingOptions.New, context: nil) } // MARK: Toggle Action @IBAction func toggleCustomCallout(sender: UISegmentedControl) { // // if if (self.toggleControl.selectedSegmentIndex == 0) { // // remove graphics layer self.mapView.removeMapLayer(self.graphicsLayer) // hide callout self.mapView.callout.hidden = true // // init callout map view self.calloutMapView = AGSMapView(frame: CGRectMake(0, 0, 180, 140)) // add base layer to callout map view let imageryMapUrl = NSURL(string: "http://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer") let imageryLayer = AGSTiledMapServiceLayer(URL: imageryMapUrl); self.calloutMapView.addMapLayer(imageryLayer, withName:"Tiled Layer") // add graphics layer to map self.graphicsLayer = AGSGraphicsLayer.graphicsLayer() as AGSGraphicsLayer self.calloutMapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer") // zoom to geometry if self.mapView.visibleAreaEnvelope != nil { self.zoomToVisibleEnvelopeForCalloutMapView() } } else if (self.toggleControl.selectedSegmentIndex == 1) { // // add graphics layer to map self.graphicsLayer = AGSGraphicsLayer.graphicsLayer() as AGSGraphicsLayer self.graphicsLayer.calloutDelegate = self self.mapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer") // add graphics to map self.addRandomPoints(15, envelope: self.mapView.visibleAreaEnvelope) } } // MARK: Helper Methods func addRandomPoints(numPoints: Int, envelope: AGSEnvelope) { var graphics = [AGSGraphic]() for index in 1...numPoints { // get random point let pt = self.randomPointInEnvelope(envelope) // create a graphic to display on the map let pms = AGSPictureMarkerSymbol(imageNamed: "green_pin") pms.leaderPoint = CGPointMake(0, 14) let g = AGSGraphic(geometry: pt, symbol: pms, attributes: nil) // set attributes g.setValue(String(index), forKey: "ID") g.setValue("Test Name", forKey: "Name") g.setValue("Test Title", forKey: "Title") g.setValue("Test Value", forKey: "Value") // add graphic to graphics array graphics.append(g) } // add graphics to layer self.graphicsLayer.addGraphics(graphics) } func randomPointInEnvelope(envelope : AGSEnvelope) -> AGSPoint { var xDomain: UInt32 = (UInt32)(envelope.xmax - envelope.xmin) var dx: Double = 0 if (xDomain != 0) { let x: UInt32 = arc4random() % xDomain dx = envelope.xmin + Double(x) } var yDomain: UInt32 = (UInt32)(envelope.ymax - envelope.ymin) var dy: Double = 0 if (yDomain != 0) { let y: UInt32 = arc4random() % xDomain dy = envelope.ymin + Double(y) } return AGSPoint(x: dx, y: dy, spatialReference: envelope.spatialReference) } func zoomToVisibleEnvelopeForCalloutMapView() { let mutableEnvelope = self.mapView.visibleAreaEnvelope.mutableCopy() as AGSMutableEnvelope mutableEnvelope.expandByFactor(0.15) self.calloutMapView.zoomToGeometry(mutableEnvelope, withPadding: 0, animated: true) } // MARK: MapView Touch Delegate func mapView(mapView: AGSMapView!, shouldProcessClickAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!) -> Bool { // only process tap if we are showing popup callout view if (self.toggleControl.selectedSegmentIndex == 1) { return true } return false } func mapView(mapView: AGSMapView!, didTapAndHoldAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) { // // process only for map view callout if (self.toggleControl.selectedSegmentIndex == 0) { // // set custom view of callout and show it self.mapView.callout.color = UIColor.brownColor() self.mapView.callout.leaderPositionFlags = .Top | .Bottom self.mapView.callout.customView = self.calloutMapView self.mapView.callout.showCalloutAt(mappoint, screenOffset: CGPointMake(0, 0), animated: true) // pan callout map view self.calloutMapView.centerAtPoint(mappoint, animated: true) // add graphic to callout map view if self.graphicsLayer.graphics.count == 0 { let symbol = AGSSimpleMarkerSymbol(color: UIColor(red: 255, green: 0, blue: 0, alpha: 0.5)) self.graphic = AGSGraphic(geometry: mappoint, symbol:symbol as AGSSymbol, attributes: nil) self.graphicsLayer.addGraphic(self.graphic) } else { self.graphic.geometry = mappoint; } } } func mapView(mapView: AGSMapView!, didMoveTapAndHoldAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) { // // process only for map view callout if (self.toggleControl.selectedSegmentIndex == 0) { // // move callout self.mapView.callout.moveCalloutTo(mappoint, screenOffset: CGPointMake(0, 0), animated: true) // update geometry of graphic self.graphic.geometry = mappoint; // pan callout map view self.calloutMapView.centerAtPoint(mappoint, animated: true) } } func mapView(mapView: AGSMapView!, didEndTapAndHoldAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) { // // process only for map view callout if (self.toggleControl.selectedSegmentIndex == 0) { // // remove all graphics from graphics layer self.graphicsLayer.removeAllGraphics() } } // MARK: Callout Delegate func callout(callout: AGSCallout!, willShowForFeature feature: AGSFeature!, layer: AGSLayer!, mapPoint: AGSPoint!) -> Bool { // // show popup view controller in callout let popupInfo = AGSPopupInfo(forGraphic: AGSGraphic(feature: feature)) self.popupsContainerVC = AGSPopupsContainerViewController(popupInfo: popupInfo, graphic: AGSGraphic(feature: feature), usingNavigationControllerStack: false) self.popupsContainerVC.delegate = self self.popupsContainerVC.doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: nil, action: nil) self.popupsContainerVC.actionButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Trash, target: nil, action: nil) self.popupsContainerVC.view.frame = CGRectMake(0,0,150,180) callout.leaderPositionFlags = .Right | .Left callout.customView = self.popupsContainerVC.view return true } // MARK: Poups Container Delegate func popupsContainerDidFinishViewingPopups(popupsContainer: AGSPopupsContainer!) { self.mapView.callout.hidden = true } // MARK: Observe override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { // get the object let mapView: AGSMapView = object as AGSMapView // zoom in the callout map view self.zoomToVisibleEnvelopeForCalloutMapView() } }
apache-2.0
4f6d55a76c113ade3f5b67ecae67dd3f
41.386555
230
0.638085
5.038961
false
false
false
false
IAskWind/IAWExtensionTool
Pods/SwiftMessages/SwiftMessages/PhysicsAnimation.swift
4
5005
// // PhysicsAnimation.swift // SwiftMessages // // Created by Timothy Moose on 6/14/17. // Copyright © 2017 SwiftKick Mobile. All rights reserved. // import UIKit public class PhysicsAnimation: NSObject, Animator { public enum Placement { case top case center case bottom } public var placement: Placement = .center public var panHandler = PhysicsPanHandler() public weak var delegate: AnimationDelegate? weak var messageView: UIView? weak var containerView: UIView? var context: AnimationContext? public override init() {} init(delegate: AnimationDelegate) { self.delegate = delegate } public func show(context: AnimationContext, completion: @escaping AnimationCompletion) { NotificationCenter.default.addObserver(self, selector: #selector(adjustMargins), name: UIDevice.orientationDidChangeNotification, object: nil) install(context: context) showAnimation(context: context, completion: completion) } public func hide(context: AnimationContext, completion: @escaping AnimationCompletion) { NotificationCenter.default.removeObserver(self) if panHandler.isOffScreen { context.messageView.alpha = 0 panHandler.state?.stop() } let view = context.messageView self.context = context CATransaction.begin() CATransaction.setCompletionBlock { view.alpha = 1 view.transform = CGAffineTransform.identity completion(true) } UIView.animate(withDuration: hideDuration!, delay: 0, options: [.beginFromCurrentState, .curveEaseIn, .allowUserInteraction], animations: { view.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) }, completion: nil) UIView.animate(withDuration: hideDuration!, delay: 0, options: [.beginFromCurrentState, .curveEaseIn, .allowUserInteraction], animations: { view.alpha = 0 }, completion: nil) CATransaction.commit() } public var showDuration: TimeInterval? { return 0.5 } public var hideDuration: TimeInterval? { return 0.15 } func install(context: AnimationContext) { let view = context.messageView let container = context.containerView messageView = view containerView = container self.context = context view.translatesAutoresizingMaskIntoConstraints = false container.addSubview(view) switch placement { case .center: view.centerYAnchor.constraint(equalTo: container.centerYAnchor).with(priority: UILayoutPriority(200)).isActive = true case .top: view.topAnchor.constraint(equalTo: container.topAnchor).with(priority: UILayoutPriority(200)).isActive = true case .bottom: view.bottomAnchor.constraint(equalTo: container.bottomAnchor).with(priority: UILayoutPriority(200)).isActive = true } NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: container, attribute: .leading, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: container, attribute: .trailing, multiplier: 1, constant: 0).isActive = true // Important to layout now in order to get the right safe area insets container.layoutIfNeeded() adjustMargins() container.layoutIfNeeded() installInteractive(context: context) } @objc public func adjustMargins() { guard let adjustable = messageView as? MarginAdjustable & UIView, let context = context else { return } adjustable.preservesSuperviewLayoutMargins = false if #available(iOS 11, *) { adjustable.insetsLayoutMarginsFromSafeArea = false } adjustable.layoutMargins = adjustable.defaultMarginAdjustment(context: context) } func showAnimation(context: AnimationContext, completion: @escaping AnimationCompletion) { let view = context.messageView view.alpha = 0.25 view.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) CATransaction.begin() CATransaction.setCompletionBlock { completion(true) } UIView.animate(withDuration: showDuration!, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [.beginFromCurrentState, .curveLinear, .allowUserInteraction], animations: { view.transform = CGAffineTransform.identity }, completion: nil) UIView.animate(withDuration: 0.3 * showDuration!, delay: 0, options: [.beginFromCurrentState, .curveLinear, .allowUserInteraction], animations: { view.alpha = 1 }, completion: nil) CATransaction.commit() } func installInteractive(context: AnimationContext) { guard context.interactiveHide else { return } panHandler.configure(context: context, animator: self) } }
mit
00e0fc7a7f1e1d51cc133863548b09a3
39.032
202
0.677258
5.185492
false
false
false
false
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/Producer.swift
6
3195
// // Producer.swift // Rx // // Created by Krunoslav Zaher on 2/20/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Producer<Element> : Observable<Element> { override init() { super.init() } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { if !CurrentThreadScheduler.isScheduleRequired { // The returned disposable needs to release all references once it was disposed. let disposer = SinkDisposer() let sinkAndSubscription = run(observer, cancel: disposer) disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) return disposer } else { return CurrentThreadScheduler.instance.schedule(()) { _ in let disposer = SinkDisposer() let sinkAndSubscription = self.run(observer, cancel: disposer) disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) return disposer } } } func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { abstractMethod() } } fileprivate class SinkDisposer: Cancelable { fileprivate enum DisposeState: UInt32 { case disposed = 1 case sinkAndSubscriptionSet = 2 } // Jeej, swift API consistency rules fileprivate enum DisposeStateInt32: Int32 { case disposed = 1 case sinkAndSubscriptionSet = 2 } private var _state: UInt32 = 0 private var _sink: Disposable? = nil private var _subscription: Disposable? = nil var isDisposed: Bool { return (_state & DisposeState.disposed.rawValue) != 0 } func setSinkAndSubscription(sink: Disposable, subscription: Disposable) { _sink = sink _subscription = subscription let previousState = OSAtomicOr32OrigBarrier(DisposeState.sinkAndSubscriptionSet.rawValue, &_state) if (previousState & DisposeStateInt32.sinkAndSubscriptionSet.rawValue) != 0 { rxFatalError("Sink and subscription were already set") } if (previousState & DisposeStateInt32.disposed.rawValue) != 0 { sink.dispose() subscription.dispose() _sink = nil _subscription = nil } } func dispose() { let previousState = OSAtomicOr32OrigBarrier(DisposeState.disposed.rawValue, &_state) if (previousState & DisposeStateInt32.disposed.rawValue) != 0 { return } if (previousState & DisposeStateInt32.sinkAndSubscriptionSet.rawValue) != 0 { guard let sink = _sink else { rxFatalError("Sink not set") } guard let subscription = _subscription else { rxFatalError("Subscription not set") } sink.dispose() subscription.dispose() _sink = nil _subscription = nil } } }
mit
34565a4cdc2ee35d76210e2f27e80738
31.262626
136
0.618347
5.176661
false
false
false
false
erremauro/Password-Update
Password Update/KeychainController.swift
1
3240
// // KeychainController.swift // Password Update // // Created by Roberto Mauro on 4/24/17. // Copyright © 2017 roberto mauro. All rights reserved. // import Foundation import Security struct AccountType { static let generic = kSecClassGenericPassword static let internet = kSecClassInternetPassword } class KeychainController { private let accountTypes = [AccountType.generic, AccountType.internet] func add(account:String, password: String, for accountType: CFString) -> Bool { let keychainQuery: NSDictionary = [ kSecClass: accountType, kSecAttrLabel: account, kSecAttrAccount: account, kSecValueData: password.data(using: String.Encoding.utf8)! ] var dataStatusRef: AnyObject? let status = SecItemAdd(keychainQuery, &dataStatusRef) return status == errSecSuccess } func delete(account: String) -> Bool { var success = true for accountType in accountTypes { if exists(account, for: accountType) { let deleted = delete(account, for: accountType) if !deleted { success = false } } } return success } func delete(_ account: String, for accountType: CFString) -> Bool { let keychainQuery: NSDictionary = [ kSecClass: accountType, kSecAttrAccount: account, kSecMatchLimit: kSecMatchLimitAll ] let status = SecItemDelete(keychainQuery) return status == errSecSuccess } func changePassword(account: String, password: String) -> Bool { var success = true for accountType in accountTypes { if exists(account, for: accountType) { let updated = update(account, with: password, for: accountType) if !updated && success { success = false } } } return success } func exists(_ account: String) -> Bool { var success = false for accountType in accountTypes { let hasAccount = exists(account, for: accountType) if hasAccount && !success { success = true } } return success } func exists(_ account: String, for accountType: CFString) -> Bool { let keychainQuery: NSDictionary = [ kSecClass: accountType, kSecAttrAccount: account, kSecMatchLimit : kSecMatchLimitOne ] var dataTypeRef: AnyObject? let status = SecItemCopyMatching(keychainQuery, &dataTypeRef) return status == errSecSuccess } func update(_ account: String, with password: String, for accountType: CFString) -> Bool { let keychainQueryGeneric: NSDictionary = [ kSecClass: accountType, kSecAttrAccount: account, kSecMatchLimit : kSecMatchLimitAll ] let updateDict: NSDictionary = [ kSecValueData: password.data(using: String.Encoding.utf8)! ] let status = SecItemUpdate(keychainQueryGeneric, updateDict) return status == errSecSuccess } }
mit
8c4c4436b3e47a8fc99d7c0b7722a5f0
30.754902
94
0.595245
5.471284
false
false
false
false
pocketworks/FloatLabelFields
FloatLabelExample/FloatLabelExample/ViewController.swift
1
982
// // ViewController.swift // FloatLabelExample // // Created by Fahim Farook on 28/11/14. // Copyright (c) 2014 RookSoft Ltd. All rights reserved. // // Updated for Swift 2.0 by Myles Ringle on 15/10/15. // import UIKit class ViewController: UIViewController { @IBOutlet var vwAddress:FloatLabelTextView! @IBOutlet var vwHolder:UIView! override func viewDidLoad() { super.viewDidLoad() // Set font for placeholder of a FloatLabelTextView if let fnt = UIFont(name:"HelveticaNeue", size:12) { vwAddress.titleFont = fnt } // Set up a FloatLabelTextField via code let fld = FloatLabelTextField(frame:vwHolder.bounds) fld.placeholder = "Comments" // Set font for place holder (only displays in title mode) if let fnt = UIFont(name:"HelveticaNeue", size:12) { fld.titleFont = fnt } vwHolder.addSubview(fld) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
27535f860b9af4a95e4631dc2012cd8e
24.842105
60
0.721996
3.583942
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Loader/LoadingCircleView.swift
1
1552
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public class LoadingCircleView: UIView { // MARK: - Properties /// The width of the stroke line private let strokeWidth: CGFloat override public var layer: CAShapeLayer { super.layer as! CAShapeLayer } override public class var layerClass: AnyClass { CAShapeLayer.self } // MARK: - Setup init( diameter: CGFloat, strokeColor: UIColor, strokeBackgroundColor: UIColor, fillColor: UIColor, strokeWidth: CGFloat = 8 ) { self.strokeWidth = strokeWidth super.init(frame: CGRect(origin: .zero, size: CGSize(edge: diameter))) configure(layer, strokeColor: strokeColor, fillColor: fillColor) let strokeBackgroundLayer = CAShapeLayer() configure(strokeBackgroundLayer, strokeColor: strokeBackgroundColor, fillColor: fillColor) layer.addSublayer(strokeBackgroundLayer) isAccessibilityElement = false } private func configure(_ layer: CAShapeLayer, strokeColor: UIColor, fillColor: UIColor) { layer.strokeColor = strokeColor.cgColor layer.lineWidth = strokeWidth layer.lineCap = .round layer.fillColor = fillColor.cgColor layer.path = UIBezierPath(ovalIn: bounds.insetBy(dx: strokeWidth / 2, dy: strokeWidth / 2)).cgPath } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
lgpl-3.0
6a62db66ed5f09202df47c86f347adca
30.02
106
0.67118
5.17
false
true
false
false
EasyIOS/EasyCoreData
Pod/Classes/EasyORM.swift
1
12736
// // NSManagedObject+EZExtend.swift // medical // // Created by zhuchao on 15/5/30. // Copyright (c) 2015年 zhuchao. All rights reserved. // import Foundation import CoreData public class EasyORM { public static var generateRelationships = false public static func setUpEntities(entities: [String:NSManagedObject.Type]) { nameToEntities = entities } private static var nameToEntities: [String:NSManagedObject.Type] = [String:NSManagedObject.Type]() } public extension NSManagedObject{ private func defaultContext() -> NSManagedObjectContext{ return self.managedObjectContext ?? self.dynamicType.defaultContext() } public static func defaultContext() -> NSManagedObjectContext{ return NSManagedObjectContext.defaultContext } private static var query:NSFetchRequest{ return self.defaultContext().createFetchRequest(self.entityName()) } public static func condition(condition: AnyObject?) -> NSFetchRequest{ return self.query.condition(condition) } public static func orderBy(key:String,_ order:String = "ASC") -> NSFetchRequest{ return self.query.orderBy(key, order) } /** * Set the "limit" value of the query. * * @param int value * @return self * @static */ public static func limit(value:Int) -> NSFetchRequest{ return self.query.limit(value) } /** * Alias to set the "limit" value of the query. * * @param int value * @return NSFetchRequest */ public static func take(value:Int) -> NSFetchRequest{ return self.query.take(value) } /** * Set the limit and offset for a given page. * * @param int page * @param int perPage * @return NSFetchRequest */ public static func forPage(page:Int,_ perPage:Int) -> NSFetchRequest{ return self.query.forPage(page,perPage) } public static func all() -> [NSManagedObject] { return self.query.get() } public static func count() -> Int { return self.query.count() } public static func updateOrCreate(unique:[String:AnyObject],data:[String:AnyObject]) -> NSManagedObject{ if let object = self.find(unique) { object.update(data) return object }else{ return self.create(data) } } public static func findOrCreate(properties: [String:AnyObject]) -> NSManagedObject { let transformed = self.transformProperties(properties) let existing = self.find(properties) return existing ?? self.create(transformed) } public static func find(condition: AnyObject) -> NSManagedObject? { return self.query.condition(condition).first() } public func update(properties: [String:AnyObject]) { if (properties.count == 0) { return } let context = self.defaultContext() let transformed = self.dynamicType.transformProperties(properties) //Finish for (key, value) in transformed { self.willChangeValueForKey(key) self.setSafeValue(value, forKey: key) self.didChangeValueForKey(key) } } public func save() -> Bool { return self.defaultContext().save() } public func delete() -> NSManagedObject { let context = self.defaultContext() context.deleteObject(self) return self } public static func deleteAll() -> NSManagedObjectContext{ for o in self.all() { o.delete() } return self.defaultContext() } public static func create() -> NSManagedObject { let o = NSEntityDescription.insertNewObjectForEntityForName(self.entityName(), inManagedObjectContext: self.defaultContext()) as! NSManagedObject if let idprop = self.autoIncrementingId() { o.setPrimitiveValue(NSNumber(integer: self.nextId()), forKey: idprop) } return o } public static func create(properties: [String:AnyObject]) -> NSManagedObject { let newEntity: NSManagedObject = self.create() newEntity.update(properties) if let idprop = self.autoIncrementingId() { if newEntity.primitiveValueForKey(idprop) == nil { newEntity.setPrimitiveValue(NSNumber(integer: self.nextId()), forKey: idprop) } } return newEntity } public static func autoIncrements() -> Bool { return self.autoIncrementingId() != nil } public static func nextId() -> Int { let key = "SwiftRecord-" + self.entityName() + "-ID" if let idprop = self.autoIncrementingId() { let id = NSUserDefaults.standardUserDefaults().integerForKey(key) NSUserDefaults.standardUserDefaults().setInteger(id + 1, forKey: key) return id } return 0 } public class func autoIncrementingId() -> String? { return nil } //Private private static func transformProperties(properties: [String:AnyObject]) -> [String:AnyObject]{ let entity = NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: self.defaultContext())! let attrs = entity.attributesByName let rels = entity.relationshipsByName var transformed = [String:AnyObject]() for (key, value) in properties { let localKey = self.keyForRemoteKey(key) if attrs[localKey] != nil { transformed[localKey] = value } else if let rel = rels[localKey] as? NSRelationshipDescription { if EasyORM.generateRelationships { if rel.toMany { if let array = value as? [[String:AnyObject]] { transformed[localKey] = self.generateSet(rel, array: array) } else { #if DEBUG println("Invalid value for relationship generation in \(NSStringFromClass(self)).\(localKey)") println(value) #endif } } else if let dict = value as? [String:AnyObject] { transformed[localKey] = self.generateObject(rel, dict: dict) } else { #if DEBUG println("Invalid value for relationship generation in \(NSStringFromClass(self)).\(localKey)") println(value) #endif } } } } return transformed } private func setSafeValue(value: AnyObject?, forKey key: String) { if (value == nil) { self.setNilValueForKey(key) return } let val: AnyObject = value! if let attr = self.entity.attributesByName[key] as? NSAttributeDescription { let attrType = attr.attributeType if attrType == NSAttributeType.StringAttributeType && value is NSNumber { self.setPrimitiveValue((val as! NSNumber).stringValue, forKey: key) } else if let s = val as? String { if self.isIntegerAttributeType(attrType) { self.setPrimitiveValue(NSNumber(integer: val.integerValue), forKey: key) return } else if attrType == NSAttributeType.BooleanAttributeType { self.setPrimitiveValue(NSNumber(bool: val.boolValue), forKey: key) return } else if (attrType == NSAttributeType.FloatAttributeType) { self.setPrimitiveValue(NSNumber(floatLiteral: val.doubleValue), forKey: key) return } else if (attrType == NSAttributeType.DateAttributeType) { self.setPrimitiveValue(self.dynamicType.dateFormatter.dateFromString(s), forKey: key) return } } } self.setPrimitiveValue(value, forKey: key) } private func isIntegerAttributeType(attrType: NSAttributeType) -> Bool { return attrType == NSAttributeType.Integer16AttributeType || attrType == NSAttributeType.Integer32AttributeType || attrType == NSAttributeType.Integer64AttributeType } private static var dateFormatter: NSDateFormatter { if _dateFormatter == nil { _dateFormatter = NSDateFormatter() _dateFormatter!.dateFormat = "yyyy-MM-dd HH:mm:ss z" } return _dateFormatter! } private static var _dateFormatter: NSDateFormatter? public class func mappings() -> [String:String] { return [String:String]() } public static func keyForRemoteKey(remote: String) -> String { if let s = cachedMappings[remote] { return s } let entity = NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: self.defaultContext())! let properties = entity.propertiesByName if properties[entity.propertiesByName] != nil { _cachedMappings![remote] = remote return remote } let camelCased = remote.camelCase if properties[camelCased] != nil { _cachedMappings![remote] = camelCased return camelCased } _cachedMappings![remote] = remote return remote } private static var cachedMappings: [String:String] { if let m = _cachedMappings { return m } else { var m = [String:String]() for (key, value) in mappings() { m[value] = key } _cachedMappings = m return m } } private static var _cachedMappings: [String:String]? private static func generateSet(rel: NSRelationshipDescription, array: [[String:AnyObject]]) -> NSSet { var cls: NSManagedObject.Type? if EasyORM.nameToEntities.count > 0 { cls = EasyORM.nameToEntities[rel.destinationEntity!.managedObjectClassName] } if cls == nil { cls = (NSClassFromString(rel.destinationEntity!.managedObjectClassName) as! NSManagedObject.Type) } else { println("Got class name from entity setup") } var set = NSMutableSet() for d in array { set.addObject(cls!.findOrCreate(d)) } return set } private static func generateObject(rel: NSRelationshipDescription, dict: [String:AnyObject]) -> NSManagedObject { var entity = rel.destinationEntity! var cls: NSManagedObject.Type = NSClassFromString(entity.managedObjectClassName) as! NSManagedObject.Type return cls.findOrCreate(dict) } public static func primaryKey() -> String { NSException(name: "Primary key undefined in " + NSStringFromClass(self), reason: "Override primaryKey if you want to support automatic creation, otherwise disable this feature", userInfo: nil).raise() return "" } private static func entityName() -> String { var name = NSStringFromClass(self) if name.rangeOfString(".") != nil { let comp = split(name) {$0 == "."} if comp.count > 1 { name = comp.last! } } if name.rangeOfString("_") != nil { var comp = split(name) {$0 == "_"} var last: String = "" var remove = -1 for (i,s) in enumerate(comp.reverse()) { if last == s { remove = i } last = s } if remove > -1 { comp.removeAtIndex(remove) name = "_".join(comp) } } return name } } public extension String { var camelCase: String { let spaced = self.stringByReplacingOccurrencesOfString("_", withString: " ", options: nil, range:Range<String.Index>(start: self.startIndex, end: self.endIndex)) let capitalized = spaced.capitalizedString let spaceless = capitalized.stringByReplacingOccurrencesOfString(" ", withString: "", options:nil, range:Range<String.Index>(start:self.startIndex, end:self.endIndex)) return spaceless.stringByReplacingCharactersInRange(Range<String.Index>(start:spaceless.startIndex, end:spaceless.startIndex.successor()), withString: "\(spaceless[spaceless.startIndex])".lowercaseString) } }
mit
9a5097dfcbbba7fb9ab4882ad2b1f7ae
34.870423
212
0.589131
5.275062
false
false
false
false
Ethenyl/JAMFKit
JamfKit/Sources/Models/DirectoryBinding.swift
1
3988
// // Copyright © 2017-present JamfKit. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // /// Represents a logical binding between a computer and an active directory user. @objc(JMFKDirectoryBinding) public final class DirectoryBinding: BaseObject, Endpoint { // MARK: - Constants public static let Endpoint = "directorybindings" static let PriorityKey = "priority" static let DomainKey = "domain" static let UsernameKey = "username" static let PasswordKey = "password" static let ComputerOrganisationalUnitKey = "computer_ou" static let TypeKey = "type" // MARK: - Properties @objc public var priority: UInt = 0 @objc public var domain = "" @objc public var username = "" @objc public var password = "" @objc public var computerOrganisationalUnit = "" @objc public var type = "" // MARK: - Initialization public required init?(json: [String: Any], node: String = "") { priority = json[DirectoryBinding.PriorityKey] as? UInt ?? 0 domain = json[DirectoryBinding.DomainKey] as? String ?? "" username = json[DirectoryBinding.UsernameKey] as? String ?? "" password = json[DirectoryBinding.PasswordKey] as? String ?? "" computerOrganisationalUnit = json[DirectoryBinding.ComputerOrganisationalUnitKey] as? String ?? "" type = json[DirectoryBinding.TypeKey] as? String ?? "" super.init(json: json) } public override init?(identifier: UInt, name: String) { super.init(identifier: identifier, name: name) } // MARK: - Functions public override func toJSON() -> [String: Any] { var json = super.toJSON() json[DirectoryBinding.PriorityKey] = priority json[DirectoryBinding.DomainKey] = domain json[DirectoryBinding.UsernameKey] = username json[DirectoryBinding.PasswordKey] = password json[DirectoryBinding.ComputerOrganisationalUnitKey] = computerOrganisationalUnit json[DirectoryBinding.TypeKey] = type return json } } // MARK: - Creatable extension DirectoryBinding: Creatable { public func createRequest() -> URLRequest? { return getCreateRequest() } } // MARK: - Readable extension DirectoryBinding: Readable { public static func readAllRequest() -> URLRequest? { return getReadAllRequest() } public static func readRequest(identifier: String) -> URLRequest? { return getReadRequest(identifier: identifier) } public func readRequest() -> URLRequest? { return getReadRequest() } /// Returns a GET **URLRequest** based on the supplied name. public static func readRequest(name: String) -> URLRequest? { return getReadRequest(name: name) } /// Returns a GET **URLRequest** based on the email. public func readRequestWithName() -> URLRequest? { return getReadRequestWithName() } } // MARK: - Updatable extension DirectoryBinding: Updatable { public func updateRequest() -> URLRequest? { return getUpdateRequest() } /// Returns a PUT **URLRequest** based on the name. public func updateRequestWithName() -> URLRequest? { return getUpdateRequestWithName() } } // MARK: - Deletable extension DirectoryBinding: Deletable { public static func deleteRequest(identifier: String) -> URLRequest? { return getDeleteRequest(identifier: identifier) } public func deleteRequest() -> URLRequest? { return getDeleteRequest() } /// Returns a DELETE **URLRequest** based on the supplied name. public static func deleteRequest(name: String) -> URLRequest? { return getDeleteRequest(name: name) } /// Returns a DELETE **URLRequest** based on the name. public func deleteRequestWithName() -> URLRequest? { return getDeleteRequestWithName() } }
mit
d45fae1f4b2de71917a48bb3226bd67c
26.6875
106
0.666667
4.880049
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/Player/NormalPlayer/ViewModel/ZHNnormalPlayerViewModel.swift
1
3315
// // ZHNnormalPlayerViewModel.swift // zhnbilibili // // Created by zhn on 16/12/14. // Copyright © 2016年 zhn. All rights reserved. // import UIKit import SwiftyJSON import Alamofire import HandyJSON /// 获取视频播放url成功的通知 let kgetPlayUrlSuccessNotification = Notification.Name("kgetPlayUrlSuccessNotification") class ZHNnormalPlayerViewModel { /// 视频播放的url var playerUrl: String? /// 弹幕的数据数组 var danmuModelArray: [danmuModel]? /// 视频的相关数据 var detailModel: YSPlayDetailModel? func requestData(aid: Int,finishCallBack:@escaping ()->(),failueCallBack:@escaping ()->()) { let urlStr = "http://app.bilibili.com/x/view?actionKey=appkey&aid=\(aid)&appkey=27eb53fc9058f8c3&build=3380" print(urlStr) YSNetworkTool.shared.requestData(.get, URLString: urlStr, finished: { (result) in let resultJson = JSON(result) // 1. 获取视频的相关数据 self.detailModel = JSONDeserializer<YSPlayDetailModel>.deserializeFrom(dict: resultJson["data"].dictionaryObject as NSDictionary?) // 2. 获取播放的url和弹幕 let dict = resultJson["data"]["pages"].array?.first?.dictionaryObject guard let cid = dict?["cid"] as? Int else {return} guard let page = dict?["page"] as? Int else {return} let group = DispatchGroup() // <1.获取视频播放的url group.enter() VideoURL.getWithAid(aid, cid: cid, page: page, completionBlock: { (url) in guard let urlStr = url?.absoluteString else {return} self.playerUrl = urlStr NotificationCenter.default.post(name: kgetPlayUrlSuccessNotification, object: nil) group.leave() }) // <2.获取弹幕数据 self.requestDanmuStatus(cid: cid, group: group) group.notify(queue: DispatchQueue.main, execute: { finishCallBack() }) }) { (error) in failueCallBack() } } func requestDanmuStatus(cid: Int,group: DispatchGroup) { group.enter() self.danmuModelArray?.removeAll() let URLString = "http://comment.bilibili.com/\(cid).xml" Alamofire.request(URLString, method: .get, parameters: nil).responseData { (response) in guard let result = try? XMLReader.dictionary(forXMLData: response.data) else {return} self.danmuModelArray = danmuModel.modelArray(dict: result) group.leave() } } func requestPagePlayUrl(page: Int,cid: Int,finishAction:@escaping (()->Void)) { let group = DispatchGroup() group.enter() VideoURL.getWithAid((detailModel?.aid)!, cid: cid, page: page, completionBlock: { (url) in guard let urlStr = url?.absoluteString else {return} self.playerUrl = urlStr NotificationCenter.default.post(name: kgetPlayUrlSuccessNotification, object: nil) group.leave() }) requestDanmuStatus(cid: cid, group: group) group.notify(queue: DispatchQueue.main) { finishAction() } } }
mit
c59d580303b5cdd18e45e213a0a75fa1
35.272727
142
0.60401
4.421053
false
false
false
false
linkedin/LayoutKit
Sources/ObjCSupport/LOKLayout.swift
1
6222
// Copyright 2018 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 CoreGraphics /** A protocol for types that layout view frames. ### Basic layouts Many UIs can be expressed by composing the basic layouts that LayoutKit provides: - `LOKLabelLayout` - `LOKInsetLayout` - `LOKSizeLayout` - `LOKStackLayout` If your UI can not be expressed by composing these basic layouts, then you can create a custom layout. Custom layouts are recommended but not required to conform to the `ConfigurableLayout` protocol due to the type safety and default implementation that it adds. ### Layout algorithm Layout is performed in two steps: 1. `measurement(within:)` 2. `arrangement(within:measurement:)`. ### Threading Layouts MUST be thread-safe. */ @objc public protocol LOKLayout { /** Measures the minimum size of the layout and its sublayouts. It MAY be run on a background thread. - parameter maxSize: The maximum size available to the layout. - returns: The minimum size required by the layout and its sublayouts given a maximum size. The size of the layout MUST NOT exceed `maxSize`. */ @objc func measurement(within maxSize: CGSize) -> LOKLayoutMeasurement /** Returns the arrangement of frames for the layout inside a given rect. The frames SHOULD NOT overflow rect, otherwise they may overlap with adjacent layouts. The layout MAY choose to not use the entire rect (and instead align itself in some way inside of the rect), but the caller SHOULD NOT reallocate unused space to other layouts because this could break the layout's desired alignment and padding. Space allocation SHOULD happen during the measure pass. MAY be run on a background thread. - parameter rect: The rectangle that the layout must position itself in. - parameter measurement: A measurement which has size less than or equal to `rect.size` and greater than or equal to `measurement.maxSize`. - returns: A complete set of frames for the layout. */ @objc func arrangement(within rect: CGRect, measurement: LOKLayoutMeasurement) -> LOKLayoutArrangement /** Indicates whether a View object needs to be created for this layout. Layouts that just position their sublayouts can return `false` here. */ @objc var needsView: Bool { get } /** Returns a new `UIView` for the layout. It is not called on a layout if the layout is using a recycled view. MUST be run on the main thread. */ @objc func makeView() -> View /** Configures the given view. MUST be run on the main thread. */ @objc func configureView(_ view: View) /** The flexibility of the layout. If a layout has a single sublayout, it SHOULD inherit the flexiblity of its sublayout. If a layout has no sublayouts (e.g. `LOKLabelLayout`), it SHOULD allow its flexibility to be configured. All layouts SHOULD provide a default flexiblity. TODO: figure out how to assert if inflexible layouts are compressed. */ @objc var flexibility: LOKFlexibility { get } /** An identifier for the view that is produced by this layout. If this layout is applied to an existing view hierarchy, and if there is a view with an identical viewReuseId, then that view will be reused for the new layout. If there is more than one view with the same viewReuseId, then an arbitrary one will be reused. */ @objc var viewReuseId: String? { get } } extension LOKLayout { var unwrapped: Layout { /* Need to check to see if `self` is one of the LayoutKit provided layouts. If so, we want to cast it as `LOKBaseLayout` and return the wrapped layout object directly. If `self` is not one of the LayoutKit provided layouts, we want to wrap it so that the methods of the class are called. We do this to make sure that if someone were to subclass one of the LayoutKit provided layouts, we would want to call their overriden methods instead of just the underlying layout object directly. Certain platforms don't have certain layouts, so we make a different array for each platform with only the layouts that it supports. */ let allLayoutClasses: [AnyClass] #if os(OSX) allLayoutClasses = [ LOKInsetLayout.self, LOKOverlayLayout.self, LOKSizeLayout.self, LOKStackLayout.self ] #elseif os(tvOS) allLayoutClasses = [ LOKInsetLayout.self, LOKOverlayLayout.self, LOKTextViewLayout.self, LOKButtonLayout.self, LOKSizeLayout.self, LOKStackLayout.self ] #else allLayoutClasses = [ LOKInsetLayout.self, LOKOverlayLayout.self, LOKTextViewLayout.self, LOKButtonLayout.self, LOKLabelLayout.self, LOKSizeLayout.self, LOKStackLayout.self ] #endif if let object = self as? NSObject { if allLayoutClasses.contains(where: { object.isMember(of: $0) }) { // Executes if `self` is one of the LayoutKit provided classes; not if it's a subclass guard let layout = (self as? LOKBaseLayout)?.layout else { assertionFailure("LayoutKit provided layout does not inherit from LOKBaseLayout") return ReverseWrappedLayout(layout: self) } return layout } } return (self as? WrappedLayout)?.layout ?? ReverseWrappedLayout(layout: self) } }
apache-2.0
ec056777f0323947347a0290f54b5ee1
37.407407
150
0.663452
4.930269
false
false
false
false
ivlasov/EvoShare
EvoShareSwift/QRCodeController.swift
2
2888
// // QRCodeController.swift // EvoShareSwift // // Created by Ilya Vlasov on 12/24/14. // Copyright (c) 2014 mtu. All rights reserved. // import Foundation import UIKit class QRCodeController : UIViewController, ConnectionManagerDelegate { @IBOutlet weak var qrimage: UIImageView! @IBOutlet weak var activityIndicator: UIImageView! var promoGuid : String? var checkID : Int = 0 var summ : Double = 0 var currency : String? @IBAction func cancelTapped(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) } override func viewDidAppear(animated: Bool) { self.rotateLayerInfinity(self.activityIndicator.layer) } override func viewDidDisappear(animated: Bool) { self.activityIndicator.layer.removeAllAnimations() } override func viewDidLoad() { let imgURLString = "http://service.evo-share.com/image.ashx?i=qr&t=\(EVOUidSingleton.sharedInstance.userID())|\(promoGuid)" let awesomeURL = imgURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) let url = NSURL(string: awesomeURL!) var err: NSError? var imageData: NSData = NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMapped, error: &err)! var relatedPromoImage = UIImage(data:imageData) qrimage.image = relatedPromoImage } override func didReceiveMemoryWarning() { // } func rotateLayerInfinity(layer:CALayer) { var rotation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation") rotation.fromValue = NSNumber(float: 0) rotation.toValue = NSNumber(floatLiteral: 2*M_PI) rotation.duration = 1.1 rotation.repeatCount = HUGE layer.removeAllAnimations() layer.addAnimation(rotation, forKey: "Spin") } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "offerSegue" { var confirmControlelr = segue.destinationViewController as! OfferController ConnectionManager.sharedInstance.delegate = confirmControlelr var price : String = String(format: "%.2f", summ) confirmControlelr.summ = price confirmControlelr.curr = currency confirmControlelr.checkID = checkID } } } extension QRCodeController : ConnectionManagerDelegate { func connectionManagerDidRecieveObject(responseObject: AnyObject) { activityIndicator.layer.removeAllAnimations() let responseDict = responseObject as! Dictionary<String,AnyObject> summ = responseDict["SUM"] as! Double currency = responseDict["CUR"] as? String checkID = responseDict["CID"] as! Int performSegueWithIdentifier("offerSegue", sender: self) } }
unlicense
76036a4192f2df5057ba4ecc6856b8e8
34.231707
131
0.681094
5.048951
false
false
false
false
ytbryan/swiftknife
project/project/AppDelegate.swift
1
7581
// // AppDelegate.swift // project // // Created by Bryan Lim on 10/22/14. // Copyright (c) 2014 TADA. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as UINavigationController let controller = masterNavigationController.topViewController as MasterViewController controller.managedObjectContext = self.managedObjectContext 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: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } // 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.tada.project" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() 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("project", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL) }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return 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 var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("project.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError.errorWithDomain("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 \(error), \(error!.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 if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // 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. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
11e9c49d552b04c99cde52484946b6ed
56.431818
290
0.724575
6.158408
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/MakerBasics/LayoutPropertyCanStoreRightType.swift
1
2394
// // LayoutPropertyCanStoreRightType.swift // NotAutoLayout // // Created by 史翔新 on 2017/11/12. // Copyright © 2017年 史翔新. All rights reserved. // import UIKit public protocol LayoutPropertyCanStoreRightType: LayoutMakerPropertyType { associatedtype WillSetRightProperty: LayoutMakerPropertyType func storeRight(_ right: LayoutElement.Horizontal) -> WillSetRightProperty } private extension LayoutMaker where Property: LayoutPropertyCanStoreRightType { func storeRight(_ right: LayoutElement.Horizontal) -> LayoutMaker<Property.WillSetRightProperty> { let newProperty = self.didSetProperty.storeRight(right) let newMaker = self.changintProperty(to: newProperty) return newMaker } } extension LayoutMaker where Property: LayoutPropertyCanStoreRightType { public func setRight(to right: Float) -> LayoutMaker<Property.WillSetRightProperty> { let right = LayoutElement.Horizontal.constant(right) let maker = self.storeRight(right) return maker } public func setRight(by right: @escaping (_ property: ViewLayoutGuides) -> Float) -> LayoutMaker<Property.WillSetRightProperty> { let right = LayoutElement.Horizontal.byParent(right) let maker = self.storeRight(right) return maker } public func pinRight(to referenceView: UIView?, with right: @escaping (ViewPinGuides.Horizontal) -> Float) -> LayoutMaker<Property.WillSetRightProperty> { return self.pinRight(by: { [weak referenceView] in referenceView }, with: right) } public func pinRight(by referenceView: @escaping () -> UIView?, with right: @escaping (ViewPinGuides.Horizontal) -> Float) -> LayoutMaker<Property.WillSetRightProperty> { let right = LayoutElement.Horizontal.byReference(referenceGetter: referenceView, right) let maker = self.storeRight(right) return maker } } public protocol LayoutPropertyCanStoreRightToEvaluateFrameType: LayoutPropertyCanStoreRightType { func evaluateFrame(right: LayoutElement.Horizontal, parameters: IndividualFrameCalculationParameters) -> Rect } extension LayoutPropertyCanStoreRightToEvaluateFrameType { public func storeRight(_ right: LayoutElement.Horizontal) -> IndividualProperty.Layout { let layout = IndividualProperty.Layout(frame: { (parameters) -> Rect in return self.evaluateFrame(right: right, parameters: parameters) }) return layout } }
apache-2.0
76fd1c3908064a92e749a66e2d02291d
26.344828
171
0.764187
4.514231
false
false
false
false
fgengine/quickly
Quickly/Compositions/Standart/QListFieldComposition.swift
1
5760
// // Quickly // open class QListFieldComposable : QComposable { public typealias ShouldClosure = (_ composable: QListFieldComposable) -> Bool public typealias Closure = (_ composable: QListFieldComposable) -> Void public var fieldStyle: QListFieldStyleSheet public var selectedRow: QListFieldPickerRow? public var height: CGFloat public var isValid: Bool{ get { return self.selectedRow != nil } } public var isEditing: Bool public var shouldBeginEditing: ShouldClosure? public var beginEditing: Closure? public var select: Closure? public var shouldEndEditing: ShouldClosure? public var endEditing: Closure? public init( edgeInsets: UIEdgeInsets = UIEdgeInsets.zero, fieldStyle: QListFieldStyleSheet, height: CGFloat = 44, selectedRow: QListFieldPickerRow? = nil, shouldBeginEditing: ShouldClosure? = nil, beginEditing: Closure? = nil, select: Closure? = nil, shouldEndEditing: ShouldClosure? = nil, endEditing: Closure? = nil ) { self.fieldStyle = fieldStyle self.selectedRow = selectedRow self.height = height self.isEditing = false self.shouldBeginEditing = shouldBeginEditing self.beginEditing = beginEditing self.select = select self.shouldEndEditing = shouldEndEditing self.endEditing = endEditing super.init(edgeInsets: edgeInsets) } } open class QListFieldComposition< Composable: QListFieldComposable > : QComposition< Composable >, IQEditableComposition { public lazy private(set) var fieldView: QListField = { let view = QListField(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false view.onShouldBeginEditing = { [weak self] _ in return self?._shouldBeginEditing() ?? true } view.onBeginEditing = { [weak self] _ in self?._beginEditing() } view.onSelect = { [weak self] listField, composable in self?._select(composable) } view.onShouldEndEditing = { [weak self] _ in return self?._shouldEndEditing() ?? true } view.onEndEditing = { [weak self] _ in self?._endEditing() } self.contentView.addSubview(view) return view }() private var _edgeInsets: UIEdgeInsets? private var _constraints: [NSLayoutConstraint] = [] { willSet { self.contentView.removeConstraints(self._constraints) } didSet { self.contentView.addConstraints(self._constraints) } } open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize { return CGSize( width: spec.containerSize.width, height: composable.edgeInsets.top + composable.height + composable.edgeInsets.bottom ) } deinit { if let observer = self.owner as? IQListFieldObserver { self.fieldView.remove(observer: observer) } } open override func setup(owner: AnyObject) { super.setup(owner: owner) if let observer = owner as? IQListFieldObserver { self.fieldView.add(observer: observer, priority: 0) } } open override func preLayout(composable: Composable, spec: IQContainerSpec) { if self._edgeInsets != composable.edgeInsets { self._edgeInsets = composable.edgeInsets self._constraints = [ self.fieldView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.fieldView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left), self.fieldView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.fieldView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom) ] } } open override func apply(composable: Composable, spec: IQContainerSpec) { self.fieldView.apply(composable.fieldStyle) } open override func postLayout(composable: Composable, spec: IQContainerSpec) { self.fieldView.selectedRow = composable.selectedRow } // MARK: IQCompositionEditable open func beginEditing() { self.fieldView.beginEditing() } open func endEditing() { self.fieldView.endEditing(false) } // MARK: Private private func _shouldBeginEditing() -> Bool { guard let composable = self.composable else { return true } if let closure = composable.shouldBeginEditing { return closure(composable) } return true } private func _beginEditing() { guard let composable = self.composable else { return } composable.selectedRow = self.fieldView.selectedRow composable.isEditing = self.fieldView.isEditing if let closure = composable.beginEditing { closure(composable) } } private func _select(_ pickerRow: QListFieldPickerRow) { guard let composable = self.composable else { return } composable.selectedRow = pickerRow if let closure = composable.select { closure(composable) } } private func _shouldEndEditing() -> Bool { guard let composable = self.composable else { return true } if let closure = composable.shouldEndEditing { return closure(composable) } return true } private func _endEditing() { guard let composable = self.composable else { return } composable.isEditing = self.fieldView.isEditing if let closure = composable.endEditing { closure(composable) } } }
mit
0c6a6c1bd0410f5df14b02c688bb5bad
34.337423
122
0.651042
5.193868
false
false
false
false
remirobert/Dotzu
Framework/Dotzu/Dotzu/InformationsTableViewController.swift
2
1576
// // InformationsTableViewController.swift // exampleWindow // // Created by Remi Robert on 18/01/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import UIKit class InformationsTableViewController: UITableViewController { @IBOutlet weak var labelVersionNumber: UILabel! @IBOutlet weak var labelBuildNumber: UILabel! @IBOutlet weak var labelBundleName: UILabel! @IBOutlet weak var labelScreenResolution: UILabel! @IBOutlet weak var labelScreenSize: UILabel! @IBOutlet weak var labelDeviceModel: UILabel! @IBOutlet weak var labelCrashCount: UILabel! var device: Device = Device() override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let store = StoreManager<LogCrash>(store: .crash) let count = store.logs().count labelCrashCount.text = "\(count)" labelCrashCount.textColor = count > 0 ? UIColor.red : UIColor.white } override func viewDidLoad() { super.viewDidLoad() labelCrashCount.frame.size = CGSize(width: 30, height: 20) labelVersionNumber.text = ApplicationInformation.versionNumber labelBuildNumber.text = ApplicationInformation.buildNumber labelBundleName.text = ApplicationInformation.bundleName labelScreenResolution.text = self.device.screenResolution labelScreenSize.text = "\(self.device.screenSize)" labelDeviceModel.text = "\(self.device.deviceModel)" } }
mit
854a15c3d5d8058e12ad6f59db10b873
31.8125
75
0.706667
4.846154
false
false
false
false
meteochu/HanekeSwift
Haneke/UIImageView+Haneke.swift
1
5624
// // UIImageView+Haneke.swift // Haneke // // Created by Hermes Pique on 9/17/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit public extension UIImageView { public var hnk_format : Format<UIImage> { let viewSize = self.bounds.size assert(viewSize.width > 0 && viewSize.height > 0, "[\(Mirror(reflecting: self).description) \(#function)]: UImageView size is zero. Set its frame, call sizeToFit or force layout first.") let scaleMode = self.hnk_scaleMode return HanekeGlobals.UIKit.formatWithSize(size: viewSize, scaleMode: scaleMode) } public func hnk_setImageFromURL(URL: URL, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = NetworkFetcher<UIImage>(url: URL) self.hnk_setImageFromFetcher(fetcher: fetcher, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setImage( image: @autoclosure @escaping () -> UIImage, key: String, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = SimpleFetcher<UIImage>(key: key, value: image) self.hnk_setImageFromFetcher(fetcher: fetcher, placeholder: placeholder, format: format, success: succeed) } public func hnk_setImageFromFile(path: String, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = DiskFetcher<UIImage>(path: path) self.hnk_setImageFromFetcher(fetcher: fetcher, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setImageFromFetcher(fetcher : Fetcher<UIImage>, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) { self.hnk_cancelSetImage() self.hnk_fetcher = fetcher let didSetImage = self.hnk_fetchImageForFetcher(fetcher: fetcher, format: format, failure: fail, success: succeed) if didSetImage { return } if let placeholder = placeholder { self.image = placeholder } } public func hnk_cancelSetImage() { if let fetcher = self.hnk_fetcher { fetcher.cancelFetch() self.hnk_fetcher = nil } } // MARK: Internal // See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances var hnk_fetcher : Fetcher<UIImage>! { get { let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey) as? ObjectWrapper let fetcher = wrapper?.object as? Fetcher<UIImage> return fetcher } set (fetcher) { var wrapper : ObjectWrapper? if let fetcher = fetcher { wrapper = ObjectWrapper(value: fetcher) } objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var hnk_scaleMode : ImageResizer.ScaleMode { switch (self.contentMode) { case .scaleToFill: return .Fill case .scaleAspectFit: return .AspectFit case .scaleAspectFill: return .AspectFill case .redraw, .center, .top, .bottom, .left, .right, .topLeft, .topRight, .bottomLeft, .bottomRight: return .None } } func hnk_fetchImageForFetcher(fetcher : Fetcher<UIImage>, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool { let cache = Shared.imageCache let format = format ?? self.hnk_format if cache.formats[format.name] == nil { cache.addFormat(format: format) } var animated = false let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in if let strongSelf = self { if strongSelf.hnk_shouldCancelForKey(key: fetcher.key) { return } strongSelf.hnk_fetcher = nil fail?(error) } }) { [weak self] image in if let strongSelf = self { if strongSelf.hnk_shouldCancelForKey(key: fetcher.key) { return } strongSelf.hnk_setImage(image: image, animated: animated, success: succeed) } } animated = true return fetch.hasSucceeded } func hnk_setImage(image : UIImage, animated : Bool, success succeed : ((UIImage) -> ())?) { self.hnk_fetcher = nil if let succeed = succeed { succeed(image) } else if animated { UIView.transition(with: self, duration: HanekeGlobals.UIKit.SetImageAnimationDuration, options: .transitionCrossDissolve, animations: { self.image = image }, completion: nil) } else { self.image = image } } func hnk_shouldCancelForKey(key:String) -> Bool { if self.hnk_fetcher?.key == key { return false } Log.debug(message: "Cancelled set image for \((key as NSString).lastPathComponent)") return true } }
apache-2.0
ce24597ee9888e56b9759b26b24161ea
39.460432
201
0.59655
4.690575
false
false
false
false
jaksatomovic/Snapgram
Snapgram/signUpVC.swift
1
9105
// // signUpVC.swift // Snapgram // // Created by Jaksa Tomovic on 28/11/16. // Copyright © 2016 Jaksa Tomovic. All rights reserved. // import UIKit import Parse class signUpVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // profile image @IBOutlet weak var avaImg: UIImageView! // textfields @IBOutlet weak var usernameTxt: UITextField! @IBOutlet weak var passwordTxt: UITextField! @IBOutlet weak var repeatPassword: UITextField! @IBOutlet weak var emailTxt: UITextField! @IBOutlet weak var fullnameTxt: UITextField! @IBOutlet weak var bioTxt: UITextField! @IBOutlet weak var webTxt: UITextField! // buttons @IBOutlet weak var signUpBtn: UIButton! @IBOutlet weak var cancelBtn: UIButton! // scrollView @IBOutlet weak var scrollView: UIScrollView! // reset default size var scrollViewHeight : CGFloat = 0 // keyboard frame size var keyboard = CGRect() // default func override func viewDidLoad() { super.viewDidLoad() // scrollview frame size scrollView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height) scrollView.contentSize.height = self.view.frame.height scrollViewHeight = scrollView.frame.size.height // check notifications if keyboard is shown or not NotificationCenter.default.addObserver(self, selector: #selector(signUpVC.showKeyboard(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(signUpVC.hideKeybard(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) // declare hide kyboard tap let hideTap = UITapGestureRecognizer(target: self, action: #selector(signUpVC.hideKeyboardTap(_:))) hideTap.numberOfTapsRequired = 1 self.view.isUserInteractionEnabled = true self.view.addGestureRecognizer(hideTap) // round ava avaImg.layer.cornerRadius = avaImg.frame.size.width / 2 avaImg.clipsToBounds = true // declare select image tap let avaTap = UITapGestureRecognizer(target: self, action: #selector(signUpVC.loadImg(_:))) avaTap.numberOfTapsRequired = 1 avaImg.isUserInteractionEnabled = true avaImg.addGestureRecognizer(avaTap) // alignment avaImg.frame = CGRect(x: self.view.frame.size.width / 2 - 40, y: 40, width: 80, height: 80) usernameTxt.frame = CGRect(x: 10, y: avaImg.frame.origin.y + 90, width: self.view.frame.size.width - 20, height: 30) passwordTxt.frame = CGRect(x: 10, y: usernameTxt.frame.origin.y + 40, width: self.view.frame.size.width - 20, height: 30) repeatPassword.frame = CGRect(x: 10, y: passwordTxt.frame.origin.y + 40, width: self.view.frame.size.width - 20, height: 30) emailTxt.frame = CGRect(x: 10, y: repeatPassword.frame.origin.y + 60, width: self.view.frame.size.width - 20, height: 30) fullnameTxt.frame = CGRect(x: 10, y: emailTxt.frame.origin.y + 40, width: self.view.frame.size.width - 20, height: 30) bioTxt.frame = CGRect(x: 10, y: fullnameTxt.frame.origin.y + 40, width: self.view.frame.size.width - 20, height: 30) webTxt.frame = CGRect(x: 10, y: bioTxt.frame.origin.y + 40, width: self.view.frame.size.width - 20, height: 30) signUpBtn.frame = CGRect(x: 20, y: webTxt.frame.origin.y + 50, width: self.view.frame.size.width / 4, height: 30) signUpBtn.layer.cornerRadius = signUpBtn.frame.size.width / 20 cancelBtn.frame = CGRect(x: self.view.frame.size.width - self.view.frame.size.width / 4 - 20, y: signUpBtn.frame.origin.y, width: self.view.frame.size.width / 4, height: 30) cancelBtn.layer.cornerRadius = cancelBtn.frame.size.width / 20 // background let bg = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)) bg.image = UIImage(named: "bg.jpg") bg.layer.zPosition = -1 self.view.addSubview(bg) } // call picker to select image func loadImg(_ recognizer:UITapGestureRecognizer) { let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .photoLibrary picker.allowsEditing = true present(picker, animated: true, completion: nil) } // connect selected image to our ImageView func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { avaImg.image = info[UIImagePickerControllerEditedImage] as? UIImage self.dismiss(animated: true, completion: nil) } // hide keyboard if tapped func hideKeyboardTap(_ recoginizer:UITapGestureRecognizer) { self.view.endEditing(true) } // show keyboard func showKeyboard(_ notification:Notification) { // define keyboard size keyboard = (((notification as NSNotification).userInfo?[UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue)! // move up UI UIView.animate(withDuration: 0.4, animations: { () -> Void in self.scrollView.frame.size.height = self.scrollViewHeight - self.keyboard.height }) } // hide keyboard func func hideKeybard(_ notification:Notification) { // move down UI UIView.animate(withDuration: 0.4, animations: { () -> Void in self.scrollView.frame.size.height = self.view.frame.height }) } // clicked sign up @IBAction func signUpBtn_click(_ sender: AnyObject) { print("sign up pressed") // dismiss keyboard self.view.endEditing(true) // if fields are empty if (usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty || repeatPassword.text!.isEmpty || emailTxt.text!.isEmpty || fullnameTxt.text!.isEmpty || bioTxt.text!.isEmpty || webTxt.text!.isEmpty) { // alert message let alert = UIAlertController(title: "PLEASE", message: "fill all fields", preferredStyle: UIAlertControllerStyle.alert) let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil) alert.addAction(ok) self.present(alert, animated: true, completion: nil) return } // if different passwords if passwordTxt.text != repeatPassword.text { // alert message let alert = UIAlertController(title: "PASSWORDS", message: "do not match", preferredStyle: UIAlertControllerStyle.alert) let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil) alert.addAction(ok) self.present(alert, animated: true, completion: nil) return } // send data to server to related collumns let user = PFUser() user.username = usernameTxt.text?.lowercased() user.email = emailTxt.text?.lowercased() user.password = passwordTxt.text user["fullname"] = fullnameTxt.text?.lowercased() user["bio"] = bioTxt.text user["web"] = webTxt.text?.lowercased() // in Edit Profile it's gonna be assigned user["tel"] = "" user["gender"] = "" // convert our image for sending to server let avaData = UIImageJPEGRepresentation(avaImg.image!, 0.5) let avaFile = PFFile(name: "ava.jpg", data: avaData!) user["ava"] = avaFile // save data in server user.signUpInBackground { (success, error) -> Void in if success { print("registered") // remember looged user UserDefaults.standard.set(user.username, forKey: "username") UserDefaults.standard.synchronize() // call login func from AppDelegate.swift class let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.login() } else { // show alert message let alert = UIAlertController(title: "Error", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil) alert.addAction(ok) self.present(alert, animated: true, completion: nil) } } } // clicked cancel @IBAction func cancelBtn_click(_ sender: AnyObject) { // hide keyboard when pressed cancel self.view.endEditing(true) self.dismiss(animated: true, completion: nil) } }
mit
12b3635bc5d8f1464187d4682d69c0c2
38.411255
204
0.621595
4.656777
false
false
false
false
wbaumann/SmartReceiptsiOS
SmartReceiptsTests/Modules Tests/TripDistancesModuleTest.swift
2
1357
// // TripDistancesModuleTest.swift // SmartReceipts // // Created by Bogdan Evsenev on 05/06/2017. // Copyright © 2017 Will Baumann. All rights reserved. // @testable import Cuckoo @testable import SmartReceipts import XCTest import Viperit class TripDistancesModuleTest: XCTestCase { var presenter: MockTripDistancesPresenter! var interactor: MockTripDistancesInteractor! var hasDistance = true override func setUp() { super.setUp() var module = AppModules.tripDistances.build() module.injectMock(presenter: MockTripDistancesPresenter().withEnabledSuperclassSpy()) module.injectMock(interactor: MockTripDistancesInteractor().withEnabledSuperclassSpy()) presenter = module.presenter as? MockTripDistancesPresenter interactor = module.interactor as? MockTripDistancesInteractor configureStubs() } func configureStubs() { stub(interactor) { mock in mock.delete(distance: Distance()).then({ distance in self.hasDistance = false }) } } override func tearDown() { super.tearDown() hasDistance = true } func testPresenterToInteractor() { presenter.delete(distance: Distance()) XCTAssertFalse(hasDistance) } }
agpl-3.0
6922a79ad31cc46c43210caf379365ae
25.076923
95
0.654867
5.255814
false
true
false
false
ktmswzw/jwtSwiftDemoClient
Temp/TableViewController.swift
1
6199
// // TableViewController.swift // Temp // // Created by vincent on 4/2/16. // Copyright © 2016 xecoder. All rights reserved. // import UIKit import CryptoSwift import Alamofire import SwiftyJSON import AlamofireObjectMapper class TableViewController: UITableViewController { let userDefaults = NSUserDefaults.standardUserDefaults() var books = [Book]() override func viewDidLoad() { books.removeAll() super.viewDidLoad() self.navigationItem.leftBarButtonItem = self.editButtonItem() // let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") // self.navigationItem.rightBarButtonItem = addButton sleep(1)//吐司延时 //refreshData() // 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 viewWillAppear(animated: Bool) { books.removeAll() super.viewWillAppear(true) self.refreshData() } func insertNewObject(sender: AnyObject) { getBook() } func refreshData() { if refreshControl != nil { refreshControl!.beginRefreshing() } refresh(refreshControl!) } func getBook() { // let random = arc4random_uniform(100) // let stateMe = random > 50 ? "123123" : "2222222" // let book = Book(inId: "\(random)", inContent: stateMe, inTitle: "\(random)"+"123", inDate: NSDate() ) // books.append(book) // let jwt = JWTTools() let newDict = Dictionary<String,String>() let headers = jwt.getHeader(jwt.token, myDictionary: newDict) Alamofire.request(.GET, "http://192.168.137.1:80/book/all", headers: headers) .responseArray { (response: Response<[Book], NSError>) in let bookList = response.result.value if let list = bookList { for book in list { self.books.append(book) } self.tableView.reloadData() } } } @IBAction func refresh(sender: UIRefreshControl) { books.removeAll() getBook() refreshControl!.endRefreshing() } 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 Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return books.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("BookInfo", forIndexPath: indexPath) as! BookTableViewCell // Configure the cell... let bookCell = books[indexPath.row] as Book cell.title.text = bookCell.title cell.id.text = bookCell.id let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle cell.content.text = dateFormatter.stringFromDate(bookCell.publicDate) return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source let bookCell = books[indexPath.row] as Book books.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) let jwt = JWTTools() let newDict: [String: String] = [:]//["id": bookCell.id] let headers = jwt.getHeader(jwt.token, myDictionary: newDict) Alamofire.request(.DELETE, "http://192.168.137.1:80/book/pathDelete/\(bookCell.id)",headers:headers) .responseJSON { response in } } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // 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?) { if segue.identifier == "showBook" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = books[indexPath.row] as Book (segue.destinationViewController as! BookViewController).detailItem = object } } } }
apache-2.0
710ff7cabfe887511c3b6ec4fdf8fd98
31.925532
157
0.626979
5.354671
false
false
false
false
maximkhatskevich/MKHSequence
Sources/OperationFlow/Defaults.swift
2
395
// // Defaults.swift // MKHOperationFlow // // Created by Maxim Khatskevich on 11/12/16. // Copyright © 2016 Maxim Khatskevich. All rights reserved. // import Foundation //=== public extension OFL { public enum Defaults { public static var targetQueue = OperationQueue() public static var maxRetries: UInt = 3 } }
mit
8ee19980d428b0ba059dba1f15e47934
13.592593
60
0.583756
4.147368
false
false
false
false
brentdax/swift
stdlib/public/SDK/Foundation/NSURL.swift
25
892
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module extension NSURL : _CustomPlaygroundQuickLookable { @available(*, deprecated, message: "NSURL.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: PlaygroundQuickLook { guard let str = absoluteString else { return .text("Unknown URL") } return .url(str) } }
apache-2.0
d0b5d6c8325de704d04f556ef6212e51
41.47619
113
0.61435
5.439024
false
false
false
false
xuech/OMS-WH
OMS-WH/Classes/DeliveryGoods/Controller/SendByOtherViewController.swift
1
13516
// // SendByOtherViewController.swift // OMS-WH // // Created by ___Gwy on 2017/8/21. // Copyright © 2017年 medlog. All rights reserved. // import UIKit import SVProgressHUD //判断发货类型 public enum SendBehaviour : Int{ case byZSFH = 0 case byKDFH case byDBFH case byHKFH case byZTFH } class SendByOtherViewController: UIViewController { var modeBehaviour: SendBehaviour! fileprivate var viewModel = DeliveryGoodsViewModel() var orderModel:OrderListModel? var outboundModel:DGOutBoundListModel? //快递发货所需 var defaultModel:[String:AnyObject]?{ didSet{ table.reloadData() } } //快递发货所需 var expressArr = [[String:AnyObject]]() var expressCode:String? //航空发货所需 var airCompanyArr = [[String:AnyObject]]() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white setUp() switch modeBehaviour { case .byZSFH: title = "直送发货" requstDefaultInfo() case .byKDFH: title = "快递发货" requstExpress() case .byDBFH: title = "大巴发货" case .byHKFH: title = "航空发货" requstAirCompany() case .byZTFH: title = "自提发货" default: return } } fileprivate func setUp(){ view.addSubview(table) view.addSubview(submitBtn) submitBtn.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self.view) make.height.equalTo(44) } } //MARK:确定按钮 fileprivate lazy var submitBtn: UIButton = { let submitBtn = UIButton(imageName: "", fontSize: 15, color: UIColor.white, title: "提交", bgColor: kAppearanceColor) submitBtn.addTarget(self, action: #selector(submit), for: .touchUpInside) return submitBtn }() //列表 fileprivate lazy var table:UITableView = { let table = UITableView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight-44), style: .plain) table.separatorStyle = .none table.dataSource = self table.delegate = self table.register(PicAndTFTableViewCell.self) return table }() //直送发货-请求默认信息 fileprivate func requstDefaultInfo(){ viewModel.requstdefaultDirectDeliveryInfo(orderModel!.sONo, "oms-api-v3/order/operation/defaultDirectDeliveryInfo") { (data, error) in self.defaultModel = data } } //快递发货-请求快递方式 fileprivate func requstExpress(){ viewModel.requstDict(["dictTypeCode":"RFNOTP","dictSubClass1":"Express"]) { (data, error) in self.expressArr = data } } //航空发货-请求航空公司 fileprivate func requstAirCompany(){ viewModel.requstDict(["dictTypeCode":"RFNOTP","dictSubClass1":"AIR"]) { (data, error) in self.airCompanyArr = data } } fileprivate func operationSuccess(){ if let vc = self.navigationController?.viewControllers[1] as? DeliveryGoodsViewController,let sONo = orderModel?.sONo { SVProgressHUD.showSuccess("订单\(sONo)发货成功") _ = self.navigationController?.popToViewController(vc, animated: true) } } @objc func submit(){ let cellOne = table.cellForRow(at: IndexPath(row: 0, section: 0)) as! PicAndTFTableViewCell let cellTwo = table.cellForRow(at: IndexPath(row: 1, section: 0)) as! PicAndTFTableViewCell let cellThree = table.cellForRow(at: IndexPath(row: 2, section: 0)) as! PicAndTFTableViewCell var param = [String:Any]() switch modeBehaviour! { case .byZSFH: guard cellOne.textTF.text != "" else { return SVProgressHUD.showError("请输入送货人姓名") } guard cellTwo.textTF.text != "" else { return SVProgressHUD.showError("请输入送货人手机") } var modelData = [String:String]() modelData["deliverymanRemark"] = cellThree.textTF.text param["deliveryman"] = cellOne.textTF.text param["deliverymanPhone"] = cellTwo.textTF.text param["sONo"] = orderModel?.sONo param["wONo"] = outboundModel?.wONo param["modelData"] = modelData viewModel.submit(param, "oms-api-v3/order/operation/deliveryByDirect") { (data, error) in self.operationSuccess() } case .byKDFH: guard cellOne.textTF.text != "" else { return SVProgressHUD.showError("请选择快递公司") } guard cellTwo.textTF.text != "" else { return SVProgressHUD.showError("请输入快递单号") } param["expressCompanyName"] = expressCode param["expressNumber"] = cellTwo.textTF.text param["sendRemark"] = cellThree.textTF.text param["sONo"] = orderModel?.sONo param["wONo"] = outboundModel?.wONo viewModel.submit(param, "oms-api-v3/order/operation/deliveryByExpress", { (data, error) in self.operationSuccess() }) case .byDBFH: let cellFour = table.cellForRow(at: IndexPath(row: 3, section: 0)) as! PicAndTFTableViewCell guard cellOne.textTF.text != "" else { return SVProgressHUD.showError("请输入车牌号") } guard cellTwo.textTF.text != "" else { return SVProgressHUD.showError("请输入司机电话") } param["busNumber"] = cellOne.textTF.text param["busDriverMobileNumber"] = cellTwo.textTF.text param["busDriverName"] = cellThree.textTF.text param["carrierTransRemark"] = cellFour.textTF.text param["sONo"] = orderModel?.sONo param["wONo"] = outboundModel?.wONo viewModel.submit(param, "oms-api-v3/order/operation/deliveryByBus", { (data, error) in self.operationSuccess() }) case.byHKFH: let cellFour = table.cellForRow(at: IndexPath(row: 3, section: 0)) as! PicAndTFTableViewCell let cellFive = table.cellForRow(at: IndexPath(row: 4, section: 0)) as! PicAndTFTableViewCell guard cellOne.textTF.text != "" else { return SVProgressHUD.showError("请选择航空公司") } guard cellTwo.textTF.text != "" else { return SVProgressHUD.showError("请输入航班号") } guard cellThree.textTF.text != "" else { return SVProgressHUD.showError("请输入送货人") } guard cellFour.textTF.text != "" else { return SVProgressHUD.showError("请输入送货人手机") } param["airlineCompany"] = cellOne.textTF.text param["carrierTransPerson"] = cellThree.textTF.text param["carrierTransPersonMobile"] = cellFour.textTF.text param["carrierTransRemark"] = cellFive.textTF.text param["flightNumber"] = cellTwo.textTF.text param["sONo"] = orderModel?.sONo param["wONo"] = outboundModel?.wONo viewModel.submit(param, "oms-api-v3/order/operation/deliveryByAir", { (data, error) in self.operationSuccess() }) case .byZTFH: guard cellOne.textTF.text != "" else { return SVProgressHUD.showError("请输入提货人") } guard cellTwo.textTF.text != "" else { return SVProgressHUD.showError("请输入提货人手机") } param["pickUpPerson"] = cellOne.textTF.text param["pickUpPersonMobile"] = cellTwo.textTF.text param["carrierTransRemark"] = cellThree.textTF.text param["sONo"] = orderModel?.sONo param["wONo"] = outboundModel?.wONo viewModel.submit(param, "oms-api-v3/order/operation/deliveryByPickUp", { (data, error) in self.operationSuccess() }) } } } extension SendByOtherViewController:UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PicAndTFTableViewCell") as! PicAndTFTableViewCell switch modeBehaviour! { case .byZSFH: if indexPath.row == 0{ cell.textTF.placeholder = "送货人" cell.textTF.text = defaultModel?["deliveryman"] as? String cell.needImage.isHidden = false }else if indexPath.row == 1{ cell.textTF.placeholder = "送货人手机" cell.textTF.text = defaultModel?["deliverymanPhone"] as? String cell.needImage.isHidden = false }else{ cell.textTF.placeholder = "送货备注" } case .byKDFH: if indexPath.row == 0{ cell.textTF.placeholder = "快递公司" cell.textTF.isUserInteractionEnabled = false cell.needImage.isHidden = false }else if indexPath.row == 1{ cell.textTF.placeholder = "快递单号" cell.needImage.isHidden = false }else{ cell.textTF.placeholder = "送货备注" cell.textTF.text = "运费已付" } case .byDBFH: if indexPath.row == 0{ cell.textTF.placeholder = "车牌号" cell.needImage.isHidden = false }else if indexPath.row == 1{ cell.textTF.placeholder = "司机电话" cell.needImage.isHidden = false }else if indexPath.row == 2{ cell.textTF.placeholder = "司机" cell.needImage.isHidden = false }else{ cell.textTF.placeholder = "送货备注" cell.textTF.text = "运费已付" } case .byHKFH: if indexPath.row == 0{ cell.textTF.placeholder = "航空公司" cell.textTF.isUserInteractionEnabled = false cell.needImage.isHidden = false }else if indexPath.row == 1{ cell.textTF.placeholder = "航班号" cell.needImage.isHidden = false }else if indexPath.row == 2{ cell.textTF.placeholder = "送货人" cell.needImage.isHidden = false }else if indexPath.row == 3{ cell.textTF.placeholder = "送货人手机" cell.needImage.isHidden = false }else{ cell.textTF.placeholder = "送货人备注" cell.textTF.text = "运费已付" } case .byZTFH: if indexPath.row == 0{ cell.textTF.placeholder = "提货人" cell.needImage.isHidden = false }else if indexPath.row == 1{ cell.textTF.placeholder = "提货人手机" cell.needImage.isHidden = false cell.textTF.keyboardType = .phonePad }else{ cell.textTF.placeholder = "提货备注(对提货的特殊提醒,如张三 身份证xxx)" } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch modeBehaviour! { case .byKDFH: if indexPath.row == 0{ let chooseVC = PickViewController(frame: self.view.bounds, dataSource: self.expressArr, title: "请选择快递公司", modeBehaviour: ChooseBehaviour.chooseDictValue) chooseVC.GetCode = {(indexpath:Int) in let cell = self.table.cellForRow(at: IndexPath(row: indexPath.row, section: 0)) as! PicAndTFTableViewCell cell.textTF.text = self.expressArr[indexpath]["dictValueName"] as? String self.expressCode = self.expressArr[indexpath]["dictValueCode"] as? String } self.view.addSubview(chooseVC.view) self.addChildViewController(chooseVC) } case .byHKFH: if indexPath.row == 0{ let chooseVC = PickViewController(frame: self.view.bounds, dataSource: self.airCompanyArr, title: "请选择航空公司", modeBehaviour: ChooseBehaviour.chooseDictValue) chooseVC.GetCode = {(indexpath:Int) in let cell = self.table.cellForRow(at: IndexPath(row: indexPath.row, section: 0)) as! PicAndTFTableViewCell cell.textTF.text = self.airCompanyArr[indexpath]["dictValueName"] as? String } self.view.addSubview(chooseVC.view) self.addChildViewController(chooseVC) } default: return } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch modeBehaviour! { case .byDBFH: return 4 case .byHKFH: return 5 default: return 3 } } }
mit
3a270b95b002d960bd87580bb2a682f0
38.227273
172
0.57389
4.663184
false
false
false
false
hooman/swift
stdlib/public/core/Random.swift
9
6870
//===--- Random.swift -----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 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 // //===----------------------------------------------------------------------===// import SwiftShims /// A type that provides uniformly distributed random data. /// /// When you call methods that use random data, such as creating new random /// values or shuffling a collection, you can pass a `RandomNumberGenerator` /// type to be used as the source for randomness. When you don't pass a /// generator, the default `SystemRandomNumberGenerator` type is used. /// /// When providing new APIs that use randomness, provide a version that accepts /// a generator conforming to the `RandomNumberGenerator` protocol as well as a /// version that uses the default system generator. For example, this `Weekday` /// enumeration provides static methods that return a random day of the week: /// /// enum Weekday: CaseIterable { /// case sunday, monday, tuesday, wednesday, thursday, friday, saturday /// /// static func random<G: RandomNumberGenerator>(using generator: inout G) -> Weekday { /// return Weekday.allCases.randomElement(using: &generator)! /// } /// /// static func random() -> Weekday { /// var g = SystemRandomNumberGenerator() /// return Weekday.random(using: &g) /// } /// } /// /// Conforming to the RandomNumberGenerator Protocol /// ================================================ /// /// A custom `RandomNumberGenerator` type can have different characteristics /// than the default `SystemRandomNumberGenerator` type. For example, a /// seedable generator can be used to generate a repeatable sequence of random /// values for testing purposes. /// /// To make a custom type conform to the `RandomNumberGenerator` protocol, /// implement the required `next()` method. Each call to `next()` must produce /// a uniform and independent random value. /// /// Types that conform to `RandomNumberGenerator` should specifically document /// the thread safety and quality of the generator. public protocol RandomNumberGenerator { /// Returns a value from a uniform, independent distribution of binary data. /// /// Use this method when you need random binary data to generate another /// value. If you need an integer value within a specific range, use the /// static `random(in:using:)` method on that integer type instead of this /// method. /// /// - Returns: An unsigned 64-bit random value. mutating func next() -> UInt64 } extension RandomNumberGenerator { // An unavailable default implementation of next() prevents types that do // not implement the RandomNumberGenerator interface from conforming to the // protocol; without this, the default next() method returning a generic // unsigned integer will be used, recursing infinitely and probably blowing // the stack. @available(*, unavailable) @_alwaysEmitIntoClient public mutating func next() -> UInt64 { fatalError() } /// Returns a value from a uniform, independent distribution of binary data. /// /// Use this method when you need random binary data to generate another /// value. If you need an integer value within a specific range, use the /// static `random(in:using:)` method on that integer type instead of this /// method. /// /// - Returns: A random value of `T`. Bits are randomly distributed so that /// every value of `T` is equally likely to be returned. @inlinable public mutating func next<T: FixedWidthInteger & UnsignedInteger>() -> T { return T._random(using: &self) } /// Returns a random value that is less than the given upper bound. /// /// Use this method when you need random binary data to generate another /// value. If you need an integer value within a specific range, use the /// static `random(in:using:)` method on that integer type instead of this /// method. /// /// - Parameter upperBound: The upper bound for the randomly generated value. /// Must be non-zero. /// - Returns: A random value of `T` in the range `0..<upperBound`. Every /// value in the range `0..<upperBound` is equally likely to be returned. @inlinable public mutating func next<T: FixedWidthInteger & UnsignedInteger>( upperBound: T ) -> T { _precondition(upperBound != 0, "upperBound cannot be zero.") // We use Lemire's "nearly divisionless" method for generating random // integers in an interval. For a detailed explanation, see: // https://arxiv.org/abs/1805.10941 var random: T = next() var m = random.multipliedFullWidth(by: upperBound) if m.low < upperBound { let t = (0 &- upperBound) % upperBound while m.low < t { random = next() m = random.multipliedFullWidth(by: upperBound) } } return m.high } } /// The system's default source of random data. /// /// When you generate random values, shuffle a collection, or perform another /// operation that depends on random data, this type is the generator used by /// default. For example, the two method calls in this example are equivalent: /// /// let x = Int.random(in: 1...100) /// var g = SystemRandomNumberGenerator() /// let y = Int.random(in: 1...100, using: &g) /// /// `SystemRandomNumberGenerator` is automatically seeded, is safe to use in /// multiple threads, and uses a cryptographically secure algorithm whenever /// possible. /// /// Platform Implementation of `SystemRandomNumberGenerator` /// ======================================================== /// /// While the system generator is automatically seeded and thread-safe on every /// platform, the cryptographic quality of the stream of random data produced by /// the generator may vary. For more detail, see the documentation for the APIs /// used by each platform. /// /// - Apple platforms use `arc4random_buf(3)`. /// - Linux platforms use `getrandom(2)` when available; otherwise, they read /// from `/dev/urandom`. /// - Windows uses `BCryptGenRandom`. @frozen public struct SystemRandomNumberGenerator: RandomNumberGenerator, Sendable { /// Creates a new instance of the system's default random number generator. @inlinable public init() { } /// Returns a value from a uniform, independent distribution of binary data. /// /// - Returns: An unsigned 64-bit random value. @inlinable public mutating func next() -> UInt64 { var random: UInt64 = 0 swift_stdlib_random(&random, MemoryLayout<UInt64>.size) return random } }
apache-2.0
f4c4dac85e376339da21cdf8667c7ca0
40.890244
95
0.675983
4.62938
false
false
false
false
kumabook/MusicFav
MusicFav/TutorialView.swift
1
7990
// // TutorialView.swift // MusicFav // // Created by Hiroki Kumamoto on 4/19/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import EAIntroView protocol TutorialViewDelegate: EAIntroDelegate { func tutorialLoginButtonTapped() } class TutorialView: EAIntroView { class func tutorialView(_ frame: CGRect, delegate: TutorialViewDelegate?) -> TutorialView { let menuPage = capturePage(frame, title: String.tutorialString("menu_page_title"), desc: String.tutorialString("menu_page_desc"), bgColor: UIColor.theme, imageName: "menu_cap") let streamPage = capturePage(frame, title: String.tutorialString("stream_page_title"), desc: String.tutorialString("stream_page_desc"), bgColor: UIColor.theme, imageName: "stream_cap") let playlistPage = capturePage(frame, title: String.tutorialString("playlist_page_title"), desc: String.tutorialString("playlist_page_desc"), bgColor: UIColor.theme, imageName: "playlist_cap") let playerPage = capturePage(frame, title: String.tutorialString("player_page_title"), desc: String.tutorialString("player_page_desc"), bgColor: UIColor.theme, imageName: "player_cap") let pages: [EAIntroPage] = [firstPage(frame), streamPage, playlistPage, playerPage, menuPage, lastPage(frame, delegate: delegate)] let tutorialView = TutorialView(frame: frame, andPages: pages) tutorialView?.delegate = delegate return tutorialView! } class func firstPage(_ frame: CGRect) -> EAIntroPage { let height = frame.height let width = frame.width let page = EAIntroPage() page.title = String.tutorialString("first_page_title") page.titlePositionY = frame.height * 0.55 let imageView = UIImageView(image: UIImage(named: "note")) imageView.contentMode = UIViewContentMode.scaleAspectFit imageView.frame = CGRect(x: 0, y: 0, width: width * 0.3, height: height * 0.3) page.titleIconView = imageView page.desc = String.tutorialString("first_page_desc") page.descPositionY = frame.height * 0.4 page.bgColor = UIColor.theme let deviceType = DeviceType.from(UIDevice.current) switch deviceType { case .iPhone4OrLess: page.descFont = UIFont.systemFont(ofSize: 14) page.titleFont = UIFont.boldSystemFont(ofSize: 20) case .iPhone5: page.descFont = UIFont.systemFont(ofSize: 16) page.titleFont = UIFont.boldSystemFont(ofSize: 24) case .iPhone6: page.descFont = UIFont.systemFont(ofSize: 18) page.titleFont = UIFont.boldSystemFont(ofSize: 26) case .iPhone6Plus: page.descFont = UIFont.systemFont(ofSize: 20) page.titleFont = UIFont.boldSystemFont(ofSize: 28) case .iPad: page.descFont = UIFont.systemFont(ofSize: 30) page.titleFont = UIFont.boldSystemFont(ofSize: 36) case .unknown: page.descFont = UIFont.systemFont(ofSize: 16) page.titleFont = UIFont.boldSystemFont(ofSize: 24) } return page } class func capturePage(_ frame: CGRect, title: String, desc: String, bgColor: UIColor, imageName: String) -> EAIntroPage { let height = frame.height let width = frame.width let deviceType = DeviceType.from(UIDevice.current) let descLabel = UILabel(frame: CGRect(x: width*0.1, y: height*0.58, width: width*0.8, height: height*0.2)) descLabel.textColor = UIColor.white descLabel.textAlignment = NSTextAlignment.left descLabel.numberOfLines = 6 descLabel.lineBreakMode = NSLineBreakMode.byWordWrapping descLabel.text = desc let page = EAIntroPage() page.title = title page.titlePositionY = frame.height * 0.5 page.bgColor = bgColor let imageView = UIImageView(image: UIImage(named: imageName)) imageView.contentMode = UIViewContentMode.scaleAspectFit imageView.frame = CGRect(x: 0, y: 0, width: width * 0.8, height: height * 0.4) page.titleIconView = imageView page.subviews = [descLabel] switch deviceType { case .iPhone4OrLess: descLabel.font = UIFont.systemFont(ofSize: 12) page.titleFont = UIFont.boldSystemFont(ofSize: 16) case .iPhone5: descLabel.font = UIFont.systemFont(ofSize: 14) page.titleFont = UIFont.boldSystemFont(ofSize: 20) case .iPhone6: descLabel.font = UIFont.systemFont(ofSize: 16) page.titleFont = UIFont.boldSystemFont(ofSize: 24) case .iPhone6Plus: descLabel.font = UIFont.systemFont(ofSize: 18) page.titleFont = UIFont.boldSystemFont(ofSize: 26) case .iPad: descLabel.font = UIFont.systemFont(ofSize: 26) page.titleFont = UIFont.boldSystemFont(ofSize: 36) case .unknown: descLabel.font = UIFont.systemFont(ofSize: 18) page.titleFont = UIFont.boldSystemFont(ofSize: 26) } return page } class func lastPage(_ frame: CGRect, delegate: TutorialViewDelegate?) -> EAIntroPage { let height = frame.height let width = frame.width let deviceType = DeviceType.from(UIDevice.current) let page = EAIntroPage() page.title = String.tutorialString("last_page_title") page.titleFont = UIFont.boldSystemFont(ofSize: 32) page.titlePositionY = height * 0.5 let imageView = UIImageView(image: UIImage(named: "note")) imageView.contentMode = UIViewContentMode.scaleAspectFit imageView.frame = CGRect(x: 0, y: 0, width: width * 0.4, height: height * 0.4) page.titleIconView = imageView page.desc = String.tutorialString("last_page_desc") page.descFont = UIFont.systemFont(ofSize: 20) page.descPositionY = height * 0.4 page.bgColor = UIColor.theme switch deviceType { case .iPhone4OrLess: page.descFont = UIFont.systemFont(ofSize: 16) page.titleFont = UIFont.boldSystemFont(ofSize: 24) case .iPhone5: page.descFont = UIFont.systemFont(ofSize: 18) page.titleFont = UIFont.boldSystemFont(ofSize: 26) case .iPhone6: page.descFont = UIFont.systemFont(ofSize: 22) page.titleFont = UIFont.boldSystemFont(ofSize: 28) case .iPhone6Plus: page.descFont = UIFont.systemFont(ofSize: 24) page.titleFont = UIFont.boldSystemFont(ofSize: 30) case .iPad: page.descFont = UIFont.systemFont(ofSize: 30) page.titleFont = UIFont.boldSystemFont(ofSize: 36) case .unknown: page.descFont = UIFont.systemFont(ofSize: 18) page.titleFont = UIFont.boldSystemFont(ofSize: 26) } return page } }
mit
e615a30e4f80f670456ca32a191f0a85
47.719512
126
0.561327
4.863055
false
false
false
false
narner/AudioKit
Examples/iOS/MIDIUtility/MIDIUtility/MIDISenderVC.swift
1
4980
// // MIDISenderVC.swift // MIDIUtility // // Created by Jeff Cooper on 9/11/17. // Copyright © 2017 AudioKit. All rights reserved. // import Foundation import AudioKit import UIKit class MIDISenderVC: UIViewController { let midiOut = AKMIDI() @IBOutlet var noteNumField: UITextField! @IBOutlet var noteVelField: UITextField! @IBOutlet var noteChanField: UITextField! @IBOutlet var ccField: UITextField! @IBOutlet var ccValField: UITextField! @IBOutlet var ccChanField: UITextField! @IBOutlet var sysexField: UITextView! var noteToSend: Int? { return Int(noteNumField.text!) } var velocityToSend: Int? { return Int(noteVelField.text!) } var noteChanToSend: Int { if noteChanField.text == nil || Int(noteChanField.text!) == nil { return 1 } return Int(noteChanField.text!)! - 1 } var ccToSend: Int? { return Int(ccField.text!) } var ccValToSend: Int? { return Int(ccValField.text!) } var ccChanToSend: Int { if ccChanField.text == nil || Int(ccChanField.text!) == nil { return 1 } return Int(ccChanField.text!)! - 1 } var sysexToSend: [Int]? { var data = [Int]() if sysexField.text == nil { return nil } let splitField = sysexField.text!.components(separatedBy: " ") for entry in splitField { let intVal = Int(entry) if intVal != nil && intVal! <= 247 && intVal! > -1 { data.append(intVal!) } } return data } override func viewDidLoad() { midiOut.openOutput() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } @IBAction func sendNotePressed(_ sender: UIButton) { if noteToSend != nil && velocityToSend != nil { print("sending note: \(noteToSend!) - \(velocityToSend!)") let event = AKMIDIEvent(noteOn: MIDINoteNumber(noteToSend!), velocity: MIDIVelocity(velocityToSend!), channel: MIDIChannel(noteChanToSend)) midiOut.sendEvent(event) } else { print("error w note fields") } } @IBAction func sendCCPressed(_ sender: UIButton) { if ccToSend != nil && ccValToSend != nil { print("sending cc: \(ccToSend!) - \(ccValToSend!)") let event = AKMIDIEvent(controllerChange: MIDIByte(ccToSend!), value: MIDIByte(ccValToSend!), channel: MIDIChannel(ccChanToSend)) midiOut.sendEvent(event) } else { print("error w cc fields") } } @IBAction func sendSysexPressed(_ sender: UIButton) { if sysexToSend != nil { var midiBytes = [MIDIByte]() for byte in sysexToSend! { midiBytes.append(MIDIByte(byte)) } if midiBytes[0] != 240 || midiBytes.last != 247 || midiBytes.count < 2 { print("bad sysex data - must start with 240 and end with 247") print("parsed sysex: \(sysexToSend!)") return } print("sending sysex \(sysexToSend!)") let event = AKMIDIEvent(data: midiBytes) midiOut.sendEvent(event) } else { print("error w sysex field") } } @IBAction func receiveMIDIButtonPressed(_ sender: UIButton) { dismiss(animated: true, completion: nil) } } class MIDIChannelField: UITextField, UITextFieldDelegate { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var startString = "" if (textField.text != nil) { startString += textField.text! } startString += string let limitNumber = Int(startString) if limitNumber == nil || limitNumber! > 16 || limitNumber! == 0 { return false } else { return true } } } class MIDINumberField: UITextField, UITextFieldDelegate { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var startString = "" if (textField.text != nil) { startString += textField.text! } startString += string let limitNumber = Int(startString) if limitNumber == nil || limitNumber! > 127 { return false } else { return true } } }
mit
33689ad1e28febaf18c4dd1b77a9ecba
30.916667
151
0.576421
4.631628
false
false
false
false
jemmons/Medea
Sources/Medea/AnyJSON.swift
1
1501
import Foundation public enum AnyJSON { case null, bool(Bool), number(NSNumber), string(String), array(JSONArray), object(JSONObject) public init(_ value: Any) throws { switch value { case is NSNull: self = .null case let b as Bool: self = .bool(b) case let n as NSNumber: self = .number(n) case let s as String: self = .string(s) case let a as JSONArray: self = .array(a) case let d as JSONObject: self = .object(d) default: throw JSONError.invalidType } } } public extension AnyJSON { func objectValue() throws -> JSONObject { guard case .object(let d) = self else { throw JSONError.unexpectedType } return d } func arrayValue() throws -> JSONArray { guard case .array(let a) = self else { throw JSONError.unexpectedType } return a } func stringValue() throws -> String { guard case .string(let s) = self else { throw JSONError.unexpectedType } return s } func boolValue() throws -> Bool { guard case .bool(let b) = self else { throw JSONError.unexpectedType } return b } func numberValue() throws -> NSNumber { guard case .number(let n) = self else { throw JSONError.unexpectedType } return n } var isNull: Bool { switch self { case .null: return true default: return false } } var isNotNull: Bool { return !isNull } }
mit
abb616a3c74ff3ba33e045611a7f4be5
16.869048
95
0.590273
4.181058
false
false
false
false
tinrobots/Mechanica
Tests/StandardLibraryTests/OptionalUtilsTests.swift
1
2788
import XCTest @testable import Mechanica extension OptionalUtilsTests { static var allTests = [ ("testHasValue", testHasValue), ("testOr", testOr), ("testOrWithAutoclosure", testOrWithAutoclosure), ("testOrWithClosure", testOrWithClosure), ("testOrThrowException", testOrThrowException), ("testCollectionIsNilOrEmpty", testCollectionIsNilOrEmpty), ("testStringIsNilOrEmpty", testStringIsNilOrEmpty), ("isNilOrBlank", testIsNilOrBlank), ] } final class OptionalUtilsTests: XCTestCase { func testHasValue() { var value: Any? XCTAssert(!value.hasValue) value = "tinrobots" XCTAssert(value.hasValue) } func testOr() { let value1: String? = "hello" XCTAssertEqual(value1.or("world"), "hello") let value2: String? = nil XCTAssertEqual(value2.or("world"), "world") } func testOrWithAutoclosure() { func runMe() -> String { return "world" } let value1: String? = "hello" XCTAssertEqual(value1.or(else: runMe()), "hello") let value2: String? = nil XCTAssertEqual(value2.or(else: runMe()), "world") } func testOrWithClosure() { let value1: String? = "hello" XCTAssertEqual(value1.or(else: { return "world" }), "hello") let value2: String? = nil XCTAssertEqual(value2.or(else: { return "world" }), "world") } func testOrThrowException() { enum DemoError: Error { case test } let value1: String? = "hello" XCTAssertNoThrow(try value1.or(throw: DemoError.test)) let value2: String? = nil XCTAssertThrowsError(try value2.or(throw: DemoError.test)) } func testCollectionIsNilOrEmpty() { do { let collection: [Int]? = [1, 2, 3] XCTAssertFalse(collection.isNilOrEmpty) } do { let collection: [Int]? = nil XCTAssertTrue(collection.isNilOrEmpty) } do { let collection: [Int]? = [] XCTAssertTrue(collection.isNilOrEmpty) } } func testStringIsNilOrEmpty() { do { let text: String? = "mechanica" XCTAssertFalse(text.isNilOrEmpty) } do { let text: String? = " " XCTAssertFalse(text.isNilOrEmpty) } do { let text: String? = "" XCTAssertTrue(text.isNilOrEmpty) } do { let text: String? = nil XCTAssertTrue(text.isNilOrEmpty) } } func testIsNilOrBlank() { do { let text: String? = "mechanica" XCTAssertFalse(text.isNilOrBlank) } do { let text: String? = " " XCTAssertTrue(text.isNilOrBlank) } do { let text: String? = " " XCTAssertTrue(text.isNilOrBlank) } do { let text: String? = "" XCTAssertTrue(text.isNilOrBlank) } do { let text: String? = nil XCTAssertTrue(text.isNilOrBlank) } } }
mit
8213b1dfc4502ced27341ac8ab78a5d6
22.233333
64
0.624462
4.052326
false
true
false
false
h-n-y/UICollectionView-TheCompleteGuide
chapter-2/2-selection-view/chapter2-5/CollectionViewCell.swift
1
1712
// // CollectionViewCell.swift // chapter2-5 // // Created by Hans Yelek on 4/25/16. // Copyright © 2016 Hans Yelek. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { private let imageView = UIImageView() var image: UIImage? = nil { didSet { imageView.image = image } } override var highlighted: Bool { didSet { if highlighted { imageView.alpha = 0.8 } else { imageView.alpha = 1.0 } } } override init(frame: CGRect) { super.init(frame: frame) imageView.frame = CGRectInset(self.bounds, 10, 10) imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true self.contentView.addSubview(imageView) let selectedBackgroundView = UIView(frame: CGRectZero) selectedBackgroundView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.8) self.selectedBackgroundView = selectedBackgroundView } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) imageView.frame = CGRectInset(self.bounds, 10, 10) self.contentView.addSubview(imageView) let selectedBackgroundView = UIView(frame: CGRectZero) selectedBackgroundView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.8) self.selectedBackgroundView = selectedBackgroundView } override func prepareForReuse() { super.prepareForReuse() self.backgroundColor = UIColor.whiteColor() self.image = nil } }
mit
e276ac47eac4f201656df37edaa97a6e
26.596774
98
0.612507
5.330218
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/Dashboard/Tab Redesign/PortraitFlowLayout.swift
2
3085
// // PortraitFlowLayout.swift // TabsRedesign // // Created by Tim Palade on 3/29/17. // Copyright © 2017 Tim Palade. All rights reserved. // import UIKit class TabSwitcherLayoutAttributes: UICollectionViewLayoutAttributes { var displayTransform: CATransform3D = CATransform3DIdentity override func copy(with zone: NSZone? = nil) -> Any { let _copy = super.copy(with: zone) as! TabSwitcherLayoutAttributes _copy.displayTransform = displayTransform return _copy } override func isEqual(_ object: Any?) -> Bool { guard let attr = object as? TabSwitcherLayoutAttributes else { return false } return super.isEqual(object) && CATransform3DEqualToTransform(displayTransform, attr.displayTransform) } } class PortraitFlowLayout: UICollectionViewFlowLayout { var currentCount: Int = 0 var currentTransform: CATransform3D = CATransform3DIdentity override init() { super.init() self.minimumInteritemSpacing = UIScreen.main.bounds.size.width self.minimumLineSpacing = 0.0 self.scrollDirection = .vertical self.sectionInset = UIEdgeInsetsMake(16, 0, 0, 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override class var layoutAttributesClass: AnyClass { return TabSwitcherLayoutAttributes.self } override func prepare() { if let count = self.collectionView?.numberOfItems(inSection: 0) { if count != currentCount { currentTransform = computeTransform(count: count) currentCount = count } } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let attrs = super.layoutAttributesForElements(in: rect) else {return nil} return attrs.map({ attr in return pimpedAttribute(attr) }) } func pimpedAttribute(_ attribute: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { if let attr = attribute.copy() as? TabSwitcherLayoutAttributes { //attr.zIndex = attr.indexPath.item attr.displayTransform = currentTransform return attr } return attribute } func computeTransform(count:Int) -> CATransform3D { var t: CATransform3D = CATransform3DIdentity t.m34 = -1.0 / (CGFloat(1000)) t = CATransform3DRotate(t, -CGFloat(Knobs.tiltAngle(count: count)), 1, 0, 0) //calculate how much down t will take the layer and then compensate for that. //this view must have the dimensions of the view this attr is going to be applied to. let view = UIView(frame: CGRect(x: 0, y: 0, width: Knobs.cellWidth(), height: Knobs.cellHeight())) view.layer.transform = t t = CATransform3DTranslate(t, 0, -view.layer.frame.origin.y, 0) return t } }
mpl-2.0
e072e47a10874c01d8493a5f4f628345
31.125
110
0.639754
4.856693
false
false
false
false
OverSwift/VisualReader
MangaReader/Classes/Presentation/Scenes/MultyLevelTableController.swift
1
2728
// // MultyLevelTableController.swift // MangaReader // // Created by Sergiy Loza on 09.02.17. // Copyright © 2017 Serhii Loza. All rights reserved. // import UIKit class MultyLevelTableController: UITableViewController { let dataIdentifiers = ["HeaderCell", "ReadNotesCell","ReadNotesCell", "LocationCell", "ReadNotesCell","ReadNotesCell", "RescheduleCell"] let shadowView = UIView(frame: CGRect.zero) override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 tableView.contentInset.bottom += 28 var nib = UINib(nibName: "HeaderCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "HeaderCell") nib = UINib(nibName: "ReadNotesCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "ReadNotesCell") nib = UINib(nibName: "RescheduleCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "RescheduleCell") nib = UINib(nibName: "LocationCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "LocationCell") shadowView.backgroundColor = UIColor.white self.view.addSubview(shadowView) self.view.sendSubview(toBack: shadowView) let layer = shadowView.layer layer.masksToBounds = false layer.shadowRadius = 5 layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor layer.shadowOpacity = 1.0 } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) tableView.reloadData() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let newFrame = CGRect(x: 10, y: 10, width: self.tableView.contentSize.width - 20, height: self.tableView.contentSize.height - 10) shadowView.frame = newFrame } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if !segue.destination.isViewLoaded { segue.destination.loadViewIfNeeded() segue.destination.view.setNeedsLayout() segue.destination.view.layoutIfNeeded() print("Child bounds \(segue.destination.view.bounds)") } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataIdentifiers.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: dataIdentifiers[indexPath.row], for: indexPath) return cell } }
bsd-3-clause
c7d094ae39ea0f3f64e08c9763a87bc9
32.666667
138
0.718739
4.734375
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/What's New/Views/AnnouncementCell.swift
1
4278
class AnnouncementCell: AnnouncementTableViewCell { // MARK: - View elements private lazy var headingLabel: UILabel = { return makeLabel(font: Appearance.headingFont) }() private lazy var subHeadingLabel: UILabel = { return makeLabel(font: Appearance.subHeadingFont, color: .textSubtle) }() private lazy var descriptionStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [headingLabel, subHeadingLabel]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical return stackView }() private lazy var announcementImageView: UIImageView = { return UIImageView() }() private lazy var mainStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [announcementImageView, descriptionStackView]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .horizontal stackView.alignment = .center stackView.setCustomSpacing(Appearance.imageTextSpacing, after: announcementImageView) return stackView }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(mainStackView) contentView.pinSubviewToSafeArea(mainStackView, insets: Appearance.mainStackViewInsets) NSLayoutConstraint.activate([ announcementImageView.heightAnchor.constraint(equalToConstant: Appearance.announcementImageSize), announcementImageView.widthAnchor.constraint(equalToConstant: Appearance.announcementImageSize) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Configures the labels and image views using the data from a `WordPressKit.Feature` object. /// - Parameter feature: The `feature` containing the information to fill the cell with. func configure(feature: WordPressKit.Feature) { if let iconBase64Components = feature.iconBase64, !iconBase64Components.isEmpty, let base64Image = iconBase64Components.components(separatedBy: ";base64,")[safe: 1], let imageData = Data(base64Encoded: base64Image, options: .ignoreUnknownCharacters), let icon = UIImage(data: imageData) { announcementImageView.image = icon } else if let url = URL(string: feature.iconUrl) { announcementImageView.af_setImage(withURL: url) } headingLabel.text = feature.title subHeadingLabel.text = feature.subtitle } /// Configures the labels and image views using the data passed as parameters. /// - Parameters: /// - title: The title string to use for the heading. /// - description: The description string to use for the sub heading. /// - image: The image to use for the image view. func configure(title: String, description: String, image: UIImage?) { headingLabel.text = title subHeadingLabel.text = description announcementImageView.image = image announcementImageView.isHidden = image == nil } } // MARK: Helpers private extension AnnouncementCell { func makeLabel(font: UIFont, color: UIColor? = nil) -> UILabel { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 label.font = font if let color = color { label.textColor = color } return label } } // MARK: - Appearance private extension AnnouncementCell { enum Appearance { // heading static let headingFont = UIFont(descriptor: UIFontDescriptor.preferredFontDescriptor(withTextStyle: .headline), size: 17) // sub-heading static let subHeadingFont = UIFont(descriptor: UIFontDescriptor.preferredFontDescriptor(withTextStyle: .subheadline), size: 15) // announcement image static let announcementImageSize: CGFloat = 48 // main stack view static let imageTextSpacing: CGFloat = 16 static let mainStackViewInsets = UIEdgeInsets(top: 0, left: 0, bottom: 24, right: 0) } }
gpl-2.0
fc8eb4d5ed63705a819696236eb72574
35.87931
135
0.684198
5.428934
false
false
false
false
xwu/swift
test/SILGen/c_function_pointers.swift
15
4413
// RUN: %target-swift-emit-silgen -verify %s | %FileCheck %s if true { var x = 0 // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}} func local() -> Int { return 0 } func localWithContext() -> Int { return x } func transitiveWithoutContext() -> Int { return local() } // Can't convert a closure with context to a C function pointer let _: @convention(c) () -> Int = { x } // expected-error{{cannot be formed from a closure that captures context}} let _: @convention(c) () -> Int = { [x] in x } // expected-error{{cannot be formed from a closure that captures context}} let _: @convention(c) () -> Int = localWithContext // expected-error{{cannot be formed from a local function that captures context}} let _: @convention(c) () -> Int = local let _: @convention(c) () -> Int = transitiveWithoutContext } class C { static func staticMethod() -> Int { return 0 } class func classMethod() -> Int { return 0 } } class Generic<X : C> { func f<Y : C>(_ y: Y) { let _: @convention(c) () -> Int = { return 0 } let _: @convention(c) () -> Int = { return X.staticMethod() } // expected-error{{cannot be formed from a closure that captures generic parameters}} let _: @convention(c) () -> Int = { return Y.staticMethod() } // expected-error{{cannot be formed from a closure that captures generic parameters}} } } func values(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(c) (Int) -> Int { return arg } // CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers6valuesyS2iXCS2iXCF // CHECK: bb0(%0 : $@convention(c) (Int) -> Int): // CHECK: return %0 : $@convention(c) (Int) -> Int @discardableResult func calls(_ arg: @convention(c) (Int) -> Int, _ x: Int) -> Int { return arg(x) } // CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers5callsyS3iXC_SitF // CHECK: bb0(%0 : $@convention(c) @noescape (Int) -> Int, %1 : $Int): // CHECK: [[RESULT:%.*]] = apply %0(%1) // CHECK: return [[RESULT]] @discardableResult func calls_no_args(_ arg: @convention(c) () -> Int) -> Int { return arg() } func global(_ x: Int) -> Int { return x } func no_args() -> Int { return 42 } // CHECK-LABEL: sil hidden [ossa] @$s19c_function_pointers0B19_to_swift_functionsyySiF func pointers_to_swift_functions(_ x: Int) { // CHECK: bb0([[X:%.*]] : $Int): func local(_ y: Int) -> Int { return y } // CHECK: [[GLOBAL_C:%.*]] = function_ref @$s19c_function_pointers6globalyS2iFTo // CHECK: [[CVT:%.*]] = convert_function [[GLOBAL_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls(global, x) // CHECK: [[LOCAL_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiF5localL_yS2iFTo // CHECK: [[CVT:%.*]] = convert_function [[LOCAL_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls(local, x) // CHECK: [[CLOSURE_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiFS2iXEfU_To // CHECK: [[CVT:%.*]] = convert_function [[CLOSURE_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls({ $0 + 1 }, x) calls_no_args(no_args) // CHECK: [[NO_ARGS_C:%.*]] = function_ref @$s19c_function_pointers7no_argsSiyFTo // CHECK: [[CVT:%.*]] = convert_function [[NO_ARGS_C]] // CHECK: apply {{.*}}([[CVT]]) } func unsupported(_ a: Any) -> Int { return 0 } func pointers_to_bad_swift_functions(_ x: Int) { calls(unsupported, x) // expected-error{{C function pointer signature '(Any) -> Int' is not compatible with expected type '@convention(c) (Int) -> Int'}} } // CHECK-LABEL: sil private [ossa] @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_ : $@convention(thin) () -> () { // CHECK-LABEL: sil private [thunk] [ossa] @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_To : $@convention(c) () -> () { struct StructWithInitializers { let fn1: @convention(c) () -> () = {} init(a: ()) {} init(b: ()) {} } func pointers_to_nested_local_functions_in_generics<T>(x: T) -> Int{ func foo(y: Int) -> Int { return y } return calls(foo, 0) } func capture_list_no_captures(x: Int) { calls({ [x] in $0 }, 0) // expected-warning {{capture 'x' was never used}} } class Selfless { func capture_dynamic_self() { calls_no_args { _ = Self.self; return 0 } // expected-error@-1 {{a C function pointer cannot be formed from a closure that captures dynamic Self type}} } }
apache-2.0
ea399eade92c8627f776b8dad217fa71
37.710526
155
0.622479
3.249632
false
false
false
false
luckytianyiyan/TySimulator
TySimulator/DirectoryWatcher.swift
1
4802
// // DirectoryWatcher.swift // TySimulator // // Created by ty0x2333 on 2017/7/20. // Copyright © 2017年 ty0x2333. All rights reserved. // import Foundation /// https://developer.apple.com/library/content/samplecode/DocInteraction/Listings/ReadMe_txt.html class DirectoryWatcher { var dirFD: Int32 = -1 var kq: Int32 = -1 var dirKQRef: CFFileDescriptor? private var didChange: (() -> Void)? deinit { invalidate() } class func watchFolder(path: String, didChange:(() -> Void)?) -> DirectoryWatcher? { let result: DirectoryWatcher = DirectoryWatcher() result.didChange = didChange if result.startMonitoring(directory: path as NSString) { return result } return nil } func invalidate() { if dirKQRef != nil { CFFileDescriptorInvalidate(dirKQRef) dirKQRef = nil // We don't need to close the kq, CFFileDescriptorInvalidate closed it instead. // Change the value so no one thinks it's still live. kq = -1 } if dirFD != -1 { close(dirFD) dirFD = -1 } } // MARK: Private func kqueueFired() { assert(kq >= 0) var event: kevent = kevent() var timeout: timespec = timespec(tv_sec: 0, tv_nsec: 0) let eventCount = kevent(kq, nil, 0, &event, 1, &timeout) assert((eventCount >= 0) && (eventCount < 2)) didChange?() CFFileDescriptorEnableCallBacks(dirKQRef, kCFFileDescriptorReadCallBack) } func startMonitoring(directory: NSString) -> Bool { // Double initializing is not going to work... if dirKQRef == nil && dirFD == -1 && kq == -1 { // Open the directory we're going to watch dirFD = open(directory.fileSystemRepresentation, O_EVTONLY) if dirFD >= 0 { // Create a kqueue for our event messages... kq = kqueue() if kq >= 0 { var eventToAdd: kevent = kevent() eventToAdd.ident = UInt(dirFD) eventToAdd.filter = Int16(EVFILT_VNODE) eventToAdd.flags = UInt16(EV_ADD | EV_CLEAR) eventToAdd.fflags = UInt32(NOTE_WRITE) eventToAdd.data = 0 eventToAdd.udata = nil let errNum = kevent(kq, &eventToAdd, 1, nil, 0, nil) if errNum == 0 { var context = CFFileDescriptorContext(version: 0, info: UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()), retain: nil, release: nil, copyDescription: nil) let callback: CFFileDescriptorCallBack = { (kqRef: CFFileDescriptor?, callBackTypes: CFOptionFlags, info: UnsafeMutableRawPointer?) in guard let info = info else { return } let obj: DirectoryWatcher = Unmanaged<DirectoryWatcher>.fromOpaque(info).takeUnretainedValue() assert(callBackTypes == kCFFileDescriptorReadCallBack) obj.kqueueFired() } // Passing true in the third argument so CFFileDescriptorInvalidate will close kq. dirKQRef = CFFileDescriptorCreate(nil, kq, true, callback, &context) if dirKQRef != nil { if let rls = CFFileDescriptorCreateRunLoopSource(nil, dirKQRef, 0) { CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, CFRunLoopMode.defaultMode) CFFileDescriptorEnableCallBacks(dirKQRef, kCFFileDescriptorReadCallBack) // If everything worked, return early and bypass shutting things down return true } // Couldn't create a runloop source, invalidate and release the CFFileDescriptorRef CFFileDescriptorInvalidate(dirKQRef) dirKQRef = nil } } // kq is active, but something failed, close the handle... close(kq) kq = -1 } // file handle is open, but something failed, close the handle... close(dirFD) dirFD = -1 } } return false } }
mit
18ba25edec2e35f7551210329874efa1
38.991667
196
0.507606
5.586729
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Athena/Athena_Paginator.swift
1
22854
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension Athena { /// Streams the results of a single query execution specified by QueryExecutionId from the Athena query results location in Amazon S3. For more information, see Query Results in the Amazon Athena User Guide. This request does not execute the query but returns results. Use StartQueryExecution to run a query. To stream query results successfully, the IAM principal with permission to call GetQueryResults also must have permissions to the Amazon S3 GetObject action for the Athena query results location. IAM principals with permission to the Amazon S3 GetObject action for the query results location are able to retrieve query results from Amazon S3 even if permission to the GetQueryResults action is denied. To restrict user or role access, ensure that Amazon S3 permissions to the Athena query location are denied. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getQueryResultsPaginator<Result>( _ input: GetQueryResultsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetQueryResultsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getQueryResults, tokenKey: \GetQueryResultsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getQueryResultsPaginator( _ input: GetQueryResultsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetQueryResultsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getQueryResults, tokenKey: \GetQueryResultsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the data catalogs in the current AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listDataCatalogsPaginator<Result>( _ input: ListDataCatalogsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListDataCatalogsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listDataCatalogs, tokenKey: \ListDataCatalogsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listDataCatalogsPaginator( _ input: ListDataCatalogsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListDataCatalogsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listDataCatalogs, tokenKey: \ListDataCatalogsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the databases in the specified data catalog. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listDatabasesPaginator<Result>( _ input: ListDatabasesInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListDatabasesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listDatabases, tokenKey: \ListDatabasesOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listDatabasesPaginator( _ input: ListDatabasesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListDatabasesOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listDatabases, tokenKey: \ListDatabasesOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provides a list of available query IDs only for queries saved in the specified workgroup. Requires that you have access to the specified workgroup. If a workgroup is not specified, lists the saved queries for the primary workgroup. For code samples using the AWS SDK for Java, see Examples and Code Samples in the Amazon Athena User Guide. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listNamedQueriesPaginator<Result>( _ input: ListNamedQueriesInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListNamedQueriesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listNamedQueries, tokenKey: \ListNamedQueriesOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listNamedQueriesPaginator( _ input: ListNamedQueriesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListNamedQueriesOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listNamedQueries, tokenKey: \ListNamedQueriesOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provides a list of available query execution IDs for the queries in the specified workgroup. If a workgroup is not specified, returns a list of query execution IDs for the primary workgroup. Requires you to have access to the workgroup in which the queries ran. For code samples using the AWS SDK for Java, see Examples and Code Samples in the Amazon Athena User Guide. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listQueryExecutionsPaginator<Result>( _ input: ListQueryExecutionsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListQueryExecutionsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listQueryExecutions, tokenKey: \ListQueryExecutionsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listQueryExecutionsPaginator( _ input: ListQueryExecutionsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListQueryExecutionsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listQueryExecutions, tokenKey: \ListQueryExecutionsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the metadata for the tables in the specified data catalog database. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTableMetadataPaginator<Result>( _ input: ListTableMetadataInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTableMetadataOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTableMetadata, tokenKey: \ListTableMetadataOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTableMetadataPaginator( _ input: ListTableMetadataInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTableMetadataOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTableMetadata, tokenKey: \ListTableMetadataOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the tags associated with an Athena workgroup or data catalog resource. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTagsForResourcePaginator<Result>( _ input: ListTagsForResourceInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTagsForResourceOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTagsForResource, tokenKey: \ListTagsForResourceOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTagsForResourcePaginator( _ input: ListTagsForResourceInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTagsForResourceOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTagsForResource, tokenKey: \ListTagsForResourceOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Lists available workgroups for the account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listWorkGroupsPaginator<Result>( _ input: ListWorkGroupsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListWorkGroupsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listWorkGroups, tokenKey: \ListWorkGroupsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listWorkGroupsPaginator( _ input: ListWorkGroupsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListWorkGroupsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listWorkGroups, tokenKey: \ListWorkGroupsOutput.nextToken, on: eventLoop, onPage: onPage ) } } extension Athena.GetQueryResultsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Athena.GetQueryResultsInput { return .init( maxResults: self.maxResults, nextToken: token, queryExecutionId: self.queryExecutionId ) } } extension Athena.ListDataCatalogsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Athena.ListDataCatalogsInput { return .init( maxResults: self.maxResults, nextToken: token ) } } extension Athena.ListDatabasesInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Athena.ListDatabasesInput { return .init( catalogName: self.catalogName, maxResults: self.maxResults, nextToken: token ) } } extension Athena.ListNamedQueriesInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Athena.ListNamedQueriesInput { return .init( maxResults: self.maxResults, nextToken: token, workGroup: self.workGroup ) } } extension Athena.ListQueryExecutionsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Athena.ListQueryExecutionsInput { return .init( maxResults: self.maxResults, nextToken: token, workGroup: self.workGroup ) } } extension Athena.ListTableMetadataInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Athena.ListTableMetadataInput { return .init( catalogName: self.catalogName, databaseName: self.databaseName, expression: self.expression, maxResults: self.maxResults, nextToken: token ) } } extension Athena.ListTagsForResourceInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Athena.ListTagsForResourceInput { return .init( maxResults: self.maxResults, nextToken: token, resourceARN: self.resourceARN ) } } extension Athena.ListWorkGroupsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Athena.ListWorkGroupsInput { return .init( maxResults: self.maxResults, nextToken: token ) } }
apache-2.0
b0996c9b9355ea928c5b651bb5866da4
43.899804
824
0.649646
5.185841
false
false
false
false
VeinGuo/VGPlayer
VGPlayerExample/VGPlayerExample/DefaultPlayerView/VGMediaViewController.swift
1
3404
// // VGMediaViewController.swift // Example // // Created by Vein on 2017/5/29. // Copyright © 2017年 Vein. All rights reserved. // import UIKit import VGPlayer import SnapKit class VGMediaViewController: UIViewController { var player = VGPlayer() var url1 : URL? override func viewDidLoad() { super.viewDidLoad() self.url1 = URL(fileURLWithPath: Bundle.main.path(forResource: "2", ofType: "mp4")!) let url = URL(string: "http://lxdqncdn.miaopai.com/stream/6IqHc-OnSMBIt-LQjPJjmA__.mp4?ssig=a81b90fdeca58e8ea15c892a49bce53f&time_stamp=1508166491488")! self.player.replaceVideo(url) view.addSubview(self.player.displayView) self.player.play() self.player.backgroundMode = .proceed self.player.delegate = self self.player.displayView.delegate = self self.player.displayView.titleLabel.text = "China NO.1" self.player.displayView.snp.makeConstraints { [weak self] (make) in guard let strongSelf = self else { return } make.top.equalTo(strongSelf.view.snp.top) make.left.equalTo(strongSelf.view.snp.left) make.right.equalTo(strongSelf.view.snp.right) make.height.equalTo(strongSelf.view.snp.width).multipliedBy(3.0/4.0) // you can 9.0/16.0 } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: true) UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: false) self.player.play() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: false) UIApplication.shared.setStatusBarHidden(false, with: .none) self.player.pause() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func changeMedia(_ sender: Any) { player.replaceVideo(url1!) player.play() } } extension VGMediaViewController: VGPlayerDelegate { func vgPlayer(_ player: VGPlayer, playerFailed error: VGPlayerError) { print(error) } func vgPlayer(_ player: VGPlayer, stateDidChange state: VGPlayerState) { print("player State ",state) } func vgPlayer(_ player: VGPlayer, bufferStateDidChange state: VGPlayerBufferstate) { print("buffer State", state) } } extension VGMediaViewController: VGPlayerViewDelegate { func vgPlayerView(_ playerView: VGPlayerView, willFullscreen fullscreen: Bool) { } func vgPlayerView(didTappedClose playerView: VGPlayerView) { if playerView.isFullScreen { playerView.exitFullscreen() } else { self.navigationController?.popViewController(animated: true) } } func vgPlayerView(didDisplayControl playerView: VGPlayerView) { UIApplication.shared.setStatusBarHidden(!playerView.isDisplayControl, with: .fade) } }
mit
0e73acf893d595d121a0be512082014f
33.01
160
0.672743
4.434159
false
false
false
false
gu704823/huobanyun
huobanyun/Spring/SpringLabel.swift
18
2732
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // 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 open class SpringLabel: UILabel, Springable { @IBInspectable public var autostart: Bool = false @IBInspectable public var autohide: Bool = false @IBInspectable public var animation: String = "" @IBInspectable public var force: CGFloat = 1 @IBInspectable public var delay: CGFloat = 0 @IBInspectable public var duration: CGFloat = 0.7 @IBInspectable public var damping: CGFloat = 0.7 @IBInspectable public var velocity: CGFloat = 0.7 @IBInspectable public var repeatCount: Float = 1 @IBInspectable public var x: CGFloat = 0 @IBInspectable public var y: CGFloat = 0 @IBInspectable public var scaleX: CGFloat = 1 @IBInspectable public var scaleY: CGFloat = 1 @IBInspectable public var rotate: CGFloat = 0 @IBInspectable public var curve: String = "" public var opacity: CGFloat = 1 public var animateFrom: Bool = false lazy private var spring : Spring = Spring(self) override open func awakeFromNib() { super.awakeFromNib() self.spring.customAwakeFromNib() } open override func layoutSubviews() { super.layoutSubviews() spring.customLayoutSubviews() } public func animate() { self.spring.animate() } public func animateNext(completion: @escaping () -> ()) { self.spring.animateNext(completion: completion) } public func animateTo() { self.spring.animateTo() } public func animateToNext(completion: @escaping () -> ()) { self.spring.animateToNext(completion: completion) } }
mit
dc8c654373642619fb58a44d3dbee846
36.944444
81
0.711201
4.678082
false
false
false
false
qiuncheng/study-for-swift
YLQRCode/Demo/ViewController.swift
1
2300
// // ViewController.swift // YLQRCode // // Created by yolo on 2017/1/1. // Copyright © 2017年 Qiuncheng. All rights reserved. // import UIKit import YLQRCodeHelper class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. textField.text = "http://weixin.qq.com/r/QkB8ZE7EuxPErQoH9xVQ" imageView.isUserInteractionEnabled = true let long = UILongPressGestureRecognizer(target: self, action: #selector(detecteQRCode(gesture:))) imageView.addGestureRecognizer(long) generateQRCodeButtonClicked(nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func detecteQRCode(gesture: UILongPressGestureRecognizer) { guard gesture.state == .ended else { return } func detect() { guard let image = imageView.image else { return } // YLDetectQRCode.scanQRCodeFromPhotoLibrary(image: image) { (result) in // guard let _result = result else { return } // YLQRScanCommon.playSound() // print(_result) // } } let alertController = UIAlertController(title: "", message: "", preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "识别二维码", style: .default, handler: { (action) in detect() })) alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) } @IBAction func generateQRCodeButtonClicked(_ sender: Any?) { view.endEditing(true) guard let text = textField.text else { return } // YLGenerateQRCode.beginGenerate(text: text) { // guard let image = $0 else { return } // DispatchQueue.main.async { [weak self] in // self?.imageView.image = image // } // } } }
mit
bf5e1f30a63c954e51737db3415f30ee
30.708333
105
0.605782
4.726708
false
false
false
false
cwwise/CWWeChat
CWWeChat/Expand/Tool/CWChatConst.swift
2
1761
// // CWChatConst.swift // CWWeChat // // Created by chenwei on 16/6/22. // Copyright © 2016年 chenwei. All rights reserved. // import Foundation import UIKit import CocoaLumberjack let kScreenSize = UIScreen.main.bounds.size let kScreenWidth = UIScreen.main.bounds.size.width let kScreenHeight = UIScreen.main.bounds.size.height let kScreenScale = UIScreen.main.scale let kNavigationBarHeight:CGFloat = 64 // stolen from Kingfisher: https://github.com/onevcat/Kingfisher/blob/master/Sources/ThreadHelper.swift extension DispatchQueue { // This method will dispatch the `block` to self. // If `self` is the main queue, and current thread is main thread, the block // will be invoked immediately instead of being dispatched. func safeAsync(_ block: @escaping ()->()) { if self === DispatchQueue.main && Thread.isMainThread { block() } else { async { block() } } } } typealias Task = (_ cancel : Bool) -> Void @discardableResult func DispatchQueueDelay(_ time: TimeInterval, task: @escaping ()->()) -> Task? { func dispatch_later(block: @escaping ()->()) { let t = DispatchTime.now() + time DispatchQueue.main.asyncAfter(deadline: t, execute: block) } var closure: (()->Void)? = task var result: Task? let delayedClosure: Task = { cancel in if let internalClosure = closure { if (cancel == false) { DispatchQueue.main.async(execute: internalClosure) } } closure = nil result = nil } result = delayedClosure dispatch_later { if let delayedClosure = result { delayedClosure(false) } } return result }
mit
d1bbc099fcba4be3074e9d9e127d9fc5
25.238806
103
0.627418
4.428212
false
false
false
false
steelwheels/KiwiScript
KiwiLibrary/Source/Data/KLEnum.swift
1
950
/** * @file KLEnum.swift * @brief Extend CNEnum class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ import CoconutData import KiwiEngine import JavaScriptCore import Foundation public extension CNEnum { static func isEnum(scriptValue val: JSValue) -> Bool { if let dict = val.toDictionary() as? Dictionary<String, Any> { if let _ = dict["type"] as? NSString, let _ = dict["value"] as? NSNumber { return true } else { return false } } else { return false } } static func fromJSValue(scriptValue val: JSValue) -> CNEnum? { if let dict = val.toDictionary() as? Dictionary<String, Any> { if let typestr = dict["type"] as? String, let membstr = dict["member"] as? String { return CNEnum.fromValue(typeName: typestr, memberName: membstr) } } return nil } func toJSValue(context ctxt: KEContext) -> JSValue { return JSValue(int32: Int32(self.value), in: ctxt) } }
lgpl-2.1
adfbd5f248fef76f8dbf27db15504197
21.619048
67
0.664211
3.275862
false
false
false
false
zbw209/-
StudyNotes/StudyNotes/知识点/控件封装/tableViewCell插入优化/OptimizeTableViewCellAnimateVC.swift
1
1582
// // OptimizeTableViewCellAnimateVC.swift // StudyNotes // // Created by zhoubiwen on 2018/11/6. // Copyright © 2018年 zhou. All rights reserved. // import UIKit class OptimizeTableViewCellAnimateVC: UIViewController { var tableView : UITableView? var arr : Array<String>? override func viewDidLoad() { super.viewDidLoad() // setupTableView() arr?.append("123") arr?.append("123") arr?.append("123") arr?.append("123") arr?.append("123") } } extension OptimizeTableViewCellAnimateVC { func setupTableView() { self.tableView = UITableView() self.tableView!.delegate = self self.tableView!.dataSource = self self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell") self.tableView?.frame = CGRect(origin: CGPoint.zero, size: self.view.bounds.size) self.view.addSubview(self.tableView!) } func insertEvent() { } } extension OptimizeTableViewCellAnimateVC : UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arr?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) cell.textLabel?.text = "indexPath = \(indexPath)" return cell } }
mit
2a5d407969c13c832e2fddac7cdc0bda
24.467742
100
0.633946
4.903727
false
false
false
false
riana/NickelSwift
NickelSwift/NickelWebViewController.swift
1
8054
// // PolymerWebView.swift // PolymerIos // // Created by Riana Ralambomanana on 17/12/2015. // Copyright © 2016 Riana.io. All rights reserved. // import Foundation import WebKit struct TransferData { var timeStamp:Int = 0 var operation:String = "NOOP" var callback:Bool = false var data:[NSObject:AnyObject]? } public typealias BridgedMethod = (String, [NSObject:AnyObject]) -> [NSObject:AnyObject]? public protocol NickelFeature { func setupFeature(nickelViewController:NickelWebViewController) } public class NickelWebViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{ var myWebView:WKWebView?; var timer:NSTimer? var elapsedTime:Int = 0 let imagePicker = UIImagePickerController() var bridgedMethods = [String: BridgedMethod]() var features = [NickelFeature]() public override func viewDidLoad() { super.viewDidLoad() let theConfiguration = WKWebViewConfiguration() theConfiguration.userContentController.addScriptMessageHandler(self, name: "native") theConfiguration.allowsInlineMediaPlayback = true myWebView = WKWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height), configuration: theConfiguration) myWebView?.scrollView.bounces = false myWebView?.navigationDelegate = self self.view.addSubview(myWebView!) } public func setMainPage(name:String){ let localUrl = NSBundle.mainBundle().URLForResource(name, withExtension: "html"); // let requestObj = NSURLRequest(URL: localUrl!); // myWebView!.loadRequest(requestObj); myWebView!.loadFileURL(localUrl!, allowingReadAccessToURL: localUrl!) } public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { let stringData = message.body as! String; let receivedData = stringData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! do { let jsonData = try NSJSONSerialization.JSONObjectWithData(receivedData, options: .AllowFragments) as! [NSObject: AnyObject] var transferData = TransferData() if let timeStamp = jsonData["timestamp"] as? Int { transferData.timeStamp = timeStamp } if let operation = jsonData["operation"] as? String { transferData.operation = operation } if let callback = jsonData["callback"] as? Bool { transferData.callback = callback } if let data = jsonData["data"] as? [NSObject:AnyObject]{ transferData.data = data } // print("\(transferData)") if let bridgedMethod = bridgedMethods[transferData.operation] { if let result = bridgedMethod(transferData.operation, transferData.data!) { if(transferData.callback){ sendtoView("\(transferData.operation)-\(transferData.timeStamp)", data:result); } } }else { print("Bridged operation not found : \(transferData.operation)") } }catch{ print("error serializing JSON: \(error)") } } public func sendtoView(operation:String, data:AnyObject){ let jsonProperties:AnyObject = ["operation": operation, "data": data] do { let jsonData = try NSJSONSerialization.dataWithJSONObject(jsonProperties,options:NSJSONWritingOptions()) let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String let callbackString = "window.NickelBridge.handleMessage" let jsFunction = "(\(callbackString)(\(jsonString)))"; // print(jsFunction) myWebView!.evaluateJavaScript(jsFunction) { (JSReturnValue:AnyObject?, error:NSError?)-> Void in if let errorDescription = error?.description{ print("returned value: \(errorDescription)") } } } catch let error { print("error converting to json: \(error)") } } public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { // JS function Initialized sendtoView("Initialized", data:["status" : "ok"]) doRegisterFeatures() registerBridgedFunction("pickImage", bridgedMethod: self.pickImage) registerBridgedFunction("startTimer", bridgedMethod: self.startTimer) registerBridgedFunction("stopTimer", bridgedMethod: self.stopTimer) features.append(StorageFeature()) features.append(LocalNotificationFeature()) features.append(AwakeFeature()) features.append(TTSFeature()) features.append(AudioFeature()) features.append(JSONFeature()) features.append(i18nFeature()) for feature in features { feature.setupFeature(self) } } public func registerBridgedFunction(operationId:String, bridgedMethod:BridgedMethod){ bridgedMethods[operationId] = bridgedMethod } public func doRegisterFeatures() { } /** * Select image feature **/ func pickImage(operation:String, content:[NSObject:AnyObject]) -> [NSObject:AnyObject]?{ imagePicker.delegate = self imagePicker.allowsEditing = false imagePicker.sourceType = .PhotoLibrary presentViewController(imagePicker, animated: true, completion: nil) return [NSObject:AnyObject]() } public func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { let imageResized = resizeImage(pickedImage, newWidth: 100) let imageData = UIImagePNGRepresentation(imageResized) let base64String = imageData!.base64EncodedStringWithOptions(.EncodingEndLineWithLineFeed) let imagesString = "data:image/png;base64,\(base64String)" sendtoView("imagePicked", data:["image" :imagesString ]) } dismissViewControllerAnimated(true, completion: nil) } func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage { let scale = newWidth / image.size.width let newHeight = image.size.height * scale UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight)) image.drawInRect(CGRectMake(0, 0, newWidth, newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } /** * END Select image feature **/ /** * Native Timer feature **/ func startTimer(operation:String, content:[NSObject:AnyObject]) -> [NSObject:AnyObject]?{ self.elapsedTime = 0 timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timerTick"), userInfo: nil, repeats: true) return [NSObject:AnyObject]() } func stopTimer(operation:String, content:[NSObject:AnyObject]) -> [NSObject:AnyObject]?{ timer?.invalidate() sendtoView("timerComplete", data:["elapsedTime" : self.elapsedTime]); return [NSObject:AnyObject]() } func timerTick(){ self.elapsedTime++; sendtoView("timeStep", data:["elapsedTime" : self.elapsedTime]); } /** * END Native Timer feature **/ }
mit
d60ad306b947817a36c14aa3d8cdf651
34.320175
166
0.627592
5.659171
false
false
false
false
gerryisaac/iPhone-CTA-Bus-Tracker-App
Bus Tracker/DirectionsViewController.swift
1
9814
// // DirectionsViewController.swift // Bus Tracker // // Created by Gerard Isaac on 10/30/14. // Copyright (c) 2014 Gerard Isaac. All rights reserved. // import UIKit class DirectionsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let cellIdentifier = "cellIdentifier" var patternID:NSString? = NSString() var routeNumber:NSString = NSString() var directionsTable:UITableView = UITableView(frame: CGRectMake(0, 64, screenDimensions.screenWidth, screenDimensions.screenHeight - 64)) //Directions Table Data Variables var directions: NSArray = [] var directionsData: NSMutableArray = [] var directionsCount: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //println("Get Directions") self.view.backgroundColor = UIColor.blueColor() //Create Background Image let bgImage = UIImage(named:"bg-DirectionsI5.png") var bgImageView = UIImageView(frame: CGRectMake(0, 0, screenDimensions.screenWidth, screenDimensions.screenHeight)) bgImageView.image = bgImage self.view.addSubview(bgImageView) retrieveDirections() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func retrieveDirections() { //Create Spinner var spinner:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White) spinner.frame = CGRectMake(screenDimensions.screenWidth/2 - 25, screenDimensions.screenHeight/2 - 25, 50, 50); spinner.transform = CGAffineTransformMakeScale(1.5, 1.5); //spinner.backgroundColor = [UIColor blackColor]; self.view.addSubview(spinner); spinner.startAnimating() //Load Bus Tracker Data let feedURL:NSString = "http://www.ctabustracker.com/bustime/api/v1/getpatterns?key=\(yourCTAkey.keyValue)&rt=\(routeNumber)" //println("Directions URL is \(feedURL)") let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFHTTPResponseSerializer() let contentType:NSSet = NSSet(object: "text/xml") manager.responseSerializer.acceptableContentTypes = contentType manager.GET(feedURL, parameters: nil, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in //println("Success") var responseData:NSData = responseObject as NSData //var responseString = NSString(data: responseData, encoding:NSASCIIStringEncoding) //println(responseString) var rxml:RXMLElement = RXMLElement.elementFromXMLData(responseData) as RXMLElement //self.directions = rxml.children("dir") self.directions = rxml.children("ptr") self.directionsData.addObjectsFromArray(self.directions) self.directionsCount = self.directions.count if self.directionsCount == 0 { //println("No Data") var noDataLabel:UILabel = UILabel(frame: CGRectMake( 0, 200, screenDimensions.screenWidth, 75)) noDataLabel.font = UIFont(name:"Gotham-Bold", size:30.0) noDataLabel.textColor = self.uicolorFromHex(0xfffee8) noDataLabel.textAlignment = NSTextAlignment.Center noDataLabel.numberOfLines = 0 noDataLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping noDataLabel.text = "No Data Available" self.view.addSubview(noDataLabel) } else { var i:Int? = 0 for direction in self.directions { i = i! + 1 } //println(i!) //Create Direction Entries self.directionsTable.backgroundColor = UIColor.clearColor() self.directionsTable.dataSource = self self.directionsTable.delegate = self self.directionsTable.separatorInset = UIEdgeInsetsZero self.directionsTable.layoutMargins = UIEdgeInsetsZero self.directionsTable.bounces = true // Register the UITableViewCell class with the tableView self.directionsTable.registerClass(DirectionsCell.self, forCellReuseIdentifier: self.cellIdentifier) //self.patternTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier) //Add the Table View self.view.addSubview(self.directionsTable) } spinner.stopAnimating() }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in var alertView = UIAlertView(title: "Error Retrieving Data", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK") alertView.show() println(error) }) } //Table View Configuration // Table Delegates and Data Source // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, shouldIndentWhileEditing indexPath: NSIndexPath) -> Bool { return false } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return self.directionsCount } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var appElement:RXMLElement = directionsData.objectAtIndex(indexPath.row) as RXMLElement var direction:NSString? = appElement.child("rtdir").text self.patternID = appElement.child("pid").text var subPoints: NSArray = [] subPoints = appElement.children("pt") var subPointsData: NSMutableArray = [] subPointsData.addObjectsFromArray(subPoints) var lastElement:RXMLElement = subPointsData.lastObject as RXMLElement var lastStopName:NSString? = lastElement.child("stpnm").text //println(lastElement) var cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) as DirectionsCell if direction == nil { cell.accessoryType = UITableViewCellAccessoryType.None cell.cellDirectionLabel.text = "No Stops Available" } else { cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.cellDirectionLabel.text = direction cell.cellDestinationLabel.text = lastStopName?.uppercaseString cell.cellpIDLabel.text = self.patternID } cell.tintColor = UIColor.whiteColor() return cell } //Remove Table Insets and Margins func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if cell.respondsToSelector("setSeparatorInset:") { cell.separatorInset.left = CGFloat(0.0) } if tableView.respondsToSelector("setLayoutMargins:") { tableView.layoutMargins = UIEdgeInsetsZero } if cell.respondsToSelector("setLayoutMargins:") { cell.layoutMargins.left = CGFloat(0.0) } } func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat { tableView.separatorColor = UIColor.whiteColor() return 100 } func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } // UITableViewDelegate methods //Double check didSelectRowAtIndexPath VS didDeselectRowAtIndexPath func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var cellDirection: NSString? if let thisCell:DirectionsCell = tableView.cellForRowAtIndexPath(indexPath) as? DirectionsCell { self.patternID = thisCell.cellpIDLabel.text cellDirection = thisCell.cellDirectionLabel.text } var displayPatterns:patternDisplayViewController = patternDisplayViewController() displayPatterns.pID = self.patternID! displayPatterns.patternRequestNumber = self.routeNumber displayPatterns.title = NSString(string:"\(self.patternID!) \(cellDirection!)") self.navigationController?.pushViewController(displayPatterns, animated: true) self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() tableView.deselectRowAtIndexPath(indexPath, animated: false) } //Hex Color Values Function func uicolorFromHex(rgbValue:UInt32)->UIColor{ let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0 let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0 let blue = CGFloat(rgbValue & 0xFF)/256.0 return UIColor(red:red, green:green, blue:blue, alpha:1.0) } }
mit
b71e0d7bed32495ee7bbc7a4e553c855
40.062762
152
0.621867
5.912048
false
false
false
false
jackywpy/AudioKit
Templates/File Templates/AudioKit/Swift AudioKit Instrument.xctemplate/___FILEBASENAME___.swift
16
1143
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // class ___FILEBASENAME___: AKInstrument { // Instrument Properties var pan = AKInstrumentProperty(value: 0.0, minimum: 0.0, maximum: 1.0) // Auxilliary Outputs (if any) var auxilliaryOutput = AKAudio() override init() { super.init() // Instrument Properties // Note Properties let note = ___FILEBASENAME___Note() // Instrument Definition let oscillator = AKFMOscillator(); oscillator.baseFrequency = note.frequency; oscillator.amplitude = note.amplitude; let panner = AKPanner(audioSource: oscillator, pan: pan) auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:panner) } } class ___FILEBASENAME___Note: AKNote { // Note Properties var frequency = AKNoteProperty(minimum: 440, maximum: 880) var amplitude = AKNoteProperty(minimum: 0, maximum: 1) override init() { super.init() addProperty(frequency) addProperty(amplitude) } }
mit
f6d45f90c06725f6e5a1d5d76cbd3928
22.8125
75
0.615923
4.62753
false
false
false
false
lyragosa/tipcalc
TipCalc/ViewController.swift
1
2262
// // ViewController.swift // TipCalc // // Created by Lyragosa on 15/10/19. // Copyright © 2015年 Lyragosa. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var totalTextField : UITextField! @IBOutlet var taxPctSlider : UISlider! @IBOutlet var taxPctLabel : UILabel! @IBOutlet var resultsTextView : UITextView! let tipCalc = TipCalculatorModel(total:200,taxPct:0.06) @IBAction func calculateTapped(sender : AnyObject) { saveData(); let possibleTips = tipCalc.returnPossibleTips() var results = "" var keys = Array(possibleTips.keys) keys.sortInPlace(); for tipPct in keys { let tipValue = possibleTips[tipPct]! let predoValue = String(format:"%.2f",tipValue) results += "\(tipPct)%: \(predoValue)\n" } /* //old: for (tipPct, tipValue) in possibleTips { let predoValue = String(format:"%.2f",tipValue) results += "\(tipPct)%: \(predoValue)\n" }*/ resultsTextView.text = results } func test123(a:Int,b:Int) -> Int { return Int(a+b) } @IBAction func taxPercentageChanged(sender : AnyObject) { saveData(); tipCalc.taxPct = Double(taxPctSlider.value) refreshUI() } @IBAction func viewTapped(sender : AnyObject) { totalTextField.resignFirstResponder(); } @IBAction func baseTotalInputed(sender : AnyObject) { saveData(); } func saveData() { tipCalc.total = Double( (totalTextField.text! as NSString).doubleValue ) } func refreshUI() { totalTextField.text = String(tipCalc.total) taxPctSlider.value = Float(tipCalc.taxPct) taxPctLabel.text = "Tax (\(Int(taxPctSlider.value * 100.0))%)" resultsTextView.text = ""; } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. refreshUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
83848ae5585b13fe50c79f41669b53b2
25.576471
80
0.598938
4.464427
false
false
false
false
wnagrodzki/DragGestureRecognizer
DragGestureRecognizer/DragGestureRecognizer.swift
1
3273
// // DragGestureRecognizer.swift // DragGestureRecognizer // // Created by Wojciech Nagrodzki on 01/09/16. // Copyright © 2016 Wojciech Nagrodzki. All rights reserved. // import UIKit import UIKit.UIGestureRecognizerSubclass /// `DragGestureRecognizer` is a subclass of `UILongPressGestureRecognizer` that allows for tracking translation similarly to `UIPanGestureRecognizer`. class DragGestureRecognizer: UILongPressGestureRecognizer { private var initialTouchLocationInScreenFixedCoordinateSpace: CGPoint? private var initialTouchLocationsInViews = [UIView: CGPoint]() /// The total translation of the drag gesture in the coordinate system of the specified view. /// - parameters: /// - view: The view in whose coordinate system the translation of the drag gesture should be computed. Pass `nil` to indicate window. func translation(in view: UIView?) -> CGPoint { // not attached to a view or outside window guard let window = self.view?.window else { return CGPoint() } // gesture not in progress guard let initialTouchLocationInScreenFixedCoordinateSpace = initialTouchLocationInScreenFixedCoordinateSpace else { return CGPoint() } let initialLocation: CGPoint let currentLocation: CGPoint if let view = view { initialLocation = initialTouchLocationsInViews[view] ?? window.screen.fixedCoordinateSpace.convert(initialTouchLocationInScreenFixedCoordinateSpace, to: view) currentLocation = location(in: view) } else { initialLocation = initialTouchLocationInScreenFixedCoordinateSpace currentLocation = location(in: nil) } return CGPoint(x: currentLocation.x - initialLocation.x, y: currentLocation.y - initialLocation.y) } /// Sets the translation value in the coordinate system of the specified view. /// - parameters: /// - translation: A point that identifies the new translation value. /// - view: A view in whose coordinate system the translation is to occur. Pass `nil` to indicate window. func setTranslation(_ translation: CGPoint, in view: UIView?) { // not attached to a view or outside window guard let window = self.view?.window else { return } // gesture not in progress guard let _ = initialTouchLocationInScreenFixedCoordinateSpace else { return } let inView = view ?? window let currentLocation = location(in: inView) let initialLocation = CGPoint(x: currentLocation.x - translation.x, y: currentLocation.y - translation.y) initialTouchLocationsInViews[inView] = initialLocation } override var state: UIGestureRecognizer.State { didSet { switch state { case .began: initialTouchLocationInScreenFixedCoordinateSpace = location(in: nil) case .ended, .cancelled, .failed: initialTouchLocationInScreenFixedCoordinateSpace = nil initialTouchLocationsInViews = [:] case .possible, .changed: break } } } }
mit
3c9405e5baf4b815187b8731f1080272
40.948718
170
0.662286
5.884892
false
false
false
false
contentful-labs/markdown-example-ios
Code/MDEmbedlyViewController.swift
1
1153
// // MDEmbedlyViewController.swift // Markdown // // Created by Boris Bügling on 24/12/15. // Copyright © 2015 Contentful GmbH. All rights reserved. // import UIKit class MDEmbedlyViewController: MDWebViewController { let embedlyCode = "<script>(function(w, d){var id='embedly-platform', n = 'script';if (!d.getElementById(id)){ w.embedly = w.embedly || function() {(w.embedly.q = w.embedly.q || []).push(arguments);}; var e = d.createElement(n); e.id = id; e.async=1; e.src = ('https:' === document.location.protocol ? 'https' : 'http') + '://cdn.embedly.com/widgets/platform.js'; var s = d.getElementsByTagName(n)[0]; s.parentNode.insertBefore(e, s); } })(window, document); </script>" convenience init() { self.init(nibName: nil, bundle: nil) self.entryId = "3qhObH1ZPyG6uCkqwyiiCG" self.tabBarItem = UITabBarItem(title: "Embedly", image: UIImage(named: "webView"), tag: 0) } override func convertMarkdownToHTML(_ markdown: String) throws -> String { let html = try super.convertMarkdownToHTML(markdown) return "<html><head>\(embedlyCode)</head><body>\(html)</body></html>" } }
mit
48856d7b724b6580b92b46ab25c060af
45.04
473
0.662033
3.405325
false
false
false
false
soapyigu/LeetCode_Swift
Array/SmallestRange.swift
1
1572
/** * Question Link: https://leetcode.com/problems/smallest-range/ * Primary idea: Merge K lists + Minimum Window Substring * Time Complexity: O(nm), Space Complexity: O(nm) * */ class SmallestRange { func smallestRange(_ nums: [[Int]]) -> [Int] { let mergedNums = merge(nums) var left = 0, diff = Int.max, res = [Int]() var numsIndexFreq = Dictionary((0..<nums.count).map { ($0, 0) }, uniquingKeysWith: +), count = 0 for (right, numIndex) in mergedNums.enumerated() { if numsIndexFreq[numIndex.1]! == 0 { count += 1 } numsIndexFreq[numIndex.1]! += 1 while count == nums.count { if diff > mergedNums[right].0 - mergedNums[left].0 { diff = mergedNums[right].0 - mergedNums[left].0 res = [mergedNums[left], mergedNums[right]].map { $0.0 } } if numsIndexFreq[mergedNums[left].1]! == 1 { count -= 1 } numsIndexFreq[mergedNums[left].1]! -= 1 left += 1 } } return res } fileprivate func merge(_ nums: [[Int]]) -> [(Int, Int)] { var res = [(Int, Int)]() for (numsIndex, nums) in nums.enumerated() { for num in nums { res.append((num, numsIndex)) } } return res.sorted { return $0.0 < $1.0 } } }
mit
f7503d128977a7373ff56401e4983d1a
29.843137
104
0.456107
4.440678
false
false
false
false
davidkobilnyk/BNRGuideSolutionsInSwift
06-ViewControllers/HypnoNerd/HypnoNerd/AppDelegate.swift
1
3207
// // AppDelegate.swift // HypnoNerd // // Created by David Kobilnyk on 7/7/14. // Copyright (c) 2014 David Kobilnyk. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. // In iOS8, you have to get permission from the user for notifications before they're allowed. // Without it, alerts won't work, and you'll get a console warning about // "haven't received permission from the user to display alerts" application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil )) let hvc = BNRHypnosisViewController() // Look in the appBundle for the file BNRReminderViewController.xib let rvc = BNRReminderViewController() let tabBarController = UITabBarController() tabBarController.viewControllers = [hvc, rvc] self.window!.rootViewController = tabBarController self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() 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:. } }
mit
e1fb39ac4b8aef5a9b52bad5cd2d225b
46.865672
285
0.722482
5.706406
false
false
false
false
benkraus/Operations
Operations/UIUserNotifications+Operations.swift
1
2662
/* The MIT License (MIT) Original work Copyright (c) 2015 pluralsight Modified work Copyright 2016 Ben Kraus 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. */ #if os(iOS) import UIKit extension UIUserNotificationSettings { /// Check to see if one Settings object is a superset of another Settings object. func contains(settings: UIUserNotificationSettings) -> Bool { // our types must contain all of the other types if !types.contains(settings.types) { return false } let otherCategories = settings.categories ?? [] let myCategories = categories ?? [] return myCategories.isSupersetOf(otherCategories) } /** Merge two Settings objects together. `UIUserNotificationCategories` with the same identifier are considered equal. */ func settingsByMerging(settings: UIUserNotificationSettings) -> UIUserNotificationSettings { let mergedTypes = types.union(settings.types) let myCategories = categories ?? [] var existingCategoriesByIdentifier = Dictionary(sequence: myCategories) { $0.identifier } let newCategories = settings.categories ?? [] let newCategoriesByIdentifier = Dictionary(sequence: newCategories) { $0.identifier } for (newIdentifier, newCategory) in newCategoriesByIdentifier { existingCategoriesByIdentifier[newIdentifier] = newCategory } let mergedCategories = Set(existingCategoriesByIdentifier.values) return UIUserNotificationSettings(forTypes: mergedTypes, categories: mergedCategories) } } #endif
mit
ce50da2149e2bde4efce55c48e90760a
39.333333
97
0.723892
5.399594
false
false
false
false
zhihuilong/ZHTabBarController
ZHTabBarController/Classes/ZHAddTabBar.swift
1
1563
// // ZHAddTabBar.swift // ZHTabBarController // // Created by Sunny on 15/10/4. // Copyright © 2015年 sunny. All rights reserved. // import UIKit public final class ZHAddTabBar: ZHTabBar { fileprivate let centerBtn = UIImageView() var btnClickBlock:(() -> Void)? func didTap() { if let tap = btnClickBlock { tap() } else { print("!!!You must assign to btnClickBlock") } } override func adjustItemFrame() { let width = frame.height centerBtn.isUserInteractionEnabled = true centerBtn.frame = CGRect(origin: CGPoint(x: (SCREEN_WIDTH-width)/2, y: 0), size: CGSize(width: width, height: width)) centerBtn.backgroundColor = UIColor.clear centerBtn.contentMode = UIViewContentMode.scaleAspectFit centerBtn.image = UIImage(named: "centerBtn") centerBtn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ZHAddTabBar.didTap))) addSubview(centerBtn) let count = subviews.count - 1 let itemWidth = frame.size.width / CGFloat(count+1) let itemHeight = frame.size.height for i in 0..<count { let item = subviews[i] as! ZHBarItem item.tag = i if i < 2 { item.frame = CGRect(x: CGFloat(i) * itemWidth, y: 0, width: itemWidth, height: itemHeight) } else { item.frame = CGRect(x: CGFloat(i+1) * itemWidth, y: 0, width: itemWidth, height: itemHeight) } } } }
mit
29f9d0af6fc00460f4e69443c8e3e377
32.913043
125
0.600641
4.297521
false
false
false
false
wuhduhren/Mr-Ride-iOS
Pods/SideMenu/Pod/Classes/SideMenuTransition.swift
1
22749
// // SideMenuTransition.swift // Pods // // Created by Jon Kent on 1/14/16. // // import UIKit internal class SideMenuTransition: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { private var presenting = false private var interactive = false private static weak var originalSuperview: UIView? internal static let singleton = SideMenuTransition() internal static var presentDirection: UIRectEdge = .Left; internal static weak var tapView: UIView! internal static weak var statusBarView: UIView? // prevent instantiation private override init() {} private class var viewControllerForPresentedMenu: UIViewController? { get { return SideMenuManager.menuLeftNavigationController?.presentingViewController != nil ? SideMenuManager.menuLeftNavigationController?.presentingViewController : SideMenuManager.menuRightNavigationController?.presentingViewController } } private class var visibleViewController: UIViewController? { get { return getVisibleViewControllerFromViewController(UIApplication.sharedApplication().keyWindow?.rootViewController) } } private class func getVisibleViewControllerFromViewController(viewController: UIViewController?) -> UIViewController? { if let navigationController = viewController as? UINavigationController { return getVisibleViewControllerFromViewController(navigationController.visibleViewController) } else if let tabBarController = viewController as? UITabBarController { return getVisibleViewControllerFromViewController(tabBarController.selectedViewController) } else if let presentedViewController = viewController?.presentedViewController { return getVisibleViewControllerFromViewController(presentedViewController) } return viewController } class func handlePresentMenuPan(pan: UIPanGestureRecognizer) { // how much distance have we panned in reference to the parent view? if let view = viewControllerForPresentedMenu != nil ? viewControllerForPresentedMenu?.view : pan.view { let transform = view.transform view.transform = CGAffineTransformIdentity let translation = pan.translationInView(pan.view!) view.transform = transform // do some math to translate this to a percentage based value if !singleton.interactive { if translation.x == 0 { return // not sure which way the user is swiping yet, so do nothing } if let edge = pan as? UIScreenEdgePanGestureRecognizer { SideMenuTransition.presentDirection = edge.edges == .Left ? .Left : .Right } else { SideMenuTransition.presentDirection = translation.x > 0 ? .Left : .Right } if let menuViewController: UINavigationController = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController { singleton.interactive = true if let visibleViewController = visibleViewController { visibleViewController.presentViewController(menuViewController, animated: true, completion: nil) } } } let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1 let distance = translation.x / SideMenuManager.menuWidth // now lets deal with different states that the gesture recognizer sends switch (pan.state) { case .Began, .Changed: if pan is UIScreenEdgePanGestureRecognizer { singleton.updateInteractiveTransition(min(distance * direction, 1)) } else if distance > 0 && SideMenuTransition.presentDirection == .Right && SideMenuManager.menuLeftNavigationController != nil { SideMenuTransition.presentDirection = .Left singleton.cancelInteractiveTransition() viewControllerForPresentedMenu?.presentViewController(SideMenuManager.menuLeftNavigationController!, animated: true, completion: nil) } else if distance < 0 && SideMenuTransition.presentDirection == .Left && SideMenuManager.menuRightNavigationController != nil { SideMenuTransition.presentDirection = .Right singleton.cancelInteractiveTransition() viewControllerForPresentedMenu?.presentViewController(SideMenuManager.menuRightNavigationController!, animated: true, completion: nil) } else { singleton.updateInteractiveTransition(min(distance * direction, 1)) } default: singleton.interactive = false view.transform = CGAffineTransformIdentity let velocity = pan.velocityInView(pan.view!).x * direction view.transform = transform if velocity >= 100 || velocity >= -50 && abs(distance) >= 0.5 { singleton.finishInteractiveTransition() } else { singleton.cancelInteractiveTransition() } } } } class func handleHideMenuPan(pan: UIPanGestureRecognizer) { let translation = pan.translationInView(pan.view!) let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? -1 : 1 let distance = translation.x / SideMenuManager.menuWidth * direction switch (pan.state) { case .Began: singleton.interactive = true viewControllerForPresentedMenu?.dismissViewControllerAnimated(true, completion: nil) case .Changed: singleton.updateInteractiveTransition(max(min(distance, 1), 0)) default: singleton.interactive = false let velocity = pan.velocityInView(pan.view!).x * direction if velocity >= 100 || velocity >= -50 && distance >= 0.5 { singleton.finishInteractiveTransition() } else { singleton.cancelInteractiveTransition() } } } class func handleHideMenuTap(tap: UITapGestureRecognizer) { viewControllerForPresentedMenu?.dismissViewControllerAnimated(true, completion: nil) } internal class func hideMenuStart() { NSNotificationCenter.defaultCenter().removeObserver(SideMenuTransition.singleton) let mainViewController = SideMenuTransition.viewControllerForPresentedMenu! let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController!.view : SideMenuManager.menuRightNavigationController!.view menuView.transform = CGAffineTransformIdentity mainViewController.view.transform = CGAffineTransformIdentity mainViewController.view.alpha = 1 SideMenuTransition.tapView.frame = CGRectMake(0, 0, mainViewController.view.frame.width, mainViewController.view.frame.height) menuView.frame.origin.y = 0 menuView.frame.size.width = SideMenuManager.menuWidth menuView.frame.size.height = mainViewController.view.frame.height SideMenuTransition.statusBarView?.frame = UIApplication.sharedApplication().statusBarFrame SideMenuTransition.statusBarView?.alpha = 0 switch SideMenuManager.menuPresentMode { case .ViewSlideOut: menuView.alpha = 1 - SideMenuManager.menuAnimationFadeStrength menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth mainViewController.view.frame.origin.x = 0 menuView.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor) case .ViewSlideInOut: menuView.alpha = 1 menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? -menuView.frame.width : mainViewController.view.frame.width mainViewController.view.frame.origin.x = 0 case .MenuSlideIn: menuView.alpha = 1 menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? -menuView.frame.width : mainViewController.view.frame.width case .MenuDissolveIn: menuView.alpha = 0 menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth mainViewController.view.frame.origin.x = 0 } } internal class func hideMenuComplete() { let mainViewController = SideMenuTransition.viewControllerForPresentedMenu! let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController!.view : SideMenuManager.menuRightNavigationController!.view SideMenuTransition.tapView.removeFromSuperview() SideMenuTransition.statusBarView?.removeFromSuperview() mainViewController.view.motionEffects.removeAll() mainViewController.view.layer.shadowOpacity = 0 menuView.layer.shadowOpacity = 0 if let topNavigationController = mainViewController as? UINavigationController { topNavigationController.interactivePopGestureRecognizer!.enabled = true } originalSuperview?.addSubview(mainViewController.view) } internal class func presentMenuStart(forSize size: CGSize = UIScreen.mainScreen().bounds.size) { let mainViewController = SideMenuTransition.viewControllerForPresentedMenu! if let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view { menuView.transform = CGAffineTransformIdentity mainViewController.view.transform = CGAffineTransformIdentity menuView.frame.size.width = SideMenuManager.menuWidth menuView.frame.size.height = size.height menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : size.width - SideMenuManager.menuWidth SideMenuTransition.statusBarView?.frame = UIApplication.sharedApplication().statusBarFrame SideMenuTransition.statusBarView?.alpha = 1 switch SideMenuManager.menuPresentMode { case .ViewSlideOut: menuView.alpha = 1 let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1 mainViewController.view.frame.origin.x = direction * (menuView.frame.width) mainViewController.view.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor mainViewController.view.layer.shadowRadius = SideMenuManager.menuShadowRadius mainViewController.view.layer.shadowOpacity = SideMenuManager.menuShadowOpacity mainViewController.view.layer.shadowOffset = CGSizeMake(0, 0) case .ViewSlideInOut: menuView.alpha = 1 menuView.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity menuView.layer.shadowOffset = CGSizeMake(0, 0) let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1 mainViewController.view.frame.origin.x = direction * (menuView.frame.width) mainViewController.view.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor) mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength case .MenuSlideIn, .MenuDissolveIn: menuView.alpha = 1 menuView.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity menuView.layer.shadowOffset = CGSizeMake(0, 0) mainViewController.view.frame = CGRectMake(0, 0, size.width, size.height) mainViewController.view.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor) mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength } } } internal class func presentMenuComplete() { NSNotificationCenter.defaultCenter().addObserver(SideMenuTransition.singleton, selector:#selector(SideMenuTransition.applicationDidEnterBackgroundNotification), name: UIApplicationDidEnterBackgroundNotification, object: nil) let mainViewController = SideMenuTransition.viewControllerForPresentedMenu! switch SideMenuManager.menuPresentMode { case .MenuSlideIn, .MenuDissolveIn: if SideMenuManager.menuParallaxStrength != 0 { let horizontal = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis) horizontal.minimumRelativeValue = -SideMenuManager.menuParallaxStrength horizontal.maximumRelativeValue = SideMenuManager.menuParallaxStrength let vertical = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis) vertical.minimumRelativeValue = -SideMenuManager.menuParallaxStrength vertical.maximumRelativeValue = SideMenuManager.menuParallaxStrength let group = UIMotionEffectGroup() group.motionEffects = [horizontal, vertical] mainViewController.view.addMotionEffect(group) } case .ViewSlideOut, .ViewSlideInOut: break; } if let topNavigationController = mainViewController as? UINavigationController { topNavigationController.interactivePopGestureRecognizer!.enabled = false } } // MARK: UIViewControllerAnimatedTransitioning protocol methods // animate a change from one viewcontroller to another internal func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let statusBarStyle = SideMenuTransition.visibleViewController?.preferredStatusBarStyle() // get reference to our fromView, toView and the container view that we should perform the transition in let container = transitionContext.containerView()! if let menuBackgroundColor = SideMenuManager.menuAnimationBackgroundColor { container.backgroundColor = menuBackgroundColor } // create a tuple of our screens let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!) // assign references to our menu view controller and the 'bottom' view controller from the tuple // remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing let menuViewController = (!presenting ? screens.from : screens.to) let topViewController = !presenting ? screens.to : screens.from let menuView = menuViewController.view let topView = topViewController.view // prepare menu items to slide in if presenting { let tapView = UIView() tapView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] let exitPanGesture = UIPanGestureRecognizer() exitPanGesture.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handleHideMenuPan(_:))) let exitTapGesture = UITapGestureRecognizer() exitTapGesture.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handleHideMenuTap(_:))) tapView.addGestureRecognizer(exitPanGesture) tapView.addGestureRecognizer(exitTapGesture) SideMenuTransition.tapView = tapView SideMenuTransition.originalSuperview = topView.superview // add the both views to our view controller switch SideMenuManager.menuPresentMode { case .ViewSlideOut: container.addSubview(menuView) container.addSubview(topView) topView.addSubview(tapView) case .MenuSlideIn, .MenuDissolveIn, .ViewSlideInOut: container.addSubview(topView) container.addSubview(tapView) container.addSubview(menuView) } if SideMenuManager.menuFadeStatusBar { let blackBar = UIView() if let menuShrinkBackgroundColor = SideMenuManager.menuAnimationBackgroundColor { blackBar.backgroundColor = menuShrinkBackgroundColor } else { blackBar.backgroundColor = UIColor.blackColor() } blackBar.userInteractionEnabled = false container.addSubview(blackBar) SideMenuTransition.statusBarView = blackBar } SideMenuTransition.hideMenuStart() // offstage for interactive } // perform the animation! let duration = transitionDuration(transitionContext) let options: UIViewAnimationOptions = interactive ? .CurveLinear : .CurveEaseInOut UIView.animateWithDuration(duration, delay: 0, options: options, animations: { () -> Void in if self.presenting { SideMenuTransition.presentMenuStart() // onstage items: slide in } else { SideMenuTransition.hideMenuStart() } }) { (finished) -> Void in if SideMenuTransition.visibleViewController?.preferredStatusBarStyle() != statusBarStyle { print("Warning: do not change the status bar style while using custom transitions or you risk transitions not properly completing and locking up the UI. See http://www.openradar.me/21961293") } // tell our transitionContext object that we've finished animating if transitionContext.transitionWasCancelled() { if self.presenting { SideMenuTransition.hideMenuComplete() } else { SideMenuTransition.presentMenuComplete() } transitionContext.completeTransition(false) } else { if self.presenting { SideMenuTransition.presentMenuComplete() transitionContext.completeTransition(true) switch SideMenuManager.menuPresentMode { case .ViewSlideOut: container.addSubview(topView) case .MenuSlideIn, .MenuDissolveIn, .ViewSlideInOut: container.insertSubview(topView, atIndex: 0) } if let statusBarView = SideMenuTransition.statusBarView { container.bringSubviewToFront(statusBarView) } } else { SideMenuTransition.hideMenuComplete() transitionContext.completeTransition(true) menuView.removeFromSuperview() } } } } // return how many seconds the transiton animation will take internal func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return presenting ? SideMenuManager.menuAnimationPresentDuration : SideMenuManager.menuAnimationDismissDuration } // MARK: UIViewControllerTransitioningDelegate protocol methods // return the animataor when presenting a viewcontroller // rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol internal func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true SideMenuTransition.presentDirection = presented == SideMenuManager.menuLeftNavigationController ? .Left : .Right return self } // return the animator used when dismissing from a viewcontroller internal func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { presenting = false return self } internal func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { // if our interactive flag is true, return the transition manager object // otherwise return nil return interactive ? SideMenuTransition.singleton : nil } internal func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactive ? SideMenuTransition.singleton : nil } internal func applicationDidEnterBackgroundNotification() { if let menuViewController: UINavigationController = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController { SideMenuTransition.hideMenuStart() SideMenuTransition.hideMenuComplete() menuViewController.dismissViewControllerAnimated(false, completion: nil) } } }
mit
4ba4a2c896c44b17528e9d7872c1c008
54.485366
243
0.670843
6.991088
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Retail
iOS/ReadyAppRetail/ReadyAppRetail/Controllers/LoginViewController.swift
1
20880
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit import Security class LoginViewController: SummitUIViewController, UITextFieldDelegate, UIAlertViewDelegate { @IBOutlet weak var loginBoxView: UIView! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var summitLogoImageView: UIImageView! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var appNameLabel: UILabel! @IBOutlet weak var logoHolderTopSpace: NSLayoutConstraint! @IBOutlet weak var loginBoxViewBottomSpace: NSLayoutConstraint! var logoHolderOriginalTopSpace : CGFloat! var loginBoxViewOriginalBottomSpace : CGFloat! var kFourInchIphoneHeight : CGFloat = 568 var kFourInchIphoneLogoHolderNewTopSpace : CGFloat = 30 var kloginBoxViewPaddingFromKeyboard : CGFloat = 60 var presentingVC : UIViewController! var noKeychainItems : Bool = true var wormhole : MMWormhole? /** This method calls the setUpLoginBoxView, setUpSignUpButton, setUpTextFields, and saveUIElementOriginalConstraints methods when the view loads */ override func viewDidLoad() { super.viewDidLoad() if let groupAppID = GroupDataAccess.sharedInstance.groupAppID { self.wormhole = MMWormhole(applicationGroupIdentifier: groupAppID, optionalDirectory: nil) } setUpLoginBoxView() setUpLoginButton() setUpSignUpButton() setUpTextFields() saveUIElementOriginalConstraints() } override func viewDidAppear(animated: Bool) { self.navigationItem.title = NSLocalizedString("LOGIN", comment:"") self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Oswald-Regular", size: 22)!, NSForegroundColorAttributeName: UIColor.whiteColor()] } /** This method calls the registerForKeyboardNotifications when the viewWillAppear - parameter animated: */ override func viewWillAppear(animated: Bool) { self.registerForKeyboardNotifications() // Attempt to fetch login details from the keychain let usr : String? = KeychainWrapper.stringForKey("summit_username") let pswd : String? = KeychainWrapper.stringForKey("summit_password") if (usr != nil && pswd != nil) { Utils.showProgressHud() self.noKeychainItems = false MILWLHelper.login(usr!, password: pswd!, callBack: self.loginCallback) } else { self.noKeychainItems = true } } /** This method calls the deregisterFromKeyboardNotifications when the viewWillDisappear - parameter animated: */ override func viewWillDisappear(animated: Bool) { self.deregisterFromKeyboardNotifications() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** This method sets up properties of the loginBoxView, specifically to make the corners rounded */ func setUpLoginBoxView(){ loginBoxView.layer.cornerRadius = 6; loginBoxView.layer.masksToBounds = true; } /** This method sets the title of the login button using a localized string */ func setUpLoginButton(){ loginButton.setTitle(NSLocalizedString("L O G I N", comment: "Another word for sign in"), forState: UIControlState.Normal) } /** This method sets up the usernameTextField and the passwordTextField to make the corners rounded, to add the icon on the left side of the textfield, and to hide the iOS 8 suggested words toolbar */ func setUpTextFields(){ //*****set up usernameTextField***** //make cursor color summit green usernameTextField.tintColor = Utils.UIColorFromHex(0x005448, alpha: 1) //create imageView of usernameIcon let usernameIconImageView = UIImageView(frame: CGRectMake(13, 12, 16, 20)) usernameIconImageView.image = UIImage(named: "profile_selected") //create paddingView that will be added to the usernameTextField. This paddingView will hold the usernameIconImageView let usernamePaddingView = UIView(frame: CGRectMake(0, 0,usernameTextField.frame.size.height - 10, usernameTextField.frame.size.height)) usernamePaddingView.addSubview(usernameIconImageView) //add usernamePaddingView to usernameTextField.leftView usernameTextField.leftView = usernamePaddingView usernameTextField.leftViewMode = UITextFieldViewMode.Always //make usernameTextField have rounded corners usernameTextField.borderStyle = UITextBorderStyle.RoundedRect //hide iOS 8 suggested words toolbar usernameTextField.autocorrectionType = UITextAutocorrectionType.No; usernameTextField.placeholder = NSLocalizedString("Username", comment: "A word for mail over the internet") //*****set up passwordTextField**** //make cursor color summit green passwordTextField.tintColor = Utils.UIColorFromHex(0x005448, alpha: 1) //create imageView for passwordIcon let passwordIconImageView = UIImageView(frame: CGRectMake(13, 10, 18, 22)) passwordIconImageView.image = UIImage(named: "password") //create paddingView that will be added to the passwordTextField. This paddingView will hold the passwordIconImageView let passwordPaddingView = UIView(frame: CGRectMake(0, 0,usernameTextField.frame.size.height - 10, usernameTextField.frame.size.height)) passwordPaddingView.addSubview(passwordIconImageView) //add passwordPaddingView to the passwordTextField.left passwordTextField.leftView = passwordPaddingView passwordTextField.leftViewMode = UITextFieldViewMode.Always //Make passwordTextField have rounded corners passwordTextField.borderStyle = UITextBorderStyle.RoundedRect //hide iOS 8 suggested words toolbar passwordTextField.autocorrectionType = UITextAutocorrectionType.No; passwordTextField.placeholder = NSLocalizedString("Password", comment: "A secret phrase that allows you to login to a service") } /** This method sets up the text of the signUpButton by creating an attributed string and assigning this attributed string to the signUpButtons attributed title */ func setUpSignUpButton(){ // create attributed string let localizedString = NSLocalizedString("Don't have an Account?", comment: "A secret phrase that allows you to login to a service") let string = localizedString let attributedString = NSMutableAttributedString(string: string) let localizedString2 = NSLocalizedString(" Sign Up.", comment: "A secret phrase that allows you to login to a service") let string2 = localizedString2 let attributedString2 = NSMutableAttributedString(string: string2) // create font descriptor for bold and italic font let fontDescriptor = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleBody) let boldItalicFontDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(.TraitBold) //Create attributes for two parts of the string let firstAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] let secondAttributes = [NSFontAttributeName: UIFont(descriptor: boldItalicFontDescriptor, size: 12), NSForegroundColorAttributeName: UIColor.whiteColor()] //Add attributes to two parts of the string attributedString.addAttributes(firstAttributes, range: NSRange(location: 0,length: string.characters.count)) attributedString2.addAttributes(secondAttributes, range: NSRange(location: 0, length: string2.characters.count)) attributedString.appendAttributedString(attributedString2) //set Attributed Title for signUp Button signUpButton.setAttributedTitle(attributedString, forState: UIControlState.Normal) } /** This method saves the original constant for the the logoHolderOriginalTopSpace and the loginBoxViewOriginalBottomSpace. These CGFloats are needed in the keyboardWillHide method to bring the logoHolder and the loginBoxView back to their original constraint constants. */ func saveUIElementOriginalConstraints(){ logoHolderOriginalTopSpace = logoHolderTopSpace.constant loginBoxViewOriginalBottomSpace = loginBoxViewBottomSpace.constant } /** This method sets up the keyboardWillShow and keyboardWillHide methods to be called when NSNotificationCenter triggers the UIKeyboardWillShowNotification and UIKeyboardWillHideNotification notifications repspectively */ func registerForKeyboardNotifications(){ NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil); NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil); } /** This method removes the observer that triggers the UIKeyboardWillShowNotification. This method is invoked in the viewWillDisappear method */ func deregisterFromKeyboardNotifications(){ NSNotificationCenter.defaultCenter().removeObserver(self, name:UIKeyboardWillShowNotification, object: nil); } /** This method is called when the loginButton is pressed. This method checks to see if the username and password entered in the textfields are of valid syntax. It does this by calling the checkEmail and checkPassword methods of the utility class SyntaxChecker.swift. This class assumes that the following regular expression is allowed for an email [A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4} and for a password [A-Z0-9a-z_@!&%$#*?]+. This method also calls the login method - parameter sender: */ @IBAction func loginButtonAction(sender: UIButton) { if(SyntaxChecker.checkUserName(usernameTextField.text!) == true && SyntaxChecker.checkPassword(passwordTextField.text!) == true){ self.login() } } override func disablesAutomaticKeyboardDismissal() -> Bool { return false } /** This method uses the view controllers instance of milWLHelper to call the login method, passing it the username and password the user entered in the text fields. */ func login(){ Utils.showProgressHud() MILWLHelper.login(self.usernameTextField.text!, password: self.passwordTextField.text!, callBack: self.loginCallback) } func loginCallback(success: Bool, errorMessage: String?) { if success { self.loginSuccessful() } else if (errorMessage != nil) { self.loginFailure(errorMessage!) } else { self.loginFailure("No message") } } /** This method is called from the LoginManager if the login was successful */ func loginSuccessful(){ // Store username and password in the keychain if (noKeychainItems == true) { KeychainWrapper.setString(self.usernameTextField.text!, forKey: "summit_username") KeychainWrapper.setString(self.passwordTextField.text!, forKey: "summit_password") } // Let the Watch know that it can log in self.wormhole!.passMessageObject(["username": KeychainWrapper.stringForKey("summit_username")!, "password": KeychainWrapper.stringForKey("summit_password")!], identifier: "loginNotification") MILWLHelper.getDefaultList(self.defaultListResult) } func defaultListResult(success: Bool) { if success { self.defaultListsDownloaded() } else { self.failureDownloadingDefaultLists() } } private func dismissLoginViewController(){ Utils.dismissProgressHud() //dismiss login and present the appropriate next view based on which VC presented the login self.usernameTextField.resignFirstResponder() self.passwordTextField.resignFirstResponder() self.view.endEditing(true) self.dismissViewControllerAnimated(true, completion:{(Bool) in if (self.presentingVC.isKindOfClass(ProductDetailViewController)) { let detailVC: ProductDetailViewController = self.presentingVC as! ProductDetailViewController detailVC.queryProductIsAvailable() //refresh product availability detailVC.addToListTapped() //show add to list view } if (self.presentingVC.isKindOfClass(ListTableViewController)) { let detailVC: ListTableViewController = self.presentingVC as! ListTableViewController detailVC.performSegueWithIdentifier("createList", sender: self) //show create a list view } }) } /** This method is called from the GetDefaultListDataManager when the lists have been successfully downloaded, parsed, and added to realm */ func defaultListsDownloaded(){ Utils.dismissProgressHud() dismissLoginViewController() } /** This method is called by the GetDefaultListDataManager when the onFailure was called by Worklight. It first dismisses the progressHud and then shows the server error alert */ func failureDownloadingDefaultLists(){ Utils.dismissProgressHud() Utils.showServerErrorAlert(self, tag: 1) } /** This method is called when the Retry button is pressed from the server error alert. It first shows the progressHud and then retrys to call MILWLHelper's getDefaultList method - parameter alertView: - parameter buttonIndex: */ func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if(alertView.tag == 1){ Utils.showProgressHud() MILWLHelper.getDefaultList(self.defaultListResult) } } /** This method is called from the LoginManager if the login was a failure */ func loginFailure(errorMessage : String){ Utils.dismissProgressHud() var alertTitle : String! if(errorMessage == NSLocalizedString("Invalid username", comment:"")){ if (self.noKeychainItems == false) { alertTitle = NSLocalizedString("Stale Keychain Credentials", comment:"") KeychainWrapper.removeObjectForKey("summit_username") KeychainWrapper.removeObjectForKey("summit_password") self.noKeychainItems = true } alertTitle = NSLocalizedString("Invalid Username", comment:"") } else if(errorMessage == "Invalid password"){ if (self.noKeychainItems == false) { alertTitle = NSLocalizedString("Stale Keychain Credentials", comment:"") KeychainWrapper.removeObjectForKey("summit_username") KeychainWrapper.removeObjectForKey("summit_password") self.noKeychainItems = true } alertTitle = NSLocalizedString("Invalid Password", comment:"") } else { alertTitle = NSLocalizedString("Can't Connect To Server", comment:"") } let alert = UIAlertView() alert.title = alertTitle alert.message = NSLocalizedString("Please Try Again", comment:"") alert.addButtonWithTitle("OK") alert.show() Utils.dismissProgressHud() } /** This method is called when the signUpButton is pressed - parameter sender: */ @IBAction func signUpButtonAction(sender: UIButton) { } /** This method is called when the user touches anywhere on the view that is not a textfield. This method triggers the keyboard to go down, which triggers the keyboardWillHide method to be called, thus bringing the loginBoxView and the logoHolderView back to their original positions - parameter touches: - parameter event: */ override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { usernameTextField.resignFirstResponder() passwordTextField.resignFirstResponder() } /** This method is called when the keyboard shows. Its main purpose is to adjust the logoHolderView and the loginBoxView's constraints to raise these views up vertically to make room for the keyboard - parameter notification: */ func keyboardWillShow(notification : NSNotification){ //if the loginBoxViewBottomSpace.constant is at its original position, aka only raise the views when they aren't already raised. if(loginBoxViewBottomSpace.constant == loginBoxViewOriginalBottomSpace){ //if the iPhone's height is less than kFourInchIphoneHeight (568) if(UIScreen.mainScreen().bounds.height <= kFourInchIphoneHeight){ let info : NSDictionary = notification.userInfo! //grab the size of the keyboard that has popped up let keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size //adjust the top space constraint for the logoHolder logoHolderTopSpace.constant = kFourInchIphoneLogoHolderNewTopSpace //adjust the loginBoxView bottom space loginBoxViewBottomSpace.constant = (keyboardSize!.height - loginBoxViewBottomSpace.constant) + kloginBoxViewPaddingFromKeyboard //arbitrary 20 padding UIView.animateWithDuration(0.3, animations: { self.view.layoutIfNeeded() self.appNameLabel.alpha = 0 }) }else{ let info : NSDictionary = notification.userInfo! //grab the size of the keyboard let keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size self.view.layoutIfNeeded() //adjust the bottom space constraint for the loginBoxView loginBoxViewBottomSpace.constant = (keyboardSize!.height - loginBoxViewBottomSpace.constant) + kloginBoxViewPaddingFromKeyboard //arbitrary 20 padding UIView.animateWithDuration(0.3, animations: { self.view.layoutIfNeeded()}) } } } /** This method is called when the keyboard hides. It sets the logoHolderView and the loginBoxView's constraints to their original positions - parameter notification: */ func keyboardWillHide(notification : NSNotification){ self.view.layoutIfNeeded() //set the logoHolderTopSpace and loginBoxViewBottomSpace to their original constraint constants logoHolderTopSpace.constant = logoHolderOriginalTopSpace loginBoxViewBottomSpace.constant = loginBoxViewOriginalBottomSpace UIView.animateWithDuration(0.2, animations: { self.view.layoutIfNeeded() self.appNameLabel.alpha = 1 }) } /** If the user presses the return key while the passwordTextField is selected, it will call the login method - parameter textField: - returns: */ func textFieldShouldReturn(textField: UITextField) -> Bool { if(textField == passwordTextField){ login() } return true } /** This method is called when the user presses the x in the top left corner - parameter sender: */ @IBAction func cancelLoginScreen(sender: AnyObject) { self.dismissViewControllerAnimated(false, completion: nil) } /* // 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. } */ }
epl-1.0
a9293a7fa59d0be19a0f2267b4151335
40.758
479
0.675368
5.970546
false
false
false
false