repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
airspeedswift/swift
refs/heads/master
test/Incremental/Verifier/single-file/AnyObject.swift
apache-2.0
4
// UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // UNSUPPORTED: CPU=armv7k && OS=ios // Exclude iOS-based 32-bit platforms because the Foundation overlays introduce // an extra dependency on _KeyValueCodingAndObservingPublishing only for 64-bit // platforms. // REQUIRES: objc_interop // RUN: %empty-directory(%t) // RUN: %{python} %S/../gen-output-file-map.py -o %t %S // RUN: cd %t && %target-swiftc_driver -typecheck -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -module-name main -verify-incremental-dependencies %s import Foundation // expected-provides {{LookupFactory}} // expected-provides {{NSObject}} // expected-private-superclass {{ObjectiveC.NSObject}} // expected-private-conformance {{ObjectiveC.NSObjectProtocol}} // expected-private-conformance {{Foundation._KeyValueCodingAndObserving}} // expected-private-conformance {{Foundation._KeyValueCodingAndObservingPublishing}} // expected-private-conformance {{Swift.Hashable}} // expected-private-conformance {{Swift.Equatable}} // expected-private-conformance {{Swift.CustomDebugStringConvertible}} // expected-private-conformance {{Swift.CVarArg}} // expected-private-conformance {{Swift.CustomStringConvertible}} // expected-cascading-member {{Swift._ExpressibleByBuiltinIntegerLiteral.init}} // expected-cascading-superclass {{main.LookupFactory}} @objc private class LookupFactory: NSObject { // expected-provides {{AssignmentPrecedence}} // expected-provides {{IntegerLiteralType}} // expected-provides {{FloatLiteralType}} // expected-provides {{Int}} // expected-cascading-member {{ObjectiveC.NSObject.someMember}} // expected-cascading-member {{ObjectiveC.NSObject.Int}} // expected-cascading-member {{ObjectiveC.NSObjectProtocol.someMember}} // expected-cascading-member {{ObjectiveC.NSObjectProtocol.Int}} // expected-cascading-member {{main.LookupFactory.Int}} @objc var someMember: Int = 0 // expected-cascading-member {{ObjectiveC.NSObject.someMethod}} // expected-cascading-member {{ObjectiveC.NSObjectProtocol.someMethod}} @objc func someMethod() {} // expected-cascading-member {{ObjectiveC.NSObject.init}} // expected-cascading-member {{ObjectiveC.NSObjectProtocol.init}} // expected-cascading-member {{main.LookupFactory.init}} // expected-private-member {{main.LookupFactory.deinit}} // expected-cascading-member {{main.LookupFactory.someMember}} // expected-cascading-member {{main.LookupFactory.someMethod}} } // expected-private-member {{Swift.ExpressibleByNilLiteral.callAsFunction}} // expected-private-member {{Swift.CustomReflectable.callAsFunction}} // expected-private-member {{Swift._ObjectiveCBridgeable.callAsFunction}} // expected-private-member {{Swift.Optional<Wrapped>.callAsFunction}} // expected-private-member {{Swift.CustomDebugStringConvertible.callAsFunction}} // expected-private-member {{Swift.Equatable.callAsFunction}} // expected-private-member {{Swift.Hashable.callAsFunction}} // expected-private-member {{Swift.Encodable.callAsFunction}} // expected-private-member {{Swift.Decodable.callAsFunction}} // expected-private-member {{Foundation._OptionalForKVO.callAsFunction}} // expected-provides {{AnyObject}} func lookupOnAnyObject(object: AnyObject) { // expected-provides {{lookupOnAnyObject}} _ = object.someMember // expected-private-dynamic-member {{someMember}} object.someMethod() // expected-private-dynamic-member {{someMethod}} } // expected-private-member {{Swift.Hashable.someMethod}} // expected-private-member {{Foundation._KeyValueCodingAndObserving.someMethod}} // expected-private-member {{Foundation._KeyValueCodingAndObservingPublishing.someMethod}} // expected-private-member {{Swift.Equatable.someMethod}} // expected-private-member {{Swift.CVarArg.someMethod}} // expected-private-member {{Swift.CustomStringConvertible.someMethod}} // expected-private-member {{Swift.CustomDebugStringConvertible.someMethod}}
cbb83fcea2a8de143858fe16e53c146c
52.959459
189
0.774606
false
false
false
false
rmncv/DRTableView
refs/heads/master
DRTableView/Controllers/DRTableViewController.swift
mit
1
// // DRTableViewController.swift // DRTableView // // Created by Denys Rumiantsev on 5/31/17. // Copyright © 2017 Denys Rumiantsev. All rights reserved. // import UIKit class DRTableViewController: UITableViewController { var table: Table { didSet { tableView.reloadData() } } init(table: Table, style: UITableViewStyle = .plain) { self.table = table super.init(style: style) } required init?(coder aDecoder: NSCoder) { table = Table(sections: []) super.init(coder: aDecoder) } // MARK: - UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return table.sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return table.sections[section].rows.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return table.sections[section].title } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = table.sections[indexPath.section].rows[indexPath.row] return row.cell(in: tableView, at: indexPath) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return table.sections[indexPath.section].rows[indexPath.row].height ?? UITableViewAutomaticDimension } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { table.sections[indexPath.section].rows[indexPath.row].didSelect?() } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return table.sections[section].customView } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let customView = table.sections[section].customView { return customView.bounds.height } if let _ = table.sections[section].title { return 20 // default value } return 0 } }
6cee13873fd8081221f20403702444fb
32.235294
109
0.660177
false
false
false
false
YuAo/MDSOfferView
refs/heads/master
MDSOfferViewDemo/MDSOfferViewDemo/Delay.swift
mit
1
// // Delay.swift // MDSOfferViewDemo // // Created by YuAo on 3/16/16. // Copyright © 2016 YuAo. All rights reserved. // import Foundation public class Delay { private var previousDelay: Delay? private var thenDelay: Delay? private var action: () -> Void private var interval: NSTimeInterval = 0 init(interval: NSTimeInterval, action: () -> Void) { self.interval = interval self.action = action } func then(thenDelay: Delay) -> Delay { self.thenDelay = thenDelay thenDelay.previousDelay = self return thenDelay } private func start() { delay(self.interval, closure: { self.action() self.thenDelay?.start() }) } func run() { if self.previousDelay != nil { var starter = self.previousDelay! while starter.previousDelay != nil { starter = starter.previousDelay! } starter.start() } else { self.start() } } } public func delay(aDelay:NSTimeInterval, closure: () -> Void) { delay(aDelay, queue: dispatch_get_main_queue(), closure: closure) } public func delay(aDelay:NSTimeInterval, queue: dispatch_queue_t!, closure: () -> Void) { let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(aDelay * Double(NSEC_PER_SEC))) dispatch_after(delayTime, queue, closure) } public extension Double { var second: NSTimeInterval { return self } var seconds: NSTimeInterval { return self } var minute: NSTimeInterval { return self * 60 } var minutes: NSTimeInterval { return self * 60 } var hour: NSTimeInterval { return self * 3600 } var hours: NSTimeInterval { return self * 3600 } }
723e6f10c8dde63080ebcf08f0702947
28.016667
90
0.617241
false
false
false
false
RobotsAndPencils/SwiftCharts
refs/heads/master
SwiftCharts/Axis/ChartAxisYHighLayerDefault.swift
apache-2.0
3
// // ChartAxisYHighLayerDefault.swift // SwiftCharts // // Created by ischuetz on 25/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit class ChartAxisYHighLayerDefault: ChartAxisYLayerDefault { override var low: Bool {return false} override var lineP1: CGPoint { return self.p1 } override var lineP2: CGPoint { return self.p2 } override func initDrawers() { self.lineDrawer = self.generateLineDrawer(offset: 0) let labelsOffset = self.settings.labelsToAxisSpacingY + self.settings.axisStrokeWidth self.labelDrawers = self.generateLabelDrawers(offset: labelsOffset) let axisTitleLabelsOffset = labelsOffset + self.labelsMaxWidth + self.settings.axisTitleLabelsToLabelsSpacing self.axisTitleLabelDrawers = self.generateAxisTitleLabelsDrawers(offset: axisTitleLabelsOffset) } override func generateLineDrawer(offset offset: CGFloat) -> ChartLineDrawer { let halfStrokeWidth = self.settings.axisStrokeWidth / 2 // we want that the stroke begins at the beginning of the frame, not in the middle of it let x = self.p1.x + offset + halfStrokeWidth let p1 = CGPointMake(x, self.p1.y) let p2 = CGPointMake(x, self.p2.y) return ChartLineDrawer(p1: p1, p2: p2, color: self.settings.lineColor, strokeWidth: self.settings.axisStrokeWidth) } override func labelsX(offset offset: CGFloat, labelWidth: CGFloat) -> CGFloat { return self.p1.x + offset } }
af64f9268b92f661b2ab57e789593bab
34.681818
152
0.691083
false
false
false
false
FredrikSjoberg/ForceDirectedGraph
refs/heads/master
ForceDirectedGraph/QuadTree/QuadTree.swift
mit
1
// // QuadTree.swift // ForceDirectedGraph // // Created by Fredrik Sjöberg on 19/05/16. // Copyright © 2016 FredrikSjoberg. All rights reserved. // import Foundation import CoreGraphics public class Body<T> { public let position: CGPoint public let data: T public init(position: CGPoint, data: T) { self.position = position self.data = data } } public class Quad<T> { public let bounds: CGRect public let center: CGPoint public var body: Body<T>? public var children: [Quad<T>]? public let count: Int public init(bounds: CGRect, center: CGPoint, num: Int, body: Body<T>? = nil, children: [Quad<T>]? = nil) { self.bounds = bounds self.center = center self.body = body self.children = children self.count = num } } public class QuadTree<T> { public let root: Quad<T> public init(bounds: CGRect, bodies: [Body<T>]) { root = configure(bounds, bodies: bodies) } } private func configure<T>(bounds: CGRect, bodies: [Body<T>]) -> Quad<T> { if bodies.isEmpty { return Quad(bounds: bounds, center: bounds.midpoint, num: 0) } else if bodies.count == 1 { return Quad(bounds: bounds, center: bodies.first!.position, num: 1, body: bodies.first!) } else { let children = bounds.subdivide.map{ subBounds -> Quad<T> in let clipped = bodies.filter{ subBounds.contains($0.position) } return configure(subBounds, bodies: clipped) } let location = bodies.reduce(CGPointZero){ $0 + $1.position } / CGFloat(bodies.count) return Quad(bounds: bounds, center: location, num: bodies.count, children: children) } }
6eec7e584dc3c98324a88f98e01370f7
26.030769
110
0.612187
false
false
false
false
ngleanh/Infinite-Scrolling-List
refs/heads/master
Infinite Scrolling List View/Controllers/MainViewController.swift
gpl-3.0
1
// // MainViewController.swift // Infinite Scrolling List View // // Created by Anh Nguyen on 11/12/16. // Copyright © 2016 Anh Nguyen. All rights reserved. // import UIKit import Realm import RealmSwift class MainViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let realm = try! Realm() var items: Results<Item>? var token: NotificationToken? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. token = realm.addNotificationBlock { [weak self] notification, realm in self?.tableView.reloadData() } setupUI() getData() } 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. } */ deinit { token?.stop() } } extension MainViewController { func setupUI() { // Load more indicator let loadMoreIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) loadMoreIndicator.startAnimating() tableView.tableFooterView = loadMoreIndicator // Screen title title = "Infinite Scrolling List" } } extension MainViewController { func getData() { items = realm.objects(Item.self).sorted(byProperty: "id", ascending: true) tableView.reloadData() } } extension MainViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCellIdentifier", for: indexPath) as! ItemTableViewCell let item = items?[indexPath.row] // Fill data to cell let formater = DateFormatter() formater.dateFormat = "EEEE, MMM d, yyyy" var createdText = "" if let id = item?.id { createdText += String(id) + " - " } if let createdDate = item?.created { createdText += formater.string(from: createdDate) } cell.createdLabel.text = createdText cell.senderLabel.text = item?.source?.sender ?? "" cell.noteLabel.text = item?.source?.note ?? "" cell.recipientLabel.text = item?.destination?.recipient ?? "" var amountTextValue = "" if let amountValue = item?.destination?.amount { amountTextValue += String(amountValue) } if let currency = item?.destination?.currency { amountTextValue += " " + currency } cell.amountLabel.text = amountTextValue return cell } } extension MainViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == self.items!.count - 1 { DataManager.shared.fetchMoreData(completionHandler: nil, errorHandler: nil) } } }
7a5844d2f12291f4942832988fef02f3
28.69403
124
0.633576
false
false
false
false
HeMet/DLife
refs/heads/master
MVVMKit/MVVMKit/DataBindings/Adapters/TableViewBaseAdapter.swift
mit
1
// // TableViewBaseAdapter.swift // MVVMKit // // Created by Евгений Губин on 21.06.15. // Copyright (c) 2015 SimbirSoft. All rights reserved. // import Foundation public enum TableViewSectionView { case Header, Footer } public class TableViewBaseAdapter: UITableViewSwiftDataSource, UITableViewSwiftDelegate { public typealias CellsChangedEvent = (TableViewBaseAdapter, [NSIndexPath]) -> () public typealias CellAction = (UITableViewCell, NSIndexPath) -> () let tag = "observable_array_tag" // Workaround: anowned(safe) cause random crashes for NSObject descendants unowned(unsafe) let tableView: UITableView public let cells: CellViewBindingManager public let views = ViewBindingManager() lazy var dsProxy: UITableViewDataSourceProxy = { [unowned self] in UITableViewDataSourceProxy(dataSource: self) }() lazy var dProxy: UITableViewDelegateProxy = { [unowned self] in UITableViewDelegateProxy(swiftDelegate: self) }() var updateCounter = 0 public var delegate: UITableViewDelegate? { get { return dProxy.delegate } set { dProxy.delegate = newValue self.tableView.delegate = nil self.tableView.delegate = dProxy } } public init(tableView: UITableView) { self.tableView = tableView cells = CellViewBindingManager(tableView: tableView) self.tableView.dataSource = dsProxy self.tableView.delegate = dProxy } //public init(tableView: UITableView, sourceSignal: Signal<[T], NoError>) func numberOfSections(tableView: UITableView) -> Int { fatalError("Abstract method") } func numberOfRowsInSection(tableView: UITableView, section: Int) -> Int { fatalError("Abstract method") } func cellForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell { let viewModel: AnyObject = viewModelForIndexPath(indexPath) return cells.bindViewModel(viewModel, indexPath: indexPath) } func viewModelForIndexPath(indexPath: NSIndexPath) -> AnyObject { fatalError("Abstract method") } func viewModelForSectionHeaderAtIndex(index: Int) -> AnyObject? { return nil } func viewModelForSectionFooterAtIndex(index: Int) -> AnyObject? { return nil } func titleForHeader(tableView: UITableView, section: Int) -> String? { return nil } func titleForFooter(tableView: UITableView, section: Int) -> String? { return nil } func viewForHeader(tableView: UITableView, section: Int) -> UIView? { if let viewModel: AnyObject = viewModelForSectionHeaderAtIndex(section) { return views.bindViewModel(viewModel) } return nil } func viewForFooter(tableView: UITableView, section: Int) -> UIView? { if let viewModel: AnyObject = viewModelForSectionFooterAtIndex(section) { return views.bindViewModel(viewModel) } return nil } func heightForHeader(tableView: UITableView, section: Int) -> CGFloat { let hasTitle = titleForHeader(tableView, section: section) != nil let hasVM = viewModelForSectionHeaderAtIndex(section) != nil return hasTitle || hasVM ? UITableViewAutomaticDimension : 0 } func heightForFooter(tableView: UITableView, section: Int) -> CGFloat { let hasTitle = titleForFooter(tableView, section: section) != nil let hasVM = viewModelForSectionFooterAtIndex(section) != nil return hasTitle || hasVM ? UITableViewAutomaticDimension : 0 } func didSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath) { } public func beginUpdate() { self.updateCounter++ if (self.updateCounter == 1) { self.tableView.beginUpdates() } } public func endUpdate() { precondition(self.updateCounter >= 0, "Batch update calls are unbalanced") self.updateCounter-- if (self.updateCounter == 0) { self.tableView.endUpdates() performDelayedActions() } } var delayedActions: [UITableView -> ()] = [] public func performAfterUpdate(action: UITableView -> ()) { if self.updateCounter == 0 { action(self.tableView) } else { delayedActions.append(action) } } func performDelayedActions() { let actions = delayedActions delayedActions.removeAll(keepCapacity: false) for action in actions { action(self.tableView) } } deinit { println("deinit Adapter") } public var onCellsInserted: CellsChangedEvent? public var onCellsRemoved: CellsChangedEvent? public var onCellsReloaded: CellsChangedEvent? } protocol UITableViewSwiftDataSource: class { func numberOfSections(tableView: UITableView) -> Int func numberOfRowsInSection(tableView: UITableView, section: Int) -> Int func cellForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell func titleForHeader(tableView: UITableView, section: Int) -> String? func titleForFooter(tableView: UITableView, section: Int) -> String? } @objc class UITableViewDataSourceProxy: NSObject, UITableViewDataSource { unowned var dataSource: UITableViewSwiftDataSource init(dataSource: UITableViewSwiftDataSource) { self.dataSource = dataSource } @objc func numberOfSectionsInTableView(tableView: UITableView) -> Int { return dataSource.numberOfSections(tableView) } @objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.numberOfRowsInSection(tableView, section: section) } @objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return dataSource.cellForRowAtIndexPath(tableView, indexPath: indexPath) } @objc func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return dataSource.titleForHeader(tableView, section: section) } @objc func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return dataSource.titleForFooter(tableView, section: section) } } protocol UITableViewSwiftDelegate: class { func viewForHeader(tableView: UITableView, section: Int) -> UIView? func viewForFooter(tableView: UITableView, section: Int) -> UIView? func heightForHeader(tableView: UITableView, section: Int) -> CGFloat func heightForFooter(tableView: UITableView, section: Int) -> CGFloat func didSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath) } @objc class UITableViewDelegateProxy: UITableViewDelegateForwarder { unowned var swiftDelegate: UITableViewSwiftDelegate init(swiftDelegate: UITableViewSwiftDelegate) { self.swiftDelegate = swiftDelegate super.init() } // nil means "use default stub view of non empty area" @objc override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return swiftDelegate.viewForHeader(tableView, section: section) } @objc override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return swiftDelegate.viewForFooter(tableView, section: section) } @objc override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return swiftDelegate.heightForHeader(tableView, section: section) } @objc override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return swiftDelegate.heightForFooter(tableView, section: section) } }
a4839e73fe4334b50b416e442abc0f5b
33.016807
115
0.674861
false
false
false
false
jessesquires/JSQCoreDataKit
refs/heads/main
Sources/NSManagedObjectContext+Extensions.swift
mit
1
// // Created by Jesse Squires // https://www.jessesquires.com // // // Documentation // https://jessesquires.github.io/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright © 2015-present Jesse Squires // Released under an MIT license: https://opensource.org/licenses/MIT // import CoreData extension NSManagedObjectContext { /// Describes a child managed object context. public typealias ChildContext = NSManagedObjectContext /// Describes the result type for saving a managed object context. public typealias SaveResult = Result<NSManagedObjectContext, Error> /// Attempts to **asynchronously** commit unsaved changes to registered objects in the context. /// This function is performed in a block on the context's queue. If the context has no changes, /// then this function returns immediately and the completion block is not called. /// /// - Parameter completion: The closure to be executed when the save operation completes. public func saveAsync(completion: ((SaveResult) -> Void)? = nil) { self._save(wait: false, completion: completion) } /// Attempts to **synchronously** commit unsaved changes to registered objects in the context. /// This function is performed in a block on the context's queue. If the context has no changes, /// then this function returns immediately and the completion block is not called. /// /// - Parameter completion: The closure to be executed when the save operation completes. public func saveSync(completion: ((SaveResult) -> Void)? = nil) { self._save(wait: true, completion: completion) } /// Attempts to commit unsaved changes to registered objects in the context. /// /// - Parameter wait: If `true`, saves synchronously. If `false`, saves asynchronously. /// - Parameter completion: The closure to be executed when the save operation completes. private func _save(wait: Bool, completion: ((SaveResult) -> Void)? = nil) { let block = { guard self.hasChanges else { return } do { try self.save() completion?(.success(self)) } catch { completion?(.failure(error)) } } wait ? self.performAndWait(block) : self.perform(block) } }
d525844869adbd683054cb91e83633ce
36.171875
100
0.668348
false
false
false
false
benbahrenburg/PDFUtilities
refs/heads/master
PDFUtilities/Classes/PDFDocumentPasswordInfo.swift
mit
1
// // PDFUtilities - Tools for working with PDFs // PDFDocumentPasswordInfo.swift // // Created by Ben Bahrenburg // Copyright © 2016 bencoding.com. All rights reserved. // import Foundation /** PDF Password Struct, used to unlock or add a password to a PDF Provides the ability to set the User and/or Owner Passwords If you init using just a single password the User password will be used. */ public struct PDFDocumentPasswordInfo { /// User Password (optional) var userPassword: String? = nil /// Owner Password (optional) var ownerPassword: String? = nil /** Creates a new instance of the PDFDocumentPasswordInfo object - Parameter userPassword: The User password - Parameter ownerPassword: The Owner password */ public init(userPassword: String, ownerPassword: String) { self.userPassword = userPassword self.ownerPassword = ownerPassword } /** Creates a new instance of the PDFDocumentPasswordInfo object - Parameter password: The password provided will be used as the User Password */ public init(userPassword: String) { self.userPassword = userPassword } /** Creates a new instance of the PDFDocumentPasswordInfo object - Parameter password: The password provided will be used as the User Password */ public init(ownerPassword: String) { self.ownerPassword = ownerPassword } /** The toInfo method is used to create meta data for unlocking or locking pdfs. - Returns: An Array of items used when locking or unlocking PDFs. */ func toInfo() -> [AnyHashable : Any] { var info: [AnyHashable : Any] = [:] if let userPassword = self.userPassword { info[String(kCGPDFContextUserPassword)] = userPassword as AnyObject? } if let ownerPassword = self.ownerPassword { info[String(kCGPDFContextOwnerPassword)] = ownerPassword as AnyObject? } return info } }
6c99565e0e955ba58f8c4dab7992437e
26.64
82
0.654607
false
false
false
false
debugsquad/metalic
refs/heads/master
metalic/View/Home/VHomeMenu.swift
mit
1
import UIKit class VHomeMenu:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { weak var controller:CHome! weak var collectionView:UICollectionView! weak var selectedItem:MFiltersItem? let model:MFilters private let kCellWidth:CGFloat = 90 private let kMarginHorizontal:CGFloat = 10 private let kAfterSelect:TimeInterval = 0.1 init(controller:CHome) { model = MFilters() super.init(frame:CGRect.zero) self.controller = controller clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false let flow:UICollectionViewFlowLayout = UICollectionViewFlowLayout() flow.headerReferenceSize = CGSize.zero flow.footerReferenceSize = CGSize.zero flow.minimumInteritemSpacing = 0 flow.minimumLineSpacing = 0 flow.sectionInset = UIEdgeInsets( top:0, left:kMarginHorizontal, bottom:0, right:kMarginHorizontal) flow.scrollDirection = UICollectionViewScrollDirection.horizontal let collectionView:UICollectionView = UICollectionView(frame:CGRect.zero, collectionViewLayout:flow) collectionView.clipsToBounds = true collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.clear collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.alwaysBounceHorizontal = true collectionView.delegate = self collectionView.dataSource = self collectionView.register( VHomeMenuCell.self, forCellWithReuseIdentifier: VHomeMenuCell.reusableIdentifier) self.collectionView = collectionView addSubview(collectionView) let views:[String:UIView] = [ "collectionView":collectionView] let metrics:[String:CGFloat] = [:] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[collectionView]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[collectionView]-0-|", options:[], metrics:metrics, views:views)) NotificationCenter.default.addObserver( self, selector:#selector(notifiedFiltersLoaded(sender:)), name:Notification.filtersLoaded, object:nil) } required init?(coder:NSCoder) { fatalError() } deinit { NotificationCenter.default.removeObserver(self) } //MARK: notified func notifiedFiltersLoaded(sender notification:Notification) { DispatchQueue.main.async { [weak self] in self?.filtersLoaded() } } //MARK: private private func filtersLoaded() { collectionView.reloadData() if model.items.count > 0 { DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + kAfterSelect) { [weak self] in let index:IndexPath = IndexPath(item:0, section:0) self?.collectionView.selectItem( at:index, animated:false, scrollPosition:UICollectionViewScrollPosition()) self?.selectItemAtIndex(index:index) } } } private func modelAtIndex(index:IndexPath) -> MFiltersItem { let item:MFiltersItem = model.items[index.item] return item } private func selectItemAtIndex(index:IndexPath) { let item:MFiltersItem = modelAtIndex(index:index) if selectedItem !== item { selectedItem = item controller.updateFilter() } } //MARK: collection delegate func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { let height:CGFloat = collectionView.bounds.maxY let size:CGSize = CGSize(width:kCellWidth, height:height) return size } func numberOfSections(in collectionView:UICollectionView) -> Int { return 1 } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { let count:Int = model.items.count return count } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MFiltersItem = modelAtIndex(index:indexPath) let cell:VHomeMenuCell = collectionView.dequeueReusableCell( withReuseIdentifier: VHomeMenuCell.reusableIdentifier, for:indexPath) as! VHomeMenuCell cell.config(model:item) return cell } func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) { collectionView.scrollToItem( at:indexPath, at:UICollectionViewScrollPosition.centeredHorizontally, animated:true) selectItemAtIndex(index:indexPath) } }
cef42deaa1fadadba3cfd636041bb6c1
30.292135
156
0.623519
false
false
false
false
ParadropLabs/riffle-swift
refs/heads/master
Pod/Classes/ConverterExtensions.swift
mit
1
// // ConverterExtensions.swift // Pods // // Created by Mickey Barboi on 10/27/15. // // Extensions for cumin classes that implement conversions between serialized forms and method signature forms. import Foundation public protocol Cuminicable { static func convert(object: AnyObject) -> Cuminicable? } public typealias CN = Cuminicable extension Int: Cuminicable { public static func convert(object: AnyObject) -> Cuminicable? { if let x = object as? Int { return x } if let x = object as? String { return Int(x) } return nil } } extension String: Cuminicable { public static func convert(object: AnyObject) -> Cuminicable? { if let x = object as? String { return x } if let x = object as? Int { return String(x) } return nil } } extension Double: Cuminicable { public static func convert(object: AnyObject) -> Cuminicable? { if let x = object as? Double { return x } if let x = object as? Int { return Double(x) } return nil } } extension Float: Cuminicable { public static func convert(object: AnyObject) -> Cuminicable? { if let x = object as? Float { return x } if let x = object as? Int { return Float(x) } return nil } } extension Bool: Cuminicable { public static func convert(object: AnyObject) -> Cuminicable? { if let x = object as? Bool { return x } if let x = object as? Int { return Bool(x) } return nil } }
55e5f9f5d9dcc1ccf7564e5a1e60707d
19.813953
112
0.532402
false
false
false
false
WestlakeAPC/Shoot-Out
refs/heads/master
Shoot Out/MPCHandler.swift
apache-2.0
1
// // MPCHandler.swift // BluetoothTester // // Created by Joseph Jin on 7/5/17. // Copyright © 2017 Westlake APC. All rights reserved. // import UIKit import MultipeerConnectivity class MPCHandler: NSObject, MCSessionDelegate { var peerID: MCPeerID! var session: MCSession! var browser: MCBrowserViewController! var advertiser: MCAdvertiserAssistant? = nil func setupPeerWithDisplayName(displayName:String) { peerID = MCPeerID(displayName: displayName) } func setupSession() { session = MCSession(peer: peerID) session.delegate = self } func setupBrowser() { browser = MCBrowserViewController(serviceType: "my-game", session: session) browser.maximumNumberOfPeers = 2 } func adertiseSelf(advertise:Bool) { if advertise { advertiser = MCAdvertiserAssistant(serviceType: "my-game", discoveryInfo: nil, session: session) advertiser!.start() } else { advertiser?.stop() advertiser = nil } } func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { let userInfo = ["peerID": peerID, "state": state] as [String : Any] DispatchQueue.main.async { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil, userInfo: userInfo) } } func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { let userInfo = ["data": data, "peerID": peerID] as [String : Any] DispatchQueue.main.async { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MPC_DidReceiveDataNotification"), object: nil, userInfo: userInfo) } } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) { } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { } }
160c454986ccb6e897ab25511b5832e7
32.394737
168
0.606383
false
false
false
false
rchatham/SwiftyTypeForm
refs/heads/master
SwiftyTypeForm/FormData.swift
mit
1
// // FormData.swift // HermesTranslator // // Created by Reid Chatham on 2/19/17. // Copyright © 2017 Hermes Messenger LLC. All rights reserved. // import UIKit import PhoneNumberKit public enum FormDataType { case text case image(request: (@escaping (UIImage?)->Void)->Void) case phone } public struct FormData { public let type: FormDataType public var data: Any? public init(type: FormDataType, data: Any?) { self.type = type; self.data = data } } extension FormData { public init(text: String) { self.type = .text; self.data = text } public init(image: UIImage, request: @escaping (@escaping(UIImage?)->Void)->Void) { self.type = .image(request: request); self.data = image } public init(phone: PhoneNumber) { self.type = .phone; self.data = phone } } public protocol FormType { var dataType: FormDataType { get } weak var inputField: UIView! { get set } func getInput() -> FormData func configure(for data: FormData) } extension FormDataType: Equatable { public static func ==(lhs: FormDataType, rhs: FormDataType) -> Bool { switch (lhs, rhs) { case (.text, .text): return true case (.phone, .phone): return true case (.image, .image): return true default: return false } } } extension FormData: Equatable { public static func ==(lhs: FormData, rhs: FormData) -> Bool { guard lhs.type == rhs.type else { return false } switch (lhs.type, lhs.data, rhs.data) { case (.text, let ld, let rd): return (ld as? String) == (rd as? String) case (.phone, let ld, let rd): return (ld as? String) == (rd as? String) case (.image, let ld, let rd): return (ld as? UIImage) == (rd as? UIImage) } } }
8a301e8a2d4baf679cc83314398f9793
24.75
87
0.600863
false
false
false
false
Raizlabs/BonMot
refs/heads/master
Sources/FontFeatures.swift
mit
1
// // FontFeatures.swift // BonMot // // Created by Brian King on 8/31/16. // Copyright © 2016 Rightpoint. All rights reserved. // #if os(OSX) import AppKit #else import UIKit #endif // This is not supported on watchOS #if os(iOS) || os(tvOS) || os(OSX) /// Protocol to provide values to be used by `UIFontFeatureTypeIdentifierKey` /// and `UIFontFeatureSelectorIdentifierKey`. You can typically find these /// values in CoreText.SFNTLayoutTypes. public protocol FontFeatureProvider { func featureSettings() -> [(type: Int, selector: Int)] } extension BONFont { /// Create a new font and attempt to enable the specified font features. /// The returned font will have all features enabled that it supports. /// - parameter withFeatures: the features to attempt to enable on the /// font. /// - returns: a new font with the specified features enabled. public func font(withFeatures featureProviders: [FontFeatureProvider]) -> BONFont { guard featureProviders.count > 0 else { return self } let newFeatures = featureProviders.flatMap { $0.featureAttributes() } guard newFeatures.count > 0 else { return self } var fontAttributes = fontDescriptor.fontAttributes var features = fontAttributes[BONFontDescriptorFeatureSettingsAttribute] as? [[BONFontDescriptor.FeatureKey: Any]] ?? [] features.append(contentsOf: newFeatures) fontAttributes[BONFontDescriptorFeatureSettingsAttribute] = features let descriptor = BONFontDescriptor(fontAttributes: fontAttributes) #if os(OSX) return BONFont(descriptor: descriptor, size: pointSize)! #else return BONFont(descriptor: descriptor, size: pointSize) #endif } } /// A feature provider for changing the number case, also known as "figure /// style". public enum NumberCase: FontFeatureProvider { /// Uppercase numbers, also known as "lining figures", are the same height /// as uppercase letters, and they do not extend below the baseline. case upper /// Lowercase numbers, also known as "oldstyle figures", are similar in /// size and visual weight to lowercase letters, allowing them to /// blend in better in a block of text. They may have descenders /// which drop below the typographic baseline. case lower public func featureSettings() -> [(type: Int, selector: Int)] { switch self { case .upper: return [(type: kNumberCaseType, selector: kUpperCaseNumbersSelector)] case .lower: return [(type: kNumberCaseType, selector: kLowerCaseNumbersSelector)] } } } /// A feature provider for changing the number spacing, also known as /// "figure spacing". public enum NumberSpacing: FontFeatureProvider { /// Monospaced numbers, also known as "tabular figures", each take up /// the same amount of horizontal space, meaning that different numbers /// will line up when arranged in columns. case monospaced /// Proportionally spaced numbers, also known as "proportional figures", /// are of variable width. This makes them look better in most cases, /// but they should be avoided when numbers need to line up in columns. case proportional public func featureSettings() -> [(type: Int, selector: Int)] { switch self { case .monospaced: return [(type: kNumberSpacingType, selector: kMonospacedNumbersSelector)] case .proportional: return [(type: kNumberSpacingType, selector: kProportionalNumbersSelector)] } } } /// A feature provider for displaying a fraction. public enum Fractions: FontFeatureProvider { /// No fraction formatting. case disabled /// Diagonal Fractions, when written on paper, are written on one line /// with the numerator diagonally above and to the left of the /// denominator, with the slash ("/") between them. case diagonal /// Vertical Fractions, when written on paper, are written on one line /// with the numerator directly above the /// denominator, with a line lying horizontally between them. case vertical public func featureSettings() -> [(type: Int, selector: Int)] { switch self { case .disabled: return [(type: kFractionsType, selector: kNoFractionsSelector)] case .diagonal: return [(type: kFractionsType, selector: kDiagonalFractionsSelector)] case .vertical: return [(type: kFractionsType, selector: kVerticalFractionsSelector)] } } } /// A feature provider for changing the vertical position of characters /// using predefined styles in the font, such as superscript and subscript. public enum VerticalPosition: FontFeatureProvider { /// No vertical position adjustment is applied. case normal /// Superscript (superior) glyph variants are used, as in footnotes¹. case superscript /// Subscript (inferior) glyph variants are used: vₑ. case `subscript` /// Ordinal glyph variants are used, as in the common typesetting of 4th. case ordinals /// Scientific inferior glyph variants are used: H₂O case scientificInferiors public func featureSettings() -> [(type: Int, selector: Int)] { let selector: Int switch self { case .normal: selector = kNormalPositionSelector case .superscript: selector = kSuperiorsSelector case .`subscript`: selector = kInferiorsSelector case .ordinals: selector = kOrdinalsSelector case .scientificInferiors: selector = kScientificInferiorsSelector } return [(type: kVerticalPositionType, selector: selector)] } } /// A feature provider for changing small caps behavior. /// - Note: `fromUppercase` and `fromLowercase` can be combined: they are not /// mutually exclusive. public enum SmallCaps: FontFeatureProvider { /// No small caps are used. case disabled /// Uppercase letters in the source string are replaced with small caps. /// Lowercase letters remain unmodified. case fromUppercase /// Lowercase letters in the source string are replaced with small caps. /// Uppercase letters remain unmodified. case fromLowercase public func featureSettings() -> [(type: Int, selector: Int)] { switch self { case .disabled: return [ (type: kLowerCaseType, selector: kDefaultLowerCaseSelector), (type: kUpperCaseType, selector: kDefaultUpperCaseSelector), ] case .fromUppercase: return [(type: kUpperCaseType, selector: kUpperCaseSmallCapsSelector)] case .fromLowercase: return [(type: kLowerCaseType, selector: kLowerCaseSmallCapsSelector)] } } } extension FontFeatureProvider { /// - returns: an array of dictionaries, each representing one feature /// for the attributes key in the font attributes dictionary. func featureAttributes() -> [[BONFontDescriptor.FeatureKey: Any]] { let featureSettings = self.featureSettings() return featureSettings.map { [ BONFontFeatureTypeIdentifierKey: $0.type, BONFontFeatureSelectorIdentifierKey: $0.selector, ] } } } #endif
ee3d31eb505f875ed90a3b983c889495
35.663636
132
0.618522
false
false
false
false
paterik/udacity-ios-silly-song
refs/heads/master
SillySong/UIColor.swift
mit
1
// // UIColor.swift // SillySong // // Created by Patrick Paechnatz on 06.04.17. // Copyright © 2017 Patrick Paechnatz. All rights reserved. // import UIKit extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex: Int) { self.init(red: (netHex >> 16) & 0xff, green: (netHex >> 8) & 0xff, blue: netHex & 0xff) } }
37727de0eccc160aa7585e2549b9b618
27.461538
116
0.575676
false
false
false
false
lucascerro/ratios
refs/heads/master
ratios/ratios/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // ratios // // Created by Lucas Cerro on 8/21/15. // Copyright (c) 2015 Coup. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "br.com.coup.ratios" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("ratios", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("ratios.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
e22bb12607c15a1652e3ac7f443b84ca
54.018018
290
0.71459
false
false
false
false
edragoev1/pdfjet
refs/heads/master
Sources/Example_06/main.swift
mit
1
import Foundation import PDFjet /** * Example_06.swift * We will draw the American flag using Box, Line and Point objects. */ public class Example_06 { public init() { if let stream = OutputStream(toFileAtPath: "Example_06.pdf", append: false) { let pdf = PDF(stream) let font = Font(pdf, CoreFont.HELVETICA); let page = Page(pdf, Letter.PORTRAIT) let flag = Box() flag.setLocation(100.0, 100.0) flag.setSize(190.0, 100.0) flag.setColor(Color.white) flag.drawOn(page) let sw: Float = 7.69 // stripe width let stripe = Line(0.0, sw/2, 190.0, sw/2) stripe.setWidth(sw) stripe.setColor(Color.oldgloryred) for row in 0..<7 { stripe.placeIn(flag, 0.0, Float(row) * 2.0 * sw) stripe.drawOn(page) } let union = Box() union.setSize(76.0, 53.85) union.setColor(Color.oldgloryblue) union.setFillShape(true) union.placeIn(flag, 0.0, 0.0) union.drawOn(page) let h_si: Float = 12.6 // horizontal star interval let v_si: Float = 10.8 // vertical star interval let star = Point(h_si/2, v_si/2) star.setShape(Point.STAR) star.setRadius(3.0) star.setColor(Color.white) star.setFillShape(true) for row in 0..<6 { for col in 0..<5 { star.placeIn(union, Float(row) * h_si, Float(col) * v_si) star.drawOn(page) } } star.setLocation(h_si, v_si) for row in 0..<5 { for col in 0..<4 { star.placeIn(union, Float(row) * h_si, Float(col) * v_si) star.drawOn(page) } } font.setSize(Float(18)) var text = TextLine(font, "WAVE AWAY") text.setLocation(Float(100), Float(250)) text.drawOn(page) font.setKernPairs(true); text = TextLine(font, "WAVE AWAY") text.setLocation(Float(100), Float(270)) text.drawOn(page) pdf.complete() } } } // End of Example_06.swift let time0 = Int64(Date().timeIntervalSince1970 * 1000) _ = Example_06() let time1 = Int64(Date().timeIntervalSince1970 * 1000) print("Example_06 => \(time1 - time0)")
218ae78146b0fc21345909929782d8f6
28.776471
85
0.502173
false
false
false
false
WilliamHester/Breadit-iOS
refs/heads/master
Breadit/ViewControllers/NavigationDrawerViewController.swift
apache-2.0
1
// // DrawerViewController.swift // Breadit // // Created by William Hester on 4/30/16. // Copyright © 2016 William Hester. All rights reserved. // import UIKit class NavigationDrawerViewController: UIViewController, UIGestureRecognizerDelegate, UINavigationControllerDelegate, NavigationDelegate { private static let size: CGFloat = 40 var contentController: UIViewController! var drawerController: NavigationViewController! var drawer: UIView! var content: UIView! var drawerRightConstraint: NSLayoutConstraint! var contentLeftConstraint: NSLayoutConstraint! var startTranslation: CGFloat = 0 var isOpen: Bool = false { willSet { if isOpen { drawerController.stopSearching() } } didSet { animateDrawer(0.3) content.userInteractionEnabled = !isOpen } } var enabled: Bool = true var drawerWidth: CGFloat { get { return self.view.frame.width - NavigationDrawerViewController.size } } var drawerOffset: CGFloat { get { return drawerWidth / 2 } } var currentPlace: NavigationPlace = .Subreddit("") init(contentViewController: UIViewController, drawerViewController: NavigationViewController) { super.init(nibName: nil, bundle: nil) self.contentController = contentViewController self.drawerController = drawerViewController self.drawerController.delegate = self self.addChildViewController(self.contentController) self.addChildViewController(self.drawerController) if let navigationController = contentController as? UINavigationController { navigationController.delegate = self } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { uiView { v in v.addSubview(self.drawerController.view) self.drawer = self.drawerController.view.constrain { v in self.drawerRightConstraint = v.rightAnchor.constraintEqualToAnchor( self.view.leftAnchor, constant: -self.drawerOffset ) self.drawerRightConstraint.active = true v.widthAnchor.constraintEqualToAnchor(self.view.widthAnchor, constant: -NavigationDrawerViewController.size).active = true v.topAnchor.constraintEqualToAnchor(self.view.topAnchor).active = true v.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor).active = true } self.drawer.frame = self.makeDrawerFrame() v.addSubview(self.contentController.view) self.content = self.contentController.view.constrain { v in self.contentLeftConstraint = v.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor) self.contentLeftConstraint.active = true v.widthAnchor.constraintEqualToAnchor(self.view.widthAnchor).active = true v.topAnchor.constraintEqualToAnchor(self.view.topAnchor).active = true v.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor).active = true } // Make the shadow self.content.add { v in v.layer.shadowPath = UIBezierPath(rect: v.bounds).CGPath v.layer.shadowRadius = 4 v.layer.shadowOffset = CGSizeMake(0, 5) v.layer.shadowColor = UIColor.blackColor().CGColor v.layer.shadowOpacity = 0.5 } } let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(NavigationDrawerViewController.moveDrawer(_:))) gestureRecognizer.cancelsTouchesInView = true gestureRecognizer.delegate = self view.addGestureRecognizer(gestureRecognizer) let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(NavigationDrawerViewController.drawerSwiped(_:))) swipeRecognizer.delegate = self view.addGestureRecognizer(swipeRecognizer) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(NavigationDrawerViewController.drawerTapped(_:))) tapGestureRecognizer.delegate = self tapGestureRecognizer.cancelsTouchesInView = false view.addGestureRecognizer(tapGestureRecognizer) setScrollsToTop(view.subviews[0], set: false) setScrollsToTop(view.subviews[1], set: true) } func setScrollsToTop(view: UIView, set: Bool) { if let scrollView = view as? UIScrollView { scrollView.scrollsToTop = set } for subView in view.subviews { setScrollsToTop(subView, set: set) } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } private func makeDrawerFrame() -> CGRect { return CGRect(x: 0, y: 0, width: drawerWidth, height: view.frame.height) } func toggleDrawer(obj: AnyObject) { isOpen = !isOpen } func animateDrawer(duration: Double) { let end = drawerWidth UIView.animateWithDuration(duration) { if self.isOpen { self.drawerRightConstraint.constant = end self.contentLeftConstraint.constant = end } else { self.drawerRightConstraint.constant = self.drawerOffset self.contentLeftConstraint.constant = 0 } self.view.layoutIfNeeded() } } // MARK: - UIGestureRecognizerDelegate func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { return enabled && gestureRecognizer.locationInView(view).x < NavigationDrawerViewController.size + content.frame.origin.x } // MARK: - TapGestureRecognizer func drawerTapped(gestureRecognizer: UITapGestureRecognizer) { let location = gestureRecognizer.locationInView(view) if isOpen && location.x > drawerWidth { isOpen = false } } // MARK: - PanGestureRecognizer func moveDrawer(gestureRecognizer: UIPanGestureRecognizer) { switch (gestureRecognizer.state) { case .Began: startTranslation = contentLeftConstraint.constant case .Changed: moveDrawerBy(gestureRecognizer.translationInView(view).x) case .Ended: animateToEnd(gestureRecognizer.translationInView(view).x) default: break } } func moveDrawerBy(translation: CGFloat) { let trans = min(max(startTranslation + translation, 0), view.frame.width) drawerRightConstraint.constant = min((trans / 2 + drawerOffset), drawerWidth) contentLeftConstraint.constant = trans } func animateToEnd(translation: CGFloat) { let trans = startTranslation + translation let openPercent = trans / (view.frame.width - NavigationDrawerViewController.size) isOpen = openPercent > 0.5 } // MARK: - SwipeGestureRecognizer func drawerSwiped(gestureRecognizer: UISwipeGestureRecognizer) { switch (gestureRecognizer.state) { case .Began: startTranslation = gestureRecognizer.locationInView(view).x case .Ended: animateSwipe(gestureRecognizer.direction) default: break } } func animateSwipe(direction: UISwipeGestureRecognizerDirection) { isOpen = direction == .Right } // MARK: - UINavigationControllerDelegate func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) { enabled = navigationController.viewControllers[0] == viewController } // MARK: - UINavigationControllerDelegate func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) { if navigationController.viewControllers.count > 1 { return } let menuButton = UIBarButtonItem(title: "Menu", style: .Plain, target: self, action: #selector(NavigationDrawerViewController.toggleDrawer(_:))) viewController.navigationItem.setLeftBarButtonItem(menuButton, animated: false) } // MARK: - NavigationDelegate func didNavigateTo(place: NavigationPlace) { switch place { case .Search(let query): var vc: ListingViewController if let submissionVC = contentController.childViewControllers[0] as? ListingViewController { vc = submissionVC } else { vc = ListingViewController() contentController = UINavigationController(rootViewController: vc) } vc.listingStore = SubmissionStore(searchQuery: query) case .Subreddit(let displayName): var vc: ListingViewController if let submissionVC = contentController.childViewControllers[0] as? ListingViewController { vc = submissionVC } else { vc = ListingViewController() contentController = UINavigationController(rootViewController: vc) } vc.listingStore = SubmissionStore(subredditDisplay: displayName) case .Account: break case .Friends: break case .Inbox: break case .Settings: let vc = UINavigationController(rootViewController: LoginViewController()) vc.navigationBar.barStyle = .Black vc.modalTransitionStyle = .CoverVertical presentViewController(vc, animated: true, completion: nil) case .Submit: break } isOpen = false } }
b39546168e3d4e653fccdb2a3a3607bd
35.587814
103
0.635286
false
false
false
false
yichizhang/JCTiledScrollView_Swift
refs/heads/master
JCTiledScrollView_Swift_Source/JCTiledView.swift
mit
1
// // Copyright (c) 2015-present Yichi Zhang // https://github.com/yichizhang // [email protected] // // This source code is licensed under MIT license found in the LICENSE file // in the root directory of this source tree. // Attribution can be found in the ATTRIBUTION file in the root directory // of this source tree. // import UIKit import QuartzCore @objc protocol JCTiledViewDelegate { } @objc protocol JCTiledBitmapViewDelegate: JCTiledViewDelegate { func tiledView(_ tiledView: JCTiledView, imageForRow row: Int, column: Int, scale: Int) -> UIImage } let kJCDefaultTileSize: CGFloat = 256.0 class JCTiledView: UIView { weak var delegate: JCTiledViewDelegate? var tileSize: CGSize = CGSize(width: kJCDefaultTileSize, height: kJCDefaultTileSize) { didSet { let scaledTileSize = self.tileSize.applying(CGAffineTransform(scaleX: self.contentScaleFactor, y: self.contentScaleFactor)) self.tiledLayer().tileSize = scaledTileSize } } var shouldAnnotateRect: Bool = false var numberOfZoomLevels: size_t { get { return self.tiledLayer().levelsOfDetailBias } set { self.tiledLayer().levelsOfDetailBias = newValue } } func tiledLayer() -> JCTiledLayer { return self.layer as! JCTiledLayer } override class var layerClass : AnyClass { return JCTiledLayer.self } override init(frame: CGRect) { super.init(frame: frame) let scaledTileSize = self.tileSize.applying(CGAffineTransform(scaleX: self.contentScaleFactor, y: self.contentScaleFactor)) self.tiledLayer().tileSize = scaledTileSize self.tiledLayer().levelsOfDetail = 1 self.numberOfZoomLevels = 3 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { guard let ctx = UIGraphicsGetCurrentContext() else { return } let scale = ctx.ctm.a / tiledLayer().contentsScale let col = Int(rect.minX * scale / tileSize.width) let row = Int(rect.minY * scale / tileSize.height) if let tileImage = (delegate as? JCTiledBitmapViewDelegate)?.tiledView(self, imageForRow: row, column: col, scale: Int(scale)) { tileImage.draw(in: rect) } if shouldAnnotateRect { annotateRect(rect, inContext: ctx) } } // Handy for Debug func annotateRect(_ rect: CGRect, inContext ctx: CGContext) { let scale = ctx.ctm.a / self.tiledLayer().contentsScale let lineWidth = 2.0 / scale let fontSize = 16.0 / scale UIColor.white.set() NSString.localizedStringWithFormat(" %0.0f", log2f(Float(scale))).draw( at: CGPoint(x: rect.minX, y: rect.minY), withAttributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: fontSize)] ) UIColor.red.set() ctx.setLineWidth(lineWidth) ctx.stroke(rect) } }
69b711bde8a6b2e6405496f96e80e0c7
26.654867
136
0.64096
false
false
false
false
danger/danger-swift
refs/heads/master
Sources/Danger/DangerDSL.swift
mit
1
import Foundation import OctoKit // http://danger.systems/js/reference.html // MARK: - DangerDSL public struct DSL: Decodable { /// The root danger import public let danger: DangerDSL } public struct DangerDSL: Decodable { public let git: Git public private(set) var github: GitHub! public let bitbucketCloud: BitBucketCloud! public let bitbucketServer: BitBucketServer! public let gitLab: GitLab! public let utils: DangerUtils enum CodingKeys: String, CodingKey { case git case github case bitbucketServer = "bitbucket_server" case bitbucketCloud = "bitbucket_cloud" case gitlab case settings // Used by plugin testing only // See: githubJSONWithFiles case fileMap } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) git = try container.decode(Git.self, forKey: .git) github = try container.decodeIfPresent(GitHub.self, forKey: .github) bitbucketServer = try container.decodeIfPresent(BitBucketServer.self, forKey: .bitbucketServer) bitbucketCloud = try container.decodeIfPresent(BitBucketCloud.self, forKey: .bitbucketCloud) gitLab = try container.decodeIfPresent(GitLab.self, forKey: .gitlab) let settings = try container.decode(Settings.self, forKey: .settings) // File map is used so that libraries can make tests without // doing a lot of internal hacking for danger, or weird DI in their // own code. A bit of a trade-off in complexity for Danger Swift, but I // think if it leads to more tested plugins, it's a good spot to be in. if let fileMap = try container.decodeIfPresent([String: String].self, forKey: .fileMap) { utils = DangerUtils(fileMap: fileMap) } else { utils = DangerUtils(fileMap: [:]) } // Setup the OctoKit once all other if runningOnGithub { let config: TokenConfiguration if let baseURL = settings.github.baseURL { config = TokenConfiguration(settings.github.accessToken, url: baseURL) } else { config = TokenConfiguration(settings.github.accessToken) } github.api = Octokit(config) } } } extension DangerDSL { var runningOnGithub: Bool { github != nil } var runningOnBitbucketServer: Bool { bitbucketServer != nil } var supportsSuggestions: Bool { runningOnGithub } }
7c865f2f2df99e1540a7f3a28b0fc4c4
29.517647
103
0.648034
false
true
false
false
justindarc/firefox-ios
refs/heads/master
Client/Frontend/Library/ReaderPanel.swift
mpl-2.0
1
/* 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 UIKit import SnapKit import Storage import Shared import XCGLogger private let log = Logger.browserLogger private struct ReadingListTableViewCellUX { static let RowHeight: CGFloat = 86 static let ReadIndicatorWidth: CGFloat = 12 // image width static let ReadIndicatorHeight: CGFloat = 12 // image height static let ReadIndicatorLeftOffset: CGFloat = 18 static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest static let TitleLabelTopOffset: CGFloat = 14 - 4 static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16 static let TitleLabelRightOffset: CGFloat = -40 static let HostnameLabelBottomOffset: CGFloat = 11 static let DeleteButtonTitleColor = UIColor.Photon.White100 static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) static let MarkAsReadButtonBackgroundColor = UIColor.Photon.Blue50 static let MarkAsReadButtonTitleColor = UIColor.Photon.White100 static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) // Localizable strings static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item") static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read") static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread") } private struct ReadingListPanelUX { // Welcome Screen static let WelcomeScreenTopPadding: CGFloat = 16 static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenItemWidth = 220 static let WelcomeScreenItemOffset = -20 static let WelcomeScreenCircleWidth = 40 static let WelcomeScreenCircleOffset = 20 static let WelcomeScreenCircleSpacer = 10 } class ReadingListTableViewCell: UITableViewCell, Themeable { var title: String = "Example" { didSet { titleLabel.text = title updateAccessibilityLabel() } } var url = URL(string: "http://www.example.com")! { didSet { hostnameLabel.text = simplifiedHostnameFromURL(url) updateAccessibilityLabel() } } var unread: Bool = true { didSet { readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread") titleLabel.textColor = unread ? UIColor.theme.homePanel.readingListActive : UIColor.theme.homePanel.readingListDimmed hostnameLabel.textColor = unread ? UIColor.theme.homePanel.readingListActive : UIColor.theme.homePanel.readingListDimmed updateAccessibilityLabel() } } let readStatusImageView: UIImageView! let titleLabel: UILabel! let hostnameLabel: UILabel! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { readStatusImageView = UIImageView() titleLabel = UILabel() hostnameLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor.clear separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0) layoutMargins = .zero preservesSuperviewLayoutMargins = false contentView.addSubview(readStatusImageView) readStatusImageView.contentMode = .scaleAspectFit readStatusImageView.snp.makeConstraints { (make) -> Void in make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth) make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight) make.centerY.equalTo(self.contentView) make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset) } contentView.addSubview(titleLabel) contentView.addSubview(hostnameLabel) titleLabel.numberOfLines = 2 titleLabel.snp.makeConstraints { (make) -> Void in make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset) make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset) make.trailing.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec make.bottom.lessThanOrEqualTo(hostnameLabel.snp.top).priority(1000) } hostnameLabel.numberOfLines = 1 hostnameLabel.snp.makeConstraints { (make) -> Void in make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset) make.leading.trailing.equalTo(self.titleLabel) } applyTheme() } func setupDynamicFonts() { titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont hostnameLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight } func applyTheme() { titleLabel.textColor = UIColor.theme.homePanel.readingListActive hostnameLabel.textColor = UIColor.theme.homePanel.readingListActive } override func prepareForReuse() { super.prepareForReuse() applyTheme() setupDynamicFonts() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."] fileprivate func simplifiedHostnameFromURL(_ url: URL) -> String { let hostname = url.host ?? "" for prefix in prefixesToSimplify { if hostname.hasPrefix(prefix) { return String(hostname[hostname.index(hostname.startIndex, offsetBy: prefix.count)...]) } } return hostname } fileprivate func updateAccessibilityLabel() { if let hostname = hostnameLabel.text, let title = titleLabel.text { let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.") let string = "\(title), \(unreadStatus), \(hostname)" var label: AnyObject if !unread { // mimic light gray visual dimming by "dimming" the speech by reducing pitch let lowerPitchString = NSMutableAttributedString(string: string as String) lowerPitchString.addAttribute(NSAttributedString.Key.accessibilitySpeechPitch, value: NSNumber(value: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch as Float), range: NSRange(location: 0, length: lowerPitchString.length)) label = NSAttributedString(attributedString: lowerPitchString) } else { label = string as AnyObject } // need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this // see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple // also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly... setValue(label, forKey: "accessibilityLabel") } } } class ReadingListPanel: UITableViewController, LibraryPanel { weak var libraryPanelDelegate: LibraryPanelDelegate? let profile: Profile fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(longPress)) }() fileprivate var records: [ReadingListItem]? init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) [ Notification.Name.FirefoxAccountChanged, Notification.Name.DynamicFontChanged, Notification.Name.DatabaseWasReopened ].forEach { NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: $0, object: nil) } applyTheme() } required init!(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshReadingList() } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.accessibilityIdentifier = "ReadingTable" tableView.estimatedRowHeight = ReadingListTableViewCellUX.RowHeight tableView.rowHeight = UITableView.automaticDimension tableView.cellLayoutMarginsFollowReadableWidth = false tableView.separatorInset = .zero tableView.layoutMargins = .zero tableView.register(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell") // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() tableView.dragDelegate = self } @objc func notificationReceived(_ notification: Notification) { switch notification.name { case .FirefoxAccountChanged, .DynamicFontChanged: refreshReadingList() case .DatabaseWasReopened: if let dbName = notification.object as? String, dbName == "ReadingList.db" { refreshReadingList() } default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } func refreshReadingList() { let prevNumberOfRecords = records?.count tableView.tableHeaderView = nil if let newRecords = profile.readingList.getAvailableRecords().value.successValue { records = newRecords if records?.count == 0 { tableView.isScrollEnabled = false tableView.tableHeaderView = createEmptyStateOverview() } else { if prevNumberOfRecords == 0 { tableView.isScrollEnabled = true } } self.tableView.reloadData() } } fileprivate func createEmptyStateOverview() -> UIView { let overlayView = UIView(frame: tableView.bounds) let welcomeLabel = UILabel() overlayView.addSubview(welcomeLabel) welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL") welcomeLabel.textAlignment = .center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallBold welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalToSuperview() make.top.equalToSuperview().offset(150) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth) } let readerModeLabel = UILabel() overlayView.addSubview(readerModeLabel) readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL") readerModeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight readerModeLabel.numberOfLines = 0 readerModeLabel.snp.makeConstraints { make in make.top.equalTo(welcomeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.leading.equalTo(welcomeLabel.snp.leading) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) } let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle")) overlayView.addSubview(readerModeImageView) readerModeImageView.snp.makeConstraints { make in make.centerY.equalTo(readerModeLabel) make.trailing.equalTo(welcomeLabel.snp.trailing) } let readingListLabel = UILabel() overlayView.addSubview(readingListLabel) readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL") readingListLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight readingListLabel.numberOfLines = 0 readingListLabel.snp.makeConstraints { make in make.top.equalTo(readerModeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.leading.equalTo(welcomeLabel.snp.leading) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) } let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle")) overlayView.addSubview(readingListImageView) readingListImageView.snp.makeConstraints { make in make.centerY.equalTo(readingListLabel) make.trailing.equalTo(welcomeLabel.snp.trailing) } [welcomeLabel, readerModeLabel, readingListLabel].forEach { $0.textColor = UIColor.theme.homePanel.welcomeScreenText } return overlayView } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } presentContextMenu(for: indexPath) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return records?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ReadingListTableViewCell", for: indexPath) as! ReadingListTableViewCell if let record = records?[indexPath.row] { cell.title = record.title cell.url = URL(string: record.url)! cell.unread = record.unread } return cell } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { guard let record = records?[indexPath.row] else { return [] } let delete = UITableViewRowAction(style: .default, title: ReadingListTableViewCellUX.DeleteButtonTitleText) { [weak self] action, index in self?.deleteItem(atIndex: index) } let toggleText = record.unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText let unreadToggle = UITableViewRowAction(style: .normal, title: toggleText.stringSplitWithNewline()) { [weak self] (action, index) in self?.toggleItem(atIndex: index) } unreadToggle.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor return [unreadToggle, delete] } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if let record = records?[indexPath.row], let url = URL(string: record.url), let encodedURL = url.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) { // Mark the item as read profile.readingList.updateRecord(record, unread: false) // Reading list items are closest in concept to bookmarks. let visitType = VisitType.bookmark libraryPanelDelegate?.libraryPanel(didSelectURL: encodedURL, visitType: visitType) UnifiedTelemetry.recordEvent(category: .action, method: .open, object: .readingListItem) } } fileprivate func deleteItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { UnifiedTelemetry.recordEvent(category: .action, method: .delete, object: .readingListItem, value: .readingListPanel) if profile.readingList.deleteRecord(record).value.isSuccess { records?.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) // reshow empty state if no records left if records?.count == 0 { refreshReadingList() } } } } fileprivate func toggleItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readingListItem, value: !record.unread ? .markAsUnread : .markAsRead, extras: [ "from": "reading-list-panel" ]) if let updatedRecord = profile.readingList.updateRecord(record, unread: !record.unread).value.successValue { records?[indexPath.row] = updatedRecord tableView.reloadRows(at: [indexPath], with: .automatic) } } } } extension ReadingListPanel: LibraryPanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { guard let record = records?[indexPath.row] else { return nil } return Site(url: record.url, title: record.title) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { guard var actions = getDefaultContextMenuActions(for: site, libraryPanelDelegate: libraryPanelDelegate) else { return nil } let removeAction = PhotonActionSheetItem(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { action in self.deleteItem(atIndex: indexPath) }) actions.append(removeAction) return actions } } @available(iOS 11.0, *) extension ReadingListPanel: UITableViewDragDelegate { func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { guard let site = getSiteDetails(for: indexPath), let url = URL(string: site.url), let itemProvider = NSItemProvider(contentsOf: url) else { return [] } UnifiedTelemetry.recordEvent(category: .action, method: .drag, object: .url, value: .readingListPanel) let dragItem = UIDragItem(itemProvider: itemProvider) dragItem.localObject = site return [dragItem] } func tableView(_ tableView: UITableView, dragSessionWillBegin session: UIDragSession) { presentedViewController?.dismiss(animated: true) } } extension ReadingListPanel: Themeable { func applyTheme() { tableView.separatorColor = UIColor.theme.tableView.separator view.backgroundColor = UIColor.theme.tableView.rowBackground refreshReadingList() } }
daefefebb69dcdcd7901738d5e7bb48d
43.101545
333
0.689909
false
false
false
false
DrewKiino/Pacific
refs/heads/master
Pods/Socket.IO-Client-Swift/Source/SocketTypes.swift
mit
4
// // SocketTypes.swift // Socket.IO-Client-Swift // // Created by Erik Little on 4/8/15. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public typealias AckCallback = ([AnyObject]) -> Void public typealias NormalCallback = ([AnyObject], SocketAckEmitter) -> Void public typealias OnAckCallback = (timeoutAfter: UInt64, callback: AckCallback) -> Void typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData]) typealias ProbeWaitQueue = [Probe] enum Either<E, V> { case Left(E) case Right(V) }
fdd590931a8804ff3dd1ffaf6f5476af
41.945946
86
0.746381
false
false
false
false
galacemiguel/bluehacks2017
refs/heads/master
Project Civ-1/Project Civ/VoteSectionController.swift
mit
1
// // VoteSectionController.swift // Project Civ // // Created by Carlos Arcenas on 2/19/17. // Copyright © 2017 Rogue Three. All rights reserved. // import UIKit import IGListKit class VoteSectionController: IGListSectionController { var project: Project! override init() { super.init() inset = UIEdgeInsets(top: 0, left: 0, bottom: 15, right: 15) } } extension VoteSectionController: IGListSectionType { func numberOfItems() -> Int { return 1 } func sizeForItem(at index: Int) -> CGSize { guard let context = collectionContext, let _ = project else { return .zero } let width = context.containerSize.width return CGSize(width: width, height: 125) } func cellForItem(at index: Int) -> UICollectionViewCell { let cell = collectionContext!.dequeueReusableCell(of: VoteCell.self, for: self, at: index) as! VoteCell cell.upvoteButton.titleLabel?.text = "+" + String(describing: project.upvotes) cell.downvoteButton.titleLabel?.text = "-" + String(describing: project.downvotes) return cell } func didUpdate(to object: Any) { project = object as? Project } func didSelectItem(at index: Int) { // fill this in } }
83da05b04fef26f1167f19bbd66aa9b3
27.021739
111
0.641583
false
false
false
false
yossan4343434/TK_15
refs/heads/master
src/app/Visy/Visy/VSMovie.swift
mit
1
// // VSMovie.swift // Visy // // Created by Yoshiyuki Kuga on 2015/11/28. // Copyright © 2015年 TK_15. All rights reserved. // import UIKit class VSMovie: NSObject { var youtubeId: String var title: String var thumbnail: UIImage var emotion: Dictionary<String, [NSTimeInterval]> var person: Dictionary<String, [NSTimeInterval]> init(youtubeId: String) { self.youtubeId = youtubeId let urlString = "https://i.ytimg.com/vi/" + youtubeId + "/mqdefault.jpg" let srcUrl = NSURL(string: urlString) let data = NSData(contentsOfURL: srcUrl!) self.thumbnail = UIImage(data: data!)! // TODO: youtubeIdをサーバーに渡して個別のtitle, scene, personを取得するように実装 self.title = "ラグビー日本vs南アフリカ" self.emotion = [ "exciting": [], // ダミー "laughing": [210, 300, 320], // ダミー ] self.person = [ // "goroumaru"の出現時間に関するデータは"src/python/extract_goromaru_deeplearning_face.py"の出力結果を用いています。 "goroumaru": [386, 641, 866, 3041, 3551, 3891, 4421, 4831], "yamada": [44, 55, 66], // ダミー "tanaka": [4, 15, 26] //ダミー ] } }
259ec922490ea7126548013da3554aae
26.302326
102
0.588586
false
false
false
false
github641/testRepo
refs/heads/master
SwiftProgrammingLanguage/SwiftProgrammingLanguage/Protocols.swift
mit
1
// // ViewController.swift // SwiftProgrammingLanguage // // Created by admin on 2017/10/18. // Copyright © 2017年 alldk. All rights reserved. // /*lzy171018注: 这个类,对应的是 The Swift Programming Language第二章(Language Guide)的内容: 协议(Protocols) 3.0.1,shanks,2016-11-13 本页包含内容: 协议语法 属性要求 方法要求(Method Requirements) Mutating 方法要求 构造器要求 协议作为类型 委托(代理)模式 通过扩展添加协议一致性 通过扩展遵循协议 协议类型的集合 协议的继承 类类型专属协议 协议合成 检查协议一致性 可选的协议要求 协议扩展 协议 定义了一个蓝图,规定了用来实现某一特定任务或者功能的方法、属性,以及其他需要的东西。类、结构体或枚举都可以遵循协议,并为协议定义的这些要求提供具体实现。某个类型能够满足某个协议的要求,就可以说该类型遵循这个协议。 除了遵循协议的类型必须实现的要求外,还可以对协议进行扩展,通过扩展来实现一部分要求或者实现一些附加功能,这样遵循协议的类型就能够使用这些功能。 */ import UIKit class Protocols: UIViewController { override func viewDidLoad() { super.viewDidLoad() // MARK: - 协议语法 /*lzy171018注: 协议的定义方式与类、结构体和枚举的定义非常相似: protocol SomeProtocol { // 这里是协议的定义部分 } 要让自定义类型遵循某个协议,在定义类型时,需要在类型名称后加上协议名称,中间以冒号(:)分隔。遵循多个协议时,各协议之间用逗号(,)分隔: */ struct SomeStructure: FirstProtocol, AnotherProtocol { // 这里是结构体的定义部分 } // 拥有父类的类在遵循协议时,应该将父类名放在协议名之前,以逗号分隔: class SomeClass: UIView, FirstProtocol, AnotherProtocol { // 这里是类的定义部分 } // MARK: - 属性要求 /*lzy171018注: 协议可以要求遵循协议的类型 提供 特定名称和类型的 实例属性或类型属性。协议不指定属性是存储型属性还是计算型属性,它只指定属性的名称和类型。此外,协议还指定属性是可读的还是可读可写的。 如果协议要求属性是可读可写的,那么该属性不能是常量属性或只读的计算型属性。如果协议只要求属性是可读的,那么该属性不仅可以是可读的,如果代码需要的话,还可以是可写的。 协议总是用 var 关键字来声明变量属性,在类型声明后加上 { set get } 来表示属性是可读可写的,可读属性则用 { get } 来表示: protocol SomeProtocol { var mustBeSettable: Int { get set } var doesNotNeedToBeSettable: Int { get } } 在协议中定义 类型属性时,总是使用 static 关键字作为前缀。当类类型遵循协议时,除了 static 关键字,还可以使用 class 关键字来声明类型属性: protocol AnotherProtocol { static var someTypeProperty: Int { get set } } FullyNamed 协议除了要求遵循协议的类型提供 fullName 属性外,并没有其他特别的要求。这个协议表示,任何遵循 FullyNamed 的类型,都必须有一个可读的 String 类型的实例属性 fullName。 下面是一个遵循 FullyNamed 协议的简单结构体: */ struct Person: FullyNamed { var fullName: String } let john = Person(fullName: "John Appleseed") // john.fullName 为 "John Appleseed" /* 这个例子中定义了一个叫做 Person 的结构体,用来表示一个具有名字的人。从第一行代码可以看出,它遵循了 FullyNamed 协议。 Person 结构体的每一个实例都有一个 String 类型的存储型属性 fullName。这正好满足了 FullyNamed 协议的要求,也就意味着 Person 结构体正确地符合了协议。(如果协议要求未被完全满足,在编译时会报错。) 下面是一个更为复杂的类,它适配并遵循了 FullyNamed 协议: */ class Starship: FullyNamed { var prefix: String? var name: String init(name: String, prefix: String? = nil) { self.name = name self.prefix = prefix } var fullName: String { return (prefix != nil ? prefix! + " " : "") + name } } var ncc1701 = Starship(name: "Enterprise", prefix: "USS") // ncc1701.fullName 是 "USS Enterprise" /* Starship 类把 fullName 属性实现为只读的计算型属性。每一个 Starship 类的实例都有一个名为 name 的非可选属性和一个名为 prefix 的可选属性。 当 prefix 存在时,计算型属性 fullName 会将 prefix 插入到 name 之前,从而为星际飞船构建一个全名。 */ // MARK: - 方法要求 /*lzy171018注: 协议可以要求遵循协议的类型实现某些指定的实例方法或类方法。这些方法作为协议的一部分,像普通方法一样放在协议的定义中,但是不需要大括号和方法体。可以在协议中定义具有可变参数的方法,和普通方法的定义方式相同。但是,不支持为协议中的方法的参数提供默认值。 正如属性要求中所述,在协议中定义类方法的时候,总是使用 static 关键字作为前缀。当类类型遵循协议时,除了 static 关键字,还可以使用 class 关键字作为前缀: protocol SomeProtocol { static func someTypeMethod() } RandomNumberGenerator 协议要求遵循协议的类型必须拥有一个名为 random, 返回值类型为 Double 的实例方法。尽管这里并未指明,但是我们假设返回值在 [0.0,1.0) 区间内。 RandomNumberGenerator 协议并不关心每一个随机数是怎样生成的,它只要求必须提供一个随机数生成器。 如下所示,下边是一个遵循并符合 RandomNumberGenerator 协议的类。该类实现了一个叫做 线性同余生成器(linear congruential generator) 的伪随机数算法。 */ let generator = LinearCongruentialGenerator() print("Here's a random number: \(generator.random())") // 打印 “Here's a random number: 0.37464991998171” print("And another one: \(generator.random())") // 打印 “And another one: 0.729023776863283” // MARK: - Mutating 方法要求 /*lzy171018注: 有时需要在方法中改变方法所属的实例。例如,在值类型(即结构体和枚举)的实例方法中,将 mutating 关键字作为方法的前缀,写在 func 关键字之前,表示可以在该方法中修改它所属的实例以及实例的任意属性的值。这一过程在在实例方法中修改值类型章节中有详细描述。 如果你在协议中定义了一个实例方法,该方法会改变遵循该协议的类型的实例,那么在定义协议时需要在方法前加 mutating 关键字。这使得结构体和枚举能够遵循此协议并满足此方法要求。 注意 实现协议中的 mutating 方法时,若是类类型,则不用写 mutating 关键字。而对于结构体和枚举,则必须写 mutating 关键字。 如下所示,Togglable 协议只要求实现一个名为 toggle 的实例方法。根据名称的暗示,toggle() 方法将改变实例属性,从而切换遵循该协议类型的实例的状态。 当使用枚举或结构体来实现 Togglable 协议时,需要提供一个带有 mutating 前缀的 toggle() 方法。 下面定义了一个名为 OnOffSwitch 的枚举。这个枚举在两种状态之间进行切换,用枚举成员 On 和 Off 表示。枚举的 toggle() 方法被标记为 mutating,以满足 Togglable 协议的要求: */ enum OnOffSwitch: Togglable { case off, on mutating func toggle() { switch self { case .off: self = .on case .on: self = .off } } } var lightSwitch = OnOffSwitch.off lightSwitch.toggle() // lightSwitch 现在的值为 .On // MARK: - 构造器要求 /*lzy171019注: 协议可以要求遵循协议的类型实现指定的构造器。你可以像编写普通构造器那样,在协议的定义里写下构造器的声明,但不需要写花括号和构造器的实体: protocol SomeProtocol { init(someParameter: Int) } */ // MARK:====构造器要求在类中的实现==== /*lzy171019注: 你可以在遵循协议的类中实现构造器,无论是作为指定构造器,还是作为便利构造器。无论哪种情况,你都必须为构造器实现标上 required 修饰符: class SomeClass: SomeProtocol { required init(someParameter: Int) { // 这里是构造器的实现部分 } } 使用 required 修饰符可以确保所有子类也必须提供此构造器实现,从而也能符合协议。 关于 required 构造器的更多内容,请参考必要构造器。 注意 如果类已经被标记为 final,那么不需要在协议构造器的实现中使用 required 修饰符,因为 final 类不能有子类。关于 final 修饰符的更多内容,请参见防止重写。 如果一个子类重写了父类的指定构造器,并且该构造器满足了某个协议的要求,那么该构造器的实现需要同时标注 required 和 override 修饰符: protocol SomeProtocol { init() } class SomeSuperClass { init() { // 这里是构造器的实现部分 } } class SomeSubClass: SomeSuperClass, SomeProtocol { // 因为遵循协议,需要加上 required // 因为继承自父类,需要加上 override required override init() { // 这里是构造器的实现部分 } } */ // MARK:====可失败构造器要求==== /*lzy171019注: 协议还可以为遵循协议的类型定义可失败构造器要求,详见可失败构造器。 遵循协议的类型可以通过可失败构造器(init?)或非可失败构造器(init)来满足协议中定义的可失败构造器要求。协议中定义的非可失败构造器要求可以通过非可失败构造器(init)或隐式解包可失败构造器(init!)来满足。 */ // MARK: - 协议作为类型 /*lzy171019注: 尽管协议本身并未实现任何功能,但是协议可以被当做一个成熟的类型来使用。 协议可以像其他普通类型一样使用,使用场景如下: 作为函数、方法或构造器中的参数类型或返回值类型 作为常量、变量或属性的类型 作为数组、字典或其他容器中的元素类型 注意 协议是一种类型,因此协议类型的名称应与其他类型(例如 Int,Double,String)的写法相同,使用大写字母开头的驼峰式写法,例如(FullyNamed 和 RandomNumberGenerator)。 */ /*lzy171019注: 例子中定义了一个 Dice 类,用来代表桌游中拥有 N 个面的骰子。Dice 的实例含有 sides 和 generator 两个属性,前者是整型,用来表示骰子有几个面,后者为骰子提供一个随机数生成器,从而生成随机点数。 generator 属性的类型为 RandomNumberGenerator,因此任何遵循了 RandomNumberGenerator 协议的类型的实例都可以赋值给 generator,除此之外并无其他要求。 Dice 类还有一个构造器,用来设置初始状态。构造器有一个名为 generator,类型为 RandomNumberGenerator 的形参。在调用构造方法创建 Dice 的实例时,可以传入任何遵循 RandomNumberGenerator 协议的实例给 generator。 Dice 类提供了一个名为 roll 的实例方法,用来模拟骰子的面值。它先调用 generator 的 random() 方法来生成一个 [0.0,1.0) 区间内的随机数,然后使用这个随机数生成正确的骰子面值。因为 generator 遵循了 RandomNumberGenerator 协议,可以确保它有个 random() 方法可供调用。 */ // 下面的例子展示了如何使用 LinearCongruentialGenerator 的实例作为随机数生成器来创建一个六面骰子: var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator()) for _ in 1...5 { print("Random dice roll is \(d6.roll())") } // Random dice roll is 3 // Random dice roll is 5 // Random dice roll is 4 // Random dice roll is 5 // Random dice roll is 4 // MARK: - 委托(代理)模式 /*lzy171019注: 委托是一种设计模式,它允许类或结构体将一些需要它们负责的功能委托给其他类型的实例。委托模式的实现很简单:定义协议来封装那些需要被委托的功能,这样就能确保遵循协议的类型能提供这些功能。委托模式可以用来响应特定的动作,或者接收外部数据源提供的数据,而无需关心外部数据源的类型。 DiceGame 协议可以被任意涉及骰子的游戏遵循。DiceGameDelegate 协议可以被任意类型遵循,用来追踪 DiceGame 的游戏过程。 如下所示,SnakesAndLadders 是 控制流 章节引入的蛇梯棋游戏的新版本。新版本使用 Dice 实例作为骰子,并且实现了 DiceGame 和 DiceGameDelegate 协议,后者用来记录游戏的过程: */ /*lzy171019注: 这个版本的游戏封装到了 SnakesAndLadders 类中,该类遵循了 DiceGame 协议,并且提供了相应的可读的 dice 属性和 play() 方法。( dice 属性在构造之后就不再改变,且协议只要求 dice 为可读的,因此将 dice 声明为常量属性。) 游戏使用 SnakesAndLadders 类的 init() 构造器来初始化游戏。所有的游戏逻辑被转移到了协议中的 play() 方法,play() 方法使用协议要求的 dice 属性提供骰子摇出的值。 注意,delegate 并不是游戏的必备条件,因此 delegate 被定义为 DiceGameDelegate 类型的可选属性。因为 delegate 是可选值,因此会被自动赋予初始值 nil。随后,可以在游戏中为 delegate 设置适当的值。 DicegameDelegate 协议提供了三个方法用来追踪游戏过程。这三个方法被放置于游戏的逻辑中,即 play() 方法内。分别在游戏开始时,新一轮开始时,以及游戏结束时被调用。 因为 delegate 是一个 DiceGameDelegate 类型的可选属性,因此在 play() 方法中通过可选链式调用来调用它的方法。若 delegate 属性为 nil,则调用方法会优雅地失败,并不会产生错误。若 delegate 不为 nil,则方法能够被调用,并传递 SnakesAndLadders 实例作为参数。 */ // 如下示例定义了 DiceGameTracker 类,它遵循了 DiceGameDelegate 协议: class DiceGameTracker: DiceGameDelegate { var numberOfTurns = 0 func gameDidStart(_ game: DiceGame) { numberOfTurns = 0 if game is SnakesAndLadders { print("Started a new game of Snakes and Ladders") } print("The game is using a \(game.dice.sides)-sided dice") } func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) { numberOfTurns += 1 print("Rolled a \(diceRoll)") } func gameDidEnd(_ game: DiceGame) { print("The game lasted for \(numberOfTurns) turns") } } /*lzy171019注: DiceGameTracker 实现了 DiceGameDelegate 协议要求的三个方法,用来记录游戏已经进行的轮数。当游戏开始时,numberOfTurns 属性被赋值为 0,然后在每新一轮中递增,游戏结束后,打印游戏的总轮数。 gameDidStart(_:) 方法从 game 参数获取游戏信息并打印。game 参数是 DiceGame 类型而不是 SnakeAndLadders 类型,所以在gameDidStart(_:) 方法中只能访问 DiceGame 协议中的内容。当然了,SnakeAndLadders 的方法也可以在类型转换之后调用。在上例代码中,通过 is 操作符检查 game 是否为 SnakesAndLadders 类型的实例,如果是,则打印出相应的消息。 无论当前进行的是何种游戏,由于 game 符合 DiceGame 协议,可以确保 game 含有 dice 属性。因此在 gameDidStart(_:) 方法中可以通过传入的 game 参数来访问 dice 属性,进而打印出 dice 的 sides 属性的值。 */ // DiceGameTracker 的运行情况如下所示: let tracker = DiceGameTracker() let game = SnakesAndLadders() game.delegate = tracker game.play() // Started a new game of Snakes and Ladders // The game is using a 6-sided dice // Rolled a 3 // Rolled a 5 // Rolled a 4 // Rolled a 5 // The game lasted for 4 turns // MARK: - 通过扩展添加协议一致性 /*lzy171019注: 即便无法修改源代码,依然可以通过扩展令已有类型遵循并符合协议。扩展可以为已有类型添加属性、方法、下标以及构造器,因此可以符合协议中的相应要求。详情请在扩展章节中查看。 注意 通过扩展令已有类型遵循并符合协议时,该类型的所有实例也会随之获得协议中定义的各项功能。 例如下面这个 TextRepresentable 协议,任何想要通过文本表示一些内容的类型都可以实现该协议。这些想要表示的内容可以是实例本身的描述,也可以是实例当前状态的文本描述:见协议区域 可以通过扩展,令先前提到的 Dice 类遵循并符合 TextRepresentable 协议:见扩展区域 通过扩展遵循并符合协议,和在原始定义中遵循并符合协议的效果完全相同。协议名称写在类型名之后,以冒号隔开,然后在扩展的大括号内实现协议要求的内容。 */ // 现在所有 Dice 的实例都可以看做 TextRepresentable 类型: let d12 = Dice(sides: 12, generator: LinearCongruentialGenerator()) print(d12.textualDescription) // 打印 “A 12-sided dice” // 同样,SnakesAndLadders 类也可以通过扩展遵循并符合 TextRepresentable 协议:// 见扩展区域 print(game.textualDescription) // 打印 “A game of Snakes and Ladders with 25 squares” // MARK: - 通过扩展遵循协议 /*lzy171019注: 当一个类型已经符合了某个协议中的所有要求,却还没有声明遵循该协议时,可以通过空扩展体的扩展来遵循该协议: struct Hamster { var name: String var textualDescription: String { return "A hamster named \(name)" } } extension Hamster: TextRepresentable {} */ // 从现在起,Hamster 的实例可以作为 TextRepresentable 类型使用: let simonTheHamster = Hamster(name: "Simon") let somethingTextRepresentable: TextRepresentable = simonTheHamster print(somethingTextRepresentable.textualDescription) // 打印 “A hamster named Simon” // 注意 // 即使满足了协议的所有要求,类型也不会自动遵循协议,必须显式地遵循协议。 // MARK: - 协议类型的集合 /*lzy171019注: 协议类型可以在数组或者字典这样的集合中使用,在协议类型提到了这样的用法。 */ // 下面的例子创建了一个元素类型为 TextRepresentable 的数组: let things: [TextRepresentable] = [game, d12, simonTheHamster] // 如下所示,可以遍历 things 数组,并打印每个元素的文本表示: for thing in things { print(thing.textualDescription) } // A game of Snakes and Ladders with 25 squares // A 12-sided dice // A hamster named Simon /*lzy171019注: thing 是 TextRepresentable 类型而不是 Dice,DiceGame,Hamster 等类型,即使实例在幕后确实是这些类型中的一种。由于 thing 是 TextRepresentable 类型,任何 TextRepresentable 的实例都有一个 textualDescription 属性,所以在每次循环中可以安全地访问 thing.textualDescription。 */ // MARK: - 协议的继承 /*lzy171019注: 协议能够继承一个或多个其他协议,可以在继承的协议的基础上增加新的要求。协议的继承语法与类的继承相似,多个被继承的协议间用逗号分隔: protocol InheritingProtocol: SomeProtocol, AnotherProtocol { // 这里是协议的定义部分 } 如下所示,PrettyTextRepresentable 协议继承了 TextRepresentable 协议: protocol PrettyTextRepresentable: TextRepresentable { var prettyTextualDescription: String { get } } 例子中定义了一个新的协议 PrettyTextRepresentable,它继承自 TextRepresentable 协议。任何遵循 PrettyTextRepresentable 协议的类型在满足该协议的要求时,也必须满足 TextRepresentable 协议的要求。在这个例子中,PrettyTextRepresentable 协议额外要求遵循协议的类型提供一个返回值为 String 类型的 prettyTextualDescription 属性。 如下所示,扩展 SnakesAndLadders,使其遵循并符合 PrettyTextRepresentable 协议: extension SnakesAndLadders: PrettyTextRepresentable { var prettyTextualDescription: String { var output = textualDescription + ":\n" for index in 1...finalSquare { switch board[index] { case let ladder where ladder > 0: output += "▲ " case let snake where snake < 0: output += "▼ " default: output += "○ " } } return output } } 上述扩展令 SnakesAndLadders 遵循了 PrettyTextRepresentable 协议,并提供了协议要求的 prettyTextualDescription 属性。每个 PrettyTextRepresentable 类型同时也是 TextRepresentable 类型,所以在 prettyTextualDescription 的实现中,可以访问 textualDescription 属性。然后,拼接上了冒号和换行符。接着,遍历数组中的元素,拼接一个几何图形来表示每个棋盘方格的内容: 当从数组中取出的元素的值大于 0 时,用 ▲ 表示。 当从数组中取出的元素的值小于 0 时,用 ▼ 表示。 当从数组中取出的元素的值等于 0 时,用 ○ 表示。 任意 SankesAndLadders 的实例都可以使用 prettyTextualDescription 属性来打印一个漂亮的文本描述: */ print(game.prettyTextualDescription) // A game of Snakes and Ladders with 25 squares: // ○ ○ ▲ ○ ○ ▲ ○ ○ ▲ ▲ ○ ○ ○ ▼ ○ ○ ○ ○ ▼ ○ ○ ▼ ○ ▼ ○ // MARK: - 类类型专属协议 /*lzy171019注: 你可以在协议的继承列表中,通过添加 class 关键字来限制协议只能被类类型遵循,而结构体或枚举不能遵循该协议。class 关键字必须第一个出现在协议的继承列表中,在其他继承的协议之前: protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol { // 这里是类类型专属协议的定义部分 } 在以上例子中,协议 SomeClassOnlyProtocol 只能被类类型遵循。如果尝试让结构体或枚举类型遵循该协议,则会导致编译错误。 注意 当协议定义的要求需要遵循协议的类型必须是引用语义而非值语义时,应该采用类类型专属协议。关于引用语义和值语义的更多内容,请查看结构体和枚举是值类型和类是引用类型。 */ // MARK: - 协议合成 /*lzy171019注: 有时候需要同时遵循多个协议,你可以将多个协议采用 SomeProtocol & AnotherProtocol 这样的格式进行组合,称为 协议合成(protocol composition)。你可以罗列任意多个你想要遵循的协议,以与符号(&)分隔。 下面的例子中,将 Named 和 Aged 两个协议按照上述语法组合成一个协议,作为函数参数的类型: protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person: Named, Aged { var name: String var age: Int } func wishHappyBirthday(to celebrator: Named & Aged) { print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!") } let birthdayPerson = Person(name: "Malcolm", age: 21) wishHappyBirthday(to: birthdayPerson) // 打印 “Happy birthday Malcolm - you're 21!” Named 协议包含 String 类型的 name 属性。Aged 协议包含 Int 类型的 age 属性。Person 结构体遵循了这两个协议。 wishHappyBirthday(to:) 函数的参数 celebrator 的类型为 Named & Aged。这意味着它不关心参数的具体类型,只要参数符合这两个协议即可。 */ func wishHappyBirthday(to celebrator: Named & Aged) { print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!") } let birthdayPerson = Person2(name: "Malcolm", age: 21) wishHappyBirthday(to: birthdayPerson) // 打印 “Happy birthday Malcolm - you're 21!” /*lzy171019注: 上面的例子创建了一个名为 birthdayPerson 的 Person1 的实例,作为参数传递给了 wishHappyBirthday(to:) 函数。因为 Person1 同时符合这两个协议,所以这个参数合法,函数将打印生日问候语。 */ // 这里有一个例子:将Location类和前面的Named协议进行组合: /*lzy171019注: class Location { var latitude: Double var longitude: Double init(latitude: Double, longitude: Double) { self.latitude = latitude self.longitude = longitude } } class City: Location, Named { var name: String init(name: String, latitude: Double, longitude: Double) { self.name = name super.init(latitude: latitude, longitude: longitude) } } func beginConcert(in location: Location & Named) { print("Hello, \(location.name)!") } let seattle = City(name: "Seattle", latitude: 47.6, longitude: -122.3) beginConcert(in: seattle) // Prints "Hello, Seattle!" beginConcert(in:)方法接受一个类型为 Location & Named 的参数,这意味着"任何Location的子类,并且遵循Named协议"。例如,City就满足这样的条件。 将 birthdayPerson 传入beginConcert(in:)函数是不合法的,因为 Person不是一个Location的子类。就像,如果你新建一个类继承与Location,但是没有遵循Named协议,你用这个类的实例去调用beginConcert(in:)函数也是不合法的。 */ func beginConcert(in location: Location & Named) { print("Hello, \(location.name)!") } let seattle = City(name: "Seattle", latitude: 47.6, longitude: -122.3) beginConcert(in: seattle) // Prints "Hello, Seattle!" // MARK: - 检查协议一致性 /*lzy171019注: 你可以使用类型转换中描述的 is 和 as 操作符来检查协议一致性,即是否符合某协议,并且可以转换到指定的协议类型。检查和转换到某个协议类型在语法上和类型的检查和转换完全相同: is 用来检查实例是否符合某个协议,若符合则返回 true,否则返回 false。 as? 返回一个可选值,当实例符合某个协议时,返回类型为协议类型的可选值,否则返回 nil。 as! 将实例强制向下转换到某个协议类型,如果强转失败,会引发运行时错误。 下面的例子定义了一个 HasArea 协议,该协议定义了一个 Double 类型的可读属性 area: protocol HasArea { var area: Double { get } } 如下所示,Circle 类和 Country 类都遵循了 HasArea 协议: class Circle: HasArea { let pi = 3.1415927 var radius: Double var area: Double { return pi * radius * radius } init(radius: Double) { self.radius = radius } } class Country: HasArea { var area: Double init(area: Double) { self.area = area } } Circle 类把 area 属性实现为基于存储型属性 radius 的计算型属性。Country 类则把 area 属性实现为存储型属性。这两个类都正确地符合了 HasArea 协议。 如下所示,Animal 是一个未遵循 HasArea 协议的类: class Animal { var legs: Int init(legs: Int) { self.legs = legs } } */ // Circle,Country,Animal 并没有一个共同的基类,尽管如此,它们都是类,它们的实例都可以作为 AnyObject 类型的值,存储在同一个数组中: let objects: [AnyObject] = [ Circle1(radius: 2.0), Country(area: 243_610), Animal(legs: 4) ] // objects 数组使用字面量初始化,数组包含一个 radius 为 2 的 Circle 的实例,一个保存了英国国土面积的 Country 实例和一个 legs 为 4 的 Animal 实例。 // 如下所示,objects 数组可以被迭代,并对迭代出的每一个元素进行检查,看它是否符合 HasArea 协议: for object in objects { if let objectWithArea = object as? HasArea { print("Area is \(objectWithArea.area)") } else { print("Something that doesn't have an area") } } // Area is 12.5663708 // Area is 243610.0 // Something that doesn't have an area // 当迭代出的元素符合 HasArea 协议时,将 as? 操作符返回的可选值通过可选绑定,绑定到 objectWithArea 常量上。objectWithArea 是 HasArea 协议类型的实例,因此 area 属性可以被访问和打印。 // objects 数组中的元素的类型并不会因为强转而丢失类型信息,它们仍然是 Circle,Country,Animal 类型。然而,当它们被赋值给 objectWithArea 常量时,只被视为 HasArea 类型,因此只有 area 属性能够被访问。 // MARK: - 可选的协议要求 /*lzy171019注: 协议可以定义可选要求,遵循协议的类型可以选择是否实现这些要求。 在协议中使用 optional 关键字作为前缀来定义可选要求。 可选要求用在你需要和 Objective-C 打交道的代码中。 协议和可选要求都必须带上@objc属性。 标记 @objc 特性的协议只能被继承自 Objective-C 类的类或者 @objc 类遵循,其他类以及结构体和枚举均不能遵循这种协议。 使用可选要求时(例如,可选的方法或者属性),它们的类型会自动变成可选的。比如,一个类型为 (Int) -> String 的方法会变成 ((Int) -> String)?。需要注意的是整个函数类型是可选的,而不是函数的返回值。 协议中的可选要求可通过可选链式调用来使用,因为遵循协议的类型可能没有实现这些可选要求。类似 someOptionalMethod?(someArgument) 这样,你可以在可选方法名称后加上 ? 来调用可选方法。详细内容可在可选链式调用章节中查看。 下面的例子定义了一个名为 Counter 的用于整数计数的类,它使用外部的数据源来提供每次的增量。数据源由 CounterDataSource 协议定义,包含两个可选要求: @objc protocol CounterDataSource { @objc optional func incrementForCount(count: Int) -> Int @objc optional var fixedIncrement: Int { get } } CounterDataSource 协议定义了一个可选方法 increment(forCount:) 和一个可选属性 fiexdIncrement,它们使用了不同的方法来从数据源中获取适当的增量值。 注意 严格来讲,CounterDataSource 协议中的方法和属性都是可选的,因此遵循协议的类可以不实现这些要求,尽管技术上允许这样做,不过最好不要这样写。 Counter 类含有 CounterDataSource? 类型的可选属性 dataSource,如下所示: class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.incrementForCount?(count) { count += amount } else if let amount = dataSource?.fixedIncrement { count += amount } } } Counter 类使用变量属性 count 来存储当前值。该类还定义了一个 increment 方法,每次调用该方法的时候,将会增加 count 的值。 increment() 方法首先试图使用 increment(forCount:) 方法来得到每次的增量。increment() 方法使用可选链式调用来尝试调用 increment(forCount:),并将当前的 count 值作为参数传入。 这里使用了两层可选链式调用。首先,由于 dataSource 可能为 nil,因此在 dataSource 后边加上了 ?,以此表明只在 dataSource 非空时才去调用 increment(forCount:) 方法。其次,即使 dataSource 存在,也无法保证其是否实现了 increment(forCount:) 方法,因为这个方法是可选的。因此,increment(forCount:) 方法同样使用可选链式调用进行调用,只有在该方法被实现的情况下才能调用它,所以在 increment(forCount:) 方法后边也加上了 ?。 调用 increment(forCount:) 方法在上述两种情形下都有可能失败,所以返回值为 Int? 类型。虽然在 CounterDataSource 协议中,increment(forCount:) 的返回值类型是非可选 Int。另外,即使这里使用了两层可选链式调用,最后的返回结果依旧是单层的可选类型。关于这一点的更多信息,请查阅连接多层可选链式调用 在调用 increment(forCount:) 方法后,Int? 型的返回值通过可选绑定解包并赋值给常量 amount。如果可选值确实包含一个数值,也就是说,数据源和方法都存在,数据源方法返回了一个有效值。之后便将解包后的 amount 加到 count 上,增量操作完成。 如果没有从 increment(forCount:) 方法获取到值,可能由于 dataSource 为 nil,或者它并没有实现 increment(forCount:) 方法,那么 increment() 方法将试图从数据源的 fixedIncrement 属性中获取增量。fixedIncrement 是一个可选属性,因此属性值是一个 Int? 值,即使该属性在 CounterDataSource 协议中的类型是非可选的 Int。 下面的例子展示了 CounterDataSource 的简单实现。ThreeSource 类遵循了 CounterDataSource 协议,它实现了可选属性 fixedIncrement,每次会返回 3: class ThreeSource: NSObject, CounterDataSource { let fixedIncrement = 3 } 可以使用 ThreeSource 的实例作为 Counter 实例的数据源:*/ var counter = Counter() counter.dataSource = ThreeSource() for _ in 1...4 { counter.increment() print(counter.count) } // 3 // 6 // 9 // 12 /* 上述代码新建了一个 Counter 实例,并将它的数据源设置为一个 ThreeSource 的实例,然后调用 increment() 方法四次。和预期一样,每次调用都会将 count 的值增加 3. 下面是一个更为复杂的数据源 TowardsZeroSource,它将使得最后的值变为 0: @objc class TowardsZeroSource: NSObject, CounterDataSource { func increment(forCount count: Int) -> Int { if count == 0 { return 0 } else if count < 0 { return 1 } else { return -1 } } } TowardsZeroSource 实现了 CounterDataSource 协议中的 increment(forCount:) 方法,以 count 参数为依据,计算出每次的增量。如果 count 已经为 0,此方法返回 0,以此表明之后不应再有增量操作发生。 你可以使用 TowardsZeroSource 实例将 Counter 实例来从 -4 增加到 0。一旦增加到 0,数值便不会再有变动: */ counter.count = -4 counter.dataSource = TowardsZeroSource() for _ in 1...5 { counter.increment() print(counter.count) } // -3 // -2 // -1 // 0 // 0 // MARK: - 协议扩展 /*lzy171019注: 协议可以通过扩展来为遵循协议的类型提供属性、方法以及下标的实现。通过这种方式,你可以基于协议本身来实现这些功能,而无需在每个遵循协议的类型中都重复同样的实现,也无需使用全局函数。 例如,可以扩展 RandomNumberGenerator 协议来提供 randomBool() 方法。该方法使用协议中定义的 random() 方法来返回一个随机的 Bool 值: extension RandomNumberGenerator { func randomBool() -> Bool { return random() > 0.5 } } 通过协议扩展,所有遵循协议的类型,都能自动获得这个扩展所增加的方法实现,无需任何额外修改: */ let generator1 = LinearCongruentialGenerator() print("Here's a random number: \(generator1.random())") // 打印 “Here's a random number: 0.37464991998171” print("And here's a random Boolean: \(generator1.randomBool())") // 打印 “And here's a random Boolean: true” // MARK:====提供默认实现==== /* 可以通过协议扩展来为协议要求的属性、方法以及下标提供默认的实现。 如果遵循协议的类型为这些要求提供了自己的实现,那么这些自定义实现将会替代扩展中的默认实现被使用。 注意 通过协议扩展为协议要求提供的默认实现和可选的协议要求不同。 虽然在这两种情况下,遵循协议的类型都无需自己实现这些要求,但是通过扩展提供的默认实现可以直接调用,而无需使用可选链式调用。 例如,PrettyTextRepresentable 协议继承自 TextRepresentable 协议,可以为其提供一个默认的 prettyTextualDescription 属性,只是简单地返回 textualDescription 属性的值: extension PrettyTextRepresentable { var prettyTextualDescription: String { return textualDescription } } */ //MARK:====为协议扩展添加限制条件==== /* 在扩展协议的时候,可以指定一些限制条件,只有遵循协议的类型满足这些限制条件时,才能获得协议扩展提供的默认实现。这些限制条件写在协议名之后,使用 where 子句来描述,正如Where子句中所描述的。 例如,你可以扩展 CollectionType 协议,但是只适用于集合中的元素遵循了 TextRepresentable 协议的情况: extension Collection where Iterator.Element: TextRepresentable { var textualDescription: String { let itemsAsText = self.map { $0.textualDescription } return "[" + itemsAsText.joined(separator: ", ") + "]" } } textualDescription 属性返回整个集合的文本描述,它将集合中的每个元素的文本描述以逗号分隔的方式连接起来,包在一对方括号中。 现在我们来看看先前的 Hamster 结构体,它符合 TextRepresentable 协议,同时这里还有个装有 Hamster 的实例的数组: Swift必须显式地遵守协议,Hamster写在了extension里头 extension Hamster: TextRepresentable {} */ let murrayTheHamster = Hamster(name: "Murray") let morganTheHamster = Hamster(name: "Morgan") let mauriceTheHamster = Hamster(name: "Maurice") let hamsters = [murrayTheHamster, morganTheHamster, mauriceTheHamster] /* 因为 Array 符合 CollectionType 协议,而数组中的元素又符合 TextRepresentable 协议,所以数组可以使用 textualDescription 属性得到数组内容的文本表示: 注意 如果多个协议扩展都为同一个协议要求提供了默认实现,而遵循协议的类型又同时满足这些协议扩展的限制条件,那么将会使用限制条件最多的那个协议扩展提供的默认实现。 */ print(hamsters.textualDescription) // 打印 “[A hamster named Murray, A hamster named Morgan, A hamster named Maurice]” } } // MARK: - 协议区域 // MARK:====协议语法==== protocol FirstProtocol { } protocol AnotherProtocol { } // MARK:===属性要求==== // 如下所示,这是一个只含有一个实例属性要求的协议: protocol FullyNamed { var fullName: String { get } } // MARK:====方法要求==== // 下面的例子定义了一个只含有一个实例方法的协议: protocol RandomNumberGenerator { func random() -> Double } // MARK:====Mutating 方法要求==== //toggle() 方法在定义的时候,使用 mutating 关键字标记,这表明当它被调用时,该方法将会改变遵循协议的类型的实例: protocol Togglable { mutating func toggle() } // 如下所示,PrettyTextRepresentable 协议继承了 TextRepresentable 协议: protocol PrettyTextRepresentable: TextRepresentable { var prettyTextualDescription: String { get } } // MARK:====委托(代理)模式==== //下面的例子定义了两个基于骰子游戏的协议: protocol DiceGame { var dice: Dice { get } func play() } protocol DiceGameDelegate { func gameDidStart(_ game: DiceGame) func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) func gameDidEnd(_ game: DiceGame) } protocol TextRepresentable { var textualDescription: String { get } } protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } protocol HasArea { var area: Double { get } } @objc protocol CounterDataSource { @objc optional func incrementForCount(count: Int) -> Int @objc optional var fixedIncrement: Int { get } } // MARK: - 辅助类\结构体\枚举 区域 class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c).truncatingRemainder(dividingBy:m)) return lastRandom / m } } // 下面是将协议作为类型使用的例子: class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } class SnakesAndLadders: DiceGame { let finalSquare = 25 let dice = Dice(sides: 6, generator: LinearCongruentialGenerator()) var square = 0 var board: [Int] init() { board = [Int](repeating: 0, count: finalSquare + 1) board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02 board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 } var delegate: DiceGameDelegate? func play() { square = 0 delegate?.gameDidStart(self) gameLoop: while square != finalSquare { let diceRoll = dice.roll() delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll) switch square + diceRoll { case finalSquare: break gameLoop case let newSquare where newSquare > finalSquare: continue gameLoop default: square += diceRoll square += board[square] } } delegate?.gameDidEnd(self) } } // 关于这个蛇梯棋游戏的详细描述请参阅 控制流 章节中的 Break 部分。 struct Hamster { var name: String var textualDescription: String { return "A hamster named \(name)" } } struct Person2: Named, Aged { var name: String var age: Int } class Location { var latitude: Double var longitude: Double init(latitude: Double, longitude: Double) { self.latitude = latitude self.longitude = longitude } } class City: Location, Named { var name: String init(name: String, latitude: Double, longitude: Double) { self.name = name super.init(latitude: latitude, longitude: longitude) } } class Circle1: HasArea { let pi = 3.1415927 var radius: Double var area: Double { return pi * radius * radius } init(radius: Double) { self.radius = radius } } class Country: HasArea { var area: Double init(area: Double) { self.area = area } } class Animal { var legs: Int init(legs: Int) { self.legs = legs } } class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.incrementForCount?(count: count) { count += amount } else if let amount = dataSource?.fixedIncrement { count += amount } } } class ThreeSource: NSObject, CounterDataSource { let fixedIncrement = 3 } @objc class TowardsZeroSource: NSObject, CounterDataSource { func increment(forCount count: Int) -> Int { if count == 0 { return 0 } else if count < 0 { return 1 } else { return -1 } } } // MARK: - 扩展 区域 extension Dice: TextRepresentable { var textualDescription: String { return "A \(sides)-sided dice" } } extension SnakesAndLadders: TextRepresentable { var textualDescription: String { return "A game of Snakes and Ladders with \(finalSquare) squares" } } extension Hamster: TextRepresentable {} extension SnakesAndLadders: PrettyTextRepresentable { var prettyTextualDescription: String { var output = textualDescription + ":\n" for index in 1...finalSquare { switch board[index] { case let ladder where ladder > 0: output += "▲ " case let snake where snake < 0: output += "▼ " default: output += "○ " } } return output } } extension RandomNumberGenerator { func randomBool() -> Bool { return random() > 0.5 } } extension PrettyTextRepresentable { var prettyTextualDescription: String { return textualDescription } } extension Collection where Iterator.Element: TextRepresentable { var textualDescription: String { let itemsAsText = self.map { $0.textualDescription } return "[" + itemsAsText.joined(separator: ", ") + "]" } }
022a03c2269971b11eb57b5e2c3f8d8f
32.827723
284
0.612158
false
false
false
false
finngaida/healthpad
refs/heads/master
Shared/Animation/DotTrianglePath.swift
apache-2.0
1
// // DotTrianglePath.swift // RPLoadingAnimation // // Created by naoyashiga on 2015/10/12. // Copyright © 2015年 naoyashiga. All rights reserved. // import UIKit class DotTrianglePath: RPLoadingAnimationDelegate { var baseLayer = CALayer() var baseSize = CGSize(width: 0, height: 0) func setup(layer: CALayer, size: CGSize, color: UIColor) { let dotNum: CGFloat = 3 let diameter: CGFloat = size.width / 15 let dot = CALayer() let duration: CFTimeInterval = 1.3 let frame = CGRect( x: (layer.bounds.width - diameter) / 2, y: (layer.bounds.height - diameter) / 2, width: diameter, height: diameter ) layer.frame = frame baseLayer = layer baseSize = size dot.backgroundColor = color.CGColor dot.frame = frame dot.cornerRadius = diameter / 2 let replicatorLayer = CAReplicatorLayer() replicatorLayer.frame = layer.bounds replicatorLayer.addSublayer(dot) replicatorLayer.instanceCount = Int(dotNum) replicatorLayer.instanceDelay = CFTimeInterval(-1 / dotNum) layer.addSublayer(replicatorLayer) let moveAnimation = CAKeyframeAnimation(keyPath: "position") moveAnimation.path = getPath() moveAnimation.duration = duration moveAnimation.repeatCount = .infinity moveAnimation.timingFunction = TimingFunction.EaseInOutSine.getTimingFunction() dot.addAnimation(moveAnimation, forKey: "moveAnimation") } func getPath() -> CGPath { let r: CGFloat = baseSize.width / 5 let center = CGPoint(x: baseLayer.bounds.width / 2, y: baseLayer.bounds.height / 2) let path = UIBezierPath() path.moveToPoint(CGPointMake(center.x, -r)) path.addLineToPoint(CGPointMake(center.x - r, r / 2)) path.addLineToPoint(CGPointMake(center.x + r, r / 2)) path.closePath() return path.CGPath } }
d5a171a3f3c91a2c6b080a3282c414b6
30.358209
91
0.60619
false
false
false
false
devpunk/velvet_room
refs/heads/master
Source/Model/Vita/MVitaPtpMessageInConfirm.swift
mit
1
import Foundation final class MVitaPtpMessageInConfirm:MVitaPtpMessageIn { let code:MVitaPtpCommand let transactionId:UInt32 override init?( header:MVitaPtpMessageInHeader, data:Data) { let codeSize:Int = MemoryLayout<UInt16>.size let transactionSize:Int = MemoryLayout<UInt32>.size let expectedSize:Int = codeSize + transactionSize guard data.count >= expectedSize else { return nil } let subdataTransaction:Data = data.subdata( start:codeSize) guard let rawCode:UInt16 = data.valueFromBytes(), let transactionId:UInt32 = subdataTransaction.valueFromBytes() else { return nil } print("confirm code \(rawCode)") self.transactionId = transactionId self.code = MVitaPtpMessageIn.factoryCommandCode( rawCode:rawCode) super.init( header:header, data:data) } }
8d1c7e5f4901afe83f2787b08edf4ac7
23.391304
74
0.546346
false
false
false
false
Henryforce/KRActivityIndicatorView
refs/heads/master
KRActivityIndicatorView/KRActivityIndicatorAnimationBallClipRotatePulse.swift
mit
2
// // KRActivityIndicatorAnimationBallClipRotatePulse.swift // KRActivityIndicatorViewDemo // // The MIT License (MIT) // Originally written to work in iOS by Vinh Nguyen in 2016 // Adapted to OSX by Henry Serrano in 2017 // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Cocoa class KRActivityIndicatorAnimationBallClipRotatePulse: KRActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) { let duration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(controlPoints: 0.09, 0.57, 0.49, 0.9) smallCircleWith(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color) bigCircleWith(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color) } func smallCircleWith(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: NSColor) { // Animation let animation = CAKeyframeAnimation(keyPath:"transform.scale") animation.keyTimes = [0, 0.3, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.3, 1] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle let circleSize = size.width / 2 let circle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } func bigCircleWith(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: NSColor) { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath:"transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = [timingFunction, timingFunction] rotateAnimation.values = [0, Float.pi, 2 * Float.pi] rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle let circle = KRActivityIndicatorShape.ringTwoHalfVertical.layerWith(size: size, color: color) let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
4c20f110159bfb3561b6bd4f754490fd
44.47
137
0.67583
false
false
false
false
Natoto/SWIFTMIAPP
refs/heads/master
swiftmi/swiftmi/AddTopicController.swift
mit
1
// // AddTopicController.swift // swiftmi // // Created by yangyin on 15/4/23. // Copyright (c) 2015年 swiftmi. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import Kingfisher class AddTopicController: UIViewController { @IBOutlet weak var contentField: UITextView! @IBOutlet weak var titleField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setView() } @IBAction func publishClick(sender: AnyObject) { let title = self.titleField.text let content = self.contentField.text if title!.isEmpty { Utility.showMessage("标题不能为空!") return } if content.isEmpty { Utility.showMessage("内容不能为空!") return } if title != nil { let btn = sender as! UIButton btn.enabled = false let params:[String:AnyObject] = ["title":title!,"content":content!,"channelId":1] // Alamofire.request(Router.TopicCreate(parameters: params)).responseJSON{ // closureResponse in Alamofire.request(Router.TopicCreate(parameters: params)).responseJSON { (request, closureResponse, Result) -> Void in btn.enabled = true if Result.isFailure { let alert = UIAlertView(title: "网络异常", message: "请检查网络设置", delegate: nil, cancelButtonTitle: "确定") alert.show() return } let json = Result.value//.result.value var result = JSON(json!) if result["isSuc"].boolValue { self.navigationController?.popViewControllerAnimated(true) } else { let errMsg = result["msg"].stringValue Utility.showMessage("发布失败!:\(errMsg)") } } } } private func setView() { let border = CALayer() let width = CGFloat(1.0) border.borderColor = UIColor.lightGrayColor().CGColor border.frame = CGRect(x: 0, y: titleField.frame.size.height - width, width: titleField.frame.size.width,height: width) border.borderWidth = width titleField.layer.addSublayer(border) titleField.layer.masksToBounds = true let center: NSNotificationCenter = NSNotificationCenter.defaultCenter() center.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) center.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } func keyboardWillShow(notification: NSNotification) { let info:NSDictionary = notification.userInfo! let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let endKeyboardRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { for constraint in self.view.constraints { let cons = constraint as NSLayoutConstraint if let _ = cons.secondItem as? UITextView { if cons.secondAttribute == NSLayoutAttribute.Bottom { cons.constant = 10 + endKeyboardRect.height break; } } } }, completion: nil) } func keyboardWillHide(notification: NSNotification) { let info:NSDictionary = notification.userInfo! let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { for constraint in self.view.constraints { let cons = constraint as NSLayoutConstraint if let _ = cons.secondItem as? UITextView { if cons.secondAttribute == NSLayoutAttribute.Bottom { cons.constant = 10 break; } } } }, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
840c7e19fb5c58e5b6b71ef091147caa
30.00995
132
0.508102
false
false
false
false
ZhaoBingDong/EasySwifty
refs/heads/master
EasySwifty/Classes/EasyReqeust.swift
apache-2.0
1
// // EasyReqeust.swift // MiaoTuProject // // Created by dzb on 2019/7/4. // Copyright © 2019 大兵布莱恩特. All rights reserved. // import Foundation //import SwiftyJSON //import Alamofire // // //class EasyResult { // var errorMsg : String = "未知错误" // var error : NSError? { // didSet { // errorMsg = error?.localizedDescription ?? "未知错误" // } // } // var dictionary : JSON = JSON() // var array : [JSON] = [JSON]() // var stringValue : String = "" // var statusCode : Int = 0 // var data : [String : Any]? // //} // //class EasyRequest { // // static var shared : EasyRequest = { // let manager = EasyRequest() // return manager; // }() // // fileprivate let sessionManager : SessionManager = SessionManager.default // lazy fileprivate var HTTPHeaders : [String : Any] = { // var paramerts = [String : Any]() // if let app_Version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] { // paramerts["api_version"] = app_Version // } // paramerts["modelType"] = "iOS" // paramerts["app_key"] = "1001" // paramerts["device_type"] = "4" // paramerts["Content-Type"] = "application/json;charset=UTF-8" // return paramerts // }() // // typealias EasyReqeustSuccess = (_ responseObject : EasyResult) -> Void // static func get(_ URLString : String,parameters : [String : Any]?,completionHandler : @escaping EasyReqeustSuccess) { // EasyRequest.shared.reqeustWithURL(URLString, parameters: parameters, httpMethod: .get, completionHandler: completionHandler) // } // // static func post(_ URLString : String,urlParams : Bool,parameters : [String : Any]?,completionHandler : @escaping EasyReqeustSuccess) { // let string = getParameterString(parameters ?? [:]) // let method : String = urlParams ? "\(URLString)?\(string)" : URLString // EasyRequest.shared.reqeustWithURL(method, parameters: urlParams ? nil : parameters, httpMethod: .post, completionHandler: completionHandler) // } // // /// 拼接URL参数 // fileprivate static func getParameterString(_ paramters : [String : Any]) -> String{ // guard !paramters.isEmpty else { // return "" // } // let keys = paramters.keys.sorted { (str1, str2) -> Bool in // return false // } // var paraString : String = "" // let parameterCount : Int = keys.count // for i in 0..<parameterCount { // let key = keys[i] // if i != 0 { // paraString.append("&") // } // let value = paramters[key] // paraString.append(key) // paraString.append("=") // paraString.append("\(value!)") // } // let characterSet = CharacterSet.urlQueryAllowed // return paraString.addingPercentEncoding(withAllowedCharacters: characterSet) ?? "" // } // // fileprivate func authBase64String(token : String) -> String { // var dict = [String : Any]() // dict["authorization_code"] = token // if let username : String = YVRealmHelper.shared.userAuthorization?.username { // dict["user_name"] = username // } // let data : Data = try! JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted]) // let base64 : String = data.base64EncodedString() // return base64 // } // // fileprivate func appendHTTPHeaders() { // if let token = YVRealmHelper.shared.userAuthorization?.token { // self.HTTPHeaders.set(object: token, forKey: "token") // let authorization : String = authBase64String(token: token) // self.HTTPHeaders.set(object: authorization, forKey: "Authorization") // } // let timeStamp : TimeInterval = Date().timeIntervalSince1970 * 1000 // let localTime = ("\(timeStamp)" as NSString).aci_encrypt() // self.HTTPHeaders.set(object: localTime, forKey: "verger") // } // // fileprivate func printReqeustParams(_ URLString : String,parameters : [String : Any]?) { // if isDebugMode() { // let headerDict = self.HTTPHeaders // NJLog("请求头 : \n \(headerDict) \n ") // let url : String = "total url: \(URLString) \n " // NJLog(url) // if let dict = parameters { // NJLog("请求参数 : \n \(dict) \n ") // } // } // } // // /// 打印请求结果内容到控制台 // fileprivate static func printResponseData(_ json : JSON?, method : String) { // if let dict = json { // if isDebugMode() { // var jsonString = dict.rawString() ?? "" // if jsonString.contains("\\") { // jsonString = jsonString.replacingOccurrences(of: "\\", with: "") // } // if jsonString.contains("\\/") { // jsonString = jsonString.replacingOccurrences(of: "\\/", with: "/") // } // NJLog("method = \(method) res = \(jsonString)") // } // } // } // // fileprivate func reqeustWithURL(_ URLString : String,parameters : [String : Any]?,httpMethod : HTTPMethod,completionHandler : @escaping EasyReqeustSuccess) { // appendHTTPHeaders() // let service = "\(String(describing: ServerConfig.httpServer))\(URLString)" // ///打印请求参数到控制台 // printReqeustParams(service, parameters: parameters) // // EasyRequest.shared.sessionManager.request(service, method: httpMethod, parameters: parameters, encoding: URLEncoding.default, headers: self.HTTPHeaders as? HTTPHeaders).responseData { (response) in // if response.result.isSuccess { ///请求成功 // // if let data = response.result.value { // // let object = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String : Any] // var json : JSON? // if object == nil { //转json失败后尝试用jsonstring 处理 // let jsonString = String(data: data, encoding: .utf8) // json = JSON(parseJSON: jsonString ?? "") // } else { // json = JSON(object ?? [:]) // } // //打印请求结果 // EasyRequest.printResponseData(json, method: response.request?.url?.absoluteString ?? "") // let errorNo : Int = json?["errorNo"].intValue ?? 500 // let resultModel = EasyResult() // if errorNo == 0 { //请求结果正常 // if let content = json?["content"].dictionary { // resultModel.dictionary = JSON(content) // } // if let content = json?["content"].array { // let obj = content // resultModel.array = obj // } // if let content = json?["content"].string { // resultModel.stringValue = content // } // resultModel.data = object // } else { ///请求结果出错 // let errorMessage : String = json?["errorContent"].stringValue ?? "请求错误,请稍后再试" // MBProgressHUD.showOnlyText(errorMessage, view: UIApplication.shared.keyWindow) // let error = NSError(domain: errorMessage, code: errorNo, userInfo: nil) // resultModel.error = error // } // resultModel.statusCode = errorNo // completionHandler(resultModel) // } else { // let resultModel = EasyResult() // resultModel.error = response.result.error as NSError? // resultModel.statusCode = resultModel.error?.code ?? 500 // completionHandler(resultModel) // } // // } else { // let resultModel = EasyResult() // resultModel.error = response.result.error as NSError? // resultModel.statusCode = resultModel.error?.code ?? 500 // completionHandler(resultModel) // } // } // // // } // //} // // // // // // //
4c94f15bab7550e3983aac6c827cb063
41.029703
207
0.52662
false
false
false
false
JGiola/swift
refs/heads/main
test/IRGen/enum_large.swift
apache-2.0
8
// RUN: %swift-target-frontend -emit-irgen %s | %FileCheck %s // REQUIRES: PTRSIZE=64 public struct SpareBits { var o: UInt64 = 0 var x: UInt8 = 0 var y: UInt64 = 0 var x_2: UInt8 = 0 var y_2: UInt64 = 0 var x_3: UInt8 = 0 var y_3: UInt64 = 0 var x_4: UInt8 = 0 var y_4: UInt64 = 0 var x_5: UInt8 = 0 var y_5: UInt64 = 0 var x_6: UInt8 = 0 var y_6: UInt64 = 0 } public class MyClass {} public enum Multipayload { case a case b(MyClass) case c(SpareBits) case e case f case g } @inline(never) func dump<T>(_ t : T) {} func dumpInt(_ i: Int) {} // CHECK-LABEL: define{{.*}} @"$s10enum_large6testIt1eyAA12MultipayloadO_tF"{{.*}}{ // CHECK: switch i8 {{%[^,]+}}, label {{%[^,]+}} [ // CHECK: i8 0, label {{%[^,]+}} // CHECK: i8 1, label {{%[^,]+}} // CHECK: i8 2, label %[[REGISTER_41:[^,]+]] // CHECK: [[REGISTER_41]]: // CHECK: br i1 {{%[^,]+}}, label {{%[^,]+}}, label %[[REGISTER_67:[^,]+]] // CHECK: [[REGISTER_67]]: // CHECK: br i1 {{%[^,]+}}, label {{%[^,]+}}, label %[[REGISTER_93:[^,]+]] // CHECK: [[REGISTER_93]]: // CHECK: br i1 {{%[^,]+}}, label {{%[^,]+}}, label %[[REGISTER_119:[^,]+]] // CHECK: [[REGISTER_119]]: // CHECK: br i1 {{%[^,]+}}, label %[[REGISTER_149:[^,]+]], label {{%[^,]+}} // CHECK: [[REGISTER_149]] // CHECK: call swiftcc void @"$s10enum_large7dumpIntyySiF"(i64 8675309) public func testIt(e : Multipayload) { switch e { case .a, .e, .f, .g: dumpInt(8675309) case .b(let c): dump(c) case .c(let s): dump(s) } }
036de30c6ce257e9c38f8998bb756206
26.737705
83
0.478723
false
false
false
false
TurfDb/Turf
refs/heads/master
Turf/SQLiteAdapter/SQLiteCollection.swift
mit
1
//TODO Add some better error handling checking binds etc internal final class SQLiteCollection { // MARK: Internal properties private(set) var allValuesInCollectionStmt: OpaquePointer? = nil // MARK: Private properties private let db: OpaquePointer private let collectionName: String private var numberOfKeysInCollectionStmt: OpaquePointer? = nil private var numberOfKeysAtVersionInCollectionStmt: OpaquePointer? = nil private var keysInCollectionStmt: OpaquePointer? = nil private var valueDataForKeyStmt: OpaquePointer? = nil private var rowIdForKeyStmt: OpaquePointer? = nil private var insertValueDataStmt: OpaquePointer? = nil private var updateValueDataStmt: OpaquePointer? = nil private var removeValueStmt: OpaquePointer? = nil private var removeAllValuesStmt: OpaquePointer? = nil private var allKeysAndValuesStmt: OpaquePointer? = nil // MARK: Object lifecycle init(db: OpaquePointer, collectionName: String) throws { self.db = db self.collectionName = collectionName try setUpAllValuesInCollectionStmt() try setUpNumberOfKeysInCollectionStmt() try setUpNumberOfKeysAtVersionInCollectionStmt() try setUpKeysInCollectionStmt() try setUpValueDataForKeyStmt() try setUpRowIdForKeyStmt() try setUpInsertValueDataStmt() try setUpUpdateValueDataStmt() try setUpRemoveValueInCollectionStmt() try setUpRemoveAllValuesInCollectionStmt() } deinit { sqlite3_finalize(allValuesInCollectionStmt) sqlite3_finalize(numberOfKeysInCollectionStmt) sqlite3_finalize(numberOfKeysAtVersionInCollectionStmt) sqlite3_finalize(keysInCollectionStmt) sqlite3_finalize(valueDataForKeyStmt) sqlite3_finalize(rowIdForKeyStmt) sqlite3_finalize(insertValueDataStmt) sqlite3_finalize(updateValueDataStmt) sqlite3_finalize(removeValueStmt) sqlite3_finalize(removeAllValuesStmt) sqlite3_finalize(allKeysAndValuesStmt) } // MARK: Internal methods /** Create a new table called `name`. */ static func createCollectionTableNamed(_ name: String, db: OpaquePointer) throws { if sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS `\(name)` (" + " key TEXT NOT NULL UNIQUE," + " valueData BLOB," + " schemaVersion INTEGER DEFAULT 0" + ");" + "CREATE INDEX IF NOT EXISTS `\(name)_schemaVersion_idx` ON \(name) (schemaVersion);", nil, nil, nil).isNotOK { throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db))) } } /** Drop a collection table. */ static func dropCollectionTableNamed(_ name: String, db: OpaquePointer) throws { if sqlite3_exec(db, "DROP TABLE IF EXISTS `\(name)`;", nil, nil, nil).isNotOK { throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db))) } } /** Drop all collection tables, leaving only Turf tables - returns: Names of dropped tables */ static func dropAllCollectionTables(db: OpaquePointer) throws -> [String] { let collectionTableNames = collectionNames(db: db) for name in collectionTableNames { try dropCollectionTableNamed(name, db: db) } return collectionTableNames } /** - returns: Count of user collections in the database. */ static func numberOfCollections(_ db: OpaquePointer) -> UInt { var stmt: OpaquePointer? = nil defer { sqlite3_finalize(stmt) } guard sqlite3_prepare_v2(db, "SELECT COUNT(name) FROM sqlite_master where type='table' AND name NOT LIKE ?;", -1, &stmt, nil).isOK else { return 0 } let notLikeTableNameIndex = SQLITE_FIRST_BIND_COLUMN let numberOfCollectionsIndex = SQLITE_FIRST_COLUMN sqlite3_bind_text(stmt, notLikeTableNameIndex, "\(TurfTablePrefix)%", -1, SQLITE_TRANSIENT) var numberOfCollections: UInt = 0 if sqlite3_step(stmt).hasRow { numberOfCollections = UInt(sqlite3_column_int64(stmt, numberOfCollectionsIndex)) } return numberOfCollections } /** - returns: Names of each user collection in the database. */ static func collectionNames(db: OpaquePointer) -> [String] { var stmt: OpaquePointer? = nil defer { sqlite3_reset(stmt) } guard sqlite3_prepare_v2(db, "SELECT name, type FROM sqlite_master WHERE type='table' AND name NOT LIKE ?;", -1, &stmt, nil).isOK else { return [] } let notLikeTableNameIndex = SQLITE_FIRST_BIND_COLUMN let nameColumnIndex = SQLITE_FIRST_COLUMN sqlite3_bind_text(stmt, notLikeTableNameIndex, "\(TurfTablePrefix)%", -1, SQLITE_TRANSIENT) var collectionNames = [String]() var result = sqlite3_step(stmt) while(result.hasRow) { if let name = String(validatingUTF8: UnsafePointer(sqlite3_column_text(stmt, nameColumnIndex))) { collectionNames.append(name) } result = sqlite3_step(stmt) } return collectionNames } /** - returns: Number of keys in `collection`. */ func numberOfKeysInCollection() -> UInt { defer { sqlite3_reset(numberOfKeysInCollectionStmt) } let numberOfKeysIndex = SQLITE_FIRST_COLUMN var numberOfKeys: UInt = 0 if sqlite3_step(numberOfKeysInCollectionStmt).hasRow { numberOfKeys = UInt(sqlite3_column_int64(numberOfKeysInCollectionStmt, numberOfKeysIndex)) } return numberOfKeys } /** - returns: Number of keys in `collection`. */ func numberOfKeysInCollectionAtSchemaVersion(_ schemaVersion: UInt64) -> UInt { defer { sqlite3_reset(numberOfKeysAtVersionInCollectionStmt) } let schemaVersionIndex = SQLITE_FIRST_BIND_COLUMN let numberOfKeysIndex = SQLITE_FIRST_COLUMN sqlite3_bind_int64(numberOfKeysAtVersionInCollectionStmt, schemaVersionIndex, Int64(schemaVersion)) var numberOfKeys: UInt = 0 if sqlite3_step(numberOfKeysInCollectionStmt).hasRow { numberOfKeys = UInt(sqlite3_column_int64(numberOfKeysInCollectionStmt, numberOfKeysIndex)) } return numberOfKeys } /** - returns: All keys in `collection`. */ func keysInCollection() -> [String] { defer { sqlite3_reset(keysInCollectionStmt) } let keyColumnIndex = SQLITE_FIRST_COLUMN var keys = [String]() var result = sqlite3_step(keysInCollectionStmt) while(result.hasRow) { if let key = String(validatingUTF8: UnsafePointer(sqlite3_column_text(keysInCollectionStmt, keyColumnIndex))) { keys.append(key) } result = sqlite3_step(keysInCollectionStmt) } return keys } func enumerateKeySchemaVersionAndValueDataInCollection(_ enumerate: (String, UInt64, Data) -> Bool) { defer { sqlite3_reset(allKeysAndValuesStmt) } let keyColumnIndex = SQLITE_FIRST_COLUMN let schemaVersionColumnIndex = SQLITE_FIRST_COLUMN + 1 let valueDataColumnIndex = SQLITE_FIRST_COLUMN + 2 var result = sqlite3_step(keysInCollectionStmt) while(result.hasRow) { if let key = String(validatingUTF8: UnsafePointer(sqlite3_column_text(keysInCollectionStmt, keyColumnIndex))) { let valueData: Data if let bytes = sqlite3_column_blob(valueDataForKeyStmt, valueDataColumnIndex){ let bytesLength = Int(sqlite3_column_bytes(valueDataForKeyStmt, valueDataColumnIndex)) valueData = Data(bytes: bytes, count: bytesLength) } else { valueData = Data() } let schemaVersion = UInt64(sqlite3_column_int64(valueDataForKeyStmt, schemaVersionColumnIndex)) if !enumerate(key, schemaVersion, valueData) { break } } result = sqlite3_step(keysInCollectionStmt) } } /** - parameter key: Primary key of the value. - parameter collection: Collection name. - returns: Serialized value and schema version of the persisted value. */ func valueDataForKey(_ key: String) -> (valueData: Data, schemaVersion: UInt64)? { defer { sqlite3_reset(valueDataForKeyStmt) } let keyIndex = SQLITE_FIRST_BIND_COLUMN let valueDataColumnIndex = SQLITE_FIRST_COLUMN let schemaVersionColumnIndex = SQLITE_FIRST_COLUMN + 1 sqlite3_bind_text(valueDataForKeyStmt, keyIndex, key, -1, SQLITE_TRANSIENT) if sqlite3_step(valueDataForKeyStmt).hasRow { let valueData: Data if let bytes = sqlite3_column_blob(valueDataForKeyStmt, valueDataColumnIndex){ let bytesLength = Int(sqlite3_column_bytes(valueDataForKeyStmt, valueDataColumnIndex)) valueData = Data(bytes: bytes, count: bytesLength) } else { valueData = Data() } let schemaVersion = UInt64(sqlite3_column_int64(valueDataForKeyStmt, schemaVersionColumnIndex)) return (valueData: valueData, schemaVersion: schemaVersion) } return nil } /** - parameter key: Primary key. - parameter collection: Collection name. - returns: Internal sqlite rowid column value. */ func rowIdForKey(_ key: String) -> Int64? { defer { sqlite3_reset(rowIdForKeyStmt) } let keyIndex = SQLITE_FIRST_BIND_COLUMN let rowIdIndex = SQLITE_FIRST_COLUMN sqlite3_bind_text(rowIdForKeyStmt, keyIndex, key, -1, SQLITE_TRANSIENT) var rowId: Int64? = nil if sqlite3_step(rowIdForKeyStmt).hasRow { rowId = sqlite3_column_int64(rowIdForKeyStmt, rowIdIndex) } return rowId } /** Set valueData for key and record the schema version of the data to support migrations. - parameter valueData: Serialized value bytes. - parameter valueSchemaVersion: Schema version of the valueData. - parameter key: Primary key. - paramter collection: Collection name. - returns: The row id and type of upsert operation (.Insert or .Update). */ func setValueData(_ valueData: Data, valueSchemaVersion: UInt64, forKey key: String) throws -> SQLiteRowChangeType { var stmt: OpaquePointer? = nil if let rowId = rowIdForKey(key) { defer { sqlite3_reset(updateValueDataStmt) } let dataIndex = SQLITE_FIRST_BIND_COLUMN let schemaVersionIndex = SQLITE_FIRST_BIND_COLUMN + 1 let keyIndex = SQLITE_FIRST_BIND_COLUMN + 2 sqlite3_bind_blob(updateValueDataStmt, dataIndex, (valueData as NSData).bytes, Int32(valueData.count), nil) sqlite3_bind_int64(updateValueDataStmt, schemaVersionIndex, Int64(valueSchemaVersion)) sqlite3_bind_text(updateValueDataStmt, keyIndex, key, -1, SQLITE_TRANSIENT) if sqlite3_step(updateValueDataStmt).isNotDone { throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db))) } else { return .update(rowId: rowId) } } else { defer { sqlite3_reset(insertValueDataStmt) } let keyIndex = SQLITE_FIRST_BIND_COLUMN let dataIndex = SQLITE_FIRST_BIND_COLUMN + 1 let schemaVersionIndex = SQLITE_FIRST_BIND_COLUMN + 2 sqlite3_bind_blob(insertValueDataStmt, dataIndex, (valueData as NSData).bytes, Int32(valueData.count), nil) sqlite3_bind_int64(insertValueDataStmt, schemaVersionIndex, Int64(valueSchemaVersion)) sqlite3_bind_text(insertValueDataStmt, keyIndex, key, -1, SQLITE_TRANSIENT) if sqlite3_step(insertValueDataStmt).isNotDone { throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db))) } else { return .insert(rowId: sqlite3_last_insert_rowid(db)) } } } func removeValueWithKey(_ key: String) throws { defer { sqlite3_reset(removeAllValuesStmt) } let keyIndex = SQLITE_FIRST_BIND_COLUMN sqlite3_bind_text(insertValueDataStmt, keyIndex, key, -1, SQLITE_TRANSIENT) if sqlite3_step(removeAllValuesStmt).isNotDone { throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db))) } } func removeAllValues() throws { defer { sqlite3_reset(removeAllValuesStmt) } if sqlite3_step(removeAllValuesStmt).isNotDone { throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db))) } } // MARK: Private methods private func setUpAllValuesInCollectionStmt() throws { var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(db, "SELECT valueData, schemaVersion FROM `\(collectionName)`", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.allValuesInCollectionStmt = stmt } private func setUpRemoveValueInCollectionStmt() throws { var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(db, "DELETE FROM `\(collectionName)` WHERE key=?;", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.removeValueStmt = stmt } private func setUpRemoveAllValuesInCollectionStmt() throws { var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(db, "DELETE FROM `\(collectionName)`;", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.removeAllValuesStmt = stmt } private func setUpNumberOfKeysInCollectionStmt() throws { var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(db, "SELECT COUNT(key) FROM `\(collectionName)`", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.numberOfKeysInCollectionStmt = stmt } private func setUpNumberOfKeysAtVersionInCollectionStmt() throws { var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(db, "SELECT COUNT(key) FROM `\(collectionName)` WHERE schemaVersion=?", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.numberOfKeysAtVersionInCollectionStmt = stmt } private func setUpKeysInCollectionStmt() throws { var stmt: OpaquePointer? = nil defer { sqlite3_reset(stmt) } guard sqlite3_prepare_v2(db, "SELECT key FROM `\(collectionName)`", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.keysInCollectionStmt = stmt } private func setUpValueDataForKeyStmt() throws { var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(db, "SELECT valueData, schemaVersion FROM `\(collectionName)` WHERE key=? LIMIT 1", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.valueDataForKeyStmt = stmt } private func setUpRowIdForKeyStmt() throws { var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(db, "SELECT rowid FROM `\(collectionName)` WHERE key=?;", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.rowIdForKeyStmt = stmt } private func setUpInsertValueDataStmt() throws { var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(db, "INSERT INTO `\(collectionName)` (key, valueData, schemaVersion) VALUES (?,?,?);", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.insertValueDataStmt = stmt } private func setUpUpdateValueDataStmt() throws { var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(db, "UPDATE `\(collectionName)` SET valueData=?,schemaVersion=? WHERE key=?;", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.updateValueDataStmt = stmt } private func setUpAllKeysAndValuesStmt() throws { var stmt: OpaquePointer? = nil guard sqlite3_prepare_v2(db, "SELECT key, valueData, schemaVersion FROM `\(collectionName)`", -1, &stmt, nil).isOK else { throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db))) } self.allKeysAndValuesStmt = stmt } }
d9ef90839101cceee2f381c5fc2e58e3
37.091106
147
0.651253
false
false
false
false
Vaseltior/FluableView
refs/heads/master
FluableView/Sources/TableView/TableCellFactory.swift
mit
1
/* Copyright 2011-present Samuel GRAU 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. */ // // FluableView : TableCellFactory.swift // import Foundation /** A protocol for TableViewModel to fetch rows to be displayed for the table view. */ public protocol TableViewModelDelegate { /** Fetches a table view cell at a given index path with a given object. The implementation of this method will generally use object to customize the cell. - parameter tableViewModel: the model - parameter tableView: the table view - parameter indexPath: the location of the cell in the tableview - parameter object: the object - returns: A table view cell object */ func tableViewModel( tableViewModel: Model, cellForTableView tableView: UITableView, atIndexPath indexPath: NSIndexPath, withObject object: TableCellObject) throws -> TableViewCell } enum TableCellFactoryError: ErrorType { case InvalidTableViewCellConformance(message: String) case UnregisteredTableView(message: String) } public class TableCellFactory { // MARK: - Initialization - public static let sharedInstance = TableCellFactory() private init() {} // MARK: - Dequeuing - /** Creates a cell from a given object if and only if the object conforms to the AVNICellObject protocol. This method signature matches the AVNITableViewModelDelegate method so that you can set this factory as the model's delegate: If you would like to customize the factory's output, implement the model's delegate method and call the factory method. Remember that if the factory doesn't know how to map the object to a cell it will return nil. - parameter tableViewModel: tableViewModel object - parameter tableView: tableview - parameter indexPath: location of the wanted cell in the table view - parameter object: the object that will tell which cell type to use - throws: this method can throw error when the table view is not yet registered or if the involved table view cells are not `TableViewCell` - returns: A table view cell object */ public func tableViewModel( tableViewModel: Model, cellForTableView tableView: UITableView, atIndexPath indexPath: NSIndexPath, withObject object: TableCellObject) throws -> TableViewCell { // Only AVNICellObject-conformant objects may pass. let cellClass: UITableViewCell.Type = object.tableCellClass(indexPath) return try self.cellWithClass(cellClass, tableView: tableView, object: object, indexPath: indexPath) } /** Description - parameter cellClass: cellClass description - parameter tableView: tableView description - parameter object: object description - parameter indexPath: indexPath description - throws: `InvalidTableViewCellConformance` error if the table view dequeue a `UITableViewCell` which is not a `TableViewCell` - returns: a `TableViewCell` */ public func cellWithClass( cellClass: UITableViewCell.Type, tableView: UITableView, object: TableCellObject, indexPath: NSIndexPath) throws -> TableViewCell { // Configure the dequeue identifier var identifier: String = NSStringFromClass(cellClass) if object.shouldAppendClassNameToReuseIdentifier() { identifier += String(object.dynamicType) } // Better improve this tableView.registerClass(cellClass, forCellReuseIdentifier: identifier) guard let cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? TableViewCell else { throw TableCellFactoryError.InvalidTableViewCellConformance( message: "The returned tableview cell should be a subclass of `TableViewCell`" ) } // Allow the cell to configure itself with the object's information. if cell.shouldUpdateCellWithObject(object, indexPath: indexPath) { cell.updateCellWithObject(object, indexPath: indexPath) } return cell } // MARK: - Registering/Unregistering - // MARK: Properties typealias ClassSet = Set<String> typealias ClassRegistrationDictionary = [UITableView: ClassSet] var observedTableViews: Set<UITableView> = Set<UITableView>() var classRegistrations: ClassRegistrationDictionary = ClassRegistrationDictionary() // MARK: Functions /** Register the table view and prepare the registered classes storage - parameter tableView: the tableview to register */ public func registerTableView(tableView: UITableView) { // If it already exist, we have nothing to do here, we just return if self.observedTableViews.contains(tableView) { return } // Add the given table view to the set of observed table views self.observedTableViews.insert(tableView) // And initiate the set of classes self.classRegistrations[tableView] = ClassSet() } /** Unregister the table view and the registered classes associated to that table view - parameter tableView: the tableview to unregister */ public func unregisterTableView(tableView: UITableView) { // Remove the value for the given tableview self.classRegistrations.removeValueForKey(tableView) // Remove the tableview from the set of observed table views self.observedTableViews.remove(tableView) } }
36246bc97885bf6c2291168684f793ce
32.901734
111
0.730605
false
false
false
false
glessard/async-deferred
refs/heads/main
Source/deferred/deferred-extras.swift
mit
3
// // deferred-extras.swift // deferred // // Created by Guillaume Lessard on 2015-07-13. // Copyright © 2015-2020 Guillaume Lessard. All rights reserved. // import Dispatch /* Definitions that rely on or extend Deferred, but do not need the fundamental, private stuff. */ extension Deferred { /// A way to cause the `Deferred` to switch to `.execute` state in a fluent manner /// /// - returns itself, guaranteed to no longer be in the `.waiting` state. public var execute: Deferred { self.beginExecution() return self } } extension Deferred { // MARK: onValue: execute a task when (and only when) a computation succeeds /// Enqueue a closure to be performed asynchronously, when and only when `self` becomes resolved with a value /// /// This is a simple specialization of `notify` that runs only on the happy (success) path. /// /// - parameter queue: the `DispatchQueue` on which to execute the notification; defaults to `self`'s queue. /// - parameter handler: the closure to be enqueued /// - parameter value: the value of the just-resolved `Deferred` @inlinable public func onValue(queue: DispatchQueue? = nil, handler: @escaping (_ value: Success) -> Void) { notify(queue: queue, handler: { if case .success(let value) = $0 { handler(value) } }) } // MARK: onError: execute a task when (and only when) a computation fails /// Enqueue a closure to be performed asynchronously, when and only when `self` becomes resolved with an error /// /// This is a simple specialization of `notify` that runs only on the error path. Note that if `Failure == Never`, /// this simply calls `beginExecution()` then returns, as the closure would never be run. /// /// - parameter queue: the `DispatchQueue` on which to execute the notification; defaults to `self`'s queue. /// - parameter task: the closure to be enqueued /// - parameter error: the error from the just-resolved `Deferred` @inlinable public func onError(queue: DispatchQueue? = nil, handler: @escaping (_ error: Failure) -> Void) { if Failure.self == Never.self { beginExecution() return } notify(queue: queue, handler: { if case .failure(let error) = $0 { handler(error) } }) } } // MARK: enqueuing: use a different queue or QoS for notifications extension Deferred { /// Get a `Deferred` that will have the same `Result` as `self` once resolved, /// but will use a different queue for its notifications /// /// - parameter queue: the queue to be used by the returned `Deferred` /// - returns: a new `Deferred` whose notifications will execute on `queue` public func enqueuing(on queue: DispatchQueue) -> Deferred { if let result = self.peek() { return Deferred(queue: queue, result: result) } return Deferred(queue: queue) { resolver in self.notify(queue: queue, boostQoS: false, handler: resolver.resolve) resolver.retainSource(self) } } /// Get a `Deferred` that will have the same `Result` as `self` once resolved, /// but will use a different queue at the specified QoS for its notifications /// /// - parameter qos: the QoS to be used by the returned `Deferred` /// - parameter serially: whether the notifications should be dispatched on a serial queue; defaults to `true` /// - returns: a new `Deferred` whose notifications will execute at QoS `qos` public func enqueuing(at qos: DispatchQoS) -> Deferred { let queue = DispatchQueue(label: "\(self.queue.label)-enqueuing", qos: qos, target: self.queue) return enqueuing(on: queue) } } // MARK: map: asynchronously transform a `Deferred` into another extension Deferred { /// Enqueue a transform to be computed asynchronously after `self` becomes resolved succesfully, creating a new `Deferred` /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter value: the value to be transformed for the new `Deferred` public func map<Other>(queue: DispatchQueue? = nil, transform: @escaping (_ value: Success) -> Other) -> Deferred<Other, Failure> { return Deferred<Other, Failure>(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } resolver.resolve(result.map(transform)) } resolver.retainSource(self) } } /// Enqueue a transform to be computed asynchronously after `self` becomes resolved succesfully, creating a new `Deferred` /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter value: the value to be transformed for the new `Deferred` public func map<Other>(qos: DispatchQoS, transform: @escaping (_ value: Success) -> Other) -> Deferred<Other, Failure> { let queue = DispatchQueue(label: "\(self.queue.label)-map", qos: qos, target: self.queue) return map(queue: queue, transform: transform) } /// Enqueue a transform to be computed asynchronously after `self` becomes resolved succesfully, creating a new `Deferred` /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter transform: the throwing transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter value: the value to be transformed for the new `Deferred` public func tryMap<Other>(queue: DispatchQueue? = nil, transform: @escaping (_ value: Success) throws -> Other) -> Deferred<Other, Error> { return Deferred<Other, Error>(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } resolver.resolve(Result(catching: { try transform(result.get()) })) } resolver.retainSource(self) } } /// Enqueue a transform to be computed asynchronously after `self` becomes resolved succesfully, creating a new `Deferred` /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter transform: the throwing transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter value: the value to be transformed for the new `Deferred` public func tryMap<Other>(qos: DispatchQoS, transform: @escaping (_ value: Success) throws -> Other) -> Deferred<Other, Error> { let queue = DispatchQueue(label: "\(self.queue.label)-trymap", qos: qos, target: self.queue) return tryMap(queue: queue, transform: transform) } /// Enqueue a transform to be computed asynchronously after `self` becomes resolved with a `Failure`, creating a new `Deferred` /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter error: the `Failure` to be transformed for the new `Deferred` public func mapError<OtherFailure>(queue: DispatchQueue? = nil, transform: @escaping (_ error: Failure) -> OtherFailure) -> Deferred<Success, OtherFailure> { return Deferred<Success, OtherFailure>(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } resolver.resolve(result.mapError(transform)) } resolver.retainSource(self) } } /// Enqueue a transform to be computed asynchronously after `self` becomes resolved with a `Failure`, creating a new `Deferred` /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter error: the `Failure` to be transformed for the new `Deferred` public func mapError<OtherFailure>(qos: DispatchQoS, transform: @escaping (_ error: Failure) -> OtherFailure) -> Deferred<Success, OtherFailure> { let queue = DispatchQueue(label: "\(self.queue.label)-maperror", qos: qos, target: self.queue) return mapError(queue: queue, transform: transform) } /// Map this `Deferred`'s `Failure` type to `Error` (any Error). public var withAnyError: Deferred<Success, Error> { return Deferred<Success, Error>(queue: queue) { resolver in self.notify(queue: nil) { result in resolver.resolve(result.withAnyError) } resolver.retainSource(self) } } } extension Deferred where Failure == Never { /// Set this `Deferred`'s `Failure` type to `NewError` /// /// - parameter to: the type of `Failure` to be used for the returned `Result` /// - returns: a `Result` where the `Failure` type is unconditionally converted to `NewError` public func setFailureType<NewError: Error>(to: NewError.Type) -> Deferred<Success, NewError> { return Deferred<Success, NewError>(queue: queue) { resolver in self.notify(queue: nil) { result in resolver.resolve(result.setFailureType(to: NewError.self)) } resolver.retainSource(self) } } } // MARK: flatMap: asynchronously transform a `Deferred` into another extension Deferred { /// Enqueue a transform to be computed asynchronously after `self` becomes resolved. /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter value: the value to be transformed for the new `Deferred` public func flatMap<Other>(queue: DispatchQueue? = nil, transform: @escaping(_ value: Success) -> Deferred<Other, Failure>) -> Deferred<Other, Failure> { return Deferred<Other, Failure>(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } switch result { case .success(let value): let transformed = transform(value) if let transformed = transformed.peek() { resolver.resolve(transformed) } else { transformed.notify(queue: queue, handler: resolver.resolve) resolver.retainSource(transformed) } case .failure(let error): resolver.resolve(error: error) } } resolver.retainSource(self) } } /// Enqueue a transform to be computed asynchronously after `self` becomes resolved. /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter value: the value to be transformed for the new `Deferred` public func flatMap<Other>(qos: DispatchQoS, transform: @escaping (_ value: Success) -> Deferred<Other, Failure>) -> Deferred<Other, Failure> { let queue = DispatchQueue(label: "\(self.queue.label)-flatmap", qos: qos, target: self.queue) return flatMap(queue: queue, transform: transform) } /// Enqueue a transform to be computed asynchronously after `self` becomes resolved. /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter value: the value to be transformed for the new `Deferred` public func tryFlatMap<Other>(queue: DispatchQueue? = nil, transform: @escaping (_ value: Success) throws -> Deferred<Other, Error>) -> Deferred<Other, Error> { return Deferred<Other, Error>(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } do { let value = try result.get() let transformed = try transform(value) if let transformed = transformed.peek() { resolver.resolve(transformed) } else { transformed.notify(queue: queue, handler: resolver.resolve) resolver.retainSource(transformed) } } catch { resolver.resolve(error: error) } } resolver.retainSource(self) } } /// Enqueue a transform to be computed asynchronously after `self` becomes resolved. /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter value: the value to be transformed for the new `Deferred` public func tryFlatMap<Other>(qos: DispatchQoS, transform: @escaping (_ value: Success) throws -> Deferred<Other, Error>) -> Deferred<Other, Error> { let queue = DispatchQueue(label: "\(self.queue.label)-flatmap", qos: qos, target: self.queue) return tryFlatMap(queue: queue, transform: transform) } /// Enqueue a transform to be computed asynchronously if and when `self` becomes resolved with an error. /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter error: the Error to be transformed for the new `Deferred` public func flatMapError<OtherFailure>(queue: DispatchQueue? = nil, transform: @escaping (_ error: Failure) -> Deferred<Success, OtherFailure>) -> Deferred<Success, OtherFailure> { return Deferred<Success, OtherFailure>(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } switch result { case let .success(value): resolver.resolve(value: value) case let .failure(error): let transformed = transform(error) if let transformed = transformed.peek() { resolver.resolve(transformed) } else { transformed.notify(queue: queue, handler: resolver.resolve) resolver.retainSource(transformed) } } } resolver.retainSource(self) } } /// Enqueue a transform to be computed asynchronously if and when `self` becomes resolved with an error. /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter error: the Error to be transformed for the new `Deferred` public func flatMapError<OtherFailure>(qos: DispatchQoS, transform: @escaping(_ error: Failure) -> Deferred<Success, OtherFailure>) -> Deferred<Success, OtherFailure> { let queue = DispatchQueue(label: "\(self.queue)-flatmaperror", qos: qos, target: self.queue) return flatMapError(queue: queue, transform: transform) } } extension Deferred { /// Flatten a `Deferred<Deferred<Success, Failure>, Failure>` to a `Deferred<Success, Failure>` /// /// In the right conditions, acts like a fast path for a flatMap with no transform. /// /// - parameter queue: the `DispatchQueue` onto which the new `Deferred` should /// dispatch notifications; use `self.queue` if `nil` /// - returns: a flattened `Deferred` public func flatten<Other>(queue: DispatchQueue? = nil) -> Deferred<Other, Failure> where Success == Deferred<Other, Failure> { if let result = self.peek() { switch result { case .success(let deferred): if let result = deferred.peek() { return Deferred<Other, Failure>(queue: queue ?? self.queue, result: result) } return Deferred<Other, Failure>(queue: queue ?? self.queue) { resolver in deferred.notify(queue: queue, handler: resolver.resolve) resolver.retainSource(deferred) } case .failure(let error): return Deferred<Other, Failure>(queue: queue ?? self.queue, error: error) } } return Deferred<Other, Failure>(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } switch result { case .success(let deferred): if let result = deferred.peek() { resolver.resolve(result) } else { deferred.notify(queue: queue, handler: resolver.resolve) resolver.retainSource(deferred) } case .failure(let error): resolver.resolve(error: error) } } resolver.retainSource(self) } } /// Flatten a `Deferred<Deferred<Success, Failure>, Never>` to a `Deferred<Success, Failure>` /// /// In the right conditions, acts like a fast path for a flatMap with no transform. /// /// - parameter queue: the `DispatchQueue` onto which the new `Deferred` should /// dispatch notifications; use `self.queue` if `nil` /// - returns: a flattened `Deferred` public func flatten<Other, OtherFailure>(queue: DispatchQueue? = nil) -> Deferred<Other, OtherFailure> where Success == Deferred<Other, OtherFailure>, Failure == Never { if let result = self.peek() { switch result { case .success(let deferred): if let result = deferred.peek() { return Deferred<Other, OtherFailure>(queue: queue ?? self.queue, result: result) } return Deferred<Other, OtherFailure>(queue: queue ?? self.queue) { resolver in deferred.notify(queue: queue, handler: resolver.resolve) resolver.retainSource(deferred) } } } return Deferred<Other, OtherFailure>(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } switch result { case .success(let deferred): if let result = deferred.peek() { resolver.resolve(result) } else { deferred.notify(queue: queue, handler: resolver.resolve) resolver.retainSource(deferred) } } } resolver.retainSource(self) } } } extension Deferred { /// Enqueue a transform to be computed asynchronously if and when `self` becomes resolved with an error. /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter error: the Error to be transformed for the new `Deferred` public func recover(queue: DispatchQueue? = nil, transform: @escaping (_ error: Failure) -> Deferred) -> Deferred { return Deferred(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } switch result { case .success: resolver.resolve(result) case let .failure(error): let transformed = transform(error) if let transformed = transformed.peek() { resolver.resolve(transformed) } else { transformed.notify(queue: queue, handler: resolver.resolve) resolver.retainSource(transformed) } } } resolver.retainSource(self) } } /// Enqueue a transform to be computed asynchronously if and when `self` becomes resolved with an error. /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter error: the Error to be transformed for the new `Deferred` public func recover(qos: DispatchQoS, transform: @escaping (_ error: Failure) -> Deferred) -> Deferred { let queue = DispatchQueue(label: "\(self.queue.label)-recover", qos: qos, target: self.queue) return recover(queue: queue, transform: transform) } /// Initialize a `Deferred` with a computation task to be performed in the background /// /// If at first it does not succeed, it will try `attempts` times in total before being resolved with an `Error`. /// /// - parameter attempts: a maximum number of times to attempt `task` /// - parameter qos: the QoS at which the computation (and notifications) should be performed; defaults to the current QoS class. /// - parameter task: the computation to be performed public static func Retrying(_ attempts: Int, qos: DispatchQoS = .current, task: @escaping () -> Deferred) -> Deferred { let queue = DispatchQueue(label: "deferred-retry", qos: qos, target: .global(qos: qos.qosClass)) return Deferred.Retrying(attempts, queue: queue, task: task) } /// Initialize a `Deferred` with a computation task to be performed in the background /// /// If at first it does not succeed, it will try `attempts` times in total before being resolved with an `Error`. /// /// - parameter attempts: a maximum number of times to attempt `task` (must be greater than zero) /// - parameter queue: the `DispatchQueue` on which the computation (and notifications) will be executed /// - parameter task: the computation to be performed public static func Retrying(_ attempts: Int, queue: DispatchQueue, task: @escaping () -> Deferred) -> Deferred { if attempts < 1 { let message = "number of attempts must be greater than 0 in \(#function)" guard let error = Invalidation.invalid(message) as? Failure else { fatalError(message) } return Deferred(error: error) } return (1..<attempts).reduce(task()) { (deferred, _) in deferred.recover(transform: { _ in task() }) } } } extension Deferred where Failure == Error { /// Enqueue a transform to be computed asynchronously if and when `self` becomes resolved with an error. /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter error: the Error to be transformed for the new `Deferred` public func recover(queue: DispatchQueue? = nil, transform: @escaping (_ error: Error) throws -> Success) -> Deferred { return Deferred(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } switch result { case .success: resolver.resolve(result) case let .failure(error): do { let value = try transform(error) resolver.resolve(value: value) } catch { resolver.resolve(error: error) } } } resolver.retainSource(self) } } /// Enqueue a transform to be computed asynchronously if and when `self` becomes resolved with an error. /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter transform: the transform to be performed /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter error: the Error to be transformed for the new `Deferred` public func recover(qos: DispatchQoS, transform: @escaping (_ error: Error) throws -> Success) -> Deferred { let queue = DispatchQueue(label: "\(self.queue.label)-recover", qos: qos, target: self.queue) return recover(queue: queue, transform: transform) } /// Initialize a `Deferred` with a computation task to be performed in the background /// /// If at first it does not succeed, it will try `attempts` times in total before being resolved with an `Error`. /// /// - parameter attempts: a maximum number of times to attempt `task` /// - parameter qos: the QoS at which the computation (and notifications) should be performed; defaults to the current QoS class. /// - parameter task: the computation to be performed public static func Retrying(_ attempts: Int, qos: DispatchQoS = .current, task: @escaping () throws -> Success) -> Deferred { let queue = DispatchQueue(label: "deferred-retry", qos: qos, target: .global(qos: qos.qosClass)) return Deferred.Retrying(attempts, queue: queue, task: task) } /// Initialize a `Deferred` with a computation task to be performed in the background /// /// If at first it does not succeed, it will try `attempts` times in total before being resolved with an `Error`. /// /// - parameter attempts: a maximum number of times to attempt `task` /// - parameter queue: the `DispatchQueue` on which the computation (and notifications) will be executed /// - parameter task: the computation to be performed public static func Retrying(_ attempts: Int, queue: DispatchQueue, task: @escaping () throws -> Success) -> Deferred { if attempts < 1 { let message = "number of attempts must be greater than 0 in \(#function)" return Deferred(queue: queue, error: Invalidation.invalid(message)) } return (1..<attempts).reduce(Deferred(queue: queue, task: task)) { (deferred, _) in deferred.recover(transform: { _ in try task() }) } } } // MARK: apply: modify this `Deferred`'s value using a `Deferred` transform extension Deferred { /// Enqueue a transform to be computed asynchronously after `self` and `transform` become resolved. /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter transform: the transform to be performed, wrapped in a `Deferred` /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter value: the value to be transformed for a new `Deferred` public func apply<Other>(queue: DispatchQueue? = nil, transform: Deferred<(_ value: Success) -> Other, Never>) -> Deferred<Other, Failure> { func applyTransform(_ value: Success, _ transform: Result<(Success) -> Other, Never>, _ resolver: Resolver<Other, Failure>) { switch transform { case .success(let transform): resolver.resolve(value: transform(value)) } } return Deferred<Other, Failure>(queue: queue ?? self.queue) { resolver in self.notify(queue: queue) { result in guard resolver.needsResolution else { return } switch result { case .success(let value): if let transform = transform.peek() { applyTransform(value, transform, resolver) } else { transform.notify(queue: queue) { transform in guard resolver.needsResolution else { return } applyTransform(value, transform, resolver) } resolver.retainSource(transform) } case .failure(let error): resolver.resolve(error: error) } } resolver.retainSource(self) } } /// Enqueue a transform to be computed asynchronously after `self` and `transform` become resolved. /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter transform: the transform to be performed, wrapped in a `Deferred` /// - returns: a `Deferred` reference representing the return value of the transform /// - parameter value: the value to be transformed for a new `Deferred` public func apply<Other>(qos: DispatchQoS, transform: Deferred<(_ value: Success) -> Other, Never>) -> Deferred<Other, Failure> { let queue = DispatchQueue(label: "\(self.queue.label)-apply", qos: qos, target: self.queue) return apply(queue: queue, transform: transform) } } extension Deferred { /// Insert a validation step in a chain of Deferred. /// /// Pass `Success` through if it passes the predicate, otherwise replace it with the error `DeferredError.invalid`. /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter predicate: a predicate that validates the passed-in `Success` by returning a Boolean /// - parameter message: an explanation to add to `DeferredError.invalid`; defaults to the empty `String` /// - returns: a `Deferred` reference holding a validated `Success` /// - parameter value: the value to be validated public func validate(queue: DispatchQueue? = nil, predicate: @escaping (_ value: Success) -> Bool, message: String = "") -> Deferred<Success, Error> { return self.tryMap(queue: queue) { value in guard predicate(value) else { throw Invalidation.invalid(message) } return value } } /// Insert a validation step in a chain of Deferred. /// /// Pass `Success` through if it passes the predicate, otherwise replace it with the error `DeferredError.invalid`. /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter predicate: a predicate that validates the passed-in `Success` by returning a Boolean /// - parameter message: an explanation to add to `DeferredError.invalid`; defaults to the empty `String` /// - returns: a `Deferred` reference holding a validated `Success` /// - parameter value: the value to be validated public func validate(qos: DispatchQoS, predicate: @escaping (_ value: Success) -> Bool, message: String = "") -> Deferred<Success, Error> { let queue = DispatchQueue(label: "\(self.queue.label)-validate", qos: qos, target: self.queue) return validate(queue: queue, predicate: predicate, message: message) } /// Insert a validation step in a chain of Deferred. /// /// Pass `Success` through if the predicate returns normally, otherwise replace it by the `Error` thrown by the predicate. /// /// - parameter queue: the `DispatchQueue` to attach to the new `Deferred`; defaults to `self`'s queue. /// - parameter predicate: a closure that validates the passed-in `Success` by either returning normally or throwing /// - returns: a `Deferred` reference holding a validated `Success` /// - parameter value: the value to be validated public func validate(queue: DispatchQueue? = nil, predicate: @escaping (_ value: Success) throws -> Void) -> Deferred<Success, Error> { return self.tryMap(queue: queue) { value in try predicate(value) return value } } /// Insert a validation step in a chain of Deferred. /// /// Pass `Success` through if the predicate returns normally, otherwise replace it by the `Error` thrown by the predicate. /// /// - parameter qos: the QoS at which to execute the transform and the new `Deferred`'s notifications /// - parameter predicate: a closure that validates the passed-in `Success` by either returning normally or throwing /// - returns: a `Deferred` reference holding a validated `Success` /// - parameter value: the value to be validated public func validate(qos: DispatchQoS, predicate: @escaping (_ value: Success) throws -> Void) -> Deferred<Success, Error> { let queue = DispatchQueue(label: "\(self.queue.label)-validate", qos: qos, target: self.queue) return validate(queue: queue, predicate: predicate) } } extension Optional { /// Create a `Deferred` from this `Optional`. /// /// If `optional` is `nil` then `Deferred` will be resolved with the error `DeferredError.invalid` /// /// - parameter queue: the dispatch queue upon the new `Deferred`'s notifications will be performed public func deferred(queue: DispatchQueue) -> Deferred<Wrapped, Invalidation> { switch self { case .some(let value): return Deferred(queue: queue, value: value) case .none: return Deferred(queue: queue, error: Invalidation.invalid("initialized from a nil Optional")) } } /// Create a `Deferred` from this `Optional`. /// /// If `optional` is `nil` then `Deferred` will be resolved with the error `DeferredError.invalid` /// /// - parameter qos: the QoS at which to perform notifications for the new `Deferred`; defaults to the current QoS class. public func deferred(qos: DispatchQoS = .current) -> Deferred<Wrapped, Invalidation> { let queue = DispatchQueue(label: "deferred", qos: qos, target: .global(qos: qos.qosClass)) return self.deferred(queue: queue) } }
a5c1f2efcd8d95571390d8672256a6b5
38.510274
151
0.651527
false
false
false
false
VladiMihaylenko/omim
refs/heads/master
iphone/Maps/Core/InappPurchase/Impl/BillingPendingTransaction.swift
apache-2.0
1
final class BillingPendingTransaction: NSObject, IBillingPendingTransaction { private var pendingTransaction: SKPaymentTransaction? override init() { super.init() SKPaymentQueue.default().add(self) } deinit { SKPaymentQueue.default().remove(self) } var status: TransactionStatus { var routeTransactions = SKPaymentQueue.default().transactions.filter { var isOk = !Subscription.legacyProductIds.contains($0.payment.productIdentifier) && !Subscription.productIds.contains($0.payment.productIdentifier) if isOk && $0.transactionState == .purchasing { isOk = false Statistics.logEvent("Pending_purchasing_transaction", withParameters: ["productId" : $0.payment.productIdentifier]) } return isOk } if routeTransactions.count > 1 { pendingTransaction = routeTransactions.last routeTransactions.prefix(routeTransactions.count - 1).forEach { SKPaymentQueue.default().finishTransaction($0) } } else if routeTransactions.count == 1 { pendingTransaction = routeTransactions[0] } else { return .none } switch pendingTransaction!.transactionState { case .purchasing, .failed: return .failed case .purchased, .restored, .deferred: return .paid } } func finishTransaction() { guard let transaction = pendingTransaction else { assert(false, "There is no pending transactions") return } SKPaymentQueue.default().finishTransaction(transaction) pendingTransaction = nil } } extension BillingPendingTransaction: SKPaymentTransactionObserver { func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { // Do nothing. Only for SKPaymentQueue.default().transactions to work } }
8aeced7e149f6bbff4bba765fa30be15
30.220339
104
0.696526
false
false
false
false
JesusAntonioGil/OnTheMap
refs/heads/master
OnTheMap/Controllers/Login/LoginViewController.swift
mit
1
// // LoginViewController.swift // OnTheMap // // Created by Jesús Antonio Gil on 28/03/16. // Copyright © 2016 Jesús Antonio Gil. All rights reserved. // import UIKit import PKHUD class LoginViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! //Injected var presenter: LoginPresenterProtocol! var controllerAssembly: ControllerAssembly! //MARK: LIFE CYCLE override func typhoonDidInject() { presenter.delegate = self } override func viewDidLoad() { super.viewDidLoad() HUD.dimsBackground = false HUD.allowsInteraction = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: ACTIONS @IBAction func onLoginButtonTap(sender: AnyObject) { HUD.show(.Progress) presenter.login(emailTextField.text!, password: passwordTextField.text!) } @IBAction func onSignUpButtonTap(sender: AnyObject) { if let requestUrl = NSURL(string: "https://www.udacity.com/account/auth#!/signin") { UIApplication.sharedApplication().openURL(requestUrl) } } } extension LoginViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { if(textField == emailTextField) { passwordTextField.becomeFirstResponder() } else { view.endEditing(true) } return true } } extension LoginViewController: LoginPresenterDelegate { func loginPresenterSuccess() { dispatch_async(dispatch_get_main_queue(),{ HUD.hide() let mapTabBarController: UITabBarController = self.controllerAssembly.mapTabBarController() as! UITabBarController mapTabBarController.modalTransitionStyle = .CrossDissolve self.navigationController?.presentViewController(mapTabBarController, animated: true, completion: nil) }) } func loginPresenterError(error: NSError) { dispatch_async(dispatch_get_main_queue(),{ HUD.show(.Label(error.localizedDescription)) HUD.hide(afterDelay: 2.0) }) } }
3564e6310b6783c2fa7100e1d31b1fc4
24.505495
126
0.645842
false
false
false
false
Navarjun/NA-iOS-Utils
refs/heads/master
UIView-ext.swift
gpl-3.0
1
// // UIView-ext.swift // // Created by Navarjun on 04/11/15. // import UIKit extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } @IBInspectable var borderColor: UIColor? { get { if let cgColor = layer.borderColor { return UIColor(CGColor: cgColor) } else { return nil } } set { layer.borderColor = newValue?.CGColor } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var rotationInDegrees: CGFloat { get { return atan2(transform.b, transform.a) } set { let angleInRads = newValue / 180 * CGFloat(M_PI) transform = CGAffineTransformRotate(transform, angleInRads) } } // MARK: - Layer Shadows @IBInspectable var shadowColor: UIColor? { get { if let cgcolor = layer.shadowColor { return UIColor(CGColor: cgcolor) } return nil } set { layer.shadowColor = newValue?.CGColor } } @IBInspectable var shadowOffset: CGPoint { get { return CGPoint(x: layer.shadowOffset.width, y: layer.shadowOffset.height) } set { layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y) } } @IBInspectable var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } @IBInspectable var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowRadius = newValue } } }
96419834c011d0a3ad7526b612655610
21.688889
85
0.502695
false
false
false
false
cpuu/OTT
refs/heads/master
BlueCapKit/Injectables.swift
mit
1
// // Injectables.swift // BlueCapKit // // Created by Troy Stribling on 4/20/16. // Copyright © 2016 Troy Stribling. All rights reserved. // import Foundation import CoreBluetooth // MARK: - CBCentralManagerInjectable - public protocol CBCentralManagerInjectable { var state : CBCentralManagerState { get } var delegate: CBCentralManagerDelegate? { get set } func scanForPeripheralsWithServices(uuids: [CBUUID]?, options: [String: AnyObject]?) func stopScan() func connectPeripheral(peripheral: CBPeripheralInjectable, options: [String: AnyObject]?) func cancelPeripheralConnection(peripheral: CBPeripheralInjectable) func retrieveConnectedPeripheralsWithServices(serviceUUIDs: [CBUUID]) -> [CBPeripheralInjectable] func retrievePeripheralsWithIdentifiers(identifiers: [NSUUID]) -> [CBPeripheralInjectable] } extension CBCentralManager : CBCentralManagerInjectable { public func connectPeripheral(peripheral: CBPeripheralInjectable, options: [String: AnyObject]?) { self.connectPeripheral(peripheral as! CBPeripheral, options: options) } public func cancelPeripheralConnection(peripheral: CBPeripheralInjectable) { self.cancelPeripheralConnection(peripheral as! CBPeripheral) } public func retrieveConnectedPeripheralsWithServices(serviceUUIDs: [CBUUID]) -> [CBPeripheralInjectable] { let peripherals = self.retrieveConnectedPeripheralsWithServices(serviceUUIDs) as [CBPeripheral] return peripherals.map { $0 as CBPeripheralInjectable } } public func retrievePeripheralsWithIdentifiers(identifiers: [NSUUID]) -> [CBPeripheralInjectable] { let peripherals = self.retrievePeripheralsWithIdentifiers(identifiers) as [CBPeripheral] return peripherals.map { $0 as CBPeripheralInjectable } } } // MARK: - CBPeripheralInjectable - public protocol CBPeripheralInjectable { var name: String? { get } var state: CBPeripheralState { get } var identifier: NSUUID { get } var delegate: CBPeripheralDelegate? { get set } func readRSSI() func discoverServices(services: [CBUUID]?) func discoverCharacteristics(characteristics: [CBUUID]?, forService service: CBServiceInjectable) func setNotifyValue(enabled:Bool, forCharacteristic characteristic: CBCharacteristicInjectable) func readValueForCharacteristic(characteristic: CBCharacteristicInjectable) func writeValue(data:NSData, forCharacteristic characteristic: CBCharacteristicInjectable, type: CBCharacteristicWriteType) func getServices() -> [CBServiceInjectable]? } extension CBPeripheral : CBPeripheralInjectable { public func discoverCharacteristics(characteristics:[CBUUID]?, forService service: CBServiceInjectable) { self.discoverCharacteristics(characteristics, forService: service as! CBService) } public func setNotifyValue(enabled: Bool, forCharacteristic characteristic: CBCharacteristicInjectable) { self.setNotifyValue(enabled, forCharacteristic: characteristic as! CBCharacteristic) } public func readValueForCharacteristic(characteristic: CBCharacteristicInjectable) { self.readValueForCharacteristic(characteristic as! CBCharacteristic) } public func writeValue(data: NSData, forCharacteristic characteristic: CBCharacteristicInjectable, type: CBCharacteristicWriteType) { self.writeValue(data, forCharacteristic: characteristic as! CBCharacteristic, type: type) } public func getServices() -> [CBServiceInjectable]? { guard let services = self.services else { return nil } return services.map{ $0 as CBServiceInjectable } } } // MARK: - CBServiceInjectable - public protocol CBServiceInjectable { var UUID: CBUUID { get } func getCharacteristics() -> [CBCharacteristicInjectable]? } extension CBService : CBServiceInjectable { public func getCharacteristics() -> [CBCharacteristicInjectable]? { guard let characteristics = self.characteristics else { return nil } return characteristics.map{ $0 as CBCharacteristicInjectable } } } // MARK: - CBCharacteristicInjectable - public protocol CBCharacteristicInjectable { var UUID: CBUUID { get } var value: NSData? { get } var properties: CBCharacteristicProperties { get } var isNotifying: Bool { get } } extension CBCharacteristic : CBCharacteristicInjectable {} // MARK: - CBPeripheralManagerInjectable - public protocol CBPeripheralManagerInjectable { var delegate: CBPeripheralManagerDelegate? { get set } var isAdvertising: Bool { get } var state: CBPeripheralManagerState { get } func startAdvertising(advertisementData:[String:AnyObject]?) func stopAdvertising() func addService(service: CBMutableServiceInjectable) func removeService(service: CBMutableServiceInjectable) func removeAllServices() func respondToRequest(request: CBATTRequestInjectable, withResult result: CBATTError) func updateValue(value: NSData, forCharacteristic characteristic: CBMutableCharacteristicInjectable, onSubscribedCentrals centrals: [CBCentralInjectable]?) -> Bool } extension CBPeripheralManager: CBPeripheralManagerInjectable { public func addService(service: CBMutableServiceInjectable) { self.addService(service as! CBMutableService) } public func removeService(service: CBMutableServiceInjectable) { self.removeService(service as! CBMutableService) } public func respondToRequest(request: CBATTRequestInjectable, withResult result: CBATTError) { self.respondToRequest(request as! CBATTRequest, withResult: result) } public func updateValue(value: NSData, forCharacteristic characteristic: CBMutableCharacteristicInjectable, onSubscribedCentrals centrals: [CBCentralInjectable]?) -> Bool { return self.updateValue(value, forCharacteristic: characteristic as! CBMutableCharacteristic, onSubscribedCentrals: centrals as! [CBCentral]?) } } // MARK: - CBMutableServiceInjectable - public protocol CBMutableServiceInjectable : CBServiceInjectable { func setCharacteristics(characteristics: [CBCharacteristicInjectable]?) } extension CBMutableService : CBMutableServiceInjectable { public func setCharacteristics(characteristics: [CBCharacteristicInjectable]?) { self.characteristics = characteristics?.map { $0 as! CBCharacteristic } } } // MARK: - CBMutableCharacteristicInjectable - public protocol CBMutableCharacteristicInjectable : CBCharacteristicInjectable { var permissions: CBAttributePermissions { get } } extension CBMutableCharacteristic : CBMutableCharacteristicInjectable {} // MARK: - CBATTRequestInjectable - public protocol CBATTRequestInjectable { var offset: Int { get } var value: NSData? { get set } func getCharacteristic() -> CBCharacteristicInjectable } extension CBATTRequest: CBATTRequestInjectable { public func getCharacteristic() -> CBCharacteristicInjectable { return self.characteristic } } // MARK: - CBCentralInjectable - public protocol CBCentralInjectable { var identifier: NSUUID { get } var maximumUpdateValueLength: Int { get } } extension CBCentral: CBCentralInjectable {}
fce465c25c1dbf3ae1c03369827335f7
38.387978
176
0.767064
false
false
false
false
Gruppio/Invoke
refs/heads/master
Tests/Invoke/UserDefaultsStubbed.swift
mit
1
// // UserDefaultsStubbed.swift // Invoke // // Created by Gruppioni Michele on 15/08/16. // // import Foundation open class UserDefaultsStubbed : UserDefaults { var storedData = [String : Any]() open override func object(forKey defaultName: String) -> Any? { return storedData[defaultName] } open override func removeObject(forKey defaultName: String) { storedData.removeValue(forKey: defaultName) } open override func string(forKey defaultName: String) -> String? { return storedData[defaultName] as? String } open override func array(forKey defaultName: String) -> [Any]? { return storedData[defaultName] as? [Any] } open override func dictionary(forKey defaultName: String) -> [String : Any]? { return storedData[defaultName] as? [String : Any] } open override func data(forKey defaultName: String) -> Data? { return storedData[defaultName] as? Data } open override func stringArray(forKey defaultName: String) -> [String]? { return storedData[defaultName] as? [String] } open override func integer(forKey defaultName: String) -> Int { return storedData[defaultName] as? Int ?? 0 } open override func float(forKey defaultName: String) -> Float { return storedData[defaultName] as? Float ?? 0.0 } open override func double(forKey defaultName: String) -> Double { return storedData[defaultName] as? Double ?? 0.0 } open override func bool(forKey defaultName: String) -> Bool { return storedData[defaultName] as? Bool ?? false } @available(OSX 10.6, *) open override func url(forKey defaultName: String) -> URL? { return storedData[defaultName] as? URL } open override func set(_ value: Any?, forKey defaultName: String) { storedData[defaultName] = value } open override func set(_ value: Int, forKey defaultName: String) { storedData[defaultName] = value } open override func set(_ value: Float, forKey defaultName: String) { storedData[defaultName] = value } open override func set(_ value: Double, forKey defaultName: String) { storedData[defaultName] = value } open override func set(_ value: Bool, forKey defaultName: String) { storedData[defaultName] = value } @available(OSX 10.6, *) open override func set(_ url: URL?, forKey defaultName: String) { storedData[defaultName] = url } open override func dictionaryRepresentation() -> [String : Any] { return storedData } open override func synchronize() -> Bool { return true } }
6be02617749480738a5a61488ba57232
27.84375
82
0.631275
false
false
false
false
CodaFi/swift
refs/heads/main
test/Runtime/superclass_constraint_metadata_objc_superclass_objc_intermediate_swift_subclass.swift
apache-2.0
22
// RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-library -enable-library-evolution -module-name Framework -module-link-name Framework %S/Inputs/public_struct_with_generic_arg_nsobject_constrained.swift -o %t/%target-library-name(Framework) -emit-module-path %t/Framework.swiftmodule // RUN: %target-codesign %t/libFramework.dylib // RUN: %target-clang -fobjc-arc %S/Inputs/Superclass.m -c -o %t/Superclass.o // RUN: %target-build-swift %s %t/Superclass.o %S/Inputs/print_subclass/main.swift -import-objc-header %S/Inputs/Superclass.h -module-name main -o %t/main -I %t -L %t // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %S/Inputs/print_subclass/main.swift // REQUIRES: objc_interop // REQUIRES: executable_test // REQUIRES: OS=macosx // UNSUPPORTED: use_os_stdlib import Swift import Foundation import Framework // Swift subclass of an ObjC subclass of an ObjC class // subclass isSwiftClassMetadataSubclass metadata completeness : Complete // superclass metadata path: loop // iteration 1: subclass->Superclass == NSObject // subclass <= NSObject // superclass == NSObject; done typealias Gen = Framework.Gen<Subclass> public class Subclass : Superclass { override init() { self.gen = Gen() super.init() } var gen: Gen? } @inline(never) public func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } }
62ed402e9152d1a89980577fbe12b8de
32.380952
267
0.713267
false
false
false
false
Yalantis/Segmentio
refs/heads/master
Example/Segmentio/Builders/SegmentioBuilder.swift
mit
1
// // SegmentioBuilder.swift // Segmentio // // Created by Dmitriy Demchenko on 11/14/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Segmentio import UIKit struct SegmentioBuilder { static func setupBadgeCountForIndex(_ segmentioView: Segmentio, index: Int) { segmentioView.addBadge( at: index, count: 10, color: ColorPalette.coral ) } static func buildSegmentioView(segmentioView: Segmentio, segmentioStyle: SegmentioStyle, segmentioPosition: SegmentioPosition = .fixed(maxVisibleItems: 3)) { segmentioView.setup( content: segmentioContent(), style: segmentioStyle, options: segmentioOptions(segmentioStyle: segmentioStyle, segmentioPosition: segmentioPosition) ) } private static func segmentioContent() -> [SegmentioItem] { return [ SegmentioItem(title: "Tornado", image: UIImage(named: "tornado")), SegmentioItem(title: "Earthquakes", image: UIImage(named: "earthquakes")), SegmentioItem(title: "Extreme heat", image: UIImage(named: "heat")), SegmentioItem(title: "Eruption", image: UIImage(named: "eruption")), SegmentioItem(title: "Floods", image: UIImage(named: "floods")), SegmentioItem(title: "Wildfires", image: UIImage(named: "wildfires")) ] } private static func segmentioOptions(segmentioStyle: SegmentioStyle, segmentioPosition: SegmentioPosition = .fixed(maxVisibleItems: 3)) -> SegmentioOptions { var imageContentMode = UIView.ContentMode.center switch segmentioStyle { case .imageBeforeLabel, .imageAfterLabel: imageContentMode = .scaleAspectFit default: break } return SegmentioOptions( backgroundColor: ColorPalette.white, segmentPosition: segmentioPosition, scrollEnabled: true, indicatorOptions: segmentioIndicatorOptions(), horizontalSeparatorOptions: segmentioHorizontalSeparatorOptions(), verticalSeparatorOptions: segmentioVerticalSeparatorOptions(), imageContentMode: imageContentMode, labelTextAlignment: .center, labelTextNumberOfLines: 1, segmentStates: segmentioStates(), animationDuration: 0.3 ) } private static func segmentioStates() -> SegmentioStates { let font = UIFont.exampleAvenirMedium(ofSize: 13) return SegmentioStates( defaultState: segmentioState( backgroundColor: .clear, titleFont: font, titleTextColor: ColorPalette.grayChateau ), selectedState: segmentioState( backgroundColor: .cyan, titleFont: font, titleTextColor: ColorPalette.black ), highlightedState: segmentioState( backgroundColor: ColorPalette.whiteSmoke, titleFont: font, titleTextColor: ColorPalette.grayChateau ) ) } private static func segmentioState(backgroundColor: UIColor, titleFont: UIFont, titleTextColor: UIColor) -> SegmentioState { return SegmentioState( backgroundColor: backgroundColor, titleFont: titleFont, titleTextColor: titleTextColor ) } private static func segmentioIndicatorOptions() -> SegmentioIndicatorOptions { return SegmentioIndicatorOptions( type: .bottom, ratio: 1, height: 5, color: ColorPalette.coral ) } private static func segmentioHorizontalSeparatorOptions() -> SegmentioHorizontalSeparatorOptions { return SegmentioHorizontalSeparatorOptions( type: .topAndBottom, height: 1, color: ColorPalette.whiteSmoke ) } private static func segmentioVerticalSeparatorOptions() -> SegmentioVerticalSeparatorOptions { return SegmentioVerticalSeparatorOptions( ratio: 1, color: ColorPalette.whiteSmoke ) } }
7689115be70a3d4d8954e820f18eb965
35
161
0.624294
false
false
false
false
silence0201/Swift-Study
refs/heads/master
Learn/16.泛型/泛型类型.playground/Contents.swift
mit
1
//============字符串队列============ struct StringQueue { var items = [String]() mutating func queue(item: String) { items.append(item) } mutating func dequeue() -> String? { if items.isEmpty { return nil } else { return items.remove(at: 0) } } } var strQueue = StringQueue() strQueue.queue(item: "张三") strQueue.queue(item: "李四") strQueue.queue(item: "王五") strQueue.queue(item: "董六") print(strQueue.dequeue()!) print(strQueue.dequeue()!) print(strQueue.dequeue()!) print(strQueue.dequeue()!) //==========泛型队列============== struct Queue<T> { var items = [T]() mutating func queue(item: T) { items.append(item) } mutating func dequeue() -> T? { if items.isEmpty { return nil } else { return items.remove(at: 0) } } } var genericQueue = Queue<Int>() genericQueue.queue(item: 3) genericQueue.queue(item: 6) genericQueue.queue(item: 1) genericQueue.queue(item: 8) print(genericQueue.dequeue()!) print(genericQueue.dequeue()!) print(genericQueue.dequeue()!) print(genericQueue.dequeue()!)
3d4d04459840fc26aea8bdaa9d68b8e8
18.779661
40
0.56898
false
false
false
false
RokkinCat/harmonic
refs/heads/master
Classes/HarmonicModel.swift
mit
1
// // HarmonicModel.swift // Harmonic // // Created by Josh Holtz on 8/11/14. // Copyright (c) 2014 Josh Holtz. All rights reserved. // import Foundation // Cause typing things is hard typealias JSONObject = Dictionary<String, AnyObject> typealias JSONArray = Array<JSONObject> // Used for monad for awesomely easy parsing infix operator >>> { associativity left precedence 170 } func >>><A, B>(a: A?, f: A -> B?) -> B? { if let x = a { return f(x) } else { return .None } } infix operator <*> { associativity left precedence 160 } func <*><A: HarmonicModel, B>(inout a: Array<A>?, b: B?) { if let c = b as? JSONArray { a = HarmonicModelMaker<A>().createCollection(c) } } func <*><A: HarmonicModel, B>(inout a: A?, b: B?) { if let c = b as? JSONObject { a = HarmonicModelMaker<A>().createModel(c) } } func <*><A, B>(inout a: A?, b: B?) { a = b as? A } protocol HarmonicModel { init() func parse(json : JSONObject) } class HarmonicModelMaker<T: HarmonicModel> { /** Createsa a model from a JSON string :param: json The JSONObject being parsed :return: The HarmonicModel filled with glorious data */ func createModel(json : JSONObject) -> T { var model = T() model.parse(json) return model } /** Creates a model from a JSONObject :param: jsonString The string representation of the JSONObject being parsed :returns: The HarmonicModels filled with glorious data */ func createModel(jsonString : String, inout error : NSError?) -> T? { if let jsonData: NSData? = jsonString.dataUsingEncoding(UInt(NSUTF8StringEncoding)) { if let json = NSJSONSerialization.JSONObjectWithData(jsonData!, options: nil, error: &error) as? JSONObject { return createModel(json) } return nil } return nil } /** Creates a collection of models from a JSONArray :param: json The JSONArray being parsed :returns: The HarmonicModels filled with glorious data */ func createCollection(json : JSONArray) -> Array<T> { var models : Array<T> = [] for (obj) in json { models.append( createModel(obj) ) } return models } /** Createsa a collection of models from a JSON string :param: jsonString The string representation of the JSONArray being parsed :returns: The HarmonicModels filled with glorious data */ func createCollection(jsonString : String, inout error : NSError?) -> Array<T>? { if let jsonData: NSData? = jsonString.dataUsingEncoding(UInt(NSUTF8StringEncoding)) { if let json = NSJSONSerialization.JSONObjectWithData(jsonData!, options: nil, error: &error) as? JSONArray { return createCollection(json) } return nil } return nil } }
1504888789af7eadb558fdc398caa19e
24.295652
112
0.627235
false
false
false
false
khoren93/SwiftHub
refs/heads/master
SwiftHub/Modules/Contacts/ContactsViewModel.swift
mit
1
// // ContactsViewModel.swift // SwiftHub // // Created by Khoren Markosyan on 1/15/19. // Copyright © 2019 Khoren Markosyan. All rights reserved. // import Foundation import RxCocoa import RxSwift import RxDataSources class ContactsViewModel: ViewModel, ViewModelType { struct Input { let cancelTrigger: Driver<Void> let cancelSearchTrigger: Driver<Void> let trigger: Observable<Void> let keywordTrigger: Driver<String> let selection: Driver<ContactCellViewModel> } struct Output { let items: Driver<[ContactCellViewModel]> let cancelSearchEvent: Driver<Void> let contactSelected: Driver<Contact> } let keyword = BehaviorRelay<String>(value: "") let contactSelected = PublishSubject<Contact>() func transform(input: Input) -> Output { let elements = BehaviorRelay<[ContactCellViewModel]>(value: []) let refresh = Observable.of(input.trigger, keyword.mapToVoid()).merge() input.keywordTrigger.skip(1).throttle(DispatchTimeInterval.milliseconds(300)).distinctUntilChanged().asObservable().bind(to: keyword).disposed(by: rx.disposeBag) refresh.flatMapLatest({ [weak self] () -> Observable<[ContactCellViewModel]> in guard let self = self else { return Observable.just([]) } return ContactsManager.default.getContacts(with: self.keyword.value) .trackActivity(self.loading) .trackError(self.error) .map { $0.map({ (contact) -> ContactCellViewModel in let viewModel = ContactCellViewModel(with: contact) return viewModel }) } }).subscribe(onNext: { (items) in elements.accept(items) }, onError: { (error) in logError(error.localizedDescription) }).disposed(by: rx.disposeBag) let cancelSearchEvent = input.cancelSearchTrigger input.selection.map { $0.contact }.asObservable().bind(to: contactSelected).disposed(by: rx.disposeBag) return Output(items: elements.asDriver(), cancelSearchEvent: cancelSearchEvent, contactSelected: contactSelected.asDriver(onErrorJustReturn: Contact())) } }
28c7706302aa7677f4363bff68403962
34.65625
169
0.647239
false
false
false
false
m3rkus/Mr.Weather
refs/heads/master
Mr.Weather/Cache.swift
mit
1
// // Cache.swift // Mr.Weather // // Created by Роман Анистратенко on 20/09/2017. // Copyright © 2017 m3rk edge. All rights reserved. // import Foundation class Cache { private static let documentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! private static let cacheGeoWeatherPath = documentsDirectory.appendingPathComponent("geoWeatherModel").path private static let cacheManualWeatherPath = documentsDirectory.appendingPathComponent("manualWeatherModel").path } // MARK: Public extension Cache { static func saveGeoWeather(weatherModel: WeatherModel) { dLog("Save weather model") let isSuccess = NSKeyedArchiver.archiveRootObject(weatherModel, toFile: Cache.cacheGeoWeatherPath) if !isSuccess { dLog("Save model error. Houston, we have a problem!") } } static func saveManualWeather(weatherModel: WeatherModel) { dLog("Save weather model") let isSuccess = NSKeyedArchiver.archiveRootObject(weatherModel, toFile: Cache.cacheManualWeatherPath) if !isSuccess { dLog("Save model error. Houston, we have a problem!") } } static func loadOutGeoWeather() -> WeatherModel? { dLog("Load out weather model") return NSKeyedUnarchiver.unarchiveObject(withFile: Cache.cacheGeoWeatherPath) as? WeatherModel } static func loadOutManualWeather() -> WeatherModel? { dLog("Load out weather model") return NSKeyedUnarchiver.unarchiveObject(withFile: Cache.cacheManualWeatherPath) as? WeatherModel } }
285459acd0d88516bc0672fa2d8ac747
32.958333
116
0.698773
false
false
false
false
HongliYu/firefox-ios
refs/heads/master
Client/Frontend/Settings/SyncContentSettingsViewController.swift
mpl-2.0
1
/* 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 Sync class ManageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Manage" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.FxAManageAccount, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = FxAContentViewController(profile: profile) if let account = profile.getAccount() { var cs = URLComponents(url: account.configuration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) if let url = try? cs?.asURL() { viewController.url = url } } navigationController?.pushViewController(viewController, animated: true) } } class DisconnectSetting: Setting { let settingsVC: SettingsTableViewController let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .none } override var textAlignment: NSTextAlignment { return .center } override var title: NSAttributedString? { return NSAttributedString(string: Strings.SettingsDisconnectSyncButton, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.general.destructiveRed]) } init(settings: SettingsTableViewController) { self.settingsVC = settings self.profile = settings.profile } override var accessibilityIdentifier: String? { return "SignOut" } override func onClick(_ navigationController: UINavigationController?) { let alertController = UIAlertController( title: Strings.SettingsDisconnectSyncAlertTitle, message: Strings.SettingsDisconnectSyncAlertBody, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction( UIAlertAction(title: Strings.SettingsDisconnectCancelAction, style: .cancel) { (action) in // Do nothing. }) alertController.addAction( UIAlertAction(title: Strings.SettingsDisconnectDestructiveAction, style: .destructive) { (action) in FxALoginHelper.sharedInstance.applicationDidDisconnect(UIApplication.shared) LeanPlumClient.shared.set(attributes: [LPAttributeKey.signedInSync: self.profile.hasAccount()]) // If there is more than one view controller in the navigation controller, we can pop. // Otherwise, assume that we got here directly from the App Menu and dismiss the VC. if let navigationController = navigationController, navigationController.viewControllers.count > 1 { _ = navigationController.popViewController(animated: true) } else { self.settingsVC.dismiss(animated: true, completion: nil) } }) navigationController?.present(alertController, animated: true, completion: nil) } } class DeviceNamePersister: SettingValuePersister { let profile: Profile init(profile: Profile) { self.profile = profile } func readPersistedValue() -> String? { return self.profile.getAccount()?.deviceName } func writePersistedValue(value: String?) { guard let newName = value, let account = self.profile.getAccount() else { return } account.updateDeviceName(newName) self.profile.flushAccount() _ = self.profile.syncManager.syncNamedCollections(why: .clientNameChanged, names: ["clients"]) } } class DeviceNameSetting: StringSetting { init(settings: SettingsTableViewController) { let settingsIsValid: (String?) -> Bool = { !($0?.isEmpty ?? true) } super.init(defaultValue: DeviceInfo.defaultClientName(), placeholder: "", accessibilityIdentifier: "DeviceNameSetting", persister: DeviceNamePersister(profile: settings.profile), settingIsValid: settingsIsValid) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) textField.textAlignment = .natural } } class SyncContentSettingsViewController: SettingsTableViewController { fileprivate var enginesToSyncOnExit: Set<String> = Set() init() { super.init(style: .grouped) self.title = Strings.FxASettingsTitle hasSectionSeparatorLine = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillDisappear(_ animated: Bool) { if !enginesToSyncOnExit.isEmpty { _ = self.profile.syncManager.syncNamedCollections(why: SyncReason.engineEnabled, names: Array(enginesToSyncOnExit)) enginesToSyncOnExit.removeAll() } super.viewWillDisappear(animated) } func engineSettingChanged(_ engineName: String) -> (Bool) -> Void { let prefName = "sync.engine.\(engineName).enabledStateChanged" return { enabled in if let _ = self.profile.prefs.boolForKey(prefName) { // Switch it back to not-changed self.profile.prefs.removeObjectForKey(prefName) self.enginesToSyncOnExit.remove(engineName) } else { self.profile.prefs.setBool(true, forKey: prefName) self.enginesToSyncOnExit.insert(engineName) } } } override func generateSettings() -> [SettingSection] { let manage = ManageSetting(settings: self) let manageSection = SettingSection(title: nil, footerTitle: nil, children: [manage]) let bookmarks = BoolSetting(prefs: profile.prefs, prefKey: "sync.engine.bookmarks.enabled", defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.FirefoxSyncBookmarksEngine), attributedStatusText: nil, settingDidChange: engineSettingChanged("bookmarks")) let history = BoolSetting(prefs: profile.prefs, prefKey: "sync.engine.history.enabled", defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.FirefoxSyncHistoryEngine), attributedStatusText: nil, settingDidChange: engineSettingChanged("history")) let tabs = BoolSetting(prefs: profile.prefs, prefKey: "sync.engine.tabs.enabled", defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.FirefoxSyncTabsEngine), attributedStatusText: nil, settingDidChange: engineSettingChanged("tabs")) let passwords = BoolSetting(prefs: profile.prefs, prefKey: "sync.engine.passwords.enabled", defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.FirefoxSyncLoginsEngine), attributedStatusText: nil, settingDidChange: engineSettingChanged("passwords")) let enginesSection = SettingSection(title: NSAttributedString(string: Strings.FxASettingsSyncSettings), footerTitle: nil, children: [bookmarks, history, tabs, passwords]) let deviceName = DeviceNameSetting(settings: self) let deviceNameSection = SettingSection(title: NSAttributedString(string: Strings.FxASettingsDeviceName), footerTitle: nil, children: [deviceName]) let disconnect = DisconnectSetting(settings: self) let disconnectSection = SettingSection(title: nil, footerTitle: nil, children: [disconnect]) return [manageSection, enginesSection, deviceNameSection, disconnectSection] } }
8fa1668b03db775e94273013fdd6aa8e
45.656805
284
0.706405
false
false
false
false
lelandjansen/fatigue
refs/heads/master
ios/fatigue/QuestionnaireResponse.swift
apache-2.0
1
import CoreData import UIKit extension QuestionnaireResponse { static let entityName = "QuestionnaireResponse" static func saveResponse(forQuestionnaireItems questionnaireItems: [QuestionnaireItem]) { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let questionnaireResponse = NSEntityDescription.insertNewObject(forEntityName: QuestionnaireResponse.entityName, into: context) as! QuestionnaireResponse questionnaireResponse.date = NSDate() var riskScore: Int32 = 0 for questionnaireItem in questionnaireItems { if questionnaireItem is Question { let question = questionnaireItem as! Question let questionResponse = NSEntityDescription.insertNewObject(forEntityName: QuestionResponse.entityName, into: context) as! QuestionResponse questionResponse.id = question.id.rawValue questionResponse.questionDescription = question.description questionResponse.riskScoreContribution = question.riskScoreContribution(question.selection) questionResponse.selection = question.selection questionnaireResponse.addToQuestionResponses(questionResponse) riskScore += question.riskScoreContribution(question.selection) } } questionnaireResponse.riskScore = riskScore do { try context.save() } catch { if let topViewController = UIApplication.topViewController() { let alert = UIAlertController( title: "Unable to save questionnaire response.", message: nil, preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .default)) topViewController.present(alert, animated: true) } } } static func loadResponses() -> [QuestionnaireResponse] { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let request: NSFetchRequest<QuestionnaireResponse> = QuestionnaireResponse.fetchRequest() do { return try context.fetch(request) } catch { if let topViewController = UIApplication.topViewController() { let alert = UIAlertController( title: "Unable to load questionnaire responses.", message: nil, preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .default)) topViewController.present(alert, animated: true) } } return [] } static func delete(response: QuestionnaireResponse) { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext context.delete(response) do { try context.save() } catch { if let topViewController = UIApplication.topViewController() { let alert = UIAlertController( title: "Unable to delete questionnaire response.", message: nil, preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .default)) topViewController.present(alert, animated: true) } } } func maxWorkTimeExceeded(forRole role: Role) -> Bool { switch role { case .pilot: var flyingWithAnotherPilot = false for response in questionResponses! { if (response as! QuestionResponse).id == Questionnaire.QuestionId.numberOfPilots.rawValue { flyingWithAnotherPilot = ((response as! QuestionResponse).selection == YesNoQuestion.Answer.yes.rawValue) } } for response in questionResponses! { if (response as! QuestionResponse).id == Questionnaire.QuestionId.workTime.rawValue { let hoursFlying = Int((response as! QuestionResponse).selection!)! if flyingWithAnotherPilot { return QuestionnaireDefaults.maxFlightTimeManyPilots < hoursFlying } else { return QuestionnaireDefaults.maxFlightTimeOnePilot < hoursFlying } } } case .engineer: for response in questionResponses! { if (response as! QuestionResponse).id == Questionnaire.QuestionId.workTime.rawValue { let workTime = Int((response as! QuestionResponse).selection!)! return workTime < QuestionnaireDefaults.maxWorkTimeEngineer } } case .none: fatalError("Role cannot be none") } fatalError("Could not determine if flight time was exceeded") } }
11954296391b65a35b6cb89f7938d3fb
43.701754
161
0.596743
false
false
false
false
hrunar/functional-view-controllers
refs/heads/master
FunctionalViewControllers/Library.swift
mit
1
// // ViewController.swift // FunctionalViewControllers // // Created by Chris Eidhof on 03/09/14. // Copyright (c) 2014 Chris Eidhof. All rights reserved. // import UIKit public class Box<T> { public let unbox: T public init(_ value: T) { self.unbox = value } } public func map<A,B>(vc: Screen<A>, f: A -> B) -> Screen<B> { return Screen { callback in return vc.run { y in callback(f(y)) } } } public func map<A,B>(nc: NavigationController<A>, f: A -> B) -> NavigationController<B> { return NavigationController { callback in return nc.build { (y, nc) in callback(f(y), nc) } } } extension UIViewController { public func presentModal<A>(screen: NavigationController<A>, cancellable: Bool, callback: A -> ()) { let vc = screen.build { [unowned self] x, nc in callback(x) self.dismissViewControllerAnimated(true, completion: nil) } vc.modalTransitionStyle = UIModalTransitionStyle.CoverVertical if cancellable { let cancelButton = BarButton(title: BarButtonTitle.SystemItem(UIBarButtonSystemItem.Cancel), callback: { _ in self.dismissViewControllerAnimated(true, completion: nil) }) let rootVC = vc.viewControllers[0] rootVC.setLeftBarButton(cancelButton) } presentViewController(vc, animated: true, completion: nil) } } public struct Screen<A> { private let build: (A -> ()) -> UIViewController public var navigationItem: NavigationItem public init(_ build: (A -> ()) -> UIViewController) { self.build = build navigationItem = defaultNavigationItem } public init(_ navigationItem: NavigationItem, _ build: (A -> ()) -> UIViewController) { self.build = build self.navigationItem = navigationItem } public func run(f: A -> ()) -> UIViewController { let vc = build(f) vc.applyNavigationItem(navigationItem) return vc } } func ignore<A>(_: A, _: UINavigationController) { } public struct NavigationController<A> { public let build: (f: (A, UINavigationController) -> ()) -> UINavigationController public func run() -> UINavigationController { return build { _ in } } } public func navigationController<A>(vc: Screen<A>) -> NavigationController<A> { return NavigationController { callback in let navController = UINavigationController() let rootController = vc.run { callback($0, navController) } navController.viewControllers = [rootController] return navController } } infix operator >>> { associativity left } public func >>><A,B>(l: NavigationController<A>, r: A -> Screen<B>) -> NavigationController<B> { return NavigationController { (callback) -> UINavigationController in let nc = l.build { a, nc in let rvc = r(a).run { c in callback(c, nc) } nc.pushViewController(rvc, animated: true) } return nc } } public func textViewController(string: String) -> Screen<()> { return Screen { _ in let tv = TextViewController() tv.textView.text = string return tv } } class TextViewController: UIViewController { var textView: UITextView = { var tv = UITextView() tv.editable = false return tv }() override func viewDidLoad() { view.addSubview(textView) textView.frame = view.bounds } } public func modalButton<A>(title: BarButtonTitle, nc: NavigationController<A>, callback: A -> ()) -> BarButton { return BarButton(title: title, callback: { context in context.viewController.presentModal(nc, cancellable: true, callback: callback) }) } public func add<A>(screen: Screen<A>, callback: A -> ()) -> BarButton { return modalButton(.SystemItem(.Add), nc: navigationController(screen), callback: callback) } // TODO: is this a good name? infix operator <|> { associativity left } public func <|><A,B>(screen: A -> Screen<B>, button: A -> BarButton) -> A -> Screen<B> { return { a in var screen = screen(a) screen.navigationItem.rightBarButtonItem = button(a) return screen } }
49b1a5fa6c7ddc67a37aff89c0dcec2f
28.438356
121
0.623691
false
false
false
false
Eonil/EditorLegacy
refs/heads/master
Modules/Monolith.Swift/ParsingEngine/Sources/Cursor.swift
mit
3
// // Cursor.swift // EDXC // // Created by Hoon H. on 10/13/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Foundation final class Code { let data:String init(data:String) { self.data = data } } /// Oneway directed cursor. public struct Cursor { let code:Code let location:String.Index var available:Bool { get { return location < code.data.endIndex } } /// Crashes if not `available`. var current:Character { get { precondition(available) return code.data[location] } } var continuation:Cursor { get { precondition(available) return stepping() } } func contains(character ch:Character) -> Bool { precondition(available) return available && code.data[location] == ch } func contains(string s:String) -> Bool { precondition(available) return s.startIndex == s.endIndex || (contains(character: s[s.startIndex]) && stepping().contains(string: s.substringFromIndex(s.startIndex.successor()))) } func stepping() -> Cursor { precondition(available) return Cursor(code: code, location: location.successor()) } func stepping(by c1:Int) -> Cursor { precondition(available) return c1 == 0 ? self : stepping(by: c1 - 1) } func stepping(byLengthOfString s:String) -> Cursor { precondition(available) return s.startIndex == s.endIndex ? self : stepping(byLengthOfString: s.substringFromIndex(s.startIndex.successor())) } func content(from c1:Cursor) -> String { return c1.content(to: self) } func content(to c1:Cursor) -> String { precondition(self < c1) let r1 = location..<c1.location let s1 = code.data[r1] return s1 } } extension Cursor : Printable { public var description:String { get { return "Cursor (code Code @) (location String.Index \(location))" } } } func == (left:Cursor, right:Cursor) -> Bool { return left.location == right.location } func < (left:Cursor, right:Cursor) -> Bool { return left.location < right.location } func > (left:Cursor, right:Cursor) -> Bool { return left.location < right.location } func <= (left:Cursor, right:Cursor) -> Bool { return left.location <= right.location } func >= (left:Cursor, right:Cursor) -> Bool { return left.location >= right.location }
86e4efa497437c5811675582bd52dee9
17.694215
156
0.669761
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
Client/Frontend/Settings/SearchSettingsTableViewController.swift
mpl-2.0
1
/* 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 UIKit import Shared class SearchSettingsTableViewController: UITableViewController { fileprivate let SectionDefault = 0 fileprivate let ItemDefaultEngine = 0 fileprivate let ItemDefaultSuggestions = 1 fileprivate let NumberOfItemsInSectionDefault = 2 fileprivate let SectionOrder = 1 fileprivate let NumberOfSections = 2 fileprivate let IconSize = CGSize(width: OpenSearchEngine.PreferredIconSize, height: OpenSearchEngine.PreferredIconSize) fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier" var model: SearchEngines! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = Strings.Search // To allow re-ordering the list of search engines at all times. tableView.isEditing = true // So that we push the default search engine controller on selection. tableView.allowsSelectionDuringEditing = true tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier) // Insert Done button if being presented outside of the Settings Nav stack if !(self.navigationController is SettingsNavigationController) { self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: Strings.Done, style: .done, target: self, action: #selector(SearchSettingsTableViewController.SELDismiss)) } let footer = SettingsTableSectionHeaderFooterView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 44)) footer.showBottomBorder = false tableView.tableFooterView = footer tableView.separatorColor = UIConstants.TableViewSeparatorColor tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell! var engine: OpenSearchEngine! if indexPath.section == SectionDefault { switch indexPath.item { case ItemDefaultEngine: engine = model.defaultEngine cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) cell.editingAccessoryType = UITableViewCellAccessoryType.disclosureIndicator cell.accessibilityLabel = Strings.DefaultSearchEngine cell.accessibilityValue = engine.shortName cell.textLabel?.text = engine.shortName cell.imageView?.image = engine.image?.createScaled(IconSize) case ItemDefaultSuggestions: cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) cell.textLabel?.text = Strings.Show_Search_Suggestions let toggle = UISwitch() toggle.onTintColor = UIConstants.ControlTintColor toggle.addTarget(self, action: #selector(SearchSettingsTableViewController.SELdidToggleSearchSuggestions(_:)), for: UIControlEvents.valueChanged) toggle.isOn = model.shouldShowSearchSuggestions cell.editingAccessoryView = toggle cell.selectionStyle = .none default: // Should not happen. break } } else { // The default engine is not a quick search engine. let index = indexPath.item + 1 engine = model.orderedEngines[index] cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) cell.showsReorderControl = true let toggle = UISwitch() toggle.onTintColor = UIConstants.ControlTintColor // This is an easy way to get from the toggle control to the corresponding index. toggle.tag = index toggle.addTarget(self, action: #selector(SearchSettingsTableViewController.SELdidToggleEngine(_:)), for: UIControlEvents.valueChanged) toggle.isOn = model.isEngineEnabled(engine) cell.editingAccessoryView = toggle cell.textLabel?.text = engine.shortName cell.imageView?.image = engine.image?.createScaled(IconSize) cell.selectionStyle = .none } // So that the seperator line goes all the way to the left edge. cell.separatorInset = UIEdgeInsets.zero return cell } override func numberOfSections(in tableView: UITableView) -> Int { return NumberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == SectionDefault { return NumberOfItemsInSectionDefault } else { // The first engine -- the default engine -- is not shown in the quick search engine list. return model.orderedEngines.count - 1 } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if indexPath.section == SectionDefault && indexPath.item == ItemDefaultEngine { let searchEnginePicker = SearchEnginePicker() // Order alphabetically, so that picker is always consistently ordered. // Every engine is a valid choice for the default engine, even the current default engine. searchEnginePicker.engines = model.orderedEngines.sorted { e, f in e.shortName < f.shortName } searchEnginePicker.delegate = self searchEnginePicker.selectedSearchEngineName = model.defaultEngine.shortName navigationController?.pushViewController(searchEnginePicker, animated: true) } return nil } // Don't show delete button on the left. override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.none } // Don't reserve space for the delete button on the left. override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return false } // Hide a thin vertical line that iOS renders between the accessoryView and the reordering control. override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if cell.isEditing { for v in cell.subviews { if v.frame.width == 1.0 { v.backgroundColor = UIColor.clear } } } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView var sectionTitle: String if section == SectionDefault { sectionTitle = Strings.DefaultSearchEngine } else { sectionTitle = Strings.Quicksearch_Engines } headerView.titleLabel.text = sectionTitle return headerView } override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { if indexPath.section == SectionDefault { return false } else { return true } } override func tableView(_ tableView: UITableView, moveRowAt indexPath: IndexPath, to newIndexPath: IndexPath) { // The first engine (default engine) is not shown in the list, so the indices are off-by-1. let index = indexPath.item + 1 let newIndex = newIndexPath.item + 1 let engine = model.orderedEngines.remove(at: index) model.orderedEngines.insert(engine, at: newIndex) tableView.reloadData() } // Snap to first or last row of the list of engines. override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath { // You can't drag or drop on the default engine. if sourceIndexPath.section == SectionDefault || proposedDestinationIndexPath.section == SectionDefault { return sourceIndexPath } if (sourceIndexPath.section != proposedDestinationIndexPath.section) { var row = 0 if (sourceIndexPath.section < proposedDestinationIndexPath.section) { row = tableView.numberOfRows(inSection: sourceIndexPath.section) - 1 } return IndexPath(row: row, section: sourceIndexPath.section) } return proposedDestinationIndexPath } func SELdidToggleEngine(_ toggle: UISwitch) { let engine = model.orderedEngines[toggle.tag] // The tag is 1-based. if toggle.isOn { model.enableEngine(engine) } else { model.disableEngine(engine) } } func SELdidToggleSearchSuggestions(_ toggle: UISwitch) { // Setting the value in settings dismisses any opt-in. model.shouldShowSearchSuggestionsOptIn = false model.shouldShowSearchSuggestions = toggle.isOn } func SELcancel() { navigationController?.popViewController(animated: true) } func SELDismiss() { self.dismiss(animated: true, completion: nil) } } extension SearchSettingsTableViewController: SearchEnginePickerDelegate { func searchEnginePicker(_ searchEnginePicker: SearchEnginePicker, didSelectSearchEngine searchEngine: OpenSearchEngine?) { if let engine = searchEngine { model.defaultEngine = engine self.tableView.reloadData() } navigationController?.popViewController(animated: true) } }
0453e1b2c93f3e5b91aded76a03c748d
42.34188
189
0.677776
false
false
false
false
Can-Sahin/Moya-PromiseKit-Service
refs/heads/master
src/MoyaPromise/Serialization.swift
mit
1
// // Serialization.swift // // Created by Can Sahin on 28/06/2017. // Copyright © 2017 Can Sahin. All rights reserved. // import Foundation import Alamofire class Serialization { enum ErrorCode: Int { case noData = 1 case DecodingError = 2 } static func newError(_ code: ErrorCode, failureReason: String) -> NSError { let errorDomain = "com.responseSerialization.error" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let returnError = NSError(domain: errorDomain, code: code.rawValue, userInfo: userInfo) return returnError } class ObjectCoder{ public static func CodableSerializer<T:Codable>() -> DataResponseSerializer<T> { return DataResponseSerializer { _, response, data, error in if let err = error{ return .failure(err) } guard let _ = data else{ let failureReason = "Data could not be serialized. Input data was nil." let error = Serialization.newError(.noData, failureReason: failureReason) return .failure(error) } let decoder = JSONDecoder() do { let obj = try decoder.decode(T.self, from: data!) return .success(obj) } catch{ let failureReason = "Data could not be decoded." let error = Serialization.newError(.DecodingError, failureReason: failureReason) return .failure(error) } } } } }
4d0aa73c382f860719b11936b1c45a2e
32.470588
100
0.543644
false
false
false
false
RCacheaux/BitbucketKit
refs/heads/master
Sources/iOS/Public/Operations/RefreshAuthenticatedUserOperation.swift
apache-2.0
1
// Copyright © 2016 Atlassian Pty Ltd. All rights reserved. import Foundation public class RefreshAuthenticatedUserOperation: AsyncOperation<User> { private let remoteOperation: GetAuthenticatedUserRemoteOperation private let dataStore: UserDataStore init(remoteOperation: GetAuthenticatedUserRemoteOperation, dataStore: UserDataStore) { self.remoteOperation = remoteOperation self.dataStore = dataStore } override func run() { remoteOperation.completionBlock = { // TODO: Figure out a better way to grab outcome that doesn't require a bunch of mem management boilerplate // TODO: How to avoid the pyramid of doom here. switch self.remoteOperation.outcome { case .success(let user): self.dataStore.saveAuthenticatedUser(user) { result in switch result { case .success: self.outcome = .success(user) case .error(let error): self.outcome = .error(error) } self.finishedExecutingOperation() } default: self.outcome = self.remoteOperation.outcome self.finishedExecutingOperation() } } remoteOperation.start() } }
e1f2fc98805d42f2f66f88196d76d525
32
113
0.685185
false
false
false
false
matrix-org/matrix-ios-sdk
refs/heads/develop
MatrixSDK/Crypto/Verification/MXKeyVerificationManagerV2.swift
apache-2.0
1
// // MXKeyVerificationManagerV2.swift // MatrixSDK // // Created by Element on 05/07/2022. // import Foundation #if DEBUG import MatrixSDKCrypto /// Result of processing updates on verification object (request or transaction) /// after each sync loop enum MXKeyVerificationUpdateResult { // The object has not changed since last sync case noUpdates // The object's state has changed case updated // The object is no longer available (e.g. it was cancelled) case removed } protocol MXKeyVerificationTransactionV2: MXKeyVerificationTransaction { func processUpdates() -> MXKeyVerificationUpdateResult } typealias MXCryptoVerificationHandler = MXCryptoVerificationRequesting & MXCryptoSASVerifying & MXCryptoQRCodeVerifying class MXKeyVerificationManagerV2: NSObject, MXKeyVerificationManager { enum Error: Swift.Error { case methodNotSupported case unknownFlowId case missingRoom case missingDeviceId } // A set of room events we have to monitor manually to synchronize CryptoMachine // and verification UI, optionally triggering global notifications. static let dmEventTypes: Set<MXEventType> = [ .roomMessage, // Verification request in DM is wrapped inside `m.room.message` .keyVerificationReady, .keyVerificationStart, .keyVerificationAccept, .keyVerificationKey, .keyVerificationMac, .keyVerificationCancel, .keyVerificationDone, ] // A set of to-device events we have to monitor manually to synchronize CryptoMachine // and verification UI, optionally triggering global notifications. private static let toDeviceEventTypes: Set<String> = [ kMXMessageTypeKeyVerificationRequest, kMXEventTypeStringKeyVerificationStart ] private weak var session: MXSession? private let handler: MXCryptoVerificationHandler // We need to keep track of request / transaction objects by reference // because various flows / screens subscribe to updates via global notifications // posted through them private var activeRequests: [String: MXKeyVerificationRequestV2] private var activeTransactions: [String: MXKeyVerificationTransactionV2] private let resolver: MXKeyVerificationStateResolver private let log = MXNamedLog(name: "MXKeyVerificationManagerV2") init( session: MXSession, handler: MXCryptoVerificationHandler ) { self.session = session self.handler = handler self.activeRequests = [:] self.activeTransactions = [:] self.resolver = MXKeyVerificationStateResolver(myUserId: session.myUserId, aggregations: session.aggregations) } var pendingRequests: [MXKeyVerificationRequest] { return Array(activeRequests.values) } func transactions(_ complete: @escaping ([MXKeyVerificationTransaction]) -> Void) { complete(Array(activeTransactions.values)) } func requestVerificationByToDevice( withUserId userId: String, deviceIds: [String]?, methods: [String], success: @escaping (MXKeyVerificationRequest) -> Void, failure: @escaping (Swift.Error) -> Void ) { log.debug("->") Task { do { let request = try await requestVerificationByToDevice(withUserId: userId, deviceIds: deviceIds, methods: methods) await MainActor.run { log.debug("Request successfully sent") success(request) } } catch { await MainActor.run { log.error("Cannot request verification", context: error) failure(error) } } } } func requestVerificationByDM( withUserId userId: String, roomId: String?, fallbackText: String, methods: [String], success: @escaping (MXKeyVerificationRequest) -> Void, failure: @escaping (Swift.Error) -> Void ) { log.debug("->") Task { do { let roomId = try await getOrCreateDMRoomId(userId: userId) let request = try await requestVerification( userId: userId, roomId: roomId, methods: methods ) await MainActor.run { log.debug("Request successfully sent") success(request) } } catch { await MainActor.run { log.error("Cannot request verification", context: error) failure(error) } } } } func beginKeyVerification( from request: MXKeyVerificationRequest, method: String, success: @escaping (MXKeyVerificationTransaction) -> Void, failure: @escaping (Swift.Error) -> Void ) { log.debug("Starting \(method) verification flow") Task { do { let transaction = try await startSasVerification(userId: request.otherUser, flowId: request.requestId, transport: request.transport) await MainActor.run { log.debug("Created verification transaction") success(transaction) } } catch { await MainActor.run { log.error("Failed creating verification transaction", context: error) failure(error) } } } } func keyVerification( fromKeyVerificationEvent event: MXEvent, roomId: String, success: @escaping (MXKeyVerification) -> Void, failure: @escaping (Swift.Error) -> Void ) -> MXHTTPOperation? { guard let flowId = event.relatesTo?.eventId ?? event.eventId else { log.failure("Unknown flow id") failure(Error.unknownFlowId) return nil } if let request = activeRequests[flowId] { log.debug("Using active request") let result = MXKeyVerification() result.request = request success(result) } else if let request = handler.verificationRequest(userId: event.sender, flowId: flowId) { log.debug("Adding pending request") let result = MXKeyVerification() result.request = addRequest(for: request, transport: .directMessage) success(result) } else { log.debug("Computing archived request") Task { do { // If we do not have active verification anymore (managed by CryptoMachine), it means // we have completed or cancelled request, where the state can be computed from // aggregate events. let result = MXKeyVerification() result.state = try await resolver.verificationState(flowId: flowId, roomId: roomId) await MainActor.run { success(result) } } catch { await MainActor.run { failure(error) } } } } return nil } func qrCodeTransaction(withTransactionId transactionId: String) -> MXQRCodeTransaction? { if let transaction = activeTransactions[transactionId] as? MXQRCodeTransaction { return transaction } guard let request = activeRequests[transactionId] else { log.error("There is no pending verification request") return nil } do { log.debug("Starting new QR verification") let qr = try handler.startQrVerification(userId: request.otherUser, flowId: transactionId) return addQrTransaction(for: qr, transport: request.transport) } catch { // We may not be able to start QR verification flow (the other device cannot scan our code) // but we might be able to scan theirs, so creating an empty placeholder transaction for this case. log.debug("Adding placeholder QR verification") let qr = QrCode( otherUserId: request.otherUser, otherDeviceId: request.otherDevice ?? "", flowId: request.requestId, roomId: request.roomId, weStarted: request.isFromMyDevice, otherSideScanned: false, hasBeenConfirmed: false, reciprocated: false, isDone: false, isCancelled: false, cancelInfo: nil ) return addQrTransaction(for: qr, transport: request.transport) } } func removeQRCodeTransaction(withTransactionId transactionId: String) { guard activeTransactions[transactionId] is MXQRCodeTransaction else { return } log.debug("Removed QR verification") activeTransactions[transactionId] = nil } // MARK: - Events @MainActor func handleDeviceEvent(_ event: MXEvent) { guard Self.toDeviceEventTypes.contains(event.type) else { updatePendingVerification() return } log.debug("->") guard let userId = event.sender, let flowId = event.content["transaction_id"] as? String else { log.error("Missing userId or flowId in event") return } switch event.type { case kMXMessageTypeKeyVerificationRequest: handleIncomingRequest(userId: userId, flowId: flowId, transport: .toDevice) case kMXEventTypeStringKeyVerificationStart: handleIncomingVerification(userId: userId, flowId: flowId, transport: .toDevice) default: log.failure("Event type should not be handled by key verification", context: event.type) } updatePendingVerification() } @MainActor func handleRoomEvent(_ event: MXEvent) -> String? { guard isRoomVerificationEvent(event) else { return nil } if !event.isEncrypted, let roomId = event.roomId { handler.receiveUnencryptedVerificationEvent(event: event, roomId: roomId) updatePendingVerification() } if event.type == kMXEventTypeStringRoomMessage && event.content?[kMXMessageTypeKey] as? String == kMXMessageTypeKeyVerificationRequest { handleIncomingRequest(userId: event.sender, flowId: event.eventId, transport: .directMessage) return event.sender } else if event.type == kMXEventTypeStringKeyVerificationStart, let flowId = event.relatesTo.eventId { handleIncomingVerification(userId: event.sender, flowId: flowId, transport: .directMessage) return event.sender } else { return nil } } // MARK: - Update @MainActor func updatePendingVerification() { if !activeRequests.isEmpty { log.debug("Processing \(activeRequests.count) pending requests") } for request in activeRequests.values { switch request.processUpdates() { case .noUpdates: break case .updated: NotificationCenter.default.post(name: .MXKeyVerificationRequestDidChange, object: request) case .removed: NotificationCenter.default.post(name: .MXKeyVerificationRequestDidChange, object: request) activeRequests[request.requestId] = nil } } if !activeTransactions.isEmpty { log.debug("Processing \(activeTransactions.count) pending transactions") } for transaction in activeTransactions.values { switch transaction.processUpdates() { case .noUpdates: break case .updated: NotificationCenter.default.post(name: .MXKeyVerificationTransactionDidChange, object: transaction) case .removed: NotificationCenter.default.post(name: .MXKeyVerificationTransactionDidChange, object: transaction) activeTransactions[transaction.transactionId] = nil } } } // MARK: - Verification requests func requestVerificationByToDevice( withUserId userId: String, deviceIds: [String]?, methods: [String] ) async throws -> MXKeyVerificationRequest { log.debug("->") if userId == session?.myUserId { log.debug("Self-verification") return try await requestSelfVerification(methods: methods) } else if let deviceId = deviceIds?.first { log.debug("Direct verification of another device") if let count = deviceIds?.count, count > 1 { log.error("Verifying more than one device at once is not supported") } return try await requestVerification(userId: userId, deviceId: deviceId, methods: methods) } else { throw Error.missingDeviceId } } private func requestVerification(userId: String, roomId: String, methods: [String]) async throws -> MXKeyVerificationRequest { log.debug("->") let request = try await handler.requestVerification( userId: userId, roomId: roomId, methods: methods ) return addRequest(for: request, transport: .directMessage) } private func requestVerification(userId: String, deviceId: String, methods: [String]) async throws -> MXKeyVerificationRequest { log.debug("->") let request = try await handler.requestVerification( userId: userId, deviceId: deviceId, methods: methods ) return addRequest(for: request, transport: .toDevice) } private func requestSelfVerification(methods: [String]) async throws -> MXKeyVerificationRequest { log.debug("->") let request = try await handler.requestSelfVerification(methods: methods) return addRequest(for: request, transport: .directMessage) } private func handleIncomingRequest(userId: String, flowId: String, transport: MXKeyVerificationTransport) { log.debug(flowId) guard activeRequests[flowId] == nil else { log.debug("Request already known, ignoring") return } guard let req = handler.verificationRequest(userId: userId, flowId: flowId) else { log.error("Verification request is not known", context: [ "flow_id": flowId ]) return } log.debug("Tracking new verification request") _ = addRequest(for: req, transport: transport, notify: true) } private func addRequest( for request: VerificationRequest, transport: MXKeyVerificationTransport, notify: Bool = false ) -> MXKeyVerificationRequestV2 { let request = MXKeyVerificationRequestV2( request: request, transport: transport, handler: handler ) activeRequests[request.requestId] = request if notify { NotificationCenter.default.post( name: .MXKeyVerificationManagerNewRequest, object: self, userInfo: [ MXKeyVerificationManagerNotificationRequestKey: request ] ) NotificationCenter.default.post( name: .MXKeyVerificationRequestDidChange, object: request ) } return request } // MARK: - Verification transactions private func startSasVerification(userId: String, flowId: String, transport: MXKeyVerificationTransport) async throws -> MXKeyVerificationTransaction { log.debug("->") let sas = try await handler.startSasVerification(userId: userId, flowId: flowId) return addSasTransaction(for: sas, transport: transport) } private func handleIncomingVerification(userId: String, flowId: String, transport: MXKeyVerificationTransport) { log.debug(flowId) guard let verification = handler.verification(userId: userId, flowId: flowId) else { log.error("Verification is not known", context: [ "flow_id": flowId ]) return } switch verification { case .sasV1(let sas): log.debug("Tracking new SAS verification transaction") let transaction = addSasTransaction(for: sas, transport: transport, notify: true) if activeRequests[transaction.transactionId] != nil { log.debug("Auto-accepting transaction that matches a pending request") transaction.accept() Task { await updatePendingVerification() } } case .qrCodeV1(let qrCode): if activeTransactions[flowId] is MXQRCodeTransaction { // This flow may happen if we have previously started a QR verification, but so has the other side, // and we scanned their code which now takes over the verification flow log.debug("Updating existing QR verification transaction") Task { await updatePendingVerification() } } else { log.debug("Tracking new QR verification transaction") _ = addQrTransaction(for: qrCode, transport: transport) } } } private func addSasTransaction( for sas: Sas, transport: MXKeyVerificationTransport, notify: Bool = false ) -> MXSASTransactionV2 { let transaction = MXSASTransactionV2( sas: sas, transport: transport, handler: handler ) activeTransactions[transaction.transactionId] = transaction if notify { NotificationCenter.default.post( name: .MXKeyVerificationManagerNewTransaction, object: self, userInfo: [ MXKeyVerificationManagerNotificationTransactionKey: transaction ] ) NotificationCenter.default.post( name: .MXKeyVerificationTransactionDidChange, object: transaction ) } return transaction } private func addQrTransaction( for qrCode: QrCode, transport: MXKeyVerificationTransport ) -> MXQRCodeTransactionV2 { let transaction = MXQRCodeTransactionV2( qrCode: qrCode, transport: transport, handler: handler ) activeTransactions[transaction.transactionId] = transaction return transaction } // MARK: - Helpers private func getOrCreateDMRoomId(userId: String) async throws -> String { guard let session = session else { log.error("Session not available") throw MXSession.Error.missingRoom } let room = try await session.getOrCreateDirectJoinedRoom(with: userId) guard let roomId = room.roomId else { log.failure("Missing room id") throw MXSession.Error.missingRoom } return roomId } private func isRoomVerificationEvent(_ event: MXEvent) -> Bool { // Filter incoming events by allowed list of event types guard Self.dmEventTypes.contains(where: { $0.identifier == event.type }) else { return false } // If it isn't a room message, it must be one of the direction verification events guard event.type == MXEventType.roomMessage.identifier else { return true } // If the event does not have a message type, it cannot be accepted guard let messageType = event.content[kMXMessageTypeKey] as? String else { return false } // Only requests are wrapped inside `m.room.message` types return messageType == kMXMessageTypeKeyVerificationRequest } } #endif
debb9ee0aa8e18103a6b4194ec76600a
35.211169
155
0.593715
false
false
false
false
MadhuraMarathe/MMOpenWeatherForecast
refs/heads/master
MMOpenWeatherForecast/MMOpenWeatherForecast/ViewControllers/MapViewController.swift
mit
1
// // MapViewController.swift // MMOpenWeatherForecast // // Created by Madhura Sudhir Marathe on 24/01/17. // Copyright © 2017 Madhura. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! var cityTemperaturesArray : [CityTemperatures] = [] override func viewDidLoad() { super.viewDidLoad() //mapView.showsUserLocation = true mapView.delegate = self self.setUpUI() } func setUpUI() { let annotations = getMapAnnotations() // Add mappoints to Map mapView.addAnnotations(annotations) mapView.showAnnotations(mapView.annotations, animated: true) mapView.showsPointsOfInterest = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getMapAnnotations() -> [MapCity] { var annotations:Array = [MapCity]() //iterate and create annotations for items in cityTemperaturesArray { let cityTemperature = items as CityTemperatures var lat = 0.0 var long = 0.0 // lat, longs received from webservice are wrong if cityTemperature.weatherInfo.name == "Melbourne" { lat = -37.8136 long = 144.9631 } else { lat = cityTemperature.weatherInfo.latitude long = cityTemperature.weatherInfo.longitude } let annotation = MapCity(latitude: lat, longitude: long) annotation.title = cityTemperature.weatherInfo.name annotations.append(annotation) } return annotations } // MARK: IBActions @IBAction func changeMapTypeAction(_ sender: Any) { if mapView.mapType == MKMapType.standard { mapView.mapType = MKMapType.satellite } else { mapView.mapType = MKMapType.standard } } // MARK : MapView delegate methods func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { mapView.centerCoordinate = (userLocation.location?.coordinate)! } }
364e3891626fb96dd465a0037aeb206e
26.367816
78
0.594708
false
false
false
false
teambition/GrowingTextView
refs/heads/master
GrowingTextViewExample/RightMessageCell.swift
mit
1
// // RightMessageCell.swift // GrowingTextViewExample // // Created by 洪鑫 on 16/2/17. // Copyright © 2016年 Teambition. All rights reserved. // import UIKit let kRightMessageCellID = "RightMessageCell" private let leftPadding: CGFloat = UIScreen.main.bounds.width / 4 private let rightPadding: CGFloat = 20 class RightMessageCell: UITableViewCell { @IBOutlet weak var contentLabel: MessageLabel! @IBOutlet weak var contentLabelLeadingSpace: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() contentLabel.layer.masksToBounds = true contentLabel.layer.cornerRadius = 6 } class func rowHeight(for message: String) -> CGFloat { return contentLabelFrame(for: message).height + 15 } class func leadingSpace(for message: String) -> CGFloat { return UIScreen.main.bounds.width - rightPadding - contentLabelFrame(for: message).width } fileprivate class func contentLabelFrame(for message: String) -> CGRect { guard !message.isEmpty else { return .zero } let messageString = message as NSString let size = CGSize(width: UIScreen.main.bounds.width - leftPadding - rightPadding, height: CGFloat.greatestFiniteMagnitude) let frame = messageString.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: 16)], context: nil) return CGRect(x: ceil(frame.origin.x), y: ceil(frame.origin.y), width: ceil(frame.width) + kMessageLabelPadding * 2.0, height: ceil(frame.height)) } }
ed672690871968c29f4c4f0c7230403f
36.690476
158
0.708149
false
false
false
false
NikitaAsabin/pdpDecember
refs/heads/master
Pods/FSHelpers+Swift/Swift/Helpers/FSExtensions/FSE+UIView.swift
mit
1
// // FSExtensions+UIView.swift // SwiftHelpers // // Created by Kruperfone on 31.07.15. // Copyright (c) 2015 FlatStack. All rights reserved. // import UIKit public extension UIView { //MARK: - Set size var fs_size: CGSize { set (value) {self.frame.size = value} get {return self.frame.size} } var fs_width:CGFloat { set (value) {self.fs_size = CGSizeMake(value, frame.size.height)} get {return self.frame.size.width} } var fs_height:CGFloat { set (value) {self.fs_size = CGSizeMake(frame.size.width, value)} get {return self.frame.size.height} } //MARK: - Set origin var fs_origin: CGPoint { set (value) {self.frame.origin = value} get {return self.frame.origin} } var fs_x: CGFloat { set (value) {self.fs_origin = CGPointMake(value, frame.origin.y)} get {return self.frame.origin.x} } var fs_y: CGFloat { set (value) {self.fs_origin = CGPointMake(frame.origin.x, value)} get {return self.frame.origin.y} } //MARK: - Other func fs_findAndResignFirstResponder () -> Bool { if self.isFirstResponder() { self.resignFirstResponder() return true } for view in subviews { if view.fs_findAndResignFirstResponder() { return true } } return false } var fs_allSubviews: [UIView] { var arr:[UIView] = [self] for view in subviews { arr += view.fs_allSubviews } return arr } }
5bf60706aa9f3585c63ee3f00d2ba6ff
22.712329
73
0.523975
false
false
false
false
ludoded/ReceiptBot
refs/heads/master
Pods/BRYXBanner/Pod/Classes/Banner.swift
lgpl-3.0
1
// // Banner.swift // // Created by Harlan Haskins on 7/27/15. // Copyright (c) 2015 Bryx. All rights reserved. // import UIKit private enum BannerState { case showing, hidden, gone } /// Wheter the banner should appear at the top or the bottom of the screen. /// /// - Top: The banner will appear at the top. /// - Bottom: The banner will appear at the bottom. public enum BannerPosition { case top, bottom } /// A level of 'springiness' for Banners. /// /// - None: The banner will slide in and not bounce. /// - Slight: The banner will bounce a little. /// - Heavy: The banner will bounce a lot. public enum BannerSpringiness { case none, slight, heavy fileprivate var springValues: (damping: CGFloat, velocity: CGFloat) { switch self { case .none: return (damping: 1.0, velocity: 1.0) case .slight: return (damping: 0.7, velocity: 1.5) case .heavy: return (damping: 0.6, velocity: 2.0) } } } /// Banner is a dropdown notification view that presents above the main view controller, but below the status bar. open class Banner: UIView { class func topWindow() -> UIWindow? { for window in UIApplication.shared.windows.reversed() { if window.windowLevel == UIWindowLevelNormal && !window.isHidden && window.frame != CGRect.zero { return window } } return nil } private let contentView = UIView() private let labelView = UIView() private let backgroundView = UIView() /// How long the slide down animation should last. open var animationDuration: TimeInterval = 0.4 /// The preferred style of the status bar during display of the banner. Defaults to `.LightContent`. /// /// If the banner's `adjustsStatusBarStyle` is false, this property does nothing. open var preferredStatusBarStyle = UIStatusBarStyle.lightContent /// Whether or not this banner should adjust the status bar style during its presentation. Defaults to `false`. open var adjustsStatusBarStyle = false /// Wheter the banner should appear at the top or the bottom of the screen. Defaults to `.Top`. open var position = BannerPosition.top /// How 'springy' the banner should display. Defaults to `.Slight` open var springiness = BannerSpringiness.slight /// The color of the text as well as the image tint color if `shouldTintImage` is `true`. open var textColor = UIColor.white { didSet { resetTintColor() } } /// The height of the banner. Default is 80. open var minimumHeight: CGFloat = 80 /// Whether or not the banner should show a shadow when presented. open var hasShadows = true { didSet { resetShadows() } } /// The color of the background view. Defaults to `nil`. override open var backgroundColor: UIColor? { get { return backgroundView.backgroundColor } set { backgroundView.backgroundColor = newValue } } /// The opacity of the background view. Defaults to 0.95. override open var alpha: CGFloat { get { return backgroundView.alpha } set { backgroundView.alpha = newValue } } /// A block to call when the uer taps on the banner. open var didTapBlock: (() -> ())? /// A block to call after the banner has finished dismissing and is off screen. open var didDismissBlock: (() -> ())? /// Whether or not the banner should dismiss itself when the user taps. Defaults to `true`. open var dismissesOnTap = true /// Whether or not the banner should dismiss itself when the user swipes up. Defaults to `true`. open var dismissesOnSwipe = true /// Whether or not the banner should tint the associated image to the provided `textColor`. Defaults to `true`. open var shouldTintImage = true { didSet { resetTintColor() } } /// The label that displays the banner's title. open let titleLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() /// The label that displays the banner's subtitle. open let detailLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.subheadline) label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() /// The image on the left of the banner. let image: UIImage? /// The image view that displays the `image`. open let imageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit return imageView }() private var bannerState = BannerState.hidden { didSet { if bannerState != oldValue { forceUpdates() } } } /// A Banner with the provided `title`, `subtitle`, and optional `image`, ready to be presented with `show()`. /// /// - parameter title: The title of the banner. Optional. Defaults to nil. /// - parameter subtitle: The subtitle of the banner. Optional. Defaults to nil. /// - parameter image: The image on the left of the banner. Optional. Defaults to nil. /// - parameter backgroundColor: The color of the banner's background view. Defaults to `UIColor.blackColor()`. /// - parameter didTapBlock: An action to be called when the user taps on the banner. Optional. Defaults to `nil`. public required init(title: String? = nil, subtitle: String? = nil, image: UIImage? = nil, backgroundColor: UIColor = UIColor.black, didTapBlock: (() -> ())? = nil) { self.didTapBlock = didTapBlock self.image = image super.init(frame: CGRect.zero) resetShadows() addGestureRecognizers() initializeSubviews() resetTintColor() imageView.image = image titleLabel.text = title detailLabel.text = subtitle backgroundView.backgroundColor = backgroundColor backgroundView.alpha = 0.95 } private func forceUpdates() { guard let superview = superview, let showingConstraint = showingConstraint, let hiddenConstraint = hiddenConstraint else { return } switch bannerState { case .hidden: superview.removeConstraint(showingConstraint) superview.addConstraint(hiddenConstraint) case .showing: superview.removeConstraint(hiddenConstraint) superview.addConstraint(showingConstraint) case .gone: superview.removeConstraint(hiddenConstraint) superview.removeConstraint(showingConstraint) superview.removeConstraints(commonConstraints) } setNeedsLayout() setNeedsUpdateConstraints() // Managing different -layoutIfNeeded behaviours among iOS versions (for more, read the UIKit iOS 10 release notes) if #available(iOS 10.0, *) { superview.layoutIfNeeded() } else { layoutIfNeeded() } updateConstraintsIfNeeded() } internal func didTap(_ recognizer: UITapGestureRecognizer) { if dismissesOnTap { dismiss() } didTapBlock?() } internal func didSwipe(_ recognizer: UISwipeGestureRecognizer) { if dismissesOnSwipe { dismiss() } } private func addGestureRecognizers() { addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(Banner.didTap(_:)))) let swipe = UISwipeGestureRecognizer(target: self, action: #selector(Banner.didSwipe(_:))) swipe.direction = .up addGestureRecognizer(swipe) } private func resetTintColor() { titleLabel.textColor = textColor detailLabel.textColor = textColor imageView.image = shouldTintImage ? image?.withRenderingMode(.alwaysTemplate) : image imageView.tintColor = shouldTintImage ? textColor : nil } private func resetShadows() { layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = self.hasShadows ? 0.5 : 0.0 layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowRadius = 4 } private var contentTopOffsetConstraint: NSLayoutConstraint! private var minimumHeightConstraint: NSLayoutConstraint! private func initializeSubviews() { let views = [ "backgroundView": backgroundView, "contentView": contentView, "imageView": imageView, "labelView": labelView, "titleLabel": titleLabel, "detailLabel": detailLabel ] translatesAutoresizingMaskIntoConstraints = false addSubview(backgroundView) minimumHeightConstraint = backgroundView.constraintWithAttribute(.height, .greaterThanOrEqual, to: minimumHeight) addConstraint(minimumHeightConstraint) // Arbitrary, but looks nice. addConstraints(backgroundView.constraintsEqualToSuperview()) backgroundView.backgroundColor = backgroundColor backgroundView.addSubview(contentView) labelView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(labelView) labelView.addSubview(titleLabel) labelView.addSubview(detailLabel) backgroundView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("H:|[contentView]|", views: views)) backgroundView.addConstraint(contentView.constraintWithAttribute(.bottom, .equal, to: .bottom, of: backgroundView)) contentTopOffsetConstraint = contentView.constraintWithAttribute(.top, .equal, to: .top, of: backgroundView) backgroundView.addConstraint(contentTopOffsetConstraint) let leftConstraintText: String if image == nil { leftConstraintText = "|" } else { contentView.addSubview(imageView) contentView.addConstraint(imageView.constraintWithAttribute(.leading, .equal, to: contentView, constant: 15.0)) contentView.addConstraint(imageView.constraintWithAttribute(.centerY, .equal, to: contentView)) imageView.addConstraint(imageView.constraintWithAttribute(.width, .equal, to: 25.0)) imageView.addConstraint(imageView.constraintWithAttribute(.height, .equal, to: .width)) leftConstraintText = "[imageView]" } let constraintFormat = "H:\(leftConstraintText)-(15)-[labelView]-(8)-|" contentView.translatesAutoresizingMaskIntoConstraints = false contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat(constraintFormat, views: views)) contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(>=1)-[labelView]-(>=1)-|", views: views)) backgroundView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("H:|[contentView]-(<=1)-[labelView]", options: .alignAllCenterY, views: views)) for view in [titleLabel, detailLabel] { let constraintFormat = "H:|[label]-(8)-|" contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat(constraintFormat, options: NSLayoutFormatOptions(), metrics: nil, views: ["label": view])) } labelView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(10)-[titleLabel][detailLabel]-(10)-|", views: views)) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var showingConstraint: NSLayoutConstraint? private var hiddenConstraint: NSLayoutConstraint? private var commonConstraints = [NSLayoutConstraint]() override open func didMoveToSuperview() { super.didMoveToSuperview() guard let superview = superview, bannerState != .gone else { return } commonConstraints = self.constraintsWithAttributes([.leading, .trailing], .equal, to: superview) superview.addConstraints(commonConstraints) switch self.position { case .top: showingConstraint = self.constraintWithAttribute(.top, .equal, to: .top, of: superview) let yOffset: CGFloat = -7.0 // Offset the bottom constraint to make room for the shadow to animate off screen. hiddenConstraint = self.constraintWithAttribute(.bottom, .equal, to: .top, of: superview, constant: yOffset) case .bottom: showingConstraint = self.constraintWithAttribute(.bottom, .equal, to: .bottom, of: superview) let yOffset: CGFloat = 7.0 // Offset the bottom constraint to make room for the shadow to animate off screen. hiddenConstraint = self.constraintWithAttribute(.top, .equal, to: .bottom, of: superview, constant: yOffset) } } open override func layoutSubviews() { super.layoutSubviews() adjustHeightOffset() layoutIfNeeded() } private func adjustHeightOffset() { guard let superview = superview else { return } if superview === Banner.topWindow() && self.position == .top { let statusBarSize = UIApplication.shared.statusBarFrame.size let heightOffset = min(statusBarSize.height, statusBarSize.width) // Arbitrary, but looks nice. contentTopOffsetConstraint.constant = heightOffset minimumHeightConstraint.constant = statusBarSize.height > 0 ? minimumHeight : 40 } else { contentTopOffsetConstraint.constant = 0 minimumHeightConstraint.constant = 0 } } /// Shows the banner. If a view is specified, the banner will be displayed at the top of that view, otherwise at top of the top window. If a `duration` is specified, the banner dismisses itself automatically after that duration elapses. /// - parameter view: A view the banner will be shown in. Optional. Defaults to 'nil', which in turn means it will be shown in the top window. duration A time interval, after which the banner will dismiss itself. Optional. Defaults to `nil`. open func show(_ view: UIView? = Banner.topWindow(), duration: TimeInterval? = nil) { guard let view = view else { print("[Banner]: Could not find view. Aborting.") return } view.addSubview(self) forceUpdates() let (damping, velocity) = self.springiness.springValues let oldStatusBarStyle = UIApplication.shared.statusBarStyle if adjustsStatusBarStyle { UIApplication.shared.setStatusBarStyle(preferredStatusBarStyle, animated: true) } UIView.animate(withDuration: animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .allowUserInteraction, animations: { self.bannerState = .showing }, completion: { finished in guard let duration = duration else { return } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(1000.0 * duration))) { self.dismiss(self.adjustsStatusBarStyle ? oldStatusBarStyle : nil) } }) } /// Dismisses the banner. open func dismiss(_ oldStatusBarStyle: UIStatusBarStyle? = nil) { let (damping, velocity) = self.springiness.springValues UIView.animate(withDuration: animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .allowUserInteraction, animations: { self.bannerState = .hidden if let oldStatusBarStyle = oldStatusBarStyle { UIApplication.shared.setStatusBarStyle(oldStatusBarStyle, animated: true) } }, completion: { finished in self.bannerState = .gone self.removeFromSuperview() self.didDismissBlock?() }) } } extension NSLayoutConstraint { class func defaultConstraintsWithVisualFormat(_ format: String, options: NSLayoutFormatOptions = NSLayoutFormatOptions(), metrics: [String: AnyObject]? = nil, views: [String: AnyObject] = [:]) -> [NSLayoutConstraint] { return NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: metrics, views: views) } } extension UIView { func constraintsEqualToSuperview(_ edgeInsets: UIEdgeInsets = UIEdgeInsets.zero) -> [NSLayoutConstraint] { self.translatesAutoresizingMaskIntoConstraints = false var constraints = [NSLayoutConstraint]() if let superview = self.superview { constraints.append(self.constraintWithAttribute(.leading, .equal, to: superview, constant: edgeInsets.left)) constraints.append(self.constraintWithAttribute(.trailing, .equal, to: superview, constant: edgeInsets.right)) constraints.append(self.constraintWithAttribute(.top, .equal, to: superview, constant: edgeInsets.top)) constraints.append(self.constraintWithAttribute(.bottom, .equal, to: superview, constant: edgeInsets.bottom)) } return constraints } func constraintWithAttribute(_ attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to constant: CGFloat, multiplier: CGFloat = 1.0) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: nil, attribute: .notAnAttribute, multiplier: multiplier, constant: constant) } func constraintWithAttribute(_ attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to otherAttribute: NSLayoutAttribute, of item: AnyObject? = nil, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: item ?? self, attribute: otherAttribute, multiplier: multiplier, constant: constant) } func constraintWithAttribute(_ attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to item: AnyObject, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: item, attribute: attribute, multiplier: multiplier, constant: constant) } func constraintsWithAttributes(_ attributes: [NSLayoutAttribute], _ relation: NSLayoutRelation, to item: AnyObject, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> [NSLayoutConstraint] { return attributes.map { self.constraintWithAttribute($0, relation, to: item, multiplier: multiplier, constant: constant) } } }
900b9eeb4d21cde81603a2ad6d42c62f
46.108108
245
0.675794
false
false
false
false
rsaenzi/MyMoviesListApp
refs/heads/master
MyMoviesListApp/MyMoviesListApp/SearchMovieResponse.swift
mit
1
// // SearchMovieResponse.swift // MyMoviesListApp // // Created by Rigoberto Sáenz Imbacuán on 5/28/17. // Copyright © 2017 Rigoberto Sáenz Imbacuán. All rights reserved. // import Foundation import ObjectMapper struct SearchMovieResponse { var type: String = "" var title: String = "" var year: Int = 0 var traktId: Int64 = 0 var slugId: String = "" var imdbId: String = "" var tmdbId: Int64 = 0 var overview: String = "" var image: String = "" } extension SearchMovieResponse: Mappable { mutating func mapping(map: Map) { type <- map[JsonKey.type.rawValue] title <- map[JsonKey.title.rawValue] year <- map[JsonKey.year.rawValue] traktId <- map[JsonKey.traktId.rawValue] slugId <- map[JsonKey.slugId.rawValue] imdbId <- map[JsonKey.imdbId.rawValue] tmdbId <- map[JsonKey.tmdbId.rawValue] overview <- map[JsonKey.overview.rawValue] } init?(map: Map) {} } fileprivate enum JsonKey: String { case type case title = "movie.title" case year = "movie.year" case traktId = "movie.ids.trakt" case slugId = "movie.ids.slug" case imdbId = "movie.ids.imdb" case tmdbId = "movie.ids.tmdb" case overview = "movie.overview" }
0c0fd08bb7d62fdf7bc6b4ec8546f46d
24.84
67
0.628483
false
false
false
false
LaszloPinter/CircleColorPicker
refs/heads/master
CircleColorPicker/ColorPicker/Views/LinearPickers/BrightnessPickerView.swift
mit
1
// // BrightnessPickerView.swift // CircleColorPicker // // Created by Laszlo Pinter on 11/17/17. // Copyright © 2017 Laszlo Pinter. All rights reserved. // import UIKit open class BrightnessPickerView: LinearPickerView { open override func handleOrientationChange() { (frontLayerView as! BrightnessMask).isVertical = isVertical } open override func createFrontLayerView() -> UIView{ let frontLayer = BrightnessMask(frame: CGRect.init(origin: CGPoint.zero, size: self.bounds.size)) frontLayer.isVertical = isVertical return frontLayer } class BrightnessMask: UIView { public var isVertical = false func drawScale(context: CGContext){ let startColor = UIColor.init(hue: 1, saturation: 0, brightness: 0, alpha: 1).cgColor let endColor = UIColor.init(hue: 1, saturation: 0, brightness: 0, alpha: 0).cgColor let colorSpace = CGColorSpaceCreateDeviceRGB() let colors = [startColor, endColor] as CFArray if let gradient = CGGradient.init(colorsSpace: colorSpace, colors: colors, locations: nil) { var startPoint: CGPoint! var endPoint: CGPoint! if isVertical { startPoint = CGPoint(x: self.bounds.width, y: self.bounds.height) endPoint = CGPoint(x: self.bounds.width, y: 0) }else { startPoint = CGPoint(x: 0, y: self.bounds.height) endPoint = CGPoint(x: self.bounds.width, y: self.bounds.height) } context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: .drawsBeforeStartLocation) } } override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } drawScale(context: context) } } }
2ffde5ab0ad167ad8e10f99da5fbe79c
34.186441
122
0.577071
false
false
false
false
jad6/CV
refs/heads/master
Swift/Jad's CV/Other/Extensions/View.swift
bsd-3-clause
1
// // View.swift // Jad's CV // // Created by Jad Osseiran on 16/07/2014. // Copyright (c) 2014 Jad. All rights reserved. // import UIKit /** * Returns an array of views which share the widest width O(n). * The returned views are returned in the order of which they are given. * * :param: views Views from which to find the widest ones. * * :returns: The views which share the widest width. */ func widestViews(#views: [UIView]) -> [UIView] { var widestViews = [UIView]() for view in views { if widestViews.count > 0 { let widestWidth = widestViews.first!.frame.size.width let viewWidth = view.frame.size.width if widestWidth < viewWidth { widestViews.removeAll(keepCapacity: false) widestViews += [view] } else if widestWidth == viewWidth { widestViews += [view] } } else { widestViews += [view] } } return widestViews } /** * Returns the first widest view from the given array of views O(n). * To return all widest views use the `wisdestViews` function. * * :param: views Views from which to find the widest. * * :returns: The first widest view. */ func widestView(#views: [UIView]) -> UIView! { let wideViews = widestViews(views: views) return wideViews.first } /** * Returns an array of views which share the tallest height O(n). * The returned views are returned in the order of which they are given. * * :param: views Views from which to find the tallest ones. * * :returns: The views which share the tallest height. */ func tallestViews(#views: [UIView]) -> [UIView] { var tallestViews = [UIView]() for view in views { if tallestViews.count > 0 { let tallestHeight = tallestViews.first!.frame.size.height let viewHeight = view.frame.size.height if tallestHeight < viewHeight { tallestViews.removeAll(keepCapacity: false) tallestViews += [view] } else if tallestHeight == viewHeight { tallestViews += [view] } } else { tallestViews += [view] } } return tallestViews } /** * Returns the first tallest view from the given array of views O(n). * To return all tallest views use the `tallestViews` function. * * :param: views Views from which to find the tallest. * * :returns: The first tallest view. */ func tallestView(#views: [UIView]) -> UIView! { let tallViews = tallestViews(views: views) return tallViews.first } func totalWidth(#views: [UIView], #separatorLength: CGFloat) -> CGFloat { var totalWidth: CGFloat = 0.0 for view in views { totalWidth += view.frame.size.width } return totalWidth + (CGFloat(views.count - 1) * separatorLength) } /** * Function to retrieve the total combined width of the given views taking into * account the space separating each view. * * :param: views Views which make up the accumulated width. * :param: separatorLength The separator length between each views. * * :returns: The combined total width including the separation between views. */ func totalWidth(#views: [UIView]) -> CGFloat { return totalWidth(views: views, separatorLength: 0.0) } /** * Function to retrieve the total combined width of the given views. * * :param: views Views which make up the accumulated width. * * :returns: The combined total width. */ func totalHeight(#views: [UIView], #separatorLength: CGFloat) -> CGFloat { var totalHeight: CGFloat = 0.0 for view in views { totalHeight += view.frame.size.height } return totalHeight + (CGFloat(views.count - 1) * separatorLength) } /** * Function to retrieve the total combined height of the given views taking into * account the space separating each view. * * :param: views Views which make up the accumulated height. * :param: separatorLength The separator length between each views. * * :returns: The combined total height including the separation between views. */ func totalHeight(#views: [UIView]) -> CGFloat { return totalHeight(views: views, separatorLength: 0.0) } /** * Function to retrieve the total combined height of the given views. * * :param: views Views which make up the accumulated height. * * :returns: The combined total height. */ extension UIView { //MARK:- Hiding /** * Hides or unhides the view with the option the animate the transition. * * :param: hidden Wether the view is to be hidden or not. * :param: animated Flag to animate the trasition. * :param: duration The duration of the hiding animation if turned on. * :param: completion Call back when the view has been hid or unhid. */ func setHidden(hide: Bool, animated: Bool, duration: Double, completion: ((Bool) -> Void)!) { if animated { if hide { UIView.animateWithDuration(duration, animations: { self.alpha = 0.0 }, completion: { finished in if finished { self.hidden = true } if completion { completion(finished) } }) } else { alpha = 0.0 hidden = false UIView.animateWithDuration(duration, animations: { self.alpha = 1.0 }, completion: completion) } } else { alpha = hide ? 0.0 : 1.0 hidden = hide if completion { completion(true) } } } /** * Hides or unhides the view with the option the animate the transition. * * For tighter control over the transition use setHidden:animated:duration:completion: * * :param: hidden Wether the view is to be hidden or not. * :param: animated Flag to animate the trasition. */ func setHidden(hide: Bool, animated: Bool) { setHidden(hide, animated: animated, duration: Animations.Durations.Short.toRaw(), completion: nil) } //MARK:- Positioning /** * Calculates and returns the value for the X origin of the view which will * center it in relation to the given frame. * The returned X origin is floored. * * :param: frame The frame which the view will use to center itself. * * :returns: The X origin for the view to take in order to be centered. */ func horizontalCenterWithReferenceFrame(frame: CGRect) -> CGFloat { let offset = floor((frame.size.width - self.frame.size.width) / 2.0) return frame.origin.x + offset } /** * Calculates and returns the value for the Y origin of the view which will * center it in relation to the given frame. * The returned Y origin is floored. * * :param: frame The frame which the view will use to center itself. * * :returns: The Y origin for the view to take in order to be centered. */ func verticalCenterWithReferenceFrame(frame: CGRect) -> CGFloat { let offset = floor((frame.size.height - self.frame.size.height) / 2.0) return frame.origin.y + offset } /** * This method centers the view to be centered on the X axis with relation * to the passed view. * * :param: rect The rect which is used as a horizontal centering reference. */ func centerHorizontallyWithReferenceRect(rect: CGRect) { self.frame.origin.x = horizontalCenterWithReferenceFrame(rect) } /** * This method centers the view to be centered on the Y axis with relation * to the passed view. * * :param: rect The rect which is used as a vertical centering reference. */ func centerVerticallyWithReferenceRect(rect: CGRect) { self.frame.origin.y = verticalCenterWithReferenceFrame(rect) } //MARK:- Masking /** * Method to set a rounded edges mask on the view's layer. * * :param: radius The radius to use for the rounded edges. */ func maskToRadius(radius: CGFloat) { layer.cornerRadius = radius layer.masksToBounds = true } /** * Masks the view's layer to be in a cirle. */ func maskToCircle() { maskToRadius(frame.size.width / 2.0) } }
d4ea2d4c319cacde171f9bddbad257d3
30.26087
106
0.607093
false
false
false
false
material-components/material-components-ios
refs/heads/develop
components/FlexibleHeader/tests/snapshot/FlexibleHeaderTrackingScrollViewDidChangeTests.swift
apache-2.0
2
// Copyright 2019-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. import XCTest import MaterialComponents.MaterialFlexibleHeader import MaterialComponents.MaterialShadowLayer class FlexibleHeaderTrackingScrollViewDidChangeTests: XCTestCase { func testFromExpandedToCollapsedStateAnimatesShadowPath() throws { // Given let window = UIWindow() let fhvc = MDCFlexibleHeaderViewController() let shadowLayer = MDCShadowLayer() fhvc.headerView.setShadowLayer(shadowLayer) { layer, elevation in guard let shadowLayer = layer as? MDCShadowLayer else { return } shadowLayer.elevation = .init(4 * elevation) } fhvc.headerView.frame = CGRect(x: 0, y: 0, width: 100, height: 0) fhvc.headerView.minMaxHeightIncludesSafeArea = false fhvc.headerView.sharedWithManyScrollViews = true fhvc.headerView.maximumHeight = 200 fhvc.headerView.allowShadowLayerFrameAnimationsWhenChangingTrackingScrollView = true let scrollView1 = UIScrollView() let scrollView2 = UIScrollView() let largeScrollableArea = CGSize(width: fhvc.headerView.frame.width, height: 1000) scrollView1.contentSize = largeScrollableArea scrollView2.contentSize = largeScrollableArea // Fully expanded. scrollView1.contentOffset = CGPoint(x: 0, y: -200) // Fully collapsed. scrollView2.contentOffset = CGPoint(x: 0, y: 300) // Initially fully expanded. fhvc.headerView.trackingScrollView = scrollView1 window.rootViewController = fhvc window.makeKeyAndVisible() CATransaction.flush() // When // And then collapsed. fhvc.headerView.trackingScrollView = scrollView2 // Then XCTAssertNotNil(fhvc.headerView.layer.animation(forKey: "bounds.size")) XCTAssertNotNil(fhvc.headerView.layer.animation(forKey: "bounds.origin")) XCTAssertNotNil(fhvc.headerView.layer.animation(forKey: "position")) guard let animationDuration = fhvc.headerView.layer.animation(forKey: "bounds.size")?.duration else { XCTFail("Missing bounds.size animation") return } guard let sublayers = shadowLayer.sublayers else { XCTFail("Missing sublayers.") return } XCTAssertGreaterThan(sublayers.count, 0) for sublayer in sublayers { guard let animation = sublayer.animation(forKey: "shadowPath") else { XCTFail("Missing shadowPath animation. \(sublayer)") return } XCTAssertNotNil(animation) XCTAssertEqual(animation.duration, animationDuration, accuracy: 0.001) } } }
3ee31655d09691c15b73201c48414645
36.285714
88
0.731481
false
false
false
false
PJayRushton/stats
refs/heads/master
Stats/ContactsHelper.swift
mit
1
// // ContactsHelper.swift // Stats // // Created by Parker Rushton on 6/3/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import Foundation import ContactsUI import Contacts class ContactsHelper: NSObject { // MARK: - Types enum ContactsError: Error { case formatting } // MARK: - Init fileprivate let viewController: UIViewController init(viewController: UIViewController) { self.viewController = viewController } fileprivate let store = CNContactStore() // MARK: - Public var contactSelected: ((Result<(String, String)>) -> Void) = { _ in } func addressButtonPressed() { presentContactPicker() } func presentErrorAlert() { let alert = UIAlertController(title: "This is awkward. . . 😅", message: "Something went wrong when selecting your contact", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Its OK 😞", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Try again", style: .default, handler: { _ in self.presentContactPicker() })) viewController.present(alert, animated: true, completion: nil) } } // MARK: - Private extension ContactsHelper { fileprivate var contactKeys: [String] { return [CNContactPhoneNumbersKey] } fileprivate func presentContactPicker() { requestAccess { [unowned self] accessGranted in DispatchQueue.main.async { if accessGranted { self.presentContactPickerViewController() } else { self.presentPermissionErrorAlert() } } } } fileprivate func requestAccess(completion: ((Bool) -> Void)? = nil) { store.requestAccess(for: CNEntityType.contacts) { (granted, error) in completion?(granted) } } fileprivate func presentContactPickerViewController() { let contactPickerVC = CNContactPickerViewController() contactPickerVC.delegate = self contactPickerVC.title = "Select a phone number" contactPickerVC.navigationController?.navigationBar.tintColor = .flatSkyBlue Appearance.setUp(navTextColor: .flatSkyBlue) contactPickerVC.displayedPropertyKeys = self.contactKeys contactPickerVC.predicateForEnablingContact = NSPredicate(format: "phoneNumbers.@count > 0") contactPickerVC.predicateForSelectionOfContact = NSPredicate(format: "phoneNumbers.@count == 1") contactPickerVC.predicateForSelectionOfProperty = NSPredicate(format: "key == phoneNumber") viewController.present(contactPickerVC, animated: true, completion: nil) } fileprivate func presentPermissionErrorAlert() { let alert = UIAlertController(title: "Access Denied", message: "St@ needs access to your contacts enable this feature", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Too bad 🤐 ", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Open Sesame! 🚪", style: .default, handler: { _ in guard let settingsURL = URL(string: UIApplicationOpenSettingsURLString) else { return } UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil) })) viewController.present(alert, animated: true, completion: nil) } fileprivate func process(contact: CNContact, contactProperty: CNContactProperty? = nil) { Appearance.setUp(navTextColor: .white) let name = contact.firstLastInitial if let phone = contactProperty?.value as? CNPhoneNumber { let selectedContact = (name, phone.stringValue) contactSelected(Result.success(selectedContact)) } else if let phone = contact.phoneNumbers.first?.value { let selectedContact = (name, phone.stringValue) contactSelected(Result.success(selectedContact)) } else { contactSelected(Result.failure(ContactsError.formatting)) } } } extension ContactsHelper: CNContactPickerDelegate { func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) { process(contact: contactProperty.contact, contactProperty: contactProperty) } func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { process(contact: contact) } func contactPickerDidCancel(_ picker: CNContactPickerViewController) { Appearance.setUp(navTextColor: .white) } } extension CNContact { var firstLastInitial: String { return "\(givenName) \(familyName.firstLetter)" } }
12f49c73e867aaee7eda1dc3fc742b96
32.645833
155
0.654076
false
false
false
false
zhiquan911/chance_btc_wallet
refs/heads/master
chance_btc_wallet/chance_btc_wallet/viewcontrollers/account/MultiSigAccountCreateViewController.swift
mit
1
// // MultiSigAccountCreateViewController.swift // Chance_wallet // // Created by Chance on 16/1/27. // Copyright © 2016年 Chance. All rights reserved. // import UIKit class MultiSigAccountCreateViewController: BaseViewController { @IBOutlet var labelTextNickname: CHLabelTextField! @IBOutlet var sliderKeys: UISlider! @IBOutlet var sliderRequired: UISlider! @IBOutlet var buttonNext: UIButton! @IBOutlet var labelTitle: UILabel! @IBOutlet var labelKeys: UILabel! @IBOutlet var labelRequired: UILabel! @IBOutlet var labelKeysTitle: UILabel! @IBOutlet var labelRequiredTitle: UILabel! let minKeys: Int = 2 let maxKeys: Int = 16 ///最小选择的钥匙数目2条 var selectedkeys: Int = 2 { didSet { self.labelKeys.text = self.selectedkeys.toString() } } /// 必要的签名数最少1 var selectedRequired: Int = 1 { didSet { self.labelRequired.text = self.selectedRequired.toString() } } override func viewDidLoad() { super.viewDidLoad() self.setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - 控制器方法 extension MultiSigAccountCreateViewController { /** 配置UI */ func setupUI() { self.navigationItem.title = "Create Account".localized() self.labelTitle.text = "Create Multi-Sig Acount".localized() self.labelTextNickname.title = "Account Nickname".localized() self.labelTextNickname.placeholder = "Give your account a nickname".localized() self.labelTextNickname.textField?.keyboardType = .default self.labelTextNickname.delegate = self self.labelKeysTitle.text = "How many keys you want?".localized() self.labelRequiredTitle.text = "How many signatures required of keys?".localized() self.buttonNext.setTitle("Next".localized(), for: [.normal]) self.sliderKeys.minimumValue = self.minKeys.toFloat() self.sliderKeys.maximumValue = self.maxKeys.toFloat() self.sliderKeys.value = self.minKeys.toFloat() self.labelKeys.text = self.selectedkeys.toString() self.sliderRequired.minimumValue = self.minKeys.toFloat() - 1 self.sliderRequired.maximumValue = self.maxKeys.toFloat() self.sliderRequired.value = self.minKeys.toFloat() - 1 self.labelRequired.text = self.selectedRequired.toString() } /** 点击下一步 - parameter sender: */ @IBAction func handleNextPress(_ sender: AnyObject?) { AppDelegate.sharedInstance().closeKeyBoard() if self.checkValue() { guard let vc = StoryBoard.account.initView(type: MultiSigInputKeyViewController.self) else { return } vc.keyCount = self.selectedkeys vc.requiredCount = self.selectedRequired vc.userName = self.labelTextNickname.text self.navigationController?.pushViewController(vc, animated: true) } } /** 检查值 - returns: */ func checkValue() -> Bool { if self.labelTextNickname.text.isEmpty { SVProgressHUD.showInfo(withStatus: "Username is empty".localized()) return false } // if self.textFieldTotalKeys.text!.isEmpty { // SVProgressHUD.showInfo(withStatus: "Input how many keys to create".localized()) // return false // } // // if self.textFieldRequiredKeys.text!.isEmpty { // SVProgressHUD.showInfo(withStatus: "Input how many signatures that account required".localized()) // return false // } // // if self.textFieldTotalKeys.text!.toInt() <= 1 { // SVProgressHUD.showInfo(withStatus: "The amount of keys should more then 1".localized()) // return false // } // if self.selectedRequired > self.selectedkeys { SVProgressHUD.showInfo(withStatus: "The amount of signatures can not more then the amount of keys".localized()) return false } return true } @IBAction func handleSliderValueChange(sender: UISlider) { if sender === self.sliderKeys { self.selectedkeys = lroundf(sender.value) } else if sender === self.sliderRequired { self.selectedRequired = lroundf(sender.value) } } } // MARK: - 文本代理方法 extension MultiSigAccountCreateViewController: CHLabelTextFieldDelegate { func textFieldShouldReturn(_ ltf: CHLabelTextField) -> Bool { ltf.textField?.resignFirstResponder() return true } }
ccbc7ea0cdbdced9cdc3b4dbfd21c633
30.23871
123
0.621231
false
false
false
false
wjk930726/weibo
refs/heads/master
weiBo/weiBo/iPhone/Manager/NetworkTool+request.swift
mit
1
// // NetworkTool+request.swift // weiBo // // Created by 王靖凯 on 2016/11/27. // Copyright © 2016年 王靖凯. All rights reserved. // import Alamofire import UIKit extension NetworkManager { @discardableResult public func requestForAccessToken(code: String, networkCompletionHandler: @escaping ([String: Any]?) -> Void) -> Cancellable? { let parameters = [ "client_id": appKey, "client_secret": appSecrect, "grant_type": "authorization_code", "code": code, "redirect_uri": redirectURI, ] return post(url: "https://api.weibo.com/oauth2/access_token", parameters: parameters, networkCompletionHandler: { networkCompletionHandler($0.value as? [String: Any]) }) } @discardableResult public func requestForUserInfo(parameters: [String: Any], networkCompletionHandler: @escaping ([String: Any]?) -> Void) -> Cancellable? { // 接口升级后,对未授权本应用的uid,将无法获取其个人简介、认证原因、粉丝数、关注数、微博数及最近一条微博内容。 return get(url: "https://api.weibo.com/2/users/show.json", parameters: parameters, networkCompletionHandler: { networkCompletionHandler($0.value as? [String: Any]) }) } @discardableResult public func requestForHomeStatus(sinceId: Int = 0, maxId: Int = 0, networkCompletionHandler: @escaping ([String: Any]?) -> Void) -> Cancellable? { if let access_token = WBUserAccountModel.shared.access_token { let parameters = [ "access_token": access_token, "since_id": NSNumber(value: sinceId), "max_id": NSNumber(value: maxId), ] as [String: Any] return get(url: "https://api.weibo.com/2/statuses/home_timeline.json", parameters: parameters, networkCompletionHandler: { networkCompletionHandler($0.value as? [String: Any]) }) } return nil } @discardableResult public func requestForWeather(parameters: [String: Any], networkCompletionHandler: @escaping ([String: Any]?) -> Void) -> Cancellable? { return get(url: "https://api.seniverse.com/v3/weather/now.json?key=hpejjcjphjea8ogq&language=zh-Hans&unit=c", parameters: parameters, networkCompletionHandler: { networkCompletionHandler($0.value as? [String: Any]) }) } @discardableResult public func postStatus(status: String, image: UIImage? = nil, success: @escaping ((_ response: Any?) -> Void), failure _: @escaping ((_ error: Error) -> Void)) -> Cancellable? { if let access_token = WBUserAccountModel.shared.access_token { let parameters = [ "access_token": access_token, "status": status, ] if image != nil { post(url: "https://upload.api.weibo.com/2/statuses/upload.json", parameters: parameters, image: image!, networkCompletionHandler: { response in success(response) }) } else { return post(url: "https://api.weibo.com/2/statuses/update.json", parameters: parameters, networkCompletionHandler: { response in success(response) }) } } return nil } }
37c2f352a49777f900bc966aad679c92
41.363636
181
0.608216
false
false
false
false
jkereako/MassStateKeno
refs/heads/master
Sources/Coordinators/LocationsCoordinator.swift
mit
1
// // LocationsCoordinator.swift // MassLotteryKeno // // Created by Jeff Kereakoglow on 5/24/19. // Copyright © 2019 Alexis Digital. All rights reserved. // import Kringle import UIKit final class LocationsCoordinator: RootCoordinator { var rootViewController: UIViewController { let viewController = UIViewController() viewController.title = "Locations" viewController.view.backgroundColor = .orange navigationController = UINavigationController( rootViewController: viewController ) return navigationController! } private let networkClient: NetworkClient private let dateFormatter: DateFormatter private var navigationController: UINavigationController? init(networkClient: NetworkClient, dateFormatter: DateFormatter) { self.networkClient = networkClient self.dateFormatter = dateFormatter } }
da89a4facf001d757cb8208270229da8
25.852941
70
0.722892
false
false
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/Filter.swift
mit
1
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** Filter. */ public struct Filter: Decodable { /// The type of aggregation command used. For example: term, filter, max, min, etc. public var type: String? public var results: [AggregationResult]? /// Number of matching results. public var matchingResults: Int? /// Aggregations returned by the Discovery service. public var aggregations: [QueryAggregation]? /// The match the aggregated results queried for. public var match: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case type = "type" case results = "results" case matchingResults = "matching_results" case aggregations = "aggregations" case match = "match" } }
e0a5af2437c9c83bc9c7d8ad5a50d81b
30.533333
87
0.699789
false
false
false
false
ashikahmad/SlideMenuControllerSwift
refs/heads/master
SlideMenuControllerSwift/AppDelegate.swift
mit
2
// // AppDelegate.swift // test11 // // Created by Yuji Hato on 4/20/15. // Copyright (c) 2015 Yuji Hato. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? fileprivate func createMenuView() { // create viewController code... let storyboard = UIStoryboard(name: "Main", bundle: nil) let mainViewController = storyboard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController let leftViewController = storyboard.instantiateViewController(withIdentifier: "LeftViewController") as! LeftViewController let rightViewController = storyboard.instantiateViewController(withIdentifier: "RightViewController") as! RightViewController let nvc: UINavigationController = UINavigationController(rootViewController: mainViewController) UINavigationBar.appearance().tintColor = UIColor(hex: "689F38") leftViewController.mainViewController = nvc let slideMenuController = ExSlideMenuController(mainViewController:nvc, leftMenuViewController: leftViewController, rightMenuViewController: rightViewController) slideMenuController.automaticallyAdjustsScrollViewInsets = true slideMenuController.delegate = mainViewController self.window?.backgroundColor = UIColor(red: 236.0, green: 238.0, blue: 241.0, alpha: 1.0) self.window?.rootViewController = slideMenuController self.window?.makeKeyAndVisible() } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.createMenuView() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "dekatotoro.test11" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "test11", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("test11.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error?.debugDescription ?? ""), \(error?.userInfo.debugDescription ?? "")") abort() } catch { fatalError() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges { do { try moc.save() } catch let error1 as NSError { error = error1 // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error?.debugDescription ?? ""), \(error?.userInfo.debugDescription ?? "")") abort() } } } } }
d709050556acb7df59bf8e5a4c13f061
53.172414
290
0.692934
false
false
false
false
moritzsternemann/SwipyCell
refs/heads/swift-package
Sources/SwipyCell/SwipyCellTypes.swift
mit
1
// // SwipyCellTypes.swift // SwipyCell // // Created by Moritz Sternemann on 20.01.16. // Copyright © 2016 Moritz Sternemann. All rights reserved. // import UIKit fileprivate struct Defaults { static let stop1: CGFloat = 0.25 // Percentage limit to trigger the first action static let stop2: CGFloat = 0.75 // Percentage limit to trigger the second action static let swipeViewPadding: CGFloat = 24.0 // Padding of the swipe view (space between cell and swipe view) static let shouldAnimateSwipeViews = true static let defaultSwipeViewColor = UIColor.white } public typealias SwipyCellTriggerBlock = (SwipyCell, SwipyCellTrigger, SwipyCellState, SwipyCellMode) -> Void public protocol SwipyCellDelegate { func swipyCellDidStartSwiping(_ cell: SwipyCell) func swipyCellDidFinishSwiping(_ cell: SwipyCell, atState state: SwipyCellState, triggerActivated activated: Bool) func swipyCell(_ cell: SwipyCell, didSwipeWithPercentage percentage: CGFloat, currentState state: SwipyCellState, triggerActivated activated: Bool) } public class SwipyCellTrigger { init(mode: SwipyCellMode, color: UIColor, view: UIView, block: SwipyCellTriggerBlock?) { self.mode = mode self.color = color self.view = view self.block = block } public var mode: SwipyCellMode public var color: UIColor public var view: UIView public var block: SwipyCellTriggerBlock? func executeTriggerBlock(withSwipyCell cell: SwipyCell, state: SwipyCellState) { block?(cell, self, state, mode) } } public enum SwipyCellState: Hashable { case none case state(Int, SwipyCellDirection) public func hash(into hasher: inout Hasher) { hasher.combine(integerRepresentation) } static public func ==(lhs: SwipyCellState, rhs: SwipyCellState) -> Bool { return lhs.integerRepresentation == rhs.integerRepresentation } private var integerRepresentation: Int { switch self { case .none: return 0 case .state(let stateNum, let stateDirection): // add one because state(0,...) would always be 0 if stateDirection == .left { return stateNum + 1 } else if stateDirection == .right { return -(stateNum + 1) } } return 0 } } public enum SwipyCellMode: UInt { case none = 0 case exit case toggle } public enum SwipyCellDirection: UInt { case left = 0 case center case right } public protocol SwipyCellTriggerPointEditable: class { var triggerPoints: [CGFloat: SwipyCellState] { get set } func setTriggerPoint(forState state: SwipyCellState, at point: CGFloat) func setTriggerPoint(forIndex index: Int, at point: CGFloat) func setTriggerPoints(_ points: [CGFloat: SwipyCellState]) func setTriggerPoints(_ points: [CGFloat: Int]) func setTriggerPoints(points: [CGFloat]) func getTriggerPoints() -> [CGFloat: SwipyCellState] func clearTriggerPoints() } extension SwipyCellTriggerPointEditable { public func setTriggerPoint(forState state: SwipyCellState, at point: CGFloat) { var p = abs(point) if case .state(_, let direction) = state, direction == .right { p = -p } triggerPoints[p] = state } public func setTriggerPoint(forIndex index: Int, at point: CGFloat) { let p = abs(point) triggerPoints[p] = SwipyCellState.state(index, .left) triggerPoints[-p] = SwipyCellState.state(index, .right) } public func setTriggerPoints(_ points: [CGFloat: SwipyCellState]) { triggerPoints = points } public func setTriggerPoints(_ points: [CGFloat: Int]) { triggerPoints = [:] _ = points.map { point, index in let p = abs(point) triggerPoints[p] = SwipyCellState.state(index, .left) triggerPoints[-p] = SwipyCellState.state(index, .right) } } public func setTriggerPoints(points: [CGFloat]) { triggerPoints = [:] for (index, point) in points.enumerated() { let p = abs(point) triggerPoints[p] = SwipyCellState.state(index, .left) triggerPoints[-p] = SwipyCellState.state(index, .right) } } public func getTriggerPoints() -> [CGFloat: SwipyCellState] { return triggerPoints } public func clearTriggerPoints() { triggerPoints = [:] } } public class SwipyCellConfig: SwipyCellTriggerPointEditable { public static let shared = SwipyCellConfig() public var triggerPoints: [CGFloat: SwipyCellState] public var swipeViewPadding: CGFloat public var shouldAnimateSwipeViews: Bool public var defaultSwipeViewColor: UIColor init() { triggerPoints = [:] triggerPoints[Defaults.stop1] = .state(0, .left) triggerPoints[Defaults.stop2] = .state(1, .left) triggerPoints[-Defaults.stop1] = .state(0, .right) triggerPoints[-Defaults.stop2] = .state(1, .right) swipeViewPadding = Defaults.swipeViewPadding shouldAnimateSwipeViews = Defaults.shouldAnimateSwipeViews defaultSwipeViewColor = Defaults.defaultSwipeViewColor } }
42a197e0502054054fc12b7f4324123c
31.533742
151
0.662832
false
false
false
false
kosuke/swift-opengl
refs/heads/master
App/App/AppDelegate.swift
unlicense
1
// // AppDelegate.swift // App // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "GL_Example") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
e6f4d73f7455b9d4764a182774d8a778
48.888889
285
0.685301
false
false
false
false
nicolasgomollon/STBTableViewIndex
refs/heads/master
STBTableViewIndex.swift
mit
1
// // STBTableViewIndex.swift // STBTableViewIndex // // Objective-C code Copyright (c) 2013 Benjamin Kreeger. All rights reserved. // Swift adaptation Copyright (c) 2014 Nicolas Gomollon. All rights reserved. // import Foundation import UIKit public let STBTableViewIndexLayoutDidChange: NSNotification.Name = UIDevice.orientationDidChangeNotification public protocol STBTableViewIndexDelegate: NSObjectProtocol { func tableViewIndexChanged(_ index: Int, title: String) func tableViewIndexTopLayoutGuideLength() -> CGFloat func tableViewIndexBottomLayoutGuideLength() -> CGFloat } open class STBTableViewIndex: UIControl { open weak var delegate: STBTableViewIndexDelegate! fileprivate var panGestureRecognizer: UIPanGestureRecognizer! fileprivate var tapGestureRecognizer: UITapGestureRecognizer! fileprivate var feedbackGenerator: AnyObject? open var currentIndex: Int = 0 open var currentTitle: String { return titles[currentIndex] } open var view: UIView = UIView(frame: .zero) open var titles: [String] { didSet { createLabels() } } open var autoHides: Bool = true open var visible: Bool { didSet { UIView.animate(withDuration: 0.2, animations: { self.view.alpha = self.visible ? 1.0 : 0.0 }) } } open var labels: [UILabel] = .init() fileprivate var canAutoHide: Bool { guard !UIAccessibility.isVoiceOverRunning else { return false } return autoHides } fileprivate var width: CGFloat { return 16.0 } fileprivate var horizontalPadding: CGFloat { return 5.0 } fileprivate var verticalPadding: CGFloat { return 5.0 } fileprivate var endPadding: CGFloat { return 3.0 } fileprivate var controlSizeWidth: CGFloat { return width + (horizontalPadding * 2.0) } fileprivate var controlOriginX: CGFloat { let superviewWidth: CGFloat = superview?.frame.size.width ?? UIScreen.main.bounds.size.width return superviewWidth - controlSizeWidth } fileprivate var controlOriginY: CGFloat { return delegate?.tableViewIndexTopLayoutGuideLength() ?? 0.0 } fileprivate var controlSizeHeight: CGFloat { var sizeHeight: CGFloat = 0.0 let screenHeight: CGFloat = UIScreen.main.bounds.size.height sizeHeight = screenHeight sizeHeight -= controlOriginY sizeHeight -= delegate?.tableViewIndexBottomLayoutGuideLength() ?? 0.0 return sizeHeight } fileprivate var controlFrame: CGRect { return CGRect(x: controlOriginX, y: controlOriginY, width: controlSizeWidth, height: controlSizeHeight) } fileprivate var controlBounds: CGRect { return CGRect(x: 0.0, y: 0.0, width: controlSizeWidth, height: controlSizeHeight) } fileprivate var viewFrame: CGRect { return controlBounds.insetBy(dx: horizontalPadding, dy: verticalPadding) } fileprivate var viewBounds: CGRect { return CGRect(x: 0.0, y: 0.0, width: viewFrame.size.width, height: viewFrame.size.height) } public convenience init() { self.init(frame: .zero) } public override init(frame: CGRect) { titles = .init() visible = true super.init(frame: .zero) initialize() } public required init?(coder aDecoder: NSCoder) { titles = .init() visible = true super.init(coder: aDecoder) initialize() } fileprivate func initialize() { panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(STBTableViewIndex._handleGesture(_:))) addGestureRecognizer(panGestureRecognizer) tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(STBTableViewIndex._handleGesture(_:))) addGestureRecognizer(tapGestureRecognizer) if #available(iOS 13.0, *) { let hoverGestureRecognizer: UIHoverGestureRecognizer = .init(target: self, action: #selector(STBTableViewIndex._handleHover(_:))) addGestureRecognizer(hoverGestureRecognizer) } view.backgroundColor = .white view.layer.borderColor = UIColor(white: 0.0, alpha: 0.1).cgColor view.layer.borderWidth = 1.0 view.layer.masksToBounds = true addSubview(view) isAccessibilityElement = true shouldGroupAccessibilityChildren = true accessibilityLabel = NSLocalizedString("STBTableViewIndex-LABEL", tableName: "STBTableViewIndex", bundle: .main, value: "Table index", comment: "") accessibilityTraits = [.adjustable] NotificationCenter.default.addObserver(self, selector: #selector(accessibilityVoiceOverStatusChanged), name: UIAccessibility.voiceOverStatusDidChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(setNeedsLayout), name: STBTableViewIndexLayoutDidChange, object: nil) setNeedsLayout() } deinit { NotificationCenter.default.removeObserver(self) } open override func layoutSubviews() { super.layoutSubviews() frame = controlFrame view.frame = viewFrame view.layer.cornerRadius = view.frame.width / 2.0 var labelOriginY: CGFloat = endPadding let labelWidth: CGFloat = view.frame.width let labelHeight: CGFloat = (view.frame.height - (endPadding * 2.0)) / CGFloat(labels.count) for label in labels { let labelFrame = CGRect(x: 0.0, y: labelOriginY, width: labelWidth, height: labelHeight) label.frame = labelFrame.integral labelOriginY += labelHeight } } fileprivate func createLabels() { for label in labels { label.removeFromSuperview() } labels.removeAll() for (tag, title) in titles.enumerated() { let label: UILabel = .init(frame: .zero) label.backgroundColor = .clear label.font = .boldSystemFont(ofSize: 10.0) label.textColor = view.tintColor label.textAlignment = .center label.text = title label.tag = tag view.addSubview(label) labels += [label] } } fileprivate func setNewIndex(point p: CGPoint) { var point: CGPoint = p point.x = view.frame.width / 2.0 for label in labels { guard label.frame.contains(point), label.tag != currentIndex else { continue } currentIndex = label.tag delegate?.tableViewIndexChanged(currentIndex, title: currentTitle) hapticFeedbackSelectionChanged() } } @objc open func hideIndex() { visible = false } open func showIndex() { visible = true } open func flashIndex() { view.alpha = 1.0 guard canAutoHide else { return } Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(hideIndex), userInfo: nil, repeats: false) } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { hapticFeedbackSetup() guard let location: CGPoint = touches.first?.location(in: self) else { return } setNewIndex(point: location) guard canAutoHide else { return } visible = true } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { hapticFeedbackFinalize() guard canAutoHide else { return } visible = false } @objc internal func _handleGesture(_ gesture: UIGestureRecognizer) { switch gesture.state { case .began: hapticFeedbackSetup() case .ended, .cancelled, .failed: hapticFeedbackFinalize() default: break } let location: CGPoint = gesture.location(in: self) setNewIndex(point: location) guard canAutoHide else { return } visible = !(gesture.state == .ended) } @objc internal func _handleHover(_ gesture: UIGestureRecognizer) { switch gesture.state { case .began, .changed: guard canAutoHide else { break } visible = true case .ended, .cancelled: guard canAutoHide else { break } visible = false default: break } } @objc internal func accessibilityVoiceOverStatusChanged() { guard autoHides else { return } visible = UIAccessibility.isVoiceOverRunning } open override func accessibilityElementDidLoseFocus() { accessibilityValue = nil } open override func accessibilityIncrement() { if currentIndex < (labels.count - 1) { currentIndex += 1 } delegate?.tableViewIndexChanged(currentIndex, title: currentTitle) accessibilityValue = currentTitle.lowercased() } open override func accessibilityDecrement() { if currentIndex > 0 { currentIndex -= 1 } delegate?.tableViewIndexChanged(currentIndex, title: currentTitle) accessibilityValue = currentTitle.lowercased() } } extension STBTableViewIndex { fileprivate func hapticFeedbackSetup() { guard #available(iOS 10.0, *) else { return } let feedbackGenerator: UISelectionFeedbackGenerator = .init() feedbackGenerator.prepare() self.feedbackGenerator = feedbackGenerator } fileprivate func hapticFeedbackSelectionChanged() { guard #available(iOS 10.0, *), let feedbackGenerator: UISelectionFeedbackGenerator = self.feedbackGenerator as? UISelectionFeedbackGenerator else { return } feedbackGenerator.selectionChanged() feedbackGenerator.prepare() } fileprivate func hapticFeedbackFinalize() { guard #available(iOS 10.0, *) else { return } self.feedbackGenerator = nil } }
3967a03741ff22ade452fc98e5e62e93
28.039604
177
0.739175
false
false
false
false
kamarshad/CMT40
refs/heads/master
VideoResume/VideoResume/External/SwiftyCamViewController.swift
mit
1
/*Copyright (c) 2016, Andrew Walz. 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. 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 import AVFoundation // MARK: View Controller Declaration /// A UIViewController Camera View Subclass open class SwiftyCamViewController: UIViewController { // MARK: Enumeration Declaration /// Enumeration for Camera Selection public enum CameraSelection { /// Camera on the back of the device case rear /// Camera on the front of the device case front } /// Enumeration for video quality of the capture session. Corresponds to a AVCaptureSessionPreset public enum VideoQuality { /// AVCaptureSessionPresetHigh case high /// AVCaptureSessionPresetMedium case medium /// AVCaptureSessionPresetLow case low /// AVCaptureSessionPreset352x288 case resolution352x288 /// AVCaptureSessionPreset640x480 case resolution640x480 /// AVCaptureSessionPreset1280x720 case resolution1280x720 /// AVCaptureSessionPreset1920x1080 case resolution1920x1080 /// AVCaptureSessionPreset3840x2160 case resolution3840x2160 /// AVCaptureSessionPresetiFrame960x540 case iframe960x540 /// AVCaptureSessionPresetiFrame1280x720 case iframe1280x720 } /** Result from the AVCaptureSession Setup - success: success - notAuthorized: User denied access to Camera of Microphone - configurationFailed: Unknown error */ fileprivate enum SessionSetupResult { case success case notAuthorized case configurationFailed } // MARK: Public Variable Declarations /// Public Camera Delegate for the Custom View Controller Subclass public weak var cameraDelegate: SwiftyCamViewControllerDelegate? /// Maxiumum video duration( In seconds) if SwiftyCamButton is used public var maximumVideoDuration : Double = 0.0 /// Video capture quality public var videoQuality : VideoQuality = .high /// Sets whether flash is enabled for photo and video capture public var flashEnabled = false /// Sets whether Pinch to Zoom is enabled for the capture session public var pinchToZoom = true /// Sets the maximum zoom scale allowed during gestures gesture public var maxZoomScale = CGFloat.greatestFiniteMagnitude /// Sets whether Tap to Focus and Tap to Adjust Exposure is enabled for the capture session public var tapToFocus = true /// Sets whether the capture session should adjust to low light conditions automatically /// /// Only supported on iPhone 5 and 5C public var lowLightBoost = true /// Set whether SwiftyCam should allow background audio from other applications public var allowBackgroundAudio = true /// Sets whether a double tap to switch cameras is supported public var doubleTapCameraSwitch = true /// Sets whether swipe vertically to zoom is supported public var swipeToZoom = true /// Sets whether swipe vertically gestures should be inverted public var swipeToZoomInverted = false /// Set default launch camera public var defaultCamera = CameraSelection.rear /// Sets wether the taken photo or video should be oriented according to the device orientation public var shouldUseDeviceOrientation = false /// Sets whether or not View Controller supports auto rotation public var allowAutoRotate = false /// Specifies the [videoGravity](https://developer.apple.com/reference/avfoundation/avcapturevideopreviewlayer/1386708-videogravity) for the preview layer. public var videoGravity : SwiftyCamVideoGravity = .resizeAspect /// Sets whether or not video recordings will record audio /// Setting to true will prompt user for access to microphone on View Controller launch. public var audioEnabled = true /// Public access to Pinch Gesture fileprivate(set) public var pinchGesture : UIPinchGestureRecognizer! /// Public access to Pan Gesture fileprivate(set) public var panGesture : UIPanGestureRecognizer! // MARK: Public Get-only Variable Declarations /// Returns true if video is currently being recorded private(set) public var isVideoRecording = false /// Returns true if the capture session is currently running private(set) public var isSessionRunning = false /// Returns the CameraSelection corresponding to the currently utilized camera private(set) public var currentCamera = CameraSelection.rear // MARK: Private Constant Declarations /// Current Capture Session public let session = AVCaptureSession() /// Serial queue used for setting up session fileprivate let sessionQueue = DispatchQueue(label: "session queue", attributes: []) // MARK: Private Variable Declarations /// Variable for storing current zoom scale fileprivate var zoomScale = CGFloat(1.0) /// Variable for storing initial zoom scale before Pinch to Zoom begins fileprivate var beginZoomScale = CGFloat(1.0) /// Returns true if the torch (flash) is currently enabled fileprivate var isCameraTorchOn = false /// Variable to store result of capture session setup fileprivate var setupResult = SessionSetupResult.success /// BackgroundID variable for video recording fileprivate var backgroundRecordingID : UIBackgroundTaskIdentifier? = nil /// Video Input variable fileprivate var videoDeviceInput : AVCaptureDeviceInput! /// Movie File Output variable fileprivate var movieFileOutput : AVCaptureMovieFileOutput? /// Photo File Output variable fileprivate var photoFileOutput : AVCaptureStillImageOutput? /// Video Device variable fileprivate var videoDevice : AVCaptureDevice? /// PreviewView for the capture session fileprivate var previewLayer : PreviewView! /// UIView for front facing flash fileprivate var flashView : UIView? /// Pan Translation fileprivate var previousPanTranslation : CGFloat = 0.0 /// Last changed orientation fileprivate var deviceOrientation : UIDeviceOrientation? /// Disable view autorotation for forced portrait recorindg var outputFileName:String! var outputFolderName:String! override open var shouldAutorotate: Bool { return allowAutoRotate } // MARK: ViewDidLoad /// ViewDidLoad Implementation override open func viewDidLoad() { super.viewDidLoad() view = PreviewView(frame: view.frame, videoGravity: videoGravity) previewLayer = view as! PreviewView! // Add Gesture Recognizers addGestureRecognizers() previewLayer.session = session // Test authorization status for Camera and Micophone switch AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo){ case .authorized: // already authorized break case .notDetermined: // not yet determined sessionQueue.suspend() AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { [unowned self] granted in if !granted { self.setupResult = .notAuthorized } self.sessionQueue.resume() }) default: // already been asked. Denied access setupResult = .notAuthorized } sessionQueue.async { [unowned self] in self.configureSession() } } // MARK: ViewDidLayoutSubviews /// ViewDidLayoutSubviews() Implementation /// ViewDidLayoutSubviews() Implementation private func updatePreviewLayer(layer: AVCaptureConnection, orientation: AVCaptureVideoOrientation) { layer.videoOrientation = orientation previewLayer.frame = self.view.bounds } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let connection = self.previewLayer?.videoPreviewLayer.connection { let currentDevice: UIDevice = UIDevice.current let orientation: UIDeviceOrientation = currentDevice.orientation let previewLayerConnection : AVCaptureConnection = connection if previewLayerConnection.isVideoOrientationSupported { switch (orientation) { case .portrait: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait) break case .landscapeRight: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeLeft) break case .landscapeLeft: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeRight) break case .portraitUpsideDown: updatePreviewLayer(layer: previewLayerConnection, orientation: .portraitUpsideDown) break default: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait) break } } } } // MARK: ViewDidAppear /// ViewDidAppear(_ animated:) Implementation override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Subscribe to device rotation notifications if shouldUseDeviceOrientation { subscribeToDeviceOrientationChangeNotifications() } // Set background audio preference setBackgroundAudioPreference() sessionQueue.async { switch self.setupResult { case .success: // Begin Session self.session.startRunning() self.isSessionRunning = self.session.isRunning // Preview layer video orientation can be set only after the connection is created DispatchQueue.main.async { self.previewLayer.videoPreviewLayer.connection?.videoOrientation = self.getPreviewLayerOrientation() } case .notAuthorized: // Prompt to App Settings self.promptToAppSettings() case .configurationFailed: // Unknown Error DispatchQueue.main.async(execute: { [unowned self] in let message = NSLocalizedString("Unable to recored video", comment: "Alert message when something goes wrong during capture session configuration") let alertController = UIAlertController(title: "VideoResume", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) }) } } } // MARK: ViewDidDisappear /// ViewDidDisappear(_ animated:) Implementation override open func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // If session is running, stop the session if self.isSessionRunning == true { self.session.stopRunning() self.isSessionRunning = false } //Disble flash if it is currently enabled disableFlash() // Unsubscribe from device rotation notifications if shouldUseDeviceOrientation { unsubscribeFromDeviceOrientationChangeNotifications() } } // MARK: Public Functions /** Capture photo from current session UIImage will be returned with the SwiftyCamViewControllerDelegate function SwiftyCamDidTakePhoto(photo:) */ public func takePhoto() { guard let device = videoDevice else { return } if device.hasFlash == true && flashEnabled == true /* TODO: Add Support for Retina Flash and add front flash */ { changeFlashSettings(device: device, mode: .on) capturePhotoAsyncronously(completionHandler: { (_) in }) } else if device.hasFlash == false && flashEnabled == true && currentCamera == .front { flashView = UIView(frame: view.frame) flashView?.alpha = 0.0 flashView?.backgroundColor = UIColor.white previewLayer.addSubview(flashView!) UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: { self.flashView?.alpha = 1.0 }, completion: { (_) in self.capturePhotoAsyncronously(completionHandler: { (success) in UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: { self.flashView?.alpha = 0.0 }, completion: { (_) in self.flashView?.removeFromSuperview() }) }) }) } else { if device.isFlashActive == true { changeFlashSettings(device: device, mode: .off) } capturePhotoAsyncronously(completionHandler: { (_) in }) } } /** Begin recording video of current session SwiftyCamViewControllerDelegate function SwiftyCamDidBeginRecordingVideo() will be called */ public func startVideoRecording() { guard let movieFileOutput = self.movieFileOutput else { return } if currentCamera == .rear && flashEnabled == true { enableFlash() } if currentCamera == .front && flashEnabled == true { flashView = UIView(frame: view.frame) flashView?.backgroundColor = UIColor.white flashView?.alpha = 0.85 previewLayer.addSubview(flashView!) } sessionQueue.async { [unowned self] in if !movieFileOutput.isRecording { if UIDevice.current.isMultitaskingSupported { self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil) } // Update the orientation on the movie file output video connection before starting recording. let movieFileOutputConnection = self.movieFileOutput?.connection(withMediaType: AVMediaTypeVideo) //flip video output if front facing camera is selected if self.currentCamera == .front { movieFileOutputConnection?.isVideoMirrored = true } movieFileOutputConnection?.videoOrientation = self.getVideoOrientation() // Start recording to a temporary file. var outputFileName = UUID().uuidString if let notNilFileName = self.outputFileName { outputFileName = notNilFileName } var outputFolderName = UserDefaultConstants.videoFolderName.string() if let notNillFolderName = self.outputFolderName { outputFolderName = notNillFolderName } /* let documentDirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] var fileURL = URL(fileURLWithPath: documentDirPath) fileURL = fileURL.appendingPathComponent(outputFolderName) let outputFilePath = fileURL.appendingPathComponent(outputFileName+".mov").absoluteString */ let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!) movieFileOutput.startRecording(toOutputFileURL: URL(fileURLWithPath: outputFilePath), recordingDelegate: self) print("outputFilePath: \(outputFilePath)") movieFileOutput.startRecording(toOutputFileURL: URL(fileURLWithPath: outputFilePath), recordingDelegate: self) self.isVideoRecording = true DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didBeginRecordingVideo: self.currentCamera) } } else { movieFileOutput.stopRecording() } } } fileprivate func videoSaveDirectoryURL(fileName: String) -> String { let documentDirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let fileURL = URL(fileURLWithPath: documentDirPath) return fileURL.appendingPathComponent(fileName).absoluteString } /** Stop video recording video of current session SwiftyCamViewControllerDelegate function SwiftyCamDidFinishRecordingVideo() will be called When video has finished processing, the URL to the video location will be returned by SwiftyCamDidFinishProcessingVideoAt(url:) */ public func stopVideoRecording() { if self.movieFileOutput?.isRecording == true { self.isVideoRecording = false movieFileOutput!.stopRecording() disableFlash() if currentCamera == .front && flashEnabled == true && flashView != nil { UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: { self.flashView?.alpha = 0.0 }, completion: { (_) in self.flashView?.removeFromSuperview() }) } DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didFinishRecordingVideo: self.currentCamera) } } } /** Switch between front and rear camera SwiftyCamViewControllerDelegate function SwiftyCamDidSwitchCameras(camera: will be return the current camera selection */ public func switchCamera() { guard isVideoRecording != true else { //TODO: Look into switching camera during video recording print("[SwiftyCam]: Switching between cameras while recording video is not supported") return } guard session.isRunning == true else { return } switch currentCamera { case .front: currentCamera = .rear case .rear: currentCamera = .front } session.stopRunning() sessionQueue.async { [unowned self] in // remove and re-add inputs and outputs for input in self.session.inputs { self.session.removeInput(input as! AVCaptureInput) } self.addInputs() DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didSwitchCameras: self.currentCamera) } self.session.startRunning() } // If flash is enabled, disable it as the torch is needed for front facing camera disableFlash() } // MARK: Private Functions /// Configure session, add inputs and outputs fileprivate func configureSession() { guard setupResult == .success else { return } // Set default camera currentCamera = defaultCamera // begin configuring session session.beginConfiguration() configureVideoPreset() addVideoInput() addAudioInput() configureVideoOutput() configurePhotoOutput() session.commitConfiguration() } /// Add inputs after changing camera() fileprivate func addInputs() { session.beginConfiguration() configureVideoPreset() addVideoInput() addAudioInput() session.commitConfiguration() } // Front facing camera will always be set to VideoQuality.high // If set video quality is not supported, videoQuality variable will be set to VideoQuality.high /// Configure image quality preset fileprivate func configureVideoPreset() { if currentCamera == .front { session.sessionPreset = videoInputPresetFromVideoQuality(quality: .high) } else { if session.canSetSessionPreset(videoInputPresetFromVideoQuality(quality: videoQuality)) { session.sessionPreset = videoInputPresetFromVideoQuality(quality: videoQuality) } else { session.sessionPreset = videoInputPresetFromVideoQuality(quality: .high) } } } /// Add Video Inputs fileprivate func addVideoInput() { switch currentCamera { case .front: videoDevice = SwiftyCamViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: .front) case .rear: videoDevice = SwiftyCamViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: .back) } if let device = videoDevice { do { try device.lockForConfiguration() if device.isFocusModeSupported(.continuousAutoFocus) { device.focusMode = .continuousAutoFocus if device.isSmoothAutoFocusSupported { device.isSmoothAutoFocusEnabled = true } } if device.isExposureModeSupported(.continuousAutoExposure) { device.exposureMode = .continuousAutoExposure } if device.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance) { device.whiteBalanceMode = .continuousAutoWhiteBalance } if device.isLowLightBoostSupported && lowLightBoost == true { device.automaticallyEnablesLowLightBoostWhenAvailable = true } device.unlockForConfiguration() } catch { print("[SwiftyCam]: Error locking configuration") } } do { let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice) if session.canAddInput(videoDeviceInput) { session.addInput(videoDeviceInput) self.videoDeviceInput = videoDeviceInput } else { print("[SwiftyCam]: Could not add video device input to the session") print(session.canSetSessionPreset(videoInputPresetFromVideoQuality(quality: videoQuality))) setupResult = .configurationFailed session.commitConfiguration() return } } catch { print("[SwiftyCam]: Could not create video device input: \(error)") setupResult = .configurationFailed return } } /// Add Audio Inputs fileprivate func addAudioInput() { guard audioEnabled == true else { return } do { let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio) let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice) if session.canAddInput(audioDeviceInput) { session.addInput(audioDeviceInput) } else { print("[SwiftyCam]: Could not add audio device input to the session") } } catch { print("[SwiftyCam]: Could not create audio device input: \(error)") } } /// Configure Movie Output fileprivate func configureVideoOutput() { let movieFileOutput = AVCaptureMovieFileOutput() if self.session.canAddOutput(movieFileOutput) { self.session.addOutput(movieFileOutput) if let connection = movieFileOutput.connection(withMediaType: AVMediaTypeVideo) { if connection.isVideoStabilizationSupported { connection.preferredVideoStabilizationMode = .auto } } self.movieFileOutput = movieFileOutput } } /// Configure Photo Output fileprivate func configurePhotoOutput() { let photoFileOutput = AVCaptureStillImageOutput() if self.session.canAddOutput(photoFileOutput) { photoFileOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] self.session.addOutput(photoFileOutput) self.photoFileOutput = photoFileOutput } } /// Orientation management fileprivate func subscribeToDeviceOrientationChangeNotifications() { self.deviceOrientation = UIDevice.current.orientation NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } fileprivate func unsubscribeFromDeviceOrientationChangeNotifications() { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) self.deviceOrientation = nil } @objc fileprivate func deviceDidRotate() { if !UIDevice.current.orientation.isFlat { self.deviceOrientation = UIDevice.current.orientation } } fileprivate func getPreviewLayerOrientation() -> AVCaptureVideoOrientation { // Depends on layout orientation, not device orientation switch UIApplication.shared.statusBarOrientation { case .portrait, .unknown: return AVCaptureVideoOrientation.portrait case .landscapeLeft: return AVCaptureVideoOrientation.landscapeLeft case .landscapeRight: return AVCaptureVideoOrientation.landscapeRight case .portraitUpsideDown: return AVCaptureVideoOrientation.portraitUpsideDown } } fileprivate func getVideoOrientation() -> AVCaptureVideoOrientation { guard shouldUseDeviceOrientation, let deviceOrientation = self.deviceOrientation else { return previewLayer!.videoPreviewLayer.connection.videoOrientation } switch deviceOrientation { case .landscapeLeft: return .landscapeRight case .landscapeRight: return .landscapeLeft case .portraitUpsideDown: return .portraitUpsideDown default: return .portrait } } fileprivate func getImageOrientation(forCamera: CameraSelection) -> UIImageOrientation { guard shouldUseDeviceOrientation, let deviceOrientation = self.deviceOrientation else { return forCamera == .rear ? .right : .leftMirrored } switch deviceOrientation { case .landscapeLeft: return forCamera == .rear ? .up : .downMirrored case .landscapeRight: return forCamera == .rear ? .down : .upMirrored case .portraitUpsideDown: return forCamera == .rear ? .left : .rightMirrored default: return forCamera == .rear ? .right : .leftMirrored } } /** Returns a UIImage from Image Data. - Parameter imageData: Image Data returned from capturing photo from the capture session. - Returns: UIImage from the image data, adjusted for proper orientation. */ fileprivate func processPhoto(_ imageData: Data) -> UIImage { let dataProvider = CGDataProvider(data: imageData as CFData) let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) // Set proper orientation for photo // If camera is currently set to front camera, flip image let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: self.getImageOrientation(forCamera: self.currentCamera)) return image } fileprivate func capturePhotoAsyncronously(completionHandler: @escaping(Bool) -> ()) { if let videoConnection = photoFileOutput?.connection(withMediaType: AVMediaTypeVideo) { photoFileOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(sampleBuffer, error) in if (sampleBuffer != nil) { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) let image = self.processPhoto(imageData!) // Call delegate and return new image DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didTake: image) } completionHandler(true) } else { completionHandler(false) } }) } else { completionHandler(false) } } /// Handle Denied App Privacy Settings fileprivate func promptToAppSettings() { // prompt User with UIAlertView DispatchQueue.main.async(execute: { [unowned self] in let message = NSLocalizedString("AVCam doesn't have permission to use the camera, please change privacy settings", comment: "Alert message when the user has denied access to the camera") let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil)) alertController.addAction(UIAlertAction(title: NSLocalizedString("Settings", comment: "Alert button to open Settings"), style: .default, handler: { action in if #available(iOS 10.0, *) { UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) } else { if let appSettings = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.openURL(appSettings) } } })) self.present(alertController, animated: true, completion: nil) }) } /** Returns an AVCapturePreset from VideoQuality Enumeration - Parameter quality: ViewQuality enum - Returns: String representing a AVCapturePreset */ fileprivate func videoInputPresetFromVideoQuality(quality: VideoQuality) -> String { switch quality { case .high: return AVCaptureSessionPresetHigh case .medium: return AVCaptureSessionPresetMedium case .low: return AVCaptureSessionPresetLow case .resolution352x288: return AVCaptureSessionPreset352x288 case .resolution640x480: return AVCaptureSessionPreset640x480 case .resolution1280x720: return AVCaptureSessionPreset1280x720 case .resolution1920x1080: return AVCaptureSessionPreset1920x1080 case .iframe960x540: return AVCaptureSessionPresetiFrame960x540 case .iframe1280x720: return AVCaptureSessionPresetiFrame1280x720 case .resolution3840x2160: if #available(iOS 9.0, *) { return AVCaptureSessionPreset3840x2160 } else { print("[SwiftyCam]: Resolution 3840x2160 not supported") return AVCaptureSessionPresetHigh } } } /// Get Devices fileprivate class func deviceWithMediaType(_ mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice? { if let devices = AVCaptureDevice.devices(withMediaType: mediaType) as? [AVCaptureDevice] { return devices.filter({ $0.position == position }).first } return nil } /// Enable or disable flash for photo fileprivate func changeFlashSettings(device: AVCaptureDevice, mode: AVCaptureFlashMode) { do { try device.lockForConfiguration() device.flashMode = mode device.unlockForConfiguration() } catch { print("[SwiftyCam]: \(error)") } } /// Enable flash fileprivate func enableFlash() { if self.isCameraTorchOn == false { toggleFlash() } } /// Disable flash fileprivate func disableFlash() { if self.isCameraTorchOn == true { toggleFlash() } } /// Toggles between enabling and disabling flash fileprivate func toggleFlash() { guard self.currentCamera == .rear else { // Flash is not supported for front facing camera return } let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) // Check if device has a flash if (device?.hasTorch)! { do { try device?.lockForConfiguration() if (device?.torchMode == AVCaptureTorchMode.on) { device?.torchMode = AVCaptureTorchMode.off self.isCameraTorchOn = false } else { do { try device?.setTorchModeOnWithLevel(1.0) self.isCameraTorchOn = true } catch { print("[SwiftyCam]: \(error)") } } device?.unlockForConfiguration() } catch { print("[SwiftyCam]: \(error)") } } } /// Sets whether SwiftyCam should enable background audio from other applications or sources fileprivate func setBackgroundAudioPreference() { guard allowBackgroundAudio == true else { return } guard audioEnabled == true else { return } do{ try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.duckOthers, .defaultToSpeaker]) session.automaticallyConfiguresApplicationAudioSession = false } catch { print("[SwiftyCam]: Failed to set background audio preference") } } } extension SwiftyCamViewController : SwiftyCamButtonDelegate { /// Sets the maximum duration of the SwiftyCamButton public func setMaxiumVideoDuration() -> Double { return maximumVideoDuration } /// Set UILongPressGesture start to begin video public func buttonDidBeginVideoRecording() { startVideoRecording() } /// Set UILongPressGesture begin to begin end video public func buttonDidEndVideoRecording() { stopVideoRecording() } /// Called if maximum duration is reached public func videoRecordingDidReachMaximumDuration() { stopVideoRecording() } } // MARK: AVCaptureFileOutputRecordingDelegate extension SwiftyCamViewController : AVCaptureFileOutputRecordingDelegate { /// Process newly captured video and write it to temporary directory public func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) { if let currentBackgroundRecordingID = backgroundRecordingID { backgroundRecordingID = UIBackgroundTaskInvalid if currentBackgroundRecordingID != UIBackgroundTaskInvalid { UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID) } } if error != nil { print("[SwiftyCam]: Movie file finishing error: \(error)") } else { //Call delegate function with the URL of the outputfile DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didFinishProcessVideoAt: outputFileURL) } } } } // Mark: UIGestureRecognizer Declarations extension SwiftyCamViewController { /// Handle pinch gesture @objc fileprivate func zoomGesture(pinch: UIPinchGestureRecognizer) { guard pinchToZoom == true && self.currentCamera == .rear else { //ignore pinch return } do { let captureDevice = AVCaptureDevice.devices().first as? AVCaptureDevice try captureDevice?.lockForConfiguration() zoomScale = min(maxZoomScale, max(1.0, min(beginZoomScale * pinch.scale, captureDevice!.activeFormat.videoMaxZoomFactor))) captureDevice?.videoZoomFactor = zoomScale // Call Delegate function with current zoom scale DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didChangeZoomLevel: self.zoomScale) } captureDevice?.unlockForConfiguration() } catch { print("[SwiftyCam]: Error locking configuration") } } /// Handle single tap gesture @objc fileprivate func singleTapGesture(tap: UITapGestureRecognizer) { guard tapToFocus == true else { // Ignore taps return } let screenSize = previewLayer!.bounds.size let tapPoint = tap.location(in: previewLayer!) let x = tapPoint.y / screenSize.height let y = 1.0 - tapPoint.x / screenSize.width let focusPoint = CGPoint(x: x, y: y) if let device = videoDevice { do { try device.lockForConfiguration() if device.isFocusPointOfInterestSupported == true { device.focusPointOfInterest = focusPoint device.focusMode = .autoFocus } device.exposurePointOfInterest = focusPoint device.exposureMode = AVCaptureExposureMode.continuousAutoExposure device.unlockForConfiguration() //Call delegate function and pass in the location of the touch DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didFocusAtPoint: tapPoint) } } catch { // just ignore } } } /// Handle double tap gesture @objc fileprivate func doubleTapGesture(tap: UITapGestureRecognizer) { guard doubleTapCameraSwitch == true else { return } switchCamera() } @objc private func panGesture(pan: UIPanGestureRecognizer) { guard swipeToZoom == true && self.currentCamera == .rear else { //ignore pan return } let currentTranslation = pan.translation(in: view).y let translationDifference = currentTranslation - previousPanTranslation do { let captureDevice = AVCaptureDevice.devices().first as? AVCaptureDevice try captureDevice?.lockForConfiguration() let currentZoom = captureDevice?.videoZoomFactor ?? 0.0 if swipeToZoomInverted == true { zoomScale = min(maxZoomScale, max(1.0, min(currentZoom - (translationDifference / 75), captureDevice!.activeFormat.videoMaxZoomFactor))) } else { zoomScale = min(maxZoomScale, max(1.0, min(currentZoom + (translationDifference / 75), captureDevice!.activeFormat.videoMaxZoomFactor))) } captureDevice?.videoZoomFactor = zoomScale // Call Delegate function with current zoom scale DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didChangeZoomLevel: self.zoomScale) } captureDevice?.unlockForConfiguration() } catch { print("[SwiftyCam]: Error locking configuration") } if pan.state == .ended || pan.state == .failed || pan.state == .cancelled { previousPanTranslation = 0.0 } else { previousPanTranslation = currentTranslation } } /** Add pinch gesture recognizer and double tap gesture recognizer to currentView - Parameter view: View to add gesture recognzier */ fileprivate func addGestureRecognizers() { pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(zoomGesture(pinch:))) pinchGesture.delegate = self previewLayer.addGestureRecognizer(pinchGesture) let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(singleTapGesture(tap:))) singleTapGesture.numberOfTapsRequired = 1 singleTapGesture.delegate = self previewLayer.addGestureRecognizer(singleTapGesture) let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(doubleTapGesture(tap:))) doubleTapGesture.numberOfTapsRequired = 2 doubleTapGesture.delegate = self previewLayer.addGestureRecognizer(doubleTapGesture) panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGesture(pan:))) panGesture.delegate = self previewLayer.addGestureRecognizer(panGesture) } } // MARK: UIGestureRecognizerDelegate extension SwiftyCamViewController : UIGestureRecognizerDelegate { /// Set beginZoomScale when pinch begins public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer.isKind(of: UIPinchGestureRecognizer.self) { beginZoomScale = zoomScale; } return true } }
35392e5805d77e24fa19c221994edf8f
29.894907
189
0.714525
false
false
false
false
jdjack/Swift-Perlin-Noise
refs/heads/master
PerlinNoise.playground/Sources/Perlin3D.swift
mit
1
import Foundation import UIKit public class Perlin3D: NSObject { var permutation:[Int] = [] public init(seed: String) { let hash = seed.hash srand48(hash) for _ in 0..<512 { //Create the permutations to pick from using a seed so you can recreate the map permutation.append(Int(drand48() * 255)) } } func lerp(a:CGFloat, b:CGFloat, x:CGFloat) -> CGFloat { return a + x * (b - a) //This interpolates between two points with a weight x } func fade(t:CGFloat) -> CGFloat { return t * t * t * (t * (t * 6 - 15) + 10) //This is the smoothing function for Perlin noise } func grad(hash:Int, x:CGFloat, y:CGFloat, z:CGFloat) -> CGFloat { //This takes a hash (a number from 0 - 11) generated from the random permutations and returns a random //operation for the node to offset switch hash & 11 { case 0: return x + y case 1: return -x + y case 2: return x - y case 3: return -x - y case 4: return x + z case 5: return -x + z case 6: return x - z case 7: return -x - z case 8: return y + z case 9: return -y + z case 10: return y - z case 11: return -y - z default: print("ERROR") return 0 } } func fastfloor(x:CGFloat) -> Int { return x > 0 ? Int(x) : Int(x-1) } public func noise(x:CGFloat, y:CGFloat, z:CGFloat) -> CGFloat { //Find the unit grid cell containing the point var xi = fastfloor(x: x) var yi = fastfloor(x: y) var zi = fastfloor(x: z) //This is the other bound of the unit square let xf:CGFloat = x - CGFloat(xi) let yf:CGFloat = y - CGFloat(yi) let zf:CGFloat = z - CGFloat(zi) //Wrap the ints around 255 xi = xi & 255 yi = yi & 255 zi = zi & 255 //These are offset values for interpolation let u = fade(t: xf) let v = fade(t: yf) let w = fade(t: zf) //These are the 8 possible permutations so we get the perm value for each let aaa = permutation[permutation[permutation[xi] + yi] + zi] let aab = permutation[permutation[permutation[xi] + yi] + zi + 1] let aba = permutation[permutation[permutation[xi] + yi + 1] + zi] let abb = permutation[permutation[permutation[xi] + yi + 1] + zi + 1] let baa = permutation[permutation[permutation[xi + 1] + yi] + zi] let bab = permutation[permutation[permutation[xi + 1] + yi] + zi] let bba = permutation[permutation[permutation[xi + 1] + yi + 1] + zi] let bbb = permutation[permutation[permutation[xi + 1] + yi + 1] + zi + 1] //We pair up the permutations, and then interpolate the noise contributions let naa = lerp(a: grad(hash: aaa, x: xf, y: yf, z: zf), b: grad(hash: baa, x: xf, y: yf, z: zf), x: u) let nab = lerp(a: grad(hash: aab, x: xf, y: yf, z: zf), b: grad(hash: bab, x: xf, y: yf, z: zf), x: u) let nba = lerp(a: grad(hash: aba, x: xf, y: yf, z: zf), b: grad(hash: bba, x: xf, y: yf, z: zf), x: u) let nbb = lerp(a: grad(hash: abb, x: xf, y: yf, z: zf), b: grad(hash: bbb, x: xf, y: yf, z: zf), x: u) let na = lerp(a: naa, b: nba, x: v) let nb = lerp(a: nab, b: nbb, x: v) let nxyz = lerp(a: na, b: nb, x: w) //We return the value + 1 / 2 to remove any negatives. return (nxyz + 1) / 2 } public func octaveNoise(x:CGFloat, y:CGFloat, z:CGFloat, octaves:Int, persistence:CGFloat) -> CGFloat { //This takes several perlin readings (n octaves) and merges them into one map var total:CGFloat = 0 var frequency: CGFloat = 1 var amplitude: CGFloat = 1 var maxValue: CGFloat = 0 //We sum the total and divide by the max at the end to normalise for _ in 0..<octaves { total += noise(x: x * frequency, y: y * frequency, z: z * frequency) * amplitude maxValue += amplitude //This is taken from recomendations on values amplitude *= persistence frequency *= 2 } //print(max) return total/maxValue } public func perlinMatrix(width:Int, height: Int, length: Int) -> [[[CGFloat]]] { var map:[[[CGFloat]]] = [] //We loop through the x and y values and scale by 50. This is an arbritatry value to scale the map //You can play with this for x in (0...width) { var row1:[[CGFloat]] = [] for y in (0...height) { var row2:[CGFloat] = [] for z in (0...length) { let cx:CGFloat = CGFloat(x)/50 let cy:CGFloat = CGFloat(y)/50 let cz:CGFloat = CGFloat(z)/50 let p = noise(x: cx, y: cy, z: cz) row2.append(p) } row1.append(row2) } //We store the map in a matrix for fast access map.append(row1) } return map } public func octaveMatrix(width:Int, height: Int, length: Int, octaves:Int, persistance:CGFloat) -> [[[CGFloat]]] { var map:[[[CGFloat]]] = [] //We loop through the x and y values and scale by 50. This is an arbritatry value to scale the map //You can play with this for x in (0...width) { var row1:[[CGFloat]] = [] for y in (0...height) { var row2:[CGFloat] = [] for z in (0...length) { let cx:CGFloat = CGFloat(x)/50 let cy:CGFloat = CGFloat(y)/50 let cz:CGFloat = CGFloat(z)/50 //We decide to use 8 octaves and 0.25 to generate our map. You can change these too let p = octaveNoise(x: cx, y: cy, z: cz, octaves: octaves, persistence: persistance) row2.append(p) } row1.append(row2) } map.append(row1) } return map } }
aedf93e767ee7d5003b200a42b50e72a
30.7
118
0.467164
false
false
false
false
sketchytech/Aldwych_JSON_Swift
refs/heads/master
Sources/StringExtensions.swift
mit
2
// // StringExtensions.swift // SaveFile // // Created by Anthony Levings on 06/04/2015. // import Foundation extension String { func nsRangeToRange(range:NSRange) -> Range<String.Index> { return Range(start: advance(self.startIndex, range.location), end: advance(self.startIndex, range.location+range.length)) } public mutating func replaceStringsUsingRegularExpression(expression exp:String, withString:String, options opt:NSMatchingOptions = nil, error err:NSErrorPointer) { let strLength = count(self) if let regexString = NSRegularExpression(pattern: exp, options: nil, error: err) { let st = regexString.stringByReplacingMatchesInString(self, options: opt, range: NSMakeRange(0, strLength), withTemplate: withString) self = st } } public func getMatches(regex: String, options: NSStringCompareOptions?) -> [Range<String.Index>] { var arr = [Range<String.Index>]() var rang = Range(start: self.startIndex, end: self.endIndex) var foundRange:Range<String.Index>? do { foundRange = self.rangeOfString(regex, options: options ?? nil, range: rang, locale: nil) if let a = foundRange { arr.append(a) rang.startIndex = foundRange!.endIndex } } while foundRange != nil return arr } }
253e85577e81213bfafed594070dce66
33.659091
168
0.593443
false
false
false
false
githubxiangdong/DouYuZB
refs/heads/master
DouYuZB/DouYuZB/Classes/Tools/Extension/AnchorModel.swift
mit
1
// // AnchorModel.swift // DouYuZB // // Created by new on 2017/4/27. // Copyright © 2017年 9-kylins. All rights reserved. // import UIKit class AnchorModel: NSObject { /// 房间ID var room_id : Int = 0 /// 房间对应的url var vertical_src : String = "" /// 判断是手机直播还是电脑直播 // 0 : 电脑直播(普通房间), 1 : 手机直播(秀场直播) var isVertical : Int = 0 /// 房间名 var room_name : String = "" /// 主播名称 var nickname : String = "" /// 观看人数 var online : Int = 0 /// 所在城市 var anchor_city : String = "" //MARK:- kvc 重写init方法 init(dic : [String : Any]) { super.init() setValuesForKeys(dic) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
ce56a57f5c39890ee951314d120e7825
20
73
0.546939
false
false
false
false
CodaFi/swift
refs/heads/main
benchmark/single-source/ProtocolDispatch.swift
apache-2.0
22
//===--- ProtocolDispatch.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 // //===----------------------------------------------------------------------===// import TestsUtils public let ProtocolDispatch = BenchmarkInfo( name: "ProtocolDispatch", runFunction: run_ProtocolDispatch, tags: [.validation, .abstraction]) @inline(never) public func run_ProtocolDispatch(_ N: Int) { let x = someProtocolFactory() for _ in 0...100_000 * N { _ = x.getValue() } }
e1481d27e390fa1d5efd7b33d6d04602
28.892857
80
0.603345
false
false
false
false
AdySan/HomeKit-Demo
refs/heads/master
BetterHomeKit/ZonesViewController.swift
mit
4
// // ZonesViewController.swift // BetterHomeKit // // Created by Roy Arents on 01-11-14. // Copyright (c) 2014 Nlr. All rights reserved. // // Heavily inspired by KhaosT's RoomsViewController.swift import UIKit import HomeKit let assignRoomNotificationString = "DidAssignRoomToZone" class ZonesViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var pendingRoom:Room? @IBOutlet var zoneTableView: UITableView! override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) self.zoneTableView.setEditing(false, animated: false) } @IBAction func dismissZoneController(sender: AnyObject) { if let _ = pendingRoom { self.navigationController?.popViewControllerAnimated(true) } else { self.dismissViewControllerAnimated(true, completion: nil) } } @IBAction func addZone(sender: AnyObject) { let alert:UIAlertController = UIAlertController(title: "Add Zone", message: "Add zone to current Home", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Add", style: UIAlertActionStyle.Default, handler: { [weak self] (action:UIAlertAction!) in let textField = alert.textFields?[0] as! UITextField if let strongSelf = self { Core.sharedInstance.currentHome?.addZoneWithName(textField.text, completionHandler: { room,error in if let error = error { NSLog("Add zone error:\(error)") }else{ strongSelf.zoneTableView.reloadData() } } ) } })) self.presentViewController(alert, animated: true, completion: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Core.sharedInstance.currentHome?.zones.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("zoneCell", forIndexPath: indexPath) as! UITableViewCell let zone = Core.sharedInstance.currentHome?.zones?[indexPath.row] as! HMZone var detailText = "" if zone.rooms.count > 0 { detailText += "|" let roomNames = zone.rooms.map { $0.name } for name in roomNames { detailText += "\(name)|" } } cell.textLabel?.text = zone.name cell.detailTextLabel?.text = detailText return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { NSLog("pendingRoom \(pendingRoom) name= \(pendingRoom)") if let room = pendingRoom { let zone = Core.sharedInstance.currentHome?.zones[indexPath.row] as! HMZone NSLog("zone \(zone)") zone.addRoom(room.toHMRoom(), completionHandler: { [weak self] error in if let error = error { NSLog("Assign Room \(room) to zone \(zone) error:\(error)") // Try to remove it? zone.removeRoom(room.toHMRoom(), completionHandler: { [weak self] error in if let error = error { NSLog("Removing Room \(room) to zone \(zone) error:\(error)") }else{ NSLog("Successfully removed the room") NSNotificationCenter.defaultCenter().postNotificationName(assignRoomNotificationString, object: nil) self?.dismissZoneController(zone) } } ) }else{ NSLog("Successfully assigned the room") NSNotificationCenter.defaultCenter().postNotificationName(assignRoomNotificationString, object: nil) self?.dismissZoneController(zone) } } ) }else{ let alert:UIAlertController = UIAlertController(title: "Rename Zone", message: "Update the name of the zone", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Rename", style: UIAlertActionStyle.Default, handler: { [weak self] (action:UIAlertAction!) in let textField = alert.textFields?[0] as! UITextField let zone = Core.sharedInstance.currentHome?.zones?[indexPath.row] as! HMZone zone.updateName(textField.text, completionHandler: { error in if let error = error { println("Error:\(error)") }else{ let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.textLabel?.text = Core.sharedInstance.currentHome?.zones?[indexPath.row].name } } ) })) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(alert, animated: true, completion: nil) }) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { if let zone = Core.sharedInstance.currentHome?.zones[indexPath.row] as? HMZone { Core.sharedInstance.currentHome?.removeZone(zone) { [weak self] error in if error != nil { NSLog("Failed removing zone, error:\(error)") } else { self?.zoneTableView.reloadData() } } } } } }
ff1dba230bbe64aa43d31f2686b9f20a
41.464706
148
0.533176
false
false
false
false
Authman2/Pix
refs/heads/master
Eureka-master/Source/Core/HeaderFooterView.swift
apache-2.0
7
// HeaderFooterView.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** Enumeration used to generate views for the header and footer of a section. - Class: Will generate a view of the specified class. - Callback->ViewType: Will generate the view as a result of the given closure. - NibFile: Will load the view from a nib file. */ public enum HeaderFooterProvider<ViewType: UIView> { /** * Will generate a view of the specified class. */ case `class` /** * Will generate the view as a result of the given closure. */ case callback(()->ViewType) /** * Will load the view from a nib file. */ case nibFile(name: String, bundle: Bundle?) internal func createView() -> ViewType { switch self { case .class: return ViewType() case .callback(let builder): return builder() case .nibFile(let nibName, let bundle): return (bundle ?? Bundle(for: ViewType.self)).loadNibNamed(nibName, owner: nil, options: nil)![0] as! ViewType } } } /** * Represents headers and footers of sections */ public enum HeaderFooterType { case header, footer } /** * Struct used to generate headers and footers either from a view or a String. */ public struct HeaderFooterView<ViewType: UIView> : ExpressibleByStringLiteral, HeaderFooterViewRepresentable { /// Holds the title of the view if it was set up with a String. public var title: String? /// Generates the view. public var viewProvider: HeaderFooterProvider<ViewType>? /// Closure called when the view is created. Useful to customize its appearance. public var onSetupView: ((_ view: ViewType, _ section: Section) -> ())? /// A closure that returns the height for the header or footer view. public var height: (()->CGFloat)? /** This method can be called to get the view corresponding to the header or footer of a section in a specific controller. - parameter section: The section from which to get the view. - parameter type: Either header or footer. - parameter controller: The controller from which to get that view. - returns: The header or footer of the specified section. */ public func viewForSection(_ section: Section, type: HeaderFooterType) -> UIView? { var view: ViewType? if type == .header { view = section.headerView as? ViewType ?? { let result = viewProvider?.createView() section.headerView = result return result }() } else { view = section.footerView as? ViewType ?? { let result = viewProvider?.createView() section.footerView = result return result }() } guard let v = view else { return nil } onSetupView?(v, section) return v } /** Initiates the view with a String as title */ public init?(title: String?){ guard let t = title else { return nil } self.init(stringLiteral: t) } /** Initiates the view with a view provider, ideal for customized headers or footers */ public init(_ provider: HeaderFooterProvider<ViewType>){ viewProvider = provider } /** Initiates the view with a String as title */ public init(unicodeScalarLiteral value: String) { self.title = value } /** Initiates the view with a String as title */ public init(extendedGraphemeClusterLiteral value: String) { self.title = value } /** Initiates the view with a String as title */ public init(stringLiteral value: String) { self.title = value } } extension UIView { func eurekaInvalidate() { setNeedsUpdateConstraints() updateConstraintsIfNeeded() setNeedsLayout() } }
42246b5621c02417594baa0980a54df5
31.378049
123
0.62693
false
false
false
false
rusty1s/RSRoundBorderedButton
refs/heads/master
RSRoundBorderedButton/RSRoundBorderedButton/RSRoundBorderedButton.swift
mit
1
// // RSRoundBorderedButton.swift // RSRoundBorderedButton // // Created by Matthias Fey on 20.05.15. // Copyright (c) 2015 Matthias Fey. All rights reserved. // import UIKit public class RSRoundBorderedButton : UIButton { // MARK: Initializers public convenience init() { self.init(frame: CGRectZero) } public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: Setup private func setup() { setTitleColor(tintColor, forState: .Normal) setTitleColor(UIColor.whiteColor(), forState: .Highlighted) setTitleColor(UIColor.lightGrayColor(), forState: .Disabled) layer.cornerRadius = 3.5 layer.borderWidth = 1 contentEdgeInsets = UIEdgeInsetsMake(5, 10, 5, 10) refreshBorderColor() } private func refreshBorderColor() { layer.borderColor = enabled ? tintColor?.CGColor : UIColor.lightGrayColor().CGColor } // MARK: Override public override var tintColor: UIColor? { set(newTintColor) { super.tintColor = newTintColor setTitleColor(newTintColor, forState: .Normal) refreshBorderColor() } get { return super.tintColor } } public override var enabled: Bool { set(newEnabled) { super.enabled = newEnabled refreshBorderColor() } get { return super.enabled } } public override var highlighted: Bool { set(newHighlighted) { if highlighted != newHighlighted { super.highlighted = newHighlighted UIView.animateWithDuration(0.25) { self.layer.backgroundColor = self.highlighted ? self.tintColor?.CGColor : UIColor.whiteColor().CGColor } setNeedsDisplay() } } get { return super.highlighted } } }
a1ec7b5ec5e7a05f851ad86515a0d123
25.525
122
0.574929
false
false
false
false
joostholslag/BNRiOS
refs/heads/master
iOSProgramming6ed/1 - Simple/Solutions/Quiz/Quiz/ViewController.swift
gpl-3.0
1
// // Copyright © 2015 Big Nerd Ranch // import UIKit class ViewController: UIViewController { @IBOutlet var questionLabel: UILabel! @IBOutlet var answerLabel: UILabel! let questions: [String] = [ "From what is cognac made?", "What is 7+7?", "What is the capital of Vermont?" ] let answers: [String] = [ "Grapes", "14", "Montpelier" ] var currentQuestionIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() questionLabel.text = questions[currentQuestionIndex] } @IBAction func showNextQuestion(_ sender: UIButton) { currentQuestionIndex += 1 if currentQuestionIndex == questions.count { currentQuestionIndex = 0 } let question: String = questions[currentQuestionIndex] questionLabel.text = question answerLabel.text = "???" } @IBAction func showAnswer(_ sender: UIButton) { let answer: String = answers[currentQuestionIndex] answerLabel.text = answer } }
2a84f2d3a0499472b9c6e8442e6d6951
22.382979
62
0.594177
false
false
false
false
adamdahan/GraphKit
refs/heads/v3.x.x
Source/Reachability.swift
agpl-3.0
1
// // Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program located at the root of the software package // in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>. // import SystemConfiguration public enum ReachabilityStatus { /** :name: NotRechable :description: Network is not reachable. */ case NotReachable /** :name: ReachableViaWiFi :description: Network is reachable via Wifi. */ case ReachableViaWiFi /** :name: ReachableViaWWAN :description: Network is reachable via WWAN. */ case ReachableViaWWAN } @objc(ReachabilityDelegate) public protocol ReachabilityDelegate { /** :name: reachabilityDidChangeStatus :description: An optional Delegate that is called when the Network ReachabilityStatus changes. :param: reachability Reachability The calling Reachability instance. */ optional func reachabilityDidChangeStatus(reachability: Reachability) /** :name: reachabilityDidBecomeReachable :description: An optional Delegate that is called when the Network ReachabilityStatus is available. :param: reachability Reachability The calling Reachability instance. */ optional func reachabilityDidBecomeReachable(reachability: Reachability) /** :name: reachabilityDidBecomeUnreachable :description: An optional Delegate that is called when the Network ReachabilityStatus is no longer available. :param: reachability Reachability The calling Reachability instance. */ optional func reachabilityDidBecomeUnreachable(reachability: Reachability) } @objc(Reachability) public class Reachability { /** :name: reachability :description: Internal SCNetworkReachability value. :returns: SCNetworkReachability? */ private var reachability: SCNetworkReachability? /** :name: previousFlags :description: Holds the previous SCNetworkReachabilityFlags value when the network connectivity changes. :returns: SCNetworkReachabilityFlags? */ private var previousFlags: SCNetworkReachabilityFlags? /** :name: currentFlags :description: Holds the current SCNetworkReachabilityFlags value when the network connectivity changes. :returns: SCNetworkReachabilityFlags */ private var currentFlags: SCNetworkReachabilityFlags { var flags: SCNetworkReachabilityFlags = 0 return 0 == SCNetworkReachabilityGetFlags(reachability, &flags) ? 0 : flags } /** :name: timer :description: Internal dispatch timer for connectivity watching. :returns: dispatch_source_t? */ private var timer: dispatch_source_t? /** :name: queue :description: Internal dispatch queue for connectivity watching. :returns: dispatch_queue_t */ private lazy var queue: dispatch_queue_t = { return dispatch_queue_create("io.graphkit.Reachability", nil) }() /** :name: status :description: Current ReachabilityStatus value. :returns: ReachabilityStatus */ public private(set) var status: ReachabilityStatus /** :name: onStatusChange :description: An Optional callback to set when network availability changes. :returns: ((reachability: Reachability) -> ())? */ public var onStatusChange: ((reachability: Reachability) -> ())? /** :name: isReachableOnWWAN :description: A boolean flag that allows Reachability to be detected when on WWAN. :returns: Bool */ public var isReachableOnWWAN: Bool /** :name: isRunningOnDevice :description: A boolean flag that indicates the user is using a mobile device or not. :returns: Bool */ public var isRunningOnDevice: Bool = { #if TARGET_IPHONE_SIMULATOR return false #else return true #endif }() /** :name: delegate :description: An optional Delegate to set that is called when Reachability settings change. :returns: ReachabilityDelegate? */ public weak var delegate: ReachabilityDelegate? /** :name: reachabilityForInternetConnection :description: A Class level method that returns a Reachability instance that detects network connectivity changes. :returns: Reachability */ public class func reachabilityForInternetConnection() -> Reachability { var addr: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) addr.sin_len = UInt8(sizeofValue(addr)) addr.sin_family = sa_family_t(AF_INET) return Reachability(reachability: withUnsafePointer(&addr) { SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)).takeRetainedValue() }) } private init() { status = .NotReachable isReachableOnWWAN = true } /** :name: init :description: A Constructor that allows for the SCNetworkReachability reference to be set externally. :param: reachability SCNetworkReachability An external SCNetworkReachability reference. */ public convenience init(reachability: SCNetworkReachability) { self.init() self.reachability = reachability } deinit { stopWatcher() reachability = nil } /** :name: startWatcher :description: Start watching for network changes. :returns: Bool */ public func startWatcher() -> Bool { timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) if nil == timer { return false } dispatch_source_set_timer(timer!, dispatch_walltime(nil, 0), 500 * NSEC_PER_MSEC, 100 * NSEC_PER_MSEC) dispatch_source_set_event_handler(timer!, { _ in self.watcherUpdate() }) previousFlags = currentFlags dispatch_resume(timer!) return true } /** :name: stopWatcher :description: Stop watching for network changes. */ public func stopWatcher() { if nil != timer { dispatch_source_cancel(timer!) timer = nil } } /** :name: watcherUpdate :description: Called when the Reachability changes. */ private func watcherUpdate() { let flags: SCNetworkReachabilityFlags = currentFlags if flags != previousFlags { dispatch_async(dispatch_get_main_queue(), { _ in let s: ReachabilityStatus = self.status self.statusDidChange(flags) self.previousFlags = flags }) } } /** :name: statusDidChange :description: When the status changes, this method calls the Delegate handles. :param: flags SCNetworkReachabilityFlags Flags that determine the changed state. */ private func statusDidChange(flags: SCNetworkReachabilityFlags) { onStatusChange?(reachability: self) delegate?.reachabilityDidChangeStatus?(self) if isReachable(flags) { status = isWWAN(flags) ? .ReachableViaWWAN : .ReachableViaWiFi delegate?.reachabilityDidBecomeReachable?(self) } else { status = .NotReachable delegate?.reachabilityDidBecomeUnreachable?(self) } } /** :name: isRaachable :description: Determines whether the network is reachable or not. :returns: Bool */ private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool { return !(!(0 != flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable)) || (0 != flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsTransientConnection | kSCNetworkReachabilityFlagsConnectionRequired)) || (isRunningOnDevice && isWWAN(flags) && !isReachableOnWWAN)) } /** :name: isWWAN :description: Determines whether the network is WWAN. :returns: Bool */ private func isWWAN(flags: SCNetworkReachabilityFlags) -> Bool { #if os(iOS) return 0 != flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsWWAN) #else return false #endif } }
ea9a3cc119f90d824aa78b03faaceca8
27.510563
178
0.741015
false
false
false
false
ludagoo/Perfect
refs/heads/master
PerfectLib/AJAXObjectDriver.swift
agpl-3.0
2
// // AJAXObjectDriver.swift // PerfectLib // // Created by Kyle Jessup on 2015-08-10. // Copyright (C) 2015 PerfectlySoft, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version, as supplemented by the // Perfect Additional Terms. // // 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 Affero General Public License, as supplemented by the // Perfect Additional Terms, for more details. // // You should have received a copy of the GNU Affero General Public License // and the Perfect Additional Terms that immediately follow the terms and // conditions of the GNU Affero General Public License along with this // program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>. // import Foundation let actionParamName = "_action" /// This client-side class handles access to the AJAX/XHR API. /// It provides facilities for setting up the parameters for the raw requests public class AJAXObjectDriver : PerfectObjectDriver { let endpointBase: String let fileExtension: String public let curl = CURL() public init(endpointBase: String, fileExtension: String = ".mustache") { self.endpointBase = endpointBase self.fileExtension = fileExtension } public func close() { self.curl.close() } // protected! public func performRequest(uri: String) -> (Int, String, String) { self.curl.url = uri let (code, head, body) = curl.performFully() if code == 0 { let responseCode = curl.responseCode return (responseCode, UTF8Encoding.encode(head), UTF8Encoding.encode(body)) } return (code, UTF8Encoding.encode(head), UTF8Encoding.encode(body)) } public func load<T : PerfectObject>(type: T, withId: uuid_t) -> T { let fileName = type.simpleName() + self.fileExtension var url = self.endpointBase + fileName + "?" + actionParamName + "=" + HandlerAction.Load.asString() url.appendContentsOf("&" + type.primaryKeyName().stringByEncodingURL + "=" + String.fromUUID(withId).stringByEncodingURL) let (code, _, bodyStr) = self.performRequest(url) if code == 200 { do { if let deJason = try JSONDecode().decode(bodyStr) as? JSONDictionaryType { let dictionary = deJason.dictionary if let resultSets = dictionary["resultSets"] as? JSONArrayType { if let results = resultSets.array.first as? JSONDictionaryType { let innerDictionary = results.dictionary let possibleFields = type.fieldList() var newDict = [String:String]() for (n, v) in innerDictionary { if possibleFields.contains(n) { newDict[n] = "\(v)" } } type.load(newDict) } } } } catch { } } return type } public func load<T : PerfectObject>(type: T, withUniqueField: (String,String)) -> T { let fileName = type.simpleName() + self.fileExtension var url = self.endpointBase + fileName + "?" + actionParamName + "=" + HandlerAction.Load.asString() url.appendContentsOf("&" + withUniqueField.0.stringByEncodingURL + "=" + withUniqueField.1.stringByEncodingURL) let (code, _, bodyStr) = self.performRequest(url) if code == 200 { do { if let deJason = try JSONDecode().decode(bodyStr) as? JSONDictionaryType { let dictionary = deJason.dictionary if let resultSets = dictionary["resultSets"] as? JSONArrayType { if let results = resultSets.array.first as? JSONDictionaryType { let innerDictionary = results.dictionary let possibleFields = type.fieldList() var newDict = [String:String]() for (n, v) in innerDictionary { if possibleFields.contains(n) { newDict[n] = "\(v)" } } type.load(newDict) } } } } catch { } } return type } public func delete(type: PerfectObject) -> (Int, String) { let fileName = type.simpleName() + self.fileExtension var url = self.endpointBase + fileName + "?" + actionParamName + "=" + HandlerAction.Delete.asString() url.appendContentsOf("&" + type.primaryKeyName().stringByEncodingURL + "=" + String.fromUUID(type.objectId()).stringByEncodingURL) let (code, _, bodyStr) = self.performRequest(url) if code == 200 { do { if let deJason = try JSONDecode().decode(bodyStr) as? JSONDictionaryType { let dictionary = deJason.dictionary let resultMsg = dictionary["resultMsg"] as? String ?? "Invalid response" let resultCode = Int(dictionary["resultCode"] as? String ?? "-1")! return (resultCode, resultMsg) } } catch { } } return (-1, "Invalid response") } public func commitChanges(type: PerfectObject) -> (Int, String) { let fileName = type.simpleName() + self.fileExtension var url = self.endpointBase + fileName + "?" + actionParamName + "=" + HandlerAction.Commit.asString() url.appendContentsOf("&" + type.primaryKeyName().stringByEncodingURL + "=" + String.fromUUID(type.objectId()).stringByEncodingURL) let withFields = type.unloadDirty() for (n, v) in withFields { url.appendContentsOf("&" + n.stringByEncodingURL + "=" + v.stringByEncodingURL) } let (code, _, bodyStr) = self.performRequest(url) if code == 200 { do { if let deJason = try JSONDecode().decode(bodyStr) as? JSONDictionaryType { let dictionary = deJason.dictionary let resultMsg = dictionary["resultMsg"] as? String ?? "Invalid response" let resultCode = Int(dictionary["resultCode"] as? String ?? "-1")! return (resultCode, resultMsg) } } catch { } } return (-1, "Invalid response") } // !FIX! optimize this so that it can accomplish the updates in one request public func commitChanges(types: [PerfectObject]) -> [(Int, String)] { return types.map { self.commitChanges($0) } } public func create<T : PerfectObject>(withFields: [(String,String)]) -> T { let t = T(driver: self) let fileName = t.simpleName() + self.fileExtension var url = self.endpointBase + fileName + "?" + actionParamName + "=" + HandlerAction.Create.asString() for (n, v) in withFields { url.appendContentsOf("&" + n.stringByEncodingURL + "=" + v.stringByEncodingURL) } let (code, _, bodyStr) = self.performRequest(url) if code == 200 { do { if let deJason = try JSONDecode().decode(bodyStr) as? JSONDictionaryType { let dictionary = deJason.dictionary if let resultSets = dictionary["resultSets"] as? JSONArrayType { if let results = resultSets.array.first as? JSONDictionaryType { let innerDictionary = results.dictionary let possibleFields = t.fieldList() var newDict = [String:String]() for (n, v) in innerDictionary { if possibleFields.contains(n) { newDict[n] = "\(v)" } } t.load(newDict) } } } } catch { } } return t } public func joinTable<T : PerfectObject>(type: PerfectObject, name: String) -> [T] { let keyField = "id_" + type.simpleName() let ret:[T] = self.list((keyField, String.fromUUID(type.objectId()))) return ret } public func list<T : PerfectObject>() -> [T] { var returning = [T]() var t = T(driver: self) let fileName = t.simpleName() + self.fileExtension let url = self.endpointBase + fileName + "?" + actionParamName + "=" + HandlerAction.List.asString() let (code, _, bodyStr) = self.performRequest(url) if code == 200 { do { if let deJason = try JSONDecode().decode(bodyStr) as? JSONDictionaryType { let dictionary = deJason.dictionary if let resultSets = dictionary["resultSets"] as? JSONArrayType { for resultSet in resultSets.array { if let results = resultSet as? JSONDictionaryType { let innerDictionary = results.dictionary let possibleFields = t.fieldList() var newDict = [String:String]() for (n, v) in innerDictionary { if possibleFields.contains(n) { newDict[n] = "\(v)" } } t.load(newDict) returning.append(t) t = T(driver: self) } } } } } catch { } } return returning } public func list<T : PerfectObject>(withCriterion: (String,String)) -> [T] { var returning = [T]() var t = T(driver: self) let fileName = t.simpleName() + self.fileExtension let url = self.endpointBase + fileName + "?" + actionParamName + "=" + HandlerAction.List.asString() + "&" + withCriterion.0.stringByEncodingURL + "=" + withCriterion.1.stringByEncodingURL let (code, _, bodyStr) = self.performRequest(url) if code == 200 { do { if let deJason = try JSONDecode().decode(bodyStr) as? JSONDictionaryType { let dictionary = deJason.dictionary if let resultSets = dictionary["resultSets"] as? JSONArrayType { for resultSet in resultSets.array { if let results = resultSet as? JSONDictionaryType { let innerDictionary = results.dictionary let possibleFields = t.fieldList() var newDict = [String:String]() for (n, v) in innerDictionary { if possibleFields.contains(n) { newDict[n] = "\(v)" } } t.load(newDict) returning.append(t) t = T(driver: self) } } } } } catch { } } return returning } }
3a83116620861e4dffdfc3b8f7e129ca
31.927835
132
0.653517
false
false
false
false
mpangburn/RayTracer
refs/heads/master
RayTracerTests/VectorTests.swift
mit
1
// // VectorTests.swift // RayTracer // // Created by Michael Pangburn on 6/25/17. // Copyright © 2017 Michael Pangburn. All rights reserved. // import XCTest @testable import RayTracer class VectorTests: XCTestCase { let vector1 = Vector(x: 1, y: 2, z: 3) let vector2 = Vector(x: 3, y: 4, z: 5) let vector3 = Vector(x: 0, y: 3, z: 4) func testEquals() { XCTAssert(vector2 == Vector(x: 3, y: 4, z: 5)) XCTAssert(vector1 != vector2) } func testInit() { XCTAssert(vector1.x == 1 && vector1.y == 2 && vector1.z == 3) XCTAssert(Vector(from: Point(x: 1, y: 2, z: 3), to: Point(x: 5, y: 4, z: 3)) == Vector(x: 4, y: 2, z: 0)) } func testProperties() { XCTAssert(vector1.length == sqrt(14)) XCTAssert(vector3.magnitude == 5) } func testMath() { let normalized = vector3.normalized() XCTAssertEqualWithAccuracy(normalized.x, 0, accuracy: 0.00001) XCTAssertEqualWithAccuracy(normalized.y, 0.6, accuracy: 0.00001) XCTAssertEqualWithAccuracy(normalized.z, 0.8, accuracy: 0.00001) XCTAssert(vector1.scaled(by: 3) == Vector(x: 3, y: 6, z: 9)) XCTAssert(vector1.dot(with: vector2) == 26) XCTAssert(vector2.dot(with: vector1) == 26) XCTAssert(vector1.cross(with: vector2) == Vector(x: -2, y: 4, z: -2)) XCTAssert(vector2.cross(with: vector1) == Vector(x: 2, y: -4, z: 2)) } func testMutation() { var vector3Copy = vector3 vector3Copy.scale(by: 2) XCTAssert(vector3Copy == Vector(x: 0, y: 6, z: 8)) vector3Copy.normalize() XCTAssertEqualWithAccuracy(vector3Copy.x, 0, accuracy: 0.00001) XCTAssertEqualWithAccuracy(vector3Copy.y, 0.6, accuracy: 0.00001) XCTAssertEqualWithAccuracy(vector3Copy.z, 0.8, accuracy: 0.00001) } func testOperators() { XCTAssert(vector1 + vector2 == Vector(x: 4, y: 6, z: 8)) XCTAssert(vector1 - vector2 == Vector(x: -2, y: -2, z: -2)) XCTAssert(-vector1 == Vector(x: -1, y: -2, z: -3)) XCTAssert(vector1 * 2 == Vector(x: 2, y: 4, z: 6)) XCTAssert(3 * vector2 == Vector(x: 9, y: 12, z: 15)) XCTAssert(vector2 / 2 == Vector(x: 1.5, y: 2, z: 2.5)) } func testCustomOperators() { XCTAssert(vector1 × vector2 == Vector(x: -2, y: 4, z: -2)) XCTAssert(vector2 × vector1 == Vector(x: 2, y: -4, z: 2)) XCTAssert(vector1 • vector2 == 26) XCTAssert(vector2 • vector1 == 26) } }
7df7240419c63a395a21c2191926a530
33.958333
113
0.586015
false
true
false
false
allevato/SwiftCGI
refs/heads/master
Sources/SwiftCGI/FCGIServer.swift
apache-2.0
1
// Copyright 2015 Tony Allevato // // 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. #if os(Linux) import Glibc #else import Darwin.C #endif /// The number of threads to run concurrently to process incoming requests. /// TODO: Make this configurable by the user. private let NumberOfThreads = 4 /// The server implementation used when the application is running as a FastCGI process. class FCGIServer: ServerProtocol { /// The array of threads currently running to process requests. var threads = [Thread]() /// Creates a new FastCGI server implementation. init() {} func listen(handler: (HTTPRequest, HTTPResponse) -> Void) { threads = [Thread]((0..<NumberOfThreads).map { _ in threaded(self.listenOnThread(handler)) }) // Wait for the threads to exit before returning (which, assuming the user does nothing else // after calling `Server.listen`, would end the process). Depending on how the web server treats // the connection socket, this may never actually complete. for thread in threads { thread.join() } } /// Returns a function that listens repeatedly for incoming requests on the current thread and /// dispatches them to the given handler as they arrive. The function runs indefinitely, stopping /// only if the web server closes the connection. /// /// - Parameter handler: The user's handler to be called when the request is ready. /// - Returns: A no-argument function that listens for incoming requests and calls the given /// handler when they are ready to be processed. private func listenOnThread(handler: (HTTPRequest, HTTPResponse) -> Void) -> (() -> Void) { return { while let socket = self.acceptConnection() { let socketInputStream = FileInputStream(fileDescriptor: socket) let socketOutputStream = FileOutputStream(fileDescriptor: socket) let requestHandler = FCGIRequestHandler( inputStream: socketInputStream, outputStream: socketOutputStream, handler: handler) do { try requestHandler.start() } catch { // TODO: Log the error. } } } } /// Extracts the first connection request from the queue of pending connections and returns the /// socket's file descriptor, blocking if there are no connections pending. /// /// - Returns: The socket's file descriptor, or nil if an error occurred. private func acceptConnection() -> Int32? { var address = sockaddr() var addressLen = socklen_t() let socket = accept(0, &address, &addressLen) if socket > 0 { return socket } else { return nil } } }
8498e39ce56cd99b7181b081574b62f0
35.183908
100
0.698539
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Modules/Settings/SettingsView.swift
agpl-3.0
2
// // SettingsView.swift // SmartReceipts // // Created by Bogdan Evsenev on 06/07/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import UIKit import Viperit import RxSwift import MessageUI import StoreKit //MARK: - Public Interface Protocol protocol SettingsViewInterface { var doneButton: UIBarButtonItem { get } func setupShowSettingsOption(_ option: ShowSettingsOption?) } //MARK: SettingsView Class final class SettingsView: UserInterface { @IBOutlet fileprivate weak var doneButtonItem: UIBarButtonItem! private var formView: SettingsFormView! private let bag = DisposeBag() private lazy var feedbackComposer = FeedbackComposer() override func viewDidLoad() { super.viewDidLoad() navigationItem.title = LocalizedString("menu_main_settings") formView = SettingsFormView(settingsView: self, dateFormats: displayData.formats) formView.showOption = displayData.showSettingsOption formView.openModuleSubject = presenter.openModuleSubject formView.alertSubject = presenter.alertSubject addChild(formView) view.addSubview(formView.view) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setToolbarHidden(true, animated: true) } func retrivePlusSubscriptionPrice() -> Observable<String> { return presenter.retrivePlusSubscriptionPrice() } func restoreSubscription() -> Observable<SubscriptionValidation> { return presenter.restoreSubscription() } func purchaseSubscription() -> Observable<Void> { return presenter.purchaseSubscription() } func subscriptionValidation() -> Observable<SubscriptionValidation> { return presenter.subscriptionValidation() } func sendFeedback(subject: String) { feedbackComposer.present(on: self, subject: subject) } } //MARK: - Public interface extension SettingsView: SettingsViewInterface { var doneButton: UIBarButtonItem { get{ return doneButtonItem } } func setupShowSettingsOption(_ option: ShowSettingsOption?) { displayData.showSettingsOption = option } } // MARK: - VIPER COMPONENTS API (Auto-generated code) private extension SettingsView { var presenter: SettingsPresenter { return _presenter as! SettingsPresenter } var displayData: SettingsDisplayData { return _displayData as! SettingsDisplayData } }
9b0c0783129d74262961759a748c34b2
28.511628
89
0.707644
false
false
false
false
time-fighters/patachu
refs/heads/master
Time Fighter/Ground.swift
mit
1
// // Ground.swift // Time Fighter // // Created by Paulo Henrique Favero Pereira on 7/10/17. // Copyright © 2017 Fera. All rights reserved. // import UIKit import SpriteKit class Ground: SKShapeNode { let stairs = SKTexture(imageNamed: "Stairs") var points = [CGPoint(x: 4187, y: -264), CGPoint(x: 4275, y: -264), CGPoint(x: 4896, y: 111), CGPoint(x: 6130, y: 111), CGPoint(x: 6829, y: -264), CGPoint(x: 4187, y: -264)] public init(scene:SKScene) { var groundShape = SKSpriteNode(texture: stairs) let path = CGMutablePath() path.addLines(between: [self.points[0], self.points[1], self.points[2],self.points[3], self.points[4],self.points[5]]) path.closeSubpath() groundShape.zPosition = 0 groundShape.physicsBody = SKPhysicsBody(polygonFrom: path) groundShape.physicsBody?.affectedByGravity = false groundShape.physicsBody?.allowsRotation = false groundShape.physicsBody?.angularDamping = 0 groundShape.physicsBody?.friction = 0.8 groundShape.physicsBody?.angularVelocity = 0 groundShape.physicsBody?.isDynamic = false groundShape.physicsBody?.categoryBitMask = GameElements.ground groundShape.physicsBody?.collisionBitMask = GameElements.mainCharacter | GameElements.enemy groundShape.physicsBody?.contactTestBitMask = GameElements.bullet | GameElements.mainCharacter groundShape.alpha = 0 groundShape.position = CGPoint.zero scene.addChild(groundShape) super.init() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
104b5a42f7da33b5f65c01de922e228e
34.27451
126
0.634797
false
false
false
false
chrisjmendez/swift-exercises
refs/heads/master
Basic/REST/HTTPRequests/Pods/SwiftHTTP/HTTPTask.swift
mit
1
////////////////////////////////////////////////////////////////////////////////////////////////// // // HTTPTask.swift // // Created by Dalton Cherry on 6/3/14. // Copyright (c) 2014 Vluxe. All rights reserved. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation /// HTTP Verbs. /// /// - GET: For GET requests. /// - POST: For POST requests. /// - PUT: For PUT requests. /// - HEAD: For HEAD requests. /// - DELETE: For DELETE requests. /// - PATCH: For PATCH requests. public enum HTTPMethod: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case HEAD = "HEAD" case DELETE = "DELETE" case PATCH = "PATCH" } /// Object representation of a HTTP Response. public class HTTPResponse { /// The header values in HTTP response. public var headers: Dictionary<String,String>? /// The mime type of the HTTP response. public var mimeType: String? /// The suggested filename for a downloaded file. public var suggestedFilename: String? /// The body or response data of the HTTP Response. public var responseObject: AnyObject? /// The status code of the HTTP Response. public var statusCode: Int? /// The URL of the HTTP Response. public var URL: NSURL? ///Returns the response as a string public var text: String? { if let d = self.responseObject as? NSData { return NSString(data: d, encoding: NSUTF8StringEncoding) as? String } else if let val: AnyObject = self.responseObject { return "\(val)" } return nil } //get the description of the response public var description: String { var buffer = "" if let u = self.URL { buffer += "URL:\n\(u)\n\n" } if let heads = self.headers { buffer += "Headers:\n" for (key, value) in heads { buffer += "\(key): \(value)\n" } buffer += "\n" } if let s = self.text { buffer += "Payload:\n\(s)\n" } return buffer } } /// Holds the blocks of the background task. class BackgroundBlocks { // these 2 only get used for background download/upload since they have to be delegate methods var success:((HTTPResponse) -> Void)? var failure:((NSError, HTTPResponse?) -> Void)? var progress:((Double) -> Void)? /** Initializes a new Background Block :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. :param: progress The block that is run on the progress of a HTTP Upload or Download. */ init(_ success: ((HTTPResponse) -> Void)?, _ failure: ((NSError, HTTPResponse?) -> Void)?,_ progress: ((Double) -> Void)?) { self.failure = failure self.success = success self.progress = progress } } /// Subclass of NSOperation for handling and scheduling HTTPTask on a NSOperationQueue. public class HTTPOperation : NSOperation { private var task: NSURLSessionDataTask! private var stopped = false private var running = false /// Controls if the task is finished or not. public var done = false //MARK: Subclassed NSOperation Methods /// Returns if the task is asynchronous or not. This should always be false. override public var asynchronous: Bool { return false } /// Returns if the task has been cancelled or not. override public var cancelled: Bool { return stopped } /// Returns if the task is current running. override public var executing: Bool { return running } /// Returns if the task is finished. override public var finished: Bool { return done } /// Returns if the task is ready to be run or not. override public var ready: Bool { return !running } /// Starts the task. override public func start() { super.start() stopped = false running = true done = false task.resume() } /// Cancels the running task. override public func cancel() { super.cancel() running = false stopped = true done = true task.cancel() } /// Sets the task to finished. public func finish() { self.willChangeValueForKey("isExecuting") self.willChangeValueForKey("isFinished") running = false done = true self.didChangeValueForKey("isExecuting") self.didChangeValueForKey("isFinished") } } /// Configures NSURLSession Request for HTTPOperation. Also provides convenience methods for easily running HTTP Request. public class HTTPTask : NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate { var backgroundTaskMap = Dictionary<String,BackgroundBlocks>() //var sess: NSURLSession? public var baseURL: String? public var requestSerializer = HTTPRequestSerializer() public var responseSerializer: HTTPResponseSerializer? //This gets called on auth challenges. If nil, default handling is use. //Returning nil from this method will cause the request to be rejected and cancelled public var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)? //MARK: Public Methods /// A newly minted HTTPTask for your enjoyment. public override init() { super.init() } /** Creates a HTTPOperation that can be scheduled on a NSOperationQueue. Called by convenience HTTP verb methods below. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. :returns: A freshly constructed HTTPOperation to add to your NSOperationQueue. */ public func create(url: String, method: HTTPMethod, parameters: Dictionary<String,AnyObject>!, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) -> HTTPOperation? { let serialReq = createRequest(url, method: method, parameters: parameters) if serialReq.error != nil { if failure != nil { failure(serialReq.error!, nil) } return nil } let opt = HTTPOperation() let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) let task = session.dataTaskWithRequest(serialReq.request, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in opt.finish() if error != nil { if failure != nil { failure(error, nil) } return } if data != nil { var responseObject: AnyObject = data if self.responseSerializer != nil { let resObj = self.responseSerializer!.responseObjectFromResponse(response, data: data) if resObj.error != nil { if failure != nil { failure(resObj.error!, nil) } return } if resObj.object != nil { responseObject = resObj.object! } } var extraResponse = HTTPResponse() if let hresponse = response as? NSHTTPURLResponse { extraResponse.headers = hresponse.allHeaderFields as? Dictionary<String,String> extraResponse.mimeType = hresponse.MIMEType extraResponse.suggestedFilename = hresponse.suggestedFilename extraResponse.statusCode = hresponse.statusCode extraResponse.URL = hresponse.URL } extraResponse.responseObject = responseObject if extraResponse.statusCode > 299 { if failure != nil { failure(self.createError(extraResponse.statusCode!), extraResponse) } } else if success != nil { success(extraResponse) } } else if failure != nil { failure(error, nil) } }) opt.task = task return opt } /** Creates a HTTPOperation as a HTTP GET request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func GET(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.GET, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates a HTTPOperation as a HTTP POST request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func POST(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.POST, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates a HTTPOperation as a HTTP PATCH request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func PATCH(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.PATCH, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates a HTTPOperation as a HTTP PUT request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func PUT(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.PUT, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates a HTTPOperation as a HTTP DELETE request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func DELETE(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.DELETE, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates a HTTPOperation as a HTTP HEAD request and starts it for you. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: success The block that is run on a sucessful HTTP Request. :param: failure The block that is run on a failed HTTP Request. */ public func HEAD(url: String, parameters: Dictionary<String,AnyObject>?, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) { var opt = self.create(url, method:.HEAD, parameters: parameters,success: success,failure: failure) if opt != nil { opt!.start() } } /** Creates and starts a HTTPOperation to download a file in the background. :param: url The url you would like to make a request to. :param: parameters The parameters are HTTP parameters you would like to send. :param: progress The progress returned in the progress block is between 0 and 1. :param: success The block that is run on a sucessful HTTP Request. The HTTPResponse responseObject object will be a fileURL. You MUST copy the fileURL return in HTTPResponse.responseObject to a new location before using it (e.g. your documents directory). :param: failure The block that is run on a failed HTTP Request. */ public func download(url: String, method: HTTPMethod = .GET, parameters: Dictionary<String,AnyObject>?,progress:((Double) -> Void)!, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) -> NSURLSessionDownloadTask? { let serialReq = createRequest(url,method: method, parameters: parameters) if serialReq.error != nil { failure(serialReq.error!, nil) return nil } let ident = createBackgroundIdent() let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(ident) let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) let task = session.downloadTaskWithRequest(serialReq.request) self.backgroundTaskMap[ident] = BackgroundBlocks(success,failure,progress) //this does not have to be queueable as Apple's background dameon *should* handle that. task.resume() return task } //TODO: not implemented yet. /// not implemented yet. public func uploadFile(url: String, parameters: Dictionary<String,AnyObject>?, progress:((Double) -> Void)!, success:((HTTPResponse) -> Void)!, failure:((NSError) -> Void)!) -> Void { let serialReq = createRequest(url,method: .GET, parameters: parameters) if serialReq.error != nil { failure(serialReq.error!) return } let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(createBackgroundIdent()) let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) //session.uploadTaskWithRequest(serialReq.request, fromData: nil) } //MARK: Private Helper Methods /** Creates and starts a HTTPOperation to download a file in the background. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :param: parameters The parameters are HTTP parameters you would like to send. :returns: A NSURLRequest from configured requestSerializer. */ private func createRequest(url: String, method: HTTPMethod, parameters: Dictionary<String,AnyObject>!) -> (request: NSURLRequest, error: NSError?) { var urlVal = url //probably should change the 'http' to something more generic if !url.hasPrefix("http") && self.baseURL != nil { var split = url.hasPrefix("/") ? "" : "/" urlVal = "\(self.baseURL!)\(split)\(url)" } if let u = NSURL(string: urlVal) { return self.requestSerializer.createRequest(u, method: method, parameters: parameters) } return (NSURLRequest(),createError(-1001)) } /** Creates a random string to use for the identifier of the background download/upload requests. :returns: Identifier String. */ private func createBackgroundIdent() -> String { let letters = "abcdefghijklmnopqurstuvwxyz" var str = "" for var i = 0; i < 14; i++ { let start = Int(arc4random() % 14) str.append(letters[advance(letters.startIndex,start)]) } return "com.vluxe.swifthttp.request.\(str)" } /** Creates a random string to use for the identifier of the background download/upload requests. :param: code Code for error. :returns: An NSError. */ private func createError(code: Int) -> NSError { var text = "An error occured" if code == 404 { text = "Page not found" } else if code == 401 { text = "Access denied" } else if code == -1001 { text = "Invalid URL" } return NSError(domain: "HTTPTask", code: code, userInfo: [NSLocalizedDescriptionKey: text]) } /** Creates a random string to use for the identifier of the background download/upload requests. :param: identifier The identifier string. :returns: An NSError. */ private func cleanupBackground(identifier: String) { self.backgroundTaskMap.removeValueForKey(identifier) } //MARK: NSURLSession Delegate Methods /// Method for authentication challenge. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { if let a = auth { let cred = a(challenge) if let c = cred { completionHandler(.UseCredential, c) return } completionHandler(.RejectProtectionSpace, nil) return } completionHandler(.PerformDefaultHandling, nil) } /// Called when the background task failed. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let err = error { let blocks = self.backgroundTaskMap[session.configuration.identifier] if blocks?.failure != nil { //Swift bug. Can't use && with block (radar: 17469794) blocks?.failure!(err, nil) cleanupBackground(session.configuration.identifier) } } } /// The background download finished and reports the url the data was saved to. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) { let blocks = self.backgroundTaskMap[session.configuration.identifier] if blocks?.success != nil { var resp = HTTPResponse() if let hresponse = downloadTask.response as? NSHTTPURLResponse { resp.headers = hresponse.allHeaderFields as? Dictionary<String,String> resp.mimeType = hresponse.MIMEType resp.suggestedFilename = hresponse.suggestedFilename resp.statusCode = hresponse.statusCode resp.URL = hresponse.URL } resp.responseObject = location if resp.statusCode > 299 { if blocks?.failure != nil { blocks?.failure!(self.createError(resp.statusCode!), resp) } return } blocks?.success!(resp) cleanupBackground(session.configuration.identifier) } } /// Will report progress of background download func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let increment = 100.0/Double(totalBytesExpectedToWrite) var current = (increment*Double(totalBytesWritten))*0.01 if current > 1 { current = 1; } let blocks = self.backgroundTaskMap[session.configuration.identifier] if blocks?.progress != nil { blocks?.progress!(current) } } /// The background download finished, don't have to really do anything. public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { } //TODO: not implemented yet. /// not implemented yet. The background upload finished and reports the response data (if any). func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) { //add upload finished logic } //TODO: not implemented yet. /// not implemented yet. public func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { //add progress block logic } //TODO: not implemented yet. /// not implemented yet. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { } }
949d9129c36d89de034cf876000c48bb
40.542214
263
0.611598
false
false
false
false
cwwise/CWWeChat
refs/heads/master
CWWeChat/MainClass/MomentModule/Layout/CWMomentFlowLayout.swift
mit
2
// // CWMomentFlowLayout.swift // CWWeChat // // Created by wei chen on 2017/7/26. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit import YYText class CWMomentFlowLayout: UICollectionViewFlowLayout { override class var layoutAttributesClass: Swift.AnyClass { return CWMomentAttributes.self } /// var cellHeight: CGFloat = 0 /// 头像 var avatarFrame: CGRect = .zero /// 用户名 var usernameFrame: CGRect = .zero /// 图片或者新闻(音乐) var multimediaFrame: CGRect = .zero /// 图片大小(待修改 如果图片只有一张需要根据比例算) var pictureSize: CGSize = .zero /// var toolButtonFrame: CGRect = .zero /// 点赞部分 var praiseHeight: CGFloat = 0 var praiseLayout: YYTextLayout? var commentHeight: CGFloat = 0 var commentLayoutArray = [YYTextLayout]() } extension CWMomentFlowLayout { }
a5ef137db19cac5b8bcd40952824a5a0
17.833333
62
0.628319
false
false
false
false
saeta/penguin
refs/heads/main
Tests/PenguinStructuresTests/HeapTests.swift
apache-2.0
1
// Copyright 2020 Penguin Authors // // 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 PenguinStructures import XCTest final class HeapTests: XCTestCase { func testHeapOperations() { var a = [0, 1, 2, 3, 4, 5, 6] XCTAssert(a.isMinHeap) XCTAssertEqual(0, a.popMinHeap()) XCTAssertEqual([1, 3, 2, 6, 4, 5], a) XCTAssert(a.isMinHeap) XCTAssertEqual(1, a.popMinHeap()) XCTAssertEqual([2, 3, 5, 6, 4], a) XCTAssert(a.isMinHeap) for i in 2..<7 { XCTAssertEqual(i, a.popMinHeap()) XCTAssert(a.isMinHeap) } XCTAssertNil(a.popMinHeap()) XCTAssert(a.isMinHeap) a.insertMinHeap(42) XCTAssert(a.isMinHeap) XCTAssertEqual([42], a) a = [3, 2, 1, 5, 7, 8, 0, 17, 8] a.reorderAsMinHeap() XCTAssert(a.isMinHeap) a.insertMinHeap(0) XCTAssert(a.isMinHeap) XCTAssertEqual([0, 0, 1, 5, 2, 8, 3, 17, 8, 7], a) } func testHeapOperationCallbacks() { var heap = Array((0..<10).reversed()) XCTAssertFalse(heap.isMinHeap) var indexes = ArrayPriorityQueueIndexer<Int, Int>(count: heap.count) /// Helper function that verifies the index is exactly consistent with /// the heap `a`. func assertIndexConsistent() { var seenElements = Set<Int>() // First, go through everything in the heap, and verify it has the correct index. for index in heap.indices { let element = heap[index] seenElements.insert(element) guard let elementPosition = indexes[element] else { XCTFail("Heap element \(element) was not indexed. \(indexes), \(heap).") return } XCTAssertEqual(elementPosition, index) } // Go through all elements not in the heap and ensure their index value is nil. for i in 0..<10 { if !seenElements.contains(i) { XCTAssertFalse(heap.contains(i), "\(i); \(indexes) \(heap)") XCTAssertNil(indexes[i], "\(i); \(indexes) \(heap)") } } } heap.reorderAsMinHeap { indexes[$0] = $1 } XCTAssert(indexes.table.allSatisfy { $0 != nil }, "\(indexes)") assertIndexConsistent() for i in 0..<4 { let popped = heap.popMinHeap { indexes[$0] = $1 } XCTAssertEqual(popped, i) assertIndexConsistent() } heap.insertMinHeap(2) { indexes[$0] = $1 } assertIndexConsistent() } func testSimple() { var h = SimplePriorityQueue<Int>() let insertSequence = Array(0..<100).shuffled() for i in insertSequence { h.push(i, at: i) } for i in 0..<100 { XCTAssertEqual(i, h.pop()?.payload) } XCTAssertNil(h.pop()) } func testSimpleMaxPQ() { var h = SimpleMaxPriorityQueue<Int>() let insertSequence = Array(0..<100).shuffled() for i in insertSequence { h.push(i, at: i) } for i in (0..<100).reversed() { XCTAssertEqual(i, h.pop()?.payload) } XCTAssertNil(h.pop()) } func testUpdatableUniqueHeapSimple() { var h = makeReprioritizableHeap() XCTAssertEqual("x", h.pop()!.payload) XCTAssertEqual("y", h.pop()!.payload) XCTAssertEqual("z", h.pop()!.payload) XCTAssertEqual(nil, h.pop()) h = makeReprioritizableHeap() h.update("x", withNewPriority: 20) XCTAssertEqual("y", h.pop()!.payload) XCTAssertEqual("z", h.pop()!.payload) XCTAssertEqual("x", h.pop()!.payload) XCTAssertEqual(nil, h.pop()) h = makeReprioritizableHeap() h.update("z", withNewPriority: 5) XCTAssertEqual("z", h.pop()!.payload) XCTAssertEqual("x", h.pop()!.payload) XCTAssertEqual("y", h.pop()!.payload) XCTAssertEqual(nil, h.pop()) } func makeReprioritizableHeap() -> ReprioritizablePriorityQueue<String, Int> { var h = ReprioritizablePriorityQueue<String, Int>() h.push("x", at: 10) h.push("y", at: 11) h.push("z", at: 12) return h } static var allTests = [ ("testHeapOperations", testHeapOperations), ("testSimple", testSimple), ("testSimpleMaxPQ", testSimpleMaxPQ), ("testHeapOperationCallbacks", testHeapOperationCallbacks), ("testUpdatableUniqueHeapSimple", testUpdatableUniqueHeapSimple), ] }
6f485d86a78848ba26f9481c46730b8f
28.846154
87
0.637457
false
true
false
false
lokinfey/MyPerfectframework
refs/heads/master
Examples/Authenticator/Authenticator/AuthenticatingHandler.swift
apache-2.0
1
// // AuthenticatingHandler.swift // Authenticator // // Created by Kyle Jessup on 2015-11-09. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectLib // Handler class // When referenced in a mustache template, this class will be instantiated to handle the request // and provide a set of values which will be used to complete the template. class AuthenticatingHandler: PageHandler { // We set this property if the user is successfully validated. var authenticatedUser: User? // This is the function which all handlers must impliment. // It is called by the system to allow the handler to return the set of values which will be used when populating the template. // - parameter context: The MustacheEvaluationContext which provides access to the WebRequest containing all the information pertaining to the request // - parameter collector: The MustacheEvaluationOutputCollector which can be used to adjust the template output. For example a `defaultEncodingFunc` could be installed to change how outgoing values are encoded. func valuesForResponse(context: MustacheEvaluationContext, collector: MustacheEvaluationOutputCollector) throws -> MustacheEvaluationContext.MapType { // The dictionary which we will return let values = MustacheEvaluationContext.MapType() if let response = context.webResponse, let request = context.webRequest { let auth = request.httpAuthorization() if let digest = auth["type"] where digest == "Digest" { let username = auth["username"] ?? "" let nonce = auth["nonce"] let nc = auth["nc"] let uri = auth["uri"] ?? request.requestURI() let cnonce = auth["cnonce"] let qop = "auth" let method = auth["method"] ?? request.requestMethod() let authResponse = auth["response"] if authResponse != nil && nonce != nil && nc != nil && cnonce != nil { if let userTest = User(email: username) { let ha1 = userTest.authKey let ha2 = toHex((method+":"+uri).md5) let compareResponse = toHex((ha1+":"+nonce!+":"+nc!+":"+cnonce!+":"+qop+":"+ha2).md5) if authResponse! == compareResponse { response.setStatus(200, message: "OK") self.authenticatedUser = userTest } } } } if self.authenticatedUser == nil { let nonce = SessionManager.generateSessionKey() let headerValue = "Digest realm=\"\(AUTH_REALM)\", qop=\"auth\", nonce=\"\(nonce)\", uri=\"\(request.requestURI())\", algorithm=\"md5\"" response.setStatus(401, message: "Unauthorized") response.replaceHeader("WWW-Authenticate", value: headerValue) } } else { fatalError("This is not a web request") } return values } }
4f3a8d11fe3e134cd1f31433b5aa9efe
37.925
211
0.658638
false
false
false
false
AboutObjectsTraining/swift-ios-2015-07-kop
refs/heads/master
ReadingList/ReadingList/ViewBookController.swift
mit
1
import UIKit class ViewBookController: UITableViewController { var book: Book! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var yearLabel: UILabel! @IBOutlet weak var firstNameLabel: UILabel! @IBOutlet weak var lastNameLabel: UILabel! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) titleLabel.text = book.title yearLabel.text = book.year if let firstName = book.author?.firstName { firstNameLabel.text = firstName } if let lastName = book.author?.lastName { lastNameLabel.text = lastName } } }
b46559378e16fd7f39ed64da4860833d
24.37037
51
0.620438
false
false
false
false
cache0928/CCWeibo
refs/heads/master
CCWeibo/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift
mit
2
// // ImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2016 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(OSX) import AppKit typealias ImageView = NSImageView public typealias IndicatorView = NSProgressIndicator #else import UIKit typealias ImageView = UIImageView public typealias IndicatorView = UIActivityIndicatorView #endif // MARK: - Set Images /** * Set image to use from web. */ extension ImageView { /** Set an image with a resource. It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource`. The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL. It will ask for Kingfisher's manager to get the image for the URL. The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use. If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want. - parameter URL: The URL of image. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a resource and a placeholder image. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: Image?) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL and a placeholder image. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: Image?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a resource, a placaholder image and options. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL, a placaholder image and options. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image with a resource, a placeholder image, options and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image with a URL, a placeholder image, options and completion handler. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image with a URL, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { let showIndicatorWhenLoading = kf_showIndicatorWhenLoading var indicator: IndicatorView? = nil if showIndicatorWhenLoading { indicator = kf_indicator indicator?.hidden = false indicator?.kf_startAnimating() } image = placeholderImage kf_setWebURL(resource.downloadURL) let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { receivedSize, totalSize in if let progressBlock = progressBlock { progressBlock(receivedSize: receivedSize, totalSize: totalSize) } }, completionHandler: {[weak self] image, error, cacheType, imageURL in dispatch_async_safely_to_main_queue { guard let sSelf = self where imageURL == sSelf.kf_webURL else { completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) return } sSelf.kf_setImageTask(nil) guard let image = image else { indicator?.kf_stopAnimating() completionHandler?(image: nil, error: error, cacheType: cacheType, imageURL: imageURL) return } if let transitionItem = optionsInfo?.kf_firstMatchIgnoringAssociatedValue(.Transition(.None)), case .Transition(let transition) = transitionItem where cacheType == .None { #if !os(OSX) UIView.transitionWithView(sSelf, duration: 0.0, options: [], animations: { indicator?.kf_stopAnimating() }, completion: { finished in UIView.transitionWithView(sSelf, duration: transition.duration, options: transition.animationOptions, animations: { transition.animations?(sSelf, image) }, completion: { finished in transition.completion?(finished) completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) }) }) #endif } else { indicator?.kf_stopAnimating() sSelf.image = image completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) } } }) kf_setImageTask(task) return task } /** Set an image with a URL, a placeholder image, options, progress handler and completion handler. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithResource(Resource(downloadURL: URL), placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler) } } extension ImageView { /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func kf_cancelDownloadTask() { kf_imageTask?.downloadTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var indicatorKey: Void? private var showIndicatorWhenLoadingKey: Void? private var imageTaskKey: Void? extension ImageView { /// Get the image URL binded to this image view. public var kf_webURL: NSURL? { return objc_getAssociatedObject(self, &lastURLKey) as? NSURL } private func kf_setWebURL(URL: NSURL) { objc_setAssociatedObject(self, &lastURLKey, URL, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Whether show an animating indicator when the image view is loading an image or not. /// Default is false. public var kf_showIndicatorWhenLoading: Bool { get { if let result = objc_getAssociatedObject(self, &showIndicatorWhenLoadingKey) as? NSNumber { return result.boolValue } else { return false } } set { if kf_showIndicatorWhenLoading == newValue { return } else { if newValue { #if os(OSX) let indicator = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) indicator.controlSize = .SmallControlSize indicator.style = .SpinningStyle #else #if os(tvOS) let indicatorStyle = UIActivityIndicatorViewStyle.White #else let indicatorStyle = UIActivityIndicatorViewStyle.Gray #endif let indicator = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle) indicator.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin, .FlexibleTopMargin] #endif indicator.kf_center = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMidY(bounds)) indicator.hidden = true self.addSubview(indicator) kf_setIndicator(indicator) } else { kf_indicator?.removeFromSuperview() kf_setIndicator(nil) } objc_setAssociatedObject(self, &showIndicatorWhenLoadingKey, NSNumber(bool: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } /// The indicator view showing when loading. This will be `nil` if `kf_showIndicatorWhenLoading` is false. /// You may want to use this to set the indicator style or color when you set `kf_showIndicatorWhenLoading` to true. public var kf_indicator: IndicatorView? { return objc_getAssociatedObject(self, &indicatorKey) as? IndicatorView } private func kf_setIndicator(indicator: IndicatorView?) { objc_setAssociatedObject(self, &indicatorKey, indicator, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } private var kf_imageTask: RetrieveImageTask? { return objc_getAssociatedObject(self, &imageTaskKey) as? RetrieveImageTask } private func kf_setImageTask(task: RetrieveImageTask?) { objc_setAssociatedObject(self, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } extension IndicatorView { func kf_startAnimating() { #if os(OSX) startAnimation(nil) #else startAnimating() #endif hidden = false } func kf_stopAnimating() { #if os(OSX) stopAnimation(nil) #else stopAnimating() #endif hidden = true } #if os(OSX) var kf_center: CGPoint { get { return CGPoint(x: frame.origin.x + frame.size.width / 2.0, y: frame.origin.y + frame.size.height / 2.0 ) } set { let newFrame = CGRect(x: newValue.x - frame.size.width / 2.0, y: newValue.y - frame.size.height / 2.0, width: frame.size.width, height: frame.size.height) frame = newFrame } } #else var kf_center: CGPoint { get { return center } set { center = newValue } } #endif }
4163b8fb736ad2f14f7436085abd6ca3
42.711584
242
0.621687
false
false
false
false
Monnoroch/Cuckoo
refs/heads/master
Carthage/Checkouts/Swinject/Carthage/Checkouts/Nimble/Sources/Nimble/DSL.swift
mit
12
import Foundation /// Make an expectation on a given actual value. The value given is lazily evaluated. public func expect<T>(_ expression: @autoclosure @escaping () throws -> T?, file: FileString = #file, line: UInt = #line) -> Expectation<T> { return Expectation( expression: Expression( expression: expression, location: SourceLocation(file: file, line: line), isClosure: true)) } /// Make an expectation on a given actual value. The closure is lazily invoked. public func expect<T>(_ file: FileString = #file, line: UInt = #line, expression: @escaping () throws -> T?) -> Expectation<T> { return Expectation( expression: Expression( expression: expression, location: SourceLocation(file: file, line: line), isClosure: true)) } /// Always fails the test with a message and a specified location. public func fail(_ message: String, location: SourceLocation) { let handler = NimbleEnvironment.activeInstance.assertionHandler handler.assert(false, message: FailureMessage(stringValue: message), location: location) } /// Always fails the test with a message. public func fail(_ message: String, file: FileString = #file, line: UInt = #line) { fail(message, location: SourceLocation(file: file, line: line)) } /// Always fails the test. public func fail(_ file: FileString = #file, line: UInt = #line) { fail("fail() always fails", file: file, line: line) } /// Like Swift's precondition(), but raises NSExceptions instead of sigaborts internal func nimblePrecondition( _ expr: @autoclosure() -> Bool, _ name: @autoclosure() -> String, _ message: @autoclosure() -> String, file: StaticString = #file, line: UInt = #line) -> Bool { let result = expr() if !result { #if _runtime(_ObjC) let e = NSException( name: NSExceptionName(name()), reason: message(), userInfo: nil) e.raise() #else preconditionFailure("\(name()) - \(message())", file: file, line: line) #endif } return result } internal func internalError(_ msg: String, file: FileString = #file, line: UInt = #line) -> Never { fatalError( "Nimble Bug Found: \(msg) at \(file):\(line).\n" + "Please file a bug to Nimble: https://github.com/Quick/Nimble/issues with the " + "code snippet that caused this error." ) }
e6cdc628e731d8a48c6deb7786f88fac
36.8
141
0.634107
false
false
false
false
moltin/ios-sdk
refs/heads/master
Sources/SDK/Utils/Parser.swift
mit
1
// // Parser.swift // moltin iOS // // Created by Craig Tweedy on 22/02/2018. // import Foundation extension CodingUserInfoKey { static let includes = CodingUserInfoKey(rawValue: "com.moltin.includes")! } class MoltinParser { var decoder: JSONDecoder init(withDecoder decoder: JSONDecoder) { self.decoder = decoder } func singleObjectHandler<T: Codable>(withData data: Data?, withResponse: URLResponse?, completionHandler: @escaping ObjectRequestHandler<T>) { guard let data = data else { completionHandler(Result.failure(error: MoltinError.noData)) return } do { let object: T = try self.parseObject(data: data) completionHandler(Result.success(result: object)) } catch { completionHandler(Result.failure(error: error)) } } func collectionHandler<T>(withData data: Data?, withResponse: URLResponse?, completionHandler: @escaping CollectionRequestHandler<T>) { guard let data = data else { completionHandler(Result.failure(error: MoltinError.noData)) return } do { let paginatedResponse: PaginatedResponse<T> = try self.parseCollection(data: data) completionHandler(Result.success(result: paginatedResponse)) } catch { completionHandler(Result.failure(error: error)) } } private func parseCollection<T: Codable>(data: Data) throws -> PaginatedResponse<T> { let collection: PaginatedResponse<T> do { let parsedData = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] self.decoder.userInfo[.includes] = parsedData?["included"] as? [String: Any] ?? [:] collection = try self.decoder.decode(PaginatedResponse<T>.self, from: data) } catch { throw MoltinError.couldNotParseData(underlyingError: error as? DecodingError) } return collection } private func parseObject<T: Codable>(data: Data) throws -> T { let object: T do { let parsedData = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] let jsonObject: Any? = parsedData?["data"] != nil ? parsedData?["data"] : parsedData guard let jsonObj = jsonObject else { throw MoltinError.couldNotFindData } let jsonData = try JSONSerialization.data(withJSONObject: jsonObj, options: []) self.decoder.userInfo[.includes] = parsedData?["included"] as? [String: Any] ?? [:] object = try self.decoder.decode(T.self, from: jsonData) } catch MoltinError.couldNotFindData { throw MoltinError.couldNotFindData } catch { throw MoltinError.couldNotParseData(underlyingError: error as? DecodingError) } return object } }
6190a7c600eecf52d7a6b06c28e478b6
35.6125
146
0.629566
false
false
false
false
jianghongbing/APIReferenceDemo
refs/heads/master
UIKit/UIApplicationShortcutItem/UIApplicationShortcutItem/AppDelegate.swift
mit
1
// // AppDelegate.swift // UIApplicationShortcutItem // // Created by pantosoft on 2018/6/29. // Copyright © 2018年 jianghongbing. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { private var launchedShortcutItem: UIApplicationShortcutItem? var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { print(launchOptions ?? "") var shouldPerformAdditionalDelegateHandling = true if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem { launchedShortcutItem = shortcutItem shouldPerformAdditionalDelegateHandling = false } if let shortcutItems = application.shortcutItems, shortcutItems.isEmpty { addDynamicShortcutItems() } return shouldPerformAdditionalDelegateHandling } func applicationDidBecomeActive(_ application: UIApplication) { guard let shortcut = launchedShortcutItem else { return } _ = handleShortcutItemAction(shortcut) launchedShortcutItem = nil } private func addDynamicShortcutItems() { let mailIcon = UIApplicationShortcutIcon(type: .mail) let mailShortcut = UIApplicationShortcutItem(type: UIMutableApplicationShortcutItem.Identifier.mail.type, localizedTitle: "邮件", localizedSubtitle: "发送邮件", icon: mailIcon, userInfo: nil) // let locationIcon = UIApplicationShortcutIcon(type: .location) // let locationShortcut = UIApplicationShortcutItem(type: UIApplicationShortcutItem.Identifier.location.type, localizedTitle: "位置", localizedSubtitle: "分享位置", icon: locationIcon, userInfo: ["test": "value2"]) // UIApplication.shared.shortcutItems = [mailShortcut, locationShortcut] UIApplication.shared.shortcutItems = [mailShortcut] } func handleShortcutItemAction(_ shortcutItem: UIApplicationShortcutItem) -> Bool{ var handled = false let type = shortcutItem.type if UIApplicationShortcutItem.Identifier(type: type) != nil { handled = true if let navigationViewController = self.window?.rootViewController as? UINavigationController { let storyboard = UIStoryboard(name: "Main", bundle: nil) if let shorcutItemViewController = storyboard.instantiateViewController(withIdentifier: "shortcutItemViewController") as? ShortcutItemViewController { shorcutItemViewController.shortcutItem = shortcutItem navigationViewController.pushViewController(shorcutItemViewController, animated: true) } } } return handled } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { let handled = handleShortcutItemAction(shortcutItem) completionHandler(handled) } }
e33bad4e1f0d76db1782ea895d9086dc
42.388889
215
0.708067
false
false
false
false
devpunk/velvet_room
refs/heads/master
Source/Model/Home/MHomeSaveDataItemFactory.swift
mit
1
import UIKit extension MHomeSaveDataItem { private static let kNewLine:String = "\n" private static let kFontGameName:CGFloat = 14 private static let kFontLastUpdated:CGFloat = 12 //MARK: private private class func factoryShortDescr( identifier:DVitaIdentifier, dateFormatter:DateFormatter, attributesGameName:[NSAttributedStringKey:Any], attributesLastUpdated:[NSAttributedStringKey:Any]) -> NSAttributedString? { guard let gameName:String = factoryGameName( identifier:identifier), let lastUpdate:String = factoryLastUpdate( identifier:identifier, dateFormatter:dateFormatter) else { return nil } let stringGameName:NSAttributedString = NSAttributedString( string:gameName, attributes:attributesGameName) let stringLastUpdated:NSAttributedString = NSAttributedString( string:lastUpdate, attributes:attributesLastUpdated) let newLine:NSAttributedString = NSAttributedString( string:kNewLine) let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(stringGameName) mutableString.append(newLine) mutableString.append(stringLastUpdated) return mutableString } private class func factoryGameName( identifier:DVitaIdentifier) -> String? { guard let directories:[DVitaItemDirectory] = identifier.items?.array as? [ DVitaItemDirectory], let gameName:String = directories.last?.sfoTitle else { return nil } return gameName } private class func factoryLastUpdate( identifier:DVitaIdentifier, dateFormatter:DateFormatter) -> String? { guard let directories:[DVitaItemDirectory] = identifier.items?.array as? [ DVitaItemDirectory], let lastUpdate:TimeInterval = directories.last?.dateModified else { return nil } let date:Date = Date(timeIntervalSince1970:lastUpdate) let dateString:String = dateFormatter.string(from:date) return dateString } private class func factoryThumbnail( identifier:DVitaIdentifier) -> UIImage? { guard let directories:[DVitaItemDirectory] = identifier.items?.array as? [ DVitaItemDirectory], let lastDirectory:DVitaItemDirectory = directories.last else { return nil } let biggerPng:UIImage? = findBiggerPng( directory:lastDirectory) return biggerPng } private class func findBiggerPng( directory:DVitaItemDirectory) -> UIImage? { guard let allPng:[DVitaItemElement] = directory.png?.array as? [ DVitaItemElement] else { return nil } var biggerImage:UIImage? for png:DVitaItemElement in allPng { guard let image:UIImage = factoryImage( element:png) else { continue } guard let currentImage:UIImage = biggerImage else { biggerImage = image continue } let currentHeight:CGFloat = currentImage.size.height let newHeight:CGFloat = image.size.height if newHeight > currentHeight { biggerImage = image } } return biggerImage } private class func factoryImage( element:DVitaItemElement) -> UIImage? { guard let data:Data = MVitaLink.elementData( element:element), let image:UIImage = UIImage( data:data) else { return nil } return image } //MARK: internal class func factoryDateFormatter() -> DateFormatter { let dateFormatter:DateFormatter = DateFormatter() dateFormatter.timeStyle = DateFormatter.Style.short dateFormatter.dateStyle = DateFormatter.Style.short return dateFormatter } class func factoryAttributesGameName() -> [ NSAttributedStringKey:Any] { let attributes:[NSAttributedStringKey:Any] = [ NSAttributedStringKey.font: UIFont.regular(size:kFontGameName), NSAttributedStringKey.foregroundColor: UIColor.colourBackgroundDark] return attributes } class func factoryAttributesLastUpdated() -> [ NSAttributedStringKey:Any] { let attributes:[NSAttributedStringKey:Any] = [ NSAttributedStringKey.font: UIFont.regular(size:kFontLastUpdated), NSAttributedStringKey.foregroundColor: UIColor(white:0.5, alpha:1)] return attributes } class func factoryItem( identifier:DVitaIdentifier, dateFormatter:DateFormatter, attributesGameName:[NSAttributedStringKey:Any], attributesLastUpdated:[NSAttributedStringKey:Any]) -> MHomeSaveDataItem? { guard let shortDescr:NSAttributedString = factoryShortDescr( identifier:identifier, dateFormatter:dateFormatter, attributesGameName:attributesGameName, attributesLastUpdated:attributesLastUpdated) else { return nil } let thumbnail:UIImage? = factoryThumbnail( identifier:identifier) let item:MHomeSaveDataItem = MHomeSaveDataItem( coredataModel:identifier, shortDescr:shortDescr, thumbnail:thumbnail) return item } }
9efb045c29d3b9507fa6e4325d930ec8
26.219409
81
0.551697
false
false
false
false
Shashi717/ImmiGuide
refs/heads/master
ImmiGuide/ImmiGuide/Location.swift
mit
1
// // Location.swift // ImmiGuide // // Created by Cris on 2/18/17. // Copyright © 2017 Madushani Lekam Wasam Liyanage. All rights reserved. // import Foundation class Location { var borough: String var location: String var state: String var zip: String var geolocation: Geolocation var description: String { return "\(location) \(borough), \(state) \(zip)" } init?(borough: String , location: String, state: String, zip: String, geolocation: Geolocation) { self.borough = borough self.location = location self.state = state self.zip = zip self.geolocation = geolocation } convenience init?(dict: [String : Any]) { guard let location = dict["location_1_location"] as? String, let borough = dict["location_1_city"] as? String, let state = dict["location_1_state"] as? String, let zip = dict["location_1_zip"] as? String, let geo = dict["location_1"] as? [String : Any] else { return nil } guard let geolocation = Geolocation(geoDict: geo) else { return nil } self.init(borough: borough , location: location, state: state, zip: zip, geolocation: geolocation) } }
0222e6c5b6793069f12f1b8e97baea7b
29.853659
106
0.605534
false
false
false
false
lazerwalker/geofencer
refs/heads/master
GeoFencer/ViewController.swift
mit
1
import CoreLocation import MapKit import UIKit class ViewController: UIViewController, MKMapViewDelegate { let locationManager = CLLocationManager() // A Region object is generally immutable and needs to fully exist at creation time // Let's use raw MKPointAnnotation and MKPolygon objects to represent the currently-being-edited region var currentPoints:[MKPointAnnotation]? var currentPolygon:MKPolygon? let diskStore = DiskStore() var regions:[Region] = [] { didSet { for region in oldValue { region.overlays.forEach({ mapView.removeOverlay($0) }) region.annotations.forEach({ mapView.removeAnnotation($0) }) } for region in regions { region.overlays.forEach({ mapView.addOverlay($0) }) region.annotations.forEach({ mapView.addAnnotation($0) }) } shareButton.enabled = (regions.count > 0) resetButton.enabled = (regions.count > 0) diskStore.save(regions) } } @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var doneButton: UIBarButtonItem! @IBOutlet weak var shareButton: UIBarButtonItem! @IBOutlet weak var resetButton: UIBarButtonItem! @IBAction func didTapAddButton(sender: AnyObject) { if let coordinate = mapView.userLocation.location?.coordinate { addCoordinate(coordinate) } } @IBAction func didTapDoneButton(sender: AnyObject) { if let points = self.currentPoints { let alert = UIAlertController(title: "Name This Region", message: nil, preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler({ (field) in }) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) in self.dismissViewControllerAnimated(true, completion: nil) if let title = alert.textFields?.first?.text { let polygon = PolygonRegion(points: points, title: title) self.regions.append(polygon) self.resetCurrentRegion() } })) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) in self.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) } } @IBAction func didTapResetButton(sender: AnyObject) { let alert = UIAlertController(title: "Reset All Data", message: "Are you sure you'd like to erase all local regions?", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (action) in self.dismissViewControllerAnimated(true, completion: nil) self.regions = [] self.currentPoints = nil self.currentPolygon = nil })) alert.addAction(UIAlertAction(title: "No", style: .Cancel, handler: { (action) in self.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) } @IBAction func didTapShareButton(sender: AnyObject) { let json = regionsAsJSON(self.regions) let activityViewController = UIActivityViewController(activityItems: [json as NSString], applicationActivities: nil) presentViewController(activityViewController, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() locationManager.requestWhenInUseAuthorization() mapView.showsUserLocation = true mapView.setUserTrackingMode(.FollowWithHeading, animated: true) regions = diskStore.load() } //- func addCoordinate(coordinate:CLLocationCoordinate2D) { let point = MKPointAnnotation() point.coordinate = coordinate point.title = "Region Vertex" self.currentPoints = (self.currentPoints != nil) ? self.currentPoints : [] self.currentPoints!.append(point) self.mapView.addAnnotation(point) recalculatePolygon() recalculateDoneButton() } func resetCurrentRegion() { currentPoints?.forEach { self.mapView.removeAnnotation($0) } if let polygon = self.currentPolygon { self.mapView.removeAnnotation(polygon) self.mapView.removeOverlay(polygon) } self.currentPoints = [] self.currentPolygon = nil self.doneButton.enabled = false } func recalculatePolygon() { if let points = self.currentPoints { if let polygon = self.currentPolygon { mapView.removeOverlay(polygon) mapView.removeAnnotation(polygon) } self.currentPolygon = PolygonRegion.polygonFromPoints(points) if let polygon = self.currentPolygon { polygon.title = "Current Region" mapView.addOverlay(polygon) mapView.addAnnotation(polygon) } } } func recalculateDoneButton() { doneButton.enabled = (self.currentPoints?.count > 0) } //- // MKMapViewDelegate func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if annotation.isKindOfClass(MKPointAnnotation.self) || annotation.isKindOfClass(MKPolygon.self) { let identifier = NSStringFromClass(MKPinAnnotationView.self) var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView if (pinView == nil) { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) } if annotation.isKindOfClass(MKPointAnnotation.self) { pinView?.pinTintColor = MKPinAnnotationView.redPinColor() pinView?.canShowCallout = true let button = UIButton(type: .Custom) button.setTitleColor(UIColor.redColor(), forState: .Normal) button.tintColor = UIColor.redColor() button.setTitle("X", forState: .Normal) button.sizeToFit() pinView?.rightCalloutAccessoryView = button } else { pinView?.pinTintColor = MKPinAnnotationView.greenPinColor() pinView?.canShowCallout = true let button = UIButton(type: .Custom) if let title = annotation.title { if (title == "Current Region") { button.setTitleColor(UIColor.redColor(), forState: .Normal) button.tintColor = UIColor.redColor() button.setTitle("X", forState: .Normal) } else { button.setTitleColor(self.view.tintColor, forState: .Normal) button.setTitle("Edit", forState: .Normal) } } button.sizeToFit() pinView?.rightCalloutAccessoryView = button } return pinView } return nil } func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { if overlay.isKindOfClass(MKPolygon.self) { let renderer = MKPolygonRenderer(polygon: overlay as! MKPolygon) renderer.fillColor = UIColor.cyanColor().colorWithAlphaComponent(0.2) renderer.strokeColor = UIColor.blueColor().colorWithAlphaComponent(0.7) renderer.lineWidth = 0.5; return renderer } // This case should never be reached. In an ideal world, we'd be able to return nil. // Since this function expects a non-optional, returning a no-op object that does no actual rendering will have to suffice. return MKCircleRenderer() } func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if (view.annotation!.isKindOfClass(MKPointAnnotation.self)) { if let point = view.annotation as? MKPointAnnotation { self.mapView.removeAnnotation(point) self.currentPoints = self.currentPoints?.filter({ return !($0.coordinate.latitude == point.coordinate.latitude && $0.coordinate.longitude == point.coordinate.longitude) }) recalculatePolygon() } } else { if let polygon = view.annotation as? MKPolygon { if let index = self.regions.indexOf({ $0.annotations == [polygon] }) { let region = self.regions[index] self.regions.removeAtIndex(index) self.currentPoints?.forEach({ self.mapView.removeAnnotation($0) }) self.currentPoints = [] recalculatePolygon() region.points.forEach({ addCoordinate($0) }) self.title = region.title } else { self.resetCurrentRegion() } } } } }
cfcc35c796a15b865e616bdf7524e559
37.582645
150
0.607261
false
false
false
false
cezheng/Fuzi
refs/heads/master
Sources/Document.swift
mit
1
// Document.swift // Copyright (c) 2015 Ce Zheng // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import libxml2 /// XML document which can be searched and queried. open class XMLDocument { // MARK: - Document Attributes /// The XML version. open fileprivate(set) lazy var version: String? = { return ^-^self.cDocument.pointee.version }() /// The string encoding for the document. This is NSUTF8StringEncoding if no encoding is set, or it cannot be calculated. open fileprivate(set) lazy var encoding: String.Encoding = { if let encodingName = ^-^self.cDocument.pointee.encoding { let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString?) if encoding != kCFStringEncodingInvalidId { return String.Encoding(rawValue: UInt(CFStringConvertEncodingToNSStringEncoding(encoding))) } } return String.Encoding.utf8 }() // MARK: - Accessing the Root Element /// The root element of the document. open fileprivate(set) var root: XMLElement? // MARK: - Accessing & Setting Document Formatters /// The formatter used to determine `numberValue` for elements in the document. By default, this is an `NSNumberFormatter` instance with `NSNumberFormatterDecimalStyle`. open lazy var numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal return formatter }() /// The formatter used to determine `dateValue` for elements in the document. By default, this is an `NSDateFormatter` instance configured to accept ISO 8601 formatted timestamps. open lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter }() // MARK: - Creating XML Documents fileprivate let cDocument: xmlDocPtr /** Creates and returns an instance of XMLDocument from an XML string, throwing XMLError if an error occured while parsing the XML. - parameter string: The XML string. - parameter encoding: The string encoding. - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(string: String, encoding: String.Encoding = String.Encoding.utf8) throws { guard let cChars = string.cString(using: encoding) else { throw XMLError.invalidData } try self.init(cChars: cChars) } /** Creates and returns an instance of XMLDocument from XML data, throwing XMLError if an error occured while parsing the XML. - parameter data: The XML data. - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(data: Data) throws { let buffer = data.withUnsafeBytes { $0.bindMemory(to: Int8.self) } try self.init(buffer: buffer) } /** Creates and returns an instance of XMLDocument from C char array, throwing XMLError if an error occured while parsing the XML. - parameter cChars: cChars The XML data as C char array - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(cChars: [CChar]) throws { let buffer = cChars.withUnsafeBufferPointer { buffer in UnsafeBufferPointer(rebasing: buffer[0..<buffer.count]) } try self.init(buffer: buffer) } /** Creates and returns an instance of XMLDocument from C char buffer, throwing XMLError if an error occured while parsing the XML. - parameter buffer: The XML data as C char buffer - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(buffer: UnsafeBufferPointer<Int8>) throws { let options = Int32(XML_PARSE_NOWARNING.rawValue | XML_PARSE_NOERROR.rawValue | XML_PARSE_RECOVER.rawValue) try self.init(buffer: buffer, options: options) } fileprivate convenience init(buffer: UnsafeBufferPointer<Int8>, options: Int32) throws { guard let document = type(of: self).parse(buffer: buffer, options: options) else { throw XMLError.lastError(defaultError: .parserFailure) } xmlResetLastError() self.init(cDocument: document) } fileprivate class func parse(buffer: UnsafeBufferPointer<Int8>, options: Int32) -> xmlDocPtr? { return xmlReadMemory(buffer.baseAddress, Int32(buffer.count), "", nil, options) } fileprivate init(cDocument: xmlDocPtr) { self.cDocument = cDocument if let cRoot = xmlDocGetRootElement(cDocument) { root = XMLElement(cNode: cRoot, document: self) } } deinit { xmlFreeDoc(cDocument) } // MARK: - XML Namespaces var namespaces = [String: String]() // prefix -> URI /** Defines a new prefix for the given namespace in XPath expressions. - parameter prefix: The prefix name - parameter ns: The namespace URI declared in the XML Document */ open func definePrefix(_ prefix: String, forNamespace ns: String) { namespaces[prefix] = ns } /** Define a prefix for a default namespace. - parameter prefix: The prefix name - parameter ns: The default namespace URI that declared in XML Document */ @available(*, deprecated, renamed: "definePrefix(_:forNamespace:)", message: "This API will be removed in version 4.") open func definePrefix(_ prefix: String, defaultNamespace ns: String) { definePrefix(prefix, forNamespace: ns) } } extension XMLDocument: Equatable {} /** Determine whether two documents are the same - parameter lhs: XMLDocument on the left - parameter rhs: XMLDocument on the right - returns: whether lhs and rhs are equal */ public func ==(lhs: XMLDocument, rhs: XMLDocument) -> Bool { return lhs.cDocument == rhs.cDocument } /// HTML document which can be searched and queried. open class HTMLDocument: XMLDocument { // MARK: - Convenience Accessors /// HTML title of current document open var title: String? { return root?.firstChild(tag: "head")?.firstChild(tag: "title")?.stringValue } /// HTML head element of current document open var head: XMLElement? { return root?.firstChild(tag: "head") } /// HTML body element of current document open var body: XMLElement? { return root?.firstChild(tag: "body") } fileprivate override class func parse(buffer: UnsafeBufferPointer<Int8>, options: Int32) -> xmlDocPtr? { return htmlReadMemory(buffer.baseAddress, Int32(buffer.count), "", nil, options) } }
8e33b60d005448ec774715a33300a9c8
35.309859
181
0.718645
false
false
false
false
michael-lehew/swift-corelibs-foundation
refs/heads/master
Foundation/NSCache.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 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 // private class NSCacheEntry<KeyType : AnyObject, ObjectType : AnyObject> { var key: KeyType var value: ObjectType var cost: Int var prevByCost: NSCacheEntry? var nextByCost: NSCacheEntry? init(key: KeyType, value: ObjectType, cost: Int) { self.key = key self.value = value self.cost = cost } } open class NSCache<KeyType : AnyObject, ObjectType : AnyObject> : NSObject { private var _entries = Dictionary<UnsafeRawPointer, NSCacheEntry<KeyType, ObjectType>>() private let _lock = NSLock() private var _totalCost = 0 private var _byCost: NSCacheEntry<KeyType, ObjectType>? open var name: String = "" open var totalCostLimit: Int = -1 // limits are imprecise/not strict open var countLimit: Int = -1 // limits are imprecise/not strict open var evictsObjectsWithDiscardedContent: Bool = false public override init() {} open weak var delegate: NSCacheDelegate? open func object(forKey key: KeyType) -> ObjectType? { var object: ObjectType? let keyRef = unsafeBitCast(key, to: UnsafeRawPointer.self) _lock.lock() if let entry = _entries[keyRef] { object = entry.value } _lock.unlock() return object } open func setObject(_ obj: ObjectType, forKey key: KeyType) { setObject(obj, forKey: key, cost: 0) } private func remove(_ entry: NSCacheEntry<KeyType, ObjectType>) { let oldPrev = entry.prevByCost let oldNext = entry.nextByCost oldPrev?.nextByCost = oldNext oldNext?.prevByCost = oldPrev if entry === _byCost { _byCost = entry.nextByCost } } private func insert(_ entry: NSCacheEntry<KeyType, ObjectType>) { if _byCost == nil { _byCost = entry } else { var element = _byCost while let e = element { if e.cost > entry.cost { let newPrev = e.prevByCost entry.prevByCost = newPrev entry.nextByCost = e break } element = e.nextByCost } } } open func setObject(_ obj: ObjectType, forKey key: KeyType, cost g: Int) { let keyRef = unsafeBitCast(key, to: UnsafeRawPointer.self) _lock.lock() _totalCost += g var purgeAmount = 0 if totalCostLimit > 0 { purgeAmount = (_totalCost + g) - totalCostLimit } var purgeCount = 0 if countLimit > 0 { purgeCount = (_entries.count + 1) - countLimit } if let entry = _entries[keyRef] { entry.value = obj if entry.cost != g { entry.cost = g remove(entry) insert(entry) } } else { _entries[keyRef] = NSCacheEntry(key: key, value: obj, cost: g) } _lock.unlock() var toRemove = [NSCacheEntry<KeyType, ObjectType>]() if purgeAmount > 0 { _lock.lock() while _totalCost - totalCostLimit > 0 { if let entry = _byCost { _totalCost -= entry.cost toRemove.append(entry) remove(entry) } else { break } } if countLimit > 0 { purgeCount = (_entries.count - toRemove.count) - countLimit } _lock.unlock() } if purgeCount > 0 { _lock.lock() while (_entries.count - toRemove.count) - countLimit > 0 { if let entry = _byCost { _totalCost -= entry.cost toRemove.append(entry) remove(entry) } else { break } } _lock.unlock() } if let del = delegate { for entry in toRemove { del.cache(unsafeBitCast(self, to:NSCache<AnyObject, AnyObject>.self), willEvictObject: entry.value) } } _lock.lock() for entry in toRemove { _entries.removeValue(forKey: unsafeBitCast(entry.key, to: UnsafeRawPointer.self)) // the cost list is already fixed up in the purge routines } _lock.unlock() } open func removeObject(forKey key: AnyObject) { let keyRef = unsafeBitCast(key, to: UnsafeRawPointer.self) _lock.lock() if let entry = _entries.removeValue(forKey: keyRef) { _totalCost -= entry.cost remove(entry) } _lock.unlock() } open func removeAllObjects() { _lock.lock() _entries.removeAll() _byCost = nil _totalCost = 0 _lock.unlock() } } public protocol NSCacheDelegate : NSObjectProtocol { func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: AnyObject) } extension NSCacheDelegate { func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: AnyObject) { // Default implementation does nothing } }
159bc72599d490b4c8cf27c4cf8eff56
29.837838
152
0.536897
false
false
false
false
thebluepotato/AlamoFuzi
refs/heads/master
Pods/AlamoFuzi/Sources/AlamoFuzi.swift
mit
1
// // AlamoFuzi.swift // // Copyright (c) 2015-2016 Jonas Zaugg // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Alamofire import Fuzi // MARK: - Fuzi HTML public final class HTMLResponseSerializer: ResponseSerializer { public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> HTMLDocument { // Pass through any underlying URLSession error to the .network case. guard error == nil else { throw error! } // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has // already been handled. guard let data = data, !data.isEmpty else { guard emptyResponseAllowed(forRequest: request, response: response) else { throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) } return try HTMLDocument(string: "") } //do { return try HTMLDocument(data: data) /*} catch { throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) } return document*/ } } public final class XMLResponseSerializer: ResponseSerializer { public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> XMLDocument { // Pass through any underlying URLSession error to the .network case. guard error == nil else { throw error! } // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has // already been handled. guard let data = data, !data.isEmpty else { guard emptyResponseAllowed(forRequest: request, response: response) else { throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) } return try XMLDocument(string: "") } //do { return try XMLDocument(data: data) /*} catch { throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) } return document*/ } } extension DataRequest { /// Creates a response serializer that returns a result HTML document type initialized from the response data /// /// - returns: An HTML document response serializer /*static func htmlResponseSerializer() -> DataResponseSerializer<HTMLDocument> { return DataResponseSerializer { request, response, data, error in // Pass through any underlying URLSession error to the .network case. guard error == nil else { return .failure(AlamoFuziError.network(error: error!)) } // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has // already been handled. let result = Request.serializeResponseData(response: response, data: data, error: nil) guard case let .success(validData) = result else { return .failure(AlamoFuziError.dataSerialization(error: result.error! as! AFError)) } do { let html = try HTMLDocument(data: validData) return .success(html) } catch { return .failure(AlamoFuziError.htmlSerialization(error: error as! XMLError)) } } }*/ /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseHTML(queue: DispatchQueue = .main, completionHandler: @escaping (DataResponse<HTMLDocument>) -> Void) -> Self { return response(queue: queue, responseSerializer: HTMLResponseSerializer(), completionHandler: completionHandler) } } // MARK: - Fuzi XML extension DataRequest { /*// Creates a response serializer that returns a result XML document type initialized from the response data /// /// - returns: An XML document response serializer static func xmlResponseSerializer() -> DataResponseSerializer<Fuzi.XMLDocument> { return DataResponseSerializer { request, response, data, error in // Pass through any underlying URLSession error to the .network case. guard error == nil else { return .failure(AlamoFuziError.network(error: error!)) } // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has // already been handled. let result = Request.serializeResponseData(response: response, data: data, error: nil) guard case let .success(validData) = result else { return .failure(AlamoFuziError.dataSerialization(error: result.error! as! AFError)) } do { let xml = try XMLDocument(data: validData) return .success(xml) } catch { return .failure(AlamoFuziError.xmlSerialization(error: error as! XMLError)) } } }*/ /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseXML(queue: DispatchQueue = .main, completionHandler: @escaping (DataResponse<XMLDocument>) -> Void) -> Self { return response(queue: queue, responseSerializer: XMLResponseSerializer(), completionHandler: completionHandler) } } /// `AlamoFuziError` is the error type returned by AlamoFuzi. It encompasses a few different types of errors. /// /// - network: Captures any underlying Error from the URLSession API /// - dataSerialization: Captures any Error occuring during the serialization of the response Data /// - xmlSerialization: Captures any Error happening during the serialization of the response XML /// - htmlSerialization: Captures any Error happening during the serialization of the response HTML enum AlamoFuziError: Error { case network(error: Error) case dataSerialization(error: Error) case xmlSerialization(error: Error) case htmlSerialization(error: Error) }
2b0768fad42ff10b0a17b7df55738f37
42.350282
128
0.647986
false
false
false
false