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
rwgrier/unsplashed
Unsplash/controllers/GalleryViewController.swift
1
3133
// // GalleryViewController.swift // Unsplash // // Created by Grier, Ryan on 5/26/16. // Copyright © 2016 Ryan Grier. All rights reserved. // import UIKit class GalleryViewController: UICollectionViewController { private let photoDataSource = PhotoDataSource() deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() (collectionView?.collectionViewLayout as? UICollectionViewFlowLayout)?.estimatedItemSize = CGSize(width: 320, height: 279) NotificationCenter.default.addObserver(self, selector: #selector(GalleryViewController.fontSizeChanged(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil) loadPhotoInfoFromNetwork() } private func loadPhotoInfoFromNetwork() { // Kick off the network request photoDataSource.loadPhotoListFromNetwork { [weak self] (result: Result<[Photo], Error>) in guard let strongSelf = self else { return } switch result { case .failure(let error): let title = NSLocalizedString("Photos Error", comment: "") var message = NSLocalizedString("An unknown error has occurred", comment: "") if let unsplashError = error as? UnsplashError { message = unsplashError.message } let alertView = UIAlertController(title: title, message: message, preferredStyle: .alert) alertView.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .cancel, handler: nil)) alertView.addAction(UIAlertAction(title: NSLocalizedString("Retry", comment: ""), style: .default, handler: { (_) in strongSelf.loadPhotoInfoFromNetwork() })) DispatchQueue.main.async { strongSelf.present(alertView, animated: true, completion: nil) } case .success: break } DispatchQueue.main.async { strongSelf.collectionView?.reloadData() } } } @objc internal func fontSizeChanged(_ notification: Notification) { collectionView?.reloadData() } } // MARK: - UICollectionViewDataSource extension GalleryViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { print("count: \(photoDataSource.cachedPhotos.count)") return photoDataSource.cachedPhotos.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let photoCell = collectionView.dequeueReusableCell(withReuseIdentifier: "thumbnailCell", for: indexPath) as? PhotoCell else { fatalError("The cell should be a PhotoCell") } let photo = photoDataSource.cachedPhotos[indexPath.row] photoCell.setupCell(photo: photo) return photoCell } }
mit
524f5668590c24f8b2482c03af1614de
36.73494
186
0.658685
5.543363
false
false
false
false
jasnig/DouYuTVMutate
DouYuTVMutate/DouYuTV/Profile/Controller/SettingController.swift
1
3421
// // SettingController.swift // DouYuTVMutate // // Created by ZeroJ on 16/7/19. // Copyright © 2016年 ZeroJ. All rights reserved. // import UIKit class SettingController: BaseViewController { var delegator: CommonTableViewDelegator! lazy var tableView: UITableView = { let tableView = UITableView(frame: CGRectZero, style: .Plain) return tableView }() var data: [CommonTableSectionData] = [] { didSet { tableView.reloadData() } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) print("appear -------- \(tableView.contentInset)") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() title = "设置" view.addSubview(tableView) setupData() delegator = CommonTableViewDelegator(tableView: tableView, data: {[unowned self] () -> [CommonTableSectionData] in return self.data }) tableView.delegate = delegator tableView.dataSource = delegator } override func addConstraints() { tableView.snp_makeConstraints { (make) in make.leading.equalTo(view) make.top.equalTo(view) make.trailing.equalTo(view) make.bottom.equalTo(view) } } func showHud() { EasyHUD.showHUD("未实现相关功能", autoHide: true, afterTime: 1.0) } func setupData() { let row1Data = TypedCellDataModel(name: "列表自动加载", isOn: false) let row2Data = TypedCellDataModel(name: "播放器手势", isOn: true) let row3Data = TypedCellDataModel(name: "清理缓存", detailValue: "44.0M") let row4Data = TypedCellDataModel(name: "关于我们") let row5Data = TypedCellDataModel(name: "意见反馈") let row6Data = TypedCellDataModel(name: "给我们评分") let row1 = CellBuilder<TitleWithSwitchCell>(dataModel: row1Data, cellDidClickAction: {[unowned self](switchS: UISwitch) -> Void in self.showHud() }) let row2 = CellBuilder<TitleWithSwitchCell>(dataModel: row2Data, cellDidClickAction: {[unowned self](switchS: UISwitch) -> Void in self.showHud() }) let row3 = CellBuilder<TitleWithDetailValueCell>(dataModel: row3Data, cellDidClickAction: {[unowned self] in self.showHud() }) let row4 = CellBuilder<TitleOnlyCell>(dataModel: row4Data, cellHeight: 50, cellDidClickAction: {[unowned self] in self.showHud() }) let row5 = CellBuilder<TitleOnlyCell>(dataModel: row5Data, cellDidClickAction: {[unowned self] in self.showHud() }) let row6 = CellBuilder<TitleOnlyCell>(dataModel: row6Data, cellDidClickAction: {[unowned self] in self.showHud() }) let section1 = CommonTableSectionData(headerTitle: "这是测试数据", footerTitle: "随便写的", headerHeight: 38, footerHeight: 38, rows: [row1,row2,row3,row4,row5,row6]) data = [section1] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f748834f96d6471fc474d601c2c0ffbd
29.495413
164
0.603791
4.356488
false
false
false
false
flodolo/firefox-ios
Storage/SQL/SQLiteFavicons.swift
1
2396
// 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 open class SQLiteFavicons { let db: BrowserDB required public init(db: BrowserDB) { self.db = db } public func getFaviconIDQuery(url: String) -> (sql: String, args: Args?) { var args: Args = [] args.append(url) return (sql: "SELECT id FROM favicons WHERE url = ? LIMIT 1", args: args) } public func getInsertFaviconQuery(favicon: Favicon) -> (sql: String, args: Args?) { var args: Args = [] args.append(favicon.url) args.append(favicon.width) args.append(favicon.height) args.append(favicon.date) return (sql: "INSERT INTO favicons (url, width, height, type, date) VALUES (?,?,?,0,?)", args: args) } public func getUpdateFaviconQuery(favicon: Favicon) -> (sql: String, args: Args?) { var args = Args() args.append(favicon.width) args.append(favicon.height) args.append(favicon.date) args.append(favicon.url) return (sql: "UPDATE favicons SET width = ?, height = ?, date = ? WHERE url = ?", args: args) } public func getCleanupFaviconsQuery() -> (sql: String, args: Args?) { let sql = """ DELETE FROM favicons WHERE favicons.id NOT IN ( SELECT faviconID FROM favicon_sites ) """ return (sql: sql, args: nil) } public func getCleanupFaviconSiteURLsQuery() -> (sql: String, args: Args?) { let sql = """ DELETE FROM favicon_site_urls WHERE id IN ( SELECT favicon_site_urls.id FROM favicon_site_urls LEFT OUTER JOIN history ON favicon_site_urls.site_url = history.url WHERE history.id IS NULL ) """ return (sql: sql, args: nil) } public func insertOrUpdateFavicon(_ favicon: Favicon) -> Deferred<Maybe<Int>> { return db.withConnection { conn -> Int in self.insertOrUpdateFaviconInTransaction(favicon, conn: conn) ?? 0 } } func insertOrUpdateFaviconInTransaction(_ favicon: Favicon, conn: SQLiteDBConnection) -> Int? { return nil } }
mpl-2.0
d44edbf7a0acbd6252bcaabf6e9f8f6c
32.277778
108
0.593489
4.196147
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 1.playgroundbook/Contents/Chapters/Document8.playgroundchapter/Pages/Exercise3.playgroundpage/Sources/SetUp.swift
1
6866
// // SetUp.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import Foundation // MARK: Globals //let world = GridWorld(columns: 9, rows: 8) let world = loadGridWorld(named: "8.3") public let actor = Actor() public func playgroundPrologue() { placeItems() world.place(actor, facing: south, at: Coordinate(column: 1, row: 7)) // Must be called in `playgroundPrologue()` to update with the current page contents. registerAssessment(world, assessment: assessmentPoint) //// ---- // Any items added or removed after this call will be animated. finalizeWorldBuilding(for: world) //// ---- } // Called from LiveView.swift to initially set the LiveView. public func presentWorld() { setUpLiveViewWith(world) } // MARK: Epilogue public func playgroundEpilogue() { sendCommands(for: world) } func placeItems() { let items = [ Coordinate(column: 7, row: 1), ] world.placeGems(at: items) } func placeBlocks() { let obstacles = [ Coordinate(column: 0, row: 3), Coordinate(column: 0, row: 4), Coordinate(column: 1, row: 0), Coordinate(column: 1, row: 1), Coordinate(column: 1, row: 3), Coordinate(column: 2, row: 0), Coordinate(column: 2, row: 1), Coordinate(column: 3, row: 6), Coordinate(column: 5, row: 6), Coordinate(column: 7, row: 0), Coordinate(column: 7, row: 2), Coordinate(column: 7, row: 3), Coordinate(column: 7, row: 4), Coordinate(column: 7, row: 6), Coordinate(column: 8, row: 0), Coordinate(column: 8, row: 1), Coordinate(column: 8, row: 2), Coordinate(column: 8, row: 3), Coordinate(column: 8, row: 4), Coordinate(column: 8, row: 7), ] world.removeNodes(at: obstacles) world.placeWater(at: obstacles) let tiers = [ Coordinate(column: 2, row: 7), Coordinate(column: 3, row: 7), Coordinate(column: 4, row: 7), Coordinate(column: 5, row: 7), Coordinate(column: 6, row: 7), Coordinate(column: 7, row: 7), Coordinate(column: 2, row: 7), Coordinate(column: 3, row: 7), Coordinate(column: 4, row: 7), Coordinate(column: 5, row: 7), Coordinate(column: 6, row: 7), Coordinate(column: 7, row: 7), Coordinate(column: 7, row: 5), Coordinate(column: 8, row: 5), Coordinate(column: 8, row: 6), Coordinate(column: 7, row: 5), Coordinate(column: 8, row: 5), Coordinate(column: 8, row: 6), Coordinate(column: 2, row: 6), Coordinate(column: 4, row: 6), Coordinate(column: 6, row: 6), Coordinate(column: 6, row: 6), Coordinate(column: 6, row: 2), Coordinate(column: 6, row: 3), Coordinate(column: 6, row: 4), Coordinate(column: 6, row: 5), Coordinate(column: 6, row: 2), Coordinate(column: 6, row: 3), Coordinate(column: 6, row: 4), Coordinate(column: 6, row: 5), Coordinate(column: 6, row: 2), Coordinate(column: 6, row: 3), Coordinate(column: 6, row: 4), Coordinate(column: 6, row: 5), Coordinate(column: 5, row: 3), Coordinate(column: 5, row: 4), Coordinate(column: 5, row: 5), Coordinate(column: 5, row: 3), Coordinate(column: 5, row: 4), Coordinate(column: 5, row: 5), Coordinate(column: 4, row: 3), Coordinate(column: 4, row: 5), Coordinate(column: 3, row: 3), Coordinate(column: 3, row: 5), Coordinate(column: 2, row: 3), Coordinate(column: 2, row: 5), Coordinate(column: 2, row: 5), Coordinate(column: 1, row: 5), Coordinate(column: 1, row: 4), Coordinate(column: 2, row: 2), Coordinate(column: 3, row: 2), Coordinate(column: 4, row: 2), Coordinate(column: 5, row: 2), Coordinate(column: 2, row: 2), Coordinate(column: 3, row: 2), Coordinate(column: 4, row: 2), Coordinate(column: 5, row: 2), Coordinate(column: 0, row: 1), Coordinate(column: 0, row: 2), Coordinate(column: 1, row: 2), Coordinate(column: 0, row: 7), Coordinate(column: 3, row: 1), Coordinate(column: 3, row: 0), Coordinate(column: 6, row: 0), ] world.placeBlocks(at: tiers) world.place(Stair(), facing: west, at: Coordinate(column: 0, row: 5)) world.place(Stair(), facing: north, at: Coordinate(column: 1, row: 6)) world.place(Stair(), facing: south, at: Coordinate(column: 4, row: 6)) world.place(Stair(), facing: north, at: Coordinate(column: 6, row: 6)) world.place(Stair(), facing: east, at: Coordinate(column: 7, row: 5)) world.place(Stair(), facing: east, at: Coordinate(column: 2, row: 4)) world.place(Stair(), facing: west, at: Coordinate(column: 4, row: 4)) world.place(Stair(), facing: west, at: Coordinate(column: 1, row: 2)) world.place(Stair(), facing: west, at: Coordinate(column: 5, row: 2)) world.place(Stair(), facing: south, at: Coordinate(column: 3, row: 1)) world.place(Stair(), facing: south, at: Coordinate(column: 0, row: 0)) world.place(Stair(), facing: east, at: Coordinate(column: 4, row: 0)) }
mit
5e55b593e114f4f19274b14f2ece4841
38.011364
89
0.452083
4.514135
false
false
false
false
matanwrites/JobQueue
JobQueueExample/JobQueueExample/DummyJob.swift
1
2101
// // DummyJob.swift // JobQueueExample // // Created by sintaiyuan on 9/13/17. // Copyright © 2017 taiyungo. All rights reserved. // import Foundation import JobQueue class PrintInteractor : NSObject, Job { //MARK: - //MARK: Our usual business code doing something useful var message: String func execute() { print(message) } override init() { message = "HI! \(Date())" super.init() } //MARK: - //MARK: - Job var retryableCount: Int = 0 required init?(coder aDecoder: NSCoder) { guard let msg = aDecoder.decodeObject(forKey: "message") as? String else { return nil } message = msg } func encode(with aCoder: NSCoder) { aCoder.encode(message, forKey: "message") } func run() { execute() } } class DoSomethingIncredible_Interactor : NSObject, Job { //MARK: - //MARK: Our usual business code doing something useful var incredibleVariableToCompute: String func execute() { //our long fake computing method DispatchQueue(label: "computing.queue").asyncAfter(deadline: .now() + 5) { let afterProcessingString = self.incredibleVariableToCompute.uppercased() DispatchQueue.main.async { print("after our incredible processing '\(self.incredibleVariableToCompute)' becomes ..' '\(afterProcessingString)' !") } } } init(stringToCompute: String) { incredibleVariableToCompute = stringToCompute super.init() } //MARK: - //MARK: - Job var retryableCount: Int = 0 required init?(coder aDecoder: NSCoder) { guard let x = aDecoder.decodeObject(forKey: "incredibleVariableToCompute") as? String else { return nil } incredibleVariableToCompute = x } func encode(with aCoder: NSCoder) { aCoder.encode(incredibleVariableToCompute, forKey: "incredibleVariableToCompute") } func run() { execute() } }
mit
fbd88be9e9f71db5350ff435d6e1d807
22.333333
135
0.595714
4.338843
false
false
false
false
RocketChat/Rocket.Chat.iOS
Pods/RocketChatViewController/Composer/Classes/Views/ComposerView.swift
1
15412
// // ComposerView.swift // RocketChatViewController Example // // Created by Matheus Cardoso on 9/5/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit import NotificationCenter /** An enum that represents a place in the composer view where an addon is placed. */ public enum ComposerAddonSlot { /** When the addon represents something in the message (eg. attached media) */ case component /** When the addon represents a utility to the composer (eg. hint view) */ case utility } /* A default composer view delegate with fallback behaviors. */ private class ComposerViewFallbackDelegate: ComposerViewDelegate { } // MARK: Initializers public class ComposerView: UIView, ComposerLocalizable { /** The object that acts as the delegate of the composer. */ public weak var delegate: ComposerViewDelegate? /** A fallback delegate for when delegate is nil. */ private var fallbackDelegate = ComposerViewFallbackDelegate() /** Returns the delegate if set, if not, returns the default delegate. Delegate should only be accessed inside this class via this computed property. */ private var currentDelegate: ComposerViewDelegate { return delegate ?? fallbackDelegate } /** The view that contains all subviews */ public let containerView = tap(UIView()) { $0.translatesAutoresizingMaskIntoConstraints = false $0.backgroundColor = .white } /** The button that stays in the left side of the composer. */ public let leftButton = tap(ComposerButton()) { $0.translatesAutoresizingMaskIntoConstraints = false $0.setBackgroundImage(ComposerAssets.addButtonImage, for: .normal) $0.accessibilityLabel = localized(.addButtonLabel) $0.addTarget(self, action: #selector(touchUpInsideButton), for: .touchUpInside) $0.addTarget(self, action: #selector(touchUpOutsideButton), for: .touchUpOutside) $0.addTarget(self, action: #selector(touchDownInButton), for: .touchDown) $0.addTarget(self, action: #selector(touchDragInsideButton), for: .touchDragInside) $0.addTarget(self, action: #selector(touchDragOutsideButton), for: .touchDragOutside) $0.setContentHuggingPriority(.required, for: .horizontal) } /** The button that stays in the right side of the composer. */ public let rightButton = tap(ComposerButton()) { $0.translatesAutoresizingMaskIntoConstraints = false $0.setBackgroundImage(ComposerAssets.sendButtonImage, for: .normal) $0.addTarget(self, action: #selector(touchUpInsideButton), for: .touchUpInside) $0.addTarget(self, action: #selector(touchUpOutsideButton), for: .touchUpOutside) $0.addTarget(self, action: #selector(touchDownInButton), for: .touchDown) $0.addTarget(self, action: #selector(touchDragInsideButton), for: .touchDragInside) $0.addTarget(self, action: #selector(touchDragOutsideButton), for: .touchDragOutside) $0.setContentHuggingPriority(.required, for: .horizontal) } /** The text view used to compose the message. */ public let textView = tap(ComposerTextView()) { $0.translatesAutoresizingMaskIntoConstraints = false $0.text = "" $0.font = .preferredFont(forTextStyle: .body) $0.adjustsFontForContentSizeCategory = true $0.accessibilityLabel = localized(.textViewPlaceholder) $0.placeholderLabel.text = localized(.textViewPlaceholder) $0.placeholderLabel.font = .preferredFont(forTextStyle: .body) $0.placeholderLabel.adjustsFontForContentSizeCategory = true $0.placeholderLabel.isAccessibilityElement = false } /** The view that contains component addons on top of the text (eg. attached media) */ public let componentStackView = tap(ComposerAddonStackView()) { $0.translatesAutoresizingMaskIntoConstraints = false $0.axis = .vertical } /** The separator line on top of the composer */ public let topSeparatorView = tap(UIView()) { $0.translatesAutoresizingMaskIntoConstraints = false $0.backgroundColor = #colorLiteral(red: 0.8823529412, green: 0.8980392157, blue: 0.9098039216, alpha: 1) NSLayoutConstraint.activate([ $0.heightAnchor.constraint(equalToConstant: 0.5) ]) } /** The view that contains utility addons on top of the composer (eg. hint view) */ public let utilityStackView = tap(ComposerAddonStackView()) { $0.translatesAutoresizingMaskIntoConstraints = false } /** The view that overlays the composer when showOverlay is called. */ public let overlayView = tap(OverlayView()) { $0.translatesAutoresizingMaskIntoConstraints = false $0.isHidden = true } /** A Boolean value that indicates whether text can change in the textView */ public var isTextInputEnabled = true public override var intrinsicContentSize: CGSize { return CGSize(width: super.intrinsicContentSize.width, height: containerView.bounds.height) } public convenience init() { self.init(frame: .zero) } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } /** Shared initialization procedures. */ public func commonInit() { translatesAutoresizingMaskIntoConstraints = false leftButton.addObserver(self, forKeyPath: "bounds", options: .new, context: nil) textView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil) textView.delegate = self containerView.addObserver(self, forKeyPath: "bounds", options: .new, context: nil) addSubviews() setupConstraints() } /** Adds buttons and other UI elements as subviews. */ private func addSubviews() { addSubview(containerView) containerView.addSubview(leftButton) containerView.addSubview(rightButton) containerView.addSubview(textView) containerView.addSubview(componentStackView) containerView.addSubview(topSeparatorView) containerView.addSubview(utilityStackView) containerView.addSubview(overlayView) } // MARK: Constraints lazy var textViewLeadingConstraint: NSLayoutConstraint = { textView.leadingAnchor.constraint(equalTo: leftButton.trailingAnchor, constant: 0) }() lazy var containerViewLeadingConstraint: NSLayoutConstraint = { containerView.leadingAnchor.constraint(equalTo: leadingAnchor) }() /** Sets up constraints between the UI elements in the composer. */ private func setupConstraints() { NSLayoutConstraint.activate([ // containerView constraints containerViewLeadingConstraint, containerView.trailingAnchor.constraint(equalTo: trailingAnchor), containerView.bottomAnchor.constraint(equalTo: bottomAnchor), // utilityStackView constraints utilityStackView.topAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.topAnchor), utilityStackView.widthAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.widthAnchor), utilityStackView.centerXAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.centerXAnchor), utilityStackView.bottomAnchor.constraint(equalTo: topSeparatorView.topAnchor), // topSeparatorView constraints topSeparatorView.widthAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.widthAnchor), topSeparatorView.centerXAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.centerXAnchor), topSeparatorView.bottomAnchor.constraint(equalTo: componentStackView.topAnchor), // componentStackView constraints componentStackView.topAnchor.constraint(equalTo: topSeparatorView.bottomAnchor), componentStackView.widthAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.widthAnchor), componentStackView.centerXAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.centerXAnchor), componentStackView.bottomAnchor.constraint(equalTo: textView.topAnchor, constant: -10), // textView constraints textViewLeadingConstraint, textView.trailingAnchor.constraint(equalTo: rightButton.leadingAnchor, constant: 0), textView.bottomAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.bottomAnchor, constant: -layoutMargins.bottom), // rightButton constraints rightButton.trailingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.trailingAnchor, constant: -layoutMargins.right*2), rightButton.bottomAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.bottomAnchor, constant: -layoutMargins.bottom*2), // leftButton constraints leftButton.leadingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.leadingAnchor, constant: layoutMargins.left*2), leftButton.bottomAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.bottomAnchor, constant: -layoutMargins.bottom*2), // overlayView constraints overlayView.topAnchor.constraint(equalTo: topSeparatorView.bottomAnchor), overlayView.bottomAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.bottomAnchor), overlayView.leadingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.leadingAnchor), overlayView.trailingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.trailingAnchor) ]) } public override func layoutSubviews() { super.layoutSubviews() } public override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) reloadAddons() configureButtons() } override public func point(inside point: CGPoint, with event: UIEvent?) -> Bool { for view in self.subviews { if view.isUserInteractionEnabled, view.point(inside: self.convert(point, to: view), with: event) { return true } } return false } } // MARK: Overlay public extension ComposerView { func showOverlay(userData: Any? = nil) { overlayView.isHidden = false leftButton.isUserInteractionEnabled = false rightButton.isUserInteractionEnabled = false isTextInputEnabled = false currentDelegate.composerView(self, willConfigureOverlayView: overlayView, with: userData) currentDelegate.composerView(self, didConfigureOverlayView: overlayView) } func hideOverlay() { overlayView.isHidden = true leftButton.isUserInteractionEnabled = true rightButton.isUserInteractionEnabled = true isTextInputEnabled = true } } // MARK: Buttons public extension ComposerView { public func configureButtons() { currentDelegate.composerView(self, willConfigureButton: leftButton) currentDelegate.composerView(self, willConfigureButton: rightButton) } } // MARK: Addons public extension ComposerView { public func reloadAddons() { [ (componentStackView, ComposerAddonSlot.component), (utilityStackView, ComposerAddonSlot.utility) ].forEach { (stackView, slot) in stackView.subviews.forEach { stackView.removeArrangedSubview($0) $0.removeFromSuperview() } for index in 0..<currentDelegate.numberOfAddons(in: self, at: slot) { if let addon = currentDelegate.composerView(self, addonAt: slot, index: index) { let addonView: UIView = addon.viewType.init() addonView.frame = stackView.frame stackView.addArrangedSubview(addonView) currentDelegate.composerView(self, didUpdateAddonView: addonView, at: slot, index: index) } else { currentDelegate.composerView(self, didUpdateAddonView: nil, at: slot, index: index) } } } } } // MARK: Observers, Gestures & Actions public extension ComposerView { /** Called when the content size of the text view changes and adjusts the composer height constraint. */ public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if object as AnyObject? === leftButton && keyPath == "bounds" { textViewLeadingConstraint.constant = leftButton.isHidden ? 0 : layoutMargins.left } if object as AnyObject? === containerView && keyPath == "bounds" { self.invalidateIntrinsicContentSize() self.superview?.setNeedsLayout() } if object as AnyObject? === textView && keyPath == "contentSize" { textView.invalidateIntrinsicContentSize() self.layoutIfNeeded() } } /** Called when a touchUpInside event happens in one of the buttons. */ @objc private func touchUpInsideButton(_ button: ComposerButton, _ event: UIEvent) { currentDelegate.composerView(self, event: event, eventType: .touchUpInside, happenedInButton: button) } /** Called when a touchUpOutside event happens in one of the buttons. */ @objc private func touchUpOutsideButton(_ button: ComposerButton, _ event: UIEvent) { currentDelegate.composerView(self, event: event, eventType: .touchUpOutside, happenedInButton: button) } /** Called when a touchDown event happens in one of the buttons. */ @objc private func touchDownInButton(_ button: ComposerButton, _ event: UIEvent) { currentDelegate.composerView(self, event: event, eventType: .touchDown, happenedInButton: button) } /** Called when a touchDragInside event happens in one of the buttons. */ @objc private func touchDragInsideButton(_ button: ComposerButton, _ event: UIEvent) { currentDelegate.composerView(self, event: event, eventType: .touchDragInside, happenedInButton: button) } /** Called when a touchDragOutside event happens in one of the buttons. */ @objc private func touchDragOutsideButton(_ button: ComposerButton, _ event: UIEvent) { currentDelegate.composerView(self, event: event, eventType: .touchDragOutside, happenedInButton: button) } } // MARK: UITextView Delegate extension ComposerView: UITextViewDelegate { @objc func textViewDidChangeSelection(_ textView: UITextView) { currentDelegate.composerViewDidChangeSelection(self) return } public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { guard isTextInputEnabled else { return false } if text == "\n" { return currentDelegate.composerViewShouldReturn(self) } return true } }
mit
c864c87c843378fa1a63a04cce731ff9
35.176056
158
0.685355
5.284979
false
false
false
false
chromium/chromium
ios/chrome/browser/ui/omnibox/popup/shared/omnibox_pedal.swift
7
2015
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Foundation import SwiftUI import UIKit @objcMembers public class OmniboxPedalData: NSObject, OmniboxPedal { /// Pedal title, as seen in the pedal button/row. public let title: String /// Pedal subtitle, e.g. "Settings -> Passwords" public let subtitle: String /// Describes the action performed; can be used for voiceover. public let hint: String /// Name of the image in the bundle. public let imageName: String /// Whether the pedal is displayed from an incognito session. public let incognito: Bool /// Action to run when the pedal is executed. public let action: () -> Void /// Action type for metrics collection. Int-casted OmniboxPedalId public let type: Int public init( title: String, subtitle: String, accessibilityHint: String, imageName: String, type: Int, incognito: Bool, action: @escaping () -> Void ) { self.title = title self.subtitle = subtitle self.hint = accessibilityHint self.imageName = imageName self.type = type self.incognito = incognito self.action = action } } extension OmniboxPedalData: OmniboxIcon { public var iconType: OmniboxIconType { return .suggestionIcon } public var iconImage: UIImage? { // Dark mode is set explicitly if incognito is enabled. let userInterfaceStyle = UITraitCollection(userInterfaceStyle: incognito ? .dark : .unspecified) return UIImage( named: self.imageName, in: nil, compatibleWith: UITraitCollection(traitsFrom: [.current, userInterfaceStyle])) } public var imageURL: CrURL? { return nil } public var iconImageTintColor: UIColor? { return nil } public var backgroundImage: UIImage? { return nil } public var backgroundImageTintColor: UIColor? { return nil } public var overlayImage: UIImage? { return nil } public var overlayImageTintColor: UIColor? { return nil } }
bsd-3-clause
2f0edc4d6f97b6d7fac3cc2453d59035
31.5
84
0.719107
4.333333
false
false
false
false
mixpanel/mixpanel-swift
MixpanelDemo/MixpanelDemoTests/MixpanelGroupTests.swift
1
6712
// // MixpanelGroupTests.swift // MixpanelDemo // // Created by Iris McLeary on 9/5/2018. // Copyright © 2018 Mixpanel. All rights reserved. // import XCTest @testable import Mixpanel @testable import MixpanelDemo class MixpanelGroupTests: MixpanelBaseTests { func testGroupSet() { let testMixpanel = Mixpanel.initialize(token: randomId(), trackAutomaticEvents: true, flushInterval: 60) let groupKey = "test_key" let groupID = "test_id" let p: Properties = ["p1": "a"] testMixpanel.getGroup(groupKey: groupKey, groupID: groupID).set(properties: p) waitForTrackingQueue(testMixpanel) let msg = groupQueue(token: testMixpanel.apiToken).last! XCTAssertEqual(msg["$group_key"] as! String, groupKey) XCTAssertEqual(msg["$group_id"] as! String, groupID) let q = msg["$set"] as! InternalProperties XCTAssertEqual(q["p1"] as? String, "a", "custom group property not queued") removeDBfile(testMixpanel.apiToken) } func testGroupSetIntegerID() { let testMixpanel = Mixpanel.initialize(token: randomId(), trackAutomaticEvents: true, flushInterval: 60) let groupKey = "test_key" let groupID = 3 let p: Properties = ["p1": "a"] testMixpanel.getGroup(groupKey: groupKey, groupID: groupID).set(properties: p) waitForTrackingQueue(testMixpanel) let msg = groupQueue(token: testMixpanel.apiToken).last! XCTAssertEqual(msg["$group_key"] as! String, groupKey) XCTAssertEqual(msg["$group_id"] as! Int, groupID) let q = msg["$set"] as! InternalProperties XCTAssertEqual(q["p1"] as? String, "a", "custom group property not queued") removeDBfile(testMixpanel.apiToken) } func testGroupSetOnce() { let testMixpanel = Mixpanel.initialize(token: randomId(), trackAutomaticEvents: true, flushInterval: 60) let groupKey = "test_key" let groupID = "test_id" let p: Properties = ["p1": "a"] testMixpanel.getGroup(groupKey: groupKey, groupID: groupID).setOnce(properties: p) waitForTrackingQueue(testMixpanel) let msg = groupQueue(token: testMixpanel.apiToken).last! XCTAssertEqual(msg["$group_key"] as! String, groupKey) XCTAssertEqual(msg["$group_id"] as! String, groupID) let q = msg["$set_once"] as! InternalProperties XCTAssertEqual(q["p1"] as? String, "a", "custom group property not queued") removeDBfile(testMixpanel.apiToken) } func testGroupSetTo() { let testMixpanel = Mixpanel.initialize(token: randomId(), trackAutomaticEvents: true, flushInterval: 60) let groupKey = "test_key" let groupID = "test_id" testMixpanel.getGroup(groupKey: groupKey, groupID: groupID).set(property: "p1", to: "a") waitForTrackingQueue(testMixpanel) let msg = groupQueue(token: testMixpanel.apiToken).last! XCTAssertEqual(msg["$group_key"] as! String, groupKey) XCTAssertEqual(msg["$group_id"] as! String, groupID) let p = msg["$set"] as! InternalProperties XCTAssertEqual(p["p1"] as? String, "a", "custom group property not queued") removeDBfile(testMixpanel.apiToken) } func testGroupUnset() { let testMixpanel = Mixpanel.initialize(token: randomId(), trackAutomaticEvents: true, flushInterval: 60) let groupKey = "test_key" let groupID = "test_id" testMixpanel.getGroup(groupKey: groupKey, groupID: groupID).unset(property: "p1") waitForTrackingQueue(testMixpanel) let msg = groupQueue(token: testMixpanel.apiToken).last! XCTAssertEqual(msg["$group_key"] as! String, groupKey) XCTAssertEqual(msg["$group_id"] as! String, groupID) XCTAssertEqual(msg["$unset"] as! [String], ["p1"], "group property unset not queued") removeDBfile(testMixpanel.apiToken) } func testGroupRemove() { let testMixpanel = Mixpanel.initialize(token: randomId(), trackAutomaticEvents: true, flushInterval: 60) let groupKey = "test_key" let groupID = "test_id" testMixpanel.getGroup(groupKey: groupKey, groupID: groupID).remove(key: "p1", value: "a") waitForTrackingQueue(testMixpanel) let msg = groupQueue(token: testMixpanel.apiToken).last! XCTAssertEqual(msg["$group_key"] as! String, groupKey) XCTAssertEqual(msg["$group_id"] as! String, groupID) XCTAssertEqual(msg["$remove"] as? [String: String], ["p1": "a"], "group property remove not queued") removeDBfile(testMixpanel.apiToken) } func testGroupUnion() { let testMixpanel = Mixpanel.initialize(token: randomId(), trackAutomaticEvents: true, flushInterval: 60) let groupKey = "test_key" let groupID = "test_id" testMixpanel.getGroup(groupKey: groupKey, groupID: groupID).union(key: "p1", values: ["a"]) waitForTrackingQueue(testMixpanel) let msg = groupQueue(token: testMixpanel.apiToken).last! XCTAssertEqual(msg["$group_key"] as! String, groupKey) XCTAssertEqual(msg["$group_id"] as! String, groupID) XCTAssertEqual(msg["$union"] as? [String: [String]], ["p1": ["a"]], "group property union not queued") removeDBfile(testMixpanel.apiToken) } func testGroupAssertPropertyTypes() { let testMixpanel = Mixpanel.initialize(token: randomId(), trackAutomaticEvents: true, flushInterval: 60) let groupKey = "test_key" let groupID = "test_id" let p: Properties = ["URL": [Data()]] XCTExpectAssert("unsupported property type was allowed") { testMixpanel.getGroup(groupKey: groupKey, groupID: groupID).set(properties: p) } XCTExpectAssert("unsupported property type was allowed") { testMixpanel.getGroup(groupKey: groupKey, groupID: groupID).set(property: "p1", to: [Data()]) } removeDBfile(testMixpanel.apiToken) } func testDeleteGroup() { let testMixpanel = Mixpanel.initialize(token: randomId(), trackAutomaticEvents: true, flushInterval: 60) let groupKey = "test_key" let groupID = "test_id" testMixpanel.getGroup(groupKey: groupKey, groupID: groupID).deleteGroup() waitForTrackingQueue(testMixpanel) let msg = groupQueue(token: testMixpanel.apiToken).last! XCTAssertEqual(msg["$group_key"] as! String, groupKey) XCTAssertEqual(msg["$group_id"] as! String, groupID) let p: InternalProperties = msg["$delete"] as! InternalProperties XCTAssertTrue(p.isEmpty, "incorrect group properties: \(p)") removeDBfile(testMixpanel.apiToken) } }
apache-2.0
28f20cde8a374262bedec436feb5e7f8
46.260563
112
0.662494
4.488963
false
true
false
false
jolucama/OpenWeatherMapAPIConsumer
OpenWeatherMapAPIConsumer/Classes/RequestOpenWeatherMap.swift
1
1558
// // RequestOpenWeatherMap.swift // WhatWearToday // // Created by jlcardosa on 14/11/2016. // Copyright © 2016 Cardosa. All rights reserved. // import Foundation public class RequestOpenWeatherMap { let baseURLString = "https://api.openweathermap.org/data/" let apiVersion = "2.5/" let method = "GET" var type : OpenWeatherMapType! var parameters : [String: String] public init(withType type : OpenWeatherMapType, andParameters parameters:[String: String]) { self.type = type self.parameters = parameters } public func request(onCompletion : @escaping (Data?, URLResponse?, Error?) -> Swift.Void) { let paramString = self.stringFromHttpParameters() let url = URL(string: baseURLString + apiVersion + type.rawValue + "?" + paramString)! let session = URLSession.shared var request = URLRequest(url: url) request.httpMethod = method request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData let task = session.dataTask(with: request, completionHandler: onCompletion) task.resume() NSLog("Request to : %@", url.absoluteString) } public func stringFromHttpParameters() -> String { var parameterArray = [String]() for (key, value) in self.parameters { parameterArray.append(key + "=" + value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!) } return parameterArray.joined(separator: "&") } }
mit
cf5d40c81f0b710964713d09d35c623e
31.4375
128
0.652537
4.790769
false
false
false
false
darofar/lswc
parcial1-javier/ExamenLabo/ExamenGestos/ExamenGestos/ViewController.swift
1
1718
// // ViewController.swift // ExamenGestos // // Created by Javier De La Rubia on 16/4/15. // Copyright (c) 2015 Javier De La Rubia. All rights reserved. // import UIKit class ViewController: UIViewController , CircleViewDataSource{ @IBOutlet var circleView: CircleView! var circleModel : CircleModel! override func viewDidLoad() { super.viewDidLoad() circleModel = CircleModel(); circleView.dataSource = self; circleView.setNeedsDisplay(); let pinchRecognizer = UIPinchGestureRecognizer(target: self, action: "processPinch:"); circleView.addGestureRecognizer(pinchRecognizer); // Do any additional setup after loading the view, typically from a nib. } func processPinch(sender : UIPinchGestureRecognizer) { if(sender.state != .Began) { circleModel.scale *= Double(sender.scale); sender.scale = 1; // trajectoryView.distanceToTarget = Double(sender.value); circleView.setNeedsDisplay(); } } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { circleView.setNeedsDisplay(); //super.didRotateFromInterfaceOrientation(fromInterfaceOrientation) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getValues() -> CircleValues { return circleModel.getValues(); } func setRadius(radius: Double) { circleModel.radius = radius; } }
apache-2.0
290d0c8b91a3e2f517f468f69bead050
23.542857
103
0.623399
5.50641
false
false
false
false
Stosyk/stosyk-service
Sources/AppLogic/Models/Admin.swift
1
1081
import Vapor import Fluent final class Admin: Model { enum Keys { static let table = "admins" static let id = "id" static let name = "name" static let email = "email" } var exists: Bool = false var id: Node? var name: String var email: String init(node: Node, in context: Context) throws { name = try node.extract(Keys.name) email = try node.extract(Keys.email) } } // MARK: - extension Admin: NodeRepresentable { func makeNode(context: Context) throws -> Node { var node: [String: NodeConvertible] = [Keys.name: name, Keys.email: email] node[Keys.id] = id?.int return try Node(node: node) } } extension Admin: Preparation { static func prepare(_ database: Database) throws { try database.create(Keys.table) { users in users.id() users.string(Keys.name) users.string(Keys.email) } } static func revert(_ database: Database) throws { try database.delete(Keys.table) } }
mit
ca3f317a6e9be0817c0461d09122e748
22.5
82
0.582794
3.974265
false
false
false
false
svbeemen/Eve
Eve/Eve/CycleNotifications.swift
1
6428
// // CycleNotifications.swift // Eve // // Created by Sangeeta van Beemen on 29/06/15. // Copyright (c) 2015 Sangeeta van Beemen. All rights reserved. // import Foundation import UIKit class CycleNotifications { class var sharedInstance: CycleNotifications { struct Static { static let instance : CycleNotifications = CycleNotifications() } return Static.instance } let savedInformationManager = SavedDataManager.sharedInstance var includeMenstruationNotifications: Bool var includeOvulationNotifications: Bool var includeCautionNotifications: Bool var notificationDates: [CycleDate] init() { self.includeMenstruationNotifications = false self.includeOvulationNotifications = true self.includeCautionNotifications = true self.notificationDates = [CycleDate]() } // Retrieve saved notification settings & dates. func loadNotificationSettings() { if (self.savedInformationManager.defaults.objectForKey("menstruationBool") as? Bool) != nil { self.includeMenstruationNotifications = self.savedInformationManager.defaults.boolForKey("menstruationBool") } if (self.savedInformationManager.defaults.objectForKey("ovulationBool") as? Bool) != nil { self.includeOvulationNotifications = self.savedInformationManager.defaults.boolForKey("ovulationBool") } if (self.savedInformationManager.defaults.objectForKey("cautionBool") as? Bool) != nil { self.includeCautionNotifications = self.savedInformationManager.defaults.boolForKey("cautionBool") } if (self.savedInformationManager.defaults.objectForKey("notificationDates") as? NSData) != nil { let encodedNotificationDates = self.savedInformationManager.defaults.objectForKey("notificationDates") as! NSData self.notificationDates = NSKeyedUnarchiver.unarchiveObjectWithData(encodedNotificationDates) as! [CycleDate] } } // Cancel old notification and schedule new notifications. func scheduleCycleNotifications(menstruationDates: [CycleDate], ovulationDates: [CycleDate], cautionDates: [CycleDate]) { self.notificationDates = [CycleDate]() UIApplication.sharedApplication().cancelAllLocalNotifications() if includeMenstruationNotifications { notificationDates += menstruationDates } if includeOvulationNotifications { notificationDates += ovulationDates } if includeCautionNotifications { notificationDates += cautionDates } self.notificationDates = self.sortNotificationDates(notificationDates) var counter = 0 for notificationDate in notificationDates { if counter < 64 { scheduleANotification(notificationDate) notificationDates = notificationDates.filter({$0.date != notificationDate.date }) counter += 1 } } } // Sort notification dates by ascending order. func sortNotificationDates(datesToSort: [CycleDate]) -> [CycleDate] { let sortedDates = datesToSort.sort({ $0.date.compare($1.date) == NSComparisonResult.OrderedAscending }) return sortedDates } // Set and schedule a notification. func scheduleANotification(date: CycleDate) { let notification = UILocalNotification() notification.alertBody = self.getAlertBodyText(date) notification.alertAction = "open" notification.fireDate = date.date notification.soundName = UILocalNotificationDefaultSoundName notification.category = "EVE_CATEGORY" UIApplication.sharedApplication().scheduleLocalNotification(notification) } // Get text for notification func getAlertBodyText(alertDate: CycleDate) -> String { var bodyText = "" if alertDate.type == "menstruation" { bodyText = "MENSTRUATION DAY! It might not be the most pleasant time of the month, but thankfully you are not pregnant. Good luck!" } else if alertDate.type == "caution" { bodyText = "CAUTION DAY! It's time to watch out and be safe. Have a great day!" } else if alertDate.type == "ovulation" { bodyText = "OVULATION DAY! Whatever you do today, be safe! If you are not safe now, 9 months of sobriety are awaiting you. " } return bodyText } // Refresh notifications func refreshNotifications() { if (savedInformationManager.defaults.objectForKey("notificationdates") as? NSData) != nil { let encodedNotificationDates = savedInformationManager.defaults.objectForKey("notificationdates") as! NSData self.notificationDates = NSKeyedUnarchiver.unarchiveObjectWithData(encodedNotificationDates) as! [CycleDate] } if notificationDates.first != nil { while UIApplication.sharedApplication().scheduledLocalNotifications!.count < 64 { self.sortNotificationDates(notificationDates) let newNotificationDate = notificationDates.first! scheduleANotification(newNotificationDate) } } let encodedNotoficationDates = NSKeyedArchiver.archivedDataWithRootObject(notificationDates) savedInformationManager.defaults.setObject(encodedNotoficationDates, forKey: "notificationdates") } // Save settings of notification buttons and save notification dates. func saveNotificationSettings() { savedInformationManager.defaults.setBool(self.includeMenstruationNotifications, forKey: "menstruationBool") savedInformationManager.defaults.setBool(self.includeOvulationNotifications, forKey: "ovulationBool") savedInformationManager.defaults.setBool(self.includeCautionNotifications, forKey: "cautionBool") let encodedNotoficationDates = NSKeyedArchiver.archivedDataWithRootObject(notificationDates) savedInformationManager.defaults.setObject(encodedNotoficationDates, forKey: "notificationdates") } }
mit
98519fb30914dc0224b240844293b6e3
36.590643
143
0.669415
5.347754
false
false
false
false
julienbodet/wikipedia-ios
WMF Framework/URLSessionTaskOperation.swift
1
1160
import Foundation class URLSessionTaskOperation: AsyncOperation { private let task: URLSessionTask private var observation: NSKeyValueObservation? init(task: URLSessionTask) { self.task = task super.init() if task.priority == 0 { queuePriority = .veryLow } else if task.priority <= URLSessionTask.lowPriority { queuePriority = .low } else if task.priority <= URLSessionTask.defaultPriority { queuePriority = .normal } else if task.priority <= URLSessionTask.highPriority { queuePriority = .high } else { queuePriority = .veryHigh } } deinit { observation?.invalidate() observation = nil } override func execute() { observation = task.observe(\.state, changeHandler: { [weak self] (task, change) in switch task.state { case .completed: self?.observation?.invalidate() self?.observation = nil self?.finish() default: break } }) task.resume() } }
mit
bc7057192abb730980753917a11478a4
27.292683
90
0.551724
5.37037
false
false
false
false
dleonard00/firebase-user-signup
Pods/Material/Sources/MaterialView.swift
1
13589
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(MaterialView) public class MaterialView : UIView { /** A CAShapeLayer used to manage elements that would be affected by the clipToBounds property of the backing layer. For example, this allows the dropshadow effect on the backing layer, while clipping the image to a desired shape within the visualLayer. */ public private(set) lazy var visualLayer: CAShapeLayer = CAShapeLayer() /** A base delegate reference used when subclassing MaterialView. */ public weak var delegate: MaterialDelegate? /** A property that manages an image for the visualLayer's contents property. Images should not be set to the backing layer's contents property to avoid conflicts when using clipsToBounds. */ public var image: UIImage? { didSet { visualLayer.contents = image?.CGImage } } /** Allows a relative subrectangle within the range of 0 to 1 to be specified for the visualLayer's contents property. This allows much greater flexibility than the contentsGravity property in terms of how the image is cropped and stretched. */ public var contentsRect: CGRect { get { return visualLayer.contentsRect } set(value) { visualLayer.contentsRect = value } } /** A CGRect that defines a stretchable region inside the visualLayer with a fixed border around the edge. */ public var contentsCenter: CGRect { get { return visualLayer.contentsCenter } set(value) { visualLayer.contentsCenter = value } } /** A floating point value that defines a ratio between the pixel dimensions of the visualLayer's contents property and the size of the view. By default, this value is set to the MaterialDevice.scale. */ public var contentsScale: CGFloat { get { return visualLayer.contentsScale } set(value) { visualLayer.contentsScale = value } } /// A Preset for the contentsGravity property. public var contentsGravityPreset: MaterialGravity { didSet { contentsGravity = MaterialGravityToString(contentsGravityPreset) } } /// Determines how content should be aligned within the visualLayer's bounds. public var contentsGravity: String { get { return visualLayer.contentsGravity } set(value) { visualLayer.contentsGravity = value } } /** This property is the same as clipsToBounds. It crops any of the view's contents from bleeding past the view's frame. If an image is set using the image property, then this value does not need to be set, since the visualLayer's maskToBounds is set to true by default. */ public var masksToBounds: Bool { get { return layer.masksToBounds } set(value) { layer.masksToBounds = value } } /// A property that accesses the backing layer's backgroundColor. public override var backgroundColor: UIColor? { didSet { layer.backgroundColor = backgroundColor?.CGColor } } /// A property that accesses the layer.frame.origin.x property. public var x: CGFloat { get { return layer.frame.origin.x } set(value) { layer.frame.origin.x = value } } /// A property that accesses the layer.frame.origin.y property. public var y: CGFloat { get { return layer.frame.origin.y } set(value) { layer.frame.origin.y = value } } /** A property that accesses the layer.frame.origin.width property. When setting this property in conjunction with the shape property having a value that is not .None, the height will be adjusted to maintain the correct shape. */ public var width: CGFloat { get { return layer.frame.size.width } set(value) { layer.frame.size.width = value if .None != shape { layer.frame.size.height = value } } } /** A property that accesses the layer.frame.origin.height property. When setting this property in conjunction with the shape property having a value that is not .None, the width will be adjusted to maintain the correct shape. */ public var height: CGFloat { get { return layer.frame.size.height } set(value) { layer.frame.size.height = value if .None != shape { layer.frame.size.width = value } } } /// A property that accesses the backing layer's shadowColor. public var shadowColor: UIColor? { didSet { layer.shadowColor = shadowColor?.CGColor } } /// A property that accesses the backing layer's shadowOffset. public var shadowOffset: CGSize { get { return layer.shadowOffset } set(value) { layer.shadowOffset = value } } /// A property that accesses the backing layer's shadowOpacity. public var shadowOpacity: Float { get { return layer.shadowOpacity } set(value) { layer.shadowOpacity = value } } /// A property that accesses the backing layer's shadowRadius. public var shadowRadius: CGFloat { get { return layer.shadowRadius } set(value) { layer.shadowRadius = value } } /// A property that accesses the backing layer's shadowPath. public var shadowPath: CGPath? { get { return layer.shadowPath } set(value) { layer.shadowPath = value } } /// Enables automatic shadowPath sizing. public var shadowPathAutoSizeEnabled: Bool = true { didSet { if shadowPathAutoSizeEnabled { layoutShadowPath() } else { shadowPath = nil } } } /** A property that sets the shadowOffset, shadowOpacity, and shadowRadius for the backing layer. This is the preferred method of setting depth in order to maintain consitency across UI objects. */ public var depth: MaterialDepth = .None { didSet { let value: MaterialDepthType = MaterialDepthToValue(depth) shadowOffset = value.offset shadowOpacity = value.opacity shadowRadius = value.radius layoutShadowPath() } } /** A property that sets the cornerRadius of the backing layer. If the shape property has a value of .Circle when the cornerRadius is set, it will become .None, as it no longer maintains its circle shape. */ public var cornerRadiusPreset: MaterialRadius = .None { didSet { if let v: MaterialRadius = cornerRadiusPreset { cornerRadius = MaterialRadiusToValue(v) } } } /// A property that accesses the layer.cornerRadius. public var cornerRadius: CGFloat { get { return layer.cornerRadius } set(value) { layer.cornerRadius = value layoutShadowPath() if .Circle == shape { shape = .None } } } /** A property that manages the overall shape for the object. If either the width or height property is set, the other will be automatically adjusted to maintain the shape of the object. */ public var shape: MaterialShape = .None { didSet { if .None != shape { if width < height { frame.size.width = height } else { frame.size.height = width } layoutShadowPath() } } } /// A preset property to set the borderWidth. public var borderWidthPreset: MaterialBorder = .None { didSet { borderWidth = MaterialBorderToValue(borderWidthPreset) } } /// A property that accesses the layer.borderWith. public var borderWidth: CGFloat { get { return layer.borderWidth } set(value) { layer.borderWidth = value } } /// A property that accesses the layer.borderColor property. public var borderColor: UIColor? { get { return nil == layer.borderColor ? nil : UIColor(CGColor: layer.borderColor!) } set(value) { layer.borderColor = value?.CGColor } } /// A property that accesses the layer.position property. public var position: CGPoint { get { return layer.position } set(value) { layer.position = value } } /// A property that accesses the layer.zPosition property. public var zPosition: CGFloat { get { return layer.zPosition } set(value) { layer.zPosition = value } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { contentsGravityPreset = .ResizeAspectFill super.init(coder: aDecoder) prepareView() } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { contentsGravityPreset = .ResizeAspectFill super.init(frame: frame) prepareView() } /// A convenience initializer. public convenience init() { self.init(frame: CGRectNull) } /// Overriding the layout callback for sublayers. public override func layoutSublayersOfLayer(layer: CALayer) { super.layoutSublayersOfLayer(layer) if self.layer == layer { layoutShape() layoutVisualLayer() layoutShadowPath() } } /** A method that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ public func animate(animation: CAAnimation) { animation.delegate = self if let a: CABasicAnimation = animation as? CABasicAnimation { a.fromValue = (nil == layer.presentationLayer() ? layer : layer.presentationLayer() as! CALayer).valueForKeyPath(a.keyPath!) } if let a: CAPropertyAnimation = animation as? CAPropertyAnimation { layer.addAnimation(a, forKey: a.keyPath!) } else if let a: CAAnimationGroup = animation as? CAAnimationGroup { layer.addAnimation(a, forKey: nil) } else if let a: CATransition = animation as? CATransition { layer.addAnimation(a, forKey: kCATransition) } } /** A delegation method that is executed when the backing layer starts running an animation. - Parameter anim: The currently running CAAnimation instance. */ public override func animationDidStart(anim: CAAnimation) { (delegate as? MaterialAnimationDelegate)?.materialAnimationDidStart?(anim) } /** A delegation method that is executed when the backing layer stops running an animation. - Parameter anim: The CAAnimation instance that stopped running. - Parameter flag: A boolean that indicates if the animation stopped because it was completed or interrupted. True if completed, false if interrupted. */ public override func animationDidStop(anim: CAAnimation, finished flag: Bool) { if let a: CAPropertyAnimation = anim as? CAPropertyAnimation { if let b: CABasicAnimation = a as? CABasicAnimation { if let v: AnyObject = b.toValue { if let k: String = b.keyPath { layer.setValue(v, forKeyPath: k) layer.removeAnimationForKey(k) } } } (delegate as? MaterialAnimationDelegate)?.materialAnimationDidStop?(anim, finished: flag) } else if let a: CAAnimationGroup = anim as? CAAnimationGroup { for x in a.animations! { animationDidStop(x, finished: true) } } } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepareView method to initialize property values and other setup operations. The super.prepareView method should always be called immediately when subclassing. */ public func prepareView() { prepareVisualLayer() backgroundColor = MaterialColor.white } /// Prepares the visualLayer property. internal func prepareVisualLayer() { visualLayer.zPosition = 0 visualLayer.masksToBounds = true layer.addSublayer(visualLayer) } /// Manages the layout for the visualLayer property. internal func layoutVisualLayer() { visualLayer.frame = bounds visualLayer.cornerRadius = cornerRadius } /// Manages the layout for the shape of the view instance. internal func layoutShape() { if .Circle == shape { let w: CGFloat = (width / 2) if w != cornerRadius { cornerRadius = w } } } /// Sets the shadow path. internal func layoutShadowPath() { if shadowPathAutoSizeEnabled { if .None == depth { shadowPath = nil } else if nil == shadowPath { shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath } else { animate(MaterialAnimation.shadowPath(UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath, duration: 0)) } } } }
mit
3e4429612383f4ed7760f212bd78d44c
26.232465
127
0.721466
3.911629
false
false
false
false
kentaiwami/masamon
masamon/masamon/ShiftRegister.swift
1
4454
// // ShiftRegister.swift // masamon // // Created by 岩見建汰 on 2015/12/06. // Copyright © 2015年 Kenta. All rights reserved. // import UIKit import RealmSwift class ShiftRegister: UIViewController { //cellの列(日付が記載されている範囲) let cellrow = ["G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ"] let holiday = ["公","夏","有"] //表に記載される休暇日 let staffnumber = 27 //TODO: 仮に設定。あとで入力項目を設ける let mark = "F" var number = 6 // func ShiftDBOnecoursRegist(importname: String, importpath: String){ let documentPath: String = NSBundle.mainBundle().pathForResource("bbb", ofType: "xlsx")! let spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(documentPath) let worksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0] as! BRAWorksheet var date = 11 let staffcellposition = self.StaffCellPositionGet() //スタッフの名前が記載されているセル場所 ex.)F8,F9 var abc = List<ShiftDetailDB>() //30日分繰り返すループ for(var i = 0; i < 30; i++){ let shiftdb = ShiftDB() let shiftdetaildb = ShiftDetailDB() shiftdb.id = DBmethod().DBRecordCount(ShiftDetailDB)/30 //30レコードで1セットのため shiftdb.shiftimportname = importname shiftdb.shiftimportpath = importpath shiftdetaildb.id = i shiftdetaildb.date = date shiftdetaildb.shiftDBrelationship = shiftdb //その日のシフトを全員分調べて出勤者だけ列挙する for(var j = 0; j < staffnumber; j++){ let nowstaff = staffcellposition[j] let replaceday = nowstaff.stringByReplacingOccurrencesOfString("F", withString: cellrow[i]) let dayshift: String = worksheet.cellForCellReference(replaceday).stringValue() let staffname: String = worksheet.cellForCellReference(nowstaff).stringValue() if(holiday.contains(dayshift) == false){ //Holiday以外なら記録 shiftdetaildb.staff = shiftdetaildb.staff + staffname + ":" + dayshift + "," } } //シフトが11日〜来月10日のため日付のリセットを行うか判断 if(date < 30){ date++ }else{ date = 1 } for(var i = 0; i < abc.count; i++){ shiftdb.shiftdetail.append(abc[i]) } shiftdb.shiftdetail.append(shiftdetaildb) let ID = shiftdb.id DBmethod().AddandUpdate(shiftdb, update: true) DBmethod().AddandUpdate(shiftdetaildb, update: false) abc = self.ShiftDBRelationArrayGet(ID) } } //表中にあるスタッフ名の場所を返す func StaffCellPositionGet() -> Array<String>{ let documentPath: String = NSBundle.mainBundle().pathForResource("bbb", ofType: "xlsx")! let spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(documentPath) let worksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0] as! BRAWorksheet var array:[String] = [] while(true){ let Fcell: String = worksheet.cellForCellReference(mark+String(number)).stringValue() if(Fcell.isEmpty){ //セルが空なら進めるだけ number++ }else{ array.append(mark+String(number)) number++ } if(staffnumber == array.count){ //設定したスタッフ人数と取り込み数が一致したら break } } return array } //ShiftDBのリレーションシップ配列を返す func ShiftDBRelationArrayGet(id: Int) -> List<ShiftDetailDB>{ var list = List<ShiftDetailDB>() let realm = try! Realm() list = realm.objects(ShiftDB).filter("id = %@", id)[0].shiftdetail return list } }
mit
6a8b7d0e392109ab7d557a370e436c2f
34.156522
149
0.548355
3.8689
false
false
false
false
cailingyun2010/swift-weibo
微博-S/Classes/Newfeature/WelcomeViewController.swift
1
2821
// // WelcomeViewController.swift // 微博-S // // Created by nimingM on 16/3/18. // Copyright © 2016年 蔡凌云. All rights reserved. // import UIKit import SDWebImage class WelcomeViewController: UIViewController { var bottonCons: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() // 1.添加子控件 view.addSubview(bgIV) view.addSubview(iconView) view.addSubview(messageLabel) // 2.布局位置 bgIV.xmg_Fill(view) // 获得并设置头像的约束 let cons = iconView.xmg_AlignInner(type: XMG_AlignType.BottomCenter, referView: view, size: CGSize(width: 100, height: 100), offset: CGPoint(x: 0, y: -150)) // 拿到头像的底部约束 bottonCons = iconView.xmg_Constraint(cons, attribute: NSLayoutAttribute.Bottom) messageLabel.xmg_AlignVertical(type: XMG_AlignType.BottomCenter, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 20)) // 3.设置头像 if let iconUrl = UserAccount.loadAccount()?.avatar_large { let url = NSURL(string: iconUrl) iconView.sd_setImageWithURL(url) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) bottonCons?.constant = -UIScreen.mainScreen().bounds.height - bottonCons!.constant // 3.执行动画 UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in // 头像动画 self.iconView.layoutIfNeeded() }) { (_) -> Void in // 文本动画 UIView.animateWithDuration( 2.0, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in self.messageLabel.alpha = 1.0 }, completion: { (_) -> Void in print("OK-去主页") NSNotificationCenter.defaultCenter().postNotificationName(XMGSwitchRootViewControllerKey, object: true) }) } } // MARK: 懒加载 private lazy var bgIV: UIImageView = UIImageView(image: UIImage(named: "ad_background")) private lazy var iconView: UIImageView = { let iv = UIImageView(image: UIImage(named: "avatar_default_big")) iv.layer.cornerRadius = 50; iv.clipsToBounds = true return iv }() private lazy var messageLabel: UILabel = { let label = UILabel() label.text = "欢迎回来" label.sizeToFit() label.alpha = 0.0 return label }() }
apache-2.0
fa1de1e52bbe11c30ea582301471cbf9
33.177215
189
0.594074
4.560811
false
false
false
false
xin-wo/kankan
kankan/Pods/Kingfisher/Sources/AnimatedImageView.swift
17
13361
// // AnimatableImageView.swift // Kingfisher // // Created by bl4ckra1sond3tre on 4/22/16. // // The AnimatableImageView, AnimatedFrame and Animator is a modified version of // some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu) // // The MIT License (MIT) // // Copyright (c) 2014-2016 Reda Lemeden. // // 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. // // The name and characters used in the demo of this software are property of their // respective owners. import UIKit import ImageIO /// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image. public class AnimatedImageView: UIImageView { /// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView. class TargetProxy { private weak var target: AnimatedImageView? init(target: AnimatedImageView) { self.target = target } @objc func onScreenUpdate() { target?.updateFrame() } } // MARK: - Public property /// Whether automatically play the animation when the view become visible. Default is true. public var autoPlayAnimatedImage = true /// The size of the frame cache. public var framePreloadCount = 10 /// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true. public var needsPrescaling = true /// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling. public var runLoopMode = NSRunLoopCommonModes { willSet { if runLoopMode == newValue { return } else { stopAnimating() displayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: runLoopMode) displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: newValue) startAnimating() } } } // MARK: - Private property /// `Animator` instance that holds the frames of a specific image in memory. private var animator: Animator? /// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D private var displayLinkInitialized: Bool = false /// A display link that keeps calling the `updateFrame` method on every screen refresh. private lazy var displayLink: CADisplayLink = { self.displayLinkInitialized = true let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: self.runLoopMode) displayLink.paused = true return displayLink }() // MARK: - Override override public var image: Image? { didSet { if image != oldValue { reset() } setNeedsDisplay() layer.setNeedsDisplay() } } deinit { if displayLinkInitialized { displayLink.invalidate() } } override public func isAnimating() -> Bool { if displayLinkInitialized { return !displayLink.paused } else { return super.isAnimating() } } /// Starts the animation. override public func startAnimating() { if self.isAnimating() { return } else { displayLink.paused = false } } /// Stops the animation. override public func stopAnimating() { super.stopAnimating() if displayLinkInitialized { displayLink.paused = true } } override public func displayLayer(layer: CALayer) { if let currentFrame = animator?.currentFrame { layer.contents = currentFrame.CGImage } else { layer.contents = image?.CGImage } } override public func didMoveToWindow() { super.didMoveToWindow() didMove() } override public func didMoveToSuperview() { super.didMoveToSuperview() didMove() } // This is for back compatibility that using regular UIImageView to show GIF. override func shouldPreloadAllGIF() -> Bool { return false } // MARK: - Private method /// Reset the animator. private func reset() { animator = nil if let imageSource = image?.kf_imageSource?.imageRef { animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount) animator?.needsPrescaling = needsPrescaling animator?.prepareFrames() } didMove() } private func didMove() { if autoPlayAnimatedImage && animator != nil { if let _ = superview, _ = window { startAnimating() } else { stopAnimating() } } } /// Update the current frame with the displayLink duration. private func updateFrame() { if animator?.updateCurrentFrame(displayLink.duration) ?? false { layer.setNeedsDisplay() } } } /// Keeps a reference to an `Image` instance and its duration as a GIF frame. struct AnimatedFrame { var image: Image? let duration: NSTimeInterval static func null() -> AnimatedFrame { return AnimatedFrame(image: .None, duration: 0.0) } } // MARK: - Animator /// class Animator { // MARK: Private property private let size: CGSize private let maxFrameCount: Int private let imageSource: CGImageSourceRef private var animatedFrames = [AnimatedFrame]() private let maxTimeStep: NSTimeInterval = 1.0 private var frameCount = 0 private var currentFrameIndex = 0 private var currentPreloadIndex = 0 private var timeSinceLastFrameChange: NSTimeInterval = 0.0 private var needsPrescaling = true /// Loop count of animatd image. private var loopCount = 0 var currentFrame: UIImage? { return frameAtIndex(currentFrameIndex) } var contentMode: UIViewContentMode = .ScaleToFill /** Init an animator with image source reference. - parameter imageSource: The reference of animated image. - parameter contentMode: Content mode of AnimatedImageView. - parameter size: Size of AnimatedImageView. - framePreloadCount: Frame cache size. - returns: The animator object. */ init(imageSource src: CGImageSourceRef, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount: Int) { self.imageSource = src self.contentMode = mode self.size = size self.maxFrameCount = framePreloadCount } func frameAtIndex(index: Int) -> Image? { return animatedFrames[index].image } func prepareFrames() { frameCount = CGImageSourceGetCount(imageSource) if let properties = CGImageSourceCopyProperties(imageSource, nil), gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary, loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int { self.loopCount = loopCount } let frameToProcess = min(frameCount, maxFrameCount) animatedFrames.reserveCapacity(frameToProcess) animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame($1))} } func prepareFrame(index: Int) -> AnimatedFrame { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { return AnimatedFrame.null() } let frameDuration = imageSource.kf_GIFPropertiesAtIndex(index).flatMap { (gifInfo) -> Double? in let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double? let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double? let duration = unclampedDelayTime ?? delayTime /** http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp Many annoying ads specify a 0 duration to make an image flash as quickly as possible. We follow Safari and Firefox's behavior and use a duration of 100 ms for any frames that specify a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser. */ return duration > 0.011 ? duration : 0.100 } let image = Image(CGImage: imageRef) let scaledImage: Image? if needsPrescaling { scaledImage = image.kf_resizeToSize(size, contentMode: contentMode) } else { scaledImage = image } return AnimatedFrame(image: scaledImage, duration: frameDuration ?? 0.0) } /** Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`. */ func updateCurrentFrame(duration: CFTimeInterval) -> Bool { timeSinceLastFrameChange += min(maxTimeStep, duration) guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration where frameDuration <= timeSinceLastFrameChange else { return false } timeSinceLastFrameChange -= frameDuration let lastFrameIndex = currentFrameIndex currentFrameIndex += 1 currentFrameIndex = currentFrameIndex % animatedFrames.count if animatedFrames.count < frameCount { animatedFrames[lastFrameIndex] = prepareFrame(currentPreloadIndex) currentPreloadIndex += 1 currentPreloadIndex = currentPreloadIndex % frameCount } return true } } // MARK: - Resize extension Image { func kf_resizeToSize(size: CGSize, contentMode: UIViewContentMode) -> Image { switch contentMode { case .ScaleAspectFit: let newSize = self.size.kf_sizeConstrainedSize(size) return kf_resizeToSize(newSize) case .ScaleAspectFill: let newSize = self.size.kf_sizeFillingSize(size) return kf_resizeToSize(newSize) default: return kf_resizeToSize(size) } } private func kf_resizeToSize(size: CGSize) -> Image { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) drawInRect(CGRect(origin: CGPoint.zero, size: size)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resizedImage ?? self } } extension CGSize { func kf_sizeConstrainedSize(size: CGSize) -> CGSize { let aspectWidth = round(kf_aspectRatio * size.height) let aspectHeight = round(size.width / kf_aspectRatio) return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } func kf_sizeFillingSize(size: CGSize) -> CGSize { let aspectWidth = round(kf_aspectRatio * size.height) let aspectHeight = round(size.width / kf_aspectRatio) return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } private var kf_aspectRatio: CGFloat { return height == 0.0 ? 1.0 : width / height } } extension CGImageSourceRef { func kf_GIFPropertiesAtIndex(index: Int) -> [String: Double]? { let properties = CGImageSourceCopyPropertiesAtIndex(self, index, nil) as Dictionary? return properties?[kCGImagePropertyGIFDictionary as String] as? [String: Double] } } extension Array { subscript(safe index: Int) -> Element? { return indices ~= index ? self[index] : .None } } private func pure<T>(value: T) -> [T] { return [value] }
mit
987b8f712a8863881cc9e52b8c2c94f2
34.629333
184
0.645536
5.235502
false
false
false
false
ronaldho/visionproject
EMIT/EMIT/Data.swift
1
35481
// // Data.swift // EMIT Project // // Created by Andrew on 21/04/16. // Copyright © 2016 Andrew. All rights reserved. // import Foundation import CoreData import UIKit class Data: NSObject { // // MARK: Medication // static func getAllMedications() -> [Medication]{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "Medication") var medicationArray: [Medication] = [Medication](); do { let results = try managedContext.executeFetchRequest(fetchRequest) let medications = results as! [NSManagedObject] if (medications.count > 0){ for i in 0...medications.count-1 { let name = medications[i].valueForKey("name") as! String; let imageData = medications[i].valueForKey("image") as! NSData?; let croppedImageData = medications[i].valueForKey("croppedImage") as! NSData?; let id = medications[i].valueForKey("id") as! String; let imageUrl = medications[i].valueForKey("imageUrl") as! String?; let pageUrl = medications[i].valueForKey("pageUrl") as! String?; var image: UIImage?; var croppedImage: UIImage?; if (imageData != nil){ image = UIImage(data: imageData!); croppedImage = UIImage(data: croppedImageData!); } let temp: Medication = Medication(withName: name, andImage: image, andCroppedImage: croppedImage, andId: id, andImageUrl: imageUrl, andPageUrl: pageUrl) medicationArray.append(temp); } } else { // No Medications in Core Data } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } return medicationArray; } static func saveMedication(med: Medication) -> String{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext var id = NSUUID().UUIDString var medicationObject: NSManagedObject? if (med.id == "0"){ let entity = NSEntityDescription.entityForName("Medication", inManagedObjectContext:managedContext) medicationObject = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) } else { id = med.id let fetchRequest = NSFetchRequest(entityName: "Medication") fetchRequest.predicate = NSPredicate(format: "id=%@", med.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ medicationObject = info[0] } else { print("Error: trying to saveMedication(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } if medicationObject != nil { if (med.image != nil){ let imageData = UIImageJPEGRepresentation(med.image!, 1) medicationObject!.setValue(imageData, forKey: "image") let croppedImageData = UIImageJPEGRepresentation(med.croppedImage!, 1) medicationObject!.setValue(croppedImageData, forKey: "croppedImage") } else { medicationObject!.setNilValueForKey("image"); medicationObject!.setNilValueForKey("croppedImage"); } medicationObject!.setValue(id, forKey: "id") medicationObject!.setValue(med.name, forKey: "name") medicationObject!.setValue(med.imageUrl, forKey: "imageUrl") medicationObject!.setValue(med.pageUrl, forKey: "pageUrl") } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } return id } static func deleteMedication(med: Medication){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext if (med.id == "0"){ print("Error: trying to delete medication with id == 0"); } else { let fetchRequest = NSFetchRequest(entityName: "Medication") fetchRequest.predicate = NSPredicate(format: "id=%@", med.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ managedContext.deleteObject(info[0]); } else { print("Error: trying to deleteMedication(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } // // MARK: MedicationDosage // static func getMedicationDosagesForMedication(med: Medication) -> [MedicationDosage] { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let dosageFetchRequest = NSFetchRequest(entityName: "MedicationDosage") dosageFetchRequest.predicate = NSPredicate(format: "medicationId=%@", med.id); var dosagesArray = [MedicationDosage]() do { let results = try managedContext.executeFetchRequest(dosageFetchRequest) let dosages = results as! [NSManagedObject] if (dosages.count > 0){ for i in 0...dosages.count-1 { let id = dosages[i].valueForKey("id") as! String; let medId = dosages[i].valueForKey("medicationId") as! String; let dosage = dosages[i].valueForKey("dosage") as! String; let imageUrl = dosages[i].valueForKey("imageUrl") as! String?; let imageData = dosages[i].valueForKey("image") as! NSData?; let croppedImageData = dosages[i].valueForKey("croppedImage") as! NSData?; var image: UIImage?; var croppedImage: UIImage?; if (imageData != nil){ image = UIImage(data: imageData!); croppedImage = UIImage(data: croppedImageData!); } let temp = MedicationDosage(withId: id, andMedicationId: medId, andDosage: dosage, andImageUrl: imageUrl, andImage: image, andCroppedImage: croppedImage) dosagesArray.append(temp) } } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } return dosagesArray } static func saveMedicationDosage(medDosage: MedicationDosage) -> String{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext var id = NSUUID().UUIDString var dosageObject: NSManagedObject? if (medDosage.id == "0"){ let entity = NSEntityDescription.entityForName("MedicationDosage", inManagedObjectContext:managedContext) dosageObject = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) } else { id = medDosage.id let fetchRequest = NSFetchRequest(entityName: "MedicationDosage") fetchRequest.predicate = NSPredicate(format: "id=%@", medDosage.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ dosageObject = info[0] } else { print("Error: trying to saveMedicationDosage(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } if dosageObject != nil { if (medDosage.image != nil){ let imageData = UIImageJPEGRepresentation(medDosage.image!, 1) dosageObject!.setValue(imageData, forKey: "image") let croppedImageData = UIImageJPEGRepresentation(medDosage.croppedImage!, 1) dosageObject!.setValue(croppedImageData, forKey: "croppedImage") } else { dosageObject!.setNilValueForKey("image"); dosageObject!.setNilValueForKey("croppedImage"); } dosageObject!.setValue(id, forKey: "id") dosageObject!.setValue(medDosage.medicationId, forKey: "medicationId") dosageObject!.setValue(medDosage.dosage, forKey: "dosage") dosageObject!.setValue(medDosage.imageUrl, forKey: "imageUrl") } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } return id } static func deleteMedicationDosage(medDosage: MedicationDosage){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext if (medDosage.id == "0"){ print("Error: trying to delete MedicationDosage with id == 0"); } else { let fetchRequest = NSFetchRequest(entityName: "MedicationDosage") fetchRequest.predicate = NSPredicate(format: "id=%@", medDosage.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ managedContext.deleteObject(info[0]); } else { print("Error: trying to deleteMedicationDosage(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } // // MARK: MyMedication // static func getAllMyMedications() -> [MyMedication]{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "MyMedication") var medicationArray: [MyMedication] = [MyMedication](); do { let results = try managedContext.executeFetchRequest(fetchRequest) let medications = results as! [NSManagedObject] if (medications.count > 0){ for i in 0...medications.count-1 { let name = medications[i].valueForKey("name") as! String; let imageData = medications[i].valueForKey("image") as! NSData?; let croppedImageData = medications[i].valueForKey("croppedImage") as! NSData?; let breakfast = medications[i].valueForKey("breakfast") as! Bool; let lunch = medications[i].valueForKey("lunch") as! Bool; let dinner = medications[i].valueForKey("dinner") as! Bool; let bed = medications[i].valueForKey("bed") as! Bool; let id = medications[i].valueForKey("id") as! String; let instructions = medications[i].valueForKey("instructions") as! String; let date = medications[i].valueForKey("date") as! NSDate; let startedDate = medications[i].valueForKey("startedDate") as! NSDate; let discontinuedDate = medications[i].valueForKey("discontinuedDate") as! NSDate?; let discontinued = medications[i].valueForKey("discontinued") as! Bool; let pageUrl = medications[i].valueForKey("pageUrl") as! String?; var image: UIImage?; var croppedImage: UIImage?; if (imageData != nil){ image = UIImage(data: imageData!); croppedImage = UIImage(data: croppedImageData!); } let temp: MyMedication = MyMedication(withName: name, andImage: image, andCroppedImage: croppedImage, andInstructions: instructions, andId: id, andBreakfast: breakfast, andLunch: lunch, andDinner: dinner, andBed: bed, andDate: date, andDiscontinued: discontinued, andStartedDate: startedDate, andDiscontinuedDate: discontinuedDate, andPageUrl: pageUrl); medicationArray.append(temp); } } else { // No Medications in Core Data } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } return medicationArray; } static func saveMyMedication(med: MyMedication) -> String{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext var id = NSUUID().UUIDString var myMedicationObject: NSManagedObject? if (med.id == "0"){ let entity = NSEntityDescription.entityForName("MyMedication", inManagedObjectContext:managedContext) myMedicationObject = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) } else { id = med.id let fetchRequest = NSFetchRequest(entityName: "MyMedication") fetchRequest.predicate = NSPredicate(format: "id=%@", med.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ myMedicationObject = info[0] } else { print("Error: trying to saveMedication(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } if myMedicationObject != nil { if (med.image != nil){ let imageData = UIImageJPEGRepresentation(med.image!, 1) myMedicationObject!.setValue(imageData, forKey: "image") let croppedImageData = UIImageJPEGRepresentation(med.croppedImage!, 1) myMedicationObject!.setValue(croppedImageData, forKey: "croppedImage") } else { myMedicationObject!.setNilValueForKey("image"); myMedicationObject!.setNilValueForKey("croppedImage"); } myMedicationObject!.setValue(id, forKey: "id") myMedicationObject!.setValue(med.name, forKey: "name") myMedicationObject!.setValue(med.instructions, forKey: "instructions") myMedicationObject!.setValue(med.date, forKey: "date") myMedicationObject!.setValue(med.startedDate, forKey: "startedDate") myMedicationObject!.setValue(med.discontinued, forKey: "discontinued") myMedicationObject!.setValue(med.pageUrl, forKey: "pageUrl") if med.discontinuedDate != nil { myMedicationObject!.setValue(med.discontinuedDate, forKey: "discontinuedDate") } else { myMedicationObject!.setNilValueForKey("discontinuedDate") } myMedicationObject!.setValue(med.breakfast, forKey: "breakfast") myMedicationObject!.setValue(med.lunch, forKey: "lunch") myMedicationObject!.setValue(med.dinner, forKey: "dinner") myMedicationObject!.setValue(med.bed, forKey: "bed") } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } return id } static func deleteMyMedication(med: MyMedication){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext if (med.id == "0"){ print("Error: trying to delete medication with id == 0"); } else { let fetchRequest = NSFetchRequest(entityName: "MyMedication") fetchRequest.predicate = NSPredicate(format: "id=%@", med.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ managedContext.deleteObject(info[0]); } else { print("Error: trying to deleteMedication(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } do { try managedContext.save() } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } // // MARK: MyMedicationHistory // static func getMyMedicationHistory(medIdToGet: String) -> [MyMedicationHistory]{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "MyMedicationHistory") fetchRequest.predicate = NSPredicate(format: "medId== %@", medIdToGet) var medicationHistoryArray: [MyMedicationHistory] = [MyMedicationHistory](); do { let results = try managedContext.executeFetchRequest(fetchRequest) let medicationHistories = results as! [NSManagedObject] if (medicationHistories.count > 0){ for i in 0...medicationHistories.count-1 { let id = medicationHistories[i].valueForKey("id") as! String; let medId = medicationHistories[i].valueForKey("medId") as! String; let date = medicationHistories[i].valueForKey("date") as! NSDate; let text = medicationHistories[i].valueForKey("text") as! String; let temp: MyMedicationHistory = MyMedicationHistory(withId: id, andMedId: medId, andDate: date, andText: text) // Insert instead of append so that latest history is at beginning of array medicationHistoryArray.insert(temp, atIndex: 0); } } else { // No MedicationHistories in Core Data } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } return medicationHistoryArray; } static func saveMyMedicationHistory(medHistory: MyMedicationHistory) -> String{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext var id = NSUUID().UUIDString var historyObject: NSManagedObject? if (medHistory.id == "0"){ let entity = NSEntityDescription.entityForName("MyMedicationHistory", inManagedObjectContext:managedContext) historyObject = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) } else { id = medHistory.id let fetchRequest = NSFetchRequest(entityName: "MyMedicationHistory") fetchRequest.predicate = NSPredicate(format: "id=%@", medHistory.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ historyObject = info[0] } else { print("Error: trying to saveMedicationHistory(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } if historyObject != nil { historyObject!.setValue(id, forKey: "id") historyObject!.setValue(medHistory.medId, forKey: "medId") historyObject!.setValue(medHistory.date, forKey: "date") historyObject!.setValue(medHistory.text, forKey: "text") } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } return id } static func deleteMyMedicationHistory(medHistory: MyMedicationHistory){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext if (medHistory.id == "0"){ print("Error: trying to delete medicationHistory with id == 0"); } else { let fetchRequest = NSFetchRequest(entityName: "MyMedicationHistory") fetchRequest.predicate = NSPredicate(format: "id=%@", medHistory.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ managedContext.deleteObject(info[0]); } else { print("Error: trying to deleteMedicationHistory(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } // // MARK: Symptoms // static func getAllSymptoms() -> [Symptom]{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "Symptom") var symptomArray: [Symptom] = [Symptom](); do { let results = try managedContext.executeFetchRequest(fetchRequest) let symptoms = results as! [NSManagedObject] if (symptoms.count > 0){ for i in 0 ... symptoms.count-1 { let id = symptoms[i].valueForKey("id") as! String; let date = symptoms[i].valueForKey("date") as! NSDate; let text = symptoms[i].valueForKey("text") as! String; let tagIDString = symptoms[i].valueForKey("tags") as! String; let imageData = symptoms[i].valueForKey("image") as! NSData?; let croppedImageData = symptoms[i].valueForKey("croppedImage") as! NSData?; var image: UIImage?; var croppedImage: UIImage?; if (imageData != nil){ image = UIImage(data: imageData!); croppedImage = UIImage(data: croppedImageData!); } else { // } let temp: Symptom = Symptom(withId: id, andDate: date, andText: text, andSymptomTags: [], andImage: image, andCroppedImage: croppedImage); temp.symptomTagsFromString(tagIDString); symptomArray.append(temp); } } else { // No MedicationHistories in Core Data } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } return symptomArray; } static func saveSymptom(symptom: Symptom) -> String{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext var id = NSUUID().UUIDString var symptomObject: NSManagedObject? if (symptom.id == "0"){ let entity = NSEntityDescription.entityForName("Symptom", inManagedObjectContext:managedContext) symptomObject = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) } else { id = symptom.id let fetchRequest = NSFetchRequest(entityName: "Symptom") fetchRequest.predicate = NSPredicate(format: "id=%@", symptom.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ symptomObject = info[0] } else { print("Error: trying to saveSymptom(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } if symptomObject != nil { if (symptom.image != nil){ let imageData = UIImageJPEGRepresentation(symptom.image!, 1) symptomObject!.setValue(imageData, forKey: "image") let croppedImageData = UIImageJPEGRepresentation(symptom.croppedImage!, 1) symptomObject!.setValue(croppedImageData, forKey: "croppedImage") } else { symptomObject!.setNilValueForKey("image"); symptomObject!.setNilValueForKey("croppedImage"); } symptomObject!.setValue(id, forKey: "id") symptomObject!.setValue(symptom.date, forKey: "date") symptomObject!.setValue(symptom.text, forKey: "text") symptomObject!.setValue(symptom.symptomTagsToString(), forKey: "tags") } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } return id } static func deleteSymptom(symptom: Symptom){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext if (symptom.id == "0"){ print("Error: trying to delete symptom with id == 0"); } else { let fetchRequest = NSFetchRequest(entityName: "Symptom") fetchRequest.predicate = NSPredicate(format: "id=%@", symptom.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ managedContext.deleteObject(info[0]); } else { print("Error: trying to deleteSymptom(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } // // SymptomTag // static func getAllSymptomTags() -> [SymptomTag]{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "SymptomTag") var symptomTagArray: [SymptomTag] = [SymptomTag](); do { let results = try managedContext.executeFetchRequest(fetchRequest) let symptomTags = results as! [NSManagedObject] if (symptomTags.count > 0){ for i in 0 ... symptomTags.count-1 { let id = symptomTags[i].valueForKey("id") as! String; let name = symptomTags[i].valueForKey("name") as! String; let colorString = symptomTags[i].valueForKey("color") as! String; let enabled = symptomTags[i].valueForKey("enabled") as! Bool; let temp: SymptomTag = SymptomTag(withId: id, andColor: UIColor.getColorFromString(colorString), andName: name, andEnabled: enabled); symptomTagArray.append(temp); } } else { // No MedicationHistories in Core Data } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } return symptomTagArray; } static func saveSymptomTag(symptomTag: SymptomTag) -> String{ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext var id = NSUUID().UUIDString var symptomTagObject: NSManagedObject? if (symptomTag.id == "0"){ let entity = NSEntityDescription.entityForName("SymptomTag", inManagedObjectContext:managedContext) symptomTagObject = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) } else { id = symptomTag.id let fetchRequest = NSFetchRequest(entityName: "SymptomTag") fetchRequest.predicate = NSPredicate(format: "id=%@", symptomTag.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ symptomTagObject = info[0] } else { print("Error: trying to saveSymptomTag(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } if symptomTagObject != nil { symptomTagObject!.setValue(id, forKey: "id") symptomTagObject!.setValue(symptomTag.name, forKey: "name") symptomTagObject!.setValue(symptomTag.enabled, forKey: "enabled") symptomTagObject!.setValue(symptomTag.color.getStringFromColor(), forKey: "color") } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } return id } static func deleteSymptomTag(symptomTag: SymptomTag){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext if (symptomTag.id == "0"){ print("Error: trying to delete symptomTag with id == 0"); } else { let fetchRequest = NSFetchRequest(entityName: "SymptomTag") fetchRequest.predicate = NSPredicate(format: "id=%@", symptomTag.id); do { let results = try managedContext.executeFetchRequest(fetchRequest) let info = results as! [NSManagedObject] if (info.count == 1){ managedContext.deleteObject(info[0]); } else { print("Error: trying to deleteSymptomTag(), but more or less than 1 object was found with the id"); } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } do { try managedContext.save() //5 } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } }
mit
15b314438ab1c9d39b67e71dd070f091
39.969977
373
0.535175
5.548084
false
false
false
false
jcollas/WhirlyGlobeSwift
WhirlyGlobeComponentTester/WhirlyGlobeComponentTester/AnimatedSphere.swift
1
1656
// // AnimationTest.m // WhirlyGlobeComponentTester // // Created by Steve Gifford on 7/31/13. // Copyright (c) 2013 mousebird consulting. All rights reserved. // import WhirlyGlobe class AnimatedSphere : MaplyActiveObject { var start : NSTimeInterval var period : Float var radius : Float var color : UIColor var startPt : MaplyCoordinate? var sphereObj : MaplyComponentObject? init(period: Float, radius: Float, color: UIColor, viewC: MaplyBaseViewController?) { self.period = period self.radius = radius self.color = color start = CFAbsoluteTimeGetCurrent() super.init(viewController: viewC) } func hasUpdate() -> Bool { return true; } func updateForFrame(frameInfo : AnyObject) { if (sphereObj != nil) { self.viewC?.removeObjects([sphereObj!], mode:MaplyThreadCurrent) sphereObj = nil } var t : Float = Float(CFAbsoluteTimeGetCurrent()-start)/period t -= Float(Int(t)) let center = MaplyCoordinateMakeWithDegrees(-180.0+Float(t)*360.0, 0.0) let sphere = MaplyShapeSphere() sphere.radius = radius sphere.center = center // Here's the trick, we must use MaplyThreadCurrent to make this happen right now sphereObj = self.viewC?.addShapes([sphere], desc:[ kMaplyColor: color ], mode:MaplyThreadCurrent) } func shutdown() { if (sphereObj != nil) { self.viewC?.removeObjects([sphereObj!], mode:MaplyThreadCurrent) sphereObj = nil; } } }
apache-2.0
640249729ef60e7f8c6dbdd8e68dfee2
26.616667
105
0.6093
4.235294
false
false
false
false
moyazi/SwiftDayList
SwiftDayList/Days/Day5/Day5LeftView.swift
1
2189
// // Day5LeftView.swift // SwiftDayList // // Created by leoo on 2017/6/5. // Copyright © 2017年 Het. All rights reserved. // import UIKit class Day5LeftView: UIViewController , UIGestureRecognizerDelegate{ var baseImageView:UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.white self.baseImageView = UIImageView(frame:self.view.bounds) self.baseImageView.image = UIImage(named:"left") self.baseImageView.isUserInteractionEnabled = true self.view.addSubview(self.baseImageView) let panGR:UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.viewPan(sender:))) panGR.delegate = self self.baseImageView.addGestureRecognizer(panGR) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func viewPan(sender: UIPanGestureRecognizer) { let _transX = sender.translation(in: self.baseImageView).x let _transY = sender.translation(in: self.baseImageView).y print(_transX,_transY) if (_transY > 0) && (_transY > self.baseImageView.bounds.height/4.0) { self.parent?.dismiss(animated: true, completion: nil) } } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { let pan:UIPanGestureRecognizer = gestureRecognizer as! UIPanGestureRecognizer let _transX = pan.translation(in: self.baseImageView).x if (gestureRecognizer.view == self.baseImageView) && (abs(_transX) > 2) { return false } return true } /* // 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. } */ }
mit
98aa332b119347a83ea704ec2fc18e80
32.630769
121
0.666057
4.67094
false
false
false
false
kyouko-taiga/anzen
Sources/Interpreter/Interpreter.swift
1
17127
import AnzenIR import AST import SystemKit import Utils /// An interpreter for AIR code. public final class Interpreter { /// The standard output of the interpreter. public var stdout: TextOutputStream /// The standard error of the interpreter. public var stderr: TextOutputStream /// The instruction pointer. private var instructionPointer: InstructionPointer? /// The stack frames. private var frames: Stack<Frame> = [] /// The locals of the current frame. private var locals: [Int: Reference] { get { return frames.top!.locals } set { frames.top!.locals = newValue } } public init(stdout: TextOutputStream = System.out, stderr: TextOutputStream = System.err) { self.stdout = stdout self.stderr = stderr } /// Invokes the main function of an AIR unit. /// /// - Note: /// The interpreter operates under the assumption that the AIR unit it is given is well-formed, /// and will unrecoverably fail otherwise. Other runtime errors (e.g. memory errors) trigger /// exceptions that can be caught to produce nicer error reports. public func invoke(function: AIRFunction) throws { instructionPointer = InstructionPointer(atEntryOf: function) frames.push(Frame()) while let instruction = instructionPointer?.next() { switch instruction { case let inst as AllocInst : execute(inst) case let inst as MakeRefInst : execute(inst) case let inst as ExtractInst : try execute(inst) case let inst as CopyInst : try execute(inst) case let inst as MoveInst : try execute(inst) case let inst as BindInst : try execute(inst) case let inst as UnsafeCastInst : try execute(inst) case let inst as RefEqInst : try execute(inst) case let inst as RefNeInst : try execute(inst) case let inst as ApplyInst : try execute(inst) case let inst as PartialApplyInst : try execute(inst) case let inst as DropInst : try execute(inst) case let inst as ReturnInst : try execute(inst) case let inst as BranchInst : try execute(inst) case let inst as JumpInst : try execute(inst) default: fatalError("unexpected instruction '\(instruction.instDescription)'") } } } private func execute(_ inst: AllocInst) { switch inst.type { case let type as AIRStructType: // Create a new unique reference on a struct instance. locals[inst.id] = Reference( to: ValuePointer(to: StructInstance(type: type)), type: type, state: .unique) default: fatalError("no allocator for type '\(inst.type)'") } } private func execute(_ inst: MakeRefInst) { // Create a new unallocated reference. locals[inst.id] = Reference(type: inst.type) } private func execute(_ inst: ExtractInst) throws { // Dereference the struct instance. guard let source = locals[inst.source.id] else { fatalError("invalid or uninitialized register '\(inst.source.id)'") } try source.assertReadable(debugInfo: inst.debugInfo) guard let instance = source.pointer?.pointee as? StructInstance else { fatalError("register '\(inst.source.id)' does not stores a struct instance") } // Dereference the struct's member. guard instance.payload.count > inst.index else { fatalError("struct member index is out of bound") } locals[inst.id] = instance.payload[inst.index] } private func execute(_ inst: CopyInst) throws { // Dereference the source and make sure it is initialized. let source = dereference(value: inst.source) try source.assertReadable(debugInfo: inst.debugInfo?[.rhs] as? DebugInfo ?? inst.debugInfo) // Dereference the target. let target = dereference(register: inst.target) // Copy the source to the target. if let pointer = target.pointer { pointer.pointee = source.pointer!.pointee.copy() } else { target.pointer = ValuePointer(to: source.pointer!.pointee.copy()) target.state = .unique } } private func execute(_ inst: MoveInst) throws { // Dereference the source and make sure it is unique. let source = dereference(value: inst.source) try source.assertReadable(debugInfo: inst.debugInfo?[.rhs] as? DebugInfo ?? inst.debugInfo) switch source.state { case .shared, .borrowed: let range = inst.debugInfo?[.range] as? SourceRange throw MemoryError("cannot move non-unique reference", at: range) default: break } // Dereference the target. let target = dereference(register: inst.target) // Move the source to the target. source.state = .moved if let pointer = target.pointer { pointer.pointee = source.pointer!.pointee } else { target.pointer = ValuePointer(to: source.pointer!.pointee) target.state = .unique } } private func execute(_ inst: BindInst) throws { // Make sure the source is not a constant. guard !(inst.source is AIRConstant) else { let info = inst.source.debugInfo?[.rhs] as? DebugInfo ?? inst.debugInfo let range = info?[.range] as? SourceRange throw MemoryError("cannot form an alias on a constant", at: range) } // Dereference the source and make sure it is initialized. let source = dereference(value: inst.source) try source.assertReadable(debugInfo: inst.debugInfo?[.rhs] as? DebugInfo ?? inst.debugInfo) // Dereference the target and make sure it is not shared. let target = dereference(register: inst.target) if case .shared = target.state { let info = inst.source.debugInfo?[.lhs] as? DebugInfo ?? inst.debugInfo let range = info?[.range] as? SourceRange throw MemoryError("cannot reassign a shared reference", at: range) } // Form the alias. target.pointer = source.pointer // Return the uniqueness fragment to its owner, if any. if case .borrowed(let owner) = target.state, owner != nil { guard case .shared(let count) = owner!.state else { unreachable() } owner!.state = count > 1 ? .shared(count: count - 1) : .unique } // Update the source and target references' capabilities. updateBorrowCapabilities(source: source, target: target) } private func execute(_ inst: UnsafeCastInst) throws { // Dereference the operand and make sure it is initialized. let operand = dereference(value: inst.operand) try operand.assertReadable( debugInfo: inst.debugInfo?[.operand] as? DebugInfo ?? inst.debugInfo) // Optimization opportunity: // Just as C++'s reinterpret_cast, unsafe_cast should actually be a noop. We may however // implement some assertion checks in the future. locals[inst.id] = Reference(to: operand.pointer, type: inst.type, state: operand.state) } private func execute(_ inst: RefEqInst) throws { let container = PrimitiveValue(areSameReferences(inst.lhs, inst.rhs)) locals[inst.id] = Reference(to: ValuePointer(to: container), type: .bool, state: .unique) } private func execute(_ inst: RefNeInst) throws { let container = PrimitiveValue(!areSameReferences(inst.lhs, inst.rhs)) locals[inst.id] = Reference(to: ValuePointer(to: container), type: .bool, state: .unique) } private func execute(_ inst: ApplyInst) throws { // Dereference the callee and make sure it is initialized. let callee = dereference(value: inst.callee) try callee.assertReadable(debugInfo: inst.debugInfo?[.callee] as? DebugInfo ?? inst.debugInfo) guard let container = callee.pointer?.pointee as? FunctionValue else { fatalError("'\(callee)' is not a function") } let function = container.function // Handle built-in funtions. if function.name.starts(with: "__") { locals[inst.id] = try applyBuiltin(name: function.name, arguments: inst.arguments) return } // Prepare the next stack frame. // Notice that all arguments are stored with an offset, so as to reserve %0. var nextFrame = Frame(returnInstructionPointer: instructionPointer, returnID: inst.id) for (i, reference) in container.closure.enumerated() { nextFrame[i + 1] = reference } for (i, argument) in inst.arguments.enumerated() { switch argument { case let constant as AIRConstant: // Create a new unique reference. let value = PrimitiveValue(constant) nextFrame[i + container.closure.count + 1] = Reference( to: ValuePointer(to: value), type: argument.type, state: .unique) case let function as AIRFunction: // Create a new borrowed reference. let value = FunctionValue(function: function) nextFrame[i + container.closure.count + 1] = Reference( to: ValuePointer(to: value), type: argument.type, state: .borrowed(owner: nil)) case let reg as AIRRegister: // Take the reference, as is. nextFrame[i + container.closure.count + 1] = locals[reg.id] default: unreachable() } } frames.push(nextFrame) // Jump into the function. instructionPointer = InstructionPointer(atEntryOf: function) } private func execute(_ inst: PartialApplyInst) throws { // Create the function's closure. var closure: [Reference] = [] for argument in inst.arguments { // Dereference the source and make sure it is initialized. let source = dereference(value: argument) do { try source.assertReadable(debugInfo: inst.debugInfo) } catch var error as MemoryError { if let name = argument.debugInfo?[.name] { // Improve the error message. error.message = "cannot capture '\(name)': \(error.message)" } throw error } // Form the capture. let capturedReference = Reference( to: source.pointer, type: argument.type, state: .uninitialized) updateBorrowCapabilities(source: source, target: capturedReference) closure.append(capturedReference) } let value = FunctionValue(function: inst.function, closure: closure) locals[inst.id] = Reference(to: ValuePointer(to: value), type: inst.type, state: .unique) } private func execute(_ inst: DropInst) throws { frames.top![inst.value.id] = nil // FIXME: Call destructors. } private func execute(_ inst: ReturnInst) throws { // Assign the return value (if any) onto the return register. if let returnValue = inst.value { // Dereference the return value. let returnReference = dereference(value: returnValue) if frames.count > 1 { frames[frames.count - 2][frames.top!.returnID!] = returnReference } } // Pop the current frame. instructionPointer = frames.top!.returnInstructionPointer frames.pop() } private func execute(_ branch: BranchInst) throws { // Dereference the condition. let reference = dereference(value: branch.condition) guard let condition = (reference.pointer?.pointee as? PrimitiveValue)?.value as? Bool else { fatalError("'\(reference)' is not a boolean value") } instructionPointer = condition ? InstructionPointer(in: instructionPointer!.function, atBeginningOf: branch.thenLabel) : InstructionPointer(in: instructionPointer!.function, atBeginningOf: branch.elseLabel) } private func execute(_ jump: JumpInst) throws { instructionPointer = InstructionPointer( in: instructionPointer!.function, atBeginningOf: jump.label) } private func dereference(value airValue: AIRValue) -> Reference { switch airValue { case let register as AIRRegister: return dereference(register: register) case let constant as AIRConstant: let container = PrimitiveValue(constant) return Reference(to: ValuePointer(to: container), type: container.type, state: .unique) case let function as AIRFunction: let container = FunctionValue(function: function) return Reference(to: ValuePointer(to: container), type: container.type, state: .unique) case is AIRNull: return Reference(type: .anything) default: unreachable() } } private func dereference(register airRegister: AIRRegister) -> Reference { guard let reference = locals[airRegister.id] else { fatalError("invalid or uninitialized register '\(airRegister.id)'") } return reference } // MARK: Capabilities helpers private func updateBorrowCapabilities(source: Reference, target: Reference) { switch source.state { case .unique: // The source is unique, so we borrow directly from it. source.state = .shared(count: 1) target.state = .borrowed(owner: source) case .shared(let count): // The source is owner and already shared, so we borrow directly from it. source.state = .shared(count: count + 1) target.state = .borrowed(owner: source) case .borrowed(let owner) where owner != nil: // The source is borrowed, so we borrow from its owner. guard case .shared(let count) = owner!.state else { unreachable() } owner!.state = .shared(count: count + 1) target.state = .borrowed(owner: owner) default: break } } // MARK: Built-in functions /// Computes reference identity. private func areSameReferences(_ lhs: AIRValue, _ rhs: AIRValue) -> Bool { let leftPointer: ValuePointer? switch lhs { case is AIRNull: leftPointer = nil case let register as AIRRegister: leftPointer = locals[register.id]?.pointer default: return false } let rightPointer: ValuePointer? switch rhs { case is AIRNull: rightPointer = nil case let register as AIRRegister: rightPointer = locals[register.id]?.pointer default: return false } return leftPointer === rightPointer } /// Applies a built-in function. private func applyBuiltin(name: String, arguments: [AIRValue]) throws -> Reference? { guard let function = builtinFunctions[name] else { fatalError("unimplemented built-in function '\(name)'") } let argumentContainers = arguments .map(dereference) .map({ $0.pointer!.pointee }) return try function(argumentContainers) } private typealias BuiltinFunction = ([ValueContainer?]) throws -> Reference? private lazy var builtinFunctions: [String: BuiltinFunction] = { var result: [String: BuiltinFunction] = [:] // print result["__print"] = { (arguments: [ValueContainer?]) in if let container = arguments[0] { self.stdout.write("\(container)\n") } else { self.stdout.write("null\n") } return nil } // Int result["__iadd"] = { primitiveBinaryFunction($0, with: (+) as (Int, Int) -> Int) } result["__isub"] = { primitiveBinaryFunction($0, with: (-) as (Int, Int) -> Int) } result["__imul"] = { primitiveBinaryFunction($0, with: (*) as (Int, Int) -> Int) } result["__idiv"] = { primitiveBinaryFunction($0, with: (/) as (Int, Int) -> Int) } result["__ilt"] = { primitiveBinaryFunction($0, with: (<) as (Int, Int) -> Bool) } result["__ile"] = { primitiveBinaryFunction($0, with: (<=) as (Int, Int) -> Bool) } result["__ieq"] = { primitiveBinaryFunction($0, with: (==) as (Int, Int) -> Bool) } result["__ine"] = { primitiveBinaryFunction($0, with: (!=) as (Int, Int) -> Bool) } result["__ige"] = { primitiveBinaryFunction($0, with: (>=) as (Int, Int) -> Bool) } result["__igt"] = { primitiveBinaryFunction($0, with: (>) as (Int, Int) -> Bool) } // Float result["__fadd"] = { primitiveBinaryFunction($0, with: (+) as (Double, Double) -> Double) } result["__fsub"] = { primitiveBinaryFunction($0, with: (-) as (Double, Double) -> Double) } result["__fmul"] = { primitiveBinaryFunction($0, with: (*) as (Double, Double) -> Double) } result["__fdiv"] = { primitiveBinaryFunction($0, with: (/) as (Double, Double) -> Double) } result["__flt"] = { primitiveBinaryFunction($0, with: (<) as (Double, Double) -> Bool) } result["__fle"] = { primitiveBinaryFunction($0, with: (<=) as (Double, Double) -> Bool) } result["__feq"] = { primitiveBinaryFunction($0, with: (==) as (Double, Double) -> Bool) } result["__fne"] = { primitiveBinaryFunction($0, with: (!=) as (Double, Double) -> Bool) } result["__fge"] = { primitiveBinaryFunction($0, with: (>=) as (Double, Double) -> Bool) } result["__fgt"] = { primitiveBinaryFunction($0, with: (>) as (Double, Double) -> Bool) } return result }() } private func primitiveBinaryFunction<T, U>( _ arguments: [ValueContainer?], with fn: (T, T) -> U) -> Reference? where U: PrimitiveType { guard let a = (arguments[0] as? PrimitiveValue)?.value as? T else { return nil } guard let b = (arguments[1] as? PrimitiveValue)?.value as? T else { return nil } let res = PrimitiveValue(fn(a, b)) return Reference(to: ValuePointer(to: res), type: res.type, state: .unique) }
apache-2.0
cec57833467b80c034a907877ca7dd97
35.363057
99
0.655048
4.109165
false
false
false
false
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/SharedModels/AppIcon.swift
2
234
import Foundation public enum AppIcon: String, Codable, CaseIterable, Hashable { case appIcon1 = "appIcon-1" case appIcon2 = "appIcon-2" case appIcon3 = "appIcon-3" case appIcon4 = "appIcon-4" case appIcon5 = "appIcon-5" }
mit
b730aa22a9368f08cd2968e3ae7df8a4
25
62
0.709402
3.391304
false
false
false
false
cpageler93/RAML-Swift
Tests/RAMLTests/TraitTests.swift
1
7600
// // TraitTests.swift // RAMLTests // // Created by Christoph Pageler on 02.07.17. // import XCTest @testable import RAML class TraitTests: XCTestCase { func testBasicTraits() { let ramlString = """ #%RAML 1.0 title: Example with headers traits: chargeable: headers: X-Dept: type: array description: | A department code to be charged. Multiple of such headers are allowed. items: pattern: ^\\d+\\-\\w+$ example: 230-OCTO traceable: headers: X-Tracker: description: A code to track API calls end to end pattern: ^\\w{16}$ example: abcdefghijklmnop """ guard let raml = try? RAML(string: ramlString) else { XCTFail("Parsing should not throw an error") return } guard let traits = raml.traitDefinitions else { XCTFail("No Traits") return } XCTAssertEqual(traits.count, 2) guard let chargeableTrait = raml.traitDefinitionWith(name: "chargeable") else { XCTFail("No Chargeable Trait") return } XCTAssertNil(chargeableTrait.description) XCTAssertNil(chargeableTrait.usage) guard let chargeableTraitHeaders = chargeableTrait.headers else { XCTFail("No Headers in Chargeable Trait") return } XCTAssertEqual(chargeableTraitHeaders.count, 1) guard let xDeptHeader = chargeableTrait.headerWith(key: "X-Dept") else { XCTFail("No X-Dept Header in Chargeable Trait") return } XCTAssertEqual(xDeptHeader.type, HeaderType.array) XCTAssertNotNil(xDeptHeader.description) XCTAssertNil(xDeptHeader.required) guard let xDeptHeaderItems = xDeptHeader.items else { XCTFail("No Items in X-Dept Header") return } XCTAssertEqual(xDeptHeaderItems.pattern, "^\\d+\\-\\w+$") XCTAssertEqual(xDeptHeaderItems.example, "230-OCTO") // // traceable: // headers: // X-Tracker: // description: A code to track API calls end to end // pattern: ^\\w{16}$ // example: abcdefghijklmnop // guard let traceableTrait = raml.traitDefinitionWith(name: "traceable") else { XCTFail("No Traceable Trait") return } XCTAssertNil(traceableTrait.description) XCTAssertNil(traceableTrait.usage) guard let traceableHeaders = traceableTrait.headers else { XCTFail("No Headers in Traceable Trait") return } XCTAssertEqual(traceableHeaders.count, 1) guard let xTrackerHeader = traceableTrait.headerWith(key: "X-Tracker") else { XCTFail("No X-Tracker Header") return } XCTAssertNil(xTrackerHeader.items) XCTAssertNil(xTrackerHeader.required) XCTAssertEqual(xTrackerHeader.description, "A code to track API calls end to end") XCTAssertEqual(xTrackerHeader.pattern, "^\\w{16}$") XCTAssertEqual(xTrackerHeader.example, "abcdefghijklmnop") } func testTraitsWithParameters() { let ramlString = """ #%RAML 1.0 title: Example API resourceTypes: apiResource: get: is: [ { secured : { tokenName: access_token } } ] traits: secured: queryParameters: <<tokenName>>: description: A valid <<tokenName>> is required /servers1: get: is: [ { secured : { tokenName: token } } ] /servers2: get: is: [ secured: { tokenName: access_token }, paged: { maxPages: 10 } ] """ guard let raml = try? RAML(string: ramlString) else { XCTFail("Parsing should not throw an error") return } guard let apiResourceTypeGet = raml.resourceTypeWith(identifier: "apiResource")?.methodWith(type: .get) else { XCTFail("No GET in apiResource ResourceType") return } guard let securedTraitUsage = apiResourceTypeGet.traitUsageWith(name: "secured") else { XCTFail("No secured trait usage in GET") return } XCTAssertEqual(securedTraitUsage.parameterFor(key: "tokenName")?.string, "access_token") guard let securedTrait = raml.traitDefinitionWith(name: "secured") else { XCTFail("No secured trait") return } XCTAssertEqual(securedTrait.queryParameters?.count ?? 0, 1) guard let tokenNameParameter = securedTrait.queryParameterWith(identifier: "<<tokenName>>") else { XCTFail("No <<tokenName>> query Parameter") return } XCTAssertEqual(tokenNameParameter.description, "A valid <<tokenName>> is required") guard let servers1Get = raml.resourceWith(path: "/servers1")?.methodWith(type: .get) else { XCTFail("no GET /servers1 resource") return } guard let servers1GetSecuredTrait = servers1Get.traitUsageWith(name: "secured") else { XCTFail("No secured trait for GET /servers1") return } guard let server1GetSecuredTraitParameters = servers1GetSecuredTrait.parameters else { XCTFail("No Parameters in secure trait for GET /servers1") return } XCTAssertEqual(server1GetSecuredTraitParameters.count, 1) XCTAssertTrue(servers1GetSecuredTrait.hasParameterFor(key: "tokenName")) XCTAssertEqual(servers1GetSecuredTrait.parameterFor(key: "tokenName")?.string, "token") guard let servers2Get = raml.resourceWith(path: "/servers2")?.methodWith(type: .get) else { XCTFail("no GET /servers2 resource") return } guard let servers2GetSecuredTrait = servers2Get.traitUsageWith(name: "secured") else { XCTFail("No secured trait for GET /servers2") return } guard let servers2GetSecuredTraitParameters = servers2GetSecuredTrait.parameters else { XCTFail("No Parameters in secure trait for GET /servers2") return } XCTAssertEqual(servers2GetSecuredTraitParameters.count, 1) XCTAssertTrue(servers2GetSecuredTrait.hasParameterFor(key: "tokenName")) XCTAssertEqual(servers2GetSecuredTrait.parameterFor(key: "tokenName")?.string, "access_token") guard let servers2GetPagedTrait = servers2Get.traitUsageWith(name: "paged") else { XCTFail("No paged trait for GET /servers2") return } guard let servers2GetPagedTraitParameters = servers2GetPagedTrait.parameters else { XCTFail("No Parameters in paged trait for GET /servers2") return } XCTAssertEqual(servers2GetPagedTraitParameters.count, 1) XCTAssertTrue(servers2GetPagedTrait.hasParameterFor(key: "maxPages")) XCTAssertEqual(servers2GetPagedTrait.parameterFor(key: "maxPages")?.int, 10) } }
mit
4cddcb989baa45591b3a3d998362c9ce
34.348837
118
0.577763
4.77687
false
false
false
false
mcgraw/tomorrow
Tomorrow/IGITaskReviewViewController.swift
1
5796
// // IGITaskReviewViewController.swift // Tomorrow // // Created by David McGraw on 1/24/15. // Copyright (c) 2015 David McGraw. All rights reserved. // import UIKit import Realm import pop class IGITaskReviewViewController: GAITrackedViewController { @IBOutlet weak var titleLabel: IGILabel! @IBOutlet weak var task1: IGILabel! @IBOutlet weak var task2: IGILabel! @IBOutlet weak var task3: IGILabel! @IBOutlet weak var completeAction: IGIButton! @IBOutlet weak var info: IGILabel! var userObject: IGIUser? override func viewDidLoad() { super.viewDidLoad() view.userInteractionEnabled = false view.backgroundColor = UIColor.clearColor() let users = IGIUser.allObjects() if users.count > 0 { userObject = users[0] as? IGIUser } else { assertionFailure("Something went wrong! User does not exist so we cannot add taskss!") } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) screenName = "Task Review Screen" if let goal = userObject?.getCurrentGoalUnderEdit() { var index = 0 let count = goal.tasks.count for item in goal.tasks { var task = item as! IGITask let title = task.getTaskTitle() if index == 0 { task1?.text = title } else if index == 1 { task2?.text = title } else if index == 2 { task3?.text = title } index++ } } else { assertionFailure("A goal should exist! No goal with edit_completed == false found.") } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) playIntroductionAnimation() } @IBAction func completeActionPressed(sender: AnyObject) { UIView.animateWithDuration(0.4, animations: { self.titleLabel.alpha = 0.0 self.completeAction.alpha = 0.0 self.info.alpha = 0.0 }) // We're done editing this goal if let goal = userObject?.getCurrentGoalUnderEdit() { RLMRealm.defaultRealm().beginWriteTransaction() goal.edit_completed = true RLMRealm.defaultRealm().commitWriteTransaction() } let goals = IGIGoal.allObjects() println("Goal count is \(goals.count)") if goals.count > 1 { UIView.animateWithDuration(0.5, animations: { self.view.alpha = 0.0 }, completion: { (done) in println("") NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "transitionToTimeline", userInfo: nil, repeats: false) }) } else { let build = GAIDictionaryBuilder.createEventWithCategory("milestone", action: "onboard_completed", label: nil, value: nil).build() GAI.sharedInstance().defaultTracker.send(build as [NSObject: AnyObject]) // Jump the tasks before transitioning to the timeline task1.jumpAnimationToConstant(-300, delayStart: 0) task2.jumpAnimationToConstant(-300, delayStart: 0.3) task3.jumpAnimationToConstant(-300, delayStart: 0.6) NSUserDefaults.standardUserDefaults().setBool(true, forKey: "kOnboardCompleted") NSUserDefaults.standardUserDefaults().synchronize() NSTimer.scheduledTimerWithTimeInterval(1.2, target: self, selector: "transitionToTimeline", userInfo: nil, repeats: false) } } @IBAction func taskEditPressed(sender: AnyObject) { var tag: Int = (sender.tag - 1000) - 1 userObject!.setTaskNeedsEdit(index: UInt(tag)) UIView.animateWithDuration(0.3, animations: { self.titleLabel.alpha = 0.0 self.task1.alpha = 0.0 self.task2.alpha = 0.0 self.task3.alpha = 0.0 self.completeAction.alpha = 0.0 self.info.alpha = 0.0 }, completion: { (done) in println("") // sigh.. self.performSegueWithIdentifier("unwindToTaskEdit", sender: self) }) } func transitionToTimeline() { let total = userObject!.totalUserGoals() if total == 1 { performSegueWithIdentifier("completeTaskSegue", sender: self) } else { performSegueWithIdentifier("unwindToTimeline", sender: self) } } // MARK: Animation func playIntroductionAnimation() { titleLabel.revealView(constant: 50) var anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha) anim.toValue = 1.0 anim.beginTime = CACurrentMediaTime() + 1.0 task1.pop_addAnimation(anim, forKey: "alpha") anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha) anim.toValue = 1.0 anim.beginTime = CACurrentMediaTime() + 2.0 task2.pop_addAnimation(anim, forKey: "alpha") anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha) anim.toValue = 1.0 anim.beginTime = CACurrentMediaTime() + 3.0 task3.pop_addAnimation(anim, forKey: "alpha") completeAction.revealViewWithDelay(constant: 50, delay: 3.5) info.revealViewWithDelay(constant: 25, delay: 3.8) NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "unlockView", userInfo: nil, repeats: false) } func unlockView() { view.userInteractionEnabled = true } }
bsd-2-clause
2e247eec7d1f54e5c890074da8ae7527
33.712575
142
0.586094
4.80597
false
false
false
false
Snowy1803/BreakBaloon-mobile
BreakBaloon/RandGame/RandGameLevelEndNode.swift
1
5413
// // RandGameLevelInfoNode.swift // BreakBaloon // // Created by Emil on 30/07/2016. // Copyright © 2016 Snowy_1803. All rights reserved. // import Foundation import SpriteKit class RandGameLevelEndNode: SKNode { let level: RandGameLevel let replay: SKSpriteNode let back: SKSpriteNode let nextlevel: SKSpriteNode? let stars: SKSpriteNode? init(level: RandGameLevel, scene: RandGameScene, stars: Int, xpBonus: Int = -1) { let isBonusLevel = xpBonus > -1 let successful = scene.points >= level.numberOfBaloons - level.maxMissingBaloonToWin self.level = level replay = SKSpriteNode(imageNamed: "levelreplay") back = SKSpriteNode(imageNamed: "levelback") if successful { nextlevel = SKSpriteNode(imageNamed: "levelnext") self.stars = SKSpriteNode(imageNamed: "levelstars\(stars)") } else { nextlevel = nil self.stars = nil } super.init() zPosition = 1000 let rect = SKShapeNode(rect: CGRect(x: scene.frame.width / 6, y: scene.frame.height / 6, width: scene.frame.width / 1.5, height: scene.frame.height / 1.5)) rect.fillColor = SKColor.lightGray addChild(rect) let tlevel = SKLabelNode(text: String(format: NSLocalizedString("gameinfo.level", comment: "Level n"), level.index + 1)) tlevel.position = CGPoint(x: scene.frame.width / 2, y: scene.frame.height / 6 * 5 - 32) tlevel.fontSize = 24 tlevel.fontColor = SKColor.black tlevel.fontName = "Copperplate-Bold" addChild(tlevel) let tstatus: SKLabelNode if isBonusLevel { tstatus = SKLabelNode(text: String(format: NSLocalizedString("gameinfo.end.bonus", comment: "Level finished with n xp"), xpBonus)) } else { tstatus = SKLabelNode(text: NSLocalizedString("gameinfo.end.\(successful ? "finished" : "failed")", comment: "Level finished")) } tstatus.position = CGPoint(x: scene.frame.width / 2, y: scene.frame.height / 6 * 5 - 128) tstatus.fontSize = 24 tstatus.fontColor = successful ? SKColor.green : SKColor.red tstatus.fontName = "Copperplate-Bold" addChild(tstatus) if !isBonusLevel { let tcomplete = SKLabelNode(text: String(format: NSLocalizedString("gameinfo.complete", comment: "complete: n / n"), scene.points, level.numberOfBaloons - level.maxMissingBaloonToWin)) tcomplete.position = CGPoint(x: scene.frame.width / 2, y: scene.frame.height / 6 * 5 - 160) tcomplete.fontSize = 24 tcomplete.fontColor = SKColor.black tcomplete.fontName = "HelveticaNeue-Bold" addChild(tcomplete) } replay.position = CGPoint(x: scene.frame.width / 2, y: scene.frame.height / 12 * 3) addChild(replay) back.position = CGPoint(x: scene.frame.width / 2 - 80, y: scene.frame.height / 12 * 3) addChild(back) if successful { if let next = level.next, next.playable { nextlevel!.position = CGPoint(x: scene.frame.width / 2 + 80, y: scene.frame.height / 12 * 3) nextlevel!.run(SKAction.repeatForever(SKAction.sequence([SKAction.resize(toWidth: 80, height: 80, duration: 0.6), SKAction.resize(toWidth: 64, height: 64, duration: 0.6)]))) addChild(nextlevel!) } self.stars!.position = CGPoint(x: scene.frame.width / 2, y: scene.frame.height / 6 * 5 - 224) addChild(self.stars!) if stars < 3 { let remaining = SKLabelNode(text: String(format: NSLocalizedString("gameinfo.end.remaining\(level.numberOfBaloons - scene.points == 1 ? ".one" : "")", comment: "n remaining"), level.numberOfBaloons - scene.points)) remaining.fontColor = SKColor.darkGray remaining.fontSize = 20 remaining.fontName = "HelveticaNeue-Bold" remaining.position = CGPoint(x: scene.frame.width / 2, y: scene.frame.height / 6 * 5 - 275) addChild(remaining) } } else { replay.run(SKAction.repeatForever(SKAction.sequence([SKAction.resize(toWidth: 80, height: 80, duration: 0.6), SKAction.resize(toWidth: 64, height: 64, duration: 0.6)]))) } } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } func click(_ touch: CGPoint) { if back.contains(touch) { backToMenu(scene!.view!) } else if replay.contains(touch) { setLevel(level, view: scene!.view!) } else if nextlevel != nil, nextlevel!.contains(touch) { if level.next != nil { setLevel(level.next!, view: scene!.view!) } else { backToMenu(scene!.view!) } } } func backToMenu(_ view: SKView) { let scene = StartScene(size: self.scene!.frame.size) view.presentScene(scene, transition: SKTransition.flipVertical(withDuration: 1)) scene.adjustPosition(false, sizeChange: true) } func setLevel(_ level: RandGameLevel, view: SKView) { if level.playable { level.start(view, transition: SKTransition.fade(with: SKColor.white, duration: 1)) } } }
mit
3c5770d458cec253fde91cb6b6db82ed
44.478992
230
0.609387
4.096896
false
false
false
false
bourvill/HydraKit
HydraKit/Classes/Result.swift
1
969
// // Result.swift // HydraKit // // Created by maxime marinel on 09/07/2017. // import Foundation public class Results<T: HydraObject> { var hydraObject: T.Type var members: [T] = [] var firstPage: Int = 1 var nextPage: Int = 1 var lastPage: Int = 0 var currentPage: Int = 1 var totalItems: Int = 0 init(_ hydraObject: T.Type, json: [String: Any]) { self.hydraObject = hydraObject if (json["@type"] as? String) == "hydra:Collection" { loadCollection(json) } if (json["@type"] as? String) == hydraObject.hydraType() { loadSingle(json) } } private func loadCollection(_ json: [String: Any]) { for member in (json["hydra:member"] as? [[String:Any]]) ?? [] { members.append(hydraObject.init(hydra: member)) } } private func loadSingle(_ json: [String: Any]) { members.append(hydraObject.init(hydra: json)) } }
mit
39e4defa55ab7258cc0a471373734ce5
23.846154
71
0.572755
3.4
false
false
false
false
nodes-vapor/admin-panel
Sources/AdminPanel/Models/AdminPanelUser/Extensions/AdminPanelUser+Submittable.swift
1
3926
import Fluent import Submissions import Sugar import Validation import Vapor extension AdminPanelUser: Submittable { public static func makeAdditionalFields( for submission: Submission?, given user: AdminPanelUser? ) throws -> [Field] { return try [ Field( keyPath: \.email, instance: submission, label: "Email", validators: [.email], asyncValidators: [{ req, _ in guard let submission = submission else { return req.future([]) } return validateThat( only: user, has: submission.email, for: \.email, on: req ) }] ) ] } public func makeSubmission() -> Submission? { return Submission( email: email, name: name, title: title, role: role?.rawValue, oldPassword: role?.rawValue, password: nil, passwordAgain: nil, shouldResetPassword: shouldResetPassword, shouldSpecifyPassword: false ) } public struct Submission: Decodable, Reflectable, FieldsRepresentable, HasUpdatableUsername, HasUpdatablePassword { public static let oldPasswordKey = \Update.oldPassword public static let updatablePasswordKey = \Update.password public static let updatableUsernameKey = \Update.email let email: String? let name: String? let title: String? let role: String? let oldPassword: String? let password: String? let passwordAgain: String? let shouldResetPassword: Bool? let shouldSpecifyPassword: Bool? public static func makeFields(for instance: Submission?) throws -> [Field] { let isPasswordRequired = instance?.shouldSpecifyPassword ?? false return try [ Field( keyPath: \.name, instance: instance, label: "Name", validators: [.count(2...191)] ), Field( keyPath: \.title, instance: instance, label: "Title", validators: [.count(...191)] ), Field( keyPath: \.role, instance: instance, label: "Role", validators: [.count(...191)] ), Field( keyPath: \.password, instance: instance, label: "Password", validators: [.count(8...), .strongPassword()], isRequired: isPasswordRequired, isAbsentWhen: .equal(to: "") ), Field( keyPath: \.passwordAgain, instance: instance, label: "Password again", validators: [Validator("") { guard $0 == instance?.password else { throw BasicValidationError("Passwords do not match") } }], isRequired: isPasswordRequired, isAbsentWhen: .equal(to: "") ), Field( keyPath: \.shouldResetPassword, instance: instance, label: "Should reset password" ), Field( keyPath: \.shouldSpecifyPassword, instance: instance, label: "Specify password" ) ] } } }
mit
0b94c041a396d0cbfc877dd477a16a14
31.716667
84
0.450076
6.068006
false
false
false
false
sandy1108/appcan-ios
AppCanEnginePackager/AppCanEnginePackager/main.swift
1
3191
// // main.swift // AppCanEnginePackager // // Created by CeriNo on 2017/2/8. // Copyright © 2017年 AppCan. All rights reserved. // import Foundation import LzmaSDK_ObjC import Swiftline import Zip var rootURL: URL let args = Args.parsed.flags guard let srcPath = args["src"] else{ fatalError("Invalid Args") } rootURL = URL(fileURLWithPath: srcPath).deletingLastPathComponent() guard rootURL.lastPathComponent == "appcan-ios" else{ fatalError("Invalid rootURL") } //MARK: - build engine let engineBuildCommand: (String) -> Void = { command in let xcodebuild = XcodeBuild(path: .workspace(path: "AppCanEngine.xcworkspace"), command: command, configuration: "Release", scheme: "AppCanEngine", sdk: "iphoneos", currentDirectoryPath: rootURL.path) xcodebuild.runSync() } engineBuildCommand("clean") engineBuildCommand("build") let info = EngineInfo(versionString: args["version"], summary: args["summary"], suffix: args["suffix"]) do{ let archiveFolderURL = rootURL.appendingPathComponent("archives") let tmpFolderURL = archiveFolderURL.appendingPathComponent("tmp") let fm = FileManager.default var isFolder: ObjCBool = false //MARK: create archive folder if !fm.fileExists(atPath: archiveFolderURL.path, isDirectory: &isFolder) || !isFolder.boolValue{ try fm.createDirectory(at: archiveFolderURL, withIntermediateDirectories: true, attributes: nil) } //MARK: create tmp folder if fm.fileExists(atPath: tmpFolderURL.path){ try fm.removeItem(at: tmpFolderURL) } try fm.createDirectory(at: tmpFolderURL, withIntermediateDirectories: true, attributes: nil) //MARK: generate 7z package let _7zURL = tmpFolderURL.appendingPathComponent("package.7z") let writer = LzmaSDKObjCWriter(fileURL: _7zURL) guard writer.addPath(rootURL.appendingPathComponent("AppCanPlugin").path, forPath: "AppCanPlugin") else{ fatalError("AppCanPlugin not exist") } writer.method = LzmaSDKObjCMethodLZMA2 // or LzmaSDKObjCMethodLZMA writer.compressionLevel = 9 try writer.open() writer.write() let packageURL = tmpFolderURL.appendingPathComponent(info.package) try fm.moveItem(atPath: _7zURL.path, toPath: packageURL.path) //MARK: generate engineInfo.xml let xml = info.XMLInfo() let xmlURL = tmpFolderURL.appendingPathComponent("iosEngine.xml") try xml.write(to: xmlURL, atomically: true, encoding: .utf8) //MARK: locate Engine dSYM files let dSYMDirURL = rootURL.appendingPathComponent("dSYM", isDirectory: true) //MARK: export engine archive let archiveURL = archiveFolderURL.appendingPathComponent("\(info.package).zip") if fm.fileExists(atPath: archiveURL.path){ try fm.removeItem(at: archiveURL) } try Zip.zipFiles(paths: [packageURL,dSYMDirURL,xmlURL], zipFilePath: archiveURL, password: nil, progress: nil) //MARK: clean up try fm.removeItem(at: tmpFolderURL) }catch let e as NSError{ fatalError("error: \(e.localizedDescription)") }
lgpl-3.0
046dcc9ff099512f34aafab647e65664
31.530612
114
0.690088
4.189225
false
false
false
false
Webtrekk/webtrekk-ios-sdk
Source/Internal/Utility/ClosedInterval.swift
1
1191
internal extension ClosedRange { func clamp(_ value: Bound) -> Bound { if value < lowerBound { return lowerBound } if value > upperBound { return upperBound } return value } } internal extension ClosedRange where Bound: MinimumMaximumAware { var conditionText: String { if lowerBound.isMinimum && upperBound.isMaximum { return "any value" } if upperBound.isMaximum { return ">= \(lowerBound)" } if lowerBound.isMinimum { return "<= \(upperBound)" } return ">= \(lowerBound) and <= \(upperBound)" } } internal protocol MinimumMaximumAware { var isMaximum: Bool { get } var isMinimum: Bool { get } } extension Float: MinimumMaximumAware { internal var isMaximum: Bool { return sign == .plus && isInfinite } internal var isMinimum: Bool { return sign == .minus && isInfinite } } extension Double: MinimumMaximumAware { internal var isMaximum: Bool { return sign == .plus && isInfinite } internal var isMinimum: Bool { return sign == .minus && isInfinite } } extension Int: MinimumMaximumAware { internal var isMaximum: Bool { return self == .max } internal var isMinimum: Bool { return self == .min } }
mit
5ef0a2bd21b01ae1ffefef396129199f
16.26087
65
0.675063
3.565868
false
false
false
false
tomaz/MassiveViewController
MVVM/MVVMBefore/MVVMBefore/ShowViewController.swift
1
2179
import UIKit private var FolderNameDidChangeContext = 0 private var FolderSizeDidChangeContext = 0 class ShowViewController: UIViewController { deinit { // Remove observer when deallocating. self.folder.removeObserver(self, forKeyPath: "name") self.folder.removeObserver(self, forKeyPath: "size") } // MARK: - Overriden methods override func viewDidLoad() { super.viewDidLoad() // Update our views with current data. self.updateUserInterface() // Setup KVO observer for our folder name and size. self.folder.addObserver(self, forKeyPath: "name", options: nil, context: &FolderNameDidChangeContext) self.folder.addObserver(self, forKeyPath: "size", options: nil, context: &FolderSizeDidChangeContext) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ChangeFolderNameScene" { // When change name view controller is instructed, pass it our folder. let destinationViewController = segue.destinationViewController as! ChangeFolderNameViewController destinationViewController.folder = self.folder } } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if context == &FolderNameDidChangeContext || context == &FolderSizeDidChangeContext { println("ShowViewController: folder name or size changed") self.updateUserInterface() } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } // MARK: - User actions @IBAction func toggleFolderSizeChangeSimulation(sender: UISwitch) { println("ShowViewController: toggling folder size change simulation") self.folder.simulateSizeChanges = sender.on } // MARK: - Helper methods private func updateUserInterface() { println("ShowViewController: updating user interface") let sizeInKB = self.folder.size / 1024 self.folderInfoLabel.text = "\(self.folder.name) (\(sizeInKB) KB)" } // MARK: - Properties private lazy var folder = DataStore.sharedInstance.folderDataForPath("/Some/Folder/Name") @IBOutlet weak var folderInfoLabel: UILabel! }
mit
3229450be9a1061c4ca6affb774640f8
32.523077
153
0.757228
4.264188
false
false
false
false
kharrison/CodeExamples
KeyCommand/KeyCommand/OptionViewController.swift
1
5543
// // OptionViewController.swift // KeyCommand // // Created by Keith Harrison http://useyourloaf.com // Copyright (c) 2016 Keith Harrison. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. import UIKit class OptionViewController: UIViewController { private enum InputKey: String { case low = "1" case medium = "2" case high = "3" } // Override keyCommands and return the three // key commands for this view controller. override var keyCommands: [UIKeyCommand]? { return [ UIKeyCommand(input: InputKey.low.rawValue, modifierFlags: .command, action: #selector(OptionViewController.performCommand(sender:)), discoverabilityTitle: NSLocalizedString("LowPriority", comment: "Low priority")), UIKeyCommand(input: InputKey.medium.rawValue, modifierFlags: .command, action: #selector(OptionViewController.performCommand(sender:)), discoverabilityTitle: NSLocalizedString("MediumPriority", comment: "Medium priority")), UIKeyCommand(input: InputKey.high.rawValue, modifierFlags: .command, action: #selector(OptionViewController.performCommand(sender:)), discoverabilityTitle: NSLocalizedString("HighPriority", comment: "High priority")) ] } @objc func performCommand(sender: UIKeyCommand) { guard let key = InputKey(rawValue: sender.input!) else { return } switch key { case .low: performSegue(withIdentifier: .low, sender: self) case .medium: performSegue(withIdentifier: .medium, sender: self) case .high: performSegue(withIdentifier: .high, sender: self) } } // You can also add key commands without overriding the // keyCommands property. For example you could call the // following function from viewDidLoad: // private func setupCommands() { // let lowCommand = UIKeyCommand(input: InputKey.low.rawValue, // modifierFlags: .command, // action: #selector(OptionViewController.performCommand(sender:)), // discoverabilityTitle: NSLocalizedString("LowPriority", comment: "Low priority")) // addKeyCommand(lowCommand) // // let mediumCommand = UIKeyCommand(input: InputKey.medium.rawValue, // modifierFlags: .command, // action: #selector(OptionViewController.performCommand(sender:)), // discoverabilityTitle: NSLocalizedString("MediumPriority", comment: "Medium priority")) // addKeyCommand(mediumCommand) // // let highCommand = UIKeyCommand(input: InputKey.high.rawValue, // modifierFlags: .command, // action: #selector(OptionViewController.performCommand(sender:)), // discoverabilityTitle: NSLocalizedString("HighPriority", comment: "High priority")) // addKeyCommand(highCommand) // } } extension OptionViewController: SegueHandlerType { enum SegueIdentifier: String { case low case medium case high } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let navController = segue.destination as? UINavigationController, let viewController = navController.topViewController as? DetailViewController else { fatalError("Expected embedded DetailViewController") } switch segueIdentifierForSegue(segue: segue) { case .low: viewController.priority = .low case .medium: viewController.priority = .medium case .high: viewController.priority = .high } } }
bsd-3-clause
ceb1f3680c1b5316b922c75a28a9ecc9
44.065041
129
0.64153
5.294174
false
false
false
false
iOS-Swift-Developers/Swift
Foundation/SortedArrayTest/SortedArrayTest/ViewController.swift
1
8501
// // ViewController.swift // SortedArrayTest // // Created by 韩俊强 on 2017/12/18. // Copyright © 2017年 HaRi. All rights reserved. // /* Swift开发者组织,汇聚Swift开源项目与实用开发技巧,Objective-C | Swift交流!官方付费QQ群:446310206|426087546 */ import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() testInitUnsortedSorts() testInitSortedDoesntResort() testSortedArrayCanUseArbitraryComparisonPredicate() testConvenienceInitsUseLessThan() testInsertAtBeginningPreservesSortOrder() testInsertInMiddlePreservesSortOrder() testInsertAtEndPreservesSortOrder() testInsertAtBeginningReturnsInsertionIndex() testInsertInMiddleReturnsInsertionIndex() testInsertAtEndReturnsInsertionIndex() testInsertInEmptyArrayReturnsInsertionIndex() testInsertEqualElementReturnsCorrectInsertionIndex() testInsertContentsOfPreservesSortOrder() testIndexOfFindsElementInMiddle() testIndexOfFindsFirstElement() testIndexOfFindsLastElement() testIndexOfReturnsNilWhenNotFound() testIndexOfReturnsFirstMatchForDuplicates() testsContains() testMin() testMax() testCustomStringConvertible() testCustomDebugStringConvertible() testFilter() testRemoveAtIndex() testRemoveSubrange() testRemoveFirst() testRemoveFirstN() testRemoveLast() testRemoveLastN() testRemoveAll() testRemoveElementAtBeginningPreservesSortOrder() testRemoveElementInMiddlePreservesSortOrder() testRemoveElementAtEndPreservesSortOrder() testIsEqual() testIsNotEqual() } func testInitUnsortedSorts() { let sut = SortedArray.init(unsorted: [3,2,4,1,5], areInIncreasingOrder: < ) print(sut) //[1, 2, 3, 4, 5] } func testInitSortedDoesntResort() { // Warning: this is not a valid way to create a SortedArray let sut = SortedArray(sorted: [3,2,1]) print(sut) //[3, 2, 1] } func testSortedArrayCanUseArbitraryComparisonPredicate() { struct Person { var firstName: String var lastName: String } let a = Person.init(firstName: "A", lastName: "Joe") let b = Person.init(firstName: "B", lastName: "HaRi") let c = Person.init(firstName: "C", lastName: "Lockey") var sut = SortedArray<Person> { $0.firstName > $1.lastName } sut.insert(contentsOf: [b,a,c]) print(sut.map { $0.firstName }) //["B", "A", "C"] } func testConvenienceInitsUseLessThan() { let sut = SortedArray(unsorted: ["a","c","b"]) print(sut)//["a", "b", "c"] } func testInsertAtBeginningPreservesSortOrder() { var sut = SortedArray(unsorted: 1...3) sut.insert(0) print(sut)//[0, 1, 2, 3] } func testInsertInMiddlePreservesSortOrder() { var sut = SortedArray(unsorted: 1...5) sut.insert(4) print(sut)//[1,2,3,4,4,5] } func testInsertAtEndPreservesSortOrder() { var sut = SortedArray(unsorted: 1...3) sut.insert(5) print(sut)//[1,2,3,5] } func testInsertAtBeginningReturnsInsertionIndex() { var sut = SortedArray(unsorted: [1,2,3]) let index = sut.insert(0) print(index) //0 } func testInsertInMiddleReturnsInsertionIndex() { var sut = SortedArray(unsorted: [1,2,3,5]) let index = sut.insert(4) print(index) //3 } func testInsertAtEndReturnsInsertionIndex() { var sut = SortedArray(unsorted: [1,2,3]) let index = sut.insert(100) print(index) //3 } func testInsertInEmptyArrayReturnsInsertionIndex() { var sut = SortedArray<Int>() let index = sut.insert(10) print(index) //0 } func testInsertEqualElementReturnsCorrectInsertionIndex() { var sut = SortedArray(unsorted: [3,1,0,2,1]) let index = sut.insert(1) print(index) //index == 1 || index == 2 || index == 3 } func testInsertContentsOfPreservesSortOrder() { var sut = SortedArray(unsorted: [10,9,8]) sut.insert(contentsOf: (7...11).reversed()) print(sut) //[7,8,8,9,9,10,10,11] } func testIndexOfFindsElementInMiddle() { let sut = SortedArray(unsorted: ["a","z","r","k"]) let index = sut.index(of: "k") print(index as Any)//1 } func testIndexOfFindsFirstElement() { let sut = SortedArray(sorted: 1..<10) let index = sut.index(of: 1) print(index as Any)//0 } func testIndexOfFindsLastElement() { let sut = SortedArray(sorted: 1..<10) let index = sut.index(of: 9) print(index as Any)//8 } func testIndexOfReturnsNilWhenNotFound() { let sut = SortedArray(unsorted: "Hello World".characters) let index = sut.index(of: "h") print(index as Any) } func testIndexOfReturnsFirstMatchForDuplicates() { let sut = SortedArray(unsorted: "abcabcabc".characters) let index = sut.index(of: "c") print(index as Any) //6 } func testsContains() { let sut = SortedArray(unsorted: "Lorem ipsum".characters) print(sut.contains(" ")) print(sut.contains("a")) } func testMin() { let sut = SortedArray(unsorted: -10...10) print(sut.min() as Any)//-10 } func testMax() { let sut = SortedArray(unsorted: -10...(-1)) print(sut.max() as Any)//-1 } func testCustomStringConvertible() { let sut = SortedArray(unsorted: ["a", "c", "b"]) let description = String(describing: sut) print(description)//["a", "b", "c"] (sorted) } func testCustomDebugStringConvertible() { let sut = SortedArray(unsorted: ["a", "c", "b"]) let description = String(reflecting: sut) print(description)//["a", "b", "c"] (sorted) } func testFilter() { let sut = SortedArray(unsorted: ["a", "b", "c"]) print(sut.filter { $0 != "a" }) //["b", "c"] } func testRemoveAtIndex() { var sut = SortedArray(unsorted: [3,4,2,1]) let removedElement = sut.remove(at: 1) print(sut)//[1,3,4] print(removedElement) //2 } func testRemoveSubrange() { var sut = SortedArray(unsorted: ["a","d","c","b"]) sut.removeSubrange(2..<4) print(sut)//["a","b"] } func testRemoveFirst() { var sut = SortedArray(unsorted: [3,4,2,1]) let removedElement = sut.removeFirst() print(sut)//[2,3,4] print(removedElement)//1 } func testRemoveFirstN() { var sut = SortedArray(unsorted: [3,4,2,1]) sut.removeFirst(2) print(sut)//[3,4] } func testRemoveLast() { var sut = SortedArray(unsorted: [3,4,2,1]) let removedElement = sut.removeLast() print(sut)//[1,2,3] print(removedElement)//4 } func testRemoveLastN() { var sut = SortedArray(unsorted: [3,4,2,1]) sut.removeLast(2) print(sut)//[1,2] } func testRemoveAll() { var sut = SortedArray(unsorted: ["a","d","c","b"]) sut.removeAll() print(sut)//[] } func testRemoveElementAtBeginningPreservesSortOrder() { var sut = SortedArray(unsorted: 1...3) sut.remove(1) print(sut)//[2,3] } func testRemoveElementInMiddlePreservesSortOrder() { var sut = SortedArray(unsorted: 1...5) sut.remove(4) print(sut)//[1,2,3,5] } func testRemoveElementAtEndPreservesSortOrder() { var sut = SortedArray(unsorted: 1...3) sut.remove(3) print(sut)//[1,2] } func testIsEqual() { let sut = SortedArray(unsorted: [3,2,1]) print(sut == SortedArray(unsorted: 1...3))//true } func testIsNotEqual() { let sut = SortedArray(unsorted: 1...3) print(sut != SortedArray(unsorted: 1...4))//true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
528d44488252e1927a0546441f0cf77d
28.704225
83
0.584756
4.107108
false
true
false
false
hikelee/hotel
Sources/Common/Controllers/UserController.swift
1
3706
import Vapor import HTTP import RandomKit import CryptoSwift extension Request{ fileprivate var success:String { return data["success"]?.string ?? "/admin" } } final class UserAdminController: RestController<User> { typealias M = User override var path:String {return "/admin/common/user"} override func postJqGrid(gridResult:GridResult) throws ->GridResult{ var gridResult = gridResult gridResult.rows = gridResult.rows.map{ var node = $0 node["password"]=nil node["salt"]=nil return node } return gridResult } private func handlePassword(model:M) { let salt = String.random(ofLength: 10, using: &Xoroshiro.default) let password = model.password! model.salt = salt model.password = "\(password)-\(salt)".md5() log.info("password:\(password),salt:\(salt)") } override func preEdit(request: Request,model:M) throws -> ResponseRepresentable? { model.password = "" return nil } override func getModel(request:Request) throws -> M{ let model = try super.getModel(request:request) return model } override func preCreate(request:Request,model:M) throws{ if let password = model.password,password.count > 0 { handlePassword(model: model) } } override func preUpdate(request:Request,new:M,old:M) throws{ if let password = new.password,password.count > 0 { handlePassword(model: new) }else{ new.password = old.password new.salt = old.salt } } } final class UserApiController: Controller { let path = "/api/common/user" func render(_ data:[String:Node]) throws ->ResponseRepresentable{ return try droplet.view.make("\(path)Login",data) } override func makeRouter(){ routerGroup.group(path){group in group.get("/login",handler: login) group.post("/login",handler:doLogin) } } //delete model func login(_ request: Request) throws -> ResponseRepresentable { request.user = nil request.channel = nil return try self.render(["success": request.success.makeNode()]) } func doLogin(_ request: Request) throws -> ResponseRepresentable { guard let name = request.data["name"]?.string, let password = request.data["password"]?.string else { return try self.render( ["success" :request.success.makeNode(), "error":true, "message": "登录名和密码都是必填项"]) } if let channel = try Channel.query().filter("name", .equals, name).first(), let md5 = channel.password,let salt = channel.salt{ let s = "\(password)-\(salt)" let newMd5 = s.md5() log.info("original:\(s),md5:\(newMd5),userMd5:\(md5)") if md5 == newMd5{ request.channel = channel return Response(redirect: request.success) } } if let user = try User.query().filter("name", .equals, name).first(), let md5 = user.password,let salt = user.salt{ let s = "\(password)-\(salt)" let newMd5 = s.md5() log.info("original:\(s),md5:\(newMd5),userMd5:\(md5)") if md5 == newMd5{ request.user = user return Response(redirect: request.success) } } return try self.render( ["success":request.success.makeNode(), "error":true, "message": "登录名或者密码错误"]) } }
mit
38d72f724927696c7e9f26efa97a768a
31.442478
86
0.573377
4.25784
false
false
false
false
brunophilipe/tune
tune/Player Interfaces/iTunes/iTunesScripting.swift
1
904
public enum iTunesScripting: String { case PrintSettings = "print settings" case AirplayDevice = "AirPlay device" case Application = "application" case Artwork = "artwork" case AudioCdPlaylist = "audio CD playlist" case AudioCdTrack = "audio CD track" case BrowserWindow = "browser window" case Encoder = "encoder" case EqPreset = "EQ preset" case EqWindow = "EQ window" case FileTrack = "file track" case FolderPlaylist = "folder playlist" case Item = "item" case LibraryPlaylist = "library playlist" case Playlist = "playlist" case PlaylistWindow = "playlist window" case RadioTunerPlaylist = "radio tuner playlist" case SharedTrack = "shared track" case Source = "source" case Track = "track" case UrlTrack = "URL track" case UserPlaylist = "user playlist" case Visual = "visual" case Window = "window" }
gpl-3.0
173acbbbf5ad4bef5fb9b17e7b06402b
33.769231
52
0.678097
4.185185
false
false
false
false
mahuiying0126/MDemo
BangDemo/BangDemo/Modules/Message/control/MessageDetailViewController.swift
1
3224
// // MessageDetailViewController.swift // BangDemo // // Created by yizhilu on 2017/5/22. // Copyright © 2017年 Magic. All rights reserved. // import UIKit class MessageDetailViewController: UIViewController , UIWebViewDelegate{ var messageId : String? /* * 分享信息 **/ var messageTitle : String? var msgImageUrl : String? var msgDetail : String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = Whit self.navigationController?.navigationBar.barTintColor = ColorFromRGB(241, 241, 241, 1.0) UIApplication.shared .statusBarStyle = .default self.navigationItem.leftBarButtonItem = UIBarButtonItem().itemWithTarg(target: self, action: #selector (backBarButtonItemClick), image: "blue_message-return", hightImage: "blue_message-return") self.navigationItem.rightBarButtonItem = UIBarButtonItem().itemWithTarg(target: self, action: #selector (MessageRightBtnClick), image: "blue_btn-share", hightImage: "blue_btn-share") setMessageDetailLayout() } override func viewWillDisappear(_ animated: Bool) { super .viewWillDisappear(animated) self.navigationController?.navigationBar.barTintColor = navColor UIApplication.shared .statusBarStyle = .lightContent } func setMessageDetailLayout() { let courseIdString = articleInfo()+("/")+(self.messageId)! let url = URL.init(string: courseIdString) let request = URLRequest.init(url: url!) self.messageWeb.loadRequest(request) self.view.addSubview(self.messageWeb) } func webViewDidStartLoad(_ webView: UIWebView) { self.tipHUD .show(animated: true) } func webViewDidFinishLoad(_ webView: UIWebView) { //加载完了 self.tipHUD.hide(animated: true) } @objc func backBarButtonItemClick() { self.navigationController?.popViewController(animated: true) } @objc func MessageRightBtnClick() { //分享 } lazy var messageWeb : UIWebView = { let temp = UIWebView.init(frame: CGRect.init(x: 0, y: 0, width: Screen_width, height: Screen_height - 64)) temp.delegate = self return temp }() lazy var tipHUD :MBProgressHUD = { let tempHUD = MBProgressHUD.showAdded(to: self.view, animated: true) tempHUD.mode = MBProgressHUDMode.indeterminate tempHUD.label.text = "正在加载" return tempHUD }() deinit { print("销毁了") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ }
mit
3e2e391147d1309da67ad91895020bbd
29.941748
201
0.647317
4.74256
false
false
false
false
Intercambio/CloudUI
CloudUI/CloudUITests/SettingsDataSourceTests.swift
1
3563
// // SettingsDataSourceTests.swift // CloudUI // // Created by Tobias Kraentzer on 04.03.17. // Copyright © 2017 Tobias Kräntzer. All rights reserved. // import XCTest @testable import CloudUI class SettingsDataSourceTests: XCTestCase, SettingsInteractor { var dataSource: SettingsDataSource? override func setUp() { super.setUp() dataSource = SettingsDataSource(interactor: self, accountIdentifier: "123") } override func tearDown() { dataSource = nil super.tearDown() } func testSettingsItems() { guard let dataSource = self.dataSource else { XCTFail(); return } XCTAssertEqual(dataSource.numberOfSections(), 4) XCTAssertEqual(dataSource.numberOfItems(inSection: 0), 1) XCTAssertEqual(dataSource.numberOfItems(inSection: 1), 2) XCTAssertEqual(dataSource.numberOfItems(inSection: 2), 1) XCTAssertEqual(dataSource.numberOfItems(inSection: 3), 1) var item: FormItem? item = dataSource.item(at: IndexPath(item: 0, section: 0)) as? FormItem XCTAssertEqual(item?.identifier, SettingsKey.Label) item = dataSource.item(at: IndexPath(item: 0, section: 1)) as? FormItem XCTAssertEqual(item?.identifier, SettingsKey.BaseURL) item = dataSource.item(at: IndexPath(item: 1, section: 1)) as? FormItem XCTAssertEqual(item?.identifier, SettingsKey.Username) item = dataSource.item(at: IndexPath(item: 0, section: 2)) as? FormItem XCTAssertEqual(item?.identifier, "password") item = dataSource.item(at: IndexPath(item: 0, section: 3)) as? FormItem XCTAssertEqual(item?.identifier, "remove") } func testUpdateLabel() { guard let dataSource = self.dataSource else { XCTFail(); return } var item: FormTextItem? item = dataSource.item(at: IndexPath(item: 0, section: 0)) as? FormTextItem XCTAssertNil(item?.text) dataSource.setValue("Romeo", forItemAt: IndexPath(item: 0, section: 0)) item = dataSource.item(at: IndexPath(item: 0, section: 0)) as? FormTextItem XCTAssertEqual(item?.text, "Romeo") } // MARK: - SettingsInteractor var identifier: AccountID? = "123" var values: [SettingsKey: Any]? var password: String? func values(forAccountWith identifier: AccountID) -> [SettingsKey: Any]? { guard self.identifier == identifier else { return nil } return values } func password(forAccountWith identifier: AccountID) -> String? { guard self.identifier == identifier else { return nil } return password } func update(accountWith identifier: AccountID, using values: [SettingsKey: Any]) throws -> [SettingsKey: Any]? { guard self.identifier == identifier else { return nil } self.values = values return values } func setPassword(_ password: String?, forAccountWith identifier: AccountID) throws { guard self.identifier == identifier else { return } self.password = password } func remove(accountWith identifier: AccountID) throws { guard self.identifier == identifier else { return } self.identifier = nil self.values = nil self.password = nil } }
gpl-3.0
edee0cc52f19f4ac386c40ed1dfb2387
29.965217
116
0.608818
4.779866
false
true
false
false
DarrenKong/firefox-ios
SyncTests/BatchingClientTests.swift
2
26771
/* 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 Deferred @testable import Sync import XCTest import SwiftyJSON // Always return a gigantic encoded payload. private func massivify<T>(_ record: Record<T>) -> JSON? { return JSON([ "id": record.id, "foo": String(repeating: "X", count: Sync15StorageClient.maxRecordSizeBytes + 1) ]) } private func basicSerializer<T>(record: Record<T>) -> String { return JSON(object: [ "id": record.id, "payload": record.payload.json.dictionaryObject as Any ]).stringValue()! } // Create a basic record with an ID and a title that is the `Site$ID`. private func createRecordWithID(id: String) -> Record<CleartextPayloadJSON> { let jsonString = "{\"id\":\"\(id)\",\"title\": \"\(id)\"}" return Record<CleartextPayloadJSON>(id: id, payload: CleartextPayloadJSON(JSON(parseJSON: jsonString)), modified: 10_000, sortindex: 123, ttl: 1_000_000) } private func assertLinesMatchRecords<T>(lines: [String], records: [Record<T>], serializer: (Record<T>) -> String) { guard lines.count == records.count else { XCTFail("Number of lines mismatch number of records") return } lines.enumerated().forEach { index, line in let record = records[index] XCTAssertEqual(line, serializer(record)) } } private func deferEmptyResponse(token batchToken: BatchToken? = nil, lastModified: Timestamp? = nil) -> Deferred<Maybe<StorageResponse<POSTResult>>> { var headers = [String: Any]() if let lastModified = lastModified { headers["X-Last-Modified"] = lastModified } return deferMaybe( StorageResponse(value: POSTResult(success: [], failed: [:], batchToken: batchToken), metadata: ResponseMetadata(status: 200, headers: headers)) ) } // Small helper operator for comparing query parameters below private func ==(param1: NSURLQueryItem, param2: NSURLQueryItem) -> Bool { return param1.name == param2.name && param1.value == param2.value } private let miniConfig = InfoConfiguration(maxRequestBytes: 1_048_576, maxPostRecords: 2, maxPostBytes: 1_048_576, maxTotalRecords: 10, maxTotalBytes: 104_857_600) class Sync15BatchClientTests: XCTestCase { func testAddLargeRecordFails() { let uploader: BatchUploadFunction = { _ in deferEmptyResponse(lastModified: 10_000) } let serializeRecord = { massivify($0)?.stringValue() } let batch = Sync15BatchClient(config: miniConfig, ifUnmodifiedSince: nil, serializeRecord: serializeRecord, uploader: uploader, onCollectionUploaded: { _ in deferMaybe(Date() as! MaybeErrorType)}) let record = createRecordWithID(id: "A") let result = batch.addRecords([record]).value XCTAssertTrue(result.isFailure) XCTAssertTrue(result.failureValue! is RecordTooLargeError) } func testFailToSerializeRecord() { let uploader: BatchUploadFunction = { _ in deferEmptyResponse(lastModified: 10_000) } let batch = Sync15BatchClient(config: miniConfig, ifUnmodifiedSince: nil, serializeRecord: { _ in nil }, uploader: uploader, onCollectionUploaded: { _ in deferMaybe(Date.now())}) let record = createRecordWithID(id: "A") let result = batch.addRecords([record]).value XCTAssertTrue(result.isFailure) XCTAssertTrue(result.failureValue! is SerializeRecordFailure) } func testBackoffDuringBatchUploading() { let uploader: BatchUploadFunction = { lines, ius, queryParams in deferMaybe(ServerInBackoffError(until: 10_000)) } // Setup a configuration so each batch supports two payloads of two records each let twoRecordBatchesConfig = InfoConfiguration( maxRequestBytes: 1_048_576, maxPostRecords: 1, maxPostBytes: 1_048_576, maxTotalRecords: 4, maxTotalBytes: 104_857_600 ) let batch = Sync15BatchClient(config: twoRecordBatchesConfig, ifUnmodifiedSince: 10_000, serializeRecord: basicSerializer, uploader: uploader, onCollectionUploaded: { _ in deferMaybe(Date.now())}) let record = createRecordWithID(id: "A") batch.addRecords([record]).succeeded() let result = batch.endBatch().value // Verify that when the server goes into backoff, we get those bubbled up through the batching client XCTAssertTrue(result.isFailure) XCTAssertTrue(result.failureValue! is ServerInBackoffError) } func testIfUnmodifiedSinceUpdatesForSinglePOSTs() { var requestCount = 0 var linesSent = [String]() var lastIUS: Timestamp? = 0 // Since we never return a batch token, the batch client won't batch upload and default to single POSTs let uploader: BatchUploadFunction = { lines, ius, _ in linesSent += lines requestCount += 1 switch requestCount { case 1: XCTAssertEqual(ius, 10_000_000) return deferEmptyResponse(lastModified: 20_000) case 2: XCTAssertEqual(ius, 20_000_000) return deferEmptyResponse(lastModified: 30_000) case 3: XCTAssertEqual(ius, 30_000_000) lastIUS = ius return deferEmptyResponse(lastModified: 30_000) default: XCTFail() return deferEmptyResponse(lastModified: 0) } } let singleRecordConfig = InfoConfiguration( maxRequestBytes: 1_048_576, maxPostRecords: 1, maxPostBytes: 1_048_576, maxTotalRecords: 10, maxTotalBytes: 104_857_600 ) let batch = Sync15BatchClient(config: singleRecordConfig, ifUnmodifiedSince: 10_000_000, serializeRecord: basicSerializer, uploader: uploader, onCollectionUploaded: { _ in deferMaybe(Date.now())}) let recordA = createRecordWithID(id: "A") let recordB = createRecordWithID(id: "B") let recordC = createRecordWithID(id: "C") let allRecords = [recordA, recordB, recordC] batch.addRecords([recordA, recordB, recordC]).succeeded() batch.endBatch().succeeded() // Validate number of requests sent XCTAssertEqual(requestCount, 3) // Validate contents sent to the server assertLinesMatchRecords(lines: linesSent, records: allRecords, serializer: basicSerializer) // Validate the last IUS we got is the last request XCTAssertEqual(lastIUS, 30_000_000) } func testUploadBatchUnsupportedBatching() { var requestCount = 0 var uploadedCollectionCount = 0 var linesSent = [String]() // Since we never return a batch token, the batch client won't batch upload and default to single POSTs let uploader: BatchUploadFunction = { lines, ius, _ in linesSent += lines requestCount += 1 return deferEmptyResponse(lastModified: 10_000) } let collectionUploaded: (POSTResult, Timestamp?) -> DeferredTimestamp = { _ in uploadedCollectionCount += 1 return deferMaybe(Date.now()) } // Setup a configuration so we each payload would be one record let twoRecordBatchesConfig = InfoConfiguration( maxRequestBytes: 1_048_576, maxPostRecords: 1, maxPostBytes: 1_048_576, maxTotalRecords: 10, maxTotalBytes: 104_857_600 ) let batch = Sync15BatchClient(config: twoRecordBatchesConfig, ifUnmodifiedSince: 10_000, serializeRecord: basicSerializer, uploader: uploader, onCollectionUploaded: collectionUploaded) let recordA = createRecordWithID(id: "A") let recordB = createRecordWithID(id: "B") let allRecords = [recordA, recordB] batch.addRecords([recordA, recordB]).succeeded() batch.endBatch().succeeded() // Validate number of requests sent. One for the start post, and one for the committing XCTAssertEqual(requestCount, 2) // Validate contents sent to the server assertLinesMatchRecords(lines: linesSent, records: allRecords, serializer: basicSerializer) // Validate we only made 2 calls to collection uploaded since we're doing single POSTs XCTAssertEqual(uploadedCollectionCount, 2) } /** Tests sending a batch consisting of 3 full payloads. This batch is regular in the sense that it should contain a batch=true call, an upload within the batch, and finish with a commit=true upload. */ func testUploadRegularSingleBatch() { var requestCount = 0 var uploadedCollectionCount = 0 var linesSent = [String]() let allRecords: [Record<CleartextPayloadJSON>] = "ABCDEF".reduce([]) { list, char in return list + [createRecordWithID(id: String(char))] } // Since we never return a batch token, the batch client won't batch upload and default to single POSTs let uploader: BatchUploadFunction = { lines, ius, queryParams in linesSent += lines requestCount += 1 switch requestCount { case 1: let expected = URLQueryItem(name: "batch", value: "true") XCTAssertEqual(expected, queryParams![0]) XCTAssertEqual(ius, 10_000) assertLinesMatchRecords(lines: lines, records: Array(allRecords[0..<2]), serializer: basicSerializer) return deferEmptyResponse(token: "1", lastModified: 10_000) case 2: let expected = URLQueryItem(name: "batch", value: "1") XCTAssertEqual(expected, queryParams![0]) XCTAssertEqual(ius, 10_000_000) assertLinesMatchRecords(lines: lines, records: Array(allRecords[2..<4]), serializer: basicSerializer) return deferEmptyResponse(token: "1", lastModified: 10_000) case 3: let expectedBatch = URLQueryItem(name: "batch", value: "1") let expectedCommit = URLQueryItem(name: "commit", value: "true") XCTAssertEqual(expectedBatch, queryParams![0]) XCTAssertEqual(expectedCommit, queryParams![1]) XCTAssertEqual(ius, 10_000_000) assertLinesMatchRecords(lines: lines, records: Array(allRecords[4..<6]), serializer: basicSerializer) return deferEmptyResponse(lastModified: 20_000) default: XCTFail() return deferEmptyResponse(lastModified: 0) } } let collectionUploaded: (POSTResult, Timestamp?) -> DeferredTimestamp = { _ in uploadedCollectionCount += 1 return deferMaybe(Date.now()) } // Setup a configuration so we send 2 records per each payload let twoRecordBatchesConfig = InfoConfiguration( maxRequestBytes: 1_048_576, maxPostRecords: 2, maxPostBytes: 1_048_576, maxTotalRecords: 10, maxTotalBytes: 104_857_600 ) let batch = Sync15BatchClient(config: twoRecordBatchesConfig, ifUnmodifiedSince: 10_000, serializeRecord: basicSerializer, uploader: uploader, onCollectionUploaded: collectionUploaded) batch.addRecords(allRecords).succeeded() batch.endBatch().succeeded() // Validate number of requests sent. One for the start post, and one for the committing XCTAssertEqual(requestCount, 3) // Validate contents sent to the server assertLinesMatchRecords(lines: linesSent, records: allRecords, serializer: basicSerializer) // Validate we only made one call to the collection upload callback XCTAssertEqual(uploadedCollectionCount, 2) XCTAssertEqual(batch.ifUnmodifiedSince!, 20_000_000) } /** Tests pushing a batch where one of the payloads is not at limit. */ func testBatchUploadWithPartialPayload() { var requestCount = 0 var uploadedCollectionCount = 0 var linesSent = [String]() let allRecords: [Record<CleartextPayloadJSON>] = "ABC".reduce([]) { list, char in return list + [createRecordWithID(id: String(char))] } // Since we never return a batch token, the batch client won't batch upload and default to single POSTs let uploader: BatchUploadFunction = { lines, ius, queryParams in linesSent += lines requestCount += 1 switch requestCount { case 1: let expected = URLQueryItem(name: "batch", value: "true") XCTAssertEqual(expected, queryParams![0]) XCTAssertEqual(ius, 10_000) assertLinesMatchRecords(lines: lines, records: Array(allRecords[0..<2]), serializer: basicSerializer) return deferEmptyResponse(token: "1", lastModified: 10_000) case 2: let expectedBatch = URLQueryItem(name: "batch", value: "1") let expectedCommit = URLQueryItem(name: "commit", value: "true") XCTAssertEqual(expectedBatch, queryParams![0]) XCTAssertEqual(expectedCommit, queryParams![1]) XCTAssertEqual(ius, 10_000_000) assertLinesMatchRecords(lines: lines, records: Array(allRecords[2..<3]), serializer: basicSerializer) return deferEmptyResponse(lastModified: 20_000) default: XCTFail() return deferEmptyResponse(lastModified: 0) } } let collectionUploaded: (POSTResult, Timestamp?) -> DeferredTimestamp = { _ in uploadedCollectionCount += 1 return deferMaybe(Date.now()) } // Setup a configuration so we send 2 records per each payload let twoRecordBatchesConfig = InfoConfiguration( maxRequestBytes: 1_048_576, maxPostRecords: 2, maxPostBytes: 1_048_576, maxTotalRecords: 10, maxTotalBytes: 104_857_600 ) let batch = Sync15BatchClient(config: twoRecordBatchesConfig, ifUnmodifiedSince: 10_000, serializeRecord: basicSerializer, uploader: uploader, onCollectionUploaded: collectionUploaded) batch.addRecords(allRecords).succeeded() batch.endBatch().succeeded() // Validate number of requests sent. One for the start post, and one for the committing XCTAssertEqual(requestCount, 2) // Validate contents sent to the server assertLinesMatchRecords(lines: linesSent, records: allRecords, serializer: basicSerializer) // Validate we only made one call to the collection upload callback XCTAssertEqual(uploadedCollectionCount, 2) XCTAssertEqual(batch.ifUnmodifiedSince!, 20_000_000) } /** Attempt to send 3 payloads: 2 which are full, 1 that is partial, within a batch that only supports 5 records. */ func testBatchUploadWithUnevenPayloadsInBatch() { var requestCount = 0 var uploadedCollectionCount = 0 var linesSent = [String]() let allRecords: [Record<CleartextPayloadJSON>] = "ABCDE".reduce([]) { list, char in return list + [createRecordWithID(id: String(char))] } // Since we never return a batch token, the batch client won't batch upload and default to single POSTs let uploader: BatchUploadFunction = { lines, ius, queryParams in linesSent += lines requestCount += 1 switch requestCount { case 1: let expected = URLQueryItem(name: "batch", value: "true") XCTAssertEqual(expected, queryParams![0]) XCTAssertEqual(ius, 10_000) assertLinesMatchRecords(lines: lines, records: Array(allRecords[0..<2]), serializer: basicSerializer) return deferEmptyResponse(token: "1", lastModified: 10_000) case 2: let expectedBatch = URLQueryItem(name: "batch", value: "1") XCTAssertEqual(expectedBatch, queryParams![0]) XCTAssertEqual(ius, 10_000_000) assertLinesMatchRecords(lines: lines, records: Array(allRecords[2..<4]), serializer: basicSerializer) return deferEmptyResponse(lastModified: 10_000) case 3: let expectedBatch = URLQueryItem(name: "batch", value: "1") let expectedCommit = URLQueryItem(name: "commit", value: "true") XCTAssertEqual(expectedBatch, queryParams![0]) XCTAssertEqual(expectedCommit, queryParams![1]) XCTAssertEqual(ius, 10_000_000) assertLinesMatchRecords(lines: lines, records: [allRecords[4]], serializer: basicSerializer) return deferEmptyResponse(lastModified: 20_000) default: XCTFail() return deferEmptyResponse(lastModified: 0) } } let collectionUploaded: (POSTResult, Timestamp?) -> DeferredTimestamp = { _ in uploadedCollectionCount += 1 return deferMaybe(Date.now()) } // Setup a configuration so we send 2 records per each payload let twoRecordBatchesConfig = InfoConfiguration( maxRequestBytes: 1_048_576, maxPostRecords: 2, maxPostBytes: 1_048_576, maxTotalRecords: 5, maxTotalBytes: 104_857_600 ) let batch = Sync15BatchClient(config: twoRecordBatchesConfig, ifUnmodifiedSince: 10_000, serializeRecord: basicSerializer, uploader: uploader, onCollectionUploaded: collectionUploaded) batch.addRecords(allRecords).succeeded() batch.endBatch().succeeded() // Validate number of requests sent. One for the start post, and one for the committing XCTAssertEqual(requestCount, 3) // Validate contents sent to the server assertLinesMatchRecords(lines: linesSent, records: allRecords, serializer: basicSerializer) // Validate we only made one call to the collection upload callback XCTAssertEqual(uploadedCollectionCount, 2) XCTAssertEqual(batch.ifUnmodifiedSince!, 20_000_000) } /** Tests pushing up a single payload as part of a batch. */ func testBatchUploadWithSinglePayload() { var requestCount = 0 var uploadedCollectionCount = 0 var linesSent = [String]() let recordA = createRecordWithID(id: "A") // Since we never return a batch token, the batch client won't batch upload and default to single POSTs let uploader: BatchUploadFunction = { lines, ius, queryParams in linesSent += lines requestCount += 1 switch requestCount { case 1: XCTAssertEqual(ius, 10_000) assertLinesMatchRecords(lines: lines, records: [recordA], serializer: basicSerializer) return deferEmptyResponse(lastModified: 20_000) default: XCTFail() return deferEmptyResponse(lastModified: 0) } } let collectionUploaded: (POSTResult, Timestamp?) -> DeferredTimestamp = { _ in uploadedCollectionCount += 1 return deferMaybe(Date.now()) } // Setup a configuration so we send 2 records per each payload let twoRecordBatchesConfig = InfoConfiguration( maxRequestBytes: 1_048_576, maxPostRecords: 2, maxPostBytes: 1_048_576, maxTotalRecords: 10, maxTotalBytes: 104_857_600 ) let batch = Sync15BatchClient(config: twoRecordBatchesConfig, ifUnmodifiedSince: 10_000, serializeRecord: basicSerializer, uploader: uploader, onCollectionUploaded: collectionUploaded) batch.addRecords([recordA]).succeeded() batch.endBatch().succeeded() // Validate number of requests sent. One for the start post, and one for the committing XCTAssertEqual(requestCount, 1) // Validate contents sent to the server assertLinesMatchRecords(lines: linesSent, records: [recordA], serializer: basicSerializer) // Validate we only made one call to the collection upload callback XCTAssertEqual(uploadedCollectionCount, 1) XCTAssertEqual(batch.ifUnmodifiedSince!, 20_000_000) } func testMultipleBatchUpload() { var requestCount = 0 var uploadedCollectionCount = 0 var linesSent = [String]() let allRecords: [Record<CleartextPayloadJSON>] = "ABCDEFGHIJKL".reduce([]) { list, char in return list + [createRecordWithID(id: String(char))] } // For each upload, verify that we are getting the correct queryParams and records to be sent. let uploader: BatchUploadFunction = { lines, ius, queryParams in linesSent += lines requestCount += 1 switch requestCount { case 1: let expected = URLQueryItem(name: "batch", value: "true") XCTAssertEqual(expected, queryParams![0]) assertLinesMatchRecords(lines: lines, records: Array(allRecords[0..<2]), serializer: basicSerializer) return deferEmptyResponse(token: "1", lastModified: 20_000) case 2: let expectedBatch = URLQueryItem(name: "batch", value: "1") XCTAssertEqual(expectedBatch, queryParams![0]) assertLinesMatchRecords(lines: lines, records: Array(allRecords[2..<4]), serializer: basicSerializer) return deferEmptyResponse(lastModified: 20_000) case 3: let expectedBatch = URLQueryItem(name: "batch", value: "1") let expectedCommit = URLQueryItem(name: "commit", value: "true") XCTAssertEqual(expectedBatch, queryParams![0]) XCTAssertEqual(expectedCommit, queryParams![1]) assertLinesMatchRecords(lines: lines, records: Array(allRecords[4..<6]), serializer: basicSerializer) return deferEmptyResponse(lastModified: 20_000) case 4: let expected = URLQueryItem(name: "batch", value: "true") XCTAssertEqual(expected, queryParams![0]) assertLinesMatchRecords(lines: lines, records: Array(allRecords[6..<8]), serializer: basicSerializer) return deferEmptyResponse(token: "2", lastModified: 30_000) case 5: let expectedBatch = URLQueryItem(name: "batch", value: "2") XCTAssertEqual(expectedBatch, queryParams![0]) assertLinesMatchRecords(lines: lines, records: Array(allRecords[8..<10]), serializer: basicSerializer) return deferEmptyResponse(lastModified: 30_000) case 6: let expectedBatch = URLQueryItem(name: "batch", value: "2") let expectedCommit = URLQueryItem(name: "commit", value: "true") XCTAssertEqual(expectedBatch, queryParams![0]) XCTAssertEqual(expectedCommit, queryParams![1]) assertLinesMatchRecords(lines: lines, records: Array(allRecords[10..<12]), serializer: basicSerializer) return deferEmptyResponse(lastModified: 30_000) default: XCTFail() return deferEmptyResponse(lastModified: 0) } } let collectionUploaded: (POSTResult, Timestamp?) -> DeferredTimestamp = { _ in uploadedCollectionCount += 1 return deferMaybe(Date.now()) } // Setup a configuration so each batch supports two payloads of two records each let twoRecordBatchesConfig = InfoConfiguration( maxRequestBytes: 1_048_576, maxPostRecords: 2, maxPostBytes: 1_048_576, maxTotalRecords: 6, maxTotalBytes: 104_857_600 ) let batch = Sync15BatchClient(config: twoRecordBatchesConfig, ifUnmodifiedSince: 10_000_000, serializeRecord: basicSerializer, uploader: uploader, onCollectionUploaded: collectionUploaded) batch.addRecords(allRecords).succeeded() batch.endBatch().succeeded() // Validate number of requests sent. One for the start post, and one for the committing XCTAssertEqual(requestCount, 6) // Validate contents sent to the server assertLinesMatchRecords(lines: linesSent, records: allRecords, serializer: basicSerializer) // Validate we only called collection uploaded when we start and finish a batch. The uploads inside // a batch should not trigger the callback. XCTAssertEqual(uploadedCollectionCount, 4) } }
mpl-2.0
3471c7c1f486becccf8200a2ba26f320
43.03125
163
0.599006
5.122656
false
true
false
false
toshiapp/toshi-ios-client
Toshi/Controllers/Sign In/SplashViewController.swift
1
9783
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation import UIKit import SweetUIKit import SafariServices let logoTopSpace: CGFloat = 100.0 let logoSize: CGFloat = 54.0 let titleLabelToSpace: CGFloat = 27.0 final class SplashViewController: UIViewController { private lazy var activityView = self.defaultActivityIndicator() private lazy var backgroundImageView: UIImageView = { let imageView = UIImageView(withAutoLayout: true) imageView.contentMode = .scaleAspectFill imageView.isUserInteractionEnabled = true imageView.image = ImageAsset.launch_screen return imageView }() private lazy var logoImageView: UIImageView = { let imageView = UIImageView(withAutoLayout: true) imageView.contentMode = .center imageView.image = ImageAsset.logo return imageView }() private lazy var titleLabel: UILabel = { let label = UILabel(withAutoLayout: true) label.font = Theme.regular(size: 43.0) label.textAlignment = .center label.textColor = Theme.viewBackgroundColor label.numberOfLines = 0 label.text = Localized.welcome_title label.isAccessibilityElement = true return label }() private lazy var subtitleLabel: UILabel = { let label = UILabel(withAutoLayout: true) label.font = Theme.preferredRegular() label.adjustsFontForContentSizeCategory = true label.textColor = Theme.viewBackgroundColor.withAlphaComponent(0.6) label.numberOfLines = 0 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 5 paragraphStyle.alignment = .center let attrString = NSMutableAttributedString(string: Localized.welcome_subtitle) attrString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attrString.length)) label.attributedText = attrString return label }() private lazy var newAccountButton: UIButton = { let button = UIButton(withAutoLayout: true) button.setTitle(Localized.create_account_button_title, for: .normal) button.setTitleColor(Theme.viewBackgroundColor, for: .normal) button.addTarget(self, action: #selector(newAccountPressed(_:)), for: .touchUpInside) button.titleLabel?.font = Theme.preferredTitle3() button.titleLabel?.adjustsFontForContentSizeCategory = true return button }() private lazy var signinButton: UIButton = { let button = UIButton(withAutoLayout: true) button.isUserInteractionEnabled = true button.setTitle(Localized.sign_in_button_title, for: .normal) button.setTitleColor(Theme.viewBackgroundColor, for: .normal) button.addTarget(self, action: #selector(signinPressed(_:)), for: .touchUpInside) button.titleLabel?.font = Theme.preferredRegularMedium() button.titleLabel?.adjustsFontForContentSizeCategory = true return button }() private var cerealToRegister: Cereal? override func viewDidLoad() { super.viewDidLoad() decorateView() setupActivityIndicator() } private func decorateView() { let margin: CGFloat = 15.0 view.addSubview(backgroundImageView) backgroundImageView.fillSuperview() backgroundImageView.addSubview(logoImageView) logoImageView.topAnchor.constraint(equalTo: backgroundImageView.topAnchor, constant: logoTopSpace).isActive = true logoImageView.centerXAnchor.constraint(equalTo: backgroundImageView.centerXAnchor).isActive = true logoImageView.set(height: logoSize) logoImageView.set(width: logoSize) backgroundImageView.addSubview(titleLabel) titleLabel.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 24.0).isActive = true titleLabel.left(to: view, offset: margin) titleLabel.right(to: view, offset: -margin) backgroundImageView.addSubview(subtitleLabel) subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: margin).isActive = true subtitleLabel.left(to: view, offset: margin) subtitleLabel.right(to: view, offset: -margin) subtitleLabel.setContentCompressionResistancePriority(.defaultLow, for: .vertical) backgroundImageView.addSubview(newAccountButton) newAccountButton.left(to: view, offset: margin) newAccountButton.height(.defaultButtonHeight) newAccountButton.right(to: view, offset: -margin) newAccountButton.topToBottom(of: subtitleLabel, offset: margin, relation: .equalOrGreater) backgroundImageView.addSubview(signinButton) signinButton.topToBottom(of: newAccountButton, offset: margin) signinButton.left(to: view, offset: margin) signinButton.right(to: view, offset: -margin) signinButton.height(.defaultButtonHeight) signinButton.bottomAnchor.constraint(equalTo: backgroundImageView.bottomAnchor, constant: -40.0).isActive = true } @objc private func signinPressed(_: UIButton) { let controller = SignInViewController() controller.delegate = self Navigator.push(controller, from: self) } @objc private func newAccountPressed(_: UIButton) { showAcceptTermsAlert() } private func showAcceptTermsAlert() { let alert = UIAlertController(title: Localized.accept_terms_title, message: Localized.accept_terms_text, preferredStyle: .alert) let read = UIAlertAction(title: Localized.accept_terms_action_read, style: .default) { [weak self] _ in guard let url = URL(string: "http://www.toshi.org/terms-of-service/") else { return } guard !UIApplication.isUITesting else { self?.showTestAlert(message: TestOnlyString.readTermsAlertMessage(termsURL: url)) return } let controller = SFSafariViewController(url: url, entersReaderIfAvailable: true) controller.delegate = self controller.preferredControlTintColor = Theme.tintColor self?.present(controller, animated: true, completion: nil) } let cancel = UIAlertAction(title: Localized.cancel_action_title, style: .default) { _ in self.cerealToRegister = nil alert.dismiss(animated: true, completion: nil) } let agree = UIAlertAction(title: Localized.accept_terms_action_agree, style: .cancel) { [weak self] _ in self?.attemptUserCreation() } alert.addAction(read) alert.addAction(cancel) alert.addAction(agree) present(alert, animated: true, completion: nil) } private func attemptUserCreation() { newAccountButton.isEnabled = false signinButton.isEnabled = false showActivityIndicator() if let existingSeedCereal = cerealToRegister { Cereal.setSharedCereal(existingSeedCereal) } SessionManager.shared.createNewUser { [weak self] success in self?.newAccountButton.isEnabled = true self?.signinButton.isEnabled = true self?.hideActivityIndicator() guard success else { guard let status = Navigator.tabbarController?.reachabilityManager.currentReachabilityStatus else { // Can't check status but just to be safe: self?.showCheckConnectionError() return } switch status { case .notReachable: // The user definitely does not have internet. self?.showCheckConnectionError() case .reachableViaWiFi, .reachableViaWWAN: // The user definitely has internet, it's something else. self?.showGenericCreateAccountError() } return } Navigator.tabbarController?.setupControllers() self?.dismiss(animated: true, completion: nil) } } func showCheckConnectionError() { showErrorOKAlert(message: Localized.alert_no_internet_message) } func showGenericCreateAccountError() { showErrorOKAlert(message: Localized.error_message_account_create) } } extension SplashViewController: ActivityIndicating { var activityIndicator: UIActivityIndicatorView { return activityView } } extension SplashViewController: SignInViewControllerDelegate { func didRequireNewAccountCreation(_ controller: SignInViewController, registrationCereal: Cereal) { cerealToRegister = registrationCereal navigationController?.popToViewController(self, animated: true) self.showAcceptTermsAlert() } } extension SplashViewController: SFSafariViewControllerDelegate { func safariViewControllerDidFinish(_ controller: SFSafariViewController) { showAcceptTermsAlert() } }
gpl-3.0
9fd5517e7d1c46adbb659f055b521b7d
36.197719
136
0.677093
5.271013
false
false
false
false
randallli/material-components-ios
components/TextFields/examples/TextFieldFilledExample.swift
1
17299
/* Copyright 2017-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // swiftlint:disable function_body_length import MaterialComponents.MaterialTextFields final class TextFieldFilledSwiftExample: UIViewController { let scrollView = UIScrollView() var colorScheme = MDCSemanticColorScheme() var typographyScheme = MDCTypographyScheme() let name: MDCTextField = { let name = MDCTextField() name.translatesAutoresizingMaskIntoConstraints = false name.autocapitalizationType = .words return name }() let address: MDCTextField = { let address = MDCTextField() address.translatesAutoresizingMaskIntoConstraints = false address.autocapitalizationType = .words return address }() let city: MDCTextField = { let city = MDCTextField() city.translatesAutoresizingMaskIntoConstraints = false city.autocapitalizationType = .words return city }() let cityController: MDCTextInputControllerFilled let state: MDCTextField = { let state = MDCTextField() state.translatesAutoresizingMaskIntoConstraints = false state.autocapitalizationType = .allCharacters return state }() let stateController: MDCTextInputControllerFilled let zip: MDCTextField = { let zip = MDCTextField() zip.translatesAutoresizingMaskIntoConstraints = false return zip }() let zipController: MDCTextInputControllerFilled let phone: MDCTextField = { let phone = MDCTextField() phone.translatesAutoresizingMaskIntoConstraints = false return phone }() let message: MDCMultilineTextField = { let message = MDCMultilineTextField() message.translatesAutoresizingMaskIntoConstraints = false return message }() var allTextFieldControllers = [MDCTextInputControllerFilled]() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { cityController = MDCTextInputControllerFilled(textInput: city) stateController = MDCTextInputControllerFilled(textInput: state) zipController = MDCTextInputControllerFilled(textInput: zip) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white:0.97, alpha: 1.0) title = "Material Filled Text Field" setupScrollView() setupTextFields() registerKeyboardNotifications() addGestureRecognizer() let styleButton = UIBarButtonItem(title: "Style", style: .plain, target: self, action: #selector(buttonDidTouch(sender: ))) self.navigationItem.rightBarButtonItem = styleButton } func setupTextFields() { scrollView.addSubview(name) let nameController = MDCTextInputControllerFilled(textInput: name) name.delegate = self name.text = "Grace Hopper" nameController.placeholderText = "Name" nameController.helperText = "First and Last" allTextFieldControllers.append(nameController) scrollView.addSubview(address) let addressController = MDCTextInputControllerFilled(textInput: address) address.delegate = self addressController.placeholderText = "Address" allTextFieldControllers.append(addressController) scrollView.addSubview(city) city.delegate = self cityController.placeholderText = "City" allTextFieldControllers.append(cityController) // In iOS 9+, you could accomplish this with a UILayoutGuide. // TODO: (larche) add iOS version specific implementations let stateZip = UIView() stateZip.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(stateZip) stateZip.addSubview(state) state.delegate = self stateController.placeholderText = "State" allTextFieldControllers.append(stateController) stateZip.addSubview(zip) zip.delegate = self zipController.placeholderText = "Zip Code" zipController.helperText = "XXXXX" allTextFieldControllers.append(zipController) scrollView.addSubview(phone) let phoneController = MDCTextInputControllerFilled(textInput: phone) phone.delegate = self phoneController.placeholderText = "Phone Number" allTextFieldControllers.append(phoneController) scrollView.addSubview(message) let messageController = MDCTextInputControllerFilled(textInput: message) message.textView?.delegate = self #if swift(>=3.2) message.text = """ This is where you could put a multi-line message like an email. It can even handle new lines. """ #else message.text = "This is where you could put a multi-line message like an email.\n\nIt can even handle new lines." #endif messageController.placeholderText = "Message" allTextFieldControllers.append(messageController) var tag = 0 for controller in allTextFieldControllers { guard let textField = controller.textInput as? MDCTextField else { continue } style(textInputController: controller); textField.tag = tag tag += 1 } let views = [ "name": name, "address": address, "city": city, "stateZip": stateZip, "phone": phone, "message": message ] var constraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[name]-[address]-[city]-[stateZip]-[phone]-[message]", options: [.alignAllLeading, .alignAllTrailing], metrics: nil, views: views) constraints += [NSLayoutConstraint(item: name, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leadingMargin, multiplier: 1, constant: 0)] constraints += [NSLayoutConstraint(item: name, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailingMargin, multiplier: 1, constant: 0)] constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[name]|", options: [], metrics: nil, views: views) #if swift(>=3.2) if #available(iOS 11.0, *) { constraints += [NSLayoutConstraint(item: name, attribute: .top, relatedBy: .equal, toItem: scrollView.contentLayoutGuide, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: message, attribute: .bottom, relatedBy: .equal, toItem: scrollView.contentLayoutGuide, attribute: .bottomMargin, multiplier: 1, constant: -20)] } else { constraints += [NSLayoutConstraint(item: name, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: message, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottomMargin, multiplier: 1, constant: -20)] } #else constraints += [NSLayoutConstraint(item: name, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: message, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottomMargin, multiplier: 1, constant: -20)] #endif let stateZipViews = [ "state": state, "zip": zip ] constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[state(80)]-[zip]|", options: [.alignAllTop], metrics: nil, views: stateZipViews) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[state]|", options: [], metrics: nil, views: stateZipViews) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[zip]|", options: [], metrics: nil, views: stateZipViews) NSLayoutConstraint.activate(constraints) } func setupScrollView() { view.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate(NSLayoutConstraint.constraints( withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView])) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView])) let marginOffset: CGFloat = 16 let margins = UIEdgeInsets(top: 0, left: marginOffset, bottom: 0, right: marginOffset) scrollView.layoutMargins = margins } func style(textInputController : MDCTextInputControllerFilled) { MDCFilledTextFieldColorThemer.applySemanticColorScheme(colorScheme, to: textInputController) MDCTextFieldTypographyThemer.applyTypographyScheme(typographyScheme, to: textInputController) } func addGestureRecognizer() { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapDidTouch(sender: ))) self.scrollView.addGestureRecognizer(tapRecognizer) } // MARK: - Actions @objc func tapDidTouch(sender: Any) { self.view.endEditing(true) } @objc func buttonDidTouch(sender: Any) { let isFloatingEnabled = allTextFieldControllers.first?.isFloatingEnabled ?? false let alert = UIAlertController(title: "Floating Labels", message: nil, preferredStyle: .actionSheet) let defaultAction = UIAlertAction(title: "Default (Yes)" + (isFloatingEnabled ? " ✓" : ""), style: .default) { _ in self.allTextFieldControllers.forEach({ (controller) in controller.isFloatingEnabled = true }) } alert.addAction(defaultAction) let floatingAction = UIAlertAction(title: "No" + (isFloatingEnabled ? "" : " ✓"), style: .default) { _ in self.allTextFieldControllers.forEach({ (controller) in controller.isFloatingEnabled = false }) } alert.addAction(floatingAction) present(alert, animated: true, completion: nil) } } extension TextFieldFilledSwiftExample: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let rawText = textField.text else { return true } let fullString = NSString(string: rawText).replacingCharacters(in: range, with: string) if textField == state { if let range = fullString.rangeOfCharacter(from: CharacterSet.letters.inverted), fullString[range].characterCount > 0 { stateController.setErrorText("Error: State can only contain letters", errorAccessibilityValue: nil) } else { stateController.setErrorText(nil, errorAccessibilityValue: nil) } } else if textField == zip { if let range = fullString.rangeOfCharacter(from: CharacterSet.letters), fullString[range].characterCount > 0 { zipController.setErrorText("Error: Zip can only contain numbers", errorAccessibilityValue: nil) } else if fullString.characterCount > 5 { zipController.setErrorText("Error: Zip can only contain five digits", errorAccessibilityValue: nil) } else { zipController.setErrorText(nil, errorAccessibilityValue: nil) } } else if textField == city { if let range = fullString.rangeOfCharacter(from: CharacterSet.decimalDigits), fullString[range].characterCount > 0 { cityController.setErrorText("Error: City can only contain letters", errorAccessibilityValue: nil) } else { cityController.setErrorText(nil, errorAccessibilityValue: nil) } } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { let index = textField.tag if index + 1 < allTextFieldControllers.count, let nextField = allTextFieldControllers[index + 1].textInput { nextField.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } } extension TextFieldFilledSwiftExample: UITextViewDelegate { func textViewDidEndEditing(_ textView: UITextView) { print(textView.text) } } // MARK: - Keyboard Handling extension TextFieldFilledSwiftExample { func registerKeyboardNotifications() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillShow, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillChangeFrame, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillHide(notif:)), name: .UIKeyboardWillHide, object: nil) } @objc func keyboardWillShow(notif: Notification) { guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else { return } scrollView.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: frame.height, right: 0.0) } @objc func keyboardWillHide(notif: Notification) { scrollView.contentInset = UIEdgeInsets() } } // MARK: - Status Bar Style extension TextFieldFilledSwiftExample { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } extension TextFieldFilledSwiftExample { @objc class func catalogBreadcrumbs() -> [String] { return ["Text Field", "Filled Text Fields"] } @objc class func catalogIsPresentable() -> Bool { return true } }
apache-2.0
7286144339281f7fabf8a9acec690112
37.778027
119
0.571206
6.196704
false
false
false
false
SeriousChoice/SCSwift
SCSwift/Controllers/SCMediaPlayerViewController.swift
1
10350
// // SCMediaPlayerViewController.swift // SCSwiftExample // // Created by Nicola Innocenti on 08/01/2022. // Copyright © 2022 Nicola Innocenti. All rights reserved. // import UIKit public enum MediaType : Int { case none = 0 case image = 1 case video = 2 case audio = 3 case pdf = 4 } public enum MediaExtension : String { case none = "" case jpg = "jpg" case png = "png" case gif = "gif" case mp4 = "mp4" case mkv = "mkv" case avi = "avi" } open class SCMedia : NSObject { open var id: String? open var title: String? open var mediaDescription: String? open var remoteUrl: URL? open var localUrl: URL? open var image: UIImage? open var thumbnail: UIImage? open var type: MediaType = .image open var fileExtension: MediaExtension = .none open var videoThumbnailSecond: Double = 1 public convenience init(id: String?, title: String?, description: String?, remoteUrl: URL?, localUrl: URL?, type: MediaType, fileExtension: MediaExtension) { self.init() self.id = id self.title = title self.mediaDescription = description self.remoteUrl = remoteUrl self.localUrl = localUrl self.type = type self.fileExtension = fileExtension } open var url: URL? { if localUrl?.fileExists == true { return localUrl } return remoteUrl } } public protocol SCMediaPlayerViewControllerDelegate : AnyObject { func mediaPlayerDidTapPlay() func mediaPlayerDidTapPause() func mediaPlayerDidTapStop() func mediaPlayerDidChangeTime(seconds: TimeInterval) } open class SCMediaPlayerViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, SCMediaViewControllerDelegate, SCVideoViewControllerDelegate, SCPDFViewControllerDelegate { // MARK: - Layout private var pageContainer: UIView = { let view = UIView() view.backgroundColor = .clear return view }() public var pageController: UIPageViewController = { let page = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) page.view.backgroundColor = .clear return page }() // MARK: - Constants & Variables public var backgroundColor: UIColor = .black public var topViewBackgroundColor: UIColor = UIColor.black.withAlphaComponent(0.5) public var bottomViewBackgroundColor: UIColor = UIColor.black.withAlphaComponent(0.5) public var videoAutoPlay: Bool = false private var medias = [SCMedia]() private var nextIndex: Int = 0 public var selectedIndex: Int = 0 private weak var playerDelegate: SCMediaPlayerViewControllerDelegate? public var dragAnimation: Bool = false private var dragGesture: UIPanGestureRecognizer? private var dragYTranslation: CGFloat = 0.0 // MARK: - Initialization public convenience init(medias: [SCMedia], selectedIndex: Int?) { self.init() self.medias = medias if let selectedIndex = selectedIndex { self.selectedIndex = selectedIndex } } // MARK: - UIViewController Methods override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = backgroundColor setupLayout() } private func setupLayout() { view.insertSubview(pageContainer, at: 0) pageController.dataSource = self pageController.delegate = self pageController.view.frame = CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: pageContainer.frame.size) if let viewController = self.viewController(at: selectedIndex) { pageController.setViewControllers([viewController], direction: .forward, animated: false, completion: nil) self.didLoadNewMedia() } pageContainer.addSubview(pageController.view) self.addChild(pageController) if dragAnimation { dragGesture = UIPanGestureRecognizer(target: self, action: #selector(handleDrag(pan:))) view.addGestureRecognizer(dragGesture!) } } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() pageContainer.frame = view.frame pageController.view.frame = CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: pageContainer.frame.size) } // MARK: - DragGesture Delegate @objc func handleDrag(pan: UIPanGestureRecognizer) { if pan.state == .began { dragYTranslation = 0.0 } else if pan.state == .changed { let translation = pan.translation(in: view) dragYTranslation += translation.y pan.view!.center = CGPoint(x: pan.view!.center.x, y: pan.view!.center.y + translation.y) pan.setTranslation(CGPoint.zero, in: view) } else if pan.state == .ended || pan.state == .cancelled { if dragYTranslation > pan.view!.frame.size.height/2 { UIView.animate(withDuration: 0.3, animations: { pan.view!.frame.origin.y = pan.view!.frame.size.height }, completion: { (completed) in self.dismiss(animated: false, completion: nil) }) } else { UIView.animate(withDuration: 0.3, animations: { pan.view!.frame.origin.y = 0 }, completion: { (completed) in }) } } } // MARK: - UIPageViewController DataSource & Delegate public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let preview = viewController as? SCMediaViewController else { return nil } return self.viewController(at: preview.index+1) } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let preview = viewController as? SCMediaViewController else { return nil } return self.viewController(at: preview.index-1) } public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed { if let viewController = pageViewController.viewControllers?.first as? SCMediaViewController { selectedIndex = viewController.index if viewController is SCVideoViewController { playerDelegate = viewController as? SCVideoViewController } self.didLoadNewMedia() } } } // MARK: - SCMediaViewController Delegate open func mediaDidTapView() { } open func mediaDidDoubleTap() { } open func mediaDidFailLoad(media: SCMedia) { } // MARK: - SCVideoViewController Delegate open func videoReadyToPlay() { } open func videoDidPlay() { } open func videoDidPause() { } open func videoDidStop() { } open func videoDidFailLoad() { } open func videoDidFinishPlay() { } open func videoDidUpdateProgress(currentTime: TimeInterval, duration: TimeInterval) { } // MARK: - SCPDFViewController Delegate open func pdfDidStartDownload() { } open func pdfDidFinishDownload() { } open func pdfDidUpdateDownload(progress: Float) { } open func pdfDidLoad(page: Int, totalPages: Int) { } // MARK: - Video Handlers public func play() { playerDelegate?.mediaPlayerDidTapPlay() } public func pause() { playerDelegate?.mediaPlayerDidTapPause() } public func stop() { playerDelegate?.mediaPlayerDidTapStop() } public func moveToSeconds(seconds: TimeInterval) { playerDelegate?.mediaPlayerDidChangeTime(seconds: seconds) } // MARK: - Other Methods open func viewController(at index: Int) -> SCMediaViewController? { if index < 0 || index >= medias.count { return nil } var viewController: SCMediaViewController? let media = medias[index] if media.type == .image { viewController = SCImageViewController(media: media) playerDelegate = nil } else if media.type == .video { viewController = SCVideoViewController(media: media, autoPlay: videoAutoPlay, loop: media.fileExtension == .gif, delegate: self) playerDelegate = viewController as? SCVideoViewController } else if media.type == .pdf { viewController = SCPDFViewController(media: media, delegate: self) } viewController?.delegate = self viewController?.index = index return viewController } open func didLoadNewMedia() { } public func close() { self.dismiss(animated: true, completion: nil) } public var selectedMedia : SCMedia { return medias[selectedIndex] } public var videoDuration : TimeInterval { guard let viewController = pageController.viewControllers?.first else { return 0.0 } if let videoViewController = viewController as? SCVideoViewController { return videoViewController.duration } return 0.0 } override open var prefersStatusBarHidden: Bool { return true } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
16c39f4818c560d7a49c83eeff4c5453
28.152113
211
0.606435
5.34832
false
false
false
false
wangtongke/WTKMVVMRxSwift
WTKMVVMRx/WTKMVVMRxSwift/Class/View/View/WTKHomeChoiceView.swift
1
4200
// // WTKHomeChoiceView.swift // WTKMVVMRxSwift // // Created by 王同科 on 2017/1/20. // Copyright © 2017年 王同科. All rights reserved. // import UIKit import SnapKit class WTKHomeChoiceView: UIView { // MARK: property var data : [WTKChannel]!{ didSet{ reloadDataSource() } } var lastIndex : Int { didSet{ if self.btnArray.count - 1 > lastIndex { btnClick(sender: self.btnArray[lastIndex] as! UIButton) } } } var scrollView = UIScrollView() var bottomLine = UIView() var btnArray = NSMutableArray() ///btn点击回调 var selectedBlock : (Int ,WTKChannel)->() = { name,channel in } // MARK: init init(title : [WTKChannel], frame : CGRect) { lastIndex = 0 // selectedBlock = nil super.init(frame: frame) data = title bottomView() initView() } func bottomView(){ bottomLine.backgroundColor = THEME_COLOR scrollView.addSubview(bottomLine) } func initView(){ let width = kWidth / 6.0 let height = self.frame.height scrollView.frame = CGRect.init(x: 0, y: 0, width: width * 5, height: self.frame.height) scrollView.showsHorizontalScrollIndicator = false scrollView.contentSize = CGSize.init(width: width * CGFloat(data.count), height: height) self.addSubview(scrollView) if data.count == 0 { return } for i in 0...data.count - 1 { let title = data[i] if btnArray.count - 1 < i { let btn = UIButton.init(type: .custom) btn.setTitleColor(WORD_COLOR, for: .normal) btn.setTitleColor(THEME_COLOR, for: .selected) btn.titleLabel?.textAlignment = NSTextAlignment.center btn.titleLabel?.font = wSystemFont(size: 14) btnArray.add(btn) } let btn = btnArray[i] as! UIButton btn.setTitle(title.name, for: UIControlState.normal) btn.frame = CGRect.init(x: width * CGFloat(i), y: 0, width: width, height: self.frame.height) btn.tag = i btn.addTarget(self, action: #selector(WTKHomeChoiceView.btnClick(sender:)), for: .touchUpInside) scrollView.addSubview(btn) if i == 0 { btnClick(sender: btn) bottomLine.frame = CGRect.init(x: width / 6.0, y: height - 3, width: width * 2.0 / 3.0, height: 2) scrollView.bringSubview(toFront: bottomLine) } } } func btnClick(sender : UIButton) { wPrint(message: sender.tag) guard let lastBtn = btnArray[lastIndex] as? UIButton else { return } lastBtn.isSelected = !lastBtn.isSelected sender.isSelected = true if lastIndex == sender.tag { return } lastIndex = sender.tag // line let width = kWidth / 6.0 let height = self.frame.height UIView.animate(withDuration: 0.3) { [unowned self] in self.bottomLine.frame = CGRect.init(x: width / 6.0 + CGFloat(sender.tag) * width, y: height - 3, width: width * 2.0 / 3.0, height: 2) } reloadScrollView() // 回调 selectedBlock(sender.tag, data[sender.tag]) } ///更新数据源 func reloadDataSource() { initView() } ///滑动 func reloadScrollView() { if lastIndex > 1 && lastIndex < data.count - 2 { // 当前选择滚到到中间 let width = kWidth / 6.0 scrollView.setContentOffset(CGPoint.init(x: width * CGFloat(lastIndex - 2), y: 0), animated: true) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
mit
25eceb3d68fa4aa740e3cac14bc6c7eb
28.791367
144
0.552524
4.22551
false
false
false
false
rzrasel/iOS-Swift-2016-01
SwiftDrawerNavigationOne/SwiftDrawerNavigationOne/RzDrawerNavigation/MenuTransitionManager.swift
2
3577
// // MenuTransitionManager.swift // SwiftDrawerNavigationOne // // Created by NextDot on 2/4/16. // Copyright © 2016 RzRasel. All rights reserved. // import UIKit @objc protocol MenuTransitionManagerDelegate { func dismiss() } class MenuTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { let duration = 0.5 var isPresenting = false var snapshot:UIView? { didSet { if let delegate = delegate { let tapGestureRecognizer = UITapGestureRecognizer(target: delegate, action: "dismiss") snapshot?.addGestureRecognizer(tapGestureRecognizer) } } } var delegate:MenuTransitionManagerDelegate? func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // Get reference to our fromView, toView and the container view let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! // Set up the transform we'll use in the animation guard let container = transitionContext.containerView() else { return } //let moveLeft = CGAffineTransformMakeTranslation(container.frame.width - 150, 0) //let moveDown = CGAffineTransformMakeTranslation(0, container.frame.height - 150) //snapshotView.transform = CGAffineTransformMakeTranslation(CGRectGetWidth(containerView.frame), 0.0) //let moveDown = CGAffineTransformMakeTranslation(CGRectGetWidth(container.frame), 0.0) let moveDown = CGAffineTransformMakeTranslation(150 - container.frame.width, 0.0) //let moveUp = CGAffineTransformMakeTranslation(0, 50) //let moveUp: CGFloat = 50 let moveUp = CGAffineTransformMakeTranslation(50, 0.0) // Add both views to the container view if isPresenting { toView.transform = moveUp snapshot = fromView.snapshotViewAfterScreenUpdates(true) container.addSubview(toView) container.addSubview(snapshot!) } // Perform the animation UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: [], animations: { if self.isPresenting { self.snapshot?.transform = moveDown toView.transform = CGAffineTransformIdentity } else { self.snapshot?.transform = CGAffineTransformIdentity fromView.transform = moveUp } }, completion: { finished in transitionContext.completeTransition(true) if !self.isPresenting { self.snapshot?.removeFromSuperview() } }) } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } }
apache-2.0
2bfece2b09bf04fc2f0c9e4458fa8be5
37.053191
217
0.65632
6.374332
false
false
false
false
jkereako/SalesForceAPI
SalesForceAPI/OAuth2.swift
1
2192
// // OAuth2.swift // SalesForceAPI // // Created by Jeffrey Kereakoglow on 1/26/16. // Copyright © 2016 Innovate!. All rights reserved. // import Foundation enum OAuth2 { // https://developer.salesforce.com/docs/atlas.en-us.200.0.api_rest.meta/api_rest/resources_limits.htm case Authorize(responseType: String, clientID: String, redirectURI: String) case Token(grantType: String, clientID: String, clientSecret: String, username: String, password: String) case Revoke } extension OAuth2: Path { var path: String { switch self { case .Authorize(let responseType, let clientID, let redirectURI): // Delegate the query string building to Cocoa let urlComponents = NSURLComponents() urlComponents.queryItems = [ NSURLQueryItem(name: "client_id", value: clientID), NSURLQueryItem(name: "response_type", value: responseType), NSURLQueryItem(name: "redirect_uri", value: redirectURI) ] return urlComponents.percentEncodedQuery! case .Token( let grantType, let clientID, let clientSecret, let username, let password): let urlComponents = NSURLComponents() urlComponents.queryItems = [ NSURLQueryItem(name: "grant_type", value: grantType), NSURLQueryItem(name: "client_id", value: clientID), NSURLQueryItem(name: "client_secret", value: clientSecret), NSURLQueryItem(name: "username", value: username), NSURLQueryItem(name: "password", value: password) ] return urlComponents.percentEncodedQuery! case .Revoke: return "" } } } extension OAuth2: Restful { var baseURL: NSURL { return NSURL(string: "https://login.salesforce.com/services/oauth2")! } var sampleData: String { switch self { case .Authorize(let responseType, let clientID, let redirectURI): return "?response_type=\(responseType)&client_id=\(clientID)&redirect_uri=\(redirectURI)" case .Token(let clientID, let clientSecret, let username, let password, let grantType): return "?client_id=\(clientID)&client_secret=\(clientSecret)&username=\(username)&password=\(password)&grant_type=\(grantType)" case .Revoke: return "" } } }
mit
b933054ed32387bd550d51301264cccf
32.723077
133
0.692378
4.373253
false
false
false
false
Tanglo/VergeOfStrife
Vos Map Maker/VoSGrid.swift
1
2181
// // VoSGrid.swift // VergeOfStrife // // Created by Lee Walsh on 31/03/2015. // Copyright (c) 2015 Lee David Walsh. All rights reserved. // import Cocoa class VoSGrid: NSObject, NSCoding { private var rows = 0 private var columns = 0 private var tileValues = [String]() //simulating a 2D matrix with an array. Rows are listed consecutively, so the cell at [2,5] is in the array at 2*rows+5 override init(){ rows = 0 columns = 0 tileValues = [String]() } convenience init(rows: Int, columns: Int){ self.init() self.rows = rows self.columns = columns tileValues = [String](count: rows*columns, repeatedValue: "-") } convenience init(rows: Int, columns: Int, tileValues: [String]){ self.init(rows: rows, columns: columns) self.tileValues = tileValues if self.tileValues.count < rows*columns { let start = self.tileValues.count for i in start..<rows*columns { self.tileValues.append("-") } } else if self.tileValues.count > rows*columns { self.tileValues.removeRange(rows*columns...self.tileValues.count-1) } } required init(coder aDecoder: NSCoder) { self.rows = aDecoder.decodeIntegerForKey("rows") self.columns = aDecoder.decodeIntegerForKey("columns") self.tileValues = aDecoder.decodeObjectForKey("cellValues") as! [String]! } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(rows, forKey: "rows") aCoder.encodeInteger(columns, forKey: "columns") aCoder.encodeObject(tileValues, forKey: "cellValues") } func gridSize() ->(Int, Int) { return (rows, columns) } func tileValue(row: Int, column: Int) ->String{ // println("rows: \(rows), cols: \(columns) - \(row*columns+column)") return tileValues[row*columns+column] } func setTileValue(row: Int, column: Int, value: String){ self.tileValues[row*columns+column] = value } /* func arrayValue(i: Int) ->String{ return cellValues[i] }*/ }
mit
e558e1c1c68db30711de70d97fc1bf4b
30.157143
160
0.603851
3.994505
false
false
false
false
stripe/stripe-ios
StripePaymentSheet/StripePaymentSheet/Internal/Link/Components/PaymentMethodPicker/LinkPaymentMethodPicker-Cell.swift
1
9959
// // LinkPaymentMethodPicker-Cell.swift // StripePaymentSheet // // Created by Ramon Torres on 10/19/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import UIKit @_spi(STP) import StripeCore @_spi(STP) import StripeUICore protocol LinkPaymentMethodPickerCellDelegate: AnyObject { func savedPaymentPickerCellDidSelect(_ cell: LinkPaymentMethodPicker.Cell) func savedPaymentPickerCell(_ cell: LinkPaymentMethodPicker.Cell, didTapMenuButton button: UIButton) } extension LinkPaymentMethodPicker { final class Cell: UIControl { struct Constants { static let margins = NSDirectionalEdgeInsets(top: 16, leading: 20, bottom: 16, trailing: 20) static let contentSpacing: CGFloat = 12 static let contentIndentation: CGFloat = 34 static let menuSpacing: CGFloat = 8 static let menuButtonSize: CGSize = .init(width: 24, height: 24) static let separatorHeight: CGFloat = 1 static let iconViewSize: CGSize = .init(width: 14, height: 20) static let disabledContentAlpha: CGFloat = 0.5 } override var isHighlighted: Bool { didSet { setNeedsLayout() } } override var isSelected: Bool { didSet { setNeedsLayout() } } var paymentMethod: ConsumerPaymentDetails? { didSet { update() } } var isLoading: Bool = false { didSet { if isLoading != oldValue { update() } } } var isSupported: Bool = true { didSet { if isSupported != oldValue { update() } } } weak var delegate: LinkPaymentMethodPickerCellDelegate? private let radioButton = RadioButton() private let contentView = CellContentView() private let activityIndicator = ActivityIndicator() private let defaultBadge = LinkBadgeView( type: .neutral, text: STPLocalizedString("Default", "Label for identifying the default payment method.") ) private let alertIconView: UIImageView = { let iconView = UIImageView() iconView.contentMode = .scaleAspectFit iconView.image = Image.icon_link_error.makeImage(template: true) iconView.tintColor = .linkDangerForeground return iconView }() private let unavailableBadge = LinkBadgeView(type: .error, text: STPLocalizedString( "Unavailable for this purchase", "Label shown when a payment method cannot be used for the current transaction." )) private lazy var menuButton: UIButton = { let button = UIButton(type: .system) button.setImage(Image.icon_menu.makeImage(), for: .normal) button.addTarget(self, action: #selector(onMenuButtonTapped(_:)), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() /// The menu button frame for hit-testing purposes. private var menuButtonFrame: CGRect { let originalFrame = menuButton.convert(menuButton.bounds, to: self) let targetSize = CGSize(width: 44, height: 44) return CGRect( x: originalFrame.midX - (targetSize.width / 2), y: originalFrame.midY - (targetSize.height / 2), width: targetSize.width, height: targetSize.height ) } private let separator: UIView = { let separator = UIView() separator.backgroundColor = .linkControlBorder separator.translatesAutoresizingMaskIntoConstraints = false return separator }() override init(frame: CGRect) { super.init(frame: frame) isAccessibilityElement = true directionalLayoutMargins = Constants.margins setupUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { let rightStackView = UIStackView(arrangedSubviews: [defaultBadge, alertIconView, activityIndicator, menuButton]) rightStackView.spacing = LinkUI.smallContentSpacing rightStackView.distribution = .equalSpacing rightStackView.alignment = .center let stackView = UIStackView(arrangedSubviews: [contentView, rightStackView]) stackView.spacing = Constants.contentSpacing stackView.distribution = .equalSpacing stackView.alignment = .center let container = UIStackView(arrangedSubviews: [stackView, unavailableBadge]) container.axis = .vertical container.spacing = Constants.contentSpacing container.distribution = .equalSpacing container.alignment = .leading container.translatesAutoresizingMaskIntoConstraints = false addSubview(container) radioButton.translatesAutoresizingMaskIntoConstraints = false addSubview(radioButton) addSubview(separator) NSLayoutConstraint.activate([ // Radio button radioButton.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor), radioButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), // Menu button menuButton.widthAnchor.constraint(equalToConstant: Constants.menuButtonSize.width), menuButton.heightAnchor.constraint(equalToConstant: Constants.menuButtonSize.height), // Loader activityIndicator.widthAnchor.constraint(equalToConstant: Constants.menuButtonSize.width), activityIndicator.heightAnchor.constraint(equalToConstant: Constants.menuButtonSize.height), // Icon alertIconView.widthAnchor.constraint(equalToConstant: Constants.iconViewSize.width), alertIconView.heightAnchor.constraint(equalToConstant: Constants.iconViewSize.height), // Container container.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor), container.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor), container.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor, constant: Constants.contentIndentation), container.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor), // Make stackView fill the container stackView.trailingAnchor.constraint(equalTo: container.trailingAnchor), // Separator separator.heightAnchor.constraint(equalToConstant: Constants.separatorHeight), separator.bottomAnchor.constraint(equalTo: bottomAnchor), separator.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor), separator.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor), ]) } private func update() { contentView.paymentMethod = paymentMethod updateAccessibilityContent() guard let paymentMethod = paymentMethod else { return } var hasExpired: Bool { switch paymentMethod.details { case .card(let card): return card.hasExpired case .bankAccount(_): return false } } defaultBadge.isHidden = isLoading || !paymentMethod.isDefault alertIconView.isHidden = isLoading || !hasExpired menuButton.isHidden = isLoading contentView.alpha = isSupported ? 1 : Constants.disabledContentAlpha unavailableBadge.isHidden = isSupported if isLoading { activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() } } override func layoutSubviews() { super.layoutSubviews() radioButton.isOn = isSelected backgroundColor = isHighlighted ? .linkControlHighlight : .clear } private func updateAccessibilityContent() { guard let paymentMethod = paymentMethod else { return } accessibilityLabel = paymentMethod.accessibilityDescription accessibilityCustomActions = [ UIAccessibilityCustomAction( name: String.Localized.show_menu, target: self, selector: #selector(onShowMenuAction(_:)) ) ] } @objc func onShowMenuAction(_ sender: UIAccessibilityCustomAction) { onMenuButtonTapped(menuButton) } @objc func onMenuButtonTapped(_ sender: UIButton) { delegate?.savedPaymentPickerCell(self, didTapMenuButton: sender) } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if menuButtonFrame.contains(point) { return menuButton } return bounds.contains(point) ? self : nil } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) guard let touchLocation = touches.first?.location(in: self) else { return } if bounds.contains(touchLocation) { delegate?.savedPaymentPickerCellDidSelect(self) } } } }
mit
ec54a61959daebe598943a22f7d3a560
35.610294
134
0.604137
6.131773
false
false
false
false
HarrisHan/Snapseed
Snapseed/Snapseed/SnapMenue.swift
1
10008
// // SnapMenue.swift // Snapseed // // Created by harris on 08/02/2017. // Copyright © 2017 harris. All rights reserved. // import UIKit protocol SnapMenueProtocal: class { func menueSelectedWithIndex(index:Int) func selectWhileTracking(index: Int) } class SnapMenue: UIView { var maxHeight:CGFloat = 0 var minHeight:CGFloat = 0 weak var delegate:SnapMenueProtocal? var itemWidth:Double? var itemHeight:Double? var panGesture:SnapPanGestureRecognizer? fileprivate var items:Array<UILabel>? fileprivate var values:Array<UILabel>? fileprivate var containers:Array<UIView>? fileprivate var positions:Array<Any>? fileprivate var labelNames:Array<String>? fileprivate var labelValues:Array<Double>? fileprivate var noOfElements:Int? fileprivate var chooseBar:UIView? fileprivate var chooseBarName:UILabel? fileprivate var chooseBarValue:UILabel? fileprivate var preTranslate = CGPoint(x: 0, y: 0) fileprivate var view:UIView? init(itemArray:Array<String>, valueArray:Array<Double>, height:Double, width:Double,viewController:UIViewController) { itemWidth = width itemHeight = height noOfElements = itemArray.count labelNames = itemArray labelValues = valueArray view = viewController.view maxHeight = view!.center.y + CGFloat((Double(noOfElements!) - 0.5) * height) minHeight = view!.center.y - (maxHeight - view!.center.y) positions = Array() items = Array() values = Array() containers = Array() let totalHeight = Double(noOfElements!) * height let noOfHalfElements = noOfElements! / 2 super.init(frame: CGRect(x: 0, y: 0, width: width, height: totalHeight)) panGesture = SnapPanGestureRecognizer(target: self, action: #selector(pan(sender:))) panGesture?.direction = .snapPanGestureRecognizerDirectionVertical self.backgroundColor = UIColor.white // each menue item's position for (index, _) in itemArray.enumerated() { if noOfElements! % 2 == 0 { positions?.append(CGFloat(noOfHalfElements - index) * CGFloat(height) - CGFloat(height / 2)) } else { positions?.append(CGFloat(noOfHalfElements - index) * CGFloat(height)) } } self.center = view!.center var frame = self.frame frame.origin.x = 0 frame.origin.y = -25 frame.size.height += 50 let bottomView = UIView.init(frame: frame) bottomView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) addSubview(bottomView) for (index, _) in itemArray.enumerated() { let containerView = UIView.init(frame: CGRect(x: 0, y: 0, width: width, height: height)) containerView.center = CGPoint(x: width / 2, y: (Double(index) * 2 + 1) * height / 2) let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(tapGes(sender:))) containerView.addGestureRecognizer(tapGesture) let label = UILabel.init(frame: CGRect(x: 30, y: 12, width: 0, height: 0)) label.text = itemArray[index] label.sizeToFit() label.font = UIFont.systemFont(ofSize: 13) label.textColor = UIColor.black.withAlphaComponent(0.6) let valueLabel = UILabel.init(frame: CGRect(x: 196, y: 12, width: 0, height: 0)) valueLabel.text = String(format:"%.f",valueArray[index]) valueLabel.sizeToFit() valueLabel.font = UIFont.systemFont(ofSize: 13) valueLabel.textColor = UIColor.black.withAlphaComponent(0.6) containerView.addSubview(label) containerView.addSubview(valueLabel) addSubview(containerView) items?.append(label) values?.append(valueLabel) containers?.append(containerView) } chooseBar = UIView.init(frame: CGRect(x: 0, y: 0, width: width, height: height)) chooseBar?.center = view!.center; chooseBar?.backgroundColor = #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1) viewController.view.addSubview(chooseBar!) viewController.view.addSubview(self) viewController.view.bringSubview(toFront: chooseBar!) chooseBarName = UILabel.init(frame: CGRect(x: 30, y: 12, width: 0, height: 0)) chooseBarName?.font = UIFont.systemFont(ofSize: 13) chooseBarName?.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) chooseBarValue = UILabel.init(frame: CGRect(x: 196, y: 12, width: 0, height: 0)) chooseBarValue?.font = UIFont.systemFont(ofSize: 13) chooseBarValue?.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) chooseBar?.addSubview(chooseBarName!) chooseBar?.addSubview(chooseBarValue!) self.alpha = 0 chooseBar?.alpha = 0 } func pan(sender: UIPanGestureRecognizer) { let translate = sender.translation(in:view) // appear animation UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { self.alpha = 1 self.chooseBar?.alpha = 1 }, completion: nil) var newFrame = self.frame newFrame.origin.y += (translate.y - preTranslate.y) if !(newFrame.origin.y < minHeight || newFrame.origin.y + newFrame.size.height > maxHeight) { self.frame = newFrame } let currentCenterY = self.center.y var pointIndex = 0 var lastValue:CGFloat = 99999.0 for (index, _) in (positions?.enumerated())! { let positonY = (view?.center.y)! - ((positions?[index])! as! CGFloat) let newValue = fabs(positonY - currentCenterY) if newValue < lastValue { lastValue = newValue pointIndex = index } } let lastIndex = Int(noOfElements! - pointIndex - 1) chooseBarName?.text = labelNames?[lastIndex] chooseBarValue?.text = String(format:"%.f",(labelValues?[lastIndex])!) chooseBarName?.sizeToFit() chooseBarValue?.sizeToFit() delegate?.selectWhileTracking(index: lastIndex) for (index, _) in (items?.enumerated())! { let nameLable = items?[index] let valueLable = values?[index] if index == lastIndex { nameLable?.text = "" valueLable?.text = "" } else { nameLable?.text = labelNames?[index] valueLable?.text = String(format:"%.f",(labelValues?[index])!) valueLable?.sizeToFit() } } preTranslate = translate if sender.state == .ended { // hidden UIView.animate(withDuration: 0.2, delay: 0.0, options: .beginFromCurrentState, animations: { self.alpha = 0 self.chooseBar?.alpha = 0 }, completion: nil) preTranslate = CGPoint(x: 0, y: 0) //adjust menue position UIView.animate(withDuration: 0.0, delay: 0.2, options: .beginFromCurrentState, animations: { self.center = CGPoint(x: self.center.x, y: (self.view?.center.y)! + ((self.positions?[lastIndex])! as! CGFloat)) }, completion: nil) self.delegate?.menueSelectedWithIndex(index: lastIndex) } } func tapGes(sender: UITapGestureRecognizer) { for container in containers! { if container == sender.view { let height = CGFloat(42) let containterY = container.frame.origin.y let lastIndex = Int(containterY / height) updateValues(lastIndex) delegate?.selectWhileTracking(index: lastIndex) UIView.animate(withDuration: 0.5, delay: 0, options: .beginFromCurrentState, animations: { self.center = CGPoint(x: self.center.x, y: (self.view?.center.y)! + ((self.positions?[lastIndex])! as! CGFloat)) }, completion: nil) UIView.animateKeyframes(withDuration: 0.4, delay: 0.5, options: .beginFromCurrentState, animations: { self.alpha = 0 self.chooseBar!.alpha = 0 }, completion: nil) } } } fileprivate func updateValues(_ lastIndex: Int) { chooseBarName?.text = labelNames?[lastIndex] chooseBarValue?.text = String(format:"%.f",(labelValues?[lastIndex])!) chooseBarName?.sizeToFit() chooseBarValue?.sizeToFit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func appear() { self.alpha = 1 chooseBar?.alpha = 1 guard chooseBarName?.text != nil else { for container in containers! { let height = CGFloat(42) let containterY = container.frame.origin.y let lastIndex = Int(containterY / height) updateValues(lastIndex) } return } } func setValueAtIndex(index:Int, value:Double) { labelValues?[index] = Double(value) } }
mit
f557ac567cca1f55c78e6c3ba0b0fc4f
34.235915
132
0.562506
4.687119
false
false
false
false
trill-lang/trill
Sources/Source/SourceFile.swift
2
2147
/// /// SourceFile.swift /// /// Copyright 2016-2017 the Trill project authors. /// Licensed under the MIT License. /// /// Full license text available at https://github.com/trill-lang/trill /// import Foundation public enum SourceFileType: Equatable, Hashable { public var hashValue: Int { switch self { case .input(let url, _): return url.hashValue ^ 0x4324 case .file(let url): return url.hashValue ^ 0x33345 case .stdin: return 0x314159 case .none: return 0xE271 } } public static func ==(lhs: SourceFileType, rhs: SourceFileType) -> Bool { switch (lhs, rhs) { case (.input(let lhsURL, _), .input(let rhsURL, _)), (.file(let lhsURL), .file(let rhsURL)): return lhsURL == rhsURL case (.stdin, .stdin): return true case (.none, .none): return true default: return false } } case input(url: URL, contents: String) case file(URL) case stdin case none public var basename: String { switch self { case .file(let url), .input(let url, _): return url.lastPathComponent case .stdin, .none: return filename } } public var filename: String { switch self { case .file(let url), .input(let url, _): return url.path case .stdin: return "<stdin>" case .none: return "<none>" } } } public struct SourceFile: Equatable, Hashable { public static func ==(lhs: SourceFile, rhs: SourceFile) -> Bool { return lhs.path == rhs.path } public var hashValue: Int { return path.hashValue ^ 0x35 } public let path: SourceFileType internal unowned let sourceFileManager: SourceFileManager public var contents: String { return try! sourceFileManager.contents(of: self) } public var lines: [String] { return try! sourceFileManager.lines(in: self) } public init(path: SourceFileType, sourceFileManager: SourceFileManager) throws { self.path = path self.sourceFileManager = sourceFileManager } } extension SourceFile { public var start: SourceLocation { return SourceLocation(line: 1, column: 1, file: self, charOffset: 0) } }
mit
25c14838eec1dd01359c78b0b78ffb58
23.397727
82
0.647415
3.925046
false
false
false
false
chronotruck/CTKFlagPhoneNumber
Sources/FPNCountryPicker/FPNNibLoadingView.swift
1
772
import UIKit class NibLoadingView: UIView { @IBOutlet weak var view: UIView! override init(frame: CGRect) { super.init(frame: frame) nibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) nibSetup() } fileprivate func nibSetup() { backgroundColor = UIColor.clear view = loadViewFromNib() view.frame = bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.translatesAutoresizingMaskIntoConstraints = true addSubview(view) } fileprivate func loadViewFromNib() -> UIView { let bundle = Bundle.FlagPhoneNumber() let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView return nibView } }
apache-2.0
f3d586d450baedcfe2f5a17ded73459c
21.057143
79
0.727979
3.747573
false
false
false
false
trill-lang/trill
Sources/IRGen/GenericIRGen.swift
2
1801
/// /// GenericIRGen.swift /// /// Copyright 2016-2017 the Trill project authors. /// Licensed under the MIT License. /// /// Full license text available at https://github.com/trill-lang/trill /// import AST import LLVM extension IRGenerator { func codegenWitnessTables(_ type: TypeDecl) -> [Global] { var globals = [Global]() for typeRef in type.conformances { guard let proto = context.protocol(named: typeRef.name) else { fatalError("no protocol named \(typeRef.name)") } let table = WitnessTable(proto: proto, implementingType: type) globals.append(codegenWitnessTable(table)) } return globals } /// Generates code for a witness table that contains all requirements of a /// type conforming to a given protocol. /// /// A Witness Table for a protocol consists of: /// /// - A pointer to the type metadata for the protocol type /// - A pointer to an array of the protocol's witness table func codegenWitnessTable(_ table: WitnessTable) -> Global { let tableSymbol = Mangler.mangle(table) if let global = module.global(named: tableSymbol) { return global } let methodArrayType = ArrayType(elementType: PointerType.toVoid, count: table.proto.methods.count) var array = builder.addGlobal(tableSymbol, type: methodArrayType) let methods = table.implementingType.methodsSatisfyingRequirements(of: table.proto) let entries: [IRValue] = methods.map { let function = codegenFunctionPrototype($0) return builder.buildBitCast(function, type: PointerType.toVoid) } array.initializer = ArrayType.constant(entries, type: PointerType.toVoid) _ = codegenProtocolMetadata(table.proto) return array } }
mit
6c8947fd47319f874f164d14d3cf7ee5
30.596491
87
0.67407
4.381995
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/Root/Views/ZSVoiceCategoryCell.swift
1
2051
// // QSCatalogProtocols.swift // zhuishushenqi // // Created yung on 2017/4/21. // Copyright © 2017年 QS. All rights reserved. // // Template generated by Juanpe Catalán @JuanpeCMiOS // class ZSVoiceCategoryCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) setupSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() imageView?.frame = CGRect(x: 20, y: 10, width: bounds.height*2/3, height: bounds.height - 20) textLabel?.frame = CGRect(x: (imageView?.frame.maxX ?? 0) + 20, y: 10, width: bounds.width - (imageView?.frame.maxX ?? 0) - 20 - 20, height: 20) detailTextLabel?.frame = CGRect(x: (imageView?.frame.maxX ?? 0) + 20, y: (bounds.height - 20)/3 + 10, width: bounds.width - (imageView?.frame.maxX ?? 0) - 20 - 20, height: 20) popularityLabel.frame = CGRect(x: (imageView?.frame.maxX ?? 0) + 20, y: (bounds.height - 20)*2/3 + 10, width: (bounds.width - (imageView?.frame.maxX ?? 0))/2 - 20, height: 20) totalLabel.frame = CGRect(x: (popularityLabel?.frame.midX ?? 0) + 40 , y: (bounds.height - 20)*2/3 + 10, width: (bounds.width - (imageView?.frame.maxX ?? 0))/2 + 20, height: 20) } private func setupSubviews() { textLabel?.font = UIFont.systemFont(ofSize: 15) detailTextLabel?.font = UIFont.systemFont(ofSize: 13) popularityLabel = UILabel() popularityLabel.font = UIFont.systemFont(ofSize: 12) popularityLabel.textColor = UIColor.gray contentView.addSubview(popularityLabel) totalLabel = UILabel() totalLabel.font = UIFont.systemFont(ofSize: 12) totalLabel.textColor = UIColor.gray contentView.addSubview(totalLabel) } var popularityLabel:UILabel! var totalLabel:UILabel! }
mit
59cdfa08373580eb667a7cb1505f4b9f
42.553191
185
0.640449
3.876894
false
false
false
false
maxim-pervushin/Overlap
Overlap/App/Views/EditButton.swift
1
2267
// // Created by Maxim Pervushin on 02/05/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import UIKit @IBDesignable class EditButton: UIButton { @IBInspectable var cornerRadius: CGFloat { set { layer.cornerRadius = newValue } get { return layer.cornerRadius } } func setColor(color: UIColor) { backgroundColor = color.colorWithAlphaComponent(0.3) setTitleColor(color) tintColor = color _editImageView.tintColor = color } override init(frame: CGRect) { super.init(frame: frame) _commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _commonInit() } override func layoutSubviews() { super.layoutSubviews() let offset = CGFloat(4) let imageSize = CGSize(width: frame.size.height - 2 * offset, height: frame.size.height - 2 * offset) let imageOrigin = CGPoint(x: frame.size.width - imageSize.width - offset, y: offset) _editImageView.frame = CGRect(origin: imageOrigin, size: imageSize) } private func _commonInit() { setColor(UIColor.greenColor()) tintColor = UIColor.greenColor() _editImageView.tintColor = UIColor.greenColor() cornerRadius = 2 contentEdgeInsets = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8) addSubview(_editImageView) } private let _editImageView = UIImageView(image: UIImage(named: "Edit")?.imageWithRenderingMode(.AlwaysTemplate)) } extension UIButton { func setTitle(title: String) { setTitle(title, forState: .Normal) setTitle(title, forState: .Selected) setTitle(title, forState: .Disabled) setTitle(title, forState: .Highlighted) if #available(iOS 9.0, *) { setTitle(title, forState: .Focused) } } func setTitleColor(color: UIColor) { setTitleColor(color, forState: .Normal) setTitleColor(color, forState: .Selected) setTitleColor(color, forState: .Disabled) setTitleColor(color, forState: .Highlighted) if #available(iOS 9.0, *) { setTitleColor(color, forState: .Focused) } } }
mit
19d7401eb72f9c155ef92d4777aa8825
28.441558
116
0.62285
4.498016
false
false
false
false
iMetalk/TCZDemo
BasicAnimationDemo/BasicAnimationDemo/ViewController.swift
1
6960
// // ViewController.swift // BasicAnimationDemo // // Created by WangSuyan on 2017/1/4. // Copyright © 2017年 WangSuyan. All rights reserved. // import UIKit private let kViewWidth: CGFloat = 100 class ViewController: UIViewController { var layerView: UIView! var colorLayer: CALayer! var bezierPath: UIBezierPath! var shipLayer: CALayer! var rotateLayer: CALayer! var trasitionImageView: UIImageView! var isHaveChanged: Bool = false var tempColor: UIColor = UIColor.blue override func viewDidLoad() { super.viewDidLoad() layerView = UIView(frame: CGRect(x: (view.frame.width - kViewWidth) / 2.0, y: 100, width: kViewWidth, height: kViewWidth)) layerView.backgroundColor = UIColor.clear layerView.layer.cornerRadius = layerView.frame.width / 2.0 layerView.layer.masksToBounds = true layerView.layer.borderWidth = 2.0 layerView.layer.borderColor = UIColor.black.cgColor view.addSubview(layerView) colorLayer = CALayer() colorLayer.frame = layerView.bounds colorLayer.backgroundColor = UIColor.blue.cgColor layerView.layer.addSublayer(colorLayer) createBirdUI() createRotateUI() createTrasitionUI() } func createBirdUI() { let startPonint = CGPoint(x: 100, y: 300) bezierPath = UIBezierPath() bezierPath.move(to: startPonint) bezierPath.addCurve(to: CGPoint(x: 300, y: 300), controlPoint1: CGPoint(x: view.frame.midX, y: 500), controlPoint2: CGPoint(x: view.frame.midX, y: 600)) let shapeLayer = CAShapeLayer() shapeLayer.path = bezierPath.cgPath shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = UIColor.red.cgColor shapeLayer.lineWidth = 3.0 self.view.layer.addSublayer(shapeLayer) shipLayer = CALayer() shipLayer.frame = CGRect(origin: startPonint, size: CGSize(width: 40, height: 40)); shipLayer.position = startPonint shipLayer.contents = UIImage(named: "bird")?.cgImage self.view.layer.addSublayer(shipLayer) } func createRotateUI() { rotateLayer = CALayer() rotateLayer.frame = CGRect(x: 200, y: 300, width: 80, height: 80) rotateLayer.position = CGPoint(x: 200, y: 300) rotateLayer.cornerRadius = 80 / 2.0 rotateLayer.masksToBounds = true rotateLayer.borderWidth = 2.0 rotateLayer.contents = UIImage(named: "bird")?.cgImage rotateLayer.borderColor = UIColor.red.cgColor self.view.layer.addSublayer(rotateLayer) } func createTrasitionUI() { trasitionImageView = UIImageView(frame: CGRect(x: 20, y: view.frame.height - 200 - 20, width: 200, height: 200)) trasitionImageView.image = UIImage(named: "3") view.addSubview(trasitionImageView) } @IBAction func transitionAction(_ sender: Any) { trasitionAnimation2() } func trasitionAnimation() { let trasition = CATransition() // Control animation ways trasition.type = kCATransitionFade // Control direction // trasition.subtype = kCATransitionFromTop let imageName = "\(arc4random() % 4 + 3)" trasitionImageView.image = UIImage(named: imageName) trasitionImageView.layer.add(trasition, forKey: nil) } func trasitionAnimation2() { UIView.transition(with: trasitionImageView, duration: 1.0, options: .transitionCurlUp, animations: {[weak self] in let imageName = "\(arc4random() % 4 + 3)" if let wself = self{ wself.trasitionImageView.image = UIImage(named: imageName) } }) { (isFinish) in } } @IBAction func rotateAction(_ sender: Any) { animationRotate2() } func animationRotate() { // Must set layer content let animation = CABasicAnimation() animation.keyPath = "transform.rotation"; animation.duration = 1.0 animation.byValue = M_PI * 2 rotateLayer.add(animation, forKey: nil) } func animationRotate2() { // Rotate let animation = CABasicAnimation() animation.keyPath = "transform"; animation.duration = 0.6 animation.toValue = CATransform3DMakeRotation(CGFloat(M_PI), 0, 1, 0) // KeyFrame let keyAnimate = CAKeyframeAnimation(keyPath: "backgroundColor") keyAnimate.duration = 1.0 keyAnimate.values = [ UIColor.red.cgColor, UIColor.yellow.cgColor, UIColor.purple.cgColor ] // Group let groupAnimate = CAAnimationGroup() groupAnimate.animations = [animation, keyAnimate] groupAnimate.duration = 1.0 groupAnimate.repeatCount = 100.0 rotateLayer.add(groupAnimate, forKey: nil) } @IBAction func pathAnimate(_ sender: Any) { let keyAnimation = CAKeyframeAnimation(keyPath: "position") keyAnimation.duration = 3.0 keyAnimation.repeatCount = 10 keyAnimation.path = bezierPath.cgPath keyAnimation.rotationMode = kCAAnimationRotateAuto shipLayer.add(keyAnimation, forKey: nil) } @IBAction func keyframeAction(_ sender: Any) { let keyAnimate = CAKeyframeAnimation(keyPath: "backgroundColor") keyAnimate.duration = 2.0 keyAnimate.repeatCount = 100.0 keyAnimate.values = [ UIColor.red.cgColor, UIColor.yellow.cgColor, UIColor.purple.cgColor ] colorLayer.add(keyAnimate, forKey: nil) } @IBAction func changeColor(_ sender: Any) { if isHaveChanged { changeColorAnimate(color: UIColor.blue) }else{ changeColorAnimate(color: UIColor.red) } isHaveChanged = !isHaveChanged } func changeColorAnimate(color: UIColor) { tempColor = color let animate = CABasicAnimation() animate.fromValue = colorLayer.backgroundColor // You must add this, or you will not chang the color animate.toValue = color.cgColor animate.duration = 0.55 animate.keyPath = "backgroundColor" animate.delegate = self colorLayer.add(animate, forKey: nil) } } extension ViewController: CAAnimationDelegate{ func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if flag { // Disable implicit animation CATransaction.begin() CATransaction.setDisableActions(true) self.colorLayer.backgroundColor = tempColor.cgColor CATransaction.commit() } } func animationDidStart(_ anim: CAAnimation) { } }
mit
904a8699cf28fb2213688c3a2f7347f6
31.208333
160
0.619232
4.644192
false
false
false
false
akabab/XcodeWeshExtensions
XcodeWeshCCP/XCSource+Extensions.swift
1
681
// // XCSource+Extensions.swift // XcodeWeshExtensions // // Created by Yoann Cribier on 17/11/2016. // Copyright © 2016 akabab. All rights reserved. // import XcodeKit extension XCSourceTextPosition: Equatable { public static func ==(lhs: XCSourceTextPosition, rhs: XCSourceTextPosition) -> Bool { return lhs.line == rhs.line && lhs.column == rhs.column } } extension XCSourceTextBuffer { var cursorLineIndex: Int? { guard let firstSelection = self.selections.firstObject as? XCSourceTextRange else { return nil } return firstSelection.start.line } } extension XCSourceTextRange { var isInsertionPoint: Bool { return start == end } }
mit
5145ea6e1cc3b6a3c4f4a590d38ac637
18.428571
100
0.711765
3.953488
false
false
false
false
tomasharkema/HoelangTotTrein2.iOS
Packages/Core/Sources/Core/DataStore/PreferenceStore.swift
1
8197
// // NSUserDefaults+HLTT.swift // HoelangTotTrein2 // // Created by Tomas Harkema on 27-09-15. // Copyright © 2015 Tomas Harkema. All rights reserved. // import API import Bindable import Foundation private struct Keys { static let adviceRequestDefaults = "adviceRequestDefaults" static let originalAdviceRequestDefaults = "originalAdviceRequestDefaults" static let userIdKey = "UserIdKey" static let geofenceInfoKey = "GeofenceInfoKey" static let persistedAdvicesAndRequest = "PersistedAdvicesAndRequest" static let currentAdviceIdentifier = "CurrentAdviceIdentifier" static let keepDepartedAdvice = "KeepDepartedAdvice" static let firstLegRitNummers = "FirstLegRitNummers" static let appSettings = "AppSettings" } private let HLTTUserDefaults = Foundation.UserDefaults(suiteName: "group.tomas.hltt")! public protocol PreferenceStore: AnyObject { var adviceRequest: Variable<AdviceRequest> { get } func set(adviceRequest: AdviceRequest) var originalAdviceRequest: Variable<AdviceRequest> { get } func set(originalAdviceRequest: AdviceRequest) var currentAdviceIdentifier: Variable<AdviceIdentifier?> { get } func setCurrentAdviceIdentifier(identifier: AdviceIdentifier?) var userId: String { get } var geofenceInfo: [String: [GeofenceModel]]? { get set } // var persistedAdvicesAndRequest: AdvicesAndRequest? { get set } func persistedAdvicesAndRequest(for adviceRequest: AdviceRequest) -> AdvicesAndRequest? func setPersistedAdvicesAndRequest(for adviceRequest: AdviceRequest, persisted: AdvicesAndRequest?) var keepDepartedAdvice: Bool { get set } var firstLegRitNummers: [String] { get set } var appSettings: AppSettings { get set } } public class UserDefaultsPreferenceStore: PreferenceStore { public var adviceRequestSource = VariableSource<AdviceRequest>(value: AdviceRequest(from: nil, to: nil)) public var adviceRequest: Variable<AdviceRequest> public var originalAdviceRequestSource = VariableSource<AdviceRequest>(value: AdviceRequest(from: nil, to: nil)) public var originalAdviceRequest: Variable<AdviceRequest> private let currentAdviceIdentifierSource = VariableSource<AdviceIdentifier?>(value: nil) public let currentAdviceIdentifier: Variable<AdviceIdentifier?> private let defaultKeepDepartedAdvice: Bool public init(defaultKeepDepartedAdvice: Bool) { self.defaultKeepDepartedAdvice = defaultKeepDepartedAdvice adviceRequest = adviceRequestSource.variable originalAdviceRequest = originalAdviceRequestSource.variable currentAdviceIdentifier = currentAdviceIdentifierSource.variable prefill() } private func prefill() { currentAdviceIdentifierSource.value = currentAdviceIdentifierValue if let adviceRequestDefaults = adviceRequestDefaults { adviceRequestSource.value = adviceRequestDefaults } if let originalAdviceRequestDefaults = originalAdviceRequestDefaults { originalAdviceRequestSource.value = originalAdviceRequestDefaults } } public func set(adviceRequest: AdviceRequest) { adviceRequestDefaults = adviceRequest adviceRequestSource.value = adviceRequest } public func set(originalAdviceRequest: AdviceRequest) { originalAdviceRequestDefaults = originalAdviceRequest originalAdviceRequestSource.value = originalAdviceRequest } private var adviceRequestDefaults: AdviceRequest? { get { HLTTUserDefaults.data(forKey: Keys.adviceRequestDefaults) .flatMap { try? JSONDecoder().decode(AdviceRequest.self, from: $0) } } set { let data = newValue.flatMap { try? JSONEncoder().encode($0) } HLTTUserDefaults.set(data, forKey: Keys.adviceRequestDefaults) } } private var originalAdviceRequestDefaults: AdviceRequest? { get { HLTTUserDefaults.data(forKey: Keys.originalAdviceRequestDefaults) .flatMap { try? JSONDecoder().decode(AdviceRequest.self, from: $0) } } set { let data = newValue.flatMap { try? JSONEncoder().encode($0) } HLTTUserDefaults.set(data, forKey: Keys.originalAdviceRequestDefaults) } } public var userId: String { let returnedUserId: String if let userId = HLTTUserDefaults.string(forKey: Keys.userIdKey) { returnedUserId = userId } else { returnedUserId = UUID().uuidString HLTTUserDefaults.set(returnedUserId, forKey: Keys.userIdKey) HLTTUserDefaults.synchronize() } return returnedUserId } public var geofenceInfo: [String: [GeofenceModel]]? { set { let encoder = JSONEncoder() do { HLTTUserDefaults.set(try encoder.encode(newValue), forKey: Keys.geofenceInfoKey) } catch { assertionFailure("Error! \(error)") } } get { let decoder = JSONDecoder() guard let data = HLTTUserDefaults.data(forKey: Keys.geofenceInfoKey) else { return nil } return try? decoder.decode([String: [GeofenceModel]].self, from: data) } } fileprivate var persistedAdvicesAndRequestObject: [String: Any]? { get { guard let data = HLTTUserDefaults.object(forKey: Keys.persistedAdvicesAndRequest) as? Data else { return nil } do { let object = try JSONSerialization.jsonObject(with: data, options: []) return object as? [String: Any] } catch { assertionFailure("ERROR: \(error)") return nil } } set { do { guard let value = newValue else { return } let json: Data = try JSONSerialization.data(withJSONObject: value, options: []) HLTTUserDefaults.set(json, forKey: Keys.persistedAdvicesAndRequest) HLTTUserDefaults.synchronize() } catch { assertionFailure("ERROR: \(error)") } } } public func setCurrentAdviceIdentifier(identifier: AdviceIdentifier?) { currentAdviceIdentifierValue = identifier currentAdviceIdentifierSource.value = identifier } private var currentAdviceIdentifierValue: AdviceIdentifier? { get { HLTTUserDefaults.string(forKey: Keys.currentAdviceIdentifier).map { AdviceIdentifier(rawValue: $0) } } set { HLTTUserDefaults.set(newValue?.rawValue ?? 0, forKey: Keys.currentAdviceIdentifier) HLTTUserDefaults.synchronize() } } public var keepDepartedAdvice: Bool { get { HLTTUserDefaults.object(forKey: Keys.keepDepartedAdvice) as? Bool ?? defaultKeepDepartedAdvice } set { HLTTUserDefaults.set(newValue, forKey: Keys.keepDepartedAdvice) HLTTUserDefaults.synchronize() } } public var firstLegRitNummers: [String] { get { HLTTUserDefaults.object(forKey: Keys.firstLegRitNummers) as? [String] ?? [] } set { HLTTUserDefaults.set(newValue, forKey: Keys.firstLegRitNummers) HLTTUserDefaults.synchronize() } } public func persistedAdvicesAndRequest(for adviceRequest: AdviceRequest) -> AdvicesAndRequest? { do { guard let data = HLTTUserDefaults.data(forKey: "\(Keys.persistedAdvicesAndRequest):\(adviceRequest)") else { return nil } let object = try JSONDecoder().decode(AdvicesAndRequest.self, from: data) return object } catch { print(error) return nil } } public func setPersistedAdvicesAndRequest(for adviceRequest: AdviceRequest, persisted: AdvicesAndRequest?) { do { let data = try JSONEncoder().encode(persisted) HLTTUserDefaults.set(data, forKey: "\(Keys.persistedAdvicesAndRequest):\(adviceRequest)") } catch { print(error) HLTTUserDefaults.set(nil, forKey: "\(Keys.persistedAdvicesAndRequest):\(adviceRequest)") } } public var appSettings: AppSettings { get { AppSettings(rawValue: HLTTUserDefaults.integer(forKey: Keys.appSettings)) } set { HLTTUserDefaults.set(newValue.rawValue, forKey: Keys.appSettings) } } } // MARK: - Settings public struct AppSettings: OptionSet { public let rawValue: Int public static let transferNotificationEnabled = AppSettings(rawValue: 1 << 0) public init(rawValue: Int) { self.rawValue = rawValue } }
mit
fd22b7293a7ebc7cbf05efccb65a1333
30.163498
114
0.713763
4.118593
false
false
false
false
brian-tran16/Fusuma
Sources/FSImageCropView.swift
1
4013
// // FZImageCropView.swift // Fusuma // // Created by Yuta Akizuki on 2015/11/16. // Copyright © 2015年 ytakzk. All rights reserved. // import UIKit final class FSImageCropView: UIScrollView, UIScrollViewDelegate { var imageView = UIImageView() var imageSize: CGSize? var image: UIImage! = nil { didSet { if image != nil { if !imageView.isDescendant(of: self) { self.imageView.alpha = 1.0 self.addSubview(imageView) } } else { imageView.image = nil return } if !fusumaCropImage { // Disable scroll view and set image to fit in view imageView.frame = self.frame imageView.contentMode = .scaleAspectFit self.isUserInteractionEnabled = false imageView.image = image return } let imageSize = self.imageSize ?? image.size let ratioW = (frame.width / imageSize.width) // 400 / 1000 => 0.4 let ratioH = (frame.height / imageSize.height) // 300 / 500 => 0.6 if ratioH > ratioW { imageView.frame = CGRect( origin: CGPoint.zero, size: CGSize(width: imageSize.width * ratioH, height: frame.height) ) } else { imageView.frame = CGRect( origin: CGPoint.zero, size: CGSize(width: frame.width, height: imageSize.height * ratioW) ) } self.contentOffset = CGPoint( x: imageView.center.x - self.center.x, y: imageView.center.y - self.center.y ) self.contentSize = CGSize(width: imageView.frame.width + 1, height: imageView.frame.height + 1) imageView.image = image self.zoomScale = 1.0 } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.backgroundColor = fusumaBackgroundColor self.frame.size = CGSize.zero self.clipsToBounds = true self.imageView.alpha = 0.0 imageView.frame = CGRect(origin: CGPoint.zero, size: CGSize.zero) self.maximumZoomScale = 2.0 self.minimumZoomScale = 0.8 self.showsHorizontalScrollIndicator = false self.showsVerticalScrollIndicator = false self.bouncesZoom = true self.bounces = true self.delegate = self } func changeScrollable(_ isScrollable: Bool) { self.isScrollEnabled = isScrollable } // MARK: UIScrollViewDelegate Protocol func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { let boundsSize = scrollView.bounds.size var contentsFrame = imageView.frame if contentsFrame.size.width < boundsSize.width { contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0 } else { contentsFrame.origin.y = 0.0 } imageView.frame = contentsFrame } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { self.contentSize = CGSize(width: imageView.frame.width + 1, height: imageView.frame.height + 1) } }
mit
c45e9254626639c44bb347d023cc9c9d
27.642857
107
0.520948
5.248691
false
false
false
false
bradhilton/August
Sources/Configuration/Configuration.swift
1
5380
// // Configuration.swift // Request // // Created by Bradley Hilton on 2/5/16. // Copyright © 2016 Brad Hilton. All rights reserved. // public struct Configuration { public enum `Type` { case `default` case ephemeral fileprivate var configuration: URLSessionConfiguration { switch self { case .default: return URLSessionConfiguration.default case .ephemeral: return URLSessionConfiguration.ephemeral // case .Background(identifier: let identifier): return NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(identifier) } } } internal let type: Type // public let identifier: String? public var cachePolicy: URLRequest.CachePolicy public var timeoutInterval: TimeInterval // public var timeoutIntervalForResource: NSTimeInterval public var networkServiceType: URLRequest.NetworkServiceType public var allowsCellularAccess: Bool // public var discretionary: Bool // public var sharedContainerIdentifier: String? // public var sessionSendsLaunchEvents: Bool public var connectionProxyDictionary: [AnyHashable: Any]? public var TLSMinimumSupportedProtocol: SSLProtocol public var TLSMaximumSupportedProtocol: SSLProtocol public var shouldUsePipelining: Bool public var shouldSetCookies: Bool public var cookieAcceptPolicy: HTTPCookie.AcceptPolicy public var additionalHeaders: [String : String]? public var maximumConnectionsPerHost: Int public var maximumSimultaneousTasks: Int? public var cookieStorage: HTTPCookieStorage? public var credentialStorage: URLCredentialStorage? public var cache: URLCache? // public var shouldUseExtendedBackgroundIdleMode: Bool public var protocolClasses: [AnyClass]? public init(_ type: Type = .default) { self.type = type let configuration = self.type.configuration // identifier = configuration.identifier cachePolicy = configuration.requestCachePolicy timeoutInterval = configuration.timeoutIntervalForRequest // timeoutIntervalForResource = configuration.timeoutIntervalForResource networkServiceType = configuration.networkServiceType allowsCellularAccess = configuration.allowsCellularAccess // discretionary = configuration.discretionary // sharedContainerIdentifier = configuration.sharedContainerIdentifier // sessionSendsLaunchEvents = configuration.sessionSendsLaunchEvents connectionProxyDictionary = configuration.connectionProxyDictionary TLSMinimumSupportedProtocol = configuration.tlsMinimumSupportedProtocol TLSMaximumSupportedProtocol = configuration.tlsMaximumSupportedProtocol shouldUsePipelining = configuration.httpShouldUsePipelining shouldSetCookies = configuration.httpShouldSetCookies cookieAcceptPolicy = configuration.httpCookieAcceptPolicy additionalHeaders = configuration.httpAdditionalHeaders?.reduce([String:String]()) { (dictionary, headers: (key: AnyHashable, value: Any)) in var copy = dictionary if let key = headers.key as? String { copy[key] = headers.value as? String } return copy } maximumConnectionsPerHost = configuration.httpMaximumConnectionsPerHost cookieStorage = configuration.httpCookieStorage credentialStorage = configuration.urlCredentialStorage cache = configuration.urlCache // shouldUseExtendedBackgroundIdleMode = configuration.shouldUseExtendedBackgroundIdleMode protocolClasses = configuration.protocolClasses } internal var foundationConfiguration: URLSessionConfiguration { let configuration = type.configuration configuration.requestCachePolicy = cachePolicy configuration.timeoutIntervalForRequest = timeoutInterval // configuration.timeoutIntervalForResource = timeoutIntervalForResource configuration.networkServiceType = networkServiceType configuration.allowsCellularAccess = allowsCellularAccess // configuration.discretionary = discretionary // configuration.sharedContainerIdentifier = sharedContainerIdentifier // configuration.sessionSendsLaunchEvents = sessionSendsLaunchEvents configuration.connectionProxyDictionary = connectionProxyDictionary configuration.tlsMinimumSupportedProtocol = TLSMinimumSupportedProtocol configuration.tlsMaximumSupportedProtocol = TLSMaximumSupportedProtocol configuration.httpShouldUsePipelining = shouldUsePipelining configuration.httpShouldSetCookies = shouldSetCookies configuration.httpCookieAcceptPolicy = cookieAcceptPolicy configuration.httpAdditionalHeaders = additionalHeaders?.reduce([String:String]()) { var headers = $0; headers[$1.0] = $1.1; return headers } configuration.httpMaximumConnectionsPerHost = maximumConnectionsPerHost configuration.httpCookieStorage = cookieStorage configuration.urlCredentialStorage = credentialStorage configuration.urlCache = cache // configuration.shouldUseExtendedBackgroundIdleMode = shouldUseExtendedBackgroundIdleMode configuration.protocolClasses = protocolClasses return configuration } }
mit
7a9863fda846a035a7e83cbaffc43cff
48.805556
149
0.750883
6.411204
false
true
false
false
jianwoo/ios-charts
Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift
1
7134
// // ChartXAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation public class ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart { public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart); } public override func computeAxis(#xValAverageLength: Float, xValues: [String]) { _xAxis.values = xValues; var longest = _xAxis.getLongestLabel() as NSString; var longestSize = longest.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]); _xAxis.labelWidth = floor(longestSize.width + _xAxis.xOffset * 3.5); _xAxis.labelHeight = longestSize.height; } public override func renderAxisLabels(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled || _chart.data === nil) { return; } var xoffset = _xAxis.xOffset; if (_xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left); } else if (_xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right); } else if (_xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, align: .Left); } else if (_xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, align: .Right); } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentLeft, align: .Left); drawLabels(context: context, pos: viewPortHandler.contentRight, align: .Left); } } /// draws the x-labels on the specified y-position internal func drawLabels(#context: CGContext, pos: CGFloat, align: NSTextAlignment) { var labelFont = _xAxis.labelFont; var labelTextColor = _xAxis.labelTextColor; // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0); var bd = _chart.data as! BarChartData; var step = bd.dataSetCount; for (var i = 0; i < _xAxis.values.count; i += _xAxis.axisLabelModulus) { position.x = 0.0; position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0; // consider groups (center label for each group) if (step > 1) { position.y += (CGFloat(step) - 1.0) / 2.0; } transformer.pointValueToPixel(&position); if (viewPortHandler.isInBoundsY(position.y)) { var label = _xAxis.values[i]; ChartUtils.drawText(context: context, text: label, point: CGPoint(x: pos, y: position.y - _xAxis.labelHeight / 2.0), align: align, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]); } } } public override func renderGridLines(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawGridLinesEnabled || _chart.data === nil) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor); CGContextSetLineWidth(context, _xAxis.gridLineWidth); if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } var lineSegments = UnsafeMutablePointer<CGPoint>.alloc(2) var position = CGPoint(x: 0.0, y: 0.0); var bd = _chart.data as! BarChartData; // take into consideration that multiple DataSets increase _deltaX var step = bd.dataSetCount; for (var i = 0; i < _xAxis.values.count; i += _xAxis.axisLabelModulus) { position.x = 0.0; position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5; transformer.pointValueToPixel(&position); if (viewPortHandler.isInBoundsY(position.y)) { lineSegments[0].x = viewPortHandler.contentLeft; lineSegments[0].y = position.y; lineSegments[1].x = viewPortHandler.contentRight; lineSegments[1].y = position.y; CGContextStrokeLineSegments(context, lineSegments, 2); } } lineSegments.dealloc(2); CGContextRestoreGState(context); } internal override func renderAxisLine(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor); CGContextSetLineWidth(context, _xAxis.axisLineWidth); if (_xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } var lineSegments = UnsafeMutablePointer<CGPoint>.alloc(2) if (_xAxis.labelPosition == .Top || _xAxis.labelPosition == .TopInside || _xAxis.labelPosition == .BothSided) { lineSegments[0].x = viewPortHandler.contentRight; lineSegments[0].y = viewPortHandler.contentTop; lineSegments[1].x = viewPortHandler.contentRight; lineSegments[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, lineSegments, 2); } if (_xAxis.labelPosition == .Bottom || _xAxis.labelPosition == .BottomInside || _xAxis.labelPosition == .BothSided) { lineSegments[0].x = viewPortHandler.contentLeft; lineSegments[0].y = viewPortHandler.contentTop; lineSegments[1].x = viewPortHandler.contentLeft; lineSegments[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, lineSegments, 2); } CGContextRestoreGState(context); } }
apache-2.0
66d23ffc8c88c39a937880a7300080bd
35.403061
241
0.590973
5.084818
false
false
false
false
invalidstream/radioonthetv
RadioOnTheTV/RadioOnTheTV/StationsSplitViewController.swift
1
1702
// // StationsSplitViewController.swift // RadioOnTheTV // // Created by Chris Adamson on 3/20/16. // Copyright © 2016 Subsequently & Furthermore, Inc. All rights reserved. // import UIKit class StationsSplitViewController: UISplitViewController { // FOCUS STUFF IS ALL FROM APPLE'S UIKitCatalog SAMPLE CODE /** Set to true from `updateFocusToDetailViewController()` to indicate that the detail view controller should be the preferred focused view when this view controller is next queried. */ private var preferDetailViewControllerOnNextFocusUpdate = false // MARK: UIFocusEnvironment override var preferredFocusedView: UIView? { let preferredFocusedView: UIView? /* Check if a request has been made to move the focus to the detail view controller. */ if preferDetailViewControllerOnNextFocusUpdate { preferredFocusedView = viewControllers.last?.preferredFocusedView preferDetailViewControllerOnNextFocusUpdate = false } else { preferredFocusedView = super.preferredFocusedView } return preferredFocusedView } // MARK: Focus helpers /** Called from a containing `MenuTableViewController` whenever the user selects a table view row in a master view controller. */ func updateFocusToDetailViewController() { preferDetailViewControllerOnNextFocusUpdate = true /* Trigger the focus system to re-query the view hierarchy for preferred focused views. */ setNeedsFocusUpdate() updateFocusIfNeeded() } }
cc0-1.0
2aaebdfc1e03d24a0581ec1d390e3574
27.830508
77
0.667842
5.540717
false
false
false
false
lemonmojo/StartupDisk
StartupDisk/AppDelegate.swift
1
3944
// // AppDelegate.swift // StartupDisk // // Created by Felix Deimel on 04.06.14. // Copyright (c) 2014 Lemon Mojo. All rights reserved. // import Cocoa class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { @IBOutlet var statusMenu: NSMenu! var statusItem: NSStatusItem override init() { let lengthSquare: CGFloat = -2 // TODO: Workaround for Xcode 6 Beta, should actually be: NSSquareStatusItemLength (see http://stackoverflow.com/questions/24024723/swift-using-nsstatusbar-statusitemwithlength-and-nsvariablestatusitemlength) self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(lengthSquare) } override func awakeFromNib() { self.statusItem.menu = self.statusMenu self.statusItem.highlightMode = true } func applicationDidFinishLaunching(aNotification: NSNotification?) { updateStatusItem() } func updateStatusItem() { self.statusItem.title = nil var icon = NSImage(named: "Icon") icon?.size = NSSize(width: 16, height: 16) icon?.setTemplate(true) self.statusItem.image = icon } func menuNeedsUpdate(menu: NSMenu!) { if (menu != self.statusMenu) { return } menu.removeAllItems() var vols = LMVolume.mountedLocalVolumesWithBootableOSXInstallations() var startupDiskDevicePath = LMVolume.startupDiskDevicePath() for vol in vols { var item = NSMenuItem(title: vol.name, action: "statusMenuItemVolume_Action:", keyEquivalent: "") item.representedObject = vol var icon : NSImage? = NSWorkspace.sharedWorkspace().iconForFile(vol.path) if (icon != nil) { icon?.size = NSSize(width: 16, height: 16) } item.image = icon if (vol.devicePath == startupDiskDevicePath) { item.state = NSOnState } menu.addItem(item) } menu.addItem(NSMenuItem.separatorItem()) menu.addItem(NSMenuItem(title: "System Preferences", action: "statusMenuItemSystemPreferences_Action:", keyEquivalent: "")) menu.addItem(NSMenuItem(title: "About StartupDisk", action: "statusMenuItemAbout_Action:", keyEquivalent: "")) menu.addItem(NSMenuItem.separatorItem()) menu.addItem(NSMenuItem(title: "Quit StartupDisk", action: "statusMenuItemQuit_Action:", keyEquivalent: "")) } func statusMenuItemVolume_Action(sender: NSMenuItem) { var vol = sender.representedObject as LMVolume if (vol.setStartupDisk()) { var alert = NSAlert() alert.addButtonWithTitle("Restart") alert.addButtonWithTitle("Cancel") alert.messageText = "Do you want to restart the Computer?" alert.informativeText = NSString(format: "Your Computer will start up using %@.", vol.name) alert.alertStyle = NSAlertStyle.InformationalAlertStyle var response = alert.runModal() if (response == NSAlertFirstButtonReturn) { LMUtils.restartMac() } } } func statusMenuItemSystemPreferences_Action(sender: NSMenuItem) { NSWorkspace.sharedWorkspace().openURL(NSURL(fileURLWithPath: "/System/Library/PreferencePanes/StartupDisk.prefPane")!) } func statusMenuItemAbout_Action(sender: NSMenuItem) { NSApplication.sharedApplication().orderFrontStandardAboutPanel(self) NSApplication.sharedApplication().activateIgnoringOtherApps(true) } func statusMenuItemQuit_Action(sender: NSMenuItem) { NSApplication.sharedApplication().terminate(self) } }
bsd-3-clause
1a0cf402f3e9651178201051ffcecad7
32.151261
247
0.618661
5.095607
false
false
false
false
jverkoey/FigmaKit
Sources/FigmaKit/Node/TextNode.swift
1
1741
extension Node { public final class TextNode: VectorNode { /// Text contained within a text box. public let characters: String /// Style of text including font family and weight. public let style: TypeStyle /// Array with same number of elements as characeters in text box. /// /// Each element is a reference to the styleOverrideTable and maps to the /// corresponding character in the characters field. /// /// Elements with value 0 have the default type style. public let characterStyleOverrides: [Int] /// Map from ID to TypeStyle for looking up style overrides. public let styleOverrideTable: [Int: TypeStyleOverride] private enum CodingKeys: String, CodingKey { case characters case style case characterStyleOverrides case styleOverrideTable } public required init(from decoder: Decoder) throws { let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys) self.characters = try keyedDecoder.decode(String.self, forKey: .characters) self.style = try keyedDecoder.decode(TypeStyle.self, forKey: .style) self.characterStyleOverrides = try keyedDecoder.decode([Int].self, forKey: .characterStyleOverrides) self.styleOverrideTable = try keyedDecoder.decodeIfPresent([Int: TypeStyleOverride].self, forKey: .styleOverrideTable) ?? [:] try super.init(from: decoder) } override var contentDescription: String { return super.contentDescription + """ - characters: \(characters) - style: \(style) - characterStyleOverrides: \(characterStyleOverrides) - styleOverrideTable: \(styleOverrideTable) """ } } }
apache-2.0
95180930c7a02466282a333598888d62
36.847826
131
0.680069
4.809392
false
false
false
false
eduresende/ios-nd-swift-syntax-swift-3
Lesson1/L1_Types&Operators.playground/Contents.swift
1
2345
//: # Types import UIKit import Foundation //: ### Example 1: Bool, Int, Float, Double class LightSwitch { var on: Bool = true } var livingRoomSwitch = LightSwitch() livingRoomSwitch.on //: ### Example 2: Strings and Characters var dollarSign: Character = "$" var myFirstSwiftString: String = "mo' money" var mySecondSwiftString: String = "mo' problems" var concatenatedString:String = myFirstSwiftString + ", " + mySecondSwiftString // para saber o tipo de uma variavel type(of: concatenatedString) //: ### Stay tuned for more on Optionals and Tuples in the upcoming lessons! //: # Operators //: ### Example 1 - Comparison operators let ticketPrice = 7.5 let allowance = 10.0 var iceCreamPrice = 3.0 var pic = UIImage(named:"Chloe.png")! if allowance >= ticketPrice + iceCreamPrice { print("Let's go to the movies!") } else { print("Let's watch a movie at home and eat ice cream") } //: ### Example 2 Logical operators var hungry = true var vegetarian = false if hungry { print("Let's eat!") } else { print("Let's wait.") } if hungry && !vegetarian { print("Let's eat steak!") } else if hungry && vegetarian { print("How about pumpkin curry?") } else { print("nevermind") } var thereIsPie = true if hungry || thereIsPie { print("Let's eat!") } else { print("Let's wait.") } //: ### Example 3 - Ternary conditional //: A theoretical example from Apple's Swift Programming Language. These two statements are equivalent: /*: if question { answer1 } else { answer2 } */ /*: question ? answer1 : answer2 */ // This statement ... //if hungry { // print("Let's eat!") //} else { // print("Let's wait.") //} // Could be rewritten like so ... hungry ? print("Let's eat!") : print("Let's wait.") // This statement... //if hungry || thereIsPie { // print("Let's eat!") //} else { // print("Let's wait.") //} // Could be rewritten like so ... hungry || thereIsPie ? print("Let's eat!") : print("Let's wait.") // Ternary statements can also be used as expressions. let sandwichPrice = 5.0 var tax = true var lunchPrice = sandwichPrice + (tax ? 0.50 : 0) //: ### Extra Example - Comparison operators let birthYear = 1984 if birthYear <= 1989 { print("I will understand Gabrielle's 90s references.") } else { print("I think that Salt n' Peppa are essential seasonings.") }
mit
d1b4a820e171a277914b3525a25019d5
20.126126
103
0.657569
3.428363
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/YPImagePicker/Source/Pages/Gallery/YPAlbumCell.swift
2
1281
// // YPAlbumCell.swift // YPImagePicker // // Created by Sacha Durand Saint Omer on 20/07/2017. // Copyright © 2017 Yummypets. All rights reserved. // import UIKit import Stevia class YPAlbumCell: UITableViewCell { let thumbnail = UIImageView() let title = UILabel() let numberOfItems = UILabel() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let stackView = UIStackView() stackView.axis = .vertical stackView.addArrangedSubview(title) stackView.addArrangedSubview(numberOfItems) sv( thumbnail, stackView ) layout( 6, |-10-thumbnail.size(78), 6 ) align(horizontally: thumbnail-10-stackView) thumbnail.contentMode = .scaleAspectFill thumbnail.clipsToBounds = true title.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular) numberOfItems.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular) } }
mit
efe534f13675e945a2f4ff7ed99256aa
26.234043
99
0.615625
4.942085
false
false
false
false
pro1polaris/SwiftEssentials
SwiftEssentials/SwiftEssentials/_extensions_UIView_PositionContraints.swift
1
4632
// // _extensions_UIView_Position_Constraints.swift // // Created by Paul Hopkins on 2017-03-05. // Modified by Paul Hopkins on 2017-03-22. // Copyright © 2017 Paul Hopkins. All rights reserved. // import UIKit extension UIView { // Apply CenterX Position Contraint (constant: 0) func applyPositionConstraintCenterX(toitem: UIView) { let centerXConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: toitem, attribute: .centerX, multiplier: 1, constant: 0) toitem.addConstraint(centerXConstraint) } // Apply CenterY Position Constraint (constant: 0) func applyPositionConstraintCenterY(toitem: UIView) { let centerYConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: toitem, attribute: .centerY, multiplier: 1, constant: 0) toitem.addConstraint(centerYConstraint) } // Apply All Four Position Constraints (constant: 0) func applyPositionConstraintAll(toitem: UIView) { self.translatesAutoresizingMaskIntoConstraints = false let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toitem, attribute: .top, multiplier: 1, constant: 0) toitem.addConstraint(topConstraint) let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toitem, attribute: .bottom, multiplier: 1, constant: 0) toitem.addConstraint(bottomConstraint) let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: 0) toitem.addConstraint(leftConstraint) let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: toitem, attribute: .right, multiplier: 1, constant: 0) toitem.addConstraint(rightConstraint) } // Apply Top Position Constraint (constant: 0) func applyPositionConstraintTop(toitem: UIView) { let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toitem, attribute: .top, multiplier: 1, constant: 0) toitem.addConstraint(topConstraint) } // Apply Top Position Constraint (constant: Int) func applyPositionConstraintTop_Constant(toitem: UIView, constant: Int) { let topConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: CGFloat(constant)) toitem.addConstraint(topConstraint) } // Apply Bottom Position Constraint (constant: 0) func applyPositionConstraintBottom(toitem: UIView) { let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toitem, attribute: .bottom, multiplier: 1, constant: 0) toitem.addConstraint(bottomConstraint) } // Apply Bottom Position Constraint (constant: Int) func applyPositionConstraintBottom_Constant(toitem: UIView, constant: Int) { let bottomConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: CGFloat(constant)) toitem.addConstraint(bottomConstraint) } // Apply Left Position Constraint (constant: 0) func applyPositionConstraintLeft(toitem: UIView) { let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: 0) toitem.addConstraint(leftConstraint) } // Apply Left Position Constraint (constant: Int) func applyPositionConstraintLeft_Constant(toitem: UIView, constant: Int) { let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: CGFloat(constant)) toitem.addConstraint(leftConstraint) } // Apply Right Position Constraint (constant: 0) func applyPositionConstraintRight(toitem: UIView) { let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: toitem, attribute: .right, multiplier: 1, constant: 0) toitem.addConstraint(rightConstraint) } //Apply Right Position Constraint (constant: Int) func applyPositionConstraintRight_Constant(toitem: UIView, constant: Int) { let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: toitem, attribute: .right, multiplier: 1, constant: CGFloat(constant)) toitem.addConstraint(rightConstraint) } }
mit
3ceb18618fda3c9294a4c47febd68233
53.482353
177
0.727057
4.402091
false
false
false
false
OscarSwanros/swift
benchmark/multi-source/PrimsSplit/Prims.swift
5
5998
//===--- Prims.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 // //===----------------------------------------------------------------------===// // The test implements Prim's algorithm for minimum spanning tree building. // http://en.wikipedia.org/wiki/Prim%27s_algorithm // This class implements array-based heap (priority queue). // It is used to store edges from nodes in spanning tree to nodes outside of it. // We are interested only in the edges with the smallest costs, so if there are // several edges pointing to the same node, we keep only one from them. Thus, // it is enough to record this node instead. // We maintain a map (node index in graph)->(node index in heap) to be able to // update the heap fast when we add a new node to the tree. import TestsUtils class PriorityQueue { final var heap: Array<EdgeCost> final var graphIndexToHeapIndexMap: Array<Int?> // Create heap for graph with NUM nodes. init(Num: Int) { heap = Array<EdgeCost>() graphIndexToHeapIndexMap = Array<Int?>(repeating:nil, count: Num) } func isEmpty() -> Bool { return heap.isEmpty } // Insert element N to heap, maintaining the heap property. func insert(_ n: EdgeCost) { let ind: Int = heap.count heap.append(n) graphIndexToHeapIndexMap[n.to] = heap.count - 1 bubbleUp(ind) } // Insert element N if in's not in the heap, or update its cost if the new // value is less than the existing one. func insertOrUpdate(_ n: EdgeCost) { let id = n.to let c = n.cost if let ind = graphIndexToHeapIndexMap[id] { if heap[ind].cost <= c { // We don't need an edge with a bigger cost return } heap[ind].cost = c heap[ind].from = n.from bubbleUp(ind) } else { insert(n) } } // Restore heap property by moving element at index IND up. // This is needed after insertion, and after decreasing an element's cost. func bubbleUp(_ ind: Int) { var ind = ind let c = heap[ind].cost while (ind != 0) { let p = getParentIndex(ind) if heap[p].cost > c { Swap(p, with: ind) ind = p } else { break } } } // Pop minimum element from heap and restore the heap property after that. func pop() -> EdgeCost? { if (heap.isEmpty) { return nil } Swap(0, with:heap.count-1) let r = heap.removeLast() graphIndexToHeapIndexMap[r.to] = nil bubbleDown(0) return r } // Restore heap property by moving element at index IND down. // This is needed after removing an element, and after increasing an // element's cost. func bubbleDown(_ ind: Int) { var ind = ind let n = heap.count while (ind < n) { let l = getLeftChildIndex(ind) let r = getRightChildIndex(ind) if (l >= n) { break } var min: Int if (r < n && heap[r].cost < heap[l].cost) { min = r } else { min = l } if (heap[ind].cost <= heap[min].cost) { break } Swap(ind, with: min) ind = min } } // Swaps elements I and J in the heap and correspondingly updates // graphIndexToHeapIndexMap. func Swap(_ i: Int, with j : Int) { if (i == j) { return } (heap[i], heap[j]) = (heap[j], heap[i]) let (I, J) = (heap[i].to, heap[j].to) (graphIndexToHeapIndexMap[I], graphIndexToHeapIndexMap[J]) = (graphIndexToHeapIndexMap[J], graphIndexToHeapIndexMap[I]) } // Dumps the heap. func dump() { print("QUEUE") for nodeCost in heap { let to: Int = nodeCost.to let from: Int = nodeCost.from let cost: Double = nodeCost.cost print("(\(from)->\(to), \(cost))") } } func getLeftChildIndex(_ index : Int) -> Int { return index*2 + 1 } func getRightChildIndex(_ index : Int) -> Int { return (index + 1)*2 } func getParentIndex(_ childIndex : Int) -> Int { return (childIndex - 1)/2 } } struct GraphNode { var id: Int var adjList: Array<Int> init(i : Int) { id = i adjList = Array<Int>() } } struct EdgeCost { var to: Int var cost: Double var from: Int } struct Edge : Equatable { var start: Int var end: Int } func ==(lhs: Edge, rhs: Edge) -> Bool { return lhs.start == rhs.start && lhs.end == rhs.end } extension Edge : Hashable { var hashValue: Int { get { return start.hashValue ^ end.hashValue } } } func Prims(_ graph : Array<GraphNode>, _ fun : (Int, Int) -> Double) -> Array<Int?> { var treeEdges = Array<Int?>(repeating:nil, count:graph.count) let queue = PriorityQueue(Num:graph.count) // Make the minimum spanning tree root its own parent for simplicity. queue.insert(EdgeCost(to: 0, cost: 0.0, from: 0)) // Take an element with the smallest cost from the queue and add its // neighbors to the queue if their cost was updated while !queue.isEmpty() { // Add an edge with minimum cost to the spanning tree let e = queue.pop()! let newnode = e.to // Add record about the edge newnode->e.from to treeEdges treeEdges[newnode] = e.from // Check all adjacent nodes and add edges, ending outside the tree, to the // queue. If the queue already contains an edge to an adjacent node, we // replace existing one with the new one in case the new one costs less. for adjNodeIndex in graph[newnode].adjList { if treeEdges[adjNodeIndex] != nil { continue } let newcost = fun(newnode, graph[adjNodeIndex].id) queue.insertOrUpdate(EdgeCost(to: adjNodeIndex, cost: newcost, from: newnode)) } } return treeEdges }
apache-2.0
602efe784b744ff4a5d359f1b52da399
27.028037
85
0.615539
3.700185
false
false
false
false
SeaHub/ImgTagging
ImgTagger/ImgTagger/PasswordResetingViewController.swift
1
3886
// // PasswordResetingViewController.swift // ImgTagger // // Created by SeaHub on 2017/6/30. // Copyright © 2017年 SeaCluster. All rights reserved. // import UIKit import NVActivityIndicatorView import PopupDialog class PasswordResetingViewController: UIViewController { @IBOutlet weak var sendVCodeButtonBelowView: UIView! @IBOutlet weak var maskView: UIView! @IBOutlet weak var phoneTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var vcodeTextField: UITextField! @IBOutlet weak var sendVCodeButton: UIButton! private var indicator: NVActivityIndicatorView! = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), type: .ballScaleRippleMultiple, color: .white, padding: nil) override func viewDidLoad() { super.viewDidLoad() self.configureIndicator() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func indicatorStartAnimating() { UIView.animate(withDuration: 0.5) { self.maskView.alpha = 0.5 } } private func indicatorStopAnimating() { UIView.animate(withDuration: 0.5) { self.maskView.alpha = 0 self.indicator.stopAnimating() } } private func configureIndicator() { self.indicator.center = CGPoint(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2) self.maskView.addSubview(self.indicator) self.indicator.startAnimating() } private func showErrorAlert() { let alert = PopupDialog(title: "Tips", message: "An error occured, please retry later!", image: nil) let cancelButton = CancelButton(title: "OK") { } alert.addButtons([cancelButton]) self.present(alert, animated: true, completion: nil) } @IBAction func sendVCodeButtonClicked(_ sender: Any) { if let phone = self.phoneTextField.text { self.indicatorStopAnimating() APIManager.getVCode(phone: phone, success: { self.indicatorStopAnimating() self.sendVCodeButton.isHidden = true self.sendVCodeButtonBelowView.isHidden = true }, failure: { (error) in self.indicatorStopAnimating() debugPrint(error.localizedDescription) self.showErrorAlert() }) } } @IBAction func resetPasswordButtonClicked(_ sender: Any) { if let _ = self.phoneTextField.text, let newPassword = self.passwordTextField.text, let vcode = self.vcodeTextField.text { self.indicatorStartAnimating() APIManager.changePassword(token: ImgTaggerUtil.userToken!, newPassword: newPassword, vcode: vcode, success: { self.indicatorStopAnimating() let alert = PopupDialog(title: "Tips", message: "Reset successfully", image: nil) let cancelButton = DefaultButton(title: "OK") { self.navigationController?.popToRootViewController(animated: true) } alert.addButtons([cancelButton]) self.present(alert, animated: true, completion: nil) }, failure: { (error) in self.indicatorStopAnimating() debugPrint(error.localizedDescription) self.showErrorAlert() }) } } @IBAction func backButtonClicked(_ sender: Any) { self.navigationController?.popToRootViewController(animated: true) } // MARK: - Keyboard Related override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } }
gpl-3.0
1eb85d1938202293b4d3cebdac786d0d
35.632075
190
0.614473
5.042857
false
false
false
false
Fyrestead/PartialGeometry
SCNGeometrySource.swift
1
1541
// // SCNGeometrySource.swift // // Created by Shon Frazier on 11/23/14. // Copyright (c) 2014 Fyrestead, LLC. All rights reserved. // // Licensed under The BSD 3-Clause License ( http://opensource.org/licenses/BSD-3-Clause ) // See accompanying LICENSE file import Foundation import SceneKit extension SCNGeometrySource { /* Preserves use of existing data buffer by changing only the offset */ func geometrySourceForRangeOfVectors(range: NSRange) -> SCNGeometrySource? { if data == nil { return nil } let newOffset = dataOffset + range.location * (dataStride + bytesPerComponent * componentsPerVector) return SCNGeometrySource( data: data!, semantic: semantic, vectorCount: range.length, floatComponents: floatComponents, componentsPerVector: componentsPerVector, bytesPerComponent: bytesPerComponent, dataOffset: newOffset, dataStride: dataStride) } func geometrySourceForRangeOfPrimitives(range: NSRange, primitiveType: SCNGeometryPrimitiveType) -> SCNGeometrySource? { var newGSource: SCNGeometrySource? switch primitiveType { case .TriangleStrip, .Point: newGSource = geometrySourceForRangeOfVectors(range) case .Triangles: let newRange = NSRange(location: range.location * 3, length: range.length * 3) newGSource = geometrySourceForRangeOfVectors(newRange) case .Line: let newRange = NSRange(location: range.location * 2, length: range.length * 2) newGSource = geometrySourceForRangeOfVectors(newRange) } return newGSource } }
bsd-3-clause
f1b99c06c06354c46bef0e9c9754dc0b
27.018182
121
0.741726
4.109333
false
false
false
false
benlangmuir/swift
test/Interop/Cxx/reference/const-ref-parameter.swift
1
5163
// REQUIRES: objc_interop import ConstRefParameter func testFunction() { let a = OptionsStruct(intOption: 1, floatOption: 2.0) let objc = OptionsConsumerObjC(options: a) _ = objc.doOtherThing(withOptions: a) _ = OptionsConsumerObjC.consumer(withOptions: a) _ = OptionsConsumerObjC.doThing(withOptions: a) var cxx = OptionsConsumerCxx(a) _ = cxx.doOtherThing(a) _ = OptionsConsumerCxx.build(a) _ = OptionsConsumerCxx.doThing(a) } // RUN: %target-swift-ide-test -print-module -module-to-print=ConstRefParameter -I %S/Inputs -source-filename=x -enable-experimental-cxx-interop -enable-objc-interop | %FileCheck -check-prefix=CHECK-IDE-TEST %s // CHECK-IDE-TEST: class OptionsConsumerObjC // CHECK-IDE-TEST: init(options: OptionsStruct) // COM: FIXME: should it be consumer(options:)? // CHECK-IDE-TEST: class func consumer(withOptions options: OptionsStruct) -> Self // COM: FIXME: should it be doThing(options:)? // CHECK-IDE-TEST: class func doThing(withOptions options: OptionsStruct) -> Int32 // COM: FIXME: should it be doOtherThing(options:)? // CHECK-IDE-TEST: func doOtherThing(withOptions options: OptionsStruct) -> Float // CHECK-IDE-TEST: struct OptionsConsumerCxx // CHECK-IDE-TEST: init(_ options: OptionsStruct) // CHECK-IDE-TEST: static func build(_ options: OptionsStruct) -> OptionsConsumerCxx // CHECK-IDE-TEST: static func doThing(_ options: OptionsStruct) -> Int32 // CHECK-IDE-TEST: mutating func doOtherThing(_ options: OptionsStruct) -> Float // RUN: %target-swift-frontend -c -enable-experimental-cxx-interop -enable-objc-interop -I %S/Inputs %s -emit-silgen -o - | %FileCheck %s // COM: FIXME: should it be @in_guaranteed OptionsStruct? https://github.com/apple/swift/issues/60601 // CHECK: [[FN1:%[0-9]+]] = function_ref @$sSo19OptionsConsumerObjCC7optionsABSo0A6StructV_tcfC : $@convention(method) (OptionsStruct, @thick OptionsConsumerObjC.Type) -> @owned OptionsConsumerObjC // CHECK-NEXT: apply [[FN1]] // CHECK-SAME: : $@convention(method) (OptionsStruct, @thick OptionsConsumerObjC.Type) -> @owned OptionsConsumerObjC // COM: FIXME: should it be @in_guaranteed OptionStruct? https://github.com/apple/swift/issues/60601 // CHECK: [[FN2:%[0-9]+]] = objc_method {{%[0-9]+}} : $OptionsConsumerObjC, #OptionsConsumerObjC.doOtherThing!foreign : (OptionsConsumerObjC) -> (OptionsStruct) -> Float, $@convention(objc_method) (@in OptionsStruct, OptionsConsumerObjC) -> Float // CHECK-NEXT: apply [[FN2]] // CHECK-SAME: : $@convention(objc_method) (@in OptionsStruct, OptionsConsumerObjC) -> Float // COM: FIXME: should it be @in_guaranteed OptionStruct? https://github.com/apple/swift/issues/60601 // CHECK: [[FN3:%[0-9]+]] = objc_method {{%[0-9]+}} : $@objc_metatype OptionsConsumerObjC.Type, #OptionsConsumerObjC.consumer!foreign : (OptionsConsumerObjC.Type) -> (OptionsStruct) -> @dynamic_self OptionsConsumerObjC, $@convention(objc_method) (@in OptionsStruct, @objc_metatype OptionsConsumerObjC.Type) -> @autoreleased OptionsConsumerObjC // CHECK-NEXT: apply [[FN3]] // CHECK-SAME: : $@convention(objc_method) (@in OptionsStruct, @objc_metatype OptionsConsumerObjC.Type) -> @autoreleased OptionsConsumerObjC // COM: FIXME: should it be @in_guaranteed OptionStruct? https://github.com/apple/swift/issues/60601 // CHECK: [[FN4:%[0-9]+]] = objc_method {{%[0-9]+}} : $@objc_metatype OptionsConsumerObjC.Type, #OptionsConsumerObjC.doThing!foreign : (OptionsConsumerObjC.Type) -> (OptionsStruct) -> Int32, $@convention(objc_method) (@in OptionsStruct, @objc_metatype OptionsConsumerObjC.Type) -> Int32 // CHECK-NEXT: apply [[FN4]] // CHECK-SAME: : $@convention(objc_method) (@in OptionsStruct, @objc_metatype OptionsConsumerObjC.Type) -> Int32 // COM: FIXME: should it be @in_guaranteed OptionStruct? https://github.com/apple/swift/issues/60601 // CHECK: [[FN5:%[0-9]+]] = function_ref @_ZN18OptionsConsumerCxxC1ERK13OptionsStruct : $@convention(c) (OptionsStruct) -> @out OptionsConsumerCxx // CHECK-NEXT: apply [[FN5]] // CHECK-SAME: : $@convention(c) (OptionsStruct) -> @out OptionsConsumerCxx // COM: FIXME: should it be @in_guaranteed OptionStruct? https://github.com/apple/swift/issues/60601 // CHECK: [[FN6:%[0-9]+]] = function_ref @_ZN18OptionsConsumerCxx12doOtherThingERK13OptionsStruct : $@convention(cxx_method) (@in OptionsStruct, @inout OptionsConsumerCxx) -> Float // CHECK-NEXT: apply [[FN6]] // CHECK-SAME: : $@convention(cxx_method) (@in OptionsStruct, @inout OptionsConsumerCxx) -> Float // COM: FIXME: should it be @in_guaranteed OptionStruct? https://github.com/apple/swift/issues/60601 // CHECK: [[FN6:%[0-9]+]] = function_ref @_ZN18OptionsConsumerCxx5buildERK13OptionsStruct : $@convention(c) (@in OptionsStruct) -> OptionsConsumerCxx // CHECK-NEXT: apply [[FN6]] // CHECK-SAME: : $@convention(c) (@in OptionsStruct) -> OptionsConsumerCxx // COM: FIXME: should it be @in_guaranteed OptionStruct? https://github.com/apple/swift/issues/60601 // CHECK: [[FN7:%[0-9]+]] = function_ref @_ZN18OptionsConsumerCxx7doThingERK13OptionsStruct : $@convention(c) (@in OptionsStruct) -> Int32 // CHECK-NEXT: apply [[FN7]] // CHECK-SAME: : $@convention(c) (@in OptionsStruct) -> Int32
apache-2.0
c53c91dab152171728faf8180b7f8035
66.051948
343
0.731745
3.437417
false
true
false
false
BWITS/xcode-projects
StopWatch/StopWatch/ViewController.swift
1
1098
// // ViewController.swift // StopWatch // // Created by Bill W on 10/01/2016. // Copyright © 2016 AppFish. All rights reserved. // import UIKit class ViewController: UIViewController { var timer = NSTimer() var time = 0 func increaseTimer() { time++ timeWatch.text = String(time) } @IBOutlet weak var timeWatch: UILabel! @IBAction func play(sender: AnyObject) { timer.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("increaseTimer"), userInfo: nil, repeats: true) } @IBAction func pause(sender: AnyObject) { timer.invalidate() } @IBAction func reset(sender: AnyObject) { timer.invalidate() time = 0 timeWatch.text = "0" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
4d8e8ab2d7bb78492e576b9e322ed144
23.377778
138
0.631723
4.441296
false
false
false
false
zirinisp/SlackKit
SlackKit/Sources/CustomProfileField.swift
1
2973
// // CustomProfileField.swift // // Copyright © 2016 Peter Zignego. All rights reserved. // // 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. public struct CustomProfileField { internal(set) public var id: String? internal(set) public var alt: String? internal(set) public var value: String? internal(set) public var hidden: Bool? internal(set) public var hint: String? internal(set) public var label: String? internal(set) public var options: String? internal(set) public var ordering: Int? internal(set) public var possibleValues: [String]? internal(set) public var type: String? internal init(field: [String: Any]?) { id = field?["id"] as? String alt = field?["alt"] as? String value = field?["value"] as? String hidden = field?["is_hidden"] as? Bool hint = field?["hint"] as? String label = field?["label"] as? String options = field?["options"] as? String ordering = field?["ordering"] as? Int possibleValues = field?["possible_values"] as? [String] type = field?["type"] as? String } internal init(id: String?) { self.id = id } internal mutating func updateProfileField(_ profile: CustomProfileField?) { id = profile?.id != nil ? profile?.id : id alt = profile?.alt != nil ? profile?.alt : alt value = profile?.value != nil ? profile?.value : value hidden = profile?.hidden != nil ? profile?.hidden : hidden hint = profile?.hint != nil ? profile?.hint : hint label = profile?.label != nil ? profile?.label : label options = profile?.options != nil ? profile?.options : options ordering = profile?.ordering != nil ? profile?.ordering : ordering possibleValues = profile?.possibleValues != nil ? profile?.possibleValues : possibleValues type = profile?.type != nil ? profile?.type : type } }
mit
1d2211926de9d490beea4898e767dfd9
44.030303
98
0.671602
4.442451
false
false
false
false
zmcartor/Functional-Swift
FunctionalSwift.playground/Contents.swift
1
12909
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // Chapt 2, BattleShip game typealias Distance = Double // This is cool - Regions are defined by whether or not a point lies within. // Region type is any function which takes a Position and returns a Bool. Very cool! typealias Region = (Position) -> Bool struct Position { var x: Double var y: Double } // Functions that return Regions. // Default position is at the origin func circle(radius:Distance, origin:Position = Position(x:0 , y:0)) -> Region { return { point in point.minus(origin).length <= radius } } // Move Regions around by adding offsets. (like CGOffset) func shift(region:Region, offset: Position) -> Region { // we wrap the original region function in another func // which offsets from the point. Neat! return { point in region (point.minus(offset)) } } // By wrapping functions, a whole bunch of great primitives can be created! func invert(region:Region) -> Region { return { point in !region(point) } } func intersection(first:Region , second:Region) -> Region { return { point in first(point) && second(point) } } func union(first:Region, second:Region) -> Region { return { point in first(point) || second(point) } } // Function to create region that are in the first, but NOT in the second. NEAATOO func difference(one:Region , two:Region) -> Region { return intersection(one, second: invert(two)) } struct Ship { var position: Position var firingRange: Distance // dont want to target ships that are too close var unsafeRange: Distance } extension Ship { func canEngageShip(target:Ship) -> Bool { let dx = target.position.x - position.x let dy = target.position.y - position.y let targetDistance = sqrt(dx*dx + dy*dy) return targetDistance <= firingRange } // take into account safe firing range func canSafelyEngageShip(target:Ship) -> Bool { let dx = target.position.x - position.x let dy = target.position.y - position.y let targetDistance = sqrt(dx*dx + dy*dy) return targetDistance <= firingRange && targetDistance > unsafeRange } // Then it gets complicated ... What about firing if a friendly ship is too close to an enemy? // This was previously a huge pain in the ass. Mixed bools and calculations. // With our new Region functions, this is much more declarative. func canSafelyEngageShip2(target: Ship, friendly: Ship) -> Bool { // Fire within the firing range, but NOT the unsafeRange :D let rangeRegion = difference(circle(firingRange), two: circle(unsafeRange)) // firing region is our current range adjusted for Ship's position let firingRegion = shift(rangeRegion, offset:position) // Also dont want to fire within unsafe range around friendly ship let friendlyRegion = shift(circle(unsafeRange), offset:friendly.position) // takes into account unsafe region, friendly ship unsafe region, adjusted for positions!! let resultRegion = difference(firingRegion , two:friendlyRegion) return resultRegion(target.position) } } extension Position { // determine if is within circle firing range func inRange(range:Distance) -> Bool { return sqrt(x*x + y*y) <= range } // Things can be made better with more granular extensions // These are vector calculations. func minus(p:Position) -> Position { return Position(x:x-p.x , y:y-p.y) } // could be called 'distance' var length: Double { return sqrt(x*x + y*y) } } // Chapter 3 , wrapping Core Image typealias Filter = (CIImage) -> CIImage // Functions take in necessary params, and then generate a 'Filter' type to use. func blur(radius:Double) -> Filter { return { image in let parameters = [ kCIInputRadiusKey: radius, kCIInputImageKey: image] let filter = CIFilter(name:"CIGaussianBlur", withInputParameters: parameters)! return filter.outputImage! } } // Generates a constant color. Doesn't apply anything to an image // Notice that the image arg is ignored. func colorGenerator(color: UIColor) -> Filter { return { _ in let parameters = [kCIInputColorKey: color] let filter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: parameters)! return filter.outputImage! } } // overlays another image on top of another func compositeSourceOver(overlay: CIImage) -> Filter { return { image in let parameters = [ kCIInputBackgroundImageKey: image, kCIInputImageKey: overlay] let filter = CIFilter(name: "CISourceOverCompositing",withInputParameters: parameters)! // crop to the size of the input image let cropRect = image.extent return filter.outputImage!.imageByCroppingToRect(cropRect) } } // Combine these things to create a color-overlay filter func coloredOverlay(color:UIColor) -> Filter { return { image in // This applies the overlay filter to image to produce an image let overlayImage = colorGenerator(color)(image) // use overlay as argument to composite fitler. Return resulting image return compositeSourceOver(overlayImage)(image) } } // Blur a photo and put an overlay on top let url = NSURL(string: "http://tinyurl.com/m74sldb") let image = CIImage(contentsOfURL: url!) // Function to compose filters // g(f(x)) func composeFilters(one:Filter , two:Filter) -> Filter { return { image in two(one(image)) } } // create a custom operator to compose filters // inputs are read from left->right like UNIX pipes infix operator -|- { associativity left } func -|- (one:Filter, two:Filter) -> Filter { return { image in two(one(image)) } } // WOW that's pretty cool! let blueOverlayFilter = coloredOverlay(UIColor.blueColor()) -|- compositeSourceOver(image!) // Chapter 4 let x:Any = "hello" let g:String? = "hldlfd" let f = g ?? "nothing" // Chapter 5 // Use enums and associated values to provide bounds of the 'type' of values a result can have. // Generic enums can provide flexible success, errors of any type. Death to magic strings! //Use enums and associated values to provide bounds on the 'type' of values a result can have. Generic enums can provide flexible success, errors of any type. No more magic strings! Dummy values are not 'rich' types; they have no place in a functional programming world. enum Result<T> { case Success(T) case Failure(NSError) } // The 'void' generic type can be created via blah<()> which means no associated value for .Success let thing = Result.Success("HELLO") // Purely Functional Data Structures // By using 'indirect' this becomes a recursive datastructure. // Associated values are either nothing (leaf) or recurse into two separate trees // associated values can be accessed via swtich or 'if case ' statements indirect enum BinarySearchTree<Element:Comparable> { case Leaf case Node(BinarySearchTree<Element> , Element , BinarySearchTree<Element>) init() { self = .Leaf } init(value:Element) { self = .Node(.Leaf , value , .Leaf) } } // TIP - Element could be anything! Structs, whatever can conform to 'comparable' let leaf:BinarySearchTree<Int> = .Leaf let oneTree:BinarySearchTree<Int> = .Node(leaf , 5 , leaf) // As with tree data structures, many of the methods written on trees will be recursive. // Use a 'self' switch to check out the type of an enum. Neat! // recursively count the size of a search tree extension BinarySearchTree { var count:Int { switch self { case .Leaf: return 0 case let .Node(left , _ , right): return 1 + left.count + right.count } } var elements:[Element] { switch self { case .Leaf: return [] case let .Node(left,x,right): return left.elements + [x] + right.elements } } } // Pretty dope use of 'where' operator. extension SequenceType { func all(predicate: (Generator.Element) -> Bool ) -> Bool { for x in self where !predicate(x) { return false } return true } } // Determine is a tree meets requirements to be a binary search tree extension BinarySearchTree where Element:Comparable { var isBST:Bool { switch self { case .Leaf: return true case let .Node(left, x, right): return left.elements.all { y in y < x } && right.elements.all { z in z > x } && left.isBST && right.isBST } } } // Binary tree 'contains' using switch pattern matching :o extension BinarySearchTree { func contains(elm:Element) -> Bool { switch self { case .Leaf: return false case let .Node(_,y,_) where elm == y: return true case let .Node(left,y,_) where elm < y: return left.contains(elm) case let .Node(_,y,right) where elm > y: return right.contains(elm) default: fatalError("nope!") } } } // Insertion into the tree. Trick is to keep recursing down the tree. // Imagine simplist case, then recurse extension BinarySearchTree { mutating func insert(elm:Element) { switch self { case .Leaf: return self = BinarySearchTree(value: elm) case .Node(var left , let y , var right): if elm < y { left.insert(elm) } else if elm > y { right.insert(elm) } // equal return the original tree else { return self = .Node(left, elm , right) } } } } // Why not use an enum ? Because tries can have N-many edges. Enums are for known quantities. // Functional Trie data structure // Tries can have mult edges from a single node struct Trie<Element:Hashable> { var isElement:Bool // determines if it is a leaf. var children:[Element:Trie<Element>] init() { isElement = false children = [:] } init(isElement:Bool , children:[Element:Trie<Element>]) { self.isElement = isElement self.children = children } } // This is like Lisp car,cdr extension Array { var decompose:(Element, [Element])? { if isEmpty { return .None } return (self[startIndex] , Array(self.dropFirst())) } } // Flattens a Trie into an array containing array of each edge extension Trie { var elements: [[Element]] { var result: [[Element]] = isElement ? [[]] : [] for (key, value) in children { result += value.elements.map { [key] + $0 } } return result } } extension Trie where Element:Hashable { init(list:[Element]) { if let (head, tail) = list.decompose { let children = [head:Trie(list:tail)] self = Trie(isElement: false, children: children) } else { self = Trie(isElement:true, children:[:]) } } } // check it out , 'sum' can be written without a loop recursively func sum(arr:[Int]) -> Int { // tuple decomposition here, nice.. guard let (head,tail) = arr.decompose else { return 0 } return head+sum(tail) } // We can use decompose to lookup items in the trie. We lookup an array of 'Elements' // such as array of characters as a string extension Trie { func lookup(key:[Element]) -> Bool { // isElement determines whether the branch is a stopping point. Such as as inserting // cat and catch . The 't' and 'h' are elements. guard let (head, tail) = key.decompose else { return isElement } // go down into the next trie and try to find a match guard let subtrie = children[head] else { return false } return subtrie.lookup(tail) } } // Returns the trie matching a specific prefix extension Trie { func withPrefix(prefix:[Element]) -> Trie<Element>? { // base case, reached the end guard let (head, tail) = prefix.decompose else { return self } guard let remainder = children[head] else {return .None} // recurse down the tree. Very cool! Much more elegant that procedural version return remainder.withPrefix(tail) } // To autocomplete, call withPrefix and return it's elements // basically returns an array of Tries func autocomplete(elms:[Element]) -> [[Element]] { return self.withPrefix(elms)?.elements ?? [] } }
mit
c6d1047bf3f405e34f60e176347de4de
28.405467
270
0.635371
4.188514
false
false
false
false
BryanHoke/swift-corelibs-foundation
Foundation/NSURL.swift
3
34873
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif #if os(OSX) || os(iOS) internal let kCFURLPOSIXPathStyle = CFURLPathStyle.CFURLPOSIXPathStyle internal let kCFURLWindowsPathStyle = CFURLPathStyle.CFURLWindowsPathStyle #endif private func _standardizedPath(path: String) -> String { if !path.absolutePath { return path._nsObject.stringByStandardizingPath } return path } public class NSURL : NSObject, NSSecureCoding, NSCopying { typealias CFType = CFURLRef internal var _base = _CFInfo(typeID: CFURLGetTypeID()) internal var _flags : UInt32 = 0 internal var _encoding : CFStringEncoding = 0 internal var _string : UnsafeMutablePointer<CFString> = nil internal var _baseURL : UnsafeMutablePointer<CFURL> = nil internal var _extra : COpaquePointer = nil internal var _resourceInfo : COpaquePointer = nil internal var _range1 = NSRange(location: 0, length: 0) internal var _range2 = NSRange(location: 0, length: 0) internal var _range3 = NSRange(location: 0, length: 0) internal var _range4 = NSRange(location: 0, length: 0) internal var _range5 = NSRange(location: 0, length: 0) internal var _range6 = NSRange(location: 0, length: 0) internal var _range7 = NSRange(location: 0, length: 0) internal var _range8 = NSRange(location: 0, length: 0) internal var _range9 = NSRange(location: 0, length: 0) internal var _cfObject : CFType { get { if self.dynamicType === NSURL.self { return unsafeBitCast(self, CFType.self) } else { return CFURLCreateWithString(kCFAllocatorSystemDefault, relativeString._cfObject, self.baseURL?._cfObject) } } } deinit { _CFDeinit(self) } public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } static public func supportsSecureCoding() -> Bool { return true } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } internal init(fileURLWithPath path: String, isDirectory isDir: Bool, relativeToURL baseURL: NSURL?) { super.init() let thePath = _standardizedPath(path) if thePath.length > 0 { _CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPOSIXPathStyle, isDir, baseURL?._cfObject) } else if let baseURL = baseURL, let path = baseURL.path { _CFURLInitWithFileSystemPathRelativeToBase(_cfObject, path._cfObject, kCFURLPOSIXPathStyle, baseURL.hasDirectoryPath, nil) } } public convenience init(fileURLWithPath path: String, relativeToURL baseURL: NSURL?) { let thePath = _standardizedPath(path) var isDir : Bool = false if thePath.hasSuffix("/") { isDir = true } else { NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDir) } self.init(fileURLWithPath: thePath, isDirectory: isDir, relativeToURL: baseURL) } public convenience init(fileURLWithPath path: String, isDirectory isDir: Bool) { self.init(fileURLWithPath: path, isDirectory: isDir, relativeToURL: nil) } public convenience init(fileURLWithPath path: String) { let thePath = _standardizedPath(path) var isDir : Bool = false if thePath.hasSuffix("/") { isDir = true } else { NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDir) } self.init(fileURLWithPath: thePath, isDirectory: isDir, relativeToURL: nil) } public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory isDir: Bool, relativeToURL baseURL: NSURL?) { // TODO: Not sure if this one is required NSUnimplemented() } public convenience init?(string URLString: String) { self.init(string: URLString, relativeToURL:nil) } public init?(string URLString: String, relativeToURL baseURL: NSURL?) { super.init() if !_CFURLInitWithURLString(_cfObject, URLString._cfObject, true, baseURL?._cfObject) { return nil } } public init(dataRepresentation data: NSData, relativeToURL baseURL: NSURL?) { super.init() // _CFURLInitWithURLString does not fail if checkForLegalCharacters == false if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, UnsafePointer(data.bytes), data.length, CFStringEncoding(kCFStringEncodingUTF8), false) { _CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject) } else if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, UnsafePointer(data.bytes), data.length, CFStringEncoding(kCFStringEncodingISOLatin1), false) { _CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject) } else { fatalError() } } public init(absoluteURLWithDataRepresentation data: NSData, relativeToURL baseURL: NSURL?) { super.init() if _CFURLInitAbsoluteURLWithBytes(_cfObject, UnsafePointer(data.bytes), data.length, CFStringEncoding(kCFStringEncodingUTF8), baseURL?._cfObject) { return } if _CFURLInitAbsoluteURLWithBytes(_cfObject, UnsafePointer(data.bytes), data.length, CFStringEncoding(kCFStringEncodingISOLatin1), baseURL?._cfObject) { return } fatalError() } /* Returns the data representation of the URL's relativeString. If the URL was initialized with -initWithData:relativeToURL:, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the relativeString encoded with NSUTF8StringEncoding. */ public var dataRepresentation: NSData { let bytesNeeded = CFURLGetBytes(_cfObject, nil, 0) assert(bytesNeeded > 0) let buffer = malloc(bytesNeeded) let bytesFilled = CFURLGetBytes(_cfObject, UnsafeMutablePointer<UInt8>(buffer), bytesNeeded) if bytesFilled == bytesNeeded { return NSData(bytesNoCopy: buffer, length: bytesNeeded, freeWhenDone: true) } else { fatalError() } } public var absoluteString: String? { if let absURL = CFURLCopyAbsoluteURL(_cfObject) { return CFURLGetString(absURL)._swiftObject } else { return nil } } // The relative portion of a URL. If baseURL is nil, or if the receiver is itself absolute, this is the same as absoluteString public var relativeString: String { return CFURLGetString(_cfObject)._swiftObject } public var baseURL: NSURL? { return CFURLGetBaseURL(_cfObject)?._nsObject } // if the receiver is itself absolute, this will return self. public var absoluteURL: NSURL? { return CFURLCopyAbsoluteURL(_cfObject)?._nsObject } /* Any URL is composed of these two basic pieces. The full URL would be the concatenation of [myURL scheme], ':', [myURL resourceSpecifier] */ public var scheme: String? { return CFURLCopyScheme(_cfObject)?._swiftObject } internal var _isAbsolute : Bool { return self.baseURL == nil && self.scheme != nil } public var resourceSpecifier: String? { // Note that this does NOT have the same meaning as CFURL's resource specifier, which, for decomposeable URLs is merely that portion of the URL which comes after the path. NSURL means everything after the scheme. if !_isAbsolute { return self.relativeString } else { let cf = _cfObject guard CFURLCanBeDecomposed(cf) else { return CFURLCopyResourceSpecifier(cf)?._swiftObject } guard baseURL == nil else { return CFURLGetString(cf)?._swiftObject } let netLoc = CFURLCopyNetLocation(cf)?._swiftObject let path = CFURLCopyPath(cf)?._swiftObject let theRest = CFURLCopyResourceSpecifier(cf)?._swiftObject if let netLoc = netLoc { return "//\(netLoc)\(path ?? "")\(theRest ?? "")" } else if let path = path { return "\(path)\(theRest ?? "")" } else { return theRest } } } /* If the URL conforms to rfc 1808 (the most common form of URL), the following accessors will return the various components; otherwise they return nil. The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is @"//". In all cases, they return the component's value after resolving the receiver against its base URL. */ public var host: String? { return CFURLCopyHostName(_cfObject)?._swiftObject } public var port: NSNumber? { let port = CFURLGetPortNumber(_cfObject) if port == -1 { return nil } else { return NSNumber(int: port) } } public var user: String? { return CFURLCopyUserName(_cfObject)?._swiftObject } public var password: String? { let absoluteURL = CFURLCopyAbsoluteURL(_cfObject) #if os(Linux) let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, kCFURLComponentPassword, nil) #else let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, .Password, nil) #endif guard passwordRange.location != kCFNotFound else { return nil } // For historical reasons, the password string should _not_ have its percent escapes removed. let bufSize = CFURLGetBytes(absoluteURL, nil, 0) var buf = [UInt8](count: bufSize, repeatedValue: 0) guard CFURLGetBytes(absoluteURL, &buf, bufSize) >= 0 else { return nil } let passwordBuf = buf[passwordRange.location ..< passwordRange.location+passwordRange.length] return passwordBuf.withUnsafeBufferPointer { ptr in NSString(bytes: ptr.baseAddress, length: passwordBuf.count, encoding: NSUTF8StringEncoding)?._swiftObject } } public var path: String? { let absURL = CFURLCopyAbsoluteURL(_cfObject) return CFURLCopyFileSystemPath(absURL, kCFURLPOSIXPathStyle)?._swiftObject } public var fragment: String? { return CFURLCopyFragment(_cfObject, nil)?._swiftObject } public var parameterString: String? { return CFURLCopyParameterString(_cfObject, nil)?._swiftObject } public var query: String? { return CFURLCopyQueryString(_cfObject, nil)?._swiftObject } // The same as path if baseURL is nil public var relativePath: String? { return CFURLCopyFileSystemPath(_cfObject, kCFURLPOSIXPathStyle)?._swiftObject } /* Determines if a given URL string's path represents a directory (i.e. the path component in the URL string ends with a '/' character). This does not check the resource the URL refers to. */ public var hasDirectoryPath: Bool { return CFURLHasDirectoryPath(_cfObject) } /* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding. */ public func getFileSystemRepresentation(buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferLength: Int) -> Bool { return CFURLGetFileSystemRepresentation(_cfObject, true, UnsafeMutablePointer<UInt8>(buffer), maxBufferLength) } /* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding. The returned C string will be automatically freed just as a returned object would be released; your code should copy the representation or use getFileSystemRepresentation:maxLength: if it needs to store the representation outside of the autorelease context in which the representation is created. */ public var fileSystemRepresentation: UnsafePointer<Int8> { NSUnimplemented() } // Whether the scheme is file:; if [myURL isFileURL] is YES, then [myURL path] is suitable for input into NSFileManager or NSPathUtilities. public var fileURL: Bool { return _CFURLIsFileURL(_cfObject) } /* A string constant for the "file" URL scheme. If you are using this to compare to a URL's scheme to see if it is a file URL, you should instead use the NSURL fileURL property -- the fileURL property is much faster. */ public var standardizedURL: NSURL? { NSUnimplemented() } /* Returns whether the URL's resource exists and is reachable. This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. If this method returns NO, the optional error is populated. This method is currently applicable only to URLs for file system resources. For other URL types, NO is returned. Symbol is present in iOS 4, but performs no operation. */ /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future public func resourceIsReachable() throws -> Bool { NSUnimplemented() } /* Returns a file path URL that refers to the same resource as a specified URL. File path URLs use a file system style path. An error will occur if the url parameter is not a file URL. A file reference URL's resource must exist and be reachable to be converted to a file path URL. Symbol is present in iOS 4, but performs no operation. */ public var filePathURL: NSURL? { NSUnimplemented() } override internal var _cfTypeID: CFTypeID { return CFURLGetTypeID() } } extension NSCharacterSet { // Predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters:. // Returns a character set containing the characters allowed in an URL's user subcomponent. public class func URLUserAllowedCharacterSet() -> NSCharacterSet { return _CFURLComponentsGetURLUserAllowedCharacterSet()._nsObject } // Returns a character set containing the characters allowed in an URL's password subcomponent. public class func URLPasswordAllowedCharacterSet() -> NSCharacterSet { return _CFURLComponentsGetURLPasswordAllowedCharacterSet()._nsObject } // Returns a character set containing the characters allowed in an URL's host subcomponent. public class func URLHostAllowedCharacterSet() -> NSCharacterSet { return _CFURLComponentsGetURLHostAllowedCharacterSet()._nsObject } // Returns a character set containing the characters allowed in an URL's path component. ';' is a legal path character, but it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the URLPathAllowedCharacterSet). public class func URLPathAllowedCharacterSet() -> NSCharacterSet { return _CFURLComponentsGetURLPathAllowedCharacterSet()._nsObject } // Returns a character set containing the characters allowed in an URL's query component. public class func URLQueryAllowedCharacterSet() -> NSCharacterSet { return _CFURLComponentsGetURLQueryAllowedCharacterSet()._nsObject } // Returns a character set containing the characters allowed in an URL's fragment component. public class func URLFragmentAllowedCharacterSet() -> NSCharacterSet { return _CFURLComponentsGetURLFragmentAllowedCharacterSet()._nsObject } } extension NSString { // Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored. public func stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters: NSCharacterSet) -> String? { return _CFStringCreateByAddingPercentEncodingWithAllowedCharacters(kCFAllocatorSystemDefault, self._cfObject, allowedCharacters._cfObject)._swiftObject } // Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters. public var stringByRemovingPercentEncoding: String? { return _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, self._cfObject)._swiftObject } } extension NSURL { /* The following methods work on the path portion of a URL in the same manner that the NSPathUtilities methods on NSString do. */ public class func fileURLWithPathComponents(components: [String]) -> NSURL? { let path = String.pathWithComponents(components) if components.last == "/" { return NSURL(fileURLWithPath: path, isDirectory: true) } else { return NSURL(fileURLWithPath: path) } } public var pathComponents: [String]? { return self.path?.pathComponents } public var lastPathComponent: String? { return self.path?.lastPathComponent } public var pathExtension: String? { return self.path?.pathExtension } public func URLByAppendingPathComponent(pathComponent: String) -> NSURL? { var result : NSURL? = URLByAppendingPathComponent(pathComponent, isDirectory: false) if !pathComponent.hasSuffix("/") && fileURL { if let urlWithoutDirectory = result, path = urlWithoutDirectory.path { var isDir : Bool = false if NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDir) && isDir { result = self.URLByAppendingPathComponent(pathComponent, isDirectory: true) } } } return result } public func URLByAppendingPathComponent(pathComponent: String, isDirectory: Bool) -> NSURL? { return CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, _cfObject, pathComponent._cfObject, isDirectory)?._nsObject } public var URLByDeletingLastPathComponent: NSURL? { return CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, _cfObject)?._nsObject } public func URLByAppendingPathExtension(pathExtension: String) -> NSURL? { return CFURLCreateCopyAppendingPathExtension(kCFAllocatorSystemDefault, _cfObject, pathExtension._cfObject)?._nsObject } public var URLByDeletingPathExtension: NSURL? { return CFURLCreateCopyDeletingPathExtension(kCFAllocatorSystemDefault, _cfObject)?._nsObject } /* The following methods work only on `file:` scheme URLs; for non-`file:` scheme URLs, these methods return the URL unchanged. */ public var URLByStandardizingPath: NSURL? { NSUnimplemented() } public var URLByResolvingSymlinksInPath: NSURL? { NSUnimplemented() } } // NSURLQueryItem encapsulates a single query name-value pair. The name and value strings of a query name-value pair are not percent encoded. For use with the NSURLComponents queryItems property. public class NSURLQueryItem : NSObject, NSSecureCoding, NSCopying { public init(name: String, value: String?) { self.name = name self.value = value } public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } required public init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } public let name: String public let value: String? } public class NSURLComponents : NSObject, NSCopying { private let _components : CFURLComponentsRef! public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } // Initialize a NSURLComponents with the components of a URL. If resolvingAgainstBaseURL is YES and url is a relative URL, the components of [url absoluteURL] are used. If the url string from the NSURL is malformed, nil is returned. public init?(URL url: NSURL, resolvingAgainstBaseURL resolve: Bool) { _components = _CFURLComponentsCreateWithURL(kCFAllocatorSystemDefault, url._cfObject, resolve) super.init() if _components == nil { return nil } } // Initialize a NSURLComponents with a URL string. If the URLString is malformed, nil is returned. public init?(string URLString: String) { _components = _CFURLComponentsCreateWithString(kCFAllocatorSystemDefault, URLString._cfObject) super.init() if _components == nil { return nil } } public override init() { _components = _CFURLComponentsCreate(kCFAllocatorSystemDefault) } // Returns a URL created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. public var URL: NSURL? { if let result = _CFURLComponentsCopyURL(_components) { return unsafeBitCast(result, NSURL.self) } else { return nil } } // Returns a URL created from the NSURLComponents relative to a base URL. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. public func URLRelativeToURL(baseURL: NSURL?) -> NSURL? { NSUnimplemented() } // Returns a URL string created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. public var string: String? { NSUnimplemented() } // Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided. // Getting these properties removes any percent encoding these components may have (if the component allows percent encoding). Setting these properties assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). // Attempting to set the scheme with an invalid scheme string will cause an exception. public var scheme: String? { get { return _CFURLComponentsCopyScheme(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetScheme(_components, new?._cfObject) { fatalError() } } } public var user: String? { get { return _CFURLComponentsCopyUser(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetUser(_components, new?._cfObject) { fatalError() } } } public var password: String? { get { return _CFURLComponentsCopyPassword(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPassword(_components, new?._cfObject) { fatalError() } } } public var host: String? { get { return _CFURLComponentsCopyHost(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetHost(_components, new?._cfObject) { fatalError() } } } // Attempting to set a negative port number will cause an exception. public var port: NSNumber? { get { if let result = _CFURLComponentsCopyPort(_components) { return unsafeBitCast(result, NSNumber.self) } else { return nil } } set(new) { if !_CFURLComponentsSetPort(_components, new?._cfObject) { fatalError() } } } public var path: String? { get { return _CFURLComponentsCopyPath(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPath(_components, new?._cfObject) { fatalError() } } } public var query: String? { get { return _CFURLComponentsCopyQuery(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetQuery(_components, new?._cfObject) { fatalError() } } } public var fragment: String? { get { return _CFURLComponentsCopyFragment(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetFragment(_components, new?._cfObject) { fatalError() } } } // Getting these properties retains any percent encoding these components may have. Setting these properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause an exception. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the URLPathAllowedCharacterSet). public var percentEncodedUser: String? { get { return _CFURLComponentsCopyPercentEncodedUser(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedUser(_components, new?._cfObject) { fatalError() } } } public var percentEncodedPassword: String? { get { return _CFURLComponentsCopyPercentEncodedPassword(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedPassword(_components, new?._cfObject) { fatalError() } } } public var percentEncodedHost: String? { get { return _CFURLComponentsCopyPercentEncodedHost(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedHost(_components, new?._cfObject) { fatalError() } } } public var percentEncodedPath: String? { get { return _CFURLComponentsCopyPercentEncodedPath(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedPath(_components, new?._cfObject) { fatalError() } } } public var percentEncodedQuery: String? { get { return _CFURLComponentsCopyPercentEncodedQuery(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedQuery(_components, new?._cfObject) { fatalError() } } } public var percentEncodedFragment: String? { get { return _CFURLComponentsCopyPercentEncodedFragment(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedFragment(_components, new?._cfObject) { fatalError() } } } /* These properties return the character range of a component in the URL string returned by -[NSURLComponents string]. If the component does not exist in the NSURLComponents object, {NSNotFound, 0} is returned. Note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. */ private final func _convertRange(r : CFRange) -> NSRange { return NSMakeRange(r.location == kCFNotFound ? NSNotFound : r.location, r.length) } public var rangeOfScheme: NSRange { return _convertRange(_CFURLComponentsGetRangeOfScheme(_components)) } public var rangeOfUser: NSRange { return _convertRange(_CFURLComponentsGetRangeOfUser(_components)) } public var rangeOfPassword: NSRange { return _convertRange(_CFURLComponentsGetRangeOfPassword(_components)) } public var rangeOfHost: NSRange { return _convertRange(_CFURLComponentsGetRangeOfHost(_components)) } public var rangeOfPort: NSRange { return _convertRange(_CFURLComponentsGetRangeOfPort(_components)) } public var rangeOfPath: NSRange { return _convertRange(_CFURLComponentsGetRangeOfPath(_components)) } public var rangeOfQuery: NSRange { return _convertRange(_CFURLComponentsGetRangeOfQuery(_components)) } public var rangeOfFragment: NSRange { return _convertRange(_CFURLComponentsGetRangeOfFragment(_components)) } // The getter method that underlies the queryItems property parses the query string based on these delimiters and returns an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, in the order in which they appear in the original query string. Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the NSURLComponents object has an empty query component, queryItems returns an empty NSArray. If the NSURLComponents object has no query component, queryItems returns nil. // The setter method that underlies the queryItems property combines an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, into a query string and sets the NSURLComponents' query property. Passing an empty NSArray to setQueryItems sets the query component of the NSURLComponents object to an empty string. Passing nil to setQueryItems removes the query component of the NSURLComponents object. // Note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a NSURLQueryItem with a zero-length name and and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value. public var queryItems: [NSURLQueryItem]? { get { // This CFURL implementation returns a CFArray of CFDictionary; each CFDictionary has an entry for name and optionally an entry for value if let queryArray = _CFURLComponentsCopyQueryItems(_components) { let count = CFArrayGetCount(queryArray) return (0..<count).map { idx in let oneEntry = unsafeBitCast(CFArrayGetValueAtIndex(queryArray, idx), NSDictionary.self) let entryName = oneEntry.objectForKey("name"._cfObject) as! String let entryValue = oneEntry.objectForKey("value"._cfObject) as? String return NSURLQueryItem(name: entryName, value: entryValue) } } else { return nil } } set(new) { if let new = new { // The CFURL implementation requires two CFArrays, one for names and one for values var names = [CFTypeRef]() var values = [CFTypeRef]() for entry in new { names.append(entry.name._cfObject) if let v = entry.value { values.append(v._cfObject) } else { values.append(kCFNull) } } _CFURLComponentsSetQueryItems(_components, names._cfObject, values._cfObject) } else { self.percentEncodedQuery = nil } } } } extension NSURL : _CFBridgable { } extension CFURLRef : _NSBridgable { typealias NSType = NSURL internal var _nsObject: NSType { return unsafeBitCast(self, NSType.self) } }
apache-2.0
7326d1068073fc614a667ad611396f6a
43.367684
740
0.667135
5.427704
false
false
false
false
xPutnikx/ProvisioningFlow
ProvisioningFlow/poc/task/RegisterUserTask.swift
1
2152
// // RegisterUserTask.swift // ProvisioningFlow // // Created by Vladimir Hudnitsky on 9/18/17. // Copyright © 2017 Vladimir Hudnitsky. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class RegisterUserTask: FlowObservableTask{ typealias ParamType = Void typealias ResultType = AuthenticatedUser func provideViewControllerNibName() -> String { return "RegisterUserViewController" } func createFlowController(nibName: String, _ param: Void, _ subscriber: AnyObserver<AuthenticatedUser>) -> FlowViewController<Void, AuthenticatedUser> { return RegisterUserViewController(nibName: nibName, param: param, subscriber: subscriber) } } class RegisterUserViewController: FlowViewController<Void, AuthenticatedUser>{ private var usernameTextField: UITextField? func nextButtonPressed(_ sender: Any) { if(self.usernameTextField != nil && self.usernameTextField!.text != nil){ self.onFinish(data: AuthenticatedUser(name: self.usernameTextField!.text!, id: "mock_id")) } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if(indexPath.row == 1){ let cell: CellWithButton = Bundle.main.loadNibNamed("CellWithButton", owner: nil, options: nil)![0] as! CellWithButton cell.button.setTitle("Done", for: .normal) cell.button.addTarget(self, action: #selector(nextButtonPressed(_:)), for: .touchUpInside) return cell }else{ let cell: CellWithEditText = Bundle.main.loadNibNamed("CellWithEditText", owner: nil, options: nil)![0] as! CellWithEditText self.usernameTextField = cell.editText return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if(indexPath.row == 1){ self.nextButtonPressed(tableView) } } }
apache-2.0
530492fb0ec8f0887b228b50ca3a3d36
34.262295
156
0.6755
4.737885
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/QMUIKit/UIKitExtensions/QMUILabel.swift
1
4670
// // QMUILabel.swift // QMUI.swift // // Created by 伯驹 黄 on 2017/3/17. // Copyright © 2017年 伯驹 黄. All rights reserved. // /** * `QMUILabel`支持通过`contentEdgeInsets`属性来实现类似padding的效果。 * * 同时通过将`canPerformCopyAction`置为`YES`来开启长按复制文本的功能,长按时label的背景色默认为`highlightedBackgroundColor` */ class QMUILabel: UILabel { /// 控制label内容的padding,默认为UIEdgeInsetsZero public var contentEdgeInsets: UIEdgeInsets = .zero /// 是否需要长按复制的功能,默认为 false。 /// 长按时的背景色通过`highlightedBackgroundColor`设置。 @IBInspectable public var canPerformCopyAction = false { didSet { setCanPerformCopyAction() } } /// 如果打开了`canPerformCopyAction`,则长按时背景色将会被改为`highlightedBackgroundColor` @IBInspectable public var highlightedBackgroundColor: UIColor? { didSet { tempBackgroundColor = backgroundColor } } private var tempBackgroundColor: UIColor? private var longGestureRecognizer: UILongPressGestureRecognizer? deinit { NotificationCenter.default.removeObserver(self) } override func sizeThatFits(_ size: CGSize) -> CGSize { let targetSize = CGSize(width: size.width - contentEdgeInsets.horizontalValue, height: size.height - contentEdgeInsets.verticalValue) var retulet = super.sizeThatFits(targetSize) retulet.width += contentEdgeInsets.horizontalValue retulet.height += contentEdgeInsets.verticalValue return retulet } override func drawText(in rect: CGRect) { super.drawText(in: rect.inset(by: contentEdgeInsets)) } override var isHighlighted: Bool { didSet { if let highlightedBackgroundColor = highlightedBackgroundColor { backgroundColor = isHighlighted ? highlightedBackgroundColor : tempBackgroundColor } } } // MARK: - 长按复制功能 private func setCanPerformCopyAction() { if canPerformCopyAction && longGestureRecognizer == nil { isUserInteractionEnabled = true longGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGestureRecognizer)) addGestureRecognizer(longGestureRecognizer!) NotificationCenter.default.addObserver(self, selector: #selector(handleMenuWillHideNotification), name: UIMenuController.willHideMenuNotification, object: nil) if !(highlightedBackgroundColor != nil) { highlightedBackgroundColor = TableViewCellSelectedBackgroundColor // 设置个默认值 } } else if let longGestureRecognizer = longGestureRecognizer, !canPerformCopyAction { removeGestureRecognizer(longGestureRecognizer) self.longGestureRecognizer = nil isUserInteractionEnabled = false NotificationCenter.default.removeObserver(self) } } override var canBecomeFirstResponder: Bool { return canPerformCopyAction } override func canPerformAction(_ action: Selector, withSender _: Any?) -> Bool { if canBecomeFirstResponder { return action == #selector(copyString) } return false } @objc private func copyString() { if canPerformCopyAction { let pasteboard = UIPasteboard.general if let text = text { pasteboard.string = text } } } @objc private func handleLongPressGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) { if !canPerformCopyAction { return } if gestureRecognizer.state == .began { becomeFirstResponder() let menuController = UIMenuController.shared let copyMenuItem = UIMenuItem(title: "复制", action: #selector(copyString)) menuController.menuItems = [copyMenuItem] menuController.setTargetRect(frame, in: superview!) menuController.setMenuVisible(true, animated: true) // 默认背景色 tempBackgroundColor = backgroundColor backgroundColor = highlightedBackgroundColor } } @objc private func handleMenuWillHideNotification(_: NSNotification) { if !canPerformCopyAction { return } if let tempBackgroundColor = tempBackgroundColor { backgroundColor = tempBackgroundColor } } }
mit
cfc21b3aef17edce2cc4bee04c21212c
32.210526
171
0.658139
5.57702
false
false
false
false
qasim/CDFLabs
CDFLabs/AppDelegate.swift
1
5484
// // AppDelegate.swift // CDFLabs // // Created by Qasim Iqbal on 12/19/15. // Copyright © 2015 Qasim Iqbal. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var mainController: MainController? var computersViewController: ComputersViewController? var printersViewController: PrintersViewController? var locationsViewController: LocationsViewController? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.mainController = MainController() // View initialization self.computersViewController = ComputersViewController() self.printersViewController = PrintersViewController() self.locationsViewController = LocationsViewController() self.mainController?.viewControllers = [ self.computersViewController!, self.printersViewController!, self.locationsViewController! ] // Tab bar item creation let computerIcon = UIImage(named: "ComputerIcon")?.imageWithRenderingMode(.AlwaysOriginal) let computerSelectedIcon = UIImage(named: "ComputerSelectedIcon")?.imageWithRenderingMode(.AlwaysOriginal) self.computersViewController!.tabBarItem = UITabBarItem(title: "Computers", image: computerIcon, tag: 0) self.computersViewController!.tabBarItem.selectedImage = computerSelectedIcon let printerIcon = UIImage(named: "PrinterIcon")?.imageWithRenderingMode(.AlwaysOriginal) let printerSelectedIcon = UIImage(named:"PrinterSelectedIcon")?.imageWithRenderingMode(.AlwaysOriginal) self.printersViewController!.tabBarItem = UITabBarItem(title: "Printers", image: printerIcon, tag: 1) self.printersViewController!.tabBarItem.selectedImage = printerSelectedIcon let locationIcon = UIImage(named: "LocationIcon")?.imageWithRenderingMode(.AlwaysOriginal) let locationSelectedIcon = UIImage(named:"LocationSelectedIcon")?.imageWithRenderingMode(.AlwaysOriginal) self.locationsViewController!.tabBarItem = UITabBarItem( title: "Locations", image: locationIcon, tag: 2) self.locationsViewController!.tabBarItem.selectedImage = locationSelectedIcon self.mainController?.selectedIndex = 0 // Tab bar item styling let tabBarItemAppearance = UITabBarItem.appearance() tabBarItemAppearance.setTitleTextAttributes( [NSForegroundColorAttributeName: UIColor.cdfDisabledBlueColor()], forState: .Normal) tabBarItemAppearance.setTitleTextAttributes( [NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Selected) // Navigation bar styling let navigationAppearance = UINavigationBar.appearance() navigationAppearance.barStyle = UIBarStyle.Default navigationAppearance.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.whiteColor() ] navigationAppearance.barTintColor = UIColor.cdfBlueColor() navigationAppearance.setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default) navigationAppearance.shadowImage = UIImage() navigationAppearance.translucent = false UIBarButtonItem.appearance().tintColor = UIColor.whiteColor() // Window styling application.statusBarStyle = UIStatusBarStyle.LightContent self.window?.backgroundColor = UIColor.cdfGreyColor() self.window?.rootViewController = self.mainController 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
b1b9bce05f19c83abb3e8ba137790ab2
51.219048
285
0.736823
5.966268
false
false
false
false
fonkadelic/Macoun
WoidKonf/BasicTableViewCell.swift
1
756
// // BasicTableViewCell.swift // UIKonf // // Copyright © 2016 Raised by Wolves. All rights reserved. // import UIKit import Reusable class BasicTableViewCell: UITableViewCell, NibReusable { @IBOutlet var titleLabel: UILabel! @IBOutlet var descriptionLabel: UILabel! @IBOutlet var pictureView: UIImageView! override func awakeFromNib() { super.awakeFromNib() let selected = UIView() selected.backgroundColor = UIColor(named: "selected")?.withAlphaComponent(0.8) selectedBackgroundView = selected } func configure(withTitle title: String, detail: String, image: UIImage) { titleLabel.text = title descriptionLabel.text = detail pictureView.image = image } }
mit
0b14056a0ef99b89f4edeba0a2753989
24.166667
86
0.683444
4.839744
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/IssuersViewController.swift
1
3272
// // IssuersViewController.swift // MercadoPagoSDK // // Created by Matias Gualino on 9/1/15. // Copyright (c) 2015 com.mercadopago. All rights reserved. // import UIKit public class IssuersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var publicKey : String? var paymentMethod: PaymentMethod? var callback: ((issuer: Issuer) -> Void)? @IBOutlet weak private var tableView : UITableView! var loadingView : UILoadingView! var items : [Issuer]! var bundle: NSBundle? = MercadoPago.getBundle() init(merchantPublicKey: String, paymentMethod: PaymentMethod, callback: (issuer: Issuer) -> Void) { super.init(nibName: "IssuersViewController", bundle: bundle) self.publicKey = merchantPublicKey self.paymentMethod = paymentMethod self.callback = callback } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public init() { super.init(nibName: nil, bundle: nil) } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override public func viewDidAppear(animated: Bool) { self.tableView.reloadData() } override public func viewDidLoad() { super.viewDidLoad() self.title = "Banco".localized self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Atrás".localized, style: UIBarButtonItemStyle.Plain, target: nil, action: nil) let mercadoPago : MercadoPago = MercadoPago(publicKey: self.publicKey!) mercadoPago.getIssuers(self.paymentMethod!._id, success: { (issuers: [Issuer]?) -> Void in self.items = issuers self.tableView.reloadData() self.loadingView.removeFromSuperview() }, failure: nil) self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized) self.view.addSubview(self.loadingView) let issuerNib = UINib(nibName: "IssuerTableViewCell", bundle: self.bundle) self.tableView.registerNib(issuerNib, forCellReuseIdentifier: "issuerCell") self.tableView.delegate = self self.tableView.dataSource = self } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items == nil ? 0 : items.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let issuerCell : IssuerTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("issuerCell") as! IssuerTableViewCell let issuer : Issuer = items[indexPath.row] issuerCell.fillWithIssuer(issuer) return issuerCell } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44 } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { callback!(issuer: self.items![indexPath.row]) } }
mit
81c9eb5ff045e4c9839e5ded6ac77c4a
35.355556
150
0.670437
5.102964
false
false
false
false
NUKisZ/MyTools
MyTools/MyTools/ThirdLibrary/EZSwiftSources/DictionaryExtensions.swift
1
6187
// // DictionaryExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit extension Dictionary { /// EZSE: Returns the value of a random Key-Value pair from the Dictionary public func random() -> Value { let index: Int = Int(arc4random_uniform(UInt32(self.count))) return Array(self.values)[index] } /// EZSE: Union of self and the input dictionaries. public func union(_ dictionaries: Dictionary...) -> Dictionary { var result = self dictionaries.forEach { (dictionary) -> Void in dictionary.forEach { (key, value) -> Void in result[key] = value } } return result } /// EZSE: Intersection of self and the input dictionaries. /// Two dictionaries are considered equal if they contain the same [key: value] copules. public func intersection<K, V>(_ dictionaries: [K: V]...) -> [K: V] where K: Equatable, V: Equatable { // Casts self from [Key: Value] to [K: V] let filtered = mapFilter { (item, value) -> (K, V)? in if let item = item as? K, let value = value as? V { return (item, value) } return nil } // Intersection return filtered.filter { (key: K, value: V) -> Bool in // check for [key: value] in all the dictionaries dictionaries.testAll { $0.has(key) && $0[key] == value } } } /// EZSE: Checks if a key exists in the dictionary. public func has(_ key: Key) -> Bool { return index(forKey: key) != nil } /// EZSE: Creates an Array with values generated by running /// each [key: value] of self through the mapFunction. public func toArray<V>(_ map: (Key, Value) -> V) -> [V] { return self.map(map) } /// EZSE: Creates a Dictionary with the same keys as self and values generated by running /// each [key: value] of self through the mapFunction. public func mapValues<V>(_ map: (Key, Value) -> V) -> [Key: V] { var mapped: [Key: V] = [:] forEach { mapped[$0] = map($0, $1) } return mapped } /// EZSE: Creates a Dictionary with the same keys as self and values generated by running /// each [key: value] of self through the mapFunction discarding nil return values. public func mapFilterValues<V>(_ map: (Key, Value) -> V?) -> [Key: V] { var mapped: [Key: V] = [:] forEach { if let value = map($0, $1) { mapped[$0] = value } } return mapped } /// EZSE: Creates a Dictionary with keys and values generated by running /// each [key: value] of self through the mapFunction discarding nil return values. public func mapFilter<K, V>(_ map: (Key, Value) -> (K, V)?) -> [K: V] { var mapped: [K: V] = [:] forEach { if let value = map($0, $1) { mapped[value.0] = value.1 } } return mapped } /// EZSE: Creates a Dictionary with keys and values generated by running /// each [key: value] of self through the mapFunction. public func map<K, V>(_ map: (Key, Value) -> (K, V)) -> [K: V] { var mapped: [K: V] = [:] forEach { let (_key, _value) = map($0, $1) mapped[_key] = _value } return mapped } /// EZSE: Constructs a dictionary containing every [key: value] pair from self /// for which testFunction evaluates to true. public func filter(_ test: (Key, Value) -> Bool) -> Dictionary { var result = Dictionary() for (key, value) in self { if test(key, value) { result[key] = value } } return result } /// EZSE: Checks if test evaluates true for all the elements in self. public func testAll(_ test: (Key, Value) -> (Bool)) -> Bool { return !contains { !test($0, $1) } } /// EZSE: Unserialize JSON string into Dictionary public static func constructFromJSON (json: String) -> Dictionary? { if let data = (try? JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8, allowLossyConversion: true)!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? Dictionary { return data } else { return nil } } /// EZSE: Serialize Dictionary into JSON string public func formatJSON() -> String? { if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions()) { let jsonStr = String(data: jsonData, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) return String(jsonStr ?? "") } return nil } } extension Dictionary where Value: Equatable { /// EZSE: Difference of self and the input dictionaries. /// Two dictionaries are considered equal if they contain the same [key: value] pairs. public func difference(_ dictionaries: [Key: Value]...) -> [Key: Value] { var result = self for dictionary in dictionaries { for (key, value) in dictionary { if result.has(key) && result[key] == value { result.removeValue(forKey: key) } } } return result } } /// EZSE: Combines the first dictionary with the second and returns single dictionary public func += <KeyType, ValueType> (left: inout [KeyType: ValueType], right: [KeyType: ValueType]) { for (k, v) in right { left.updateValue(v, forKey: k) } } /// EZSE: Difference operator public func - <K, V: Equatable> (first: [K: V], second: [K: V]) -> [K: V] { return first.difference(second) } /// EZSE: Intersection operator public func & <K, V: Equatable> (first: [K: V], second: [K: V]) -> [K: V] { return first.intersection(second) } /// EZSE: Union operator public func | <K: Hashable, V> (first: [K: V], second: [K: V]) -> [K: V] { return first.union(second) }
mit
2ffda0b16929f1f02c97e98d51c364ae
34.354286
210
0.576047
4.086526
false
false
false
false
kickerchen/Noitacilppa
Noitacilppa/GarageViewController.swift
1
1926
// // GarageViewController.swift // Noitacilppa // // Created by CHENCHIAN on 8/6/15. // Copyright (c) 2015 KICKERCHEN. All rights reserved. // import UIKit import Parse class GarageViewController: UIViewController { @IBOutlet weak var logoutLabel: UILabel! @IBOutlet weak var countDownLabel: UILabel! @IBOutlet weak var logoutButton: UIButton! let logoutSegue = "LogOutSegue" var logoutTimer: NSTimer? = nil var count: Int = 6 { didSet { if count == 0 { self.performSegueWithIdentifier(logoutSegue, sender: nil) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } deinit { if let timer = logoutTimer { timer.invalidate() logoutTimer = nil } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ @IBAction func logoutButtonPressed(sender: UIButton) { PFUser.logOut() UIView.animateWithDuration(0.5, animations: { self.logoutLabel.alpha = 1.0 }) logoutTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "countDown", userInfo: nil, repeats: true) } func countDown() { count-- if count > 0 { countDownLabel.text = "\(count)" } } }
mit
e1574dffce731de224c515fc4b53308e
23.692308
132
0.599688
4.863636
false
false
false
false
kohtenko/fastlane
fastlane/swift/Runner.swift
4
9275
// Runner.swift // Copyright (c) 2020 FastlaneTools // // ** NOTE ** // This file is provided by fastlane and WILL be overwritten in future updates // If you want to add extra functionality to this project, create a new file in a // new group so that it won't be marked for upgrade // import Foundation let logger: Logger = { Logger() }() let runner: Runner = { Runner() }() func desc(_: String) { // no-op, this is handled in fastlane/lane_list.rb } class Runner { private var thread: Thread! private var socketClient: SocketClient! private let dispatchGroup = DispatchGroup() private var returnValue: String? // lol, so safe private var currentlyExecutingCommand: RubyCommandable? private var shouldLeaveDispatchGroupDuringDisconnect = false private var executeNext: [String: Bool] = [:] func executeCommand(_ command: RubyCommandable) -> String { dispatchGroup.enter() currentlyExecutingCommand = command socketClient.send(rubyCommand: command) let secondsToWait = DispatchTimeInterval.seconds(SocketClient.defaultCommandTimeoutSeconds) // swiftformat:disable:next redundantSelf let timeoutResult = Self.waitWithPolling(self.executeNext[command.id], toEventually: { $0 == true }, timeout: SocketClient.defaultCommandTimeoutSeconds) executeNext.removeValue(forKey: command.id) let failureMessage = "command didn't execute in: \(SocketClient.defaultCommandTimeoutSeconds) seconds" let success = testDispatchTimeoutResult(timeoutResult, failureMessage: failureMessage, timeToWait: secondsToWait) guard success else { log(message: "command timeout") preconditionFailure() } if let _returnValue = returnValue { return _returnValue } else { return "" } } static func waitWithPolling<T>(_ expression: @autoclosure @escaping () throws -> T, toEventually predicate: @escaping (T) -> Bool, timeout: Int, pollingInterval: DispatchTimeInterval = .milliseconds(4)) -> DispatchTimeoutResult { func memoizedClosure<T>(_ closure: @escaping () throws -> T) -> (Bool) throws -> T { var cache: T? return { withoutCaching in if withoutCaching || cache == nil { cache = try closure() } guard let cache = cache else { preconditionFailure() } return cache } } let runLoop = RunLoop.current let timeoutDate = Date(timeInterval: TimeInterval(timeout), since: Date()) var fulfilled: Bool = false let _expression = memoizedClosure(expression) repeat { do { let exp = try _expression(true) fulfilled = predicate(exp) } catch { fatalError("Error raised \(error.localizedDescription)") } if !fulfilled { runLoop.run(until: Date(timeIntervalSinceNow: pollingInterval.timeInterval)) } else { break } } while Date().compare(timeoutDate) == .orderedAscending if fulfilled { return .success } else { return .timedOut } } } // Handle threading stuff extension Runner { func startSocketThread(port: UInt32) { let secondsToWait = DispatchTimeInterval.seconds(SocketClient.connectTimeoutSeconds) dispatchGroup.enter() socketClient = SocketClient(port: port, commandTimeoutSeconds: timeout, socketDelegate: self) thread = Thread(target: self, selector: #selector(startSocketComs), object: nil) guard let thread = thread else { preconditionFailure("Thread did not instantiate correctly") } thread.name = "socket thread" thread.start() let connectTimeout = DispatchTime.now() + secondsToWait let timeoutResult = dispatchGroup.wait(timeout: connectTimeout) let failureMessage = "couldn't start socket thread in: \(SocketClient.connectTimeoutSeconds) seconds" let success = testDispatchTimeoutResult(timeoutResult, failureMessage: failureMessage, timeToWait: secondsToWait) guard success else { log(message: "socket thread timeout") preconditionFailure() } } func disconnectFromFastlaneProcess() { shouldLeaveDispatchGroupDuringDisconnect = true dispatchGroup.enter() socketClient.sendComplete() let connectTimeout = DispatchTime.now() + 2 _ = dispatchGroup.wait(timeout: connectTimeout) } @objc func startSocketComs() { guard let socketClient = self.socketClient else { return } socketClient.connectAndOpenStreams() dispatchGroup.leave() } fileprivate func testDispatchTimeoutResult(_ timeoutResult: DispatchTimeoutResult, failureMessage: String, timeToWait _: DispatchTimeInterval) -> Bool { switch timeoutResult { case .success: return true case .timedOut: log(message: "timeout: \(failureMessage)") return false } } } extension Runner: SocketClientDelegateProtocol { func commandExecuted(serverResponse: SocketClientResponse, completion: (SocketClient) -> Void) { switch serverResponse { case let .success(returnedObject, closureArgumentValue): verbose(message: "command executed") returnValue = returnedObject if let command = currentlyExecutingCommand as? RubyCommand { if let closureArgumentValue = closureArgumentValue, !closureArgumentValue.isEmpty { command.performCallback(callbackArg: closureArgumentValue, socket: socketClient) { self.executeNext[command.id] = true } } else { executeNext[command.id] = true } } dispatchGroup.leave() completion(socketClient) case .clientInitiatedCancelAcknowledged: verbose(message: "server acknowledged a cancel request") dispatchGroup.leave() if let command = currentlyExecutingCommand as? RubyCommand { executeNext[command.id] = true } completion(socketClient) case .alreadyClosedSockets, .connectionFailure, .malformedRequest, .malformedResponse, .serverError: log(message: "error encountered while executing command:\n\(serverResponse)") dispatchGroup.leave() if let command = currentlyExecutingCommand as? RubyCommand { executeNext[command.id] = true } completion(socketClient) case let .commandTimeout(timeout): log(message: "Runner timed out after \(timeout) second(s)") } } func connectionsOpened() { DispatchQueue.main.async { verbose(message: "connected!") } } func connectionsClosed() { DispatchQueue.main.async { if let thread = self.thread { thread.cancel() } self.thread = nil self.socketClient.closeSession() self.socketClient = nil verbose(message: "connection closed!") if self.shouldLeaveDispatchGroupDuringDisconnect { self.dispatchGroup.leave() } exit(0) } } } class Logger { enum LogMode { init(logMode: String) { switch logMode { case "normal", "default": self = .normal case "verbose": self = .verbose default: logger.log(message: "unrecognized log mode: \(logMode), defaulting to 'normal'") self = .normal } } case normal case verbose } public static var logMode: LogMode = .normal func log(message: String) { let timestamp = NSDate().timeIntervalSince1970 print("[\(timestamp)]: \(message)") } func verbose(message: String) { if Logger.logMode == .verbose { let timestamp = NSDate().timeIntervalSince1970 print("[\(timestamp)]: \(message)") } } } func log(message: String) { logger.log(message: message) } func verbose(message: String) { logger.verbose(message: message) } private extension DispatchTimeInterval { var timeInterval: TimeInterval { var result: TimeInterval = 0 switch self { case let .seconds(value): result = TimeInterval(value) case let .milliseconds(value): result = TimeInterval(value) * 0.001 case let .microseconds(value): result = TimeInterval(value) * 0.000_001 case let .nanoseconds(value): result = TimeInterval(value) * 0.000_000_001 case .never: fatalError() } return result } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.2]
mit
1b7b6c20642f24db59679204618cec0e
32.727273
233
0.608302
5.144204
false
false
false
false
RevenueCat/purchases-ios
Tests/UnitTests/Mocks/MockProductsRequestFactory.swift
1
969
// // Created by Andrés Boedo on 8/12/20. // Copyright (c) 2020 Purchases. All rights reserved. // import Foundation @testable import RevenueCat import StoreKit class MockProductsRequestFactory: ProductsRequestFactory { var invokedRequest = false var invokedRequestCount = 0 var invokedRequestParameters: Set<String>? var invokedRequestParametersList = [Set<String>]() var stubbedRequestResult: MockProductsRequest! var requestResponseTime: DispatchTimeInterval = .seconds(0) override func request(productIdentifiers: Set<String>) -> SKProductsRequest { invokedRequest = true invokedRequestCount += 1 invokedRequestParameters = productIdentifiers invokedRequestParametersList.append(productIdentifiers) return stubbedRequestResult ?? MockProductsRequest(productIdentifiers: productIdentifiers, responseTime: requestResponseTime) } }
mit
f6f20164ea1602ebac0d4a6f3f4c1152
34.851852
98
0.716942
5.761905
false
false
false
false
iSapozhnik/FamilyPocket
FamilyPocket/Delegates/CategoryCollectionViewDelegate/CategoryCollectionViewDelegate.swift
1
2588
// // CategoryCollectionViewDelegate.swift // FamilyPocket // // Created by Ivan Sapozhnik on 5/14/17. // Copyright © 2017 Ivan Sapozhnik. All rights reserved. // import UIKit protocol CategoryDelegate: NSObjectProtocol { func wantAddNewCategory() func didSelect(categoryItem category: Category?) func willDisplay(categoryItem category: Category?) } class CategoryCollectionViewDelegate: NSObject, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { var items: [Category] = [] { didSet { // guard let category = items.first else { return } // controller.didSelect(categoryItem: category) } } weak var controller: CategoryDelegate! init(withController controller: CategoryDelegate) { super.init() self.controller = controller } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.row == items.count { controller.wantAddNewCategory() } else { let category = items[indexPath.row] controller.didSelect(categoryItem: category) } } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.row != items.count { let category = items[indexPath.row] controller.willDisplay(categoryItem: category) } else { controller.willDisplay(categoryItem: nil) } } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return .zero } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } }
mit
3f33692d3966345b2cf2c908c27ffd6e
34.930556
175
0.696946
5.826577
false
false
false
false
yulingtianxia/Self-Sizing-CollectionView-Demo
UICollectionViewSelfSizingDemo/ViewController.swift
1
2028
// // ViewController.swift // UICollectionViewSelfSizingDemo // // Created by 杨萧玉 on 15/4/12. // Copyright (c) 2015年 杨萧玉. All rights reserved. // import UIKit let text = "The UICollectionViewFlowLayout class is a concrete layout object that organizes items into a grid with optional header and footer views for each section. The items in the collection view flow from one row or column (depending on the scrolling direction) to the next, with each row comprising as many cells as will fit. Cells can be the same sizes or different sizes." let strings = text.components(separatedBy: " ") class ViewController: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. (collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width: 20, height: 20) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return strings.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "selfsizingcell", for: indexPath) as! SelfSizingCell cell.textLabel.text = strings[indexPath.item] return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { print(kind) return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "selfsizingheader", for: indexPath) } }
mit
ae62df501ea4a883e21d7b019e54cd03
41.851064
379
0.733863
5.428571
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureApp/Sources/FeatureAppUI/CardIssuing/CardIssuingAdapter.swift
1
17389
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import ComposableArchitecture import DIKit import Errors import FeatureAccountPickerUI import FeatureAddressSearchDomain import FeatureAddressSearchUI import FeatureCardIssuingDomain import FeatureCardIssuingUI import FeatureKYCDomain import FeatureKYCUI import FeatureSettingsUI import FeatureTransactionUI import Foundation import Localization import MoneyKit import PlatformKit import PlatformUIKit import RxSwift import SwiftUI import UIComponentsKit final class CardIssuingAdapter: FeatureSettingsUI.CardIssuingViewControllerAPI { private let cardIssuingBuilder: CardIssuingBuilderAPI private let nabuUserService: NabuUserServiceAPI init( cardIssuingBuilder: CardIssuingBuilderAPI, nabuUserService: NabuUserServiceAPI ) { self.cardIssuingBuilder = cardIssuingBuilder self.nabuUserService = nabuUserService } func makeIntroViewController( onComplete: @escaping (FeatureSettingsUI.CardOrderingResult) -> Void ) -> UIViewController { let address = nabuUserService .user .mapError { _ in CardOrderingError.noAddress } .flatMap { user -> AnyPublisher<Card.Address, CardOrderingError> in guard let address = user.address else { return .failure(.noAddress) } return .just(Card.Address(with: address)) } .eraseToAnyPublisher() return cardIssuingBuilder.makeIntroViewController(address: address) { result in switch result { case .created: onComplete(.created) case .cancelled: onComplete(.cancelled) } } } func makeManagementViewController( onComplete: @escaping () -> Void ) -> UIViewController { cardIssuingBuilder.makeManagementViewController(onComplete: onComplete) } } final class CardIssuingTopUpRouter: TopUpRouterAPI { private let coincore: CoincoreAPI private let transactionsRouter: TransactionsRouterAPI private var cancellables = [AnyCancellable]() init( coincore: CoincoreAPI, transactionsRouter: TransactionsRouterAPI ) { self.coincore = coincore self.transactionsRouter = transactionsRouter } func openBuyFlow(for currency: FiatCurrency?) { guard let fiatCurrency = currency else { transactionsRouter.presentTransactionFlow(to: .buy(nil)) .subscribe() .store(in: &cancellables) return } coincore .allAccounts(filter: .all) .receive(on: DispatchQueue.main) .map { accountGroup -> FiatAccount? in accountGroup.accounts .compactMap { account in account as? FiatAccount } .first(where: { account in account.fiatCurrency.code == fiatCurrency.code }) } .flatMap { [weak self] fiatAccount -> AnyPublisher<TransactionFlowResult, Never> in guard let self = self else { return .just(.abandoned) } guard let fiatAccount = fiatAccount else { return self .transactionsRouter .presentTransactionFlow(to: .buy(nil)) } return self .transactionsRouter .presentTransactionFlow(to: .deposit(fiatAccount)) } .subscribe() .store(in: &cancellables) } func openBuyFlow(for currency: CryptoCurrency?) { guard let cryptoCurrency = currency else { transactionsRouter.presentTransactionFlow(to: .buy(nil)) .subscribe() .store(in: &cancellables) return } coincore .cryptoAccounts(for: cryptoCurrency) .receive(on: DispatchQueue.main) .flatMap { [weak self] accounts -> AnyPublisher<TransactionFlowResult, Never> in guard let self = self else { return .just(.abandoned) } return self .transactionsRouter .presentTransactionFlow(to: .buy(accounts.first(where: { account in account.accountType.isCustodial }))) } .subscribe() .store(in: &cancellables) } func openSwapFlow() { transactionsRouter .presentTransactionFlow(to: .swap(nil)) .subscribe() .store(in: &cancellables) } } final class CardIssuingAddressSearchRouter: FeatureCardIssuingUI.AddressSearchRouterAPI { private let addressSearchRouterRouter: FeatureAddressSearchDomain.AddressSearchRouterAPI init( addressSearchRouterRouter: FeatureAddressSearchDomain.AddressSearchRouterAPI ) { self.addressSearchRouterRouter = addressSearchRouterRouter } func openSearchAddressFlow( prefill: Card.Address? ) -> AnyPublisher<CardAddressSearchResult, Never> { typealias Localization = LocalizationConstants.CardIssuing.AddressSearch return addressSearchRouterRouter.presentSearchAddressFlow( prefill: prefill.map(Address.init(cardAddress:)), config: .init( addressSearchScreen: .init(title: Localization.AddressSearchScreen.title), addressEditScreen: .init( title: Localization.AddressEditSearchScreen.title, subtitle: Localization.AddressEditSearchScreen.subtitle ) ) ) .map { CardAddressSearchResult(addressResult: $0) } .eraseToAnyPublisher() } func openEditAddressFlow( isPresentedFromSearchView: Bool ) -> AnyPublisher<CardAddressSearchResult, Never> { typealias Localization = LocalizationConstants.CardIssuing.AddressSearch.AddressEditSearchScreen return addressSearchRouterRouter.presentEditAddressFlow( isPresentedFromSearchView: isPresentedFromSearchView, config: .init( title: Localization.title, subtitle: nil ) ) .map { CardAddressSearchResult(addressResult: $0) } .eraseToAnyPublisher() } } final class AddressService: AddressServiceAPI { private let repository: ResidentialAddressRepositoryAPI init(repository: ResidentialAddressRepositoryAPI) { self.repository = repository } func fetchAddress() -> AnyPublisher<Address?, AddressServiceError> { repository.fetchResidentialAddress() .map { Address(cardAddress: $0) } .mapError(AddressServiceError.network) .eraseToAnyPublisher() } func save(address: Address) -> AnyPublisher<Address, AddressServiceError> { repository.update(residentialAddress: Card.Address(address: address)) .map(Address.init(cardAddress:)) .mapError(AddressServiceError.network) .eraseToAnyPublisher() } } final class AddressSearchFlowPresenter: FeatureKYCUI.AddressSearchFlowPresenterAPI { private let addressSearchRouterRouter: FeatureAddressSearchDomain.AddressSearchRouterAPI init( addressSearchRouterRouter: FeatureAddressSearchDomain.AddressSearchRouterAPI ) { self.addressSearchRouterRouter = addressSearchRouterRouter } func openSearchAddressFlow( country: String, state: String? ) -> AnyPublisher<UserAddressSearchResult, Never> { typealias Localization = LocalizationConstants.NewKYC.AddressVerification let title = Localization.title return addressSearchRouterRouter.presentSearchAddressFlow( prefill: Address(state: state, country: country), config: .init( addressSearchScreen: .init(title: title), addressEditScreen: .init( title: title, saveAddressButtonTitle: Localization.saveButtonTitle ) ) ) .map { UserAddressSearchResult(addressResult: $0) } .eraseToAnyPublisher() } } final class AddressKYCService: FeatureAddressSearchDomain.AddressServiceAPI { typealias Address = FeatureAddressSearchDomain.Address private let locationUpdateService: LocationUpdateService init(locationUpdateService: LocationUpdateService = LocationUpdateService()) { self.locationUpdateService = locationUpdateService } func fetchAddress() -> AnyPublisher<Address?, AddressServiceError> { .just(nil) } func save(address: Address) -> AnyPublisher<Address, AddressServiceError> { guard let userAddress = UserAddress(address: address, countryCode: address.country) else { return .failure(AddressServiceError.network(Nabu.Error.unknown)) } return locationUpdateService .save(address: userAddress) .map { address } .mapError(AddressServiceError.network) .eraseToAnyPublisher() } } class CardIssuingAccountPickerAdapter: AccountProviderAPI, AccountPickerAccountProviding { private struct Account { let details: BlockchainAccount let balance: AccountBalance } private let nabuUserService: NabuUserServiceAPI private let coinCore: CoincoreAPI private var cancellables = [AnyCancellable]() private let cardService: CardServiceAPI private let fiatCurrencyService: FiatCurrencyServiceAPI init( cardService: CardServiceAPI, coinCore: CoincoreAPI, fiatCurrencyService: FiatCurrencyServiceAPI, nabuUserService: NabuUserServiceAPI ) { self.cardService = cardService self.coinCore = coinCore self.fiatCurrencyService = fiatCurrencyService self.nabuUserService = nabuUserService } private let accountPublisher = CurrentValueSubject<[Account], Never>([]) private var router: AccountPickerRouting? var accounts: Observable<[BlockchainAccount]> { accountPublisher .map { pairs in pairs.map(\.details) } .asObservable() } func selectAccount(for card: Card) -> AnyPublisher<AccountBalance, NabuNetworkError> { let publisher = PassthroughSubject<AccountBalance, NabuNetworkError>() let accounts = cardService.eligibleAccounts(for: card) let accountBalances = Publishers .CombineLatest(accounts.eraseError(), coinCore.allAccounts(filter: .all).eraseError()) .map { accountBalances, group -> [Account] in accountBalances .compactMap { accountBalance in guard let account = group.accounts.first(where: { accountBalance.balance.symbol == $0.currencyType.code && $0.accountType.isCustodial }) else { return nil } return Account(details: account, balance: accountBalance) } } let builder = AccountPickerBuilder( accountProvider: self, action: .linkToDebitCard ) let router = builder.build( listener: .simple { [weak self] account in if let balance = self?.accountPublisher.value.first(where: { pair in pair.details.identifier == account.identifier })?.balance { publisher.send(balance) } self?.router?.viewControllable .uiviewController .dismiss( animated: true ) }, navigationModel: ScreenNavigationModel.AccountPicker.modal( title: LocalizationConstants .CardIssuing .Manage .SourceAccount .title ), headerModel: .none ) self.router = router router.interactable.activate() router.load() let viewController = router.viewControllable.uiviewController viewController.isModalInPresentation = true let navigationController = UINavigationController(rootViewController: viewController) accountBalances.sink(receiveValue: accountPublisher.send).store(in: &cancellables) let topMostViewControllerProvider: TopMostViewControllerProviding = resolve() topMostViewControllerProvider .topMostViewController? .present(navigationController, animated: true) return publisher.eraseToAnyPublisher() } func linkedAccount(for card: Card) -> AnyPublisher<AccountSnapshot?, Never> { Publishers .CombineLatest3( cardService.fetchLinkedAccount(for: card).eraseError(), coinCore.allAccounts(filter: .all).eraseError(), fiatCurrencyService.displayCurrency.eraseError() ) .flatMap { accountCurrency, group, fiatCurrency -> AnyPublisher<AccountSnapshot?, Never> in guard let account = group.accounts.first(where: { account in account.currencyType.code == accountCurrency.accountCurrency && account.accountType.isCustodial }) else { return .just(nil) } return AccountSnapshot .with( account, fiatCurrency ) .optional() } .replaceError(with: nil) .eraseToAnyPublisher() } } extension FeatureCardIssuingDomain.Card.Address { init(with address: UserAddress) { self.init( line1: address.lineOne, line2: address.lineTwo, city: address.city, postCode: address.postalCode, state: address.state, country: address.country.code ) } } extension CardAddressSearchResult { fileprivate init(addressResult: AddressResult) { switch addressResult { case .saved(let address): self = .saved(Card.Address(address: address)) case .abandoned: self = .abandoned } } } extension Card.Address { fileprivate init(address: Address) { self.init( line1: address.line1, line2: address.line2, city: address.city, postCode: address.postCode, state: address.state, country: address.country ) } } extension Address { fileprivate init(cardAddress: Card.Address) { self.init( line1: cardAddress.line1, line2: cardAddress.line2, city: cardAddress.city, postCode: cardAddress.postCode, state: cardAddress.state, country: cardAddress.country ) } } extension UserAddressSearchResult { fileprivate init(addressResult: AddressResult) { switch addressResult { case .saved: self = .saved case .abandoned: self = .abandoned } } } extension UserAddress { fileprivate init?( address: FeatureAddressSearchDomain.Address, countryCode: String? ) { guard let countryCode = countryCode else { return nil } self.init( lineOne: address.line1, lineTwo: address.line2, postalCode: address.postCode, city: address.city, state: address.state, countryCode: countryCode ) } } extension FeatureAddressSearchDomain.Address { fileprivate init( address: UserAddress ) { self.init( line1: address.lineOne, line2: address.lineTwo, city: address.city, postCode: address.postalCode, state: address.state, country: address.countryCode ) } } extension AccountSnapshot { static func with( _ account: SingleAccount, _ fiatCurrency: FiatCurrency ) -> AnyPublisher<FeatureCardIssuingDomain.AccountSnapshot, Never> { account.balance.ignoreFailure() .combineLatest( account.fiatBalance(fiatCurrency: fiatCurrency) .ignoreFailure() ) .map { crypto, fiat in AccountSnapshot( id: account.identifier, name: account.label, cryptoCurrency: account.currencyType.cryptoCurrency, fiatCurrency: fiatCurrency, crypto: crypto, fiat: fiat, image: crypto.currencyType.image, backgroundColor: account.currencyType.cryptoCurrency == nil ? .backgroundFiat : .clear ) } .eraseToAnyPublisher() } }
lgpl-3.0
636ea6069714679541e8347f14e9c889
31.994307
106
0.604957
5.473088
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Services/CredentialsStore/CredentialsStore.swift
1
7569
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import RxSwift import ToolKit import WalletPayloadKit final class CredentialsStore: CredentialsStoreAPI { // MARK: Types enum CredentialsStoreError: Error { case incompleteData case backupNotNeeded } private enum PBKDF2Iterations { static let guid: Int = 5001 static let sharedKey: Int = 5002 } private enum Keys: String { case data = "BC_KV_DATA" case guid = "BC_KV_GUID" case sharedKey = "BC_KV_SHARED_KEY" case pinKey = "BC_KV_PIN_KEY" case encryptedPinPassword = "BC_KV_ENCRYPTED_PIN_PWD" } // MARK: Private Properties private let appSettings: AppSettingsAPI private let appSettingsAuthenticating: AppSettingsAuthenticating private let store: UbiquitousKeyValueStore private let cryptoService: WalletCryptoServiceAPI private let disposeBag = DisposeBag() // MARK: Init init( appSettings: AppSettingsAPI = resolve(), appSettingsAuthenticating: AppSettingsAuthenticating = resolve(), store: UbiquitousKeyValueStore = NSUbiquitousKeyValueStore.default, cryptoService: WalletCryptoServiceAPI = resolve() ) { self.appSettings = appSettings self.appSettingsAuthenticating = appSettingsAuthenticating self.store = store self.cryptoService = cryptoService } func erase() { store.set(nil, forKey: Keys.data.rawValue) synchronize() } func backup(pinDecryptionKey: String) -> Completable { let pinData = Single.just(pinData()) let walletData = walletData(pinDecryptionKey: pinDecryptionKey) .optional() .catchAndReturn(nil) return Single .zip( appSettingsAuthenticating.pinKey, appSettingsAuthenticating.encryptedPinPassword, appSettings.guid, appSettings.sharedKey, pinData, walletData ) { (pinKey: $0, encryptedPinPassword: $1, guid: $2, sharedKey: $3, pinData: $4, walletData: $5) } .map { data -> (pinKey: String, encryptedPinPassword: String, guid: String, sharedKey: String) in guard let pinKey = data.pinKey, let encryptedPinPassword = data.encryptedPinPassword, let guid = data.guid, let sharedKey = data.sharedKey else { throw CredentialsStoreError.incompleteData } // If we have both pin data and wallet data, we check that at least one of the values // needs to be updated. If none of them needs to be updated, we abort with '.backupNotNeeded' if let pinData = data.pinData, let walletData = data.walletData { guard pinData.encryptedPinPassword != encryptedPinPassword || pinData.pinKey != pinKey || walletData.guid != guid || walletData.sharedKey != sharedKey else { throw CredentialsStoreError.backupNotNeeded } } return (pinKey: pinKey, encryptedPinPassword: encryptedPinPassword, guid: guid, sharedKey: sharedKey) } .flatMapCompletable(weak: self) { (self, data) in self.backup( pinDecryptionKey: pinDecryptionKey, pinKey: data.pinKey, encryptedPinPassword: data.encryptedPinPassword, guid: data.guid, sharedKey: data.sharedKey ) } .catch { error in switch error { case CredentialsStoreError.backupNotNeeded: return .empty() default: throw error } } } private func backup( pinDecryptionKey: String, pinKey: String, encryptedPinPassword: String, guid: String, sharedKey: String ) -> Completable { Single .zip( cryptoService.encrypt( pair: KeyDataPair( key: pinDecryptionKey, data: guid ), pbkdf2Iterations: PBKDF2Iterations.guid ) .asObservable() .take(1) .asSingle(), cryptoService.encrypt( pair: KeyDataPair( key: pinDecryptionKey, data: sharedKey ), pbkdf2Iterations: PBKDF2Iterations.sharedKey ) .asObservable() .take(1) .asSingle() ) .do( onSuccess: { [weak self] payload in let (encryptedGuid, encryptedSharedKey) = payload let data = [ Keys.pinKey.rawValue: pinKey, Keys.encryptedPinPassword.rawValue: encryptedPinPassword, Keys.guid.rawValue: encryptedGuid, Keys.sharedKey.rawValue: encryptedSharedKey ] self?.store.set(data, forKey: Keys.data.rawValue) self?.synchronize() } ) .asCompletable() } func pinData() -> CredentialsPinData? { guard let data = store.dictionary(forKey: Keys.data.rawValue), let pinKey = data[Keys.pinKey.rawValue] as? String, let encryptedPinPassword = data[Keys.encryptedPinPassword.rawValue] as? String else { return nil } return CredentialsPinData( pinKey: pinKey, encryptedPinPassword: encryptedPinPassword ) } func walletData(pinDecryptionKey: String) -> Single<CredentialsWalletData> { guard let data = store.dictionary(forKey: Keys.data.rawValue), let encryptedGuid = data[Keys.guid.rawValue] as? String, let encryptedSharedKey = data[Keys.sharedKey.rawValue] as? String else { return .error(CredentialsStoreError.incompleteData) } return Single .zip( cryptoService.decrypt( pair: KeyDataPair( key: pinDecryptionKey, data: encryptedGuid ), pbkdf2Iterations: PBKDF2Iterations.guid ) .asObservable() .take(1) .asSingle(), cryptoService.decrypt( pair: KeyDataPair( key: pinDecryptionKey, data: encryptedSharedKey ), pbkdf2Iterations: PBKDF2Iterations.sharedKey ) .asObservable() .take(1) .asSingle() ) .map { payload in let (guid, sharedKey) = payload return CredentialsWalletData(guid: guid, sharedKey: sharedKey) } } func synchronize() { let result = store.synchronize() assert(result, "UbiquitousKeyValueStore synchronize: false") } }
lgpl-3.0
cafcbd42aa78d66162c8d236f18fedf8
34.867299
117
0.527352
5.367376
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Money/Sources/MoneyKit/CurrencyRepresentation/Currency/Currency.swift
1
6039
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit /// A currency error. public enum CurrencyError: Error { /// Unknown currency code. case unknownCurrency } public protocol Currency { /// The maximum display precision between all the possible currencies. static var maxDisplayPrecision: Int { get } /// The currency name (e.g. `US Dollar`, `Bitcoin`, etc.). var name: String { get } /// The currency code (e.g. `USD`, `BTC`, etc.). var code: String { get } /// The currency display code (e.g. `USD`, `BTC`, etc.). var displayCode: String { get } /// The currency symbol (e.g. `$`, `BTC`, etc.). var displaySymbol: String { get } /// The currency precision. var precision: Int { get } /// The currency display precision (shorter than or equal to `precision`). var displayPrecision: Int { get } /// Whether the currency is a fiat currency. var isFiatCurrency: Bool { get } /// Whether the currency is a crypto currency. var isCryptoCurrency: Bool { get } /// The `CurrencyType` wrapper for self. var currencyType: CurrencyType { get } } extension Currency { public var isFiatCurrency: Bool { self is FiatCurrency } public var isCryptoCurrency: Bool { self is CryptoCurrency } } public enum CurrencyType: Hashable { /// A fiat currency. case fiat(FiatCurrency) /// A crypto currency. case crypto(CryptoCurrency) /// Creates a currency type. /// /// - Parameters: /// - code: A currency code. /// - enabledCurrenciesService: An enabled currencies service. /// /// - Throws: A `CurrencyError.unknownCurrency` if `code` is invalid. public init(code: String, enabledCurrenciesService: EnabledCurrenciesServiceAPI = resolve()) throws { if let cryptoCurrency = CryptoCurrency(code: code, enabledCurrenciesService: enabledCurrenciesService) { self = .crypto(cryptoCurrency) return } if let fiatCurrency = FiatCurrency(code: code) { self = .fiat(fiatCurrency) return } throw CurrencyError.unknownCurrency } public static func == (lhs: CurrencyType, rhs: FiatCurrency) -> Bool { switch lhs { case crypto: return false case fiat(let lhs): return lhs == rhs } } public static func == (lhs: CurrencyType, rhs: CryptoCurrency) -> Bool { switch lhs { case crypto(let lhs): return lhs == rhs case fiat: return false } } } extension CurrencyType: Currency { public static let maxDisplayPrecision: Int = max(FiatCurrency.maxDisplayPrecision, CryptoCurrency.maxDisplayPrecision) public var name: String { switch self { case .crypto(let cryptoCurrency): return cryptoCurrency.name case .fiat(let fiatCurrency): return fiatCurrency.name } } public var code: String { switch self { case .crypto(let cryptoCurrency): return cryptoCurrency.code case .fiat(let fiatCurrency): return fiatCurrency.code } } public var displayCode: String { switch self { case .crypto(let cryptoCurrency): return cryptoCurrency.displayCode case .fiat(let fiatCurrency): return fiatCurrency.displayCode } } public var displaySymbol: String { switch self { case .crypto(let cryptoCurrency): return cryptoCurrency.displaySymbol case .fiat(let fiatCurrency): return fiatCurrency.displaySymbol } } public var precision: Int { switch self { case .crypto(let cryptoCurrency): return cryptoCurrency.precision case .fiat(let fiatCurrency): return fiatCurrency.precision } } public var displayPrecision: Int { switch self { case .crypto(let cryptoCurrency): return cryptoCurrency.displayPrecision case .fiat(let fiatCurrency): return fiatCurrency.displayPrecision } } public var isFiatCurrency: Bool { switch self { case .crypto: return false case .fiat: return true } } public var isCryptoCurrency: Bool { switch self { case .crypto: return true case .fiat: return false } } public var currencyType: CurrencyType { self } /// The crypto currency, or `nil` if not a crypto currency. public var cryptoCurrency: CryptoCurrency? { switch self { case .crypto(let cryptoCurrency): return cryptoCurrency case .fiat: return nil } } /// The fiat currency, or `nil` if not a fiat currency. public var fiatCurrency: FiatCurrency? { switch self { case .crypto: return nil case .fiat(let fiatCurrency): return fiatCurrency } } } extension CryptoCurrency { public var currencyType: CurrencyType { .crypto(self) } } extension FiatCurrency { public var currencyType: CurrencyType { .fiat(self) } } extension CryptoValue { public var currencyType: CurrencyType { currency.currencyType } } extension FiatValue { public var currencyType: CurrencyType { currency.currencyType } } extension Currency { public func matchSearch(_ searchString: String?) -> Bool { guard let searchString = searchString, !searchString.isEmpty else { return true } return name.localizedCaseInsensitiveContains(searchString) || code.localizedCaseInsensitiveContains(searchString) || displayCode.localizedCaseInsensitiveContains(searchString) } }
lgpl-3.0
72a6a851f55281bba1130923b31fdcc7
24.263598
122
0.602021
5.082492
false
false
false
false
evilBird/music-notation-swift
MusicNotationKit/MusicNotationKit/Key.swift
1
446
// // Key.swift // MusicNotationKit // // Created by Kyle Sherman on 7/11/15. // Copyright © 2015 Kyle Sherman. All rights reserved. // public struct Key { private let type: KeyType private let noteLetter: NoteLetter private let accidental: Accidental? public init(noteLetter: NoteLetter, accidental: Accidental? = nil, type: KeyType = .Major) { self.noteLetter = noteLetter self.accidental = accidental self.type = type } }
mit
f90dc2205be6276f195432824000c9e7
21.25
93
0.71236
3.503937
false
false
false
false
3sidedcube/CubeGeoJSON
GeoJSON/Shapes.swift
1
5587
// // Polygon.swift // Thunder Alert // // Created by Simon Mitchell on 07/12/2015. // Copyright © 2015 3 SIDED CUBE. All rights reserved. // import Foundation import MapKit #if os(iOS) || os(macOS) || os(tvOS) /** A subclass of MKPolygon for easy allocation from GeoJSON */ @objc(TSCPolygon) open class Polygon: MKPolygon { /** Returns a new instance from an array of Position objects - Parameter coordinates: An array of coordinates representing the Polygon */ public static func polygon(_ coordinates:[Position]) -> Polygon { return self.polygon(coordinates: coordinates, order: .lngLat, interiorPolygons:[]) } /** Returns a new instance from an array of Position objects with a given coordinate order - Parameter coordinates: An array of coordinates representing the Polygon - Parameter order: The order that the coordinates appear in */ public static func polygon(_ coordinates:[Position], order:CoordinateOrder) -> Polygon { return self.polygon(coordinates: coordinates, order:order, interiorPolygons:[]) } /** Returns a new instance from an array of Position objects with an optional set of interior polygons - Parameter coordinates: An array of coordinates representing the Polygon - Parameter order: The order that the coordinates appear in - Parameter interiorPolygons: Any interior polygon objects that the polygon has */ public static func polygon(coordinates coords:[Position], order:CoordinateOrder, interiorPolygons:[Polygon]?) -> Polygon { var coordinates: [CLLocationCoordinate2D] = coords.map({ return $0.coordinate(order) }) return Polygon(coordinates: &coordinates, count: coords.count, interiorPolygons: interiorPolygons) } } /** A subclass of MKPolyline for easy allocation from GeoJSON */ open class Polyline: MKPolyline { /** Returns a new instance from an array of Position objects - Parameter coordinates: An array of coordinates representing the Polyline */ public static func polyline(_ coordinates:[Position]) -> Polyline { return self.polyline(coordinates: coordinates, order: .lngLat) } /** Returns a new instance from an array of Position objects - Parameter coordinates: An array of coordinates representing the Polyline - Parameter order: The order that the coordinates appear in */ public static func polyline(coordinates coords:[Position], order: CoordinateOrder) -> Polyline { var coordinates: [CLLocationCoordinate2D] = coords.map({ return $0.coordinate(order) }) return Polyline(coordinates: &coordinates, count: coords.count) } } /** A subclass of MKCircle for easy allocation from GeoJSON */ open class Circle: MKCircle { /** Returns a new instance from an array of Position objects - Parameter coordinate: The center coordinate of the circle - Parameter radius: The radius of the circle */ public static func circle(_ coordinate:Position, radius:CLLocationDistance) -> Circle { return self.circle(coordinate, radius:radius, order: .lngLat) } /** Returns a new instance from an array of Position objects - Parameter coordinate: The center coordinate of the circle - Parameter radius: The radius of the circle - Parameter order: The order that the coordinates appear in */ public static func circle(_ coordinate:Position, radius:CLLocationDistance, order:CoordinateOrder) -> Circle { return Circle(center: coordinate.coordinate(order), radius: radius) } } /** A subclass of MKPointAnnotation for easy allocation from GeoJSON */ open class PointShape: MKPointAnnotation { /** Returns a new instance from a position object - Parameter coordinate: The coordinate of the annotation */ public static func point(_ coordinate:Position) -> PointShape { return self.point(coordinate, order: .lngLat) } /** Returns a new instance from a position object - Parameter coordinate: The coordinate of the annotation - Parameter order: The coordinate order of the position object */ public static func point(_ coordinate:Position, order: CoordinateOrder) -> PointShape { let point = PointShape() point.coordinate = coordinate.coordinate(order) return point } } #elseif os(watchOS) /** A subclass of MKPointAnnotation for easy allocation from GeoJSON */ open class PointShape: NSObject, MKAnnotation { /// The coordinate of the point public var coordinate: CLLocationCoordinate2D override init() { coordinate = kCLLocationCoordinate2DInvalid super.init() } /** Returns a new instance from a position object - Parameter coordinate: The coordinate of the annotation */ public static func point(_ coordinate:Position) -> PointShape { return self.point(coordinate, order: .lngLat) } /** Returns a new instance from a position object - Parameter coordinate: The coordinate of the annotation - Parameter order: The coordinate order of the position object */ public static func point(_ coordinate:Position, order: CoordinateOrder) -> PointShape { let point = PointShape() point.coordinate = coordinate.coordinate(order) return point } } #endif
apache-2.0
fd788cc9c6c24ee4aeba9dfdb19dfae4
31.476744
126
0.677408
5.068966
false
false
false
false
qiuncheng/study-for-swift
YLLoginManager/YLAuthManager/YLAuthManager.swift
1
9145
import UIKit enum YLAuthPlatform { case qq case wechat case weibo } enum YLAuthErrorCodeType: Int { case userCancelled = -1 case versionUnsupport = -2 case authDenied = -3 case badNetwork = -4 case appNotInstalled = -5 case unknown = -404 } struct YLAuthError: Error { var description: String var codeType: YLAuthErrorCodeType init(description: String, codeType: YLAuthErrorCodeType) { self.description = description self.codeType = codeType } } struct YLAuthResult { var uid: String? var openid: String? var refreshToken: String? var expiration: Date? var accessToken: String? var wxCode: String? var originResponse: Any? } typealias SuccessHandler = (YLAuthResult?) -> Void typealias FailHandler = (Error?) -> Void class YLAuthManager: NSObject { // MARK: - Private property fileprivate var loginSuccess: SuccessHandler? fileprivate var loginFail: FailHandler? fileprivate let permissions = [kOPEN_PERMISSION_GET_INFO, kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO] fileprivate var tencentOAth: TencentOAuth? fileprivate override init() { super.init() } // MARK: - Public property static let manager = YLAuthManager() var isWechatInstalled: Bool { return WXApi.isWXAppInstalled() } var isWeiboInstalled: Bool { return WeiboSDK.isWeiboAppInstalled() } var isQQInstalled: Bool { return QQApiInterface.isQQInstalled() } // MARK: - Private function fileprivate func loginWithQQ(success: SuccessHandler?, fail: FailHandler?) { loginSuccess = success loginFail = fail tencentOAth?.authorize(self.permissions, inSafari: true) } fileprivate func loginWithWeChat(success: SuccessHandler?, fail: FailHandler?) { if !isWechatInstalled { let error = YLAuthError(description: "未安装此应用", codeType: .appNotInstalled) fail?(error) return } loginSuccess = success loginFail = fail let req = SendAuthReq() req.scope = "snsapi_userinfo" req.state = "com.tongzhuogame.wechat.state" WXApi.send(req) } fileprivate func loginWithWeibo(success: SuccessHandler?, fail: FailHandler?) { loginSuccess = success loginFail = fail let request = WBAuthorizeRequest() request.redirectURI = "https://www.sina.com" // 关于scope说明 http://open.weibo.com/wiki/Scope request.scope = "all" request.userInfo = ["name": "com.tongzhuogame.weibo.auth"] WeiboSDK.send(request) } // MARK: - Public function func register(wechatID: String?, qqID: String?, weiboID: String?) { WXApi.registerApp(wechatID, enableMTA: false) tencentOAth = TencentOAuth(appId: qqID, andDelegate: self) tencentOAth?.redirectURI = "https://yoloyolo.tv" tencentOAth?.authShareType = AuthShareType_QQ WeiboSDK.enableDebugMode(false) WeiboSDK.registerApp(weiboID) } func authWithPlatform(platform: YLAuthPlatform, success: SuccessHandler?, fail: FailHandler?) { switch platform { case .qq: loginWithQQ(success: success, fail: fail) case .weibo: loginWithWeibo(success: success, fail: fail) case .wechat: loginWithWeChat(success: success, fail: fail) } } @available (iOS 9.0, *) func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if let sourceApp = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String { if sourceApp == "com.tencent.xin" { return WXApi.handleOpen(url, delegate: YLAuthManager.manager) } else if sourceApp == "com.tencent.mqq"{ return TencentOAuth.handleOpen(url) } else if sourceApp == "com.sina.weibo" { return WeiboSDK.handleOpen(url, delegate: self) } } return true } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { if sourceApplication == "com.tencent.xin" { return WXApi.handleOpen(url, delegate: YLAuthManager.manager) } else if sourceApplication == "com.tencent.mqq" { return TencentOAuth.handleOpen(url) } else if sourceApplication == "com.sina.weibo" { return WeiboSDK.handleOpen(url, delegate: self) } return true } } // MARK: - WXApiDelegate extension YLAuthManager: WXApiDelegate { func onResp(_ resp: BaseResp!) { if let authResp = resp as? SendAuthResp { if resp.errCode == WXSuccess.rawValue, authResp.state == "com.tongzhuogame.wechat.state" { print(authResp) var result = YLAuthResult() result.wxCode = authResp.code self.loginSuccess?(result) } else if resp.errCode == WXErrCodeUserCancel.rawValue { let error = YLAuthError(description: "用户取消了登录", codeType: .userCancelled) loginFail?(error) } else if resp.errCode == WXErrCodeAuthDeny.rawValue { let error = YLAuthError(description: "授权失败", codeType: .authDenied) loginFail?(error) } else { let error = YLAuthError(description: "授权失败", codeType: .unknown) loginFail?(error) } } else if let messageResp = resp as? SendMessageToWXResp { if messageResp.errCode == WXSuccess.rawValue { YLShareManager.manager.success?() } else if messageResp.errCode == WXErrCodeUserCancel.rawValue { let error = YLAuthError(description: "用户取消分享", codeType: .userCancelled) YLShareManager.manager.fail?(error) } else if messageResp.errCode == WXErrCodeAuthDeny.rawValue { let error = YLAuthError(description: "授权失败", codeType: .authDenied) YLShareManager.manager.fail?(error) } else { let error = YLAuthError(description: "分享失败", codeType: .unknown) YLShareManager.manager.fail?(error) } } } } // MARK: - WeiboSDKDelegate extension YLAuthManager: WeiboSDKDelegate { func didReceiveWeiboRequest(_ request: WBBaseRequest!) { } func didReceiveWeiboResponse(_ response: WBBaseResponse!) { if response.statusCode == WeiboSDKResponseStatusCode.success { if let authRes = response as? WBAuthorizeResponse, let name = response.requestUserInfo["name"] as? String, name == "com.tongzhuogame.weibo.auth" { var result = YLAuthResult() result.accessToken = authRes.accessToken result.refreshToken = authRes.refreshToken result.uid = authRes.userID result.expiration = authRes.expirationDate result.originResponse = authRes.userInfo loginSuccess?(result) } } else if response.statusCode == WeiboSDKResponseStatusCode.userCancel { let error = YLAuthError(description: "用户取消登录", codeType: .userCancelled) loginFail?(error) } else if response.statusCode == WeiboSDKResponseStatusCode.authDeny { let error = YLAuthError(description: "授权失败", codeType: .authDenied) loginFail?(error) } else { let error = YLAuthError(description: "授权失败", codeType: .unknown) loginFail?(error) } } } // MARK: - TencentSessionDelegate extension YLAuthManager: TencentSessionDelegate { func tencentDidNotNetWork() { let error = YLAuthError(description: "网络异常,请重新登录", codeType: .badNetwork) loginFail?(error) } func tencentDidLogin() { if tencentOAth?.accessToken != nil && !tencentOAth!.accessToken.isEmpty { tencentOAth?.getUserInfo() } } func tencentDidLogout() { } func tencentDidNotLogin(_ cancelled: Bool) { if cancelled { let error = YLAuthError(description: "用户取消登录", codeType: .userCancelled) loginFail?(error) } } func getUserInfoResponse(_ response: APIResponse!) { var result = YLAuthResult() result.accessToken = tencentOAth?.accessToken result.expiration = tencentOAth?.expirationDate result.openid = tencentOAth?.openId result.uid = tencentOAth?.unionid result.originResponse = response.jsonResponse loginSuccess?(result) } }
mit
1e30366608930bc523d373b852cc0694
32.988679
132
0.608638
4.553589
false
false
false
false
wilfreddekok/Antidote
Antidote/FriendListCellModel.swift
1
533
// 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 class FriendListCellModel: BaseCellModel { var avatar: UIImage? var topText: String = "" var bottomText: String = "" var multilineBottomtext: Bool = false var accessibilityLabel = "" var accessibilityValue = "" var status: UserStatus = .Offline var hideStatus: Bool = false }
mpl-2.0
86fbc0501ae584bbfeef1d2b0a8e02f4
27.052632
70
0.694184
4.164063
false
false
false
false
AliSoftware/SwiftGen
Sources/SwiftGenCLI/ParserCLI.swift
1
3636
// // SwiftGen // Copyright © 2020 SwiftGen // MIT Licence // import SwiftGenKit /// Describes the Command-Line Interface for each parser subcommands public struct ParserCLI { public let parserType: Parser.Type public let name: String public let templateFolder: String public let description: String public let pathDescription: String } extension ParserCLI { init(parserType: Parser.Type, name: String, description: String, pathDescription: String) { self.init( parserType: parserType, name: name, templateFolder: name, description: description, pathDescription: pathDescription ) } public static func command(named name: String) -> ParserCLI? { allCommands.first { $0.name == name } } } // We consider the name as the identifier of a ParserCLI extension ParserCLI: Hashable { public static func == (lhs: ParserCLI, rhs: ParserCLI) -> Bool { lhs.name == rhs.name } public func hash(into hasher: inout Hasher) { hasher.combine(name) } } // MARK: - All Parser Commands extension ParserCLI { public static let allCommands: [ParserCLI] = [ .init( parserType: Colors.Parser.self, name: "colors", description: "generate code for color palettes", pathDescription: "Colors.txt|.clr|.xml|.json file(s) to parse." ), .init( parserType: CoreData.Parser.self, name: "coredata", description: "generate code for your Core Data models", pathDescription: "Core Data models (.xcdatamodel or .xcdatamodeld) to parse." ), .init( parserType: Files.Parser.self, name: "files", description: "generate code for referencing specified files", pathDescription: "Files and/or directories to recursively search." ), .init( parserType: Fonts.Parser.self, name: "fonts", description: "generate code for your fonts", pathDescription: "Directory(ies) to parse." ), .init( parserType: InterfaceBuilder.Parser.self, name: "ib", description: "generate code for your storyboard scenes and segues", pathDescription: "Directory to scan for .storyboard files. Can also be a path to a single .storyboard" ), .init( parserType: JSON.Parser.self, name: "json", description: "generate code for custom json configuration files", pathDescription: "JSON files (or directories that contain them) to parse." ), .init( parserType: Plist.Parser.self, name: "plist", description: "generate code for custom plist flies", pathDescription: "Plist files (or directories that contain them) to parse." ), .init( parserType: Strings.Parser.self, name: "strings", description: "generate code for your Localizable.strings or Localizable.stringsdict file(s)", pathDescription: "Strings file(s) to parse." ), .init( parserType: AssetsCatalog.Parser.self, name: "xcassets", description: "generate code for items in your Assets Catalog(s)", pathDescription: "Asset Catalog file(s)." ), .init( parserType: Yaml.Parser.self, name: "yaml", description: "generate code for custom yaml configuration files", pathDescription: "YAML files (or directories that contain them) to parse." ), // Deprecated .init( parserType: InterfaceBuilder.Parser.self, name: "storyboards", templateFolder: "ib", description: "DEPRECATED, please use 'ib' instead", pathDescription: "Directory to scan for .storyboard files. Can also be a path to a single .storyboard" ) ] }
mit
74c341d567718cf4ece4830253f3732f
29.546218
108
0.665475
4.182969
false
false
false
false
GrupoGO/PGActionWidget
ActionWidgetExample/ActionWidget/PGDActionView.swift
1
12847
// // PGDActionView.swift // ActionWidget // // Created by Emilio Cubo Ruiz on 13/7/17. // Copyright © 2017 Grupo Go Optimizations, SL. All rights reserved. // import UIKit public class PGDActionView: UIView { // MARK: Outlets @IBOutlet fileprivate var contentView:UIView? @IBOutlet weak var container: UIView! @IBOutlet weak var detailView: UIView! @IBOutlet weak var actionImage: UIImageView! @IBOutlet weak var actionPlatformView: UIView! @IBOutlet weak var actionPlatform: UILabel! @IBOutlet weak var actionType: UILabel! @IBOutlet weak var actionTitle: UILabel! @IBOutlet weak var star1: UIImageView! @IBOutlet weak var star2: UIImageView! @IBOutlet weak var star3: UIImageView! @IBOutlet weak var star4: UIImageView! @IBOutlet weak var star5: UIImageView! @IBOutlet weak var actionPledges: UILabel! @IBOutlet weak var actionButton: UIButton! @IBOutlet weak var actionDetailButtonImage: UIImageView! @IBOutlet weak var actionDetailButton: UIButton! @IBOutlet weak var actionTitleDetail: UILabel! @IBOutlet weak var actionTypeDetail: UILabel! @IBOutlet weak var actionDescription: UITextView! @IBOutlet weak var actionShareButtonImage: UIImageView! var fillRatingImage = UIImage(named: "fill", in: Bundle(for: PGDActionView.self), compatibleWith: nil) var outlineRatingImage = UIImage(named: "outline", in: Bundle(for: PGDActionView.self), compatibleWith: nil) var zoomOutImage = UIImage(named: "zoom_out", in: Bundle(for: PGDActionView.self), compatibleWith: nil) var downloadPGS:Bool = false var zoomInImage: UIImage = UIImage(named: "zoom_in", in: Bundle(for: PGDActionView.self), compatibleWith: nil)! { didSet { layoutSubviews() } } var shareImage: UIImage = UIImage(named: "share", in: Bundle(for: PGDActionView.self), compatibleWith: nil)! { didSet { layoutSubviews() } } var action: Action? { didSet { if let action = action { if action.platform.lowercased() != "" && action.platform.lowercased() != "webintra" { actionPlatform.text = action.platform.uppercased() } else { actionPlatformView.isHidden = true } var actionButtonTile:String = "" switch action.type.lowercased() { case "Signatures for change".lowercased(): actionButtonTile = "Sign" case "Free Training".lowercased(): actionButtonTile = "Learn" case "Ideation".lowercased(): actionButtonTile = "Think" case "Micro-Volunteering".lowercased(), "NGOs and volunteer work".lowercased(): actionButtonTile = "Participate" case "Events".lowercased(): actionButtonTile = "Assist" case "Donations".lowercased(): actionButtonTile = "Donate" case "Personal Habits".lowercased(), "Ethical Consumer".lowercased(): actionButtonTile = "Pledge" case "Messages Worth Spreading".lowercased(): actionButtonTile = "Share" case "Adoptions".lowercased(): actionButtonTile = "Adopt" case "Crowdfunding positive projects".lowercased(), "Donate Processing Power".lowercased(): actionButtonTile = "Contribute" case "Individual Actions".lowercased(), "Special".lowercased(), "Help us prioritize".lowercased(): actionButtonTile = "Do" case "Poll".lowercased(): actionButtonTile = "Reply" default: actionButtonTile = "Do" } print(actionButtonTile) actionTitle.text = action.title actionTitleDetail.text = action.title actionDescription.text = action.text actionType.text = action.type actionTypeDetail.text = action.type // actionButton.setTitle(actionButtonTile, for: .normal) // actionDetailButton.setTitle(actionButtonTile, for: .normal) actionPledges.text = "\(action.pledges)" switch action.review { case 1: star1.image = fillRatingImage star2.image = outlineRatingImage star3.image = outlineRatingImage star4.image = outlineRatingImage star5.image = outlineRatingImage case 2: star1.image = fillRatingImage star2.image = fillRatingImage star3.image = outlineRatingImage star4.image = outlineRatingImage star5.image = outlineRatingImage case 3: star1.image = fillRatingImage star2.image = fillRatingImage star3.image = fillRatingImage star4.image = outlineRatingImage star5.image = outlineRatingImage case 4: star1.image = fillRatingImage star2.image = fillRatingImage star3.image = fillRatingImage star4.image = fillRatingImage star5.image = outlineRatingImage case 5: star1.image = fillRatingImage star2.image = fillRatingImage star3.image = fillRatingImage star4.image = fillRatingImage star5.image = fillRatingImage default: star1.image = outlineRatingImage star2.image = outlineRatingImage star3.image = outlineRatingImage star4.image = outlineRatingImage star5.image = outlineRatingImage } let catPictureURL = URL(string: action.image)! let session = URLSession(configuration: .default) let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in if let e = error { print("Error downloading cat picture: \(e)") } else { if let _ = response as? HTTPURLResponse { if data != nil, let image = UIImage(data: data!) { self.actionImage.image = image } else { print("Couldn't get image: Image is nil") } } else { print("Couldn't get response code for some reason") } } } downloadPicTask.resume() } } } override init(frame: CGRect) { super.init(frame: frame) self.commonInit(); } func schemeAvailable(_ scheme: String) -> Bool { if let url = URL.init(string: scheme) { return UIApplication.shared.canOpenURL(url) } return false } @IBAction func pledgeAction(_ sender: UIButton) { if let action = action { let PGDHook = "playgrounddo://#social!\(action.id)" let PGURL = URL(string: PGDHook) if UIApplication.shared.canOpenURL(PGURL! as URL) { UIApplication.shared.openURL(PGURL!) } else { if downloadPGS { let alertVC = UIAlertController(title: "No tienes la aplicación PlayGround Do.", message: "¿Quieres instalarla ahora?", preferredStyle: .actionSheet) let downloadAction = UIAlertAction(title: "Si", style: .default, handler: { (success) in let url = "https://itunes.apple.com/us/app/playground-do/id1234718743" let scheme = "itms-apps://itunes.apple.com/es/app/apple-store/id1234718743" if self.schemeAvailable("itms-apps://") { UIApplication.shared.openURL(URL(string: scheme)!) } else { UIApplication.shared.openURL(URL(string: url)!) } }) let cancelAction = UIAlertAction(title: "Ahora no", style: .cancel, handler: { (success) in let url = action.url let url_cms = action.cms_url if url != "" { UIApplication.shared.openURL(URL(string: url)!) } else { UIApplication.shared.openURL(URL(string: url_cms)!) } }) alertVC.addAction(downloadAction) alertVC.addAction(cancelAction) if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } topController.present(alertVC, animated: true, completion: nil) } } else { let url = action.url let url_cms = action.cms_url if url != "" { UIApplication.shared.openURL(URL(string: url)!) } else { UIApplication.shared.openURL(URL(string: url_cms)!) } } } } } @IBAction func shareAction(_ sender: UIButton) { if let action = action { let shortURL:String = action.url != "" ? action.url : action.cms_url; if let urlToShare = URL(string: shortURL as String) { let objectsToShare = ["\(action.title)", urlToShare, "vía @PlaygroundDO"] as [Any] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } topController.present(activityVC, animated: true, completion: nil) } } } } @IBAction func showDetail(_ sender: Any) { rotateView() } @IBAction func closeDetail(_ sender: Any) { rotateView() } func rotateView() { UIView.transition(with: self, duration: 0.5, options: .transitionFlipFromLeft, animations: { if self.detailView.isHidden { self.detailView.isHidden = false self.actionDetailButtonImage.image = self.zoomOutImage } else { self.detailView.isHidden = true self.actionDetailButtonImage.image = self.zoomInImage } }, completion: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } fileprivate func commonInit() { let bundle = Bundle(for: PGDActionView.self) bundle.loadNibNamed("PGDActionView", owner: self, options: nil) guard let content = contentView else { return } content.frame = self.bounds content.autoresizingMask = [.flexibleHeight, .flexibleWidth] content.layer.shadowColor = UIColor.black.withAlphaComponent(0.5).cgColor content.layer.shadowOffset = CGSize(width: 0, height: 0) content.layer.shadowOpacity = 0.5 content.layer.cornerRadius = 5 container.layer.cornerRadius = 5 detailView.layer.cornerRadius = 5 // actionButton.layer.borderColor = UIColor.black.cgColor // actionButton.layer.borderWidth = 1 // actionDetailButton.layer.borderColor = UIColor.black.cgColor // actionDetailButton.layer.borderWidth = 1 self.addSubview(content) } }
mit
f5b9e6b45fb9af0e9732bc324428ff11
41.667774
169
0.530328
5.43504
false
false
false
false
tjw/swift
stdlib/public/core/StringUTF8.swift
1
25589
//===--- StringUTF8.swift - A UTF8 view of String -------------------------===// // // 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 // //===----------------------------------------------------------------------===// extension String { /// A view of a string's contents as a collection of UTF-8 code units. /// /// You can access a string's view of UTF-8 code units by using its `utf8` /// property. A string's UTF-8 view encodes the string's Unicode scalar /// values as 8-bit integers. /// /// let flowers = "Flowers 💐" /// for v in flowers.utf8 { /// print(v) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 240 /// // 159 /// // 146 /// // 144 /// /// A string's Unicode scalar values can be up to 21 bits in length. To /// represent those scalar values using 8-bit integers, more than one UTF-8 /// code unit is often required. /// /// let flowermoji = "💐" /// for v in flowermoji.unicodeScalars { /// print(v, v.value) /// } /// // 💐 128144 /// /// for v in flowermoji.utf8 { /// print(v) /// } /// // 240 /// // 159 /// // 146 /// // 144 /// /// In the encoded representation of a Unicode scalar value, each UTF-8 code /// unit after the first is called a *continuation byte*. /// /// UTF8View Elements Match Encoded C Strings /// ========================================= /// /// Swift streamlines interoperation with C string APIs by letting you pass a /// `String` instance to a function as an `Int8` or `UInt8` pointer. When you /// call a C function using a `String`, Swift automatically creates a buffer /// of UTF-8 code units and passes a pointer to that buffer. The code units /// of that buffer match the code units in the string's `utf8` view. /// /// The following example uses the C `strncmp` function to compare the /// beginning of two Swift strings. The `strncmp` function takes two /// `const char*` pointers and an integer specifying the number of characters /// to compare. Because the strings are identical up to the 14th character, /// comparing only those characters results in a return value of `0`. /// /// let s1 = "They call me 'Bell'" /// let s2 = "They call me 'Stacey'" /// /// print(strncmp(s1, s2, 14)) /// // Prints "0" /// print(String(s1.utf8.prefix(14))) /// // Prints "They call me '" /// /// Extending the compared character count to 15 includes the differing /// characters, so a nonzero result is returned. /// /// print(strncmp(s1, s2, 15)) /// // Prints "-17" /// print(String(s1.utf8.prefix(15))) /// // Prints "They call me 'B" @_fixed_layout // FIXME(sil-serialize-all) public struct UTF8View : BidirectionalCollection, CustomStringConvertible, CustomDebugStringConvertible { /// Underlying UTF-16-compatible representation @usableFromInline internal var _guts: _StringGuts /// Distances to `(startIndex, endIndex)` from the endpoints of _guts, /// measured in UTF-8 code units. /// /// Note: this is *only* here to support legacy Swift3-style slicing where /// `s.utf8[i..<j]` produces a `String.UTF8View`, and should be removed when /// those semantics are no longer supported. @usableFromInline internal let _legacyOffsets: (start: Int8, end: Int8) /// Flags indicating whether the limits of this view did not originally fall /// on grapheme cluster boundaries in the original string. This is used to /// emulate (undocumented) Swift 3 behavior where String.init?(_:) returned /// nil in such cases. /// /// Note: this is *only* here to support legacy Swift3-style slicing where /// `s.utf8[i..<j]` produces a `String.UTF8View`, and should be removed when /// those semantics are no longer supported. @usableFromInline internal let _legacyPartialCharacters: (start: Bool, end: Bool) @inlinable // FIXME(sil-serialize-all) internal init( _ _guts: _StringGuts, legacyOffsets: (Int, Int) = (0, 0), legacyPartialCharacters: (Bool, Bool) = (false, false) ) { self._guts = _guts self._legacyOffsets = (Int8(legacyOffsets.0), Int8(legacyOffsets.1)) self._legacyPartialCharacters = legacyPartialCharacters } public typealias Index = String.Index /// The position of the first code unit if the UTF-8 view is /// nonempty. /// /// If the UTF-8 view is empty, `startIndex` is equal to `endIndex`. @inlinable // FIXME(sil-serialize-all) public var startIndex: Index { let r = _index(atEncodedOffset: _guts.startIndex) if _legacyOffsets.start == 0 { return r } return index(r, offsetBy: numericCast(_legacyOffsets.start)) } /// The "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// In an empty UTF-8 view, `endIndex` is equal to `startIndex`. @inlinable // FIXME(sil-serialize-all) public var endIndex: Index { _sanityCheck(_legacyOffsets.end >= -3 && _legacyOffsets.end <= 0, "out of bounds legacy end") var r = Index(encodedOffset: _guts.endIndex) if _fastPath(_legacyOffsets.end == 0) { return r } switch _legacyOffsets.end { case -3: r = index(before: r); fallthrough case -2: r = index(before: r); fallthrough case -1: return index(before: r) default: Builtin.unreachable() } } @inlinable // FIXME(sil-serialize-all) internal func _index(atEncodedOffset n: Int) -> Index { if _fastPath(_guts.isASCII) { return Index(encodedOffset: n) } let count = _guts.count if n == count { return endIndex } var p = UTF16.ForwardParser() var i = _guts.makeIterator(in: n..<count) var buffer = Index._UTF8Buffer() Loop: while true { switch p.parseScalar(from: &i) { case .valid(let u16): let u8 = Unicode.UTF8.transcode(u16, from: Unicode.UTF16.self) ._unsafelyUnwrappedUnchecked if buffer.count + u8.count > buffer.capacity { break Loop } buffer.append(contentsOf: u8) case .error: let u8 = Unicode.UTF8.encodedReplacementCharacter if buffer.count + u8.count > buffer.capacity { break Loop } buffer.append(contentsOf: u8) case .emptyInput: break Loop } } return Index(encodedOffset: n, .utf8(buffer: buffer)) } /// Returns the next consecutive position after `i`. /// /// - Precondition: The next position is representable. @inlinable // FIXME(sil-serialize-all) @inline(__always) public func index(after i: Index) -> Index { if _fastPath(_guts.isASCII) { precondition(i.encodedOffset < _guts.count) return Index(encodedOffset: i.encodedOffset + 1) } var j = i // Ensure j's cache is utf8 if _slowPath(j._cache.utf8 == nil) { j = _index(atEncodedOffset: j.encodedOffset) precondition(j != endIndex, "Index out of bounds") } let buffer = j._cache.utf8._unsafelyUnwrappedUnchecked var scalarLength16 = 1 let b0 = buffer.first._unsafelyUnwrappedUnchecked var nextBuffer = buffer let leading1s = (~b0).leadingZeroBitCount if _fastPath(leading1s == 0) { // ASCII in buffer; just consume it nextBuffer.removeFirst() } else { // Number of bytes consumed in this scalar let n8 = j._transcodedOffset + 1 // If we haven't reached a scalar boundary... if _fastPath(n8 < leading1s) { // Advance to the next position in this scalar return Index( encodedOffset: j.encodedOffset, transcodedOffset: n8, .utf8(buffer: buffer)) } // We reached a scalar boundary; compute the underlying utf16's width // based on the number of utf8 code units scalarLength16 = n8 >> 2 + 1 nextBuffer.removeFirst(n8) } if _fastPath(!nextBuffer.isEmpty) { return Index( encodedOffset: j.encodedOffset + scalarLength16, .utf8(buffer: nextBuffer)) } // If nothing left in the buffer, refill it. return _index(atEncodedOffset: j.encodedOffset + scalarLength16) } @inlinable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { if _fastPath(_guts.isASCII) { precondition(i.encodedOffset > 0) return Index(encodedOffset: i.encodedOffset - 1) } if i._transcodedOffset != 0 { _sanityCheck(i._cache.utf8 != nil) var r = i r._compoundOffset = r._compoundOffset &- 1 return r } // Handle the scalar boundary the same way as the not-a-utf8-index case. _precondition(i.encodedOffset > 0, "Can't move before startIndex") // Parse a single scalar let u = _guts.unicodeScalar(endingAt: i.encodedOffset) let u8 = Unicode.UTF8.encode(u)._unsafelyUnwrappedUnchecked return Index( encodedOffset: i.encodedOffset &- (u8.count < 4 ? 1 : 2), transcodedOffset: u8.count &- 1, .utf8(buffer: String.Index._UTF8Buffer(u8)) ) } @inlinable // FIXME(sil-serialize-all) public func distance(from i: Index, to j: Index) -> Int { if _fastPath(_guts.isASCII) { return j.encodedOffset - i.encodedOffset } return j >= i ? _forwardDistance(from: i, to: j) : -_forwardDistance(from: j, to: i) } @inlinable // FIXME(sil-serialize-all) @inline(__always) internal func _forwardDistance(from i: Index, to j: Index) -> Int { return j._transcodedOffset - i._transcodedOffset + String.UTF8View._count(fromUTF16: IteratorSequence(_guts.makeIterator( in: i.encodedOffset..<j.encodedOffset))) } /// Accesses the code unit at the given position. /// /// The following example uses the subscript to print the value of a /// string's first UTF-8 code unit. /// /// let greeting = "Hello, friend!" /// let i = greeting.utf8.startIndex /// print("First character's UTF-8 code unit: \(greeting.utf8[i])") /// // Prints "First character's UTF-8 code unit: 72" /// /// - Parameter position: A valid index of the view. `position` /// must be less than the view's end index. @inlinable // FIXME(sil-serialize-all) public subscript(position: Index) -> UTF8.CodeUnit { @inline(__always) get { if _fastPath(_guts.isASCII) { let ascii = _guts._unmanagedASCIIView let offset = position.encodedOffset _precondition(offset < ascii.count, "Index out of bounds") return ascii.buffer[position.encodedOffset] } var j = position while true { if case .utf8(let buffer) = j._cache { _onFastPath() return buffer[ buffer.index(buffer.startIndex, offsetBy: j._transcodedOffset)] } j = _index(atEncodedOffset: j.encodedOffset) precondition(j < endIndex, "Index out of bounds") } } } @inlinable // FIXME(sil-serialize-all) public var description: String { return String(_guts) } @inlinable // FIXME(sil-serialize-all) public var debugDescription: String { return "UTF8View(\(self.description.debugDescription))" } } /// A UTF-8 encoding of `self`. @inlinable // FIXME(sil-serialize-all) public var utf8: UTF8View { get { return UTF8View(self._guts) } set { self = String(describing: newValue) } } /// A contiguously stored null-terminated UTF-8 representation of the string. /// /// To access the underlying memory, invoke `withUnsafeBufferPointer` on the /// array. /// /// let s = "Hello!" /// let bytes = s.utf8CString /// print(bytes) /// // Prints "[72, 101, 108, 108, 111, 33, 0]" /// /// bytes.withUnsafeBufferPointer { ptr in /// print(strlen(ptr.baseAddress!)) /// } /// // Prints "6" @inlinable // FIXME(sil-serialize-all) public var utf8CString: ContiguousArray<CChar> { var result = ContiguousArray<CChar>() result.reserveCapacity(utf8.count + 1) for c in utf8 { result.append(CChar(bitPattern: c)) } result.append(0) return result } @inlinable // FIXME(sil-serialize-all) internal func _withUnsafeBufferPointerToUTF8<R>( _ body: (UnsafeBufferPointer<UTF8.CodeUnit>) throws -> R ) rethrows -> R { if _guts.isASCII { return try body(_guts._unmanagedASCIIView.buffer) } var nullTerminatedUTF8 = ContiguousArray<UTF8.CodeUnit>() nullTerminatedUTF8.reserveCapacity(utf8.count + 1) nullTerminatedUTF8 += utf8 nullTerminatedUTF8.append(0) return try nullTerminatedUTF8.withUnsafeBufferPointer(body) } /// Creates a string corresponding to the given sequence of UTF-8 code units. /// /// If `utf8` is an ill-formed UTF-8 code sequence, the result is `nil`. /// /// You can use this initializer to create a new string from a slice of /// another string's `utf8` view. /// /// let picnicGuest = "Deserving porcupine" /// if let i = picnicGuest.utf8.index(of: 32) { /// let adjective = String(picnicGuest.utf8[..<i]) /// print(adjective) /// } /// // Prints "Optional(Deserving)" /// /// The `adjective` constant is created by calling this initializer with a /// slice of the `picnicGuest.utf8` view. /// /// - Parameter utf8: A UTF-8 code sequence. @inlinable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2, message: "Failable initializer was removed in Swift 4. When upgrading to Swift 4, please use non-failable String.init(_:UTF8View)") @available(swift, obsoleted: 4.0, message: "Please use non-failable String.init(_:UTF8View) instead") public init?(_ utf8: UTF8View) { if utf8.startIndex._transcodedOffset != 0 || utf8.endIndex._transcodedOffset != 0 || utf8._legacyPartialCharacters.start || utf8._legacyPartialCharacters.end { return nil } self = String(utf8._guts) } /// Creates a string corresponding to the given sequence of UTF-8 code units. @inlinable // FIXME(sil-serialize-all) @available(swift, introduced: 4.0, message: "Please use failable String.init?(_:UTF8View) when in Swift 3.2 mode") public init(_ utf8: UTF8View) { self = String(utf8._guts) } /// The index type for subscripting a string. public typealias UTF8Index = UTF8View.Index } extension String.UTF8View : _SwiftStringView { @inlinable // FIXME(sil-serialize-all) internal var _persistentContent : String { return String(self._guts) } @inlinable // FIXME(sil-serialize-all) var _wholeString : String { return String(_guts) } @inlinable // FIXME(sil-serialize-all) var _encodedOffsetRange : Range<Int> { return 0..<_guts.count } } extension String.UTF8View { @_fixed_layout // FIXME(sil-serialize-all) public struct Iterator { internal typealias _OutputBuffer = _ValidUTF8Buffer<UInt64> @usableFromInline internal let _guts: _StringGuts @usableFromInline internal let _endOffset: Int @usableFromInline // FIXME(sil-serialize-all) internal var _nextOffset: Int @usableFromInline // FIXME(sil-serialize-all) internal var _buffer: _OutputBuffer } public func makeIterator() -> Iterator { return Iterator(self) } } extension String.UTF8View.Iterator : IteratorProtocol { public typealias Element = String.UTF8View.Element @inlinable // FIXME(sil-serialize-all) internal init(_ utf8: String.UTF8View) { self._guts = utf8._guts self._nextOffset = 0 self._buffer = _OutputBuffer() self._endOffset = utf8._guts.count } @inlinable // FIXME(sil-serialize-all) public mutating func next() -> Unicode.UTF8.CodeUnit? { if _slowPath(_nextOffset == _endOffset) { if _slowPath(_buffer.isEmpty) { return nil } } if _guts.isASCII { defer { _nextOffset += 1 } return _guts._unmanagedASCIIView.buffer[_nextOffset] } if _guts._isSmall { defer { _nextOffset += 1 } return _guts._smallUTF8String[_nextOffset] } if _fastPath(!_buffer.isEmpty) { return _buffer.removeFirst() } return _fillBuffer() } @usableFromInline @inline(never) internal mutating func _fillBuffer() -> Unicode.UTF8.CodeUnit { _sanityCheck(!_guts.isASCII, "next() already checks for known ASCII") if _slowPath(_guts._isOpaque) { return _opaqueFillBuffer() } defer { _fixLifetime(_guts) } return _fillBuffer(from: _guts._unmanagedUTF16View) } @usableFromInline // @opaque internal mutating func _opaqueFillBuffer() -> Unicode.UTF8.CodeUnit { _sanityCheck(_guts._isOpaque) defer { _fixLifetime(_guts) } return _fillBuffer(from: _guts._asOpaque()) } // NOT @usableFromInline internal mutating func _fillBuffer<V: _StringVariant>( from variant: V ) -> Unicode.UTF8.CodeUnit { // Eat as many ASCII characters as possible let asciiEnd = Swift.min(_nextOffset + _buffer.capacity, _endOffset) for cu in variant[_nextOffset..<asciiEnd] { if !UTF16._isASCII(cu) { break } _buffer.append(UInt8(truncatingIfNeeded: cu)) _nextOffset += 1 } if _nextOffset == asciiEnd { return _buffer.removeFirst() } // Decode UTF-16, encode UTF-8 for scalar in IteratorSequence( variant[_nextOffset..<_endOffset].makeUnicodeScalarIterator()) { let u8 = UTF8.encode(scalar)._unsafelyUnwrappedUnchecked let c8 = u8.count guard _buffer.count + c8 <= _buffer.capacity else { break } _buffer.append(contentsOf: u8) _nextOffset += 1 &+ (c8 &>> 2) } return _buffer.removeFirst() } } extension String.UTF8View { @inlinable // FIXME(sil-serialize-all) internal static func _count<Source: Sequence>(fromUTF16 source: Source) -> Int where Source.Element == Unicode.UTF16.CodeUnit { var result = 0 var prev: Unicode.UTF16.CodeUnit = 0 for u in source { switch u { case 0..<0x80: result += 1 case 0x80..<0x800: result += 2 case 0x800..<0xDC00: result += 3 case 0xDC00..<0xE000: result += UTF16.isLeadSurrogate(prev) ? 1 : 3 default: result += 3 } prev = u } return result } @inlinable // FIXME(sil-serialize-all) public var count: Int { if _fastPath(_guts.isASCII) { return _guts.count } return _visitGuts(_guts, ascii: { ascii in return ascii.count }, utf16: { utf16 in return String.UTF8View._count(fromUTF16: utf16) }, opaque: { opaque in return String.UTF8View._count(fromUTF16: opaque) }) } } // Index conversions extension String.UTF8View.Index { /// Creates an index in the given UTF-8 view that corresponds exactly to the /// specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the string's /// `utf8` view. /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.index(of: 32)! /// let utf8Index = String.UTF8View.Index(utf16Index, within: cafe.utf8)! /// /// print(Array(cafe.utf8[..<utf8Index])) /// // Prints "[67, 97, 102, 195, 169]" /// /// If the position passed in `utf16Index` doesn't have an exact /// corresponding position in `utf8`, the result of the initializer is /// `nil`. For example, because UTF-8 and UTF-16 represent high Unicode code /// points differently, an attempt to convert the position of the trailing /// surrogate of a UTF-16 surrogate pair fails. /// /// The next example attempts to convert the indices of the two UTF-16 code /// points that represent the teacup emoji (`"🍵"`). The index of the lead /// surrogate is successfully converted to a position in `utf8`, but the /// index of the trailing surrogate is not. /// /// let emojiHigh = cafe.utf16.index(after: utf16Index) /// print(String.UTF8View.Index(emojiHigh, within: cafe.utf8)) /// // Prints "Optional(String.Index(...))" /// /// let emojiLow = cafe.utf16.index(after: emojiHigh) /// print(String.UTF8View.Index(emojiLow, within: cafe.utf8)) /// // Prints "nil" /// /// - Parameters: /// - sourcePosition: A position in a `String` or one of its views. /// - target: The `UTF8View` in which to find the new position. @inlinable // FIXME(sil-serialize-all) public init?(_ sourcePosition: String.Index, within target: String.UTF8View) { switch sourcePosition._cache { case .utf8: self.init(encodedOffset: sourcePosition.encodedOffset, transcodedOffset:sourcePosition._transcodedOffset, sourcePosition._cache) default: guard String.UnicodeScalarView(target._guts)._isOnUnicodeScalarBoundary( sourcePosition) else { return nil } self.init(encodedOffset: sourcePosition.encodedOffset) } } } // Reflection extension String.UTF8View : CustomReflectable { /// Returns a mirror that reflects the UTF-8 view of a string. @inlinable // FIXME(sil-serialize-all) public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } extension String.UTF8View : CustomPlaygroundQuickLookable { @inlinable // FIXME(sil-serialize-all) @available(*, deprecated, message: "UTF8View.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(description) } } // backward compatibility for index interchange. extension String.UTF8View { @inlinable // FIXME(sil-serialize-all) @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index") public func index(after i: Index?) -> Index { return index(after: i!) } @inlinable // FIXME(sil-serialize-all) @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index") public func index(_ i: Index?, offsetBy n: Int) -> Index { return index(i!, offsetBy: n) } @inlinable // FIXME(sil-serialize-all) @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices") public func distance( from i: Index?, to j: Index?) -> Int { return distance(from: i!, to: j!) } @inlinable // FIXME(sil-serialize-all) @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index") public subscript(i: Index?) -> Unicode.UTF8.CodeUnit { return self[i!] } } //===--- Slicing Support --------------------------------------------------===// /// In Swift 3.2, in the absence of type context, /// /// someString.utf8[someString.utf8.startIndex..<someString.utf8.endIndex] /// /// was deduced to be of type `String.UTF8View`. Provide a more-specific /// Swift-3-only `subscript` overload that continues to produce /// `String.UTF8View`. extension String.UTF8View { public typealias SubSequence = Substring.UTF8View @inlinable // FIXME(sil-serialize-all) @available(swift, introduced: 4) public subscript(r: Range<Index>) -> String.UTF8View.SubSequence { return String.UTF8View.SubSequence(self, _bounds: r) } @inlinable // FIXME(sil-serialize-all) @available(swift, obsoleted: 4) public subscript(r: Range<Index>) -> String.UTF8View { let wholeString = String(_guts) let legacyPartialCharacters = ( (self._legacyPartialCharacters.start && r.lowerBound.encodedOffset == 0) || r.lowerBound.samePosition(in: wholeString) == nil, (self._legacyPartialCharacters.end && r.upperBound.encodedOffset == _guts.count) || r.upperBound.samePosition(in: wholeString) == nil) if r.upperBound._transcodedOffset == 0 { return String.UTF8View( _guts._extractSlice( r.lowerBound.encodedOffset..<r.upperBound.encodedOffset), legacyOffsets: (r.lowerBound._transcodedOffset, 0), legacyPartialCharacters: legacyPartialCharacters) } let b0 = r.upperBound._cache.utf8!.first! let scalarLength8 = (~b0).leadingZeroBitCount let scalarLength16 = scalarLength8 == 4 ? 2 : 1 let coreEnd = r.upperBound.encodedOffset + scalarLength16 return String.UTF8View( _guts._extractSlice(r.lowerBound.encodedOffset..<coreEnd), legacyOffsets: ( r.lowerBound._transcodedOffset, r.upperBound._transcodedOffset - scalarLength8), legacyPartialCharacters: legacyPartialCharacters) } @inlinable // FIXME(sil-serialize-all) @available(swift, obsoleted: 4) public subscript(bounds: ClosedRange<Index>) -> String.UTF8View { return self[bounds.relative(to: self)] } }
apache-2.0
39e7730e202cea4a9a8f92eecaac0061
33.888131
135
0.635514
3.987681
false
false
false
false
vvusu/LogAnalysis
Log Analysis/LogDetailVC.swift
1
811
// // LogDetailVC.swift // Log Analysis // // Created by vvusu on 10/28/15. // Copyright © 2015 vvusu. All rights reserved. // import Cocoa class LogDetailVC: NSViewController { @IBOutlet var logTextView: NSTextView! var content : String! override func viewDidLoad() { super.viewDidLoad() let textStorage = NSTextStorage() let layoutManager = NSLayoutManager() textStorage.addLayoutManager(layoutManager) let textContainer = NSTextContainer(containerSize: view.frame.size) layoutManager.addTextContainer(textContainer) logTextView.editable = true logTextView.selectable = true logTextView.textStorage?.appendAttributedString(NSAttributedString(string: content)) // Do view setup here. } }
lgpl-3.0
97402b222d22572d7dc825538a2cba70
26.931034
92
0.677778
4.909091
false
false
false
false
HipHipArr/PocketCheck
Cheapify 2.0/CategoryEntriesTableViewController.swift
1
3343
// // CategoryEntriesTableViewController.swift // Cheapify 2.0 // // Created by loaner on 7/6/15. // Copyright (c) 2015 Your Friend. All rights reserved. // import UIKit class CategoryEntriesTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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 tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } 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 NO 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?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
967ec59f87a1fe5b3bf1d6c914a459cd
33.463918
157
0.685911
5.534768
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Browser/BrowserViewController/BrowserViewController+URLBarDelegate.swift
1
15233
/* 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 Shared import Storage import Telemetry extension BrowserViewController: URLBarDelegate { func showTabTray() { Sentry.shared.clearBreadcrumbs() updateFindInPageVisibility(visible: false) var shouldShowChronTabs = false // default don't show let chronDebugValue = profile.prefs.boolForKey(PrefsKeys.ChronTabsPrefKey) let chronLPValue = chronTabsUserResearch?.chronTabsState ?? false // Only allow chron tabs on iPhone if UIDevice.current.userInterfaceIdiom == .phone { // Respect debug mode chron tab value on if chronDebugValue != nil { shouldShowChronTabs = chronDebugValue! // Respect build channel based settings } else if chronDebugValue == nil { if AppConstants.CHRONOLOGICAL_TABS { shouldShowChronTabs = true } else { // Respect LP value shouldShowChronTabs = chronLPValue } } } if shouldShowChronTabs { let tabTrayViewController = TabTrayV2ViewController(tabTrayDelegate: self, profile: profile) let controller: UINavigationController if #available(iOS 13.0, *) { controller = UINavigationController(rootViewController: tabTrayViewController) controller.presentationController?.delegate = tabTrayViewController // If we're not using the system theme, override the view's style to match if !ThemeManager.instance.systemThemeIsOn { controller.overrideUserInterfaceStyle = ThemeManager.instance.userInterfaceStyle } } else { let themedController = ThemedNavigationController(rootViewController: tabTrayViewController) themedController.presentingModalViewControllerDelegate = self controller = themedController } self.present(controller, animated: true, completion: nil) self.tabTrayControllerV2 = tabTrayViewController } else { let tabTrayController = TabTrayControllerV1(tabManager: tabManager, profile: profile, tabTrayDelegate: self) navigationController?.pushViewController(tabTrayController, animated: true) self.tabTrayController = tabTrayController } if let tab = tabManager.selectedTab { screenshotHelper.takeScreenshot(tab) } TelemetryWrapper.recordEvent(category: .action, method: .open, object: .tabTray) } func urlBarDidPressReload(_ urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressQRButton(_ urlBar: URLBarView) { let qrCodeViewController = QRCodeViewController() qrCodeViewController.qrCodeDelegate = self let controller = QRCodeNavigationController(rootViewController: qrCodeViewController) self.present(controller, animated: true, completion: nil) } func urlBarDidPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { guard let tab = tabManager.selectedTab, let urlString = tab.url?.absoluteString, !urlBar.inOverlayMode else { return } let actionMenuPresenter: (URL, Tab, UIView, UIPopoverArrowDirection) -> Void = { (url, tab, view, _) in self.presentActivityViewController(url, tab: tab, sourceView: view, sourceRect: view.bounds, arrowDirection: .up) } let findInPageAction = { self.updateFindInPageVisibility(visible: true) } let reportSiteIssue = { self.openURLInNewTab(SupportUtils.URLForReportSiteIssue(self.urlBar.currentURL?.absoluteString)) } let successCallback: (String, ButtonToastAction) -> Void = { (successMessage, toastAction) in switch toastAction { case .removeBookmark: let toast = ButtonToast(labelText: successMessage, buttonText: Strings.UndoString, textAlignment: .left) { isButtonTapped in isButtonTapped ? self.addBookmark(url: urlString) : nil } self.show(toast: toast) default: SimpleToast().showAlertWithText(successMessage, bottomContainer: self.webViewContainer) } } let deferredBookmarkStatus: Deferred<Maybe<Bool>> = fetchBookmarkStatus(for: urlString) let deferredPinnedTopSiteStatus: Deferred<Maybe<Bool>> = fetchPinnedTopSiteStatus(for: urlString) // Wait for both the bookmark status and the pinned status deferredBookmarkStatus.both(deferredPinnedTopSiteStatus).uponQueue(.main) { let shouldShowNewTabButton = false let isBookmarked = $0.successValue ?? false let isPinned = $1.successValue ?? false let pageActions = self.getTabActions(tab: tab, buttonView: button, presentShareMenu: actionMenuPresenter, findInPage: findInPageAction, reportSiteIssue: reportSiteIssue, presentableVC: self, isBookmarked: isBookmarked, isPinned: isPinned, shouldShowNewTabButton: shouldShowNewTabButton, success: successCallback) self.presentSheetWith(title: Strings.PageActionMenuTitle, actions: pageActions, on: self, from: button) } } func urlBarDidLongPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { guard let tab = tabManager.selectedTab else { return } guard let url = tab.canonicalURL?.displayURL, self.presentedViewController == nil else { return } let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() presentActivityViewController(url, tab: tab, sourceView: button, sourceRect: button.bounds, arrowDirection: .up) } func urlBarDidTapShield(_ urlBar: URLBarView) { if let tab = self.tabManager.selectedTab { let trackingProtectionMenu = self.getTrackingSubMenu(for: tab) let title = String.localizedStringWithFormat(Strings.TPPageMenuTitle, tab.url?.host ?? "") LeanPlumClient.shared.track(event: .trackingProtectionMenu) TelemetryWrapper.recordEvent(category: .action, method: .press, object: .trackingProtectionMenu) self.presentSheetWith(title: title, actions: trackingProtectionMenu, on: self, from: urlBar) } } func urlBarDidPressStop(_ urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(_ urlBar: URLBarView) { showTabTray() } func urlBarDidPressReaderMode(_ urlBar: URLBarView) { libraryDrawerViewController?.close() guard let tab = tabManager.selectedTab, let readerMode = tab.getContentScript(name: "ReaderMode") as? ReaderMode else { return } switch readerMode.state { case .available: enableReaderMode() TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .readerModeOpenButton) LeanPlumClient.shared.track(event: .useReaderView) case .active: disableReaderMode() TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .readerModeCloseButton) case .unavailable: break } } func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool { guard let tab = tabManager.selectedTab, let url = tab.url?.displayURL else { UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: String.ReaderModeAddPageGeneralErrorAccessibilityLabel) return false } let result = profile.readingList.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) switch result.value { case .success: UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: String.ReaderModeAddPageSuccessAcessibilityLabel) SimpleToast().showAlertWithText(Strings.ShareAddToReadingListDone, bottomContainer: self.webViewContainer) case .failure(let error): UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: String.ReaderModeAddPageMaybeExistsErrorAccessibilityLabel) print("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)") } return true } func urlBarDidLongPressReload(_ urlBar: URLBarView, from button: UIButton) { guard let tab = tabManager.selectedTab else { return } let urlActions = self.getRefreshLongPressMenu(for: tab) guard !urlActions.isEmpty else { return } let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() let shouldSuppress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad presentSheetWith(actions: [urlActions], on: self, from: button, suppressPopover: shouldSuppress) } func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.general.string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDisplayTextForURL(_ url: URL?) -> (String?, Bool) { // use the initial value for the URL so we can do proper pattern matching with search URLs var searchURL = self.tabManager.selectedTab?.url if let url = searchURL, InternalURL.isValid(url: url) { searchURL = url } if let query = profile.searchEngines.queryForSearchURL(searchURL as URL?) { return (query, true) } else { return (url?.absoluteString, false) } } func urlBarDidLongPressLocation(_ urlBar: URLBarView) { let urlActions = self.getLongPressLocationBarActions(with: urlBar, webViewContainer: self.webViewContainer) let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() self.presentSheetWith(actions: [urlActions], on: self, from: urlBar) } func urlBarDidPressScrollToTop(_ urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab, firefoxHomeViewController == nil { // Only scroll to top if we are not showing the home view controller selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true) } } func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(_ urlBar: URLBarView, didRestoreText text: String) { if text.isEmpty { hideSearchController() } else { showSearchController() } searchController?.searchQuery = text searchLoader?.setQueryWithoutAutocomplete(text) } func urlBar(_ urlBar: URLBarView, didEnterText text: String) { urlBar.updateSearchEngineImage() if text.isEmpty { hideSearchController() } else { showSearchController() } searchController?.searchQuery = text searchLoader?.query = text } func urlBar(_ urlBar: URLBarView, didSubmitText text: String) { guard let currentTab = tabManager.selectedTab else { return } if let fixupURL = URIFixup.getURL(text) { // The user entered a URL, so use it. finishEditingAndSubmit(fixupURL, visitType: VisitType.typed, forTab: currentTab) return } // We couldn't build a URL, so check for a matching search keyword. let trimmedText = text.trimmingCharacters(in: .whitespaces) guard let possibleKeywordQuerySeparatorSpace = trimmedText.firstIndex(of: " ") else { submitSearchText(text, forTab: currentTab) return } let possibleKeyword = String(trimmedText[..<possibleKeywordQuerySeparatorSpace]) let possibleQuery = String(trimmedText[trimmedText.index(after: possibleKeywordQuerySeparatorSpace)...]) profile.places.getBookmarkURLForKeyword(keyword: possibleKeyword).uponQueue(.main) { result in if var urlString = result.successValue ?? "", let escapedQuery = possibleQuery.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed), let range = urlString.range(of: "%s") { urlString.replaceSubrange(range, with: escapedQuery) if let url = URL(string: urlString) { self.finishEditingAndSubmit(url, visitType: VisitType.typed, forTab: currentTab) return } } self.submitSearchText(text, forTab: currentTab) } } func submitSearchText(_ text: String, forTab tab: Tab) { let engine = profile.searchEngines.defaultEngine if let searchURL = engine.searchURLForQuery(text) { // We couldn't find a matching search keyword, so do a search query. Telemetry.default.recordSearch(location: .actionBar, searchEngine: engine.engineID ?? "other") GleanMetrics.Search.counts["\(engine.engineID ?? "custom").\(SearchesMeasurement.SearchLocation.actionBar.rawValue)"].add() searchTelemetry?.shouldSetUrlTypeSearch = true finishEditingAndSubmit(searchURL, visitType: VisitType.typed, forTab: tab) } else { // We still don't have a valid URL, so something is broken. Give up. print("Error handling URL entry: \"\(text)\".") assertionFailure("Couldn't generate search URL: \(text)") } } func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) { libraryDrawerViewController?.close() urlBar.updateSearchEngineImage() guard let profile = profile as? BrowserProfile else { return } if .blankPage == NewTabAccessors.getNewTabPage(profile.prefs) { UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: UIAccessibility.Notification.screenChanged) } else { if let toast = clipboardBarDisplayHandler?.clipboardToast { toast.removeFromSuperview() } showFirefoxHome(inline: false) } LeanPlumClient.shared.track(event: .interactWithURLBar) } func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) { destroySearchController() updateInContentHomePanel(tabManager.selectedTab?.url as URL?) } func urlBarDidBeginDragInteraction(_ urlBar: URLBarView) { dismissVisibleMenus() } }
mpl-2.0
cf3e0b6c6121d0fcc7e6fe084a218e14
43.802941
161
0.656535
5.545322
false
false
false
false
nathawes/swift
test/SILGen/objc_witnesses.swift
13
4771
// RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import gizmo protocol Fooable { func foo() -> String! } // Witnesses Fooable.foo with the original ObjC-imported -foo method . extension Foo: Fooable {} class Phoûx : NSObject, Fooable { @objc func foo() -> String! { return "phoûx!" } } // witness for Foo.foo uses the foreign-to-native thunk: // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$sSo3FooC14objc_witnesses7FooableA2cDP3foo{{[_0-9a-zA-Z]*}}FTW // CHECK: function_ref @$sSo3FooC3foo{{[_0-9a-zA-Z]*}}FTO // witness for Phoûx.foo uses the Swift vtable // CHECK-LABEL: $s14objc_witnesses008Phox_xraC3foo{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[IN_ADDR:%.*]] : // CHECK: [[VALUE:%.*]] = load_borrow [[IN_ADDR]] // CHECK: [[CLS_METHOD:%.*]] = class_method [[VALUE]] : $Phoûx, #Phoûx.foo : // CHECK: apply [[CLS_METHOD]]([[VALUE]]) // CHECK: end_borrow [[VALUE]] protocol Bells { init(bellsOn: Int) } extension Gizmo : Bells { } // CHECK: sil private [transparent] [thunk] [ossa] @$sSo5GizmoC14objc_witnesses5BellsA2cDP{{[_0-9a-zA-Z]*}}fCTW // CHECK: bb0([[SELF:%[0-9]+]] : $*Gizmo, [[I:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick Gizmo.Type): // CHECK: [[INIT:%[0-9]+]] = function_ref @$sSo5GizmoC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thick Gizmo.Type) -> @owned Optional<Gizmo> // CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[I]], [[META]]) : $@convention(method) (Int, @thick Gizmo.Type) -> @owned Optional<Gizmo> // CHECK: switch_enum [[IUO_RESULT]] // CHECK: bb1: // CHECK-NEXT: [[FILESTR:%.*]] = string_literal utf8 " // CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1, // CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK: [[PRECOND:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]]) // CHECK: bb2([[UNWRAPPED_RESULT:%.*]] : @owned $Gizmo): // CHECK: store [[UNWRAPPED_RESULT]] to [init] [[SELF]] : $*Gizmo // Test extension of a native @objc class to conform to a protocol with a // subscript requirement. rdar://problem/20371661 protocol Subscriptable { subscript(x: Int) -> Any { get } } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$sSo7NSArrayC14objc_witnesses13SubscriptableA2cDPyypSicigTW : // CHECK: function_ref @$sSo7NSArrayCyypSicigTO : $@convention(method) (Int, @guaranteed NSArray) -> @out Any // CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$sSo7NSArrayCyypSicigTO : $@convention(method) (Int, @guaranteed NSArray) -> @out Any { // CHECK: objc_method {{%.*}} : $NSArray, #NSArray.subscript!getter.foreign extension NSArray: Subscriptable {} // witness is a dynamic thunk: protocol Orbital { var quantumNumber: Int { get set } } class Electron : Orbital { @objc dynamic var quantumNumber: Int = 0 } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s14objc_witnesses8ElectronCAA7OrbitalA2aDP13quantumNumberSivgTW // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] [ossa] @$s14objc_witnesses8ElectronC13quantumNumberSivgTD // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s14objc_witnesses8ElectronCAA7OrbitalA2aDP13quantumNumberSivsTW // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] [ossa] @$s14objc_witnesses8ElectronC13quantumNumberSivsTD // witness is a dynamic thunk and is public: public protocol Lepton { var spin: Float { get } } public class Positron : Lepton { @objc public dynamic var spin: Float = 0.5 } // CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$s14objc_witnesses8PositronCAA6LeptonA2aDP4spinSfvgTW // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] [ossa] @$s14objc_witnesses8PositronC4spinSfvgTD // Override of property defined in @objc extension class Derived : NSObject { @objc override var valence: Int { get { return 2 } set { } } } extension NSObject : Atom { @objc var valence: Int { get { return 1 } set { } } } // CHECK-LABEL: sil shared [ossa] @$sSo8NSObjectC14objc_witnessesE7valenceSivM : $@yield_once @convention(method) (@guaranteed NSObject) -> @yields @inout Int { // CHECK: objc_method %0 : $NSObject, #NSObject.valence!getter.foreign // CHECK: yield // CHECK: objc_method %0 : $NSObject, #NSObject.valence!setter.foreign // CHECK: } protocol Atom : class { var valence: Int { get set } }
apache-2.0
4453da91a56fcc7dde9da82affe67252
38.716667
160
0.670373
3.183701
false
false
false
false
atomkirk/TouchForms
TouchForms/Source/MessageChildFormElement.swift
1
1275
// // MessageChildFormElement.swift // TouchForms // // Created by Adam Kirk on 7/23/15. // Copyright (c) 2015 Adam Kirk. All rights reserved. // import Foundation class MessageChildFormElement: ChildFormElement, Hashable { let message: String init(message: String, type: ChildFormElementType, parentElement: FormElement) { self.message = message super.init(parentElement: parentElement, type: type, position: .Below) } override var cellClass: AnyClass { get { if type == .Loading { return LoadingChildFormCell.self } return super.cellClass } set { super.cellClass = newValue } } override func populateCell() { if let cell = cell as? MessageChildFormCell { cell.type = type cell.messageLabel.text = message } } // MARK: - Hashable var hashValue: Int { return message.hashValue } } // MARK: - Equatable func ==(lhs: MessageChildFormElement, rhs: MessageChildFormElement) -> Bool { return lhs.dynamicType === rhs.dynamicType && lhs.parentElement == rhs.parentElement && lhs.type == rhs.type && lhs.message == rhs.message }
mit
68d18cc60cb1e5e681615b71b4d6c19b
23.056604
83
0.598431
4.537367
false
false
false
false
AcerFeng/SwiftProject
TumbirMenu/TumbirMenu/MenuTransitionManager.swift
1
4983
// // MenuTransitionManager.swift // TumbirMenu // // Created by LanFeng on 2016/11/26. // Copyright © 2016年 LanFeng. All rights reserved. // import UIKit class MenuTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { private var presenting = false // MARK: -UIViewControllerAnimatedTransitioning func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!, transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!) let menuViewController = !presenting ? screens.from as! MenuViewController : screens.to as! MenuViewController let bottomViewController = !presenting ? screens.to as UIViewController : screens.from as UIViewController let menuView = menuViewController.view let bottomView = bottomViewController.view if presenting { offStageMenuController(menuViewController) } container.addSubview(bottomView!) container.addSubview(menuView!) let duration = transitionDuration(using: transitionContext) UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: [], animations: { if self.presenting { self.onStageMenuController(menuViewController) } else { self.offStageMenuController(menuViewController) } }, completion: { finished in transitionContext.completeTransition(true) UIApplication.shared.keyWindow!.addSubview(screens.to.view) }) } // MARK: -UIViewControllerTransitioningDelegate func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } // MARK: - private method func offStageMenuController(_ menuViewController: MenuViewController) -> Void { menuViewController.view.alpha = 0 let topRowOffset: CGFloat = 300 let middleRowOffset: CGFloat = 150 let bottomRowOffset: CGFloat = 50 menuViewController.textButton.transform = offstage(-topRowOffset) menuViewController.textLabel.transform = offstage(-topRowOffset) menuViewController.quoteButton.transform = offstage(-middleRowOffset) menuViewController.quoteLabel.transform = offstage(-middleRowOffset) menuViewController.chatButton.transform = offstage(-bottomRowOffset) menuViewController.chatLabel.transform = offstage(-bottomRowOffset) menuViewController.photoButton.transform = offstage(topRowOffset) menuViewController.photoLabel.transform = offstage(topRowOffset) menuViewController.linkButton.transform = offstage(middleRowOffset) menuViewController.linkLabel.transform = offstage(middleRowOffset) menuViewController.audioButton.transform = offstage(bottomRowOffset) menuViewController.audioLabel.transform = offstage(bottomRowOffset) } func onStageMenuController(_ menuViewController: MenuViewController) { menuViewController.view.alpha = 1 menuViewController.textButton.transform = CGAffineTransform.identity menuViewController.textLabel.transform = CGAffineTransform.identity menuViewController.quoteButton.transform = CGAffineTransform.identity menuViewController.quoteLabel.transform = CGAffineTransform.identity menuViewController.chatButton.transform = CGAffineTransform.identity menuViewController.chatLabel.transform = CGAffineTransform.identity menuViewController.photoButton.transform = CGAffineTransform.identity menuViewController.photoLabel.transform = CGAffineTransform.identity menuViewController.linkButton.transform = CGAffineTransform.identity menuViewController.linkLabel.transform = CGAffineTransform.identity menuViewController.audioButton.transform = CGAffineTransform.identity menuViewController.audioLabel.transform = CGAffineTransform.identity } func offstage(_ amount: CGFloat) -> CGAffineTransform { return CGAffineTransform(translationX: amount, y: 0) } }
apache-2.0
d1e46215a732815a463d281b6ed9c6da
44.688073
239
0.721486
6.409266
false
false
false
false
caronae/caronae-ios
Caronae/MenuViewController.swift
1
2239
import UIKit class MenuViewController: UIViewController { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var profileNameLabel: UILabel! @IBOutlet weak var profileCourseLabel: UILabel! var photoURL: String! deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() navigationController?.view.backgroundColor = .white navigationItem.titleView = UIImageView(image: UIImage(named: "NavigationBarLogo")) updateProfileFields() NotificationCenter.default.addObserver(self, selector: #selector(updateProfileFields), name: .CaronaeDidUpdateUser, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let user = UserService.instance.user, let userPhotoURL = user.profilePictureURL, !userPhotoURL.isEmpty, userPhotoURL != photoURL { photoURL = userPhotoURL profileImageView.crn_setImage(with: URL(string: userPhotoURL)) } } @objc func updateProfileFields() { guard let user = UserService.instance.user else { return } profileNameLabel.text = user.name profileCourseLabel.text = user.occupation } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ViewProfile" { let vc = segue.destination as! ProfileViewController vc.user = UserService.instance.user } else if segue.identifier == "About" { let vc = segue.destination as! WebViewController vc.page = .aboutPage } else if segue.identifier == "TermsOfUse" { let vc = segue.destination as! WebViewController vc.page = .termsOfUsePage } else if segue.identifier == "FAQ" { let vc = segue.destination as! WebViewController vc.page = .FAQPage } } func openRidesHistory() { performSegue(withIdentifier: "RidesHistory", sender: nil) } }
gpl-3.0
313b2221f02bfbe8ddbcd629a19a82e8
30.985714
136
0.615453
5.24356
false
false
false
false
nodekit-io/nodekit-darwin-lite
src/nodekit/NKScriptingLite/NKJSContext.swift
1
8151
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright 2015 XWebView * Portions Copyright (c) 2014 Intel Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import JavaScriptCore open class NKJSContext: NSObject { fileprivate let _jsContext: JSContext fileprivate let _id: Int private var plugins: [String: NKNativePlugin] = [:] //namespace -> plugin private var sources: [String: NKScriptSource] = [:] //filename -> source internal init(_ jsContext: JSContext, id: Int) { _jsContext = jsContext _id = id super.init() } internal func prepareEnvironment() -> Void { let logjs: @convention(block) (String, String, [String: AnyObject] ) -> () = { body, severity, labels in NKLogging.log(body, level: NKLogging.Level(description: severity), labels: labels); } _jsContext.exceptionHandler = { (ctx: JSContext?, value: JSValue?) in NKLogging.log("JavaScript Error"); // type of String let stacktrace = value?.objectForKeyedSubscript("stack").toString() ?? "No stack trace" // type of Number let lineNumber: Any = value?.objectForKeyedSubscript("line") ?? "Unknown" // type of Number let column: Any = value?.objectForKeyedSubscript("column") ?? "Unknown" let moreInfo = "in method \(stacktrace) Line number: \(lineNumber), column: \(column)" let errorString = value.map { $0.description } ?? "null" NKLogging.log("JavaScript Error: \(errorString) \(moreInfo)") } guard let _ = NKStorage.getResource("lib-scripting.nkar/lib-scripting/timer.js", NKJSContext.self) else { NKLogging.die("Failed to read provision script: timer") } loadPlugin(NKJSTimer()) let scriptingBridge = JSValue(newObjectIn: _jsContext) scriptingBridge?.setObject(logjs as AnyObject, forKeyedSubscript: "log" as NSString) _jsContext.setObject(scriptingBridge, forKeyedSubscript: "NKScriptingBridge" as NSString) let appjs = NKStorage.getResource("lib-scripting.nkar/lib-scripting/init_jsc.js", NKJSContext.self) let script = "function loadinit(){\n" + appjs! + "\n}\n" + "loadinit();" + "\n" self.injectJavaScript(NKScriptSource(source: script, asFilename: "io.nodekit.scripting/init_jsc", namespace: "io.nodekit.scripting.init")) guard let promiseSource = NKStorage.getResource("lib-scripting.nkar/lib-scripting/promise.js", NKJSContext.self) else { NKLogging.die("Failed to read provision script: promise") } self.injectJavaScript( NKScriptSource( source: promiseSource, asFilename: "io.nodekit.scripting/NKScripting/promise.js", namespace: "Promise" ) ) NKStorage.attachTo(self) } } extension NKJSContext: NKScriptContext { public var id: Int { get { return self._id } } public func loadPlugin(_ plugin: NKNativePlugin) -> Void { if let jsValue = setObjectForNamespace(plugin, namespace: plugin.namespace), let proxy = plugin as? NKNativeProxy { proxy.nkScriptObject = jsValue } NKLogging.log("+Plugin object \(plugin) is bound to \(plugin.namespace) with NKScriptingLite (JSExport) channel") plugins[plugin.namespace] = plugin guard let jspath: String = plugin.sourceJS else { return } guard let js = NKStorage.getResource(jspath, type(of: plugin)) else { return } self.injectJavaScript( NKScriptSource( source: js, asFilename: jspath, namespace: plugin.namespace ) ) } public func injectJavaScript(_ script: NKScriptSource) -> Void { script.inject(self) sources[script.filename] = script } public func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((AnyObject?, NSError?) -> Void)?) { let result = self._jsContext.evaluateScript(javaScriptString) completionHandler?(result, nil) } public func stop() -> Void { for plugin in plugins.values { if let proxy = plugin as? NKNativeProxy { proxy.nkScriptObject = nil } if let disposable = plugin as? NKDisposable { disposable.dispose() } } for script in sources.values { script.eject() } plugins.removeAll() sources.removeAll() } public func serialize(_ object: AnyObject?) -> String { var obj: AnyObject? = object if let val = obj as? NSValue { obj = val as? NSNumber ?? val.nonretainedObjectValue as AnyObject? } if let s = obj as? String { let d = try? JSONSerialization.data(withJSONObject: [s], options: JSONSerialization.WritingOptions(rawValue: 0)) let json = NSString(data: d!, encoding: String.Encoding.utf8.rawValue)! return json.substring(with: NSMakeRange(1, json.length - 2)) } else if let n = obj as? NSNumber { if CFGetTypeID(n) == CFBooleanGetTypeID() { return n.boolValue.description } return n.stringValue } else if let date = obj as? Date { return "\"\(date.toJSONDate())\"" } else if let _ = obj as? Data { // TODO: map to Uint8Array object } else if let a = obj as? [AnyObject] { return "[" + a.map(self.serialize).joined(separator: ", ") + "]" } else if let d = obj as? [String: AnyObject] { return "{" + d.keys.map {"\"\($0)\": \(self.serialize(d[$0]!))"}.joined(separator: ", ") + "}" } else if obj === NSNull() { return "null" } else if obj == nil { return "undefined" } return "'\(obj!)'" } // private methods fileprivate func setObjectForNamespace(_ object: AnyObject, namespace: String) -> JSValue? { let global = _jsContext.globalObject var fullNameArr = namespace.split {$0 == "."}.map(String.init) let lastItem = fullNameArr.removeLast() if (fullNameArr.isEmpty) { _jsContext.setObject(object, forKeyedSubscript: lastItem as NSString) return nil } let jsv = fullNameArr.reduce(global, {previous, current in if (previous?.hasProperty(current))! { return previous?.objectForKeyedSubscript(current) } let _jsv = JSValue(newObjectIn: _jsContext) previous?.setObject(_jsv, forKeyedSubscript: current as NSString) return _jsv }) jsv?.setObject(object, forKeyedSubscript: lastItem as NSString) let selfjsv = (jsv?.objectForKeyedSubscript(lastItem))! as JSValue return selfjsv } }
apache-2.0
1ab18f70a7964d480badf08a6e1ad150
31.73494
146
0.565697
4.843137
false
false
false
false