repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
gerardogrisolini/Webretail
Sources/Webretail/Repositories/TagValueRepository.swift
1
1099
// // TagValueRepository.swift // Webretail // // Created by Gerardo Grisolini on 07/11/17. // import StORM struct TagValueRepository : TagValueProtocol { func getAll() throws -> [TagValue] { let items = TagValue() try items.query() return items.rows() } func get(id: Int) throws -> TagValue? { let item = TagValue() try item.query(id: id) return item } func add(item: TagValue) throws { item.tagValueCreated = Int.now() item.tagValueUpdated = Int.now() try item.save { id in item.tagValueId = id as! Int } } func update(id: Int, item: TagValue) throws { guard let current = try get(id: id) else { throw StORMError.noRecordFound } current.tagValueName = item.tagValueName current.tagValueUpdated = Int.now() try current.save() } func delete(id: Int) throws { let item = TagValue() item.tagValueId = id try item.delete() } }
apache-2.0
ff620c08d4ca57e87eff6fe5ff76cd5b
20.54902
50
0.540491
3.996364
false
false
false
false
agrippa1994/iOS-PLC
PLC/ViewControllers/MainTableViewController.swift
1
9216
// // MainTableViewController.swift // PLC // // Created by Manuel Stampfl on 03.09.15. // Copyright © 2015 mani1337. All rights reserved. // import UIKit class MainTableViewController: UITableViewController, ServerListTableViewControllerDelegate, EditDataTableViewControllerDelegate { var currentAlertController: UIAlertController? var client = S7Client() var currentServer: Server? var dynamicData = [DynamicData]() var staticData = [Data]() @IBAction func onAdd(sender: UIBarButtonItem) { // When we are not connected to any server... if self.currentServer == nil { self.addDataEntry(isStatic: true) } else { // Otherwise the user can add an address entry for the current server or for all servers (static) let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) alertController.addAction(UIAlertAction(title: "MAINTABLEVIEWCONTROLLER_ADD_STATIC".localized, style: .Default) { _ in self.addDataEntry(isStatic: true) }) alertController.addAction(UIAlertAction(title: "MAINTABLEVIEWCONTROLLER_ADD_DYNAMIC".localized, style: .Default) { _ in self.addDataEntry(isStatic: false) }) alertController.addAction(UIAlertAction(title: "MAINTABLEVIEWCONTROLLER_ADD_CANCEL".localized, style: .Cancel, handler: nil)) // Set the bar button item for the popover controller (neccessary for the iPad) alertController.popoverPresentationController?.barButtonItem = sender self.presentViewController(alertController, animated: true, completion: nil) } } @IBAction func onMore(sender: UIBarButtonItem) { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) alertController.addAction(UIAlertAction(title: "MAINTABLEVIEWCONTROLLER_MORE_STATISTIC".localized, style: .Default) { _ in }) alertController.addAction(UIAlertAction(title: "MAINTABLEVIEWCONTROLLER_ADD_CANCEL".localized, style: .Cancel, handler: nil)) // Set the bar button item for the popover controller (neccessary for the iPad) alertController.popoverPresentationController?.barButtonItem = sender self.presentViewController(alertController, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = self.editButtonItem() // Load everything from CoreData to this controller and display all values self.reloadData() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return ChameleonStatusBar.statusBarStyleForColor(self.navigationController!.navigationBar.barTintColor!) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? self.staticData.count : self.dynamicData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { let data = self.staticData[indexPath.row] guard let address = (try? data.address?.toS7Address()) else { return UITableViewCell() } if address?.length == .Bit { let cell = tableView.dequeueReusableCellWithIdentifier("BitCell", forIndexPath: indexPath) as! BitTableViewCell cell.nameLabel.text = data.name cell.addressLabel.text = data.address return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("ValueCell", forIndexPath: indexPath) as! ValueTableViewCell cell.nameLabel.text = data.name cell.addressLabel.text = data.address cell.valueLabel.text = "" return cell } } return UITableViewCell() } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return (section == 0 ? "MAINTABLEVIEWCONTROLLER_STATIC_HEADER_TITLE" : "MAINTABLEVIEWCONTROLLER_DYNAMIC_HEADER_TITLE").localized } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 45.0 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 75.0 } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ServerListNavigation" { if let ctrl = (segue.destinationViewController as? UINavigationController)?.topViewController as? ServerListTableViewController { ctrl.delegate = self } } if segue.identifier == "EditData" { if let ctrl = (segue.destinationViewController as? UINavigationController)?.topViewController as? EditDataTableViewController { ctrl.delegate = self ctrl.server = self.currentServer if let cell = sender as? UITableViewCell { if let indexPath = self.tableView.indexPathForCell(cell) { ctrl.data = indexPath.section == 0 ? self.staticData[indexPath.row] : self.dynamicData[indexPath.row] } } } } } func serverListTableViewControllerServerChosen(controller: ServerListTableViewController, server: Server) { controller.dismissViewControllerAnimated(true, completion: nil) self.currentAlertController = UIAlertController(title: "Info", message: "Baue Verbindung auf", preferredStyle: .Alert) self.presentViewController(self.currentAlertController!, animated: true) { self.client.connect(server.host!, rack: Int(server.rack), slot: Int(server.slot)) { state in dispatch_async(dispatch_get_main_queue()) { self.currentAlertController?.dismissViewControllerAnimated(true) { let texts = state == 0 ? ("ALERT_INFO_TITLE", "ALERT_INFO_CONNECTED_MESSAGE") : ("ALERT_ERROR_TITLE", "ALERT_ERROR_CONNECT_MESSAGE") self.currentAlertController = UIAlertController(title: texts.0.localized, message: texts.1.localized, preferredStyle: .Alert) self.currentAlertController!.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { action in self.currentAlertController!.dismissViewControllerAnimated(true, completion: nil) }) self.presentViewController(self.currentAlertController!, animated: true, completion: nil) } } } } } func serverListTableViewControllerCancelled(controller: ServerListTableViewController) { controller.dismissViewControllerAnimated(true, completion: nil) } func editDataTableViewControllerDidCancel(controller: EditDataTableViewController) { controller.dismissViewControllerAnimated(true, completion: nil) } func editDataTableViewControllerDidSave(controller: EditDataTableViewController) { controller.dismissViewControllerAnimated(true, completion: nil) self.reloadData() } func addDataEntry(isStatic isStatic: Bool) { self.performSegueWithIdentifier("EditData", sender: nil) } func reloadData() { self.dynamicData = CoreData.coreData.dynamicData.all() self.staticData = CoreData.coreData.staticData.all() self.tableView.reloadData() } }
mit
b667a814fe31a0d759a2ae441104151c
43.73301
157
0.64905
5.551205
false
false
false
false
ChristianKienle/Bold
Bold/Row.swift
1
3450
import Foundation /** Represents a row in a result set. You cann add support for custom types just by extending Row. For an example look at boolValue(columnName:) which is simply uses intValue(columnName:) internally. */ public struct Row { struct Item { let columnIndex: Int32 let columnName: String let value: Bindable? } /// MARK: Properties fileprivate let items: [Item] fileprivate let _valuesByColumnNames: [String: Bindable?] fileprivate let _valuesByColumnIndexes: [Int32: Bindable?] /// MARK: Creating Rows init(items: [Item]) { self.items = items var valuesByColumnNames = [String: Bindable?]() var valuesByColumnIndexes = [Int32: Bindable?]() self.items.forEach { (item) in valuesByColumnNames[item.columnName] = item.value valuesByColumnIndexes[item.columnIndex] = item.value } _valuesByColumnNames = valuesByColumnNames _valuesByColumnIndexes = valuesByColumnIndexes } public subscript(column: String) -> SQLValue { guard let value = _valuesByColumnNames[column] else { return SQLValue(nil) } return SQLValue(value) } public subscript(columnIndex columnIndex: Int32) -> SQLValue { guard let value = _valuesByColumnIndexes[columnIndex] else { return SQLValue(nil) } return SQLValue(value) } } // MARK: General extension Row { /** All column names of the row. */ public var allColumnNames:[String] { return self.items.map { $0.columnName } } } // MARK: Extracting Values extension Row { /** Used to get the string value at a specific column in the row. :param: columnName The name of the column you want to get the value of. :returns: The string stored in the specified column. */ public func stringValue(forColumn columnName:String) -> String? { return value(forColumn: columnName) } /** Used to get the int value at a specific column in the row. :param: columnName The name of the column you want to get the value of. :returns: The integer stored in the specified column. */ public func intValue(forColumn columnName:String) -> Int? { return value(forColumn: columnName) } /** Used to get the double value at a specific column in the row. :param: columnName The name of the column you want to get the value of. :returns: The double value stored in the specified column. */ public func doubleValue(forColumn columnName:String) -> Double? { return value(forColumn: columnName) } /** Used to get the data value at a specific column in the row. :param: columnName The name of the column you want to get the value of. :returns: The data stored in the specified column. */ public func dataValue(forColumn columnName:String) -> Data? { return value(forColumn: columnName) } fileprivate func value<T>(forColumn columnName:String) -> T? { return _valuesByColumnNames[columnName] as? T } } // MARK: Convenience extension Row { /** Used to get the bool value at a specific column in the row. :param: columnName The name of the column you want to get the value of. :returns: The boolean value stored in the specified column. */ public func boolValue(forColumn columnName:String) -> Bool? { guard let intValue = intValue(forColumn: columnName) else { return nil } switch intValue { case 0: return false case 1: return true default: return nil } } }
mit
c3de0a87a919243a161d0d1f36ba941d
29
196
0.694203
4.156627
false
false
false
false
steelwheels/KiwiControls
Source/Combination/KCDrawingView.swift
1
8689
/** * @file KCDrawingView.swift * @brief Define KCDrawingView class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ #if os(OSX) import Cocoa #else import UIKit #endif import CoconutData open class KCDrawingView: KCStackView { private var mMainToolsView: KCCollectionView? private var mSubToolsView: KCCollectionView? private var mStrokeColorView: KCColorSelector? private var mFillColorView: KCColorSelector? private var mVectorGraphicsView: KCVectorGraphics? #if os(OSX) public override init(frame : NSRect){ mMainToolsView = nil mSubToolsView = nil mStrokeColorView = nil mFillColorView = nil mVectorGraphicsView = nil super.init(frame: frame) ; setup() } #else public override init(frame: CGRect){ mMainToolsView = nil mSubToolsView = nil mStrokeColorView = nil mFillColorView = nil mVectorGraphicsView = nil super.init(frame: frame) setup() } #endif public convenience init(){ #if os(OSX) let frame = NSRect(x: 0.0, y: 0.0, width: 480, height: 270) #else let frame = CGRect(x: 0.0, y: 0.0, width: 375, height: 346) #endif self.init(frame: frame) } public required init?(coder: NSCoder) { mMainToolsView = nil mSubToolsView = nil mStrokeColorView = nil mFillColorView = nil mVectorGraphicsView = nil super.init(coder: coder) setup() } public var mainToolType: KCVectorToolType { get { if let view = mVectorGraphicsView { return view.toolType } else { CNLog(logLevel: .error, message: "No graphics view (get)", atFunction: #function, inFile: #file) return .path(false) } } set(newval) { if let view = mVectorGraphicsView { view.toolType = newval } else { CNLog(logLevel: .error, message: "No graphics view (set)", atFunction: #function, inFile: #file) } } } public var strokeColor: CNColor { get { if let view = mVectorGraphicsView { return view.strokeColor } else { return CNColor.clear } } set(newval) { if let view = mVectorGraphicsView { view.strokeColor = newval } } } public var fillColor: CNColor { get { if let view = mVectorGraphicsView { return view.fillColor } else { return CNColor.clear } } set(newval) { if let view = mVectorGraphicsView { view.fillColor = newval } } } private func setup(){ let initmaintools: Array<KCVectorToolType> = [ .mover, .string, .path(false), .path(true), .rect(false, false), .rect(true, false), .rect(false, true), .rect(true, true), .oval(false), .oval(true) ] /* Holizontal axis*/ self.axis = .horizontal /* Allocate tool box */ let toolbox = KCStackView() toolbox.axis = .vertical self.addArrangedSubView(subView: toolbox) /* Add main tool component */ let maintool = KCCollectionView() maintool.store(data: allocateMainToolImages(mainTools: initmaintools)) maintool.numberOfColumuns = 2 maintool.set(selectionCallback: { (_ section: Int, _ item: Int) -> Void in self.selectMainTool(item: item) }) toolbox.addArrangedSubView(subView: maintool) mMainToolsView = maintool /* Add sub tool component */ let subtool = KCCollectionView() subtool.store(data: allocateSubToolImages(toolType: initmaintools[0])) subtool.numberOfColumuns = 1 subtool.set(selectionCallback: { (_ section: Int, _ item: Int) -> Void in self.selectSubTool(item: item) }) toolbox.addArrangedSubView(subView: subtool) mSubToolsView = subtool /* Add color tool component */ let strokeview = KCColorSelector() strokeview.callbackFunc = { (_ color: CNColor) -> Void in self.strokeColor = color } mStrokeColorView = strokeview let fillview = KCColorSelector() fillview.callbackFunc = { (_ color: CNColor) -> Void in self.fillColor = color } mFillColorView = fillview let colorbox = KCStackView() colorbox.axis = .horizontal colorbox.addArrangedSubView(subView: strokeview) colorbox.addArrangedSubView(subView: fillview) toolbox.addArrangedSubView(subView: colorbox) /* Add drawing area */ let bezierview = KCVectorGraphics() self.addArrangedSubView(subView: bezierview) mVectorGraphicsView = bezierview /* assign initial tool */ self.mainToolType = initmaintools[0] /* assign default color */ strokeview.color = bezierview.strokeColor fillview.color = bezierview.fillColor } private func allocateMainToolImages(mainTools tools: Array<KCVectorToolType>) -> CNCollection { var images: Array<CNCollection.Item> = [] for tool in tools { let item: CNCollection.Item switch tool { case .mover: item = .image(CNSymbol.shared.URLOfSymbol(type: .handRaised)) case .path(let dofill): let symtype = CNSymbol.SymbolType.pencil(doFill: dofill) item = .image(CNSymbol.shared.URLOfSymbol(type: symtype)) case .rect(let dofill, let hasround): let symtype = CNSymbol.SymbolType.rect(doFill: dofill, doRound:hasround) item = .image(CNSymbol.shared.URLOfSymbol(type: symtype)) case .string: item = .image(CNSymbol.shared.URLOfSymbol(type: .characterA)) case .oval(let dofill): let symtype = CNSymbol.SymbolType.oval(doFill: dofill) item = .image(CNSymbol.shared.URLOfSymbol(type: symtype)) } images.append(item) } let cdata = CNCollection() cdata.add(header: "", footer: "", items: images) return cdata } private func selectMainTool(item itm: Int){ let newtype: KCVectorToolType switch itm { case 0: newtype = .mover case 1: newtype = .string case 2: newtype = .path(false) case 3: newtype = .path(true) case 4: newtype = .rect(false, false) case 5: newtype = .rect(true, false) case 6: newtype = .rect(false, true) case 7: newtype = .rect(true, true) case 8: newtype = .oval(false) case 9: newtype = .oval(true) default: CNLog(logLevel: .error, message: "Unexpected main tool item", atFunction: #function, inFile: #file) return } self.mainToolType = newtype } private func allocateSubToolImages(toolType tool: KCVectorToolType) -> CNCollection { let images: Array<CNCollection.Item> switch tool { case .mover, .path, .rect, .oval, .string: images = [ .image(CNSymbol.shared.URLOfSymbol(type: .line1P )), .image(CNSymbol.shared.URLOfSymbol(type: .line2P )), .image(CNSymbol.shared.URLOfSymbol(type: .line4P )), .image(CNSymbol.shared.URLOfSymbol(type: .line8P )), .image(CNSymbol.shared.URLOfSymbol(type: .line16P)) ] } let cdata = CNCollection() cdata.add(header: "", footer: "", items: images) return cdata } private func selectSubTool(item itm: Int){ switch self.mainToolType { case .mover, .path, .rect, .oval, .string: switch itm { case 0: bezierLineWidth = 1.0 // line1P case 1: bezierLineWidth = 2.0 // line2P case 2: bezierLineWidth = 4.0 // line4P case 3: bezierLineWidth = 8.0 // line8P case 4: bezierLineWidth = 16.0 // line16P default: CNLog(logLevel: .error, message: "Unexpected item: \(itm)", atFunction: #function, inFile: #file) } } } public var drawingWidth: CGFloat? { get { if let view = mVectorGraphicsView { return view.width } else { return nil } } set(newval){ if let view = mVectorGraphicsView { view.width = newval } else { CNLog(logLevel: .error, message: "No bezier view", atFunction: #function, inFile: #file) } } } public var drawingHeight: CGFloat? { get { if let view = mVectorGraphicsView { return view.height } else { return nil } } set(newval){ if let view = mVectorGraphicsView { view.height = newval } else { CNLog(logLevel: .error, message: "No bezier view", atFunction: #function, inFile: #file) } } } private var bezierLineWidth: CGFloat { get { if let bezier = mVectorGraphicsView { return bezier.lineWidth } else { CNLog(logLevel: .error, message: "No bezier view", atFunction: #function, inFile: #file) return 0.0 } } set(newval){ if let bezier = mVectorGraphicsView { bezier.lineWidth = newval } else { CNLog(logLevel: .error, message: "No bezier view", atFunction: #function, inFile: #file) } } } public var firstResponderView: KCViewBase? { get { return mVectorGraphicsView }} /* * load/store */ public func toValue() -> CNValue { if let view = mVectorGraphicsView { return view.toValue() } else { return CNValue.null } } public func load(from url: URL) -> Bool { if let view = mVectorGraphicsView { return view.load(from: url) } else { CNLog(logLevel: .error, message: "No vector graphics view", atFunction: #function, inFile: #file) return false } } }
lgpl-2.1
aa1a96e224b47d3be580ea2adebc74bc
24.258721
102
0.678099
3.041302
false
false
false
false
i-schuetz/SwiftCharts
Examples/Examples/GroupedBarsExample.swift
1
9130
// // GroupedBarsExample.swift // Examples // // Created by ischuetz on 19/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class GroupedBarsExample: UIViewController { fileprivate var chart: Chart? fileprivate let dirSelectorHeight: CGFloat = 50 fileprivate func barsChart(horizontal: Bool) -> Chart { let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let groupsData: [(title: String, [(min: Double, max: Double)])] = [ ("A", [ (0, 40), (0, 50), (0, 35) ]), ("B", [ (0, 20), (0, 30), (0, 25) ]), ("C", [ (0, 30), (0, 50), (0, 5) ]), ("D", [ (0, 55), (0, 30), (0, 25) ]) ] let groupColors = [UIColor.red.withAlphaComponent(0.6), UIColor.blue.withAlphaComponent(0.6), UIColor.green.withAlphaComponent(0.6)] let groups: [ChartPointsBarGroup] = groupsData.enumerated().map {index, entry in let constant = ChartAxisValueDouble(index) let bars = entry.1.enumerated().map {index, tuple in ChartBarModel(constant: constant, axisValue1: ChartAxisValueDouble(tuple.min), axisValue2: ChartAxisValueDouble(tuple.max), bgColor: groupColors[index]) } return ChartPointsBarGroup(constant: constant, bars: bars) } let (axisValues1, axisValues2): ([ChartAxisValue], [ChartAxisValue]) = ( stride(from: 0, through: 60, by: 5).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)}, [ChartAxisValueString(order: -1)] + groupsData.enumerated().map {index, tuple in ChartAxisValueString(tuple.0, order: index, labelSettings: labelSettings)} + [ChartAxisValueString(order: groupsData.count)] ) let (xValues, yValues) = horizontal ? (axisValues1, axisValues2) : (axisValues2, axisValues1) let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let frame = ExamplesDefaults.chartFrame(view.bounds) let chartFrame = chart?.frame ?? CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: frame.size.height - dirSelectorHeight) let chartSettings = ExamplesDefaults.chartSettingsWithPanZoom let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame) let barViewSettings = ChartBarViewSettings(animDuration: 0.5, selectionViewUpdater: ChartViewSelectorBrightness(selectedFactor: 0.5)) let groupsLayer = ChartGroupedPlainBarsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, groups: groups, horizontal: horizontal, barSpacing: 2, groupSpacing: 25, settings: barViewSettings, tapHandler: { tappedGroupBar /*ChartTappedGroupBar*/ in let barPoint = horizontal ? CGPoint(x: tappedGroupBar.tappedBar.view.frame.maxX, y: tappedGroupBar.tappedBar.view.frame.midY) : CGPoint(x: tappedGroupBar.tappedBar.view.frame.midX, y: tappedGroupBar.tappedBar.view.frame.minY) guard let chart = self.chart, let chartViewPoint = tappedGroupBar.layer.contentToGlobalCoordinates(barPoint) else {return} let viewPoint = CGPoint(x: chartViewPoint.x, y: chartViewPoint.y) let infoBubble = InfoBubble(point: viewPoint, preferredSize: CGSize(width: 50, height: 40), superview: self.chart!.view, text: tappedGroupBar.tappedBar.model.axisValue2.description, font: ExamplesDefaults.labelFont, textColor: UIColor.white, bgColor: UIColor.black, horizontal: horizontal) let anchor: CGPoint = { switch (horizontal, infoBubble.inverted(chart.view)) { case (true, true): return CGPoint(x: 1, y: 0.5) case (true, false): return CGPoint(x: 0, y: 0.5) case (false, true): return CGPoint(x: 0.5, y: 0) case (false, false): return CGPoint(x: 0.5, y: 1) } }() let animatorsSettings = ChartViewAnimatorsSettings(animInitSpringVelocity: 5) let animators = ChartViewAnimators(view: infoBubble, animators: ChartViewGrowAnimator(anchor: anchor), settings: animatorsSettings, invertSettings: animatorsSettings.withoutDamping(), onFinishInverts: { infoBubble.removeFromSuperview() }) chart.view.addSubview(infoBubble) infoBubble.tapHandler = { animators.invert() } animators.animate() }) let guidelinesSettings = ChartGuideLinesLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesLayer(xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, axis: horizontal ? .x : .y, settings: guidelinesSettings) return Chart( frame: chartFrame, innerFrame: innerFrame, settings: chartSettings, layers: [ xAxisLayer, yAxisLayer, guidelinesLayer, groupsLayer ] ) } fileprivate func showChart(horizontal: Bool) { self.chart?.clearView() let chart = barsChart(horizontal: horizontal) view.addSubview(chart.view) self.chart = chart } override func viewDidLoad() { showChart(horizontal: false) if let chart = chart { let dirSelector = DirSelector(frame: CGRect(x: 0, y: chart.frame.origin.y + chart.frame.size.height, width: view.frame.size.width, height: dirSelectorHeight), controller: self) view.addSubview(dirSelector) } } class DirSelector: UIView { let horizontal: UIButton let vertical: UIButton weak var controller: GroupedBarsExample? fileprivate let buttonDirs: [UIButton : Bool] init(frame: CGRect, controller: GroupedBarsExample) { self.controller = controller horizontal = UIButton() horizontal.setTitle("Horizontal", for: UIControl.State()) vertical = UIButton() vertical.setTitle("Vertical", for: UIControl.State()) buttonDirs = [horizontal : true, vertical : false] super.init(frame: frame) addSubview(horizontal) addSubview(vertical) for button in [horizontal, vertical] { button.titleLabel?.font = ExamplesDefaults.fontWithSize(14) button.setTitleColor(UIColor.blue, for: UIControl.State()) button.addTarget(self, action: #selector(DirSelector.buttonTapped(_:)), for: .touchUpInside) } } @objc func buttonTapped(_ sender: UIButton) { let horizontal = sender == self.horizontal ? true : false controller?.showChart(horizontal: horizontal) } override func didMoveToSuperview() { let views = [horizontal, vertical] for v in views { v.translatesAutoresizingMaskIntoConstraints = false } let namedViews = views.enumerated().map{index, view in ("v\(index)", view) } var viewsDict = Dictionary<String, UIView>() for namedView in namedViews { viewsDict[namedView.0] = namedView.1 } let buttonsSpace: CGFloat = Env.iPad ? 20 : 10 let hConstraintStr = namedViews.reduce("H:|") {str, tuple in "\(str)-(\(buttonsSpace))-[\(tuple.0)]" } let vConstraits = namedViews.flatMap {NSLayoutConstraint.constraints(withVisualFormat: "V:|[\($0.0)]", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: viewsDict)} addConstraints(NSLayoutConstraint.constraints(withVisualFormat: hConstraintStr, options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: viewsDict) + vConstraits) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } }
apache-2.0
0a9248360fecd343018a8603945fd903
42.894231
301
0.593319
5.058172
false
false
false
false
loudnate/LoopKit
MockKitUI/Views/BoundSwitchTableViewCell.swift
2
1131
// // BoundSwitchTableViewCell.swift // MockKitUI // // Copyright © 2019 LoopKit Authors. All rights reserved. // import LoopKitUI class BoundSwitchTableViewCell: SwitchTableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none } required init?(coder: NSCoder) { super.init(coder: coder) } var onToggle: ((_ isOn: Bool) -> Void)? { didSet { if onToggle == nil { self.switch?.removeTarget(nil, action: nil, for: .valueChanged) } else { `switch`?.addTarget(self, action: #selector(respondToToggle), for: .valueChanged) } } } override func prepareForReuse() { super.prepareForReuse() onToggle = nil `switch`?.addTarget(self, action: #selector(respondToToggle), for: .valueChanged) } @objc private func respondToToggle() { if let `switch` = `switch`, let onToggle = onToggle { onToggle(`switch`.isOn) } } }
mit
bbc6427d20e439623455f00a72817969
24.681818
97
0.60177
4.466403
false
false
false
false
weby/Stencil
Sources/Namespace.swift
1
1474
public class Namespace { public typealias TagParser = (TokenParser, Token) throws -> NodeType var tags = [String: TagParser]() var filters = [String: Filter]() public init() { registerDefaultTags() registerDefaultFilters() } private func registerDefaultTags() { registerTag(name: "for", parser: ForNode.parse) registerTag(name: "if", parser: IfNode.parse) registerTag(name: "ifnot", parser: IfNode.parse_ifnot) #if !os(Linux) registerTag(name: "now", parser: NowNode.parse) #endif registerTag(name: "include", parser: IncludeNode.parse) registerTag(name: "extends", parser: ExtendsNode.parse) registerTag(name: "block", parser: BlockNode.parse) } private func registerDefaultFilters() { registerFilter(name: "capitalize", filter: capitalise) registerFilter(name: "uppercase", filter: uppercase) registerFilter(name: "lowercase", filter: lowercase) } /// Registers a new template tag public func registerTag(name: String, parser: TagParser) { tags[name] = parser } /// Registers a simple template tag with a name and a handler public func registerSimpleTag(name: String, handler: Context throws -> String) { registerTag(name: name, parser: { parser, token in return SimpleNode(handler: handler) }) } /// Registers a template filter with the given name public func registerFilter(name: String, filter: Filter) { filters[name] = filter } }
bsd-2-clause
a004d7d6303d5422c2aafed3af48218e
31.043478
82
0.688602
3.983784
false
false
false
false
tsolomko/SWCompression
Tests/TarCreateTests.swift
1
14699
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import XCTest import SWCompression class TarCreateTests: XCTestCase { func test1() throws { var info = TarEntryInfo(name: "file.txt", type: .regular) info.ownerUserName = "timofeysolomko" info.ownerGroupName = "staff" info.ownerID = 501 info.groupID = 20 info.permissions = Permissions(rawValue: 420) // We have to convert time interval to int, since tar can't store fractional timestamps, so we lose in accuracy. let intTimeInterval = Int(Date().timeIntervalSince1970) let date = Date(timeIntervalSince1970: Double(intTimeInterval)) info.modificationTime = date info.creationTime = date info.accessTime = date info.comment = "comment" let data = Data("Hello, World!\n".utf8) let entry = TarEntry(info: info, data: data) let containerData = TarContainer.create(from: [entry]) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .pax) let newEntries = try TarContainer.open(container: containerData) XCTAssertEqual(newEntries.count, 1) XCTAssertEqual(newEntries[0].info.name, "file.txt") XCTAssertEqual(newEntries[0].info.type, .regular) XCTAssertEqual(newEntries[0].info.size, 14) XCTAssertEqual(newEntries[0].info.ownerUserName, "timofeysolomko") XCTAssertEqual(newEntries[0].info.ownerGroupName, "staff") XCTAssertEqual(newEntries[0].info.ownerID, 501) XCTAssertEqual(newEntries[0].info.groupID, 20) XCTAssertEqual(newEntries[0].info.permissions, Permissions(rawValue: 420)) XCTAssertEqual(newEntries[0].info.modificationTime, date) XCTAssertEqual(newEntries[0].info.creationTime, date) XCTAssertEqual(newEntries[0].info.accessTime, date) XCTAssertEqual(newEntries[0].info.comment, "comment") XCTAssertEqual(newEntries[0].data, data) } func test2() throws { let dict = [ "SWCompression/Tests/TAR": "value", "key": "valuevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevalue22" ] var info = TarEntryInfo(name: "symbolic-link", type: .symbolicLink) info.accessTime = Date(timeIntervalSince1970: 1) info.creationTime = Date(timeIntervalSince1970: 2) info.modificationTime = Date(timeIntervalSince1970: 0) info.permissions = Permissions(rawValue: 420) info.permissions?.insert(.executeOwner) info.ownerID = 250 info.groupID = 250 info.ownerUserName = "testUserName" info.ownerGroupName = "testGroupName" info.deviceMajorNumber = 1 info.deviceMinorNumber = 2 info.charset = "UTF-8" info.comment = "some comment..." info.linkName = "file" info.unknownExtendedHeaderRecords = dict let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())]) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .pax) let newInfo = try TarContainer.open(container: containerData)[0].info XCTAssertEqual(newInfo.name, "symbolic-link") XCTAssertEqual(newInfo.type, .symbolicLink) XCTAssertEqual(newInfo.permissions?.rawValue, 484) XCTAssertEqual(newInfo.ownerID, 250) XCTAssertEqual(newInfo.groupID, 250) XCTAssertEqual(newInfo.size, 0) XCTAssertEqual(newInfo.modificationTime?.timeIntervalSince1970, 0) XCTAssertEqual(newInfo.linkName, "file") XCTAssertEqual(newInfo.ownerUserName, "testUserName") XCTAssertEqual(newInfo.ownerGroupName, "testGroupName") XCTAssertEqual(newInfo.deviceMajorNumber, 1) XCTAssertEqual(newInfo.deviceMinorNumber, 2) XCTAssertEqual(newInfo.accessTime?.timeIntervalSince1970, 1) XCTAssertEqual(newInfo.creationTime?.timeIntervalSince1970, 2) XCTAssertEqual(newInfo.charset, "UTF-8") XCTAssertEqual(newInfo.comment, "some comment...") XCTAssertEqual(newInfo.unknownExtendedHeaderRecords, dict) } func testLongName() throws { var info = TarEntryInfo(name: "", type: .regular) info.name = "path/to/" info.name.append(String(repeating: "readme/", count: 15)) info.name.append("readme.txt") let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())]) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .pax) let newInfo = try TarContainer.open(container: containerData)[0].info // This name should fit into ustar format using "prefix" field XCTAssertEqual(newInfo.name, info.name) } func testVeryLongName() throws { var info = TarEntryInfo(name: "", type: .regular) info.name = "path/to/" info.name.append(String(repeating: "readme/", count: 25)) info.name.append("readme.txt") let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())]) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .pax) let newInfo = try TarContainer.open(container: containerData)[0].info XCTAssertEqual(newInfo.name, info.name) } func testLongDirectoryName() throws { // Tests what happens to the filename's trailing slash when "prefix" field is used. var info = TarEntryInfo(name: "", type: .regular) info.name = "path/to/" info.name.append(String(repeating: "readme/", count: 15)) let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())]) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .pax) let newInfo = try TarContainer.open(container: containerData)[0].info XCTAssertEqual(newInfo.name, info.name) } func testUnicode() throws { let date = Date(timeIntervalSince1970: 1300000) var info = TarEntryInfo(name: "ссылка", type: .symbolicLink) info.accessTime = date info.creationTime = date info.modificationTime = date info.permissions = Permissions(rawValue: 420) info.ownerID = 501 info.groupID = 20 info.ownerUserName = "timofeysolomko" info.ownerGroupName = "staff" info.deviceMajorNumber = 1 info.deviceMinorNumber = 2 info.comment = "комментарий" info.linkName = "путь/к/файлу" let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())]) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .pax) let newInfo = try TarContainer.open(container: containerData)[0].info XCTAssertEqual(newInfo.name, "ссылка") XCTAssertEqual(newInfo.type, .symbolicLink) XCTAssertEqual(newInfo.permissions?.rawValue, 420) XCTAssertEqual(newInfo.ownerID, 501) XCTAssertEqual(newInfo.groupID, 20) XCTAssertEqual(newInfo.size, 0) XCTAssertEqual(newInfo.modificationTime?.timeIntervalSince1970, 1300000) XCTAssertEqual(newInfo.linkName, "путь/к/файлу") XCTAssertEqual(newInfo.ownerUserName, "timofeysolomko") XCTAssertEqual(newInfo.ownerGroupName, "staff") XCTAssertEqual(newInfo.accessTime?.timeIntervalSince1970, 1300000) XCTAssertEqual(newInfo.creationTime?.timeIntervalSince1970, 1300000) XCTAssertEqual(newInfo.comment, "комментарий") } func testUstar() throws { // This set of settings should result in the container which uses only ustar TAR format features. let date = Date(timeIntervalSince1970: 1300000) var info = TarEntryInfo(name: "file.txt", type: .regular) info.permissions = Permissions(rawValue: 420) info.ownerID = 501 info.groupID = 20 info.modificationTime = date let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())], force: .ustar) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .ustar) let newInfo = try TarContainer.open(container: containerData)[0].info XCTAssertEqual(newInfo.name, "file.txt") XCTAssertEqual(newInfo.type, .regular) XCTAssertEqual(newInfo.permissions?.rawValue, 420) XCTAssertEqual(newInfo.ownerID, 501) XCTAssertEqual(newInfo.groupID, 20) XCTAssertEqual(newInfo.size, 0) XCTAssertEqual(newInfo.modificationTime?.timeIntervalSince1970, 1300000) XCTAssertEqual(newInfo.linkName, "") XCTAssertEqual(newInfo.ownerUserName, "") XCTAssertEqual(newInfo.ownerGroupName, "") XCTAssertNil(newInfo.accessTime) XCTAssertNil(newInfo.creationTime) XCTAssertNil(newInfo.comment) } func testNegativeMtime() throws { let date = Date(timeIntervalSince1970: -1300000) var info = TarEntryInfo(name: "file.txt", type: .regular) info.modificationTime = date let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())]) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .pax) let newInfo = try TarContainer.open(container: containerData)[0].info XCTAssertEqual(newInfo.name, "file.txt") XCTAssertEqual(newInfo.type, .regular) XCTAssertEqual(newInfo.size, 0) XCTAssertEqual(newInfo.modificationTime?.timeIntervalSince1970, -1300000) XCTAssertEqual(newInfo.linkName, "") XCTAssertEqual(newInfo.ownerUserName, "") XCTAssertEqual(newInfo.ownerGroupName, "") XCTAssertNil(newInfo.permissions) XCTAssertNil(newInfo.ownerID) XCTAssertNil(newInfo.groupID) XCTAssertNil(newInfo.accessTime) XCTAssertNil(newInfo.creationTime) XCTAssertNil(newInfo.comment) } func testBigUid() throws { // Int.max tests that base-256 encoding of integer fields works in the edge case. for uid in [(1 << 32) - 1, Int.max] { var info = TarEntryInfo(name: "file.txt", type: .regular) info.ownerID = uid let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())]) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .pax) let newInfo = try TarContainer.open(container: containerData)[0].info XCTAssertEqual(newInfo.name, "file.txt") XCTAssertEqual(newInfo.type, .regular) XCTAssertEqual(newInfo.size, 0) XCTAssertEqual(newInfo.ownerID, uid) XCTAssertEqual(newInfo.linkName, "") XCTAssertEqual(newInfo.ownerUserName, "") XCTAssertEqual(newInfo.ownerGroupName, "") XCTAssertNil(newInfo.permissions) XCTAssertNil(newInfo.groupID) XCTAssertNil(newInfo.accessTime) XCTAssertNil(newInfo.creationTime) XCTAssertNil(newInfo.modificationTime) XCTAssertNil(newInfo.comment) } } func testGnuLongName() throws { var info = TarEntryInfo(name: "", type: .regular) info.name = "path/to/" info.name.append(String(repeating: "name/", count: 25)) info.name.append("name.txt") let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())], force: .gnu) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .gnu) let newInfo = try TarContainer.open(container: containerData)[0].info XCTAssertEqual(newInfo.name, info.name) } func testGnuLongLinkName() throws { var info = TarEntryInfo(name: "", type: .symbolicLink) info.name = "link" info.linkName = "path/to/" info.linkName.append(String(repeating: "name/", count: 25)) info.linkName.append("name.txt") let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())], force: .gnu) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .gnu) let newInfo = try TarContainer.open(container: containerData)[0].info XCTAssertEqual(newInfo.name, info.name) } func testGnuBothLongNames() throws { var info = TarEntryInfo(name: "", type: .symbolicLink) info.name = "path/to/" info.name.append(String(repeating: "name/", count: 25)) info.name.append("name.txt") info.linkName = "path/to/" info.linkName.append(String(repeating: "link/", count: 25)) info.linkName.append("link.txt") let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())], force: .gnu) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .gnu) let newInfo = try TarContainer.open(container: containerData)[0].info XCTAssertEqual(newInfo.name, info.name) } func testGnuTimes() throws { var info = TarEntryInfo(name: "dir", type: .directory) info.ownerUserName = "tsolomko" info.ownerGroupName = "staff" info.ownerID = 501 info.groupID = 20 info.permissions = Permissions(rawValue: 420) // We have to convert time interval to int, since tar can't store fractional timestamps, so we lose in accuracy. let intTimeInterval = Int(Date().timeIntervalSince1970) let date = Date(timeIntervalSince1970: Double(intTimeInterval)) info.modificationTime = date info.creationTime = date info.accessTime = date let containerData = TarContainer.create(from: [TarEntry(info: info, data: Data())], force: .gnu) XCTAssertEqual(try TarContainer.formatOf(container: containerData), .gnu) let newEntries = try TarContainer.open(container: containerData) XCTAssertEqual(newEntries.count, 1) XCTAssertEqual(newEntries[0].info.name, "dir") XCTAssertEqual(newEntries[0].info.type, .directory) XCTAssertEqual(newEntries[0].info.size, 0) XCTAssertEqual(newEntries[0].info.ownerUserName, "tsolomko") XCTAssertEqual(newEntries[0].info.ownerGroupName, "staff") XCTAssertEqual(newEntries[0].info.ownerID, 501) XCTAssertEqual(newEntries[0].info.groupID, 20) XCTAssertEqual(newEntries[0].info.permissions, Permissions(rawValue: 420)) XCTAssertEqual(newEntries[0].info.modificationTime, date) XCTAssertEqual(newEntries[0].info.creationTime, date) XCTAssertEqual(newEntries[0].info.accessTime, date) XCTAssertNil(newEntries[0].info.comment) } }
mit
b1c203960f016b4acdfab2e185794132
44.340557
120
0.673131
4.290946
false
true
false
false
BananosTeam/CreativeLab
Assistant/View/SideMenu/ENSideMenuNavigationController.swift
2
1699
// // RootNavigationViewController.swift // SwiftSideMenu // // Created by Evgeny Nazarov on 29.09.14. // Copyright (c) 2014 Evgeny Nazarov. All rights reserved. // import UIKit public class ENSideMenuNavigationController: UINavigationController, ENSideMenuProtocol { public var sideMenu : ENSideMenu? public var sideMenuAnimationType : ENSideMenuAnimation = .Default // MARK: - Life cycle public override func viewDidLoad() { super.viewDidLoad() } public init( menuViewController: UIViewController, contentViewController: UIViewController?) { super.init(nibName: nil, bundle: nil) if (contentViewController != nil) { self.viewControllers = [contentViewController!] } sideMenu = ENSideMenu(sourceView: self.view, menuViewController: menuViewController, menuPosition:.Left) view.bringSubviewToFront(navigationBar) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation public func setContentViewController(contentViewController: UIViewController) { self.sideMenu?.hideSideMenu() switch sideMenuAnimationType { case .None: self.viewControllers = [contentViewController] break default: contentViewController.navigationItem.hidesBackButton = true self.setViewControllers([contentViewController], animated: true) break } } }
mit
504f094ded9ffb792ed16cad6df96e30
28.807018
112
0.665097
5.682274
false
false
false
false
twostraws/SwiftGD
Tests/SwiftGDTests/SwiftGDTests.swift
1
1135
import XCTest @testable import SwiftGD class SwiftGDTests: XCTestCase { func testReduceColors() { let size = 16 let imColor = Color.init(red: 0.2, green: 0.10, blue: 0.77, alpha: 1.0) let image = Image(width: size, height: size) image!.fillRectangle(topLeft: Point.zero, bottomRight: Point(x: size, y: size), color: imColor) try! image?.reduceColors(max: 4, shouldDither: false) XCTAssert(image != nil, "ReduceColors without dithering should not destroy Image instance") try! image?.reduceColors(max: 2, shouldDither: true) XCTAssert(image != nil, "ReduceColors while dithering should not destroy Image instance") for ii in -1...1 { XCTAssertThrowsError(try image?.reduceColors(max: ii), "`Image` should throw with insane maxColor values when making indexed `Image`s") } } static var allTests: [(String, (SwiftGDTests) -> () throws -> Void)] { return [ ("testReduceColors", testReduceColors) ] } }
mit
cfe5d4a40ebc14f4fe9d9fad8a3e99c8
41.037037
147
0.586784
4.283019
false
true
false
false
Jaspion/Kilza
spec/res/swift/hash/Underscore.swift
1
2639
// // Underscore.swift // // Created on <%= Time.now.strftime("%Y-%m-%d") %> // Copyright (c) <%= Time.now.strftime("%Y") %>. All rights reserved. // Generated by Kilza https://github.com/Jaspion/Kilza // import Foundation public class Underscore: NSObject, NSCoding { // Original names static let kUnderscore_: String = "_" public var _: String? public class func model(obj: AnyObject) -> Underscore? { var instance: Underscore? if (obj is String) { instance = Underscore.init(str: obj as! String) } else if (obj is Dictionary<String, AnyObject>) { instance = Underscore.init(dict: obj as! Dictionary) } return instance } public convenience init?(str: String) { var nStr: String = str if let trimmed: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) { if !trimmed.hasPrefix("{") { nStr = "{ \"\(Underscore.kUnderscore_)\" : \(str) }" } } if let data = nStr.dataUsingEncoding(NSUTF8StringEncoding) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) self.init(dict: object as! Dictionary) } catch _ as NSError { self.init(dict: Dictionary()) } } else { self.init(dict: Dictionary()) } } public init?(dict: Dictionary<String, AnyObject>) { super.init() self._ = objectOrNil(forKey: Underscore.kUnderscore_, fromDictionary:dict) as? String } public func dictionaryRepresentation() -> Dictionary<String, AnyObject> { var mutableDict: Dictionary = [String: AnyObject]() mutableDict[Underscore.kUnderscore_] = self._ return NSDictionary.init(dictionary: mutableDict) as! Dictionary<String, AnyObject> } public func objectOrNil(forKey key: String, fromDictionary dict: Dictionary<String, AnyObject>) -> AnyObject? { if let object: AnyObject = dict[key] { if !(object is NSNull) { return object } } return nil } required public init(coder aDecoder: NSCoder) { self._ = aDecoder.decodeObjectForKey(Underscore.kUnderscore_)! as? String } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(_, forKey:Underscore.kUnderscore_) } override public var description: String { get { return "\(dictionaryRepresentation())" } } }
mit
253fe1e445ab7e0322bccb544f7244e8
31.580247
134
0.603638
4.646127
false
false
false
false
DarlingXIe/WeiBoProject
WeiBo/WeiBo/Classes/View/compose/view/XDLComposePictureView.swift
1
6769
// // XDLComposePictureView.swift // WeiBo // // Created by DalinXie on 16/10/3. // Copyright © 2016年 itcast. All rights reserved. // import UIKit import SVProgressHUD //MARK: - 1.register cells' Id private let XDLComposePictureViewCellId = "ComposePictureViewCellId" class XDLComposePictureView: UICollectionView { var addImageClosure: (() -> ())? internal lazy var images :[UIImage] = [UIImage]() override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout){ super.init(frame: frame, collectionViewLayout: layout) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ self.register(XDLComposePictureViewCell.self, forCellWithReuseIdentifier: XDLComposePictureViewCellId) self.dataSource = self self.delegate = self } func addImage(image: UIImage){ if images.count < 9 { images.append(image) reloadData() }else{ SVProgressHUD.showError(withStatus: "beyond") } } //MARK: - 2. setup size of item for collectionView override func layoutSubviews() { super.layoutSubviews() let itemMargin: CGFloat = 5 let itemWH = (self.frame.width - 2 * itemMargin) / 3 let layout = self.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = CGSize(width: itemWH, height: itemWH) layout.minimumLineSpacing = itemMargin layout.minimumInteritemSpacing = itemMargin } } //MARK: - 3.Load Image Data to cell.image //extension XDLComposePictureView: UICollectionViewDelegate{ // // //MARK: - recall the funcation about didSelectItem to know that if the cell is last one, it should be addButton // func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // print("click:") // if indexPath.item == images.count{ // addImageClosure?() // } // } // // override func numberOfItems(inSection section: Int) -> Int { // // return (images.count == 0 || images.count == 9) ? images.count : images.count + 1 // } // // // func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // // let cell = collectionView.dequeueReusableCell(withReuseIdentifier: XDLComposePictureViewCellId, for: indexPath) as! XDLComposePictureViewCell // // if indexPath.item < images.count{ // // cell.image = images[indexPath.item] // // }else{ // // cell.image = nil // } // // cell.deleteClickClosure = {[weak self] in // // self?.images.remove(at: indexPath.item) // self?.reloadData() // } // // return cell // } // //} extension XDLComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("点击") collectionView.deselectItem(at: indexPath, animated: true) // 要在这个地方判断是否是最后一个cell点击 if indexPath.item == images.count { // 代表是最后一个cell代表是加号按钮 // 要在这个地方通知外界去弹出控制器 addImageClosure?() } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 如果count为0或者为9的话,都不显示+按钮,否则要显示,要显示的话就多返回一个cell return (images.count == 0 || images.count == 9) ? images.count : images.count + 1 // return images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: XDLComposePictureViewCellId, for: indexPath) as! XDLComposePictureViewCell if indexPath.item < images.count { // 给cell设置数据 let image = images[indexPath.item] cell.image = image }else{ cell.image = nil } cell.deleteClickClosure = {[weak self] in // 在这个闭包里面删除数组里面对应位置的图片 self?.images.remove(at: indexPath.item) // 刷新数据 self?.reloadData() } return cell } } //MARK: - 4.setupUI for cells and register for cells class XDLComposePictureViewCell:UICollectionViewCell{ var deleteClickClosure:(() ->())? var image: UIImage?{ didSet{ if image == nil{ imageView.image = UIImage(named: "compose_pic_add") imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted") }else{ imageView.image = image imageView.highlightedImage = image } deleteButton.isHidden = image == nil } } override init(frame: CGRect){ super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup(){ contentView.addSubview(imageView) contentView.addSubview(deleteButton) imageView.snp_makeConstraints { (make) in make.edges.equalTo(contentView) } deleteButton.snp_makeConstraints { (make) in make.top.right.equalTo(contentView) } } @objc private func clickDelectButton(){ print("deleteClickButtion") deleteClickClosure?() } private lazy var imageView :UIImageView = {()-> UIImageView in let imageView = UIImageView() imageView.contentMode = UIViewContentMode.scaleAspectFill imageView.clipsToBounds = true //label.textColor = UIcolor.red return imageView }() private lazy var deleteButton :UIButton = {()-> UIButton in let button = UIButton() button.addTarget(self, action: #selector(clickDelectButton), for: .touchUpInside) button.setImage(UIImage(named:"compose_photo_close"), for: .normal) return button }() }
mit
0073d94d96db16e5764a266d06fd1e29
27.576419
151
0.592145
4.854599
false
false
false
false
algoliareadmebot/algoliasearch-client-swift
Source/AbstractQuery.swift
1
13532
// // Copyright (c) 2015 Algolia // http://www.algolia.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 // ---------------------------------------------------------------------------- // IMPLEMENTATION NOTES // ---------------------------------------------------------------------------- // # Typed vs untyped parameters // // All parameters are stored as untyped, string values. They can be // accessed via the low-level `get` and `set` methods (or the subscript // operator). // // Besides, the class provides typed properties, acting as wrappers on top // of the untyped storage (i.e. serializing to and parsing from string // values). // // # Bridgeability // // **This Swift client must be bridgeable to Objective-C.** // // Unfortunately, query parameters with primitive types (Int, Bool...) are not // bridgeable, because all parameters are optional, and primitive optionals are // not bridgeable to Objective-C. // // To avoid polluting too much the Swift interface with suboptimal types, the // following policy is used: // // - Any parameter whose type is representable in Objective-C is implemented // directly in Swift and marked as `@objc`. // // - Any paramater whose type is *not* bridgeable to Objective-C is implemented // a first time as a Swift-only type... // // - ... and supplemented by an Objective-C specific artifact. To guarantee // optimal developer experience, this artifact is: // // - Named with a `z_objc_` prefix in Swift. This makes it clear that they // are Objective-C specific. The leading "z" ensures they are last in // autocompletion. // // - Exposed to Objective-C using the normal (unprefixed name). // // - Not documented. This ensures that it does not appear in the reference // documentation. // // This way, each platform sees a properties with the right name and the most // adequate type. The only drawback is the added clutter of the `z_objc_`-prefixed // properties in Swift. // // There is also an edge case for the `aroundRadiusAll` constant, which is not // documented. // // ## The case of enums // // Enums can only be bridged to Objective-C if their raw type is integral. // We could do that, but since parameters are optional and optional value types // cannot be bridged anyway (see above), this would be pointless: the type // safety of the enum would be lost in the wrapping into `NSNumber`. Therefore, // enums have a string raw value, and the Objective-C bridge uses a plain // `NSString`. // // ## The case of structs // // Auxiliary types used for query parameters, like `LatLng` or `GeoRect`, have // value semantics. However, structs are not bridgeable to Objective-C. Therefore // we use plain classes (inheriting from `NSObject`) and we make them immutable. // // Equality comparison is implemented in those classes only for the sake of // testability (we use comparisons extensively in unit tests). // // ## Annotations // // Properties and methods visible in Objective-C are annotated with `@objc`. // From an implementation point of view, this is not necessary, because `Query` // derives from `NSObject` and thus every brdigeable property/method is // automatically bridged. We use these annotations as hints for maintainers // (so please keep them). // // ---------------------------------------------------------------------------- /// A pair of (latitude, longitude). /// Used in geo-search. /// @objc public class LatLng: NSObject { // IMPLEMENTATION NOTE: Cannot be `struct` because of Objective-C bridgeability. /// Latitude. public let lat: Double /// Longitude. public let lng: Double /// Create a geo location. /// /// - parameter lat: Latitude. /// - parameter lng: Longitude. /// public init(lat: Double, lng: Double) { self.lat = lat self.lng = lng } // MARK: Equatable public override func isEqual(_ object: Any?) -> Bool { if let rhs = object as? LatLng { return self.lat == rhs.lat && self.lng == rhs.lng } else { return false } } } /// A rectangle in geo coordinates. /// Used in geo-search. /// @objc public class GeoRect: NSObject { // IMPLEMENTATION NOTE: Cannot be `struct` because of Objective-C bridgeability. /// One of the rectangle's corners (typically the northwesternmost). public let p1: LatLng /// Corner opposite from `p1` (typically the southeasternmost). public let p2: LatLng /// Create a geo rectangle. /// /// - parameter p1: One of the rectangle's corners (typically the northwesternmost). /// - parameter p2: Corner opposite from `p1` (typically the southeasternmost). /// public init(p1: LatLng, p2: LatLng) { self.p1 = p1 self.p2 = p2 } public override func isEqual(_ object: Any?) -> Bool { if let rhs = object as? GeoRect { return self.p1 == rhs.p1 && self.p2 == rhs.p2 } else { return false } } } /// An abstract search query. /// /// + Warning: This class is not meant to be used directly. Please see `Query` or `PlacesQuery` instead. /// /// ## KVO /// /// Every parameter is observable via KVO under its own name. /// @objc open class AbstractQuery : NSObject, NSCopying { // MARK: - Low-level (untyped) parameters /// Parameters, as untyped values. @objc public private(set) var parameters: [String: String] = [:] /// Get a parameter in an untyped fashion. /// /// - parameter name: The parameter's name. /// - returns: The parameter's value, or nil if a parameter with the specified name does not exist. /// @objc public func parameter(withName name: String) -> String? { return parameters[name] } /// Set a parameter in an untyped fashion. /// This low-level accessor is intended to access parameters that this client does not yet support. /// /// - parameter name: The parameter's name. /// - parameter value: The parameter's value, or nill to remove it. /// @objc public func setParameter(withName name: String, to value: String?) { let oldValue = parameters[name] if value != oldValue { self.willChangeValue(forKey: name) } if value == nil { parameters.removeValue(forKey: name) } else { parameters[name] = value! } if value != oldValue { self.didChangeValue(forKey: name) } } /// Convenience shortcut to `parameter(withName:)` and `setParameter(withName:to:)`. @objc public subscript(index: String) -> String? { get { return parameter(withName: index) } set(newValue) { setParameter(withName: index, to: newValue) } } // MARK: - // MARK: - Miscellaneous @objc override open var description: String { get { return "\(String(describing: type(of: self))){\(parameters)}" } } // MARK: - Initialization /// Construct an empty query. @objc public override init() { } /// Construct a query with the specified low-level parameters. @objc public init(parameters: [String: String]) { self.parameters = parameters } /// Clear all parameters. @objc open func clear() { parameters.removeAll() } // MARK: NSCopying /// Support for `NSCopying`. /// /// + Note: Primarily intended for Objective-C use. Swift coders should use `init(copy:)`. /// @objc open func copy(with zone: NSZone?) -> Any { // NOTE: As per the docs, the zone argument is ignored. return AbstractQuery(parameters: self.parameters) } // MARK: Serialization & parsing /// Return the final query string used in URL. @objc open func build() -> String { return AbstractQuery.build(parameters: parameters) } /// Build a query string from a set of parameters. @objc static public func build(parameters: [String: String]) -> String { var components = [String]() // Sort parameters by name to get predictable output. let sortedParameters = parameters.sorted { $0.0 < $1.0 } for (key, value) in sortedParameters { let escapedKey = key.urlEncodedQueryParam() let escapedValue = value.urlEncodedQueryParam() components.append(escapedKey + "=" + escapedValue) } return components.joined(separator: "&") } internal static func parse(_ queryString: String, into query: AbstractQuery) { let components = queryString.components(separatedBy: "&") for component in components { let fields = component.components(separatedBy: "=") if fields.count < 1 || fields.count > 2 { continue } if let name = fields[0].removingPercentEncoding { let value: String? = fields.count >= 2 ? fields[1].removingPercentEncoding : nil if value == nil { query.parameters.removeValue(forKey: name) } else { query.parameters[name] = value! } } } } // MARK: Equatable override open func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? AbstractQuery else { return false } return self.parameters == rhs.parameters } // MARK: - Helper methods to build & parse URL /// Build a plain, comma-separated array of strings. /// internal static func buildStringArray(_ array: [String]?) -> String? { if array != nil { return array!.joined(separator: ",") } return nil } internal static func parseStringArray(_ string: String?) -> [String]? { if string != nil { // First try to parse the JSON notation: do { if let array = try JSONSerialization.jsonObject(with: string!.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [String] { return array } } catch { } // Fallback on plain string parsing. return string!.components(separatedBy: ",") } return nil } internal static func buildJSONArray(_ array: [Any]?) -> String? { if array != nil { do { let data = try JSONSerialization.data(withJSONObject: array!, options: JSONSerialization.WritingOptions(rawValue: 0)) if let string = String(data: data, encoding: String.Encoding.utf8) { return string } } catch { } } return nil } internal static func parseJSONArray(_ string: String?) -> [Any]? { if string != nil { do { if let array = try JSONSerialization.jsonObject(with: string!.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [Any] { return array } } catch { } } return nil } internal static func buildUInt(_ int: UInt?) -> String? { return int == nil ? nil : String(int!) } internal static func parseUInt(_ string: String?) -> UInt? { if string != nil { if let intValue = UInt(string!) { return intValue } } return nil } internal static func buildBool(_ bool: Bool?) -> String? { return bool == nil ? nil : String(bool!) } internal static func parseBool(_ string: String?) -> Bool? { if string != nil { switch (string!.lowercased()) { case "true": return true case "false": return false default: if let intValue = Int(string!) { return intValue != 0 } } } return nil } internal static func toNumber(_ bool: Bool?) -> NSNumber? { return bool == nil ? nil : NSNumber(value: bool!) } internal static func toNumber(_ int: UInt?) -> NSNumber? { return int == nil ? nil : NSNumber(value: int!) } }
mit
df0051299b7b85a550e1663f4bffabb8
33
184
0.599542
4.550101
false
false
false
false
cruisediary/GitHub
GitHub/Scenes/ListIssues/ListIssuesViewController.swift
1
4531
// // ListIssuesViewController.swift // GitHub // // Created by CruzDiary on 15/01/2017. // Copyright © 2017 cruz. All rights reserved. // import UIKit import RxSwift protocol ListIssuesViewControllerInput { func displayIssues(_ viewModel: ListIssues.FetchIssues.ViewModel) } protocol ListIssuesViewControllerOutput { func fetchIssues() } class ListIssuesViewController: UIViewController, ListIssuesViewControllerInput { var router: ListIssuesRouter! var output: ListIssuesViewControllerOutput! var id: Int = -1 { didSet { guard id != -1 else { return } router.navigateToShowIssueScene() } } @IBOutlet weak var collectionView: UICollectionView! enum Section { static let number = 1 } enum State { case fetching case fetched case networkError } var state: State = .fetching { didSet { collectionView.reloadData() } } var viewModel = ListIssues.FetchIssues.ViewModel(issues: []) override func awakeFromNib() { super.awakeFromNib() ListIssuesConfigurator.sharedInstance.configure(self) } override func viewDidLoad() { super.viewDidLoad() registerUINibs() state = .fetching // Do any additional setup after loading the view. } func registerUINibs() { collectionView.register(UINib(nibName: IndicatorCell.nibName, bundle: nil), forCellWithReuseIdentifier: IndicatorCell.reuseIdentifier) collectionView.register(UINib(nibName: ListIssueCell.nibName, bundle: nil), forCellWithReuseIdentifier: ListIssueCell.reuseIdentifier) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationItem.title = "Issues" switch state { case .fetching, .networkError: output.fetchIssues() case .fetched: break } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func displayIssues(_ viewModel: ListIssues.FetchIssues.ViewModel) { DispatchQueue.main.async { self.viewModel = viewModel self.state = .fetched } } } extension ListIssuesViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let id = viewModel.issue(at: indexPath)?.id else { return } self.id = id } } extension ListIssuesViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch state { case .fetching: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: IndicatorCell.reuseIdentifier, for: indexPath) as! IndicatorCell return cell default: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ListIssueCell.reuseIdentifier, for: indexPath) as! ListIssueCell if let issue = viewModel.issue(at: indexPath) { cell.configure(issue: issue) } return cell } } func numberOfSections(in collectionView: UICollectionView) -> Int { return Section.number } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch state { case .fetching, .networkError: return 1 case .fetched: return viewModel.numberOfItem } } } extension ListIssuesViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { switch state { case .fetching, .networkError: return collectionView.bounds.size case .fetched: return CGSize(width: collectionView.width, height: ListIssueCell.height) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 1 } } extension UIView { var width: CGFloat { return bounds.width } }
mit
03aac63d73244a38f9224e8af34fccaf
29.608108
170
0.671082
5.431655
false
false
false
false
WXYC/wxyc-ios-64
iOS/PlaybackButton.swift
1
6592
// // PlaybackButton.swift // PlaybackButton // // Created by Yuji Hato on 1/1/16. // Copyright © 2016 dekatotoro. All rights reserved. // import UIKit let DefaultsPlaybackDuration: CFTimeInterval = 0.24 @objc public enum PlaybackButtonState : Int { case paused case playing public var value: CGFloat { switch self { case .paused: return 1.0 case .playing: return 0.0 } } } @objc @IBDesignable class PlaybackLayer: CALayer { private static let AnimationKey = "playbackValue" private static let AnimationIdentifier = "playbackLayerAnimation" private var contentEdgeInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16) var status: PlaybackButtonState = .paused @objc var playbackValue: CGFloat = 1.0 { didSet { setNeedsDisplay() } } var color = UIColor.white var playbackAnimationDuration: CFTimeInterval = DefaultsPlaybackDuration override init() { super.init() self.backgroundColor = UIColor.clear.cgColor } override init(layer: Any) { super.init(layer: layer) if let playbackLayer = layer as? PlaybackLayer { self.status = playbackLayer.status self.playbackValue = playbackLayer.playbackValue self.color = playbackLayer.color } } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { self.removeAllAnimations() } func set(status: PlaybackButtonState, animated: Bool) { if self.status == status { return } self.status = status if animated { if self.animation(forKey: PlaybackLayer.AnimationIdentifier) != nil { self.removeAnimation(forKey: PlaybackLayer.AnimationIdentifier) } let fromValue: CGFloat = self.playbackValue let toValue: CGFloat = status.value let animation = CABasicAnimation(keyPath: PlaybackLayer.AnimationKey) animation.fromValue = fromValue animation.toValue = toValue animation.duration = self.playbackAnimationDuration animation.isRemovedOnCompletion = true animation.fillMode = CAMediaTimingFillMode.forwards animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) animation.delegate = self self.add(animation, forKey: PlaybackLayer.AnimationIdentifier) } else { self.playbackValue = status.value } } override class func needsDisplay(forKey key: String) -> Bool { if key == PlaybackLayer.AnimationKey { return true } return CALayer.needsDisplay(forKey: key) } override func draw(in context: CGContext) { context.clear(self.visibleRect) let rect = context.boundingBoxOfClipPath let halfWidth = rect.width / 2.0 let eighthWidth = halfWidth / 2.0 let sixteenthWidth: CGFloat = eighthWidth / 2.0 let thirtySecondWidth: CGFloat = sixteenthWidth / 2.0 let componentWidth: CGFloat = sixteenthWidth * (1 + self.playbackValue) let insetMargin: CGFloat = thirtySecondWidth * (1 - self.playbackValue) let firstHalfMargin: CGFloat = eighthWidth + insetMargin let secondHalfMargin = halfWidth + insetMargin let halfHeight = rect.height / 2.0 let quarterHeight: CGFloat = halfHeight / 2.0 let sixteenthHeight: CGFloat = halfHeight / 4.0 let h1: CGFloat = sixteenthHeight * self.playbackValue let h2: CGFloat = quarterHeight * self.playbackValue context.move(to: CGPoint(x: firstHalfMargin, y: quarterHeight)) context.addLine(to: CGPoint(x: firstHalfMargin + componentWidth, y: quarterHeight + h1)) context.addLine(to: CGPoint(x: firstHalfMargin + componentWidth, y: quarterHeight + halfHeight - h1)) context.addLine(to: CGPoint(x: firstHalfMargin, y: quarterHeight + halfHeight)) context.move(to: CGPoint(x: secondHalfMargin, y: quarterHeight + h1)) context.addLine(to: CGPoint(x: secondHalfMargin + componentWidth, y: quarterHeight + h2)) context.addLine(to: CGPoint(x: secondHalfMargin + componentWidth, y: quarterHeight + halfHeight - h2)) context.addLine(to: CGPoint(x: secondHalfMargin, y: quarterHeight + halfHeight - h1)) context.setFillColor(self.color.cgColor) context.fillPath() } } extension PlaybackLayer: CAAnimationDelegate { func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { guard flag else { return } if self.animation(forKey: PlaybackLayer.AnimationIdentifier) != nil { self.removeAnimation(forKey: PlaybackLayer.AnimationIdentifier) } if let toValue: CGFloat = anim.value(forKey: "toValue") as? CGFloat { self.playbackValue = toValue } } } @objc @IBDesignable class PlaybackButton : UIButton { override var layer: PlaybackLayer { return super.layer as! PlaybackLayer } var duration: CFTimeInterval = DefaultsPlaybackDuration { didSet { self.layer.playbackAnimationDuration = self.duration } } var status: PlaybackButtonState { get { return self.layer.status } set { self.layer.set(status: newValue, animated: true) } } override init(frame: CGRect) { super.init(frame: frame) self.addPlaybackLayer() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addPlaybackLayer() } func set(status: PlaybackButtonState, animated: Bool = true) { self.layer.set(status: status, animated: animated) } override var tintColor: UIColor! { didSet { self.layer.color = tintColor } } override class var layerClass: AnyClass { return PlaybackLayer.self } private func addPlaybackLayer() { layer.contentsScale = UIScreen.main.scale layer.frame = self.bounds layer.playbackValue = PlaybackButtonState.paused.value layer.color = self.tintColor layer.playbackAnimationDuration = self.duration } }
mit
0d8eec124da66b92f021be6396bad016
30.535885
110
0.623274
4.828571
false
false
false
false
pmlbrito/cookiecutter-ios-template
PRODUCTNAME/app/PRODUCTNAME/Domain/Models/Common/ProcessResult.swift
1
765
// // ProcessResult.swift // PRODUCTNAME // // Created by LEADDEVELOPER on 28/06/2017. // Copyright © 2017 ORGANIZATION. All rights reserved. // import Foundation open class ProcessResult { enum Status: Int { case ok = 1 case error = 2 case unknown = -1 } var statusCode: Status var message: String? init(status: Status) { self.statusCode = status self.message = nil } convenience init(resultCode: Int) { self.init(status: Status(rawValue: resultCode) ?? .unknown) } init(status: Status, resultMessage: String?) { self.statusCode = status self.message = resultMessage } func hasError() -> Bool { return self.statusCode == .error } }
mit
5ee8f5dff54a354c895b67373679eb12
19.105263
67
0.603403
4.12973
false
false
false
false
TinyCrayon/TinyCrayon-iOS-SDK
TCMask/HairBrushLog.swift
1
1932
// // HairBrushLog.swift // TinyCrayon // // Created by Xin Zeng on 10/12/16. // // import Foundation import TCCore class HairBrushLog : ToolLog { var diffs = [[UInt32]]() override var count: Int { return diffs.count } override var size: Int { var retval = 0 for diff in diffs { retval += diff.count } return retval } init() { super.init(type: .hairBrush) } func push(diff: [UInt32]) { idx = idx + 1 diffs.removeLast(diffs.count - idx) diffs.append(diff) } override func undo(tool: Tool) { assert(tool.type == self.type, "inv type: tool:\(tool.type) self:\(self.type)") let hbtool = tool as! HairBrushTool let diff = diffs[idx] if diff.count == 0 { hbtool.invert() } else { TCCore.logDecodeDiff(to: &hbtool.maskView.opacity, from: hbtool.maskView.opacity, diff: diff, count: hbtool.maskView.opacity.count, diffCount: diff.count) TCCore.arrayCopy(&hbtool.previousAlpha, src: hbtool.maskView.opacity, count: hbtool.previousAlpha.count) } idx -= 1 } override func redo(tool: Tool) { assert(tool.type == self.type, "inv type: tool:\(tool.type) self:\(self.type)") let hbtool = tool as! HairBrushTool idx += 1 let diff = diffs[idx] if diff.count == 0 { hbtool.invert() } else { TCCore.logDecodeDiff(to: &hbtool.maskView.opacity, from: hbtool.maskView.opacity, diff: diff, count: hbtool.maskView.opacity.count, diffCount: diff.count) TCCore.arrayCopy(&hbtool.previousAlpha, src: hbtool.maskView.opacity, count: hbtool.previousAlpha.count) } } override func invert() { idx = idx + 1 diffs.removeLast(diffs.count - idx) diffs.append([UInt32]()) } }
mit
f2c32c08523fb0189218ec2571634109
27
166
0.575052
3.887324
false
false
false
false
wijjo/iOS-WeatherReport
WeatherReport/WeatherItem.swift
1
5256
// // WeatherItem.swift // WeatherReport // // Created by Steve Cooper on 12/28/14. // Copyright (c) 2014 Steve Cooper. All rights reserved. // import Foundation let bearings = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] struct WeatherItem { var label: String var text: String var symbol: String? init(_ label: String, _ text: String, _ symbol: String?) { self.label = label self.text = text self.symbol = symbol } init(_ label: String, _ text: String) { self.label = label self.text = text } } // Utility for building weather items with single or multi-field values from a dictionary. class WeatherItemBuilder { let d: NSDictionary struct FieldSpec { let label: String let symbol: String? let builder: WeatherFieldBuilder } var fieldSpecs: [FieldSpec] = [] init(_ d: NSDictionary) { self.d = d } func makeItem(label: String, symbol: String? = nil) -> WeatherFieldBuilder { let fieldSpec = FieldSpec(label: label, symbol: symbol, builder: WeatherFieldBuilder(d)) self.fieldSpecs.append(fieldSpec) return fieldSpec.builder } func toItems() -> [WeatherItem] { var items: [WeatherItem] = [] for fieldSpec in self.fieldSpecs { items.append(WeatherItem(fieldSpec.label, fieldSpec.builder.toString(), fieldSpec.symbol)) } return items } } func formatDouble(value: Double?, precision: Int = 2) -> String? { if let v = value { if precision == 0 { let i = Int(v + 0.5) return "\(i)" } let format = "%.\(precision)f" return NSString(format: format, v) } return nil } // Used to build each individual multi-field items. class WeatherFieldBuilder { let d: NSDictionary var f: [String] = [] var wrapParens = false var itemLabel: String? var itemSymbol: String? var fieldLabel: String? init(_ d: NSDictionary) { self.d = d } func parenthesize() { self.wrapParens = true } func label(fieldLabel: String) { self.fieldLabel = fieldLabel } private func resetField() { self.wrapParens = false self.fieldLabel = nil } func appendValue(valueString: String) { var before = self.wrapParens ? "(" : "" var after = self.wrapParens ? ")" : "" var labelString = self.fieldLabel != nil ? "\(self.fieldLabel!) " : "" self.f.append("\(before)\(labelString)\(valueString)\(after)") } func getInt(key: String) -> Int? { if let v = self.d[key] as? Int { return v } if let v = (self.d[key] as? String)?.toInt() { return v } return nil } func getDouble(key: String) -> Double? { if let v = self.d[key] as? Double { return v } if let v = self.d[key] as? NSString { return v.doubleValue } return nil } func getString(key: String) -> String? { return self.d[key] as? String } func unixDate(key: String) { if let v = self.getInt(key) { let formatter = NSDateFormatter() formatter.dateFormat = "HH:mm:ss zzz MM-dd-yyyy" self.appendValue( formatter.stringFromDate(NSDate(timeIntervalSince1970: NSTimeInterval(v)))) } self.resetField() } func degrees(key: String, precision: Int = 0) { if let v = formatDouble(self.getDouble(key), precision: precision) { self.appendValue("\(v)˚") } self.resetField() } func percent(key: String, precision: Int = 0) { if let v = self.getDouble(key) { if let percentString = formatDouble(v * 100.0, precision: precision) { self.appendValue("\(percentString)%") } } self.resetField() } func string(key: String) { if let v = self.getString(key) { self.appendValue(v) } self.resetField() } func mph(key: String, precision: Int = 0) { if let v = formatDouble(self.getDouble(key), precision: precision) { self.appendValue("\(v) MPH") } self.resetField() } func miles(key: String, precision: Int = 0) { if let v = formatDouble(self.getDouble(key), precision: precision) { self.appendValue("\(v) miles") } self.resetField() } func millibars(key: String, precision: Int = 0) { if let v = formatDouble(self.getDouble(key), precision: precision) { self.appendValue("\(v) millibars") } self.resetField() } func bearing(key: String) { if let degrees = self.getDouble(key) { let bearingDivisor = 360.0 / Double(bearings.count) // Formula rounds so that bearing regions surround the precise directions. let index = Int((degrees + (bearingDivisor / 2.0)) / bearingDivisor) % bearings.count self.appendValue(bearings[index]) } self.resetField() } func toString() -> String { return " ".join(self.f) } }
apache-2.0
230df9c91a2100eb1a81f380303d46d3
25.811224
102
0.56118
3.93633
false
false
false
false
MCanhisares/Chatify-ios
Chatify/Chatify/Services/FirebaseService.swift
1
1966
// // FirebaseService.swift // Chatify // // Created by Marcel Canhisares on 14/02/17. // Copyright © 2017 Azell. All rights reserved. // import UIKit import Firebase import FirebaseDatabase import FirebaseAuth class FirebaseService: NSObject { static let sharedInstance = FirebaseService() let databaseInstance = FIRDatabase.database().reference() var currentUser: User? = nil var currentUserUid: String? func login(email: String, password: String, completion: @escaping (_ success: Bool) -> Void) { FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { user, error in if let err = error { print(err.localizedDescription) completion(false) } else { print(user) self.currentUserUid = user?.uid ProfileService.GetUser(uid: user!.uid, completion: { user in self.currentUser = user completion(true) }) } }) } func createAccount(email: String, password: String, username: String, completion: @escaping (_ success: Bool) -> Void) { FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error) in if error != nil { print(error?.localizedDescription) completion(false) return } self.currentUserUid = user?.uid ProfileService.AddUser(username: username, email: email) self.login(email: email, password: password, completion: { (success) in if success { print("Login successful") } else { print("Login unsuccessful") } completion(success) }) }) } }
mit
4511fcbee0697f1bf704f3d293d5ca90
30.190476
124
0.532316
5.198413
false
false
false
false
lennet/CycleHack_AR
CycleHack_AR/Model/GeoFeatureCollection.swift
1
1125
// // GeoFeatureCollection.swift // CycleHack_AR // // Created by Leo Thomas on 16.09.17. // Copyright © 2017 CycleHackBer. All rights reserved. // import Foundation struct StreetFeatureCollection: Codable { var type: String var features: [GeoFeature<Street, [[[Double]]]>] } extension StreetFeatureCollection { init() { let path = Bundle.main.path(forResource: "streets", ofType: "geojson") let data = try! Data(contentsOf: URL(fileURLWithPath: path!)) self = try! JSONDecoder().decode(StreetFeatureCollection.self, from: data) } } struct PointFeatureCollection: Codable { var type: String var features: [GeoFeature<Point, [Double]>] } extension PointFeatureCollection { init() { let path = Bundle.main.path(forResource: "points", ofType: "geojson") let data = try! Data(contentsOf: URL(fileURLWithPath: path!)) self = try! JSONDecoder().decode(PointFeatureCollection.self, from: data) } } struct GeoFeatureCollection<T: Codable, P: Codable>: Codable { var type: String var features: [GeoFeature<T, P>] }
mit
f9545cc93ab71c715c4665f2137901a3
24.545455
82
0.66726
3.849315
false
false
false
false
typelift/Basis
Basis/Version.swift
2
1152
// // Version.swift // Basis // // Created by Robert Widmann on 10/10/14. // Copyright (c) 2014 TypeLift. All rights reserved. // Released under the MIT license. // /// Represents the version of a piece of software. /// /// Versions are equal if they have the same number, value, and ordering of branch versions and the /// same tags that may not necessarily be in the same order. public struct Version { public let versionBranch : [Int] public let versionTags : [String] public init(_ versionBranch : [Int], _ versionTags : [String]) { self.versionBranch = versionBranch self.versionTags = versionTags } } extension Version : Equatable {} public func ==(lhs : Version, rhs : Version) -> Bool { return lhs.versionBranch == rhs.versionBranch && sort(lhs.versionTags) == sort(rhs.versionTags) } extension Version : Printable { public var description : String { get { let versions = concat(intersperse(unpack("."))(self.versionBranch.map({ (let b : Int) in unpack(b.description) }))) let tags = concatMap({ (let xs : [Character]) in unpack("-") + xs })(self.versionTags.map(unpack)) return pack(versions + tags) } } }
mit
3f0202e7c1a3593f735c98b8bb67eae8
29.315789
118
0.690104
3.544615
false
false
false
false
kolyasev/YaftDB
Source/DatabaseCollection.swift
1
7168
// ---------------------------------------------------------------------------- // // DatabaseCollection.swift // // @author Denis Kolyasev <[email protected]> // // ---------------------------------------------------------------------------- import YapDatabase // ---------------------------------------------------------------------------- open class DatabaseCollection<T: DatabaseObject> { // MARK: - Construction init(name: String, database: Database) { self.name = name self.database = database } // MARK: - Properties let name: String let database: Database // MARK: - Functions: Observing open func observe(_ key: String) -> DatabaseObjectObserver<T> { let connection = self.database.database.newConnection() return DatabaseObjectObserver<T>(collection: self.name, key: key, connection: connection) } open func observe<V: DatabaseCollectionViewProtocol>(_ viewType: V.Type) -> DatabaseCollectionViewObserver<V> where V.Object == T { let view = viewType.init(collection: self.name) view.registerExtensionInDatabase(self.database.database) let connection = self.database.database.newConnection() return DatabaseCollectionViewObserver<V>(view: view, connection: connection) } open func observe() -> DatabaseCollectionObserver<T> { let connection = self.database.database.newConnection() return DatabaseCollectionObserver<T>(collection: self.name, connection: connection) } // MARK: - Functions: Read Transactions open func read(_ block: @escaping (DatabaseCollectionReadTransaction<T>) -> Void) { self.database.connection.read { transaction in block(self.collectionReadTransaction(transaction)) } } open func read<R>(_ block: @escaping (DatabaseCollectionReadTransaction<T>) -> R) -> R { var result: R! self.database.connection.read { transaction in result = block(self.collectionReadTransaction(transaction)) } return result } open func asyncRead(_ block: @escaping (DatabaseCollectionReadTransaction<T>) -> Void) { weak var weakSelf = self self.database.connection.asyncRead { transaction in if let collectionTransaction = weakSelf?.collectionReadTransaction(transaction) { block(collectionTransaction) } } } // MARK: - Functions: Write Transactions open func write(_ block: @escaping (DatabaseCollectionReadWriteTransaction<T>) -> Void) { self.database.connection.readWrite { transaction in block(self.collectionReadWriteTransaction(transaction)) } } open func write<R>(_ block: @escaping (DatabaseCollectionReadWriteTransaction<T>) -> R) -> R { var result: R! self.database.connection.readWrite { transaction in result = block(self.collectionReadWriteTransaction(transaction)) } return result } open func asyncWrite(_ block: @escaping (DatabaseCollectionReadWriteTransaction<T>) -> Void) { weak var weakSelf = self self.database.connection.asyncReadWrite { transaction in if let collectionTransaction = weakSelf?.collectionReadWriteTransaction(transaction) { block(collectionTransaction) } } } // MARK: - Private Functions fileprivate func collectionReadTransaction(_ transaction: YapDatabaseReadTransaction) -> DatabaseCollectionReadTransaction<T> { return DatabaseCollectionReadTransaction<T>(transaction: transaction, collection: self.name) } fileprivate func collectionReadWriteTransaction(_ transaction: YapDatabaseReadWriteTransaction) -> DatabaseCollectionReadWriteTransaction<T> { return DatabaseCollectionReadWriteTransaction<T>(transaction: transaction, collection: self.name) } // MARK: - Inner Types typealias ObjectType = T } // ---------------------------------------------------------------------------- extension DatabaseCollection { // MARK: - Functions: Operations public func put(_ key: String, object: T) { asyncWrite { transaction in transaction.put(key, object: object) } } public func put(_ entities: [Entity]) { asyncWrite { transaction in for entity in entities { transaction.put(entity.key, object: entity.object) } } } public func get(_ key: String) -> T? { return read { transaction in return transaction.get(key) } } public func get(_ keys: [String]) -> [String: T?] { return read { transaction in var result: [String: T?] = [:] for key in keys { result[key] = transaction.get(key) } return result } } // TODO: ... // public func filterKeys(block: (String) -> Bool) -> [String] // { // var result: [String] = [] // // // Read from database // self.connection.readWithBlock { transaction in // transaction.enumerateKeysInCollection(collection) { key, stop in // if block(key) { // result.append(key) // } // } // } // // return result // } // TODO: ... // public func filterByKey(block: (String) -> Bool) -> [T] // { // var result: [T] = [] // // // Read from database // self.connection.readWithBlock { transaction in // transaction.enumerateKeysInCollection(collection) { key, stop in // if block(key) // { // if let object = transaction.objectForKey(key, inCollection: collection) as? T { // result.append(object) // } // } // } // } // // return result // } public func filter(_ block: @escaping (T) -> Bool) -> [T] { return read { transaction in var result: [T] = [] transaction.enumerateObjects { key, object, stop in if block(object) { result.append(object) } } return result } } public func remove(_ key: String) { asyncWrite { transaction in transaction.remove(key) } } public func remove(_ keys: [String]) { asyncWrite { transaction in transaction.remove(keys) } } public func removeAll() { asyncWrite { transaction in transaction.removeAll() } } public func replaceAll(_ entities: [Entity]) { asyncWrite { transaction in transaction.removeAll() for entity in entities { transaction.put(entity.key, object: entity.object) } } } // MARK: - Inner Types public typealias Entity = (key: String, object: T) } // ----------------------------------------------------------------------------
mit
ad768cb94cba7fa26f419e8670b68d83
26.569231
146
0.55678
4.862958
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/InsertMediaSearchResultPreviewingViewController.swift
3
3053
import UIKit final class InsertMediaSearchResultPreviewingViewController: UIViewController { @IBOutlet private weak var imageView: UIImageView! @IBOutlet private weak var imageInfoViewContainer: UIView! @IBOutlet private weak var activityIndicator: UIActivityIndicatorView! private lazy var imageInfoView = InsertMediaImageInfoView.wmf_viewFromClassNib()! var selectImageAction: (() -> Void)? var moreInformationAction: ((URL) -> Void)? private let searchResult: InsertMediaSearchResult private let imageURL: URL private var theme = Theme.standard init(imageURL: URL, searchResult: InsertMediaSearchResult) { self.imageURL = imageURL self.searchResult = searchResult super.init(nibName: "InsertMediaSearchResultPreviewingViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() imageView.accessibilityIgnoresInvertColors = true imageView.wmf_setImage(with: imageURL, detectFaces: true, onGPU: true, failure: { _ in }) { self.imageView.backgroundColor = self.view.backgroundColor self.activityIndicator.stopAnimating() } imageInfoView.configure(with: searchResult, showLicenseName: false, showMoreInformationButton: false, theme: theme) imageInfoView.apply(theme: theme) imageInfoViewContainer.wmf_addSubviewWithConstraintsToEdges(imageInfoView) apply(theme: theme) } override var previewActionItems: [UIPreviewActionItem] { let selectImageAction = UIPreviewAction(title: WMFLocalizedString("insert-media-image-preview-select-image-action-title", value: "Select image", comment: "Title for preview action that results in image selection"), style: .default, handler: { [weak self] (_, _) in self?.selectImageAction?() }) let moreInformationAction = UIPreviewAction(title: WMFLocalizedString("insert-media-image-preview-more-information-action-title", value: "More information", comment: "Title for preview action that results in presenting more information"), style: .default, handler: { [weak self] (_, _) in guard let url = self?.searchResult.imageInfo?.filePageURL else { return } self?.moreInformationAction?(url) }) let cancelAction = UIPreviewAction(title: CommonStrings.cancelActionTitle, style: .default) { (_, _) in } return [selectImageAction, moreInformationAction, cancelAction] } } extension InsertMediaSearchResultPreviewingViewController: Themeable { func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground imageView.backgroundColor = view.backgroundColor activityIndicator.style = theme.isDark ? .white : .gray imageInfoView.apply(theme: theme) } }
mit
353bff160c14752b3f4fe6f0eff1bb1e
45.257576
296
0.70357
5.201022
false
false
false
false
avito-tech/Paparazzo
Paparazzo/Core/VIPER/InfoMessage/InfoMessageView.swift
1
2604
import UIKit struct InfoMessageViewData { let text: String let timeout: TimeInterval let font: UIFont? } final class InfoMessageView: UIView { private struct Layout { static let height: CGFloat = 26 static let textInsets = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 6) static let widthTextInsets = textInsets.left + textInsets.right static let heightTextInsets = textInsets.top + textInsets.bottom } private struct Spec { static let textColor = UIColor.black static let cornerRadius: CGFloat = 2 static let backgroundColor = UIColor.white static let shadowOffset = CGSize(width: 0, height: 1) static let shadowOpacity: Float = 0.14 static let shadowRadius: CGFloat = 2 } private let textLabel = UILabel() private let contentView = UIView() // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) addSubview(contentView) contentView.layer.cornerRadius = Spec.cornerRadius contentView.layer.masksToBounds = true textLabel.textColor = Spec.textColor contentView.addSubview(textLabel) contentView.backgroundColor = Spec.backgroundColor layer.masksToBounds = false layer.shadowOffset = Spec.shadowOffset layer.shadowRadius = Spec.shadowRadius layer.shadowOpacity = Spec.shadowOpacity } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View data func setViewData(_ viewData: InfoMessageViewData) { textLabel.font = viewData.font textLabel.text = viewData.text } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() textLabel.frame = CGRect( x: Layout.textInsets.left, y: Layout.textInsets.top, width: bounds.width - Layout.widthTextInsets, height: bounds.height - Layout.heightTextInsets ) contentView.frame = bounds } override func sizeThatFits(_ size: CGSize) -> CGSize { let shrinkedSize = CGSize( width: size.width - Layout.widthTextInsets, height: Layout.height - Layout.heightTextInsets ) let textSize = textLabel.sizeThatFits(shrinkedSize) return CGSize( width: textSize.width + Layout.widthTextInsets, height: Layout.height ) } }
mit
d7e5421f8a36ea8308bc58f31ef312ed
28.931034
82
0.614439
5.105882
false
false
false
false
abitofalchemy/auralML
Sandbox/STBlueMS_iOS/W2STApp/MainApp/Demo/BlueVoice/ASREngine/BlueVoiceASREngine.swift
1
5729
/* * Copyright (c) 2017 STMicroelectronics – All rights reserved * The STMicroelectronics corporate logo is a trademark of STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name nor trademarks of STMicroelectronics International N.V. nor any other * STMicroelectronics company nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * - All of the icons, pictures, logos and other images that are provided with the source code * in a directory whose title begins with st_images may only be used for internal purposes and * shall not be redistributed to any third party or modified in any way. * * - Any redistributions in binary form shall not include the capability to display any of the * icons, pictures, logos and other images that are provided with the source code in a directory * whose title begins with st_images. * * 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 Foundation import UIKit /// List of possible error during the voice to text convertion enum BlueVoiceAsrRequestError:Int8,CustomStringConvertible { case NO_ERROR = 0; ///error diring the cominication case IO_CONNECTION_ERROR = 1; ///response parsing fail case RESPONSE_ERROR = 2; ///imposible send the request case REQUEST_FAILED = 3; /// valid respose but with a low confidence case LOW_CONFIDENCE=4 /// valid response but empyt case NOT_RECOGNIZED = 5; /// impossible to use the network case NETWORK_PROBLEM = 6; var description : String { switch self { case .NO_ERROR: return "Success"; case .IO_CONNECTION_ERROR: return "I/O Error"; case .RESPONSE_ERROR: return "Invalid Response"; case .REQUEST_FAILED: return "Invalid Request"; case .LOW_CONFIDENCE: return "Low Confidence Response"; case .NOT_RECOGNIZED: return "Not Recognizer"; case .NETWORK_PROBLEM: return "Network Error"; } } } /// Interface used to comunicate the voice to text results protocol BlueVoiceAsrRequestCallback{ /// call when the ASREngine has a valid response /// /// - Parameter withText: text extract from the last asr request func onAsrRequestSuccess(withText:String ); /// call when the ASREngine has a invalid reposse /// /// - Parameter error: error happen during the last asr request func onAsrRequestFail(error:BlueVoiceAsrRequestError); } protocol BlueVoiceASREngine{ /// It reveals if this engine needs an authentication key or not. var needAuthKey:Bool{get}; /// It reveals if this engine has a continuous recognizer or not. var hasContinuousRecognizer:Bool{get}; /// Engine name var name:String{get} /** * * @return */ /// It provide a dialog for ASR key insertion. /// /// - Returns: a UIViewController which allows the insertion of the /// ASR service activation key. It return null if the service doesn't need any key. func getAuthKeyDialog()->UIViewController?; /// Start the recognizer listener func startListener(); /// Stop the recognizer listener func stopListener(); /// Destroy the recognizer listener func destroyListener(); /// tell if the engine has a valid key inserted /// /// - Returns: if the engine has a valid key, or if it doesn't need one func hasLoadedAuthKey() ->Bool; /// send and audio voice sample to convert it to text /// /// - Parameters: /// - audio: audio sample to convert /// - callback: object where notify the operation results /// - Returns: true if the reuqest is correctly send func sendASRRequest(audio:Data, callback: BlueVoiceAsrRequestCallback) -> Bool; } /// utility object wuse to build an ASR Engine public class BlueVoiceASREngineUtil{ /// build the best ASR engine availbe for that language and sampling rate /// /// - Parameters: /// - samplingRateHz: audio sampling rate, in Hz /// - language: voice language /// - Returns: best available ASR engine for that languaga and sampling rate static func getEngine(samplingRateHz:UInt , language: BlueVoiceLangauge)->BlueVoiceASREngine{ return BlueVoiceGoogleASREngine(language:language,samplingRateHz:samplingRateHz); } }
bsd-3-clause
8bbacf540c9479e644d86f72cbe8b871
36.927152
100
0.700716
4.559713
false
false
false
false
varkor/firefox-ios
Extensions/ShareTo/InitialViewController.swift
1
6197
/* 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 import Storage private let LastUsedShareDestinationsKey = "LastUsedShareDestinations" @objc(InitialViewController) class InitialViewController: UIViewController, ShareControllerDelegate { var shareDialogController: ShareDialogController! lazy var profile: Profile = { return BrowserProfile(localName: "profile", app: nil) }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(white: 0.0, alpha: 0.66) // TODO: Is the correct color documented somewhere? } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) ExtensionUtils.extractSharedItemFromExtensionContext(self.extensionContext, completionHandler: { (item, error) -> Void in if let item = item where error == nil { dispatch_async(dispatch_get_main_queue()) { guard item.isShareable else { let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .Default) { _ in self.finish() }) self.presentViewController(alert, animated: true, completion: nil) return } self.presentShareDialog(item) } } else { self.extensionContext!.completeRequestReturningItems([], completionHandler: nil) } }) } // func shareControllerDidCancel(shareController: ShareDialogController) { UIView.animateWithDuration(0.25, animations: { () -> Void in self.shareDialogController.view.alpha = 0.0 }, completion: { (Bool) -> Void in self.dismissShareDialog() self.finish() }) } func finish() { self.extensionContext!.completeRequestReturningItems([], completionHandler: nil) } func shareController(shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) { setLastUsedShareDestinations(destinations) UIView.animateWithDuration(0.25, animations: { () -> Void in self.shareDialogController.view.alpha = 0.0 }, completion: { (Bool) -> Void in self.dismissShareDialog() if destinations.containsObject(ShareDestinationReadingList) { self.shareToReadingList(item) } if destinations.containsObject(ShareDestinationBookmarks) { self.shareToBookmarks(item) } self.extensionContext!.completeRequestReturningItems([], completionHandler: nil) }) } // // TODO: use Set. func getLastUsedShareDestinations() -> NSSet { if let destinations = NSUserDefaults.standardUserDefaults().objectForKey(LastUsedShareDestinationsKey) as? NSArray { return NSSet(array: destinations as [AnyObject]) } return NSSet(object: ShareDestinationBookmarks) } func setLastUsedShareDestinations(destinations: NSSet) { NSUserDefaults.standardUserDefaults().setObject(destinations.allObjects, forKey: LastUsedShareDestinationsKey) NSUserDefaults.standardUserDefaults().synchronize() } func presentShareDialog(item: ShareItem) { shareDialogController = ShareDialogController() shareDialogController.delegate = self shareDialogController.item = item shareDialogController.initialShareDestinations = getLastUsedShareDestinations() self.addChildViewController(shareDialogController) shareDialogController.view.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(shareDialogController.view) shareDialogController.didMoveToParentViewController(self) // Setup constraints for the dialog. We keep the dialog centered with 16 points of padding on both // sides. The dialog grows to max 380 points wide so that it does not look too big on landscape or // iPad devices. let views: NSDictionary = ["dialog": shareDialogController.view] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(16@751)-[dialog(<=380@1000)]-(16@751)-|", options: NSLayoutFormatOptions(), metrics: nil, views: (views as? [String : AnyObject])!)) let cx = NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0) cx.priority = 1000 // TODO: Why does UILayoutPriorityRequired give a linker error? SDK Bug? view.addConstraint(cx) view.addConstraint(NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)) // Fade the dialog in shareDialogController.view.alpha = 0.0 UIView.animateWithDuration(0.25, animations: { () -> Void in self.shareDialogController.view.alpha = 1.0 }, completion: nil) } func dismissShareDialog() { shareDialogController.willMoveToParentViewController(nil) shareDialogController.view.removeFromSuperview() shareDialogController.removeFromParentViewController() } // func shareToReadingList(item: ShareItem) { profile.readingList?.createRecordWithURL(item.url, title: item.title ?? "", addedBy: UIDevice.currentDevice().name) } func shareToBookmarks(item: ShareItem) { profile.bookmarks.shareItem(item) } }
mpl-2.0
8e6a62bb9b8df83bbbbaff888528dcfb
41.445205
147
0.663063
5.523173
false
false
false
false
mcrollin/safecaster
safecaster/RACBindings.swift
1
1536
// // RACBindings.swift // safecaster // // Created by Marc Rollin on 4/8/15. // Copyright (c) 2015 safecast. All rights reserved. // import Foundation import ReactiveCocoa // So I expect the ReactiveCocoa fellows to figure out a replacement API for the RAC macro. // Currently, I don't see one there, so we'll use this solution until an official one exists. // Pulled from http://www.scottlogic.com/blog/2014/07/24/mvvm-reactivecocoa-swift.html struct RAC { var target : NSObject! var keyPath : String! var nilValue : AnyObject! init(_ target: NSObject!, _ keyPath: String, nilValue: AnyObject? = nil) { self.target = target self.keyPath = keyPath self.nilValue = nilValue } func assignSignal(signal : RACSignal) { signal.setKeyPath(keyPath, onObject: target, nilValue: nilValue) } } extension NSObject { func RACObserve(target: NSObject!,_ keyPath: String) -> RACSignal{ return target.rac_valuesForKeyPath(keyPath, observer: self) } } infix operator <~ {} func <~ (rac: RAC, signal: RACSignal) { rac.assignSignal(signal) } infix operator ~> {} func ~> (signal: RACSignal, rac: RAC) { rac.assignSignal(signal) } extension RACSignal { func subscribeNextAs<T>(nextClosure:(T) -> ()) -> () { subscribeNext { (next: AnyObject!) -> () in let nextAsT = next as! T nextClosure(nextAsT) } } func filterNil() -> RACSignal! { return filter { $0 != nil } } }
cc0-1.0
cb6db4c2d1fe09a3cdc7e05865e91b3d
24.196721
93
0.632813
3.792593
false
false
false
false
tkremenek/swift
test/Concurrency/Runtime/async_taskgroup_throw_recover.swift
1
1672
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency -Xfrontend -disable-availability-checking -parse-as-library) | %FileCheck %s --dump-input=always // REQUIRES: executable_test // REQUIRES: concurrency // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime struct Boom: Error {} struct IgnoredBoom: Error {} @available(SwiftStdlib 5.5, *) func one() async -> Int { 1 } @available(SwiftStdlib 5.5, *) func boom() async throws -> Int { throw Boom() } @available(SwiftStdlib 5.5, *) func test_taskGroup_throws() async { let got: Int = try await withThrowingTaskGroup(of: Int.self) { group in group.spawn { try await boom() } do { while let r = try await group.next() { print("next: \(r)") } } catch { print("error caught in group: \(error)") let gc = group.isCancelled print("group cancelled: \(gc)") group.spawn { () async -> Int in let c = Task.isCancelled print("task 3 (cancelled: \(c))") return 3 } guard let third = try! await group.next() else { print("task group failed to get 3") return 0 } print("task group returning normally: \(third)") return third } fatalError("Should have thrown and handled inside the catch block") } // CHECK: error caught in group: Boom() // CHECK: group cancelled: false // CHECK: task 3 (cancelled: false) // CHECK: task group returning normally: 3 // CHECK: got: 3 print("got: \(got)") } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await test_taskGroup_throws() } }
apache-2.0
1a91a94dd43d493767308b1b8297afb8
23.231884
173
0.628589
3.826087
false
false
false
false
tkremenek/swift
test/SourceKit/CodeComplete/complete_working_directory.swift
40
382
import Foo // REQUIRES: objc_interop // RUN: %sourcekitd-test -req=complete.open -pos=2:1 -req-opts=hidelowpriority=0 %s -- %s -F libIDE-mock-sdk -working-directory %S/../Inputs | %FileCheck %s // RUN: %sourcekitd-test -req=complete.open -pos=2:1 -req-opts=hidelowpriority=0 %s -- %s -Xcc -F -Xcc libIDE-mock-sdk -working-directory %S/../Inputs | %FileCheck %s // CHECK: fooFunc
apache-2.0
b09926fbb914ed83b3e477ecd7b1b058
46.75
166
0.691099
2.850746
false
true
false
false
realtime-framework/RealtimeMessaging-iOS-Swift3
Pod/Classes/RealtimeMessaging-iOS-Swift.swift
1
121614
// // OrtcClient.swift // OrtcClient // // Created by João Caixinha on 21/1/16. // Copyright (c) 2016 Realtime.co. All rights reserved. // import Foundation import UIKit import Starscream fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } let heartbeatDefaultTime = 15// Heartbeat default interval time let heartbeatDefaultFails = 3// Heartbeat default max fails let heartbeatMaxTime = 60 let heartbeatMinTime = 10 let heartbeatMaxFails = 6 let heartbeatMinFails = 1 /** * Delegation protocol for ortc client events */ public protocol OrtcClientDelegate{ ///--------------------------------------------------------------------------------------- /// @name Instance Methods ///-------------------------------------------------------------------------------------- /** * Occurs when the client connects. * * - parameter ortc: The ORTC object. */ func onConnected(_ ortc: OrtcClient) /** * Occurs when the client disconnects. * * - parameter ortc: The ORTC object. */ func onDisconnected(_ ortc: OrtcClient) /** * Occurs when the client subscribes to a channel. * * - parameter ortc: The ORTC object. * - parameter channel: The channel name. */ func onSubscribed(_ ortc: OrtcClient, channel: String) /** * Occurs when the client unsubscribes from a channel. * * - parameter ortc: The ORTC object. * - parameter channel: The channel name. */ func onUnsubscribed(_ ortc: OrtcClient, channel: String) /** * Occurs when there is an exception. * * - parameter ortc: The ORTC object. * - parameter error: The occurred exception. */ func onException(_ ortc: OrtcClient, error: NSError) /** * Occurs when the client attempts to reconnect. * * - parameter ortc: The ORTC object. */ func onReconnecting(_ ortc: OrtcClient) /** * Occurs when the client reconnects. * * - parameter ortc: The ORTC object. */ func onReconnected(_ ortc: OrtcClient) } /** *Part of the The Realtime® Framework, Realtime Cloud Messaging (aka ORTC) is a secure, fast and highly scalable cloud-hosted Pub/Sub real-time message broker for web and mobile apps. * *If your website or mobile app has data that needs to be updated in the user’s interface as it changes (e.g. real-time stock quotes or ever changing social news feed) Realtime Cloud Messaging is the reliable, easy, unbelievably fast, “works everywhere” solution. Example: ```swift import RealtimeMessaging_iOS_Swift class OrtcClass: NSObject, OrtcClientDelegate{ let APPKEY = "<INSERT_YOUR_APP_KEY>" let TOKEN = "guest" let METADATA = "swift example" let URL = "https://ortc-developers.realtime.co/server/ssl/2.1/" var ortc: OrtcClient? func connect() { self.ortc = OrtcClient.ortcClientWithConfig(self) self.ortc!.connectionMetadata = METADATA self.ortc!.clusterUrl = URL self.ortc!.connect(APPKEY, authenticationToken: TOKEN) } func onConnected(ortc: OrtcClient){ NSLog("CONNECTED") ortc.subscribe("SOME_CHANNEL", subscribeOnReconnected: true, onMessage: { (ortcClient:OrtcClient!, channel:String!, message:String!) -> Void in NSLog("Receive message: %@ on channel: %@", message!, channel!) }) } func onDisconnected(ortc: OrtcClient){ // Disconnected } func onSubscribed(ortc: OrtcClient, channel: String){ // Subscribed to the channel // Send a message ortc.send(channel, "Hello world!!!") } func onUnsubscribed(ortc: OrtcClient, channel: String){ // Unsubscribed from the channel 'channel' } func onException(ortc: OrtcClient, error: NSError){ // Exception occurred } func onReconnecting(ortc: OrtcClient){ // Reconnecting } func onReconnected(ortc: OrtcClient){ // Reconnected } } */ open class OrtcClient: NSObject, WebSocketDelegate { ///--------------------------------------------------------------------------------------- /// @name Properties ///--------------------------------------------------------------------------------------- enum opCodes : Int { case opValidate case opSubscribe case opUnsubscribe case opException case opAck } enum errCodes : Int { case errValidate case errSubscribe case errSubscribeMaxSize case errUnsubscribeMaxSize case errSendMaxSize } let JSON_PATTERN: String = "^a\\[\"(.*?)\"\\]$" let OPERATION_PATTERN: String = "^a\\[\"\\{\\\\\"op\\\\\":\\\\\"(.*?[^\"]+)\\\\\",(.*?)\\}\"\\]$" let VALIDATED_PATTERN: String = "^(\\\\\"up\\\\\":){1}(.*?)(,\\\\\"set\\\\\":(.*?))?$" let CHANNEL_PATTERN: String = "^\\\\\"ch\\\\\":\\\\\"(.*?)\\\\\"$" let EXCEPTION_PATTERN: String = "^\\\\\"ex\\\\\":\\{(\\\\\"op\\\\\":\\\\\"(.*?[^\"]+)\\\\\",)?(\\\\\"ch\\\\\":\\\\\"(.*?)\\\\\",)?\\\\\"ex\\\\\":\\\\\"(.*?)\\\\\"\\}$" let RECEIVED_PATTERN: String = "^a\\[\"\\{\\\\\"ch\\\\\":\\\\\"(.*?)\\\\\",\\\\\"m\\\\\":\\\\\"([\\s\\S]*?)\\\\\"\\}\"\\]$" let RECEIVED_PATTERN_FILTERED: String = "^a\\[\"\\{\\\\\"ch\\\\\":\\\\\"(.*?)\\\\\",\\\\\"f\\\\\":(.*),\\\\\"m\\\\\":\\\\\"([\\s\\S]*?)\\\\\"\\}\"\\]$" let MULTI_PART_MESSAGE_PATTERN: String = "^(.[^_]*?)_(.[^-]*?)-(.[^_]*?)_([\\s\\S]*?)$" let CLUSTER_RESPONSE_PATTERN: String = "^var SOCKET_SERVER = \\\"(.*?)\\\";$" let DEVICE_TOKEN_PATTERN: String = "[0-9A-Fa-f]{64}" let MAX_MESSAGE_SIZE: Int = 600 let MAX_CHANNEL_SIZE: Int = 100 let MAX_CONNECTION_METADATA_SIZE: Int = 256 var SESSION_STORAGE_NAME: String = "ortcsession-" let PLATFORM: String = "Apns" var webSocket: WebSocket? var ortcDelegate: OrtcClientDelegate? var subscribedChannels: NSMutableDictionary? var pendingPublishMessages: NSMutableDictionary? var permissions: NSMutableDictionary? var messagesBuffer: NSMutableDictionary? var opCases: NSMutableDictionary? var errCases: NSMutableDictionary? /**Is the acount application key*/ open var applicationKey: String? /**Is the authentication token for this client*/ open var authenticationToken: String? /**Sets if client url is from cluster*/ open var isCluster: Bool? = true var isConnecting: Bool? var isReconnecting: Bool? var hasConnectedFirstTime: Bool? var stopReconnecting: Bool? var doFallback: Bool? var sessionCreatedAt: Date? var sessionExpirationTime: Int? // Time in seconds var heartbeatTime: Int? // = heartbeatDefaultTime; // Heartbeat interval time var heartbeatFails: Int? // = heartbeatDefaultFails; // Heartbeat max fails var heartbeatTimer: Timer? open var heartbeatActive: Bool? var pid: NSString? /**Client url connection*/ open var url: NSString? /**Client url connection*/ open var clusterUrl: NSString? /**Client connection metadata*/ open var connectionMetadata: NSString? var announcementSubChannel: NSString? var sessionId: NSString? var connectionTimeout: Int32? var publishTimeout: Double? var partsSentInterval:Timer? /**Client connection state*/ var sema = DispatchSemaphore(value: 0) open var isConnected: Bool? //MARK: Public methods /** * Initializes a new instance of the ORTC class. * * - parameter delegate: The object holding the ORTC callbacks, usually 'self'. * * - returns: New instance of the OrtcClient class. */ open static func ortcClientWithConfig(_ delegate: OrtcClientDelegate) -> OrtcClient{ return OrtcClient(config: delegate) } init(config delegate: OrtcClientDelegate) { super.init() if opCases == nil { opCases = NSMutableDictionary(capacity: 4) opCases!["ortc-validated"] = NSNumber(value: opCodes.opValidate.rawValue as Int) opCases!["ortc-subscribed"] = NSNumber(value: opCodes.opSubscribe.rawValue as Int) opCases!["ortc-unsubscribed"] = NSNumber(value: opCodes.opUnsubscribe.rawValue as Int) opCases!["ortc-error"] = NSNumber(value: opCodes.opException.rawValue as Int) opCases!["ortc-ack"] = NSNumber(value: opCodes.opAck.rawValue as Int) } if errCases == nil { errCases = NSMutableDictionary(capacity: 5) errCases!["validate"] = NSNumber(value: errCodes.errValidate.rawValue as Int) errCases!["subscribe"] = NSNumber(value: errCodes.errSubscribe.rawValue as Int) errCases!["subscribe_maxsize"] = NSNumber(value: errCodes.errSubscribeMaxSize.rawValue as Int) errCases!["unsubscribe_maxsize"] = NSNumber(value: errCodes.errUnsubscribeMaxSize.rawValue as Int) errCases!["send_maxsize"] = NSNumber(value: errCodes.errSendMaxSize.rawValue as Int) } //apply properties self.ortcDelegate = delegate connectionTimeout = 5 publishTimeout = 5 // seconds sessionExpirationTime = 30 // minutes isConnected = false isConnecting = false isReconnecting = false hasConnectedFirstTime = false doFallback = true self.permissions = nil self.subscribedChannels = NSMutableDictionary() self.messagesBuffer = NSMutableDictionary() NotificationCenter.default.addObserver(self, selector: #selector(OrtcClient.receivedNotification(_:)), name: NSNotification.Name(rawValue: "ApnsNotification"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(OrtcClient.receivedNotification(_:)), name: NSNotification.Name(rawValue: "ApnsRegisterError"), object: nil) heartbeatTime = heartbeatDefaultTime // Heartbeat interval time heartbeatFails = heartbeatDefaultFails // Heartbeat max fails heartbeatTimer = nil heartbeatActive = false } /** * Connects with the application key and authentication token. * * - parameter applicationKey: The application key. * - parameter authenticationToken: The authentication token. */ open func connect(_ applicationKey:NSString?, authenticationToken:NSString?){ if isConnected == true { self.delegateExceptionCallback(self, error: self.generateError("Already connected")) } else if self.url == nil && self.clusterUrl == nil { self.delegateExceptionCallback(self, error: self.generateError("URL and Cluster URL are null or empty")) } else if applicationKey == nil { self.delegateExceptionCallback(self, error: self.generateError("Application Key is null or empty")) } else if authenticationToken == nil { self.delegateExceptionCallback(self, error: self.generateError("Authentication Token is null or empty")) } else if self.isCluster == false && !self.ortcIsValidUrl(self.url as! String) { self.delegateExceptionCallback(self, error: self.generateError("Invalid URL")) } else if self.isCluster == true && !self.ortcIsValidUrl(self.clusterUrl as! String) { self.delegateExceptionCallback(self, error: self.generateError("Invalid Cluster URL")) } else if !self.ortcIsValidInput(applicationKey as! String) { self.delegateExceptionCallback(self, error: self.generateError("Application Key has invalid characters")) } else if !self.ortcIsValidInput(authenticationToken as! String) { self.delegateExceptionCallback(self, error: self.generateError("Authentication Token has invalid characters")) } else if self.announcementSubChannel != nil && !self.ortcIsValidInput(self.announcementSubChannel as! String) { self.delegateExceptionCallback(self, error: self.generateError("Announcement Subchannel has invalid characters")) } else if !self.isEmpty(self.connectionMetadata) && self.connectionMetadata!.length > MAX_CONNECTION_METADATA_SIZE { self.delegateExceptionCallback(self, error: self.generateError("Connection metadata size exceeds the limit of \(MAX_CONNECTION_METADATA_SIZE) characters")) } else if self.isConnecting == true { self.delegateExceptionCallback(self, error: self.generateError("Already trying to connect")) } else { self.applicationKey = applicationKey as? String self.authenticationToken = authenticationToken as? String self.isConnecting = true self.isReconnecting = false self.stopReconnecting = false self.doConnect(self) } } /** * Disconnects. */ open func disconnect(){ // Stop the connecting/reconnecting process stopReconnecting = true isConnecting = false isReconnecting = false hasConnectedFirstTime = false // Clear subscribed channels self.subscribedChannels?.removeAllObjects() /* * Sanity Checks. */ if isConnected == false { self.delegateExceptionCallback(self, error: self.generateError("Not connected")) } else { self.processDisconnect(true) } } /** * Publish a message to a channel. * * - parameter channel: The channel name. * - parameter message: The message to publish. * - parameter ttl: The message expiration time in seconds (0 for maximum allowed ttl). * - parameter callback: Returns error if message publish was not successful or published message unique id (seqId) if sucessfully published */ open func publish(_ channel:NSString, message:NSString, ttl:NSNumber, callback:@escaping (_ error:NSError?,_ seqId:NSString?)->Void){ var message = message if self.isConnected == false { self.delegateExceptionCallback(self, error: self.generateError("Not connected")) } else if self.isEmpty(channel) { self.delegateExceptionCallback(self, error: self.generateError("Channel is null or empty")) } else if !self.ortcIsValidInput(channel as String) { self.delegateExceptionCallback(self, error: self.generateError("Channel has invalid characters")) } else if self.isEmpty(message) { self.delegateExceptionCallback(self, error: self.generateError("Message is null or empty")) } else { message = message.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\n", with: "\\n") as NSString message = message.replacingOccurrences(of: "\"", with: "\\\"") as NSString let channelBytes: Data = channel.data(using: String.Encoding.utf8.rawValue)! if channelBytes.count >= MAX_CHANNEL_SIZE { self.delegateExceptionCallback(self, error: self.generateError("Channel size exceeds the limit of \(MAX_CHANNEL_SIZE) characters")) } else { let domainChannelIndex: Int = channel.range(of: ":").location var channelToValidate: NSString = channel var hashPerm: String? if domainChannelIndex != NSNotFound { channelToValidate = (channel as NSString).substring(to: domainChannelIndex + 1) as NSString channelToValidate = "\(channelToValidate)*" as NSString } if self.permissions != nil { if self.permissions![channelToValidate] != nil { hashPerm = self.permissions!.object(forKey: channelToValidate) as? String } else{ hashPerm = self.permissions!.object(forKey: channel) as? String } } if self.permissions != nil && hashPerm == nil { self.delegateExceptionCallback(self, error: self.generateError("No permission found to send to the channel '\(channel)'")) } else { let messageBytes: Data = Data(bytes:(message.utf8String!), count: message.lengthOfBytes(using: String.Encoding.utf8.rawValue)) let messageParts: NSMutableArray = NSMutableArray() var pos: Int = 0 var remaining: Int let messageId: String = self.generateId(8) while (UInt(messageBytes.count - pos) > 0) { remaining = messageBytes.count - pos let arraySize: Int if remaining >= MAX_MESSAGE_SIZE-channelBytes.count { arraySize = MAX_MESSAGE_SIZE-channelBytes.count } else { arraySize = remaining } let messageBytesTemp = UnsafeRawPointer((messageBytes as NSData).bytes).assumingMemoryBound(to: UInt8.self) let messagePart = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(messageBytesTemp) + pos, count: arraySize)) let res:NSString? = NSString(bytes: messagePart, length: arraySize, encoding: String.Encoding.utf8.rawValue) if res != nil{ messageParts.add(res!) } pos += arraySize } var err:String = "" if pendingPublishMessages == nil{ pendingPublishMessages = NSMutableDictionary() } if((pendingPublishMessages?.object(forKey: messageId)) != nil){ err = "Message id conflict. Please retry publishing the message"; } else { DispatchQueue.main.async(execute: { var ackTimeout = Timer.scheduledTimer(timeInterval: Double(self.publishTimeout!), target: self, selector: #selector(self.ACKTimeout(_:)), userInfo: messageId, repeats: false) var pendingMsg = ["totalNumOfParts": messageParts.count, "callback": callback, "timeout": ackTimeout] as [String : Any] self.pendingPublishMessages?.setObject(pendingMsg, forKey: messageId as NSCopying) }) if(messageParts.count < 20){ var counter: Int32 = 1 for messageToSend in messageParts { let encodedData: NSString = messageToSend as! NSString let aString: NSString = "\"publish;\(applicationKey!);\(authenticationToken!);\(channel);\(ttl);\(hashPerm);\(messageId)_\(counter)-\((Int32(messageParts.count)))_\(encodedData)\"" as NSString self.webSocket!.write(string:aString as String, completion:nil) counter += 1 } }else{ var counter:Int = 1 var partsSent:Int = 0 DispatchQueue.global(qos: .userInitiated).async { while true{ if self.isConnected == true && self.webSocket != nil{ var currentPart:Int = partsSent; var totalParts:Int = messageParts.count; let encodedData: NSString = messageParts.object(at: currentPart) as! NSString let aString: NSString = "\"publish;\(self.applicationKey!);\(self.authenticationToken!);\(channel);\(ttl);\(hashPerm);\(messageId)_\(counter)-\((Int32(messageParts.count)))_\(encodedData)\"" as NSString self.webSocket!.write(string:aString as String, completion:nil) partsSent += 1 if partsSent == messageParts.count { break } sleep(UInt32(0.1)) }else{ break } } } } } } } } } func ACKTimeout(_ timer: Timer){ let messageId = timer.userInfo as! String var err:String = "" if self.pendingPublishMessages?.object(forKey: messageId) != nil{ err = "Message publish timeout after \(self.publishTimeout) seconds" if (self.pendingPublishMessages?.object(forKey: messageId) as! NSDictionary).object(forKey: "callback") != nil { let dictionary:NSDictionary = self.pendingPublishMessages?.object(forKey: messageId) as! NSDictionary var callbackP: ((_ error:NSError?,_ seqId:NSString?)->Void) = dictionary.object(forKey: "callback") as! ((NSError?, NSString?) -> Void) callbackP(self.generateError(err), nil) } self.pendingPublishMessages?.removeObject(forKey: messageId) } } /** * Sends a message to a channel. * * - parameter channel: The channel name. * - parameter message: The message to send. */ open func send(_ channel:NSString, message:NSString){ var message = message if self.isConnected == false { self.delegateExceptionCallback(self, error: self.generateError("Not connected")) } else if self.isEmpty(channel) { self.delegateExceptionCallback(self, error: self.generateError("Channel is null or empty")) } else if !self.ortcIsValidInput(channel as String) { self.delegateExceptionCallback(self, error: self.generateError("Channel has invalid characters")) } else if self.isEmpty(message) { self.delegateExceptionCallback(self, error: self.generateError("Message is null or empty")) } else { message = message.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\n", with: "\\n") as NSString message = message.replacingOccurrences(of: "\"", with: "\\\"") as NSString let channelBytes: Data = channel.data(using: String.Encoding.utf8.rawValue)! if channelBytes.count >= MAX_CHANNEL_SIZE { self.delegateExceptionCallback(self, error: self.generateError("Channel size exceeds the limit of \(MAX_CHANNEL_SIZE) characters")) } else { let domainChannelIndex: Int = channel.range(of: ":").location var channelToValidate: NSString = channel var hashPerm: String? if domainChannelIndex != NSNotFound { channelToValidate = (channel as NSString).substring(to: domainChannelIndex + 1) as NSString channelToValidate = "\(channelToValidate)*" as NSString } if self.permissions != nil { if self.permissions![channelToValidate] != nil { hashPerm = self.permissions!.object(forKey: channelToValidate) as? String } else{ hashPerm = self.permissions!.object(forKey: channel) as? String } } if self.permissions != nil && hashPerm == nil { self.delegateExceptionCallback(self, error: self.generateError("No permission found to send to the channel '\(channel)'")) } else { let messageBytes: Data = Data(bytes:(message.utf8String!), count: message.lengthOfBytes(using: String.Encoding.utf8.rawValue)) let messageParts: NSMutableArray = NSMutableArray() var pos: Int = 0 var remaining: Int let messageId: String = self.generateId(8) while (UInt(messageBytes.count - pos) > 0) { remaining = messageBytes.count - pos let arraySize: Int if remaining >= MAX_MESSAGE_SIZE-channelBytes.count { arraySize = MAX_MESSAGE_SIZE-channelBytes.count } else { arraySize = remaining } let messageBytesTemp = UnsafeRawPointer((messageBytes as NSData).bytes).assumingMemoryBound(to: UInt8.self) let messagePart = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(messageBytesTemp) + pos, count: arraySize)) let res:NSString? = NSString(bytes: messagePart, length: arraySize, encoding: String.Encoding.utf8.rawValue) if res != nil{ messageParts.add(res!) } pos += arraySize } var counter: Int32 = 1 for messageToSend in messageParts { let encodedData: NSString = messageToSend as! NSString let aString: NSString = "\"send;\(applicationKey!);\(authenticationToken!);\(channel);\(hashPerm);\(messageId)_\(counter)-\((Int32(messageParts.count)))_\(encodedData)\"" as NSString self.webSocket?.write(string:aString as String, completion:nil) counter += 1 } } } } } /** * Subscribes to a channel to receive messages sent to it. * * - parameter channel: The channel name. * - parameter subscribeOnReconnected: Indicates whether the client should subscribe to the channel when reconnected (if it was previously subscribed when connected). * - parameter onMessage: The callback called when a message arrives at the channel. */ open func subscribe(_ channel:String, subscribeOnReconnected:Bool, onMessage:@escaping (_ ortc:OrtcClient, _ channel:String, _ message:String)->Void){ self.subscribeChannel(channel, withNotifications: WITHOUT_NOTIFICATIONS, subscribeOnReconnect: subscribeOnReconnected, withFilter: false, filter: "", onMessage: onMessage, onMessageWithFilter: nil) } /** * Subscribes to a channel to receive messages sent to it with given options. * * Options dictionary example: * * ```swift * var options:[String : Any] = ["channel":channel, * "subscribeOnReconnected":true, * "subscriberId":subscriberId] * * self.subscribeWithOptions(options as NSDictionary?) { (client, dictionary) in * //your code * } * ``` * * - parameter options: The subscription options dictionary,<br> * <code>options = {<br> * &nbsp;&nbsp;&nbsp;&nbsp; channel,<br> * &nbsp;&nbsp;&nbsp;&nbsp; subscribeOnReconnected, // optional, default = true<br> * &nbsp;&nbsp;&nbsp;&nbsp; withNotifications (Bool), // optional, default = false, push notifications as in subscribeWithNotifications<br> * &nbsp;&nbsp;&nbsp;&nbsp; filter, // optional, default = "", the subscription filter as in subscribeWithFilter<br> * &nbsp;&nbsp;&nbsp;&nbsp; subscriberId // optional, default = "", the subscriberId as in subscribeWithBuffer<br> * }<br></code> * - parameter onMessageWithOptionsCallback: The callback called when a message arrives at the channel, data is provided in a dictionary. */ open func subscribeWithOptions(_ options:NSDictionary? ,onMessageWithOptionsCallback:@escaping (_ ortc:OrtcClient, _ msgOptions:NSDictionary)->Void){ if(options != nil) { var subscribeOnReconnected:Bool? = options!.object(forKey: "subscribeOnReconnected") as? Bool if subscribeOnReconnected == nil { subscribeOnReconnected = true } self._subscribeOptions(channel: options!.object(forKey: "channel") as! String, subscribeOnReconnected: subscribeOnReconnected!, withNotifications: options!.object(forKey: "withNotifications") as? Bool, filter: options!.object(forKey: "filter") as? String, subscriberId: options!.object(forKey: "subscriberId") as? String, onMessageWithOptionsCallback: onMessageWithOptionsCallback) } else { self.delegateExceptionCallback(self, error: self.generateError("subscribeWithOptions called with no options")) } } /** * Subscribes to a channel to receive messages published to it. * * - parameter channel: The channel name. * - parameter subscriberId: The subscriberId associated to the channel. * - parameter onMessageWithBufferCallback: The callback called when a message arrives at the channel and message seqId number. */ open func subscribeWithBuffer(channel:String, subscriberId:String, onMessageWithBufferCallback:@escaping (_ ortc:OrtcClient, _ channel:String, _ seqId:String, _ message:String)->Void){ var options:[String : Any] = ["channel":channel, "subscribeOnReconnected":true, "subscriberId":subscriberId] self.subscribeWithOptions(options as NSDictionary?) { (client, dictionary) in onMessageWithBufferCallback(client, dictionary.object(forKey: "channel") as! String, dictionary.object(forKey: "seqId") as! String, dictionary.object(forKey: "message") as! String) } } open func _subscribeOptions(channel:String, subscribeOnReconnected:Bool, withNotifications:Bool?, filter:String?, subscriberId:String?, onMessageWithOptionsCallback: @escaping (_ ortc:OrtcClient, _ msgOptions: NSDictionary)->Void){ if self.isConnected == false { self.delegateExceptionCallback(self, error: self.generateError("Not connected")) } else if self.isEmpty(channel as AnyObject?) { self.delegateExceptionCallback(self, error: self.generateError("Channel is null or empty")) } else if !self.ortcIsValidInput(channel as String) { self.delegateExceptionCallback(self, error: self.generateError("Channel has invalid characters")) } else if subscriberId != nil && !self.ortcIsValidInput(subscriberId!) { self.delegateExceptionCallback(self, error: self.generateError("subscriberId has invalid characters")) } else if self.subscribedChannels?.object(forKey: channel) != nil && (self.subscribedChannels?.object(forKey: channel) as! ChannelSubscription).isSubscribing == true { self.delegateExceptionCallback(self, error: self.generateError("Already subscribing to the channel \'' + channel + '\''")) } else if self.subscribedChannels?.object(forKey: channel) != nil && (self.subscribedChannels?.object(forKey: channel) as! ChannelSubscription).isSubscribed == true { self.delegateExceptionCallback(self, error: self.generateError("Already subscribed to the channel \'' + channel + '\'")) } else if channel.lengthOfBytes(using: String.Encoding.utf8) > MAX_CHANNEL_SIZE { self.delegateExceptionCallback(self, error: self.generateError("Channel size exceeds the limit of ' + channelMaxSize + ' characters")) } else { var _subscribeOnReconnected:Bool = false; var _regId:String; var _filter:String; var _subscriberId:String = ""; if (subscribeOnReconnected == true) { _subscribeOnReconnected = true; }else{ _subscribeOnReconnected = false } if(withNotifications == nil || OrtcClient.getDEVICE_TOKEN() == nil) { _regId = ""; }else{ _regId = OrtcClient.getDEVICE_TOKEN()! } if(filter == nil) { _filter = ""; }else{ _filter = filter! } if(subscriberId == nil) { _subscriberId = ""; }else{ _subscriberId = subscriberId! } var domainChannelCharacterIndex:[String] = (channel as! NSString).components(separatedBy: ":"); var channelToValidate:NSString = (channel as! NSString); if (domainChannelCharacterIndex.count > 0) { channelToValidate = domainChannelCharacterIndex[0] as NSString; } var hashPerm:NSString? = self.checkChannelPermissions(channel as NSString) if (permissions == nil || (permissions != nil && hashPerm != nil)) { if (subscribedChannels?.object(forKey: channel) == nil) { // Instantiate ChannelSubscription var channelSubscription:ChannelSubscription = ChannelSubscription() // Set channelSubscription properties channelSubscription.isSubscribing = true; channelSubscription.isSubscribed = false; channelSubscription.subscribeOnReconnected = _subscribeOnReconnected; channelSubscription.withOptions = true; channelSubscription.onMessageWithOptions = onMessageWithOptionsCallback; channelSubscription.subscriberId = _subscriberId; channelSubscription.regId = _regId; channelSubscription.withNotifications = (_regId == "" ? true : false); // Add to subscribed channels dictionary subscribedChannels!.setObject(channelSubscription, forKey: channel as NSCopying) } var aString:String = "\"subscribeoptions;\(applicationKey!);\(authenticationToken!);\(channel);\(_subscriberId);\(_regId);\(PLATFORM);\(hashPerm);\(_filter)\"" if (self.isEmpty(aString as AnyObject?) == false) { self.webSocket?.write(string: aString) } } } } /** * Subscribes to a channel to receive messages sent to it. * * - parameter channel: The channel name. * - parameter subscribeOnReconnected: Indicates whether the client should subscribe to the channel when reconnected (if it was previously subscribed when connected). * - parameter filter: The filter to apply to the channel messages. * - parameter onMessageWithFilter: The callback called when a message arrives at the channel. */ open func subscribeWithFilter(_ channel:String, subscribeOnReconnected:Bool, filter:String ,onMessageWithFilter:@escaping (_ ortc:OrtcClient, _ channel:String, _ filtered:Bool, _ message:String)->Void){ self.subscribeChannel(channel, withNotifications: WITHOUT_NOTIFICATIONS, subscribeOnReconnect: subscribeOnReconnected, withFilter: true, filter: filter, onMessage: nil, onMessageWithFilter: onMessageWithFilter) } /** * Subscribes to a channel, with Push Notifications Service, to receive messages sent to it. * * - parameter channel: The channel name. Only channels with alphanumeric name and the following characters: "_" "-" ":" are allowed. * - parameter subscribeOnReconnected: Indicates whether the client should subscribe to the channel when reconnected (if it was previously subscribed when connected). * - parameter onMessage: The callback called when a message or a Push Notification arrives at the channel. */ open func subscribeWithNotifications(_ channel:String, subscribeOnReconnected:Bool, onMessage:@escaping (_ ortc:OrtcClient, _ channel:String, _ message:String)->Void){ self.subscribeChannel(channel, withNotifications: WITH_NOTIFICATIONS, subscribeOnReconnect: subscribeOnReconnected, withFilter: false, filter: "", onMessage: onMessage, onMessageWithFilter: nil) } /** * Unsubscribes from a channel to stop receiving messages sent to it. * * - parameter channel: The channel name. */ open func unsubscribe(_ channel:String){ let channelSubscription:ChannelSubscription? = (self.subscribedChannels!.object(forKey: channel as String) as? ChannelSubscription); if isConnected == false { self.delegateExceptionCallback(self, error: self.generateError("Not connected")) } else if self.isEmpty(channel as AnyObject?) { self.delegateExceptionCallback(self, error: self.generateError("Channel is null or empty")) } else if !self.ortcIsValidInput(channel) { self.delegateExceptionCallback(self, error: self.generateError("Channel has invalid characters")) } else if channelSubscription != nil && channelSubscription!.isSubscribed == false { self.delegateExceptionCallback(self, error: self.generateError("Not subscribed to the channel \(channel)")) } else { let channelBytes: Data = Data(bytes: (channel as NSString).utf8String!, count: channel.lengthOfBytes(using: String.Encoding.utf8)) if channelBytes.count >= MAX_CHANNEL_SIZE { self.delegateExceptionCallback(self, error: self.generateError("Channel size exceeds the limit of \(MAX_CHANNEL_SIZE) characters")) } else { var aString: NSString = NSString() if channelSubscription?.withNotifications == true { if !self.isEmpty(OrtcClient.getDEVICE_TOKEN()! as AnyObject?) { aString = "\"unsubscribe;\(applicationKey!);\(channel);\(OrtcClient.getDEVICE_TOKEN()!);\(PLATFORM)\"" as NSString } else { aString = "\"unsubscribe;\(applicationKey!);\(channel)\"" as NSString } } else { aString = "\"unsubscribe;\(applicationKey!);\(channel)\"" as NSString } if !self.isEmpty(aString) { self.webSocket?.write(string:aString as String, completion: nil) } } } } func checkChannelSubscription(_ channel:String, withNotifications:Bool) -> Bool{ let channelSubscription:ChannelSubscription? = self.subscribedChannels!.object(forKey: channel as NSString) as? ChannelSubscription if self.isConnected == false{ self.delegateExceptionCallback(self, error: self.generateError("Not connected")) return false } else if self.isEmpty(channel as AnyObject?) { self.delegateExceptionCallback(self, error: self.generateError("Channel is null or empty")) return false } else if withNotifications { if !self.ortcIsValidChannelForMobile(channel) { self.delegateExceptionCallback(self, error: self.generateError("Channel has invalid characters")) return false } } else if !self.ortcIsValidInput(channel) { self.delegateExceptionCallback(self, error: self.generateError("Channel has invalid characters")) return false } else if channelSubscription?.isSubscribing == true { self.delegateExceptionCallback(self, error: self.generateError("Already subscribing to the channel \(channel)")) return false } else if channelSubscription?.isSubscribed == true { self.delegateExceptionCallback(self, error: self.generateError("Already subscribed to the channel \(channel)")) return false } else { let channelBytes: Data = Data(bytes: (channel as NSString).utf8String!, count: channel.lengthOfBytes(using: String.Encoding.utf8)) if channelBytes.count >= MAX_CHANNEL_SIZE { self.delegateExceptionCallback(self, error: self.generateError("Channel size exceeds the limit of \(MAX_CHANNEL_SIZE) characters")) return false } } return true } func checkChannelPermissions(_ channel:NSString)->NSString?{ let domainChannelIndex: Int = Int(channel.range(of: ":").location) var channelToValidate: NSString = channel var hashPerm: NSString? if domainChannelIndex != NSNotFound { channelToValidate = channel.substring(to: domainChannelIndex+1) as NSString channelToValidate = "\(channelToValidate)*" as NSString } if self.permissions != nil { hashPerm = (self.permissions![channelToValidate] != nil ? self.permissions![channelToValidate] : self.permissions![channel]) as? NSString return hashPerm } if self.permissions != nil && hashPerm == nil { self.delegateExceptionCallback(self, error: self.generateError("No permission found to subscribe to the channel '\(channel)'")) return nil } return hashPerm } /** * Indicates whether is subscribed to a channel or not. * * - parameter channel: The channel name. * * - returns: TRUE if subscribed to the channel or FALSE if not. */ open func isSubscribed(_ channel:String) -> NSNumber?{ var result: NSNumber? /* * Sanity Checks. */ if isConnected == false { self.delegateExceptionCallback(self, error: self.generateError("Not connected")) } else if self.isEmpty(channel as AnyObject?) { self.delegateExceptionCallback(self, error: self.generateError("Channel is null or empty")) } else if !self.ortcIsValidInput(channel) { self.delegateExceptionCallback(self, error: self.generateError("Channel has invalid characters")) } else { result = NSNumber(value: false as Bool) let channelSubscription:ChannelSubscription? = self.subscribedChannels!.object(forKey: channel) as? ChannelSubscription if channelSubscription != nil && channelSubscription!.isSubscribed == true { result = NSNumber(value: true as Bool) }else{ result = NSNumber(value: false as Bool) } } return result } /** Saves the channels and its permissions for the authentication token in the ORTC server. @warning This function will send your private key over the internet. Make sure to use secure connection. - parameter url: ORTC server URL. - parameter isCluster: Indicates whether the ORTC server is in a cluster. - parameter authenticationToken: The authentication token generated by an application server (for instance: a unique session ID). - parameter authenticationTokenIsPrivate: Indicates whether the authentication token is private (1) or not (0). - parameter applicationKey: The application key provided together with the ORTC service purchasing. - parameter timeToLive: The authentication token time to live (TTL), in other words, the allowed activity time (in seconds). - parameter privateKey: The private key provided together with the ORTC service purchasing. - parameter permissions: The channels and their permissions (w: write, r: read, p: presence, case sensitive). - return: TRUE if the authentication was successful or FALSE if it was not. */ open func saveAuthentication(_ aUrl:String, isCluster:Bool, authenticationToken:String, authenticationTokenIsPrivate:Bool, applicationKey:String, timeToLive:Int, privateKey:String, permissions:NSMutableDictionary?)->Bool{ /* * Sanity Checks. */ if self.isEmpty(aUrl as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Url"), reason: "URL is null or empty", userInfo: nil).raise() } else if self.isEmpty(authenticationToken as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Authentication Token"), reason: "Authentication Token is null or empty", userInfo: nil).raise() } else if self.isEmpty(applicationKey as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Application Key"), reason: "Application Key is null or empty", userInfo: nil).raise() } else if self.isEmpty(privateKey as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Private Key"), reason: "Private Key is null or empty", userInfo: nil).raise() } else { var ret: Bool = false var connectionUrl: String? = aUrl if isCluster { connectionUrl = String(self.getClusterServer(true, aPostUrl: aUrl)!) } if connectionUrl != nil { connectionUrl = connectionUrl!.hasSuffix("/") ? connectionUrl! : connectionUrl! + "/" var post: String = "AT=\(authenticationToken)&PVT=\(authenticationTokenIsPrivate ? "1" : "0")&AK=\(applicationKey)&TTL=\(timeToLive)&PK=\(privateKey)" if permissions != nil && permissions!.count > 0 { post = post + "&TP=\(CUnsignedLong(permissions!.count))" let keys: [AnyObject]? = permissions!.allKeys as [AnyObject]? // the dictionary keys for key in keys! { post = post + "&\(key)=\(permissions![key as! String] as! String)" } } let postData: Data? = post.data(using: String.Encoding.utf8, allowLossyConversion: true) let postLength: String? = "\(CUnsignedLong((postData! as Data).count))" let request: NSMutableURLRequest = NSMutableURLRequest() request.url = URL(string: connectionUrl! + "authenticate") request.httpMethod = "POST" request.setValue(postLength, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpBody = postData // Send request and get response let semaphore = DispatchSemaphore(value: 0) let task = URLSession.shared.dataTask(with: request as URLRequest){ data, urlResponse, error in if urlResponse != nil { ret = Bool((urlResponse as! HTTPURLResponse).statusCode == 201) }else if error != nil{ ret = false } semaphore.signal() } task.resume() _ = semaphore.wait(timeout: DispatchTime.distantFuture) } else { NSException(name: NSExceptionName(rawValue: "Get Cluster URL"), reason: "Unable to get URL from cluster", userInfo: nil).raise() } return ret } return false } /** Enables presence for the specified channel with first 100 unique metadata if true. @warning This function will send your private key over the internet. Make sure to use secure connection. - parameter url: Server containing the presence service. - parameter isCluster: Specifies if url is cluster. - parameter applicationKey: Application key with access to presence service. - parameter privateKey: The private key provided when the ORTC service is purchased. - parameter channel: Channel with presence data active. - parameter metadata: Defines if to collect first 100 unique metadata. - parameter callback: Callback with error (NSError) and result (NSString) parameters */ open func enablePresence(_ aUrl:String, isCluster:Bool, applicationKey:String, privateKey:String, channel:String, metadata:Bool, callback:@escaping (_ error:NSError?, _ result:NSString?)->Void){ self.setPresence(true, aUrl: aUrl, isCluster: isCluster, applicationKey: applicationKey, privateKey: privateKey, channel: channel, metadata: metadata, callback: callback) } /** Disables presence for the specified channel. @warning This function will send your private key over the internet. Make sure to use secure connection. - parameter url: Server containing the presence service. - parameter isCluster: Specifies if url is cluster. - parameter applicationKey: Application key with access to presence service. - parameter privateKey: The private key provided when the ORTC service is purchased. - parameter channel: Channel with presence data active. - parameter callback: Callback with error (NSError) and result (NSString) parameters */ open func disablePresence(_ aUrl:String, isCluster:Bool, applicationKey:String, privateKey:String, channel:String, callback:@escaping (_ error:NSError?, _ result:NSString?)->Void){ self.setPresence(false, aUrl: aUrl, isCluster: isCluster, applicationKey: applicationKey, privateKey: privateKey, channel: channel, metadata: false, callback: callback) } func setPresence(_ enable:Bool, aUrl:String, isCluster:Bool, applicationKey:String, privateKey:String, channel:String, metadata:Bool, callback:@escaping (_ error:NSError?, _ result:NSString?)->Void){ if self.isEmpty(aUrl as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Url"), reason: "URL is null or empty", userInfo: nil).raise() } else if self.isEmpty(applicationKey as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Application Key"), reason: "Application Key is null or empty", userInfo: nil).raise() } else if self.isEmpty(privateKey as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Private Key"), reason: "Private Key is null or empty", userInfo: nil).raise() } else if self.isEmpty(channel as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Channel"), reason: "Channel is null or empty", userInfo: nil).raise() } else if !self.ortcIsValidInput(channel) { NSException(name: NSExceptionName(rawValue: "Channel"), reason: "Channel has invalid characters", userInfo: nil).raise() } else { var connectionUrl: String? = aUrl if isCluster { connectionUrl = String(describing: self.getClusterServer(true, aPostUrl: aUrl)!) } if connectionUrl != nil { connectionUrl = connectionUrl!.hasSuffix("/") ? connectionUrl! : connectionUrl! + "/" var path: String = "" var content: String = "" if enable { path = "presence/enable/\(applicationKey)/\(channel)" content = "privatekey=\(privateKey)&metadata=\((metadata ? "1" : "0"))" }else{ path = "presence/disable/\(applicationKey)/\(channel)" content = "privatekey=\(privateKey)" } connectionUrl = connectionUrl! + path let postData: Data = (content as NSString).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: true)! let postLength: String = "\(CUnsignedLong((postData as Data).count))" let request: NSMutableURLRequest = NSMutableURLRequest() request.url = URL(string: connectionUrl!) request.httpMethod = "POST" request.setValue(postLength, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpBody = postData let pr:PresenceRequest = PresenceRequest() pr.callback = callback pr.post(request) } else { let error: NSError = self.generateError("Unable to get URL from cluster") callback(error, nil) } } } /** * Gets a NSDictionary indicating the subscriptions in the specified channel and if active the first 100 unique metadata. * * - parameter url: Server containing the presence service. * - parameter isCluster: Specifies if url is cluster. * - parameter applicationKey: Application key with access to presence service. * - parameter authenticationToken: Authentication token with access to presence service. * - parameter channel: Channel with presence data active. * - parameter callback: Callback with error (NSError) and result (NSDictionary) parameters */ open func presence(_ aUrl:String, isCluster:Bool, applicationKey:String, authenticationToken:String, channel:String, callback:@escaping (_ error:NSError?, _ result:NSDictionary?)->Void){ /* * Sanity Checks. */ if self.isEmpty(aUrl as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Url"), reason: "URL is null or empty", userInfo: nil).raise() } else if self.isEmpty(applicationKey as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Application Key"), reason: "Application Key is null or empty", userInfo: nil).raise() } else if self.isEmpty(authenticationToken as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Authentication Token"), reason: "Authentication Token is null or empty", userInfo: nil).raise() } else if self.isEmpty(channel as AnyObject?) { NSException(name: NSExceptionName(rawValue: "Channel"), reason: "Channel is null or empty", userInfo: nil).raise() } else if !self.ortcIsValidInput(channel) { NSException(name: NSExceptionName(rawValue: "Channel"), reason: "Channel has invalid characters", userInfo: nil).raise() } else { var connectionUrl: String? = aUrl if isCluster { connectionUrl = String(describing: self.getClusterServer(true, aPostUrl: aUrl)!) } if connectionUrl != nil { connectionUrl = connectionUrl!.hasSuffix("/") ? connectionUrl! : "\(connectionUrl!)/" let path: String = "presence/\(applicationKey)/\(authenticationToken)/\(channel)" connectionUrl = "\(connectionUrl!)\(path)" let request: NSMutableURLRequest = NSMutableURLRequest() request.url = URL(string: connectionUrl!) request.httpMethod = "GET" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") let pr:PresenceRequest = PresenceRequest() pr.callbackDictionary = callback pr.get(request) } else { let error: NSError = self.generateError("Unable to get URL from cluster") callback(error, nil) } } } /** * Sets publish timeout. * - parameter timeout: publish messages timeout. */ open func setPublishTimeout(_ timeout:Double){ self.publishTimeout = timeout } /** * Returns publishTimeout: publish timeout. */ open func getPublishTimeout() -> Double{ return self.publishTimeout! } /** * Get heartbeat interval. */ open func getHeartbeatTime()->Int?{ return self.heartbeatTime } /** * Set heartbeat interval. */ open func setHeartbeatTime(_ time:Int){ self.heartbeatTime = time } /** * Get how many times can the client fail the heartbeat. */ open func getHeartbeatFails()->Int?{ return self.heartbeatFails } /** * Set heartbeat fails. Defines how many times can the client fail the heartbeat. */ open func setHeartbeatFails(_ time:Int){ self.heartbeatFails = time } /** * Indicates whether heartbeat is active or not. */ open func isHeartbeatActive()->Bool{ return self.heartbeatActive! } /** * Enables the client heartbeat */ open func enableHeartbeat(){ self.heartbeatActive = true } /** * Disables the client heartbeat */ open func disableHeartbeat(){ self.heartbeatActive = false } func startHeartbeatLoop(){ if heartbeatTimer == nil && heartbeatActive == true { DispatchQueue.main.async(execute: { self.heartbeatTimer = Timer.scheduledTimer(timeInterval: Double(self.heartbeatTime!), target: self, selector: #selector(OrtcClient.heartbeatLoop), userInfo: nil, repeats: true) }) } } func stopHeartbeatLoop(){ if heartbeatTimer != nil { heartbeatTimer!.invalidate() } heartbeatTimer = nil } func heartbeatLoop(){ if heartbeatActive == true { self.webSocket!.write(string:"\"b\"", completion: nil) } else { self.stopHeartbeatLoop() } } static var ortcDEVICE_TOKEN: String? open class func setDEVICE_TOKEN(_ deviceToken: String) { ortcDEVICE_TOKEN = deviceToken; } open class func getDEVICE_TOKEN() -> String? { return ortcDEVICE_TOKEN } func receivedNotification(_ notification: Notification) { // [notification name] should be @"ApnsNotification" for received Apns Notififications if (notification.name.rawValue == "ApnsNotification") { var recRegex: NSRegularExpression? do{ recRegex = try NSRegularExpression(pattern: "^#(.*?):", options:NSRegularExpression.Options.caseInsensitive) }catch{ } let recMatch: NSTextCheckingResult? = recRegex?.firstMatch(in: notification.userInfo!["M"] as! String, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (notification.userInfo!["M"] as! NSString).length)) var strRangeSeqId: NSRange? if recMatch != nil{ strRangeSeqId = recMatch!.rangeAt(1) } var seqId:NSString? var message:NSString? if (recMatch != nil && strRangeSeqId?.location != NSNotFound) { seqId = (notification.userInfo!["M"] as! NSString).substring(with: strRangeSeqId!) as NSString let parts:[String] = (notification.userInfo!["M"] as! NSString).components(separatedBy: "#\(seqId!):") message = parts[1] as NSString } var ortcMessage: String if seqId != nil && seqId != "" { ortcMessage = "a[\"{\\\"ch\\\":\\\"\(notification.userInfo!["C"] as! String)\\\",\\\"s\\\":\\\"\(seqId! as! String)\\\",\\\"m\\\":\\\"\(message! as! String)\\\"}\"]" }else{ ortcMessage = "a[\"{\\\"ch\\\":\\\"\(notification.userInfo!["C"] as! String)\\\",\\\"m\\\":\\\"\(notification.userInfo!["M"] as! String)\\\"}\"]" } self.parseReceivedMessage(ortcMessage as NSString?) } // [notification name] should be @"ApnsRegisterError" if an error ocured on RegisterForRemoteNotifications if (notification.name.rawValue == "ApnsRegisterError") { self.delegateExceptionCallback(self, error: (NSError(domain: "ApnsRegisterError", code: 0, userInfo: (notification as NSNotification).userInfo))) } } func subscribeChannel(_ channel:String, withNotifications:Bool, subscribeOnReconnect:Bool, withFilter:Bool, filter:String, onMessage:((_ ortc:OrtcClient, _ channel:String, _ message:String)->Void)?, onMessageWithFilter:((_ ortc:OrtcClient, _ channel:String, _ filtered:Bool, _ message:String)->Void)?){ if Bool(self.checkChannelSubscription(channel, withNotifications: withNotifications)) == true { let hashPerm: String? = self.checkChannelPermissions(channel as NSString) as? String if self.permissions == nil || (self.permissions != nil && hashPerm != nil) { let channelSubscription:ChannelSubscription = ChannelSubscription(); if self.subscribedChannels![channel] == nil { // Set channelSubscription properties channelSubscription.isSubscribing = true channelSubscription.isSubscribed = false channelSubscription.withFilter = withFilter channelSubscription.filter = filter channelSubscription.subscribeOnReconnected = subscribeOnReconnect channelSubscription.onMessage = onMessage channelSubscription.onMessageWithFilter = onMessageWithFilter channelSubscription.withNotifications = withNotifications // Add to subscribed channels dictionary self.subscribedChannels![channel] = channelSubscription } var aString: String if withNotifications { if !self.isEmpty(OrtcClient.getDEVICE_TOKEN()! as AnyObject?) { aString = "\"subscribe;\(applicationKey!);\(authenticationToken!);\(channel);\(hashPerm);\(OrtcClient.getDEVICE_TOKEN()!);\(PLATFORM)\"" } else { self.delegateExceptionCallback(self, error: self.generateError("Failed to register Device Token. Channel subscribed without Push Notifications")) aString = "\"subscribe;\(applicationKey!);\(authenticationToken!);\(channel);\(hashPerm)\"" } } else if(withFilter){ aString = "\"subscribefilter;\(applicationKey!);\(authenticationToken!);\(channel);\(hashPerm);\(filter)\"" } else if channelSubscription.withOptions == true{ aString = "\"subscribeoptions;\(applicationKey);\(authenticationToken);\(channel);\(channelSubscription.subscriberId);\(channelSubscription.regId);\(PLATFORM); \(hashPerm);\(filter)\"" } else { aString = "\"subscribe;\(applicationKey!);\(authenticationToken!);\(channel);\(hashPerm)\"" } if !self.isEmpty(aString as AnyObject?) { self.webSocket?.write(string: aString as String, completion: nil) } } } } func ortcIsValidInput(_ input: String) -> Bool { var opMatch: NSTextCheckingResult? do{ let opRegex: NSRegularExpression = try NSRegularExpression(pattern: "^[\\w-:/.]*$", options: NSRegularExpression.Options.caseInsensitive) opMatch = opRegex.firstMatch(in: input, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (input as NSString).length)) }catch{ return false } return opMatch != nil ? true : false } func ortcIsValidUrl(_ input: String) -> Bool { var opMatch: NSTextCheckingResult? do{ let opRegex: NSRegularExpression = try NSRegularExpression(pattern: "^\\s*(http|https)://(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(/|/([\\w#!:.?+=&%@!\\-/]))?\\s*$", options: NSRegularExpression.Options.caseInsensitive) opMatch = opRegex.firstMatch(in: input, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (input as NSString).length)) }catch{ } return opMatch != nil ? true : false } func ortcIsValidChannelForMobile(_ input:String) -> Bool{ var opMatch: NSTextCheckingResult? do{ let opRegex: NSRegularExpression = try NSRegularExpression(pattern: "^[\\w-:/.]*$", options: NSRegularExpression.Options.caseInsensitive) opMatch = opRegex.firstMatch(in: input, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (input as NSString).length)) }catch{ return false } return opMatch != nil ? true : false } func isEmpty(_ thing: AnyObject?) -> Bool { return thing == nil || (thing!.responds(to: #selector(getter: UILayoutSupport.length)) && (thing! as? Data)?.count == 0) || (thing!.responds(to: #selector(getter: CIVector.count)) && (thing! as? [NSArray])?.count == 0) || (thing! as? String) == "" } func generateError(_ errText: String) -> NSError { let errorDetail: NSMutableDictionary = NSMutableDictionary() errorDetail.setValue(errText, forKey: NSLocalizedDescriptionKey) return NSError(domain: "OrtcClient", code: 1, userInfo: ((errorDetail as NSDictionary) as! [AnyHashable: Any])) } func doConnect(_ sender: AnyObject) { if heartbeatTimer != nil { self.stopHeartbeatLoop() } if isReconnecting == true { self.delegateReconnectingCallback(self) } if stopReconnecting == false { self.processConnect(self) } } func parseReceivedMessage(_ aMessage: NSString?) { if aMessage != nil { if (!aMessage!.isEqual(to: "o") && !aMessage!.isEqual(to: "h")){ var opMatch: NSTextCheckingResult? do{ let opRegex: NSRegularExpression = try NSRegularExpression(pattern: OPERATION_PATTERN, options: NSRegularExpression.Options.caseInsensitive) opMatch = opRegex.firstMatch(in: aMessage! as String, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (aMessage! as NSString).length)) }catch{ return } if opMatch != nil { var operation: String? var arguments: String? let strRangeOp: NSRange? = opMatch!.rangeAt(1) let strRangeArgs: NSRange? = opMatch!.rangeAt(2) if strRangeOp != nil { operation = aMessage!.substring(with: strRangeOp!) } if strRangeArgs != nil { arguments = aMessage!.substring(with: strRangeArgs!) } if operation != nil { if (opCases![operation!] != nil) { switch (opCases![operation!] as! Int) { case opCodes.opValidate.rawValue: if arguments != nil { self.opValidated(arguments! as NSString) } break case opCodes.opSubscribe.rawValue: if arguments != nil { self.opSubscribed(arguments!) } break case opCodes.opUnsubscribe.rawValue: if arguments != nil { self.opUnsubscribed(arguments!) } break case opCodes.opException.rawValue: if arguments != nil { self.opException(arguments!) } break case opCodes.opAck.rawValue: if arguments != nil { self.opAck(aMessage as! String) } break default: self.delegateExceptionCallback(self, error: self.generateError("Unknown message received: \(aMessage!)")) break } } } else { self.delegateExceptionCallback(self, error: self.generateError("Unknown message received: \(aMessage!)")) } } else { self.opReceive(aMessage! as String) } } } } var balancer:Balancer? func processConnect(_ sender: AnyObject) { if stopReconnecting == false { balancer = (Balancer(cluster: self.clusterUrl as? String, serverUrl: self.url as? String, isCluster: self.isCluster!, appKey: self.applicationKey!, callback: { (aBalancerResponse: String?) in if self.isCluster != nil { if self.isEmpty(aBalancerResponse as AnyObject?) { self.delegateExceptionCallback(self, error: self.generateError("Unable to get URL from cluster (\(self.clusterUrl!))")) self.url = nil }else{ self.url = String(aBalancerResponse!) as NSString? } } if self.url != nil { var wsScheme: String = "ws" let connectionUrl: URL = URL(string: self.url! as String)! if connectionUrl.scheme == "https" { wsScheme = "wss" } let serverId: NSString = NSString(format: "%0.3u", self.randomInRangeLo(1, toHi: 1000)) let connId: String = self.randomString(8) var connUrl: String = connectionUrl.host! if self.isEmpty((connectionUrl as NSURL).port) == false { connUrl = connUrl + ":" + (connectionUrl as NSURL).port!.stringValue } let wsUrl: String = "\(wsScheme)://\(connUrl)/broadcast/\(serverId)/\(connId)/websocket" let wurl:URL = URL(string: wsUrl)! if self.webSocket != nil { self.webSocket!.delegate = nil self.webSocket = nil } self.webSocket = WebSocket(url: wurl) self.webSocket!.delegate = self self.webSocket!.connect() } else { DispatchQueue.main.async(execute: { self.timer = Timer.scheduledTimer(timeInterval: Double(self.connectionTimeout!), target: self, selector: #selector(OrtcClient.processConnect(_:)), userInfo: nil, repeats: false) }) } })) } } var timer:Timer? func randomString(_ size: UInt32) -> String { var ret: NSString = "" for _ in 0...size { let letter: NSString = NSString(format: "%0.1u", self.randomInRangeLo(65, toHi: 90)) ret = "\(ret)\(CChar(letter.intValue))" as NSString } return ret as String } func randomInRangeLo(_ loBound: UInt32, toHi hiBound: UInt32) -> UInt32 { var random: UInt32 let range: UInt32 = UInt32(hiBound) - UInt32(loBound+1) let limit:UInt32 = UINT32_MAX - (UINT32_MAX % range) repeat { random = arc4random() } while random > limit return loBound+(random%range) } func processDisconnect(_ callDisconnectCallback:Bool){ self.stopHeartbeatLoop() self.webSocket!.delegate = nil self.webSocket!.disconnect() if callDisconnectCallback == true { self.delegateDisconnectedCallback(self) } isConnected = false isConnecting = false // Clear user permissions self.permissions = nil } func createLocalStorage(_ sessionStorageName: String) { sessionCreatedAt = Date() var plistData: Data? var plistPath: NSString? do{ let keys: [AnyObject] = NSArray(objects: "sessionId","sessionCreatedAt") as [AnyObject] let objects: [AnyObject] = NSArray(objects: sessionId!,sessionCreatedAt!) as [AnyObject] let sessionInfo: [AnyHashable: Any] = NSDictionary(objects: objects, forKeys: keys as! [NSCopying]) as! [AnyHashable: Any] let rootPath: NSString = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString plistPath = rootPath.appendingPathComponent("OrtcClient.plist") as NSString? try plistData = PropertyListSerialization.data(fromPropertyList: sessionInfo, format: PropertyListSerialization.PropertyListFormat.xml, options: PropertyListSerialization.WriteOptions.allZeros) }catch{ } if plistData != nil { try? plistData!.write(to: URL(fileURLWithPath: plistPath! as String), options: [.atomic]) } else { self.delegateExceptionCallback(self, error: self.generateError("Error : Creating local storage")) } } func readLocalStorage(_ sessionStorageName: String) -> String? { let format:UnsafeMutablePointer<PropertyListSerialization.PropertyListFormat>? = nil var plistPath: String? var plistProps: NSDictionary? let rootPath: NSString = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString plistPath = rootPath.appendingPathComponent("OrtcClient.plist") if FileManager.default.fileExists(atPath: plistPath!) { plistPath = Bundle.main.path(forResource: "OrtcClient", ofType: "plist") //NSLog(@"plistPath: %@", plistPath); do{ if plistPath != nil { let plistXML: Data? plistXML = FileManager.default.contents(atPath: plistPath!) if plistXML != nil{ plistProps = try (PropertyListSerialization.propertyList(from: plistXML!, options: PropertyListSerialization.MutabilityOptions.mutableContainersAndLeaves, format: format) as? NSDictionary) } } }catch{ } } if plistProps != nil { if plistProps!.object(forKey: "sessionCreatedAt") != nil { sessionCreatedAt = (plistProps!.object(forKey: "sessionCreatedAt")!) as? Date } let currentDateTime: Date = Date() let time: TimeInterval = currentDateTime.timeIntervalSince(sessionCreatedAt!) let minutes: Int = Int(time / 60.0) if minutes >= sessionExpirationTime { plistProps = nil } else if plistProps!.object(forKey: "sessionId") != nil { sessionId = plistProps!.object(forKey: "sessionId") as? NSString } } return sessionId as? String } func getClusterServer(_ isPostingAuth: Bool, aPostUrl postUrl: String) -> String? { var result:String? let semaphore = DispatchSemaphore(value: 0) self.send(isPostingAuth, aPostUrl: postUrl, res: { (res:String) -> () in result = res semaphore.signal() }) _ = semaphore.wait(timeout: DispatchTime.distantFuture) return result } func send(_ isPostingAuth: Bool, aPostUrl postUrl: String, res:@escaping (String)->()){ // Send request and get response var parsedUrl: String = postUrl if applicationKey != nil { parsedUrl = parsedUrl + "?appkey=" parsedUrl = parsedUrl + self.applicationKey! } let request: URLRequest = URLRequest(url:URL(string: parsedUrl)!) let task = URLSession.shared.dataTask(with: request as URLRequest){ data, Response, error in if data != nil { var result: String = "" var resRegex: NSRegularExpression? let myString: NSString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as NSString! do{ resRegex = try NSRegularExpression(pattern: self.CLUSTER_RESPONSE_PATTERN, options: NSRegularExpression.Options.caseInsensitive) }catch{ } let resMatch: NSTextCheckingResult? = resRegex?.firstMatch(in: myString as String, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, myString.length)) if resMatch != nil { let strRange: NSRange? = resMatch!.rangeAt(1) if strRange != nil { result = myString.substring(with: strRange!) } } if !isPostingAuth { if self.isEmpty(result as AnyObject?) == true { self.delegateExceptionCallback(self, error: self.generateError("Unable to get URL from cluster (\(parsedUrl))")) } } res(result) } } task.resume() } func opValidated(_ message: NSString) { var isValid: Bool = false var valRegex: NSRegularExpression? do{ valRegex = try NSRegularExpression(pattern: VALIDATED_PATTERN, options: NSRegularExpression.Options.caseInsensitive) }catch{ } let valMatch: NSTextCheckingResult? = valRegex?.firstMatch(in: message as String, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (message as NSString).length)) if valMatch != nil{ isValid = true var userPermissions: NSString? let strRangePerm: NSRange? = valMatch!.rangeAt(2) let strRangeExpi: NSRange? = valMatch!.rangeAt(4) if strRangePerm!.location != NSNotFound { userPermissions = message.substring(with: strRangePerm!) as NSString? } if strRangeExpi!.location != NSNotFound{ sessionExpirationTime = (message.substring(with: strRangeExpi!)as NSString).integerValue } if self.isEmpty(self.readLocalStorage(SESSION_STORAGE_NAME + applicationKey!) as AnyObject?) { self.createLocalStorage(SESSION_STORAGE_NAME + applicationKey!) } // NOTE: userPermissions = null -> No authentication required for the application key if userPermissions != nil && !(userPermissions!.isEqual(to: "null")) { userPermissions = userPermissions!.replacingOccurrences(of: "\\\"", with: "\"") as NSString? // Parse the string into JSON var dictionary: NSDictionary do{ dictionary = try JSONSerialization.jsonObject(with: userPermissions!.data(using: String.Encoding.utf8.rawValue)!, options:JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary }catch{ self.delegateExceptionCallback(self, error: self.generateError("Error parsing the permissions received from server")) return } self.permissions = NSMutableDictionary() for key in dictionary.allKeys { // Add to permissions dictionary self.permissions!.setValue(dictionary.object(forKey: key), forKey: key as! String) } } } if isValid == true { isConnecting = false isReconnecting = false isConnected = true if (hasConnectedFirstTime == true) { let channelsToRemove: NSMutableArray = NSMutableArray() // Subscribe to the previously subscribed channels for channel in self.subscribedChannels! { let channelSubscription:ChannelSubscription = self.subscribedChannels!.object(forKey: channel.key as! String) as! ChannelSubscription! // Subscribe again if channelSubscription.subscribeOnReconnected == true && (channelSubscription.isSubscribing == true || channelSubscription.isSubscribed == true) { channelSubscription.isSubscribing = true channelSubscription.isSubscribed = false let domainChannelIndex: Int = (channel.key as! NSString).range(of: ":").location var channelToValidate: String = channel.key as! String var hashPerm: String = "" if domainChannelIndex != NSNotFound { channelToValidate = (channel.key as AnyObject).substring(to: domainChannelIndex+1) + "*" } if self.permissions != nil { hashPerm = (self.permissions![channelToValidate] != nil ? self.permissions![channelToValidate] : self.permissions![channel.key as! String]) as! String } var aString: NSString = NSString() if channelSubscription.withNotifications == true { if !self.isEmpty(OrtcClient.getDEVICE_TOKEN()! as AnyObject?) { aString = "\"subscribe;\(applicationKey!);\(authenticationToken!);\(channel.key);\(hashPerm);\(OrtcClient.getDEVICE_TOKEN()!);\(PLATFORM)\"" as NSString } else { self.delegateExceptionCallback(self, error: self.generateError("Failed to register Device Token. Channel subscribed without Push Notifications")) aString = "\"subscribe;\(applicationKey!);\(authenticationToken!);\(channel.key);\(hashPerm)\"" as NSString } } else if channelSubscription.withOptions == true{ var _regId:String; var _filter:String; var _subscriberId:String = ""; if(channelSubscription.regId == nil) { _regId = ""; }else{ _regId = channelSubscription.regId! } if(channelSubscription.filter == nil) { _filter = ""; }else{ _filter = channelSubscription.filter! } if(channelSubscription.subscriberId == nil) { _subscriberId = ""; }else{ _subscriberId = channelSubscription.subscriberId! } aString = "\"subscribeoptions;\(applicationKey!);\(authenticationToken!);\(channel.key);\(_subscriberId);\(_regId);\(PLATFORM);\(hashPerm);\(_filter)\"" as NSString } else if (channelSubscription.withFilter == true){ aString = "\"subscribefilter;\(applicationKey!);\(authenticationToken!);\(channel.key);\(hashPerm);\(channelSubscription.filter!)\"" as NSString } else { aString = "\"subscribe;\(applicationKey!);\(authenticationToken!);\(channel.key);\(hashPerm)\"" as NSString } //NSLog(@"SUB ON ORTC:\n%@",aString); if !self.isEmpty(aString) { self.webSocket?.write(string:aString as String, completion: nil) } } else { channelsToRemove.add(channel as AnyObject) } } for channel in channelsToRemove { self.subscribedChannels!.removeObject(forKey: channel) } // Clean messages buffer (can have lost message parts in memory) //messagesBuffer!.removeAllObjects() //OrtcClient.removeReceivedNotifications() self.delegateReconnectedCallback(self) } else { hasConnectedFirstTime = true self.delegateConnectedCallback(self) } self.startHeartbeatLoop() } else { self.disconnect() self.delegateExceptionCallback(self, error: self.generateError("Invalid connection")) } } static func removeReceivedNotifications(){ if UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) != nil{ let notificationsDict: NSMutableDictionary? = NSMutableDictionary(dictionary: (UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) as! NSMutableDictionary?)!) notificationsDict?.removeAllObjects() UserDefaults.standard.set(notificationsDict, forKey: NOTIFICATIONS_KEY) UserDefaults.standard.synchronize() } } func opSubscribed(_ message: String) { var subRegex: NSRegularExpression? do{ subRegex = try NSRegularExpression(pattern: CHANNEL_PATTERN, options: NSRegularExpression.Options.caseInsensitive) }catch{ } let subMatch: NSTextCheckingResult? = subRegex?.firstMatch(in: message, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (message as NSString).length))! if subMatch != nil { var channel: String? let strRangeChn: NSRange? = subMatch!.rangeAt(1) if strRangeChn != nil { channel = (message as NSString).substring(with: strRangeChn!) } if channel != nil { let channelSubscription:ChannelSubscription = (self.subscribedChannels!.object(forKey: channel! as AnyObject) as? ChannelSubscription)! channelSubscription.isSubscribing = false channelSubscription.isSubscribed = true self.delegateSubscribedCallback(self, channel: channel!) } } } func opUnsubscribed(_ message: String) { var unsubRegex: NSRegularExpression? do{ unsubRegex = try NSRegularExpression(pattern: CHANNEL_PATTERN, options: NSRegularExpression.Options.caseInsensitive) }catch{ } let unsubMatch: NSTextCheckingResult? = unsubRegex?.firstMatch(in: message, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (message as NSString).length)) if unsubMatch != nil { var channel: String? let strRangeChn: NSRange? = unsubMatch!.rangeAt(1) if strRangeChn != nil { channel = (message as NSString).substring(with: strRangeChn!) } if channel != nil { self.subscribedChannels!.removeObject(forKey: channel! as NSString) self.delegateUnsubscribedCallback(self, channel: channel!) } } } func opAck(_ message: String){ var unsubRegex: NSRegularExpression? do{ unsubRegex = try NSRegularExpression(pattern: JSON_PATTERN, options: NSRegularExpression.Options.caseInsensitive) }catch{ } let unsubMatch: NSTextCheckingResult? = unsubRegex?.firstMatch(in: message, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (message as NSString).length)) if unsubMatch != nil { var msg: String? let strRangeChn: NSRange? = unsubMatch!.rangeAt(1) if strRangeChn != nil { msg = (message as NSString).substring(with: strRangeChn!) msg = self.simulateJsonParse(msg! as NSString) as String } if msg != nil { var dictionary: [AnyHashable: Any]? = [AnyHashable: Any]() do{ dictionary = try JSONSerialization.jsonObject(with: msg!.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [AnyHashable: Any] if dictionary?["m"] != nil && dictionary?["seq"] != nil { var msgId:String = dictionary!["m"] as! String var pendingMsg:NSDictionary = pendingPublishMessages!.object(forKey: msgId) as! NSDictionary var timer:Timer = pendingMsg.object(forKey: "timeout") as! Timer timer.invalidate() var callback:(NSError?,NSString?)->Void = pendingMsg.object(forKey: "callback") as! (NSError?,NSString?)->Void let seq:NSString = (dictionary?["seq"] as? NSString)! callback(nil, seq) pendingPublishMessages?.removeObject(forKey: msgId) } }catch{ } } } } func opException(_ message: String) { var exRegex: NSRegularExpression? do{ exRegex = try NSRegularExpression(pattern: JSON_PATTERN, options:NSRegularExpression.Options.caseInsensitive) }catch{ return } let exMatch: NSTextCheckingResult? = exRegex?.firstMatch(in: message, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (message as NSString).length))! if exMatch != nil { var operation: String? var channel: String? var error: String? let strRangeOp: NSRange? = exMatch!.rangeAt(2) let strRangeChn: NSRange? = exMatch!.rangeAt(4) let strRangeErr: NSRange? = exMatch!.rangeAt(5) if strRangeOp!.location != NSNotFound{ operation = (message as NSString).substring(with: strRangeOp!) } if strRangeChn!.location != NSNotFound{ channel = (message as NSString).substring(with: strRangeChn!) } if strRangeErr!.location != NSNotFound{ error = (message as NSString).substring(with: strRangeErr!) } if error != nil{ if error == "Invalid connection." { self.disconnect() } self.delegateExceptionCallback(self, error: self.generateError(error!)) } if operation != nil { if errCases?.object(forKey: operation!) != nil { switch (errCases?.object(forKey: operation!)as! Int) { case errCodes.errValidate.rawValue: isConnecting = false isReconnecting = false // Stop the connecting/reconnecting process stopReconnecting = true hasConnectedFirstTime = false self.processDisconnect(false) break case errCodes.errSubscribe.rawValue: if channel != nil && self.subscribedChannels!.object(forKey: channel!) != nil { let channelSubscription:ChannelSubscription? = self.subscribedChannels!.object(forKey: channel!) as? ChannelSubscription channelSubscription?.isSubscribing = false } break case errCodes.errSendMaxSize.rawValue: if channel != nil && self.subscribedChannels?.object(forKey: channel!) != nil { let channelSubscription:ChannelSubscription? = self.subscribedChannels!.object(forKey: channel!) as? ChannelSubscription channelSubscription?.isSubscribing = false } // Stop the connecting/reconnecting process stopReconnecting = true hasConnectedFirstTime = false self.disconnect() break default: break } } } } } func opReceive(_ message: String) { var originalMessage:String = String(message) var recRegex: NSRegularExpression? var recRegexFiltered: NSRegularExpression? do{ recRegex = try NSRegularExpression(pattern: JSON_PATTERN, options:NSRegularExpression.Options.caseInsensitive) }catch{ } let recMatch: NSTextCheckingResult? = recRegex?.firstMatch(in: message, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (message as NSString).length)) if recMatch != nil{ var jsonMessage: String? var aMessage: String? var aChannel: String? var aFiltered: Bool? var aSeqId: String? let strRangeJSON: NSRange? = recMatch!.rangeAt(1) if strRangeJSON != nil { jsonMessage = (message as NSString).substring(with: strRangeJSON!) jsonMessage = self.simulateJsonParse(jsonMessage! as NSString) as String } var json: [AnyHashable: Any]? = [AnyHashable: Any]() do{ json = try JSONSerialization.jsonObject(with: jsonMessage!.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [AnyHashable: Any] }catch{ } if json != nil{ if json?["ch"] != nil { aChannel = json!["ch"] as! String } if json?["m"] != nil { aMessage = json!["m"] as! String } if json?["f"] != nil { aFiltered = json!["f"] as! Bool } if json?["s"] != nil { aSeqId = json!["s"] as! String } if aChannel != nil && aMessage != nil { var msgRegex: NSRegularExpression? do{ msgRegex = try NSRegularExpression(pattern: MULTI_PART_MESSAGE_PATTERN, options:NSRegularExpression.Options.caseInsensitive) }catch{ } let multiMatch: NSTextCheckingResult? = msgRegex!.firstMatch(in: aMessage!, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (aMessage! as NSString).length)) var messageId: String = "" var messageCurrentPart: Int32 = 1 var messageTotalPart: Int32 = 1 var lastPart: Bool = false if multiMatch != nil { let strRangeMsgId: NSRange? = multiMatch!.rangeAt(1) let strRangeMsgCurPart: NSRange? = multiMatch!.rangeAt(2) let strRangeMsgTotPart: NSRange? = multiMatch!.rangeAt(3) let strRangeMsgRec: NSRange? = multiMatch!.rangeAt(4) if strRangeMsgId != nil { messageId = (aMessage! as NSString).substring(with: strRangeMsgId!) } if strRangeMsgCurPart != nil { messageCurrentPart = ((aMessage! as NSString).substring(with: strRangeMsgCurPart!) as NSString).intValue } if strRangeMsgTotPart != nil { messageTotalPart = ((aMessage! as NSString).substring(with: strRangeMsgTotPart!) as NSString).intValue } if strRangeMsgRec != nil { aMessage = (aMessage! as NSString).substring(with: strRangeMsgRec!) //code below written by Rafa, gives a bug for a meesage containing % character //aMessage = [[aMessage substringWithRange:strRangeMsgRec] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; } } // Is a message part if self.isEmpty(messageId as AnyObject?) == false { if messagesBuffer?.object(forKey: messageId) == nil { let msgSentDict: NSMutableDictionary = NSMutableDictionary() msgSentDict["isMsgSent"] = NSNumber(value: false as Bool) messagesBuffer?.setObject(msgSentDict, forKey: messageId as NSCopying) } let messageBufferId: NSMutableDictionary? = messagesBuffer?.object(forKey: messageId) as? NSMutableDictionary messageBufferId?.setObject(aMessage!, forKey: "\(messageCurrentPart)" as NSCopying) if messageTotalPart == Int32(messageBufferId!.allKeys.count - 1) { lastPart = true } } else { lastPart = true } if lastPart { if !self.isEmpty(messageId as AnyObject?) { aMessage = "" let messageBufferId: NSMutableDictionary? = messagesBuffer?.object(forKey: messageId) as? NSMutableDictionary for i in 1...messageTotalPart { let messagePart: String? = messageBufferId?.object(forKey: "\(i)") as? String aMessage = aMessage! + messagePart! // Delete from messages buffer messageBufferId!.removeObject(forKey: "\(i)") } } if messagesBuffer?.object(forKey: messageId) != nil && ((messagesBuffer?.object(forKey: messageId) as! NSDictionary).object(forKey: "isMsgSent") as! Bool) == true { messagesBuffer?.removeObject(forKey: messageId) } else if self.subscribedChannels!.object(forKey: aChannel!) != nil { let channelSubscription:ChannelSubscription? = self.subscribedChannels!.object(forKey: aChannel!) as? ChannelSubscription if !self.isEmpty(messageId as AnyObject?) { let msgSentDict: NSMutableDictionary? = messagesBuffer?.object(forKey: messageId) as? NSMutableDictionary msgSentDict?.setObject(NSNumber(value: true as Bool), forKey: "isMsgSent" as NSCopying) messagesBuffer?.setObject(msgSentDict!, forKey: messageId as NSCopying) } //aMessage = self.escapeRecvChars(aMessage! as NSString) as String aMessage = self.checkForEmoji(aMessage! as NSString) as String var callbackCalled:Bool = false if self.deliveredNotification(originalMessage, self.applicationKey!) == true { return; } if channelSubscription?.withFilter == true { channelSubscription?.onMessageWithFilter!(self, aChannel!, aFiltered!, aMessage!) callbackCalled = true }else if channelSubscription?.withOptions == true{ var dataResult: NSMutableDictionary = NSMutableDictionary() dataResult.setObject(aChannel!, forKey: "channel" as NSCopying) dataResult.setObject(aMessage!, forKey: "message" as NSCopying) if aFiltered != nil { dataResult.setObject(aFiltered!, forKey: "filter" as NSCopying) } if aSeqId != nil { dataResult.setObject(aSeqId!, forKey: "seqId" as NSCopying) } channelSubscription?.onMessageWithOptions!(self, dataResult) callbackCalled = true }else if channelSubscription?.onMessage != nil{ channelSubscription!.onMessage!(self, aChannel!, aMessage!) callbackCalled = true } if callbackCalled == true { self.storeNotification(originalMessage, self.applicationKey!) } } } if(messageId != nil && aSeqId != nil){ let haveAllParts: String = lastPart ? "1":"0" let ack: String = "\"ack;\(applicationKey!);\(aChannel!);\(messageId);\(aSeqId!);\(haveAllParts)\"" self.webSocket?.write(string: ack) } } } } } func checkForEmoji(_ str:NSString)->String{ var str = str var i = 0 var len = str.length while i < len { let ascii:unichar = str.character(at: i) if(ascii == ("\\" as NSString).character(at: 0)){ let next = str.character(at:i + 1) if next == ("u" as NSString).character(at: 0) { let size = ((i - 1) + 12) if (size < len && str.character(at: i + 6) == ("u" as NSString).character(at: 0)){ var emoji: NSString? = str.substring(with: NSMakeRange((i), 12)) as NSString? let pos: Data? = emoji?.data(using: String.Encoding.utf8.rawValue) if pos != nil{ emoji = NSString(data: pos!, encoding: String.Encoding.nonLossyASCII.rawValue) as? String as NSString? } if emoji != nil { str = str.replacingCharacters(in: NSMakeRange((i), 12), with: emoji! as String) as NSString } }else{ var emoji: NSString? = str.substring(with: NSMakeRange((i), 6)) as NSString? let pos: Data? = emoji?.data(using: String.Encoding.utf8.rawValue) if pos != nil{ emoji = NSString(data: pos!, encoding: String.Encoding.nonLossyASCII.rawValue) as? String as NSString? } if emoji != nil { str = str.replacingCharacters(in: NSMakeRange((i), 6), with: emoji! as String) as NSString } } } } len = str.length i = i + 1 } return str as String } func escapeRecvChars(_ str:NSString)->String{ var str = str str = self.simulateJsonParse(str) str = self.simulateJsonParse(str) return str as String } func simulateJsonParse(_ str:NSString)->NSString{ let ms: NSMutableString = NSMutableString() let len = str.length var i = 0 while i < len { var ascii:unichar = str.character(at: i) if ascii > 128 { //unicode ms.appendFormat("%@",NSString(characters: &ascii, length: 1)) } else { //ascii if ascii == ("\\" as NSString).character(at: 0) { i = i+1 let next = str.character(at: i) if next == ("\\" as NSString).character(at: 0) { ms.append("\\") } else if next == ("n" as NSString).character(at: 0) { ms.append("\n") } else if next == ("\"" as NSString).character(at: 0) { ms.append("\"") } else if next == ("b" as NSString).character(at: 0) { ms.append("b") } else if next == ("f" as NSString).character(at: 0) { ms.append("f") } else if next == ("r" as NSString).character(at: 0) { ms.append("\r") } else if next == ("t" as NSString).character(at: 0) { ms.append("\t") } else if next == ("u" as NSString).character(at: 0) { ms.append("\\u") } } else { ms.appendFormat("%c",ascii) } } i = i + 1 } return ms as NSString } func generateId(_ size: Int) -> String { let uuidRef: CFUUID = CFUUIDCreate(nil) let uuidStringRef: CFString = CFUUIDCreateString(nil, uuidRef) let uuid: NSString = NSString(string: uuidStringRef) return (uuid.replacingOccurrences(of: "-", with: "") as NSString).substring(to: size).lowercased() } public func websocketDidConnect(socket: WebSocket){ self.timer?.invalidate() if self.isEmpty(self.readLocalStorage(SESSION_STORAGE_NAME + applicationKey!) as AnyObject?) { sessionId = self.generateId(16) as NSString? } //Heartbeat details var hbDetails: String = "" if heartbeatActive == true{ hbDetails = ";\(heartbeatTime!);\(heartbeatFails!);" } var tempMetaData:NSString? if connectionMetadata != nil { tempMetaData = connectionMetadata!.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") as NSString? } // Send validate let aString: String = "\"validate;\(applicationKey!);\(authenticationToken!);\(announcementSubChannel != nil ? announcementSubChannel! : "");\(sessionId != nil ? sessionId! : "");\(tempMetaData != nil ? "\(tempMetaData!)" : "")\(hbDetails)\"" self.webSocket!.write(string:aString, completion: nil) } public func websocketDidDisconnect(socket: WebSocket, error: NSError?){ isConnecting = false // Reconnect if stopReconnecting == false { isConnecting = true stopReconnecting = false if isReconnecting == false { isReconnecting = true if isCluster == true { let tUrl: URL? = URL(string: (clusterUrl as? String)!) if (tUrl!.scheme == "http") && doFallback == true { let t: NSString = clusterUrl!.replacingOccurrences(of: "http:", with: "https:") as NSString let r: NSRange = t.range(of: "/server/ssl/") if r.location == NSNotFound { clusterUrl = t.replacingOccurrences(of: "/server/", with: "/server/ssl/") as NSString? } else { clusterUrl = t } } } self.doConnect(self) } else { DispatchQueue.main.async(execute: { self.timer = Timer.scheduledTimer(timeInterval: Double(self.connectionTimeout!), target: self, selector: #selector(OrtcClient.doConnect(_:)), userInfo: nil, repeats: false) }) } } } public func websocketDidReceiveMessage(socket: WebSocket, text: String){ self.parseReceivedMessage(text as NSString?) } public func websocketDidReceiveData(socket: WebSocket, data: Data){ } func parseReceivedNotifications(){ if UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) != nil{ var notificationsDict: NSMutableDictionary? if UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) != nil{ notificationsDict = NSMutableDictionary(dictionary: UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) as! NSDictionary) } if notificationsDict == nil { notificationsDict = NSMutableDictionary() } var notificationsArray: NSMutableDictionary? if notificationsDict?.object(forKey: applicationKey!) != nil{ notificationsArray = NSMutableDictionary(dictionary: notificationsDict?.object(forKey: applicationKey!) as! NSMutableDictionary) } if notificationsArray != nil{ for message in notificationsArray!.allKeys { self.parseReceivedMessage(message as! NSString) } } notificationsArray = NSMutableDictionary() notificationsArray?.removeAllObjects() notificationsDict!.setObject(notificationsArray!, forKey: (applicationKey! as! NSCopying)) UserDefaults.standard.set(notificationsDict!, forKey: NOTIFICATIONS_KEY) UserDefaults.standard.synchronize() } } func deliveredNotification(_ ortcMessage:String, _ withAppKey:String) -> Bool{ var notificationsDict: NSMutableDictionary? if UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) != nil{ notificationsDict = NSMutableDictionary(dictionary: UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) as! NSDictionary) } if notificationsDict == nil { notificationsDict = NSMutableDictionary() } var notificationsArray: NSMutableDictionary? if notificationsDict?.object(forKey: applicationKey!) != nil{ notificationsArray = NSMutableDictionary(dictionary: notificationsDict?.object(forKey: applicationKey!) as! NSMutableDictionary) } if notificationsArray == nil{ notificationsArray = NSMutableDictionary() } let delivered:Bool? = (notificationsArray?.object(forKey: ortcMessage) as? Bool) if delivered != nil && delivered == true{ return true } return false } func storeNotification(_ ortcMessage:String, _ withAppKey:String){ var notificationsDict: NSMutableDictionary? if UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) != nil{ notificationsDict = NSMutableDictionary(dictionary: UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) as! NSDictionary) } if notificationsDict == nil { notificationsDict = NSMutableDictionary() } var notificationsArray: NSMutableDictionary? if notificationsDict?.object(forKey: applicationKey!) != nil{ notificationsArray = NSMutableDictionary(dictionary: notificationsDict?.object(forKey: applicationKey!) as! NSMutableDictionary) } if notificationsArray == nil{ notificationsArray = NSMutableDictionary() } notificationsArray!.setObject(true, forKey: ortcMessage as NSCopying) notificationsDict!.setObject(notificationsArray!, forKey: (applicationKey! as! NSCopying)) UserDefaults.standard.set(notificationsDict!, forKey: NOTIFICATIONS_KEY) UserDefaults.standard.synchronize() } func removeNotification(message:String){ var notificationsDict: NSMutableDictionary? if UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) != nil{ notificationsDict = NSMutableDictionary(dictionary: UserDefaults.standard.object(forKey: NOTIFICATIONS_KEY) as! NSDictionary) } if notificationsDict == nil { notificationsDict = NSMutableDictionary() } var notificationsArray: NSMutableDictionary? if notificationsDict?.object(forKey: applicationKey!) != nil{ notificationsArray = NSMutableDictionary(dictionary: notificationsDict?.object(forKey: applicationKey!) as! NSMutableDictionary) } if notificationsArray == nil{ notificationsArray = NSMutableDictionary() } for notification in notificationsArray! { if message == (notification as! String) { notificationsArray?.removeObject(forKey: notification) } } notificationsDict!.setObject(notificationsArray!, forKey: (applicationKey! as! NSCopying)) UserDefaults.standard.set(notificationsDict!, forKey: NOTIFICATIONS_KEY) UserDefaults.standard.synchronize() } func delegateConnectedCallback(_ ortc: OrtcClient) { self.ortcDelegate?.onConnected(ortc) self.parseReceivedNotifications() } func delegateDisconnectedCallback(_ ortc: OrtcClient) { self.ortcDelegate?.onDisconnected(ortc) } func delegateSubscribedCallback(_ ortc: OrtcClient, channel: String) { self.ortcDelegate?.onSubscribed(ortc, channel: channel) } func delegateUnsubscribedCallback(_ ortc: OrtcClient, channel: String) { self.ortcDelegate?.onUnsubscribed(ortc, channel: channel) } func delegateExceptionCallback(_ ortc: OrtcClient, error aError: NSError) { self.ortcDelegate?.onException(ortc, error: aError) } func delegateReconnectingCallback(_ ortc: OrtcClient) { self.ortcDelegate?.onReconnecting(ortc) } func delegateReconnectedCallback(_ ortc: OrtcClient) { self.ortcDelegate?.onReconnected(ortc) } } let WITH_NOTIFICATIONS = true let WITHOUT_NOTIFICATIONS = false let NOTIFICATIONS_KEY = "Local_Storage_Notifications" class ChannelSubscription: NSObject { var isSubscribing: Bool? var isSubscribed: Bool? var subscribeOnReconnected: Bool? var withNotifications: Bool? var withFilter: Bool? var filter:String? var withOptions:Bool? var regId:String?; var subscriberId:String?; var onMessage: ((_ ortc:OrtcClient, _ channel:String, _ message:String)->Void?)? var onMessageWithFilter: ((_ ortc:OrtcClient, _ channel:String, _ filtered:Bool, _ message:String)->Void?)? var onMessageWithOptions: ((_ ortc:OrtcClient, _ msgOptions: NSDictionary)->Void?)? override init() { super.init() } } class PresenceRequest: NSObject { var isResponseJSON: Bool? var callback: ((_ error:NSError?, _ result:NSString?)->Void?)? var callbackDictionary: ((_ error:NSError?, _ result:NSDictionary?)->Void)? override init() { super.init() } func get(_ request: NSMutableURLRequest) { self.isResponseJSON = true self.processRequest(request) } func post(_ request: NSMutableURLRequest) { self.isResponseJSON = false self.processRequest(request) } func processRequest(_ request: NSMutableURLRequest){ let ret:URLSessionDataTask? = URLSession.shared.dataTask(with: request as URLRequest){ data, urlResponse, error in if data == nil && error != nil{ self.callbackDictionary!(error! as NSError?, nil) return } let dataStr: String? = String(data: data!, encoding: String.Encoding.utf8) if self.isResponseJSON == true && dataStr != nil { var dictionary: [AnyHashable: Any]? = [AnyHashable: Any]() do{ dictionary = try JSONSerialization.jsonObject(with: dataStr!.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [AnyHashable: Any] }catch{ if dataStr!.caseInsensitiveCompare("null") != ComparisonResult.orderedSame { let errorDetail: NSMutableDictionary = NSMutableDictionary() errorDetail.setObject(dataStr!, forKey: NSLocalizedDescriptionKey as NSCopying) let error: NSError = NSError(domain:"OrtcClient", code: 1, userInfo: ((errorDetail as NSDictionary) as! [AnyHashable: Any])) self.callbackDictionary!(error, nil) } else { self.callbackDictionary!(nil, ["null": "null"]) } return } self.callbackDictionary!(nil, dictionary! as NSDictionary?) }else { self.callback!(nil, dataStr as NSString?) } } if ret == nil { var errorDetail: [AnyHashable: Any] = [AnyHashable: Any]() errorDetail[NSLocalizedDescriptionKey] = "The connection can't be initialized." let error: NSError = NSError(domain:"OrtcClient", code: 1, userInfo: errorDetail) if self.isResponseJSON == true { self.callbackDictionary!(error, nil) } else { self.callback!(error, nil) } }else{ ret!.resume() } } }
mit
8107382011296d2c4d1ce1abebf1b969
47.759423
393
0.560194
5.304746
false
false
false
false
xwu/swift
benchmark/single-source/SIMDReduceInteger.swift
1
7083
//===--- SIMDReduceInteger.swift ------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 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 benchmarks = [ BenchmarkInfo( name: "SIMDReduce.Int32", runFunction: run_SIMDReduceInt32x1, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x4.Initializer", runFunction: run_SIMDReduceInt32x4_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x4.Cast", runFunction: run_SIMDReduceInt32x4_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x16.Initializer", runFunction: run_SIMDReduceInt32x16_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x16.Cast", runFunction: run_SIMDReduceInt32x16_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8", runFunction: run_SIMDReduceInt8x1, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x16.Initializer", runFunction: run_SIMDReduceInt8x16_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x16.Cast", runFunction: run_SIMDReduceInt8x16_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x64.Initializer", runFunction: run_SIMDReduceInt8x64_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x64.Cast", runFunction: run_SIMDReduceInt8x64_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ) ] // TODO: use 100 for Onone? let scale = 1000 let int32Data: UnsafeBufferPointer<Int32> = { let count = 256 // Allocate memory for `count` Int32s with alignment suitable for all // SIMD vector types. let untyped = UnsafeMutableRawBufferPointer.allocate( byteCount: MemoryLayout<Int32>.size * count, alignment: 16 ) // Intialize the memory as Int32 and fill with random values. let typed = untyped.initializeMemory(as: Int32.self, repeating: 0) var g = SplitMix64(seed: 0) for i in 0 ..< typed.count { typed[i] = .random(in: .min ... .max, using: &g) } return UnsafeBufferPointer(typed) }() @inline(never) public func run_SIMDReduceInt32x1(_ n: Int) { for _ in 0 ..< scale*n { var accum: Int32 = 0 for v in int32Data { accum &+= v &* v } blackHole(accum) } } @inline(never) public func run_SIMDReduceInt32x4_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD4<Int32>() for i in stride(from: 0, to: int32Data.count, by: 4) { let v = SIMD4(int32Data[i ..< i+4]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt32x4_cast(_ n: Int) { // Morally it seems like we "should" be able to use withMemoryRebound // to SIMD4<Int32>, but that function requries that the sizes match in // debug builds, so this is pretty ugly. The following "works" for now, // but is probably in violation of the formal model (the exact rules // for "assumingMemoryBound" are not clearly documented). We need a // better solution. let vecs = UnsafeBufferPointer<SIMD4<Int32>>( start: UnsafeRawPointer(int32Data.baseAddress!).assumingMemoryBound(to: SIMD4<Int32>.self), count: int32Data.count / 4 ) for _ in 0 ..< scale*n { var accum = SIMD4<Int32>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt32x16_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD16<Int32>() for i in stride(from: 0, to: int32Data.count, by: 16) { let v = SIMD16(int32Data[i ..< i+16]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt32x16_cast(_ n: Int) { let vecs = UnsafeBufferPointer<SIMD16<Int32>>( start: UnsafeRawPointer(int32Data.baseAddress!).assumingMemoryBound(to: SIMD16<Int32>.self), count: int32Data.count / 16 ) for _ in 0 ..< scale*n { var accum = SIMD16<Int32>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } } let int8Data: UnsafeBufferPointer<Int8> = { let count = 1024 // Allocate memory for `count` Int8s with alignment suitable for all // SIMD vector types. let untyped = UnsafeMutableRawBufferPointer.allocate( byteCount: MemoryLayout<Int8>.size * count, alignment: 16 ) // Intialize the memory as Int8 and fill with random values. let typed = untyped.initializeMemory(as: Int8.self, repeating: 0) var g = SplitMix64(seed: 0) for i in 0 ..< typed.count { typed[i] = .random(in: .min ... .max, using: &g) } return UnsafeBufferPointer(typed) }() @inline(never) public func run_SIMDReduceInt8x1(_ n: Int) { for _ in 0 ..< scale*n { var accum: Int8 = 0 for v in int8Data { accum &+= v &* v } blackHole(accum) } } @inline(never) public func run_SIMDReduceInt8x16_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD16<Int8>() for i in stride(from: 0, to: int8Data.count, by: 16) { let v = SIMD16(int8Data[i ..< i+16]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt8x16_cast(_ n: Int) { let vecs = UnsafeBufferPointer<SIMD16<Int8>>( start: UnsafeRawPointer(int8Data.baseAddress!).assumingMemoryBound(to: SIMD16<Int8>.self), count: int8Data.count / 16 ) for _ in 0 ..< scale*n { var accum = SIMD16<Int8>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt8x64_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD64<Int8>() for i in stride(from: 0, to: int8Data.count, by: 64) { let v = SIMD64(int8Data[i ..< i+64]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt8x64_cast(_ n: Int) { let vecs = UnsafeBufferPointer<SIMD64<Int8>>( start: UnsafeRawPointer(int8Data.baseAddress!).assumingMemoryBound(to: SIMD64<Int8>.self), count: int8Data.count / 64 ) for _ in 0 ..< scale*n { var accum = SIMD64<Int8>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } }
apache-2.0
f3659491709bb61445d4e7bee4c59547
27.676113
96
0.642242
3.405288
false
false
false
false
thebnich/firefox-ios
Storage/FileAccessor.swift
26
3685
/* 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 /** * A convenience class for file operations under a given root directory. * Note that while this class is intended to be used to operate only on files * under the root, this is not strictly enforced: clients can go outside * the path using ".." or symlinks. */ public class FileAccessor { public let rootPath: NSString public init(rootPath: String) { self.rootPath = NSString(string:rootPath) } /** * Gets the absolute directory path at the given relative path, creating it if it does not exist. */ public func getAndEnsureDirectory(relativeDir: String? = nil) throws -> String { var absolutePath = rootPath if let relativeDir = relativeDir { absolutePath = absolutePath.stringByAppendingPathComponent(relativeDir) } let absPath = absolutePath as String try createDir(absPath) return absPath } /** * Gets the file or directory at the given path, relative to the root. */ public func remove(relativePath: String) throws { let path = rootPath.stringByAppendingPathComponent(relativePath) try NSFileManager.defaultManager().removeItemAtPath(path) } /** * Removes the contents of the directory without removing the directory itself. */ public func removeFilesInDirectory(relativePath: String = "") throws { let fileManager = NSFileManager.defaultManager() let path = rootPath.stringByAppendingPathComponent(relativePath) let files = try fileManager.contentsOfDirectoryAtPath(path) for file in files { try remove(NSString(string:relativePath).stringByAppendingPathComponent(file)) } return } /** * Determines whether a file exists at the given path, relative to the root. */ public func exists(relativePath: String) -> Bool { let path = rootPath.stringByAppendingPathComponent(relativePath) return NSFileManager.defaultManager().fileExistsAtPath(path) } /** * Moves the file or directory to the given destination, with both paths relative to the root. * The destination directory is created if it does not exist. */ public func move(fromRelativePath: String, toRelativePath: String) throws { let fromPath = rootPath.stringByAppendingPathComponent(fromRelativePath) let toPath = rootPath.stringByAppendingPathComponent(toRelativePath) as NSString let toDir = toPath.stringByDeletingLastPathComponent try createDir(toDir) try NSFileManager.defaultManager().moveItemAtPath(fromPath, toPath: toPath as String) } public func copy(fromRelativePath: String, toAbsolutePath: String) throws -> Bool { let fromPath = rootPath.stringByAppendingPathComponent(fromRelativePath) guard let dest = NSURL.fileURLWithPath(toAbsolutePath).URLByDeletingLastPathComponent?.path else { return false } try createDir(dest) try NSFileManager.defaultManager().copyItemAtPath(fromPath, toPath: toAbsolutePath) return true } /** * Creates a directory with the given path, including any intermediate directories. * Does nothing if the directory already exists. */ private func createDir(absolutePath: String) throws { try NSFileManager.defaultManager().createDirectoryAtPath(absolutePath, withIntermediateDirectories: true, attributes: nil) } }
mpl-2.0
15f164b927b318eb610103e592f2551d
37.789474
130
0.700678
5.29454
false
false
false
false
eelcokoelewijn/StepUp
StepUp/Modules/Settings/EmailView.swift
1
6793
import UIKit class EmailView: UIView { private lazy var title: UILabel = { let l = UILabel() l.translatesAutoresizingMaskIntoConstraints = false l.textAlignment = .center l.text = "Je oefeningen versturen" l.textColor = .black l.font = UIFont.light(withSize: 17) return l }() lazy var email: UITextField = { let s = UITextField() s.translatesAutoresizingMaskIntoConstraints = false s.borderStyle = UITextField.BorderStyle.roundedRect s.placeholder = "E-mailadres van je therapeut" s.keyboardType = .emailAddress return s }() lazy var name: UITextField = { let s = UITextField() s.translatesAutoresizingMaskIntoConstraints = false s.borderStyle = UITextField.BorderStyle.roundedRect s.placeholder = "Je naam" return s }() lazy var sendButton: UIButton = { let b = UIButton(type: .custom) b.translatesAutoresizingMaskIntoConstraints = false b.titleLabel?.font = UIFont.regular(withSize: 14) b.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10) b.setTitleColor(.white, for: .normal) b.setTitleColor(.buttonDisabled, for: .highlighted) b.backgroundColor = .treamentButtonBackground b.layer.cornerRadius = 3 b.setTitle("Versturen", for: .normal) return b }() override init(frame: CGRect) { super.init(frame: frame) setupViews() applyViewConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupViews() { addSubview(title) addSubview(name) addSubview(email) addSubview(sendButton) } // swiftlint:disable function_body_length private func applyViewConstraints() { var constraints: [NSLayoutConstraint] = [] constraints.append(NSLayoutConstraint(item: title, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: title, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: title, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: name, attribute: .top, relatedBy: .equal, toItem: title, attribute: .bottom, multiplier: 1, constant: 10)) constraints.append(NSLayoutConstraint(item: name, attribute: .left, relatedBy: .equal, toItem: title, attribute: .left, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: name, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: email, attribute: .top, relatedBy: .equal, toItem: name, attribute: .bottom, multiplier: 1, constant: 5)) constraints.append(NSLayoutConstraint(item: email, attribute: .left, relatedBy: .equal, toItem: title, attribute: .left, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: email, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: sendButton, attribute: .top, relatedBy: .equal, toItem: email, attribute: .bottom, multiplier: 1, constant: 5)) constraints.append(NSLayoutConstraint(item: sendButton, attribute: .left, relatedBy: .equal, toItem: title, attribute: .left, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: sendButton, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)) NSLayoutConstraint.activate(constraints) } // swiftlint:enable function_body_length }
mit
b5734beb15d23326d7c17e95f59937d9
46.838028
82
0.39791
7.150526
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Search/Response/SearchResponse/Auxiliary/RenderingContent/FacetOrder/FacetValuesOrder.swift
1
1273
// // FacetValuesOrder.swift // // // Created by Vladislav Fitc on 15/06/2021. // import Foundation /// Facet values ordering rule container public struct FacetValuesOrder { /// Pinned order of facet values. public let order: [String] /// How to display the remaining items. public let sortRemainingBy: SortRule? /// Rule defining the sort order of facet values. public enum SortRule: String, Codable { /// alphabetical (ascending) case alpha /// facet count (descending) case count /// hidden (show only pinned values) case hidden } /** - parameters: - order: Pinned order of facet values. - sortRemainingBy: How to display the remaining items. */ public init(order: [String] = [], sortRemainingBy: SortRule? = nil) { self.order = order self.sortRemainingBy = sortRemainingBy } } extension FacetValuesOrder: Codable { enum CodingKeys: String, CodingKey { case order case sortRemainingBy } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.order = try container.decodeIfPresent(forKey: .order) ?? [] self.sortRemainingBy = try container.decodeIfPresent(forKey: .sortRemainingBy) } }
mit
edbbe4f3a6aba4f5ca9b6ab1bb90aa54
21.333333
82
0.678712
4.080128
false
false
false
false
Foild/SugarRecord
example/SugarRecordExample/Shared/Controllers/RealmTableViewController.swift
1
2321
// // RealmTableViewController.swift // SugarRecordExample // // Created by Pedro Piñera Buendía on 25/12/14. // Copyright (c) 2014 Robert Dougan. All rights reserved. // import Foundation import Realm class RealmTableViewController: StackTableViewController { //MARK: - Attributes var data: SugarRecordResults<RLMObject>? //MARK: - Viewcontroller Lifecycle override func viewDidLoad() { super.viewDidLoad() self.title = "Realm" self.stack = DefaultREALMStack(stackName: "Realm", stackDescription: "") SugarRecord.addStack(self.stack!) } //MARK: - Actions @IBAction override func add(sender: AnyObject?) { let formatter = NSDateFormatter() formatter.dateFormat = "MMMM d yyyy - HH:mm:ss" let model = RealmModel.create() as! RealmModel model.name = formatter.stringFromDate(NSDate()) model.save() self.fetchData() let indexPath = NSIndexPath(forRow: 0, inSection: 0) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Top) } //MARK: - Data Source override func fetchData() { self.data = RealmModel.all().sorted(by: "date", ascending: false).find() } override func dataCount() -> Int { if (data == nil) { return 0 } else { return data!.count } } //MARK: - Cell override func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) { let formatter = NSDateFormatter() formatter.dateFormat = "MMMM d yyyy - HH:mm:ss" let model = self.data![indexPath.row] as! RealmModel cell.textLabel?.text = model.name cell.detailTextLabel?.text = formatter.stringFromDate(model.date) } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == .Delete) { let model = self.data![indexPath.row] as! RealmModel model.beginWriting().delete().endWriting() self.fetchData() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } override func cellIdentifier() -> String { return "ModelCell" } }
mit
0e71f970623ba7b370694686d34969b2
29.12987
157
0.633463
4.801242
false
false
false
false
denis631/Bankathon-Vienna-
frontend/cashSlicer/cashSlicer/Spending/SpendingScene.swift
1
6083
// // SpendingScene.swift // test // // Created by Denis Grebennicov on 30.05.17. // Copyright © 2017 ca$hSlicer. All rights reserved. // import SpriteKit import GameplayKit import RxSwift enum TouchEvent { case drag(node: SKShapeNode) case merge(nodeA: SKShapeNode, nodeB: SKShapeNode) } class GameScene: SKScene { var parentViewController: UIViewController! var nodes: [SKShapeNode] = [] var totalCost = 0.0 var budgetNode: SKShapeNode! var currentTouchEvent: TouchEvent? = nil let dragNodeNormalizedLocation = Variable<CGPoint>(CGPoint.zero) func createBubbles(fromSpendingItem spendingItem: BubbleConstructable) { guard let scene = view?.scene else { return } let radius = min(CGFloat(spendingItem.cost / totalCost), CGFloat(0.6)) * scene.frame.size.width * 0.5 let position = CGPoint(x: scene.frame.midX, y: scene.frame.midY) let node = SKShapeNode(circleOfRadius: radius) node.physicsBody = SKPhysicsBody(circleOfRadius: radius) node.strokeColor = UIColor.white node.lineWidth = 5 let label = SKLabelNode(text: spendingItem.previewText) label.fontColor = UIColor.black let scalingFactor = min(node.frame.width / label.frame.width, node.frame.height / label.frame.height) * 0.8 label.fontSize *= scalingFactor label.position = CGPoint(x: node.frame.midX, y: node.frame.midY - label.frame.midY) if spendingItem.priority > 0 { node.fillColor = spendingItem.priority.color } else { node.fillColor = UIColor.white } node.physicsBody?.allowsRotation = false node.associatedObject = spendingItem node.addChild(label) DispatchQueue.main.asyncAfter(deadline: .now() + 0.33) { [unowned self] in self.nodes.append(node) self.budgetNode.addChild(node) let randomOffset = CGPoint(x: position.x + CGFloat(20 + arc4random() % 20), y: position.y + CGFloat(20 + arc4random() % 20)) let moveAction = SKAction.move(to: randomOffset, duration: 1.0) node.run(moveAction) } } override func didMove(to view: SKView) { self.physicsWorld.gravity = CGVector() let gravityField = SKFieldNode.radialGravityField() gravityField.minimumRadius = 200 let boundary = CGRect(origin: CGPoint(x: self.frame.size.width / 2, y: self.frame.size.width / 2), size: CGSize(width: self.frame.size.width / 2, height: self.frame.size.width / 2)) budgetNode = SKShapeNode(ellipseIn: boundary) // budgetNode.strokeColor = UIColor.clear budgetNode.addChild(gravityField) addChild(budgetNode) self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame) let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(self.handlePinchFrom(_:))) self.view?.addGestureRecognizer(pinchGesture) } func handlePinchFrom(_ sender: UIPinchGestureRecognizer) { currentTouchEvent = nil if sender.state == .changed { let pinch = SKAction.scale(by: sender.scale, duration: 0.0) budgetNode.run(pinch) sender.scale = 1.0 } } func node(fromTouch touch: UITouch) -> SKShapeNode? { let location = touch.location(in: self) let node = self.atPoint(location) guard node.frame.contains(location) else { return nil } node.physicsBody?.affectedByGravity = false if node is SKShapeNode { return node as? SKShapeNode } return node.parent as? SKShapeNode } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let node = node(fromTouch: touches.first!), touches.count == 1 { let touch = touches.first! if touch.tapCount == 2 { let transactionVC = parentViewController.storyboard?.instantiateViewController(withIdentifier: "transactionVC") as! TransactionsViewController transactionVC.viewModel.category.value = (node.associatedObject?.priortyUpdateField)! parentViewController.present(transactionVC, animated: true) } else { node.physicsBody?.affectedByGravity = false currentTouchEvent = .drag(node: node) } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touchEvent = currentTouchEvent else { return } switch touchEvent { case .drag(node: let nodeToDrag): var location = touches.first!.location(in: self) nodeToDrag.position = location location.x += -frame.origin.x location.y += -frame.origin.y location.y = frame.size.height - location.y let normalizedLocation = CGPoint(x: location.x / frame.size.width, y: location.y / frame.size.height) dragNodeNormalizedLocation.value = normalizedLocation default: break } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touchEvent = currentTouchEvent, let scene = view?.scene else { return } switch touchEvent { case .drag(node: let nodeToDrag): nodeToDrag.physicsBody?.affectedByGravity = true let newPosition = CGPoint(x: scene.frame.midX, y: scene.frame.midY) let moveAction = SKAction.move(to: newPosition, duration: 2.0) nodeToDrag.run(moveAction) default: break //TODO: implement } } }
mit
f1fc7b31828fc2fa5e02110c74b9f8b3
33.954023
158
0.595692
4.725719
false
false
false
false
Speicher210/wingu-sdk-ios-demoapp
Example/winguSDK-iOS/ViewController.swift
1
2135
// // ViewController.swift // winguSDK-iOS // // Created by Jakub Mazur on 08/16/2017. // Copyright (c) 2017 wingu AG. All rights reserved. // import UIKit import winguSDK class ViewController: UIViewController { let winguSegueIdentifier = "loadWinguSegue" @IBOutlet weak var tableView: UITableView! var beaconsLocationManger : WinguLocations! var channels : [Channel] = [Channel]() { didSet { self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.beaconsLocationManger = WinguLocations.sharedInstance self.beaconsLocationManger.delegate = self self.beaconsLocationManger.startBeaconsRanging() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == winguSegueIdentifier { let gp = sender as? Channel let destVC = (segue.destination as! WinguDeckViewController) destVC.content = gp?.content! destVC.channelId = gp?.uID } } } // MARK: - BeaconsLocationManagerDelegate extension ViewController : WinguLocationsDelegate { func winguRangedChannels(_ channels: [Channel]) { self.channels = channels } } // MARK: - UITableViewDelegate, UITableViewDataSource extension ViewController : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:UITableViewCell=UITableViewCell(style: .subtitle, reuseIdentifier: "winguDemoCell") let guidepost : Channel = self.channels[indexPath.row] cell.textLabel?.text = guidepost.name cell.detailTextLabel?.text = guidepost.uID return cell } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.channels.count } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: winguSegueIdentifier, sender: self.channels[indexPath.row]) } }
apache-2.0
7fbb71f9f8412e63639973e1ce3ec3ee
31.846154
101
0.684309
4.744444
false
false
false
false
anzfactory/QiitaCollection
QiitaCollection/AdventCalendarTableViewCell.swift
1
1311
// // AdventCalendarTableViewCell.swift // QiitaCollection // // Created by ANZ on 2015/07/06. // Copyright (c) 2015年 anz. All rights reserved. // import UIKit class AdventCalendarTableViewCell: UITableViewCell { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var title: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var day: UILabel! override func awakeFromNib() { super.awakeFromNib() self.dateLabel.textColor = UIColor.textAdventCalendar() self.dateLabel.backgroundColor = UIColor.backgroundSub() self.dateLabel.drawBorder(UIColor.borderImageViewCircle(), linewidth: 1) self.day.textColor = UIColor.textAdventCalendar() self.title.textColor = UIColor.textBase() self.authorLabel.textColor = UIColor.textBase() self.prepare() } override func prepareForReuse() { super.prepareForReuse() self.prepare() } private func prepare() { self.dateLabel.text = "" self.title.text = "" self.authorLabel.text = "" } func show(entity: AdventEntity) { self.dateLabel.text = String(entity.date) self.title.text = entity.displayTitle() self.authorLabel.text = entity.displayAuthor() } }
mit
c8fdd78ded6625bf81dae4780dfec322
25.714286
80
0.650879
4.392617
false
false
false
false
milseman/swift
test/ClangImporter/CoreServices_test.swift
44
996
// RUN: %target-typecheck-verify-swift %clang-importer-sdk // REQUIRES: objc_interop import CoreServices func test(_ url: CFURL, ident: CSIdentity) { _ = CSBackupIsItemExcluded(url, nil) // okay _ = nil as TypeThatDoesNotExist? // expected-error {{use of undeclared type 'TypeThatDoesNotExist'}} _ = nil as CoreServices.Collection? // okay _ = kCollectionNoAttributes // expected-error{{use of unresolved identifier 'kCollectionNoAttributes'}} var name: Unmanaged<CFString>? _ = LSCopyDisplayNameForURL(url, &name) as OSStatus // okay let unicharArray: [UniChar] = [ 0x61, 0x62, 0x63, 0x2E, 0x64 ] var extIndex: Int = 0 LSGetExtensionInfo(unicharArray.count, unicharArray, &extIndex) // okay _ = CSIdentityCreateCopy(nil, ident) // okay var vers: UInt32 = 0 _ = KCGetKeychainManagerVersion(&vers) as OSStatus// expected-error{{use of unresolved identifier 'KCGetKeychainManagerVersion'}} _ = CoreServices.KCGetKeychainManagerVersion(&vers) as OSStatus// okay }
apache-2.0
acc9be8ff3e4387730c2ecb616534fe8
35.888889
131
0.732932
3.621818
false
false
false
false
alreadyRight/Swift-algorithm
自定义cell编辑状态/Pods/SnapKit/Source/Debugging.swift
80
6035
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public extension LayoutConstraint { override public var description: String { var description = "<" description += descriptionForObject(self) if let firstItem = conditionalOptional(from: self.firstItem) { description += " \(descriptionForObject(firstItem))" } if self.firstAttribute != .notAnAttribute { description += ".\(descriptionForAttribute(self.firstAttribute))" } description += " \(descriptionForRelation(self.relation))" if let secondItem = self.secondItem { description += " \(descriptionForObject(secondItem))" } if self.secondAttribute != .notAnAttribute { description += ".\(descriptionForAttribute(self.secondAttribute))" } if self.multiplier != 1.0 { description += " * \(self.multiplier)" } if self.secondAttribute == .notAnAttribute { description += " \(self.constant)" } else { if self.constant > 0.0 { description += " + \(self.constant)" } else if self.constant < 0.0 { description += " - \(abs(self.constant))" } } if self.priority.rawValue != 1000.0 { description += " ^\(self.priority)" } description += ">" return description } } private func descriptionForRelation(_ relation: LayoutRelation) -> String { switch relation { case .equal: return "==" case .greaterThanOrEqual: return ">=" case .lessThanOrEqual: return "<=" } } private func descriptionForAttribute(_ attribute: LayoutAttribute) -> String { #if os(iOS) || os(tvOS) switch attribute { case .notAnAttribute: return "notAnAttribute" case .top: return "top" case .left: return "left" case .bottom: return "bottom" case .right: return "right" case .leading: return "leading" case .trailing: return "trailing" case .width: return "width" case .height: return "height" case .centerX: return "centerX" case .centerY: return "centerY" case .lastBaseline: return "lastBaseline" case .firstBaseline: return "firstBaseline" case .topMargin: return "topMargin" case .leftMargin: return "leftMargin" case .bottomMargin: return "bottomMargin" case .rightMargin: return "rightMargin" case .leadingMargin: return "leadingMargin" case .trailingMargin: return "trailingMargin" case .centerXWithinMargins: return "centerXWithinMargins" case .centerYWithinMargins: return "centerYWithinMargins" } #else switch attribute { case .notAnAttribute: return "notAnAttribute" case .top: return "top" case .left: return "left" case .bottom: return "bottom" case .right: return "right" case .leading: return "leading" case .trailing: return "trailing" case .width: return "width" case .height: return "height" case .centerX: return "centerX" case .centerY: return "centerY" case .lastBaseline: return "lastBaseline" case .firstBaseline: return "firstBaseline" } #endif } private func conditionalOptional<T>(from object: Optional<T>) -> Optional<T> { return object } private func conditionalOptional<T>(from object: T) -> Optional<T> { return Optional.some(object) } private func descriptionForObject(_ object: AnyObject) -> String { let pointerDescription = String(format: "%p", UInt(bitPattern: ObjectIdentifier(object))) var desc = "" desc += type(of: object).description() if let object = object as? ConstraintView { desc += ":\(object.snp.label() ?? pointerDescription)" } else if let object = object as? LayoutConstraint { desc += ":\(object.label ?? pointerDescription)" } else { desc += ":\(pointerDescription)" } if let object = object as? LayoutConstraint, let file = object.constraint?.sourceLocation.0, let line = object.constraint?.sourceLocation.1 { desc += "@\((file as NSString).lastPathComponent)#\(line)" } desc += "" return desc }
mit
f97d69de710c589116b3708a6d1925ff
36.71875
145
0.584921
4.983485
false
false
false
false
EaglesoftZJ/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Managed Runtime/AAManagedTableController.swift
1
5086
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation open class AAManagedTableController: AAViewController { public let style: AAContentTableStyle open var managedTableDelegate: AAManagedTableControllerDelegate? public let binder = AABinder() open var tableView: UITableView! open var managedTable: AAManagedTable! open var unbindOnDissapear: Bool = false fileprivate var isBinded: Bool = false public init(style: AAContentTableStyle) { self.style = style super.init() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() // Creating tables let tableViewStyle: UITableViewStyle switch(style) { case .plain: tableViewStyle = .plain break case .settingsPlain: tableViewStyle = .plain break case .settingsGrouped: tableViewStyle = .grouped break } tableView = UITableView(frame: view.bounds, style: tableViewStyle) // Disabling separators as we use manual separators handling tableView.separatorStyle = .none // Setting tableView and view bg color depends on table style tableView.backgroundColor = style == .plain ? appStyle.vcBgColor : appStyle.vcBackyardColor view.backgroundColor = tableView.backgroundColor // Useful for making table view with fixed row height if let d = managedTableDelegate { d.managedTableWillLoad(self) } managedTable = AAManagedTable(style: style, tableView: tableView, controller: self) view.addSubview(tableView) // Invoking table loading if let d = managedTableDelegate { d.managedTableLoad(self, table: managedTable) } // Initial load of Managed Table tableView.reloadData() } open override func viewWillAppear(_ animated: Bool) { if let t = tableView { if let row = t.indexPathForSelectedRow { t.deselectRow(at: row, animated: animated) } } super.viewWillAppear(animated) if let m = managedTable { // Performing data binding if let d = managedTableDelegate { d.managedTableBind(self, table: m, binder: binder) } if !isBinded { // Binding rows m.bind(binder) isBinded = true } // Passing event to table m.controllerViewWillAppear(animated) // Reloading data tableView.reloadData() } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Stopping data binding here if let m = managedTable { if let d = managedTableDelegate { d.managedTableUnbind(self, table: m, binder: binder) } if unbindOnDissapear { if isBinded { // Unbinding rows m.unbind(binder) isBinded = false } // Removing all bindings binder.unbindAll() } // Passing event to table m.controllerViewWillDisappear(animated) } } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if let m = managedTable { // Passing event to table m.controllerViewDidDisappear(animated) } } open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableView.frame = view.bounds } } public protocol AAManagedTableControllerDelegate { func managedTableWillLoad(_ controller: AAManagedTableController) func managedTableLoad(_ controller: AAManagedTableController, table: AAManagedTable) func managedTableBind(_ controller: AAManagedTableController, table: AAManagedTable, binder: AABinder) func managedTableUnbind(_ controller: AAManagedTableController, table: AAManagedTable, binder: AABinder) } public extension AAManagedTableControllerDelegate { public func managedTableLoad(_ controller: AAManagedTableController, table: AAManagedTable) { // Do nothing } public func managedTableBind(_ controller: AAManagedTableController, table: AAManagedTable, binder: AABinder) { // Do nothing } public func managedTableUnbind(_ controller: AAManagedTableController, table: AAManagedTable, binder: AABinder) { // Do nothing } }
agpl-3.0
3a0e18adc54f72244425fa8bfb2b11b3
28.74269
117
0.581007
5.534276
false
false
false
false
ubi-naist/SenStick
SenStickSDK/SenStickSDK/MagneticFieldSensorService.swift
1
2556
// // MagneticSensorService.swift // SenStickSDK // // Created by AkihiroUehara on 2016/05/24. // Copyright © 2016年 AkihiroUehara. All rights reserved. // import Foundation import CoreMotion public enum MagneticFieldRange : UInt16, CustomStringConvertible { case magneticRangeDefault = 0x00 public var description : String { switch self { case .magneticRangeDefault: return "magneticRangeDefault" } } } // 磁界のデータ構造体 // 16-bit 符号付き数字 フルスケール f ±4800 μT struct MagneticFieldRawData { var xRawValue : Int16 var yRawValue : Int16 var zRawValue : Int16 init(xRawValue:Int16, yRawValue:Int16, zRawValue:Int16) { self.xRawValue = xRawValue self.yRawValue = yRawValue self.zRawValue = zRawValue } // 物理センサーの1uTあたりのLBSの値 static func getLSBperuT(_ range: MagneticFieldRange) -> Double { switch range { case .magneticRangeDefault: return 1/0.15; // AK8963, 16-bit mode } } static func unpack(_ data: [Byte]) -> MagneticFieldRawData { let x = Int16.unpack(data[0..<2]) let y = Int16.unpack(data[2..<4]) let z = Int16.unpack(data[4..<6]) return MagneticFieldRawData(xRawValue: x!, yRawValue: y!, zRawValue: z!) } } extension CMMagneticField : SensorDataPackableType { public typealias RangeType = MagneticFieldRange public static func unpack(_ range:MagneticFieldRange, value: [UInt8]) -> CMMagneticField? { guard value.count >= 6 else { return nil } let rawData = MagneticFieldRawData.unpack(value) let LSBperuT = MagneticFieldRawData.getLSBperuT(range) // FIXME 右手系/左手系などの座標変換など確認すること。 //debugPrint("x:\(rawData.xRawValue), y:\(rawData.yRawValue), z: \(rawData.zRawValue), lsbPerDeg:\(LSBperuT)") return CMMagneticField(x: Double(rawData.xRawValue) / Double(LSBperuT), y: Double(rawData.yRawValue) / Double(LSBperuT), z: Double(rawData.zRawValue) / Double(LSBperuT)) } } // センサー各種のベースタイプ, Tはセンサデータ独自のデータ型, Sはサンプリングの型、 open class MagneticFieldSensorService: SenStickSensorService<CMMagneticField, MagneticFieldRange> { required public init?(device:SenStickDevice) { super.init(device: device, sensorType: SenStickSensorType.magneticFieldSensor) } }
mit
6a90b158e4dbf92138960747081c3fec
27.841463
177
0.665539
3.452555
false
false
false
false
Michaelyb520/PhotoBrowser
PhotoBrowser/PhotoBrowser/Controller/PhotoBrowser+ZoomAnim.swift
1
4290
// // PhotoBrowser+ZoomAnim.swift // PhotoBrowser // // Created by 冯成林 on 15/8/11. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit /** 力求用最简单的方式实现 */ extension PhotoBrowser{ /** 展示动画: 妈妈,这里好复杂~~ */ func zoomInWithAnim(page: Int){ let photoModel = photoModels[page] let propImgV = UIImageView(frame: photoModel.sourceView.convertRect(photoModel.sourceView.bounds, toView: vc.view)) propImgV.contentMode = UIViewContentMode.ScaleAspectFill propImgV.clipsToBounds = true vc.view.addSubview(propImgV) self.view.alpha = 0 self.collectionView.alpha = 0 if photoType == PhotoType.Local { propImgV.image = photoModel.localImg handleShowAnim(propImgV, thumbNailSize: nil) }else{ let cache = Cache<UIImage>(name: CFPBCacheKey) cache.fetch(key: photoModel.hostHDImgURL).onSuccess {[unowned self] image in propImgV.image = image self.handleShowAnim(propImgV, thumbNailSize: nil) }.onFailure{[unowned self] error in let size = CGSizeMake(CFPBThumbNailWH, CFPBThumbNailWH) if photoModel.hostThumbnailImg != nil { propImgV.image = photoModel.hostThumbnailImg self.handleShowAnim(propImgV, thumbNailSize: size) }else{ /** 这里需要大量修改 */ let img = UIImage.imageWithColor(size: CGSizeMake(CFPBThumbNailWH, CFPBThumbNailWH)) propImgV.image = img self.handleShowAnim(propImgV, thumbNailSize: size) } } } } func handleShowAnim(propImgV: UIImageView,thumbNailSize: CGSize?){ let showSize = thumbNailSize ?? CGSize.decisionShowSize(propImgV.image!.size, contentSize: vc.view.bounds.size) UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 20, options: UIViewAnimationOptions.CurveEaseOut, animations: {[unowned self] () -> Void in propImgV.bounds = CGRectMake(0, 0, showSize.width, showSize.height) propImgV.center = self.vc.view.center self.view.alpha = 1 }) { (complete) -> Void in propImgV.removeFromSuperview() self.collectionView.alpha = 1 } } /** 关闭动画 */ func zoomOutWithAnim(page: Int){ let photoModel = photoModels[page] let cell = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: page, inSection: 0)) as! ItemCell let cellImageView = cell.imageV let propImgV = UIImageView(frame: cellImageView.frame) propImgV.contentMode = UIViewContentMode.ScaleAspectFill propImgV.clipsToBounds = true propImgV.image = !cell.hasHDImage && photoModel.hostThumbnailImg == nil ? UIImage.imageWithColor(size: CGSizeMake(CFPBThumbNailWH, CFPBThumbNailWH)) : cellImageView.image propImgV.frame = cellImageView.frame vc.view.addSubview(propImgV) cellImageView.hidden = true photoModel.sourceView.hidden = true UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 20, options: UIViewAnimationOptions.CurveEaseOut, animations: {[unowned self] () -> Void in self.view.alpha = 0 propImgV.frame = photoModel.sourceView.convertRect(photoModel.sourceView.bounds, toView: self.vc.view) }) { (complete) -> Void in photoModel.sourceView.hidden = false propImgV.removeFromSuperview() self.view.removeFromSuperview() self.removeFromParentViewController() } } }
mit
e1de80836075d6f8d71aed14de200a34
34.058333
193
0.568474
5.344346
false
false
false
false
SPECURE/rmbt-ios-client
Sources/QOSTest.swift
1
4015
/***************************************************************************************************** * Copyright 2014-2016 SPECURE GmbH * * 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 /// open class QOSTest: CustomStringConvertible { /* TODO: declarations in extensions cannot be overriden yet */ // should be abstract let PARAM_TEST_UID = "qos_test_uid" let PARAM_CONCURRENCY_GROUP = "concurrency_group" let PARAM_SERVER_ADDRESS = "server_addr" let PARAM_SERVER_PORT = "server_port" let PARAM_TIMEOUT = "timeout" // values from server /// The id of this QOS test (provided by control server) var qosTestId: UInt = 0 // TODO: make this field optional? /// The concurrency group of this QOS test (provided by control server) var concurrencyGroup: UInt = 0 // TODO: make this field optional? /// The server address of this QOS test (provided by control server) var serverAddress: String = "_server_address"// TODO: make this field optional? /// The server port of this QOS test (provided by control server) var serverPort: UInt16 = 443 // TODO: make this field optional? /// The general timeout in nano seconds of this QOS test (provided by control server) var timeout: UInt64 = QOS_DEFAULT_TIMEOUT_NS // var testStartTimestampNS: UInt64? var testEndTimestampNS: UInt64? var hasStarted: Bool = false var hasFinished: Bool = false // /// public var description: String { return "QOSTest(\(String(describing: getType()?.rawValue))) [id: \(qosTestId), concurrencyGroup: \(concurrencyGroup), serverAddress: \(serverAddress), serverPort: \(serverPort), timeout: \(timeout)]" } // /// init(testParameters: QOSTestParameters) { // qosTestId if let qosTestIdString = testParameters[PARAM_TEST_UID] as? String { if let qosTestId = UInt(qosTestIdString) { self.qosTestId = qosTestId } } // concurrencyGroup if let concurrencyGroupString = testParameters[PARAM_CONCURRENCY_GROUP] as? String { if let concurrencyGroup = UInt(concurrencyGroupString) { self.concurrencyGroup = concurrencyGroup } } // serverAddress if let serverAddress = testParameters[PARAM_SERVER_ADDRESS] as? String { // TODO: length check on url? self.serverAddress = serverAddress } // serverPort if let serverPortString = testParameters[PARAM_SERVER_PORT] as? String { if let serverPort = UInt16(serverPortString) { self.serverPort = serverPort } } // timeout if let timeoutString = testParameters[PARAM_TIMEOUT] as? NSString { let timeout = timeoutString.longLongValue if timeout > 0 { self.timeout = UInt64(timeout) } } } // /// returns the type of this test object func getType() -> QosMeasurementType! { return nil } } // MARK: Printable methods /// // extension QOSTest: Printable { // // /// // var description: String { // return "QOSTest(\(getType().rawValue)) [id: \(qosTestId), concurrencyGroup: \(concurrencyGroup), serverAddress: \(serverAddress), serverPort: \(serverPort), timeout: \(timeout)]" // } // }
apache-2.0
34e24e78933922d3c6da7e6b67092774
32.739496
207
0.6132
4.729093
false
true
false
false
IvanVorobei/TwitterLaunchAnimation
TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/animation/SPAnimation.swift
2
2528
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class SPAnimation { static func animate(_ duration: TimeInterval, animations: (() -> Void)!, delay: TimeInterval = 0, options: UIViewAnimationOptions = [], withComplection completion: (() -> Void)! = {}) { UIView.animate( withDuration: duration, delay: delay, options: options, animations: { animations() }, completion: { finished in completion() }) } static func animateWithRepeatition(_ duration: TimeInterval, animations: (() -> Void)!, delay: TimeInterval = 0, options: UIViewAnimationOptions = [], withComplection completion: (() -> Void)! = {}) { var optionsWithRepeatition = options optionsWithRepeatition.insert([.autoreverse, .repeat]) self.animate( duration, animations: { animations() }, delay: delay, options: optionsWithRepeatition, withComplection: { finished in completion() }) } }
mit
06bee030a8bb0450dfd08bc9d5ebeb05
37.876923
88
0.586862
5.578366
false
false
false
false
leehana-ios/util-hana-music
Hana Music/MusicListViewController.swift
1
5192
// // MusicListViewController.swift // Hana Music // // Created by Hana Lee on 2015. 8. 10.. // Copyright (c) 2015년 Hana Lee. All rights reserved. // import UIKit import AVFoundation var activeIndex:Int = -1 var audioList = NSBundle.mainBundle().pathsForResourcesOfType("mp3", inDirectory: "") class MusicListViewController: UIViewController, UITableViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source // func numberOfSectionsInTableView(tableView: UITableView) -> Int { // // #warning Potentially incomplete method implementation. // // Return the number of sections. // return 1 // } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return audioList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("musicCell", forIndexPath: indexPath) as! UITableViewCell // let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "musicCell") let fileName = audioList[indexPath.row] as! String var name = split(fileName) {$0 == "/"} let cnt = name.count var songName = name[cnt-1] cell.textLabel?.text = songName let albumArtWork:UIImage = getArtwork(indexPath.row) cell.imageView!.image = albumArtWork let albumName:String = getAlbumName(indexPath.row) cell.detailTextLabel?.text = albumName return cell } func getAlbumName(index: Int) -> String { var audioPath = audioList[index] as! String var name = split(audioPath) {$0 == "/"} let cnt = name.count var songName = name[cnt-1] var songTitle = songName.stringByReplacingOccurrencesOfString(".mp3", withString: "") var encodedPath = audioPath.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! let audioPath2:NSURL! = NSBundle.mainBundle().URLForResource(songTitle, withExtension: "mp3") let playerItem = AVPlayerItem(URL: audioPath2) // println(playerItem.asset.commonMetadata) var assets:AVURLAsset = AVURLAsset(URL: NSURL(string: encodedPath), options: nil) var metaData = assets.commonMetadata var albumNames = AVMetadataItem.metadataItemsFromArray(playerItem.asset.commonMetadata, withKey: AVMetadataCommonKeyAlbumName, keySpace: AVMetadataKeySpaceCommon) var albumNameItem:AVMetadataItem = albumNames[0] as! AVMetadataItem var albumName:String? if albumNameItem.keySpace == AVMetadataKeySpaceID3 { albumName = albumNameItem.value as? String } else if albumNameItem.keySpace == AVMetadataKeySpaceiTunes { } return albumName! } func getArtwork(index : Int) -> UIImage { var audioPath = audioList[index] as! String var name = split(audioPath) {$0 == "/"} let cnt = name.count var songName = name[cnt-1] var songTitle = songName.stringByReplacingOccurrencesOfString(".mp3", withString: "") var encodedPath = audioPath.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! let audioPath2:NSURL! = NSBundle.mainBundle().URLForResource(songTitle, withExtension: "mp3") let playerItem = AVPlayerItem(URL: audioPath2) // println(playerItem.asset.commonMetadata) var assets:AVURLAsset = AVURLAsset(URL: NSURL(string: encodedPath), options: nil) var metaData = assets.commonMetadata // println(metaData) var artworks:NSArray = AVMetadataItem.metadataItemsFromArray(playerItem.asset.commonMetadata, withKey: AVMetadataCommonKeyArtwork, keySpace: AVMetadataKeySpaceCommon) var artwork:AVMetadataItem = artworks[0] as! AVMetadataItem var artworkImage:UIImage? if artwork.keySpace == AVMetadataKeySpaceID3 { artworkImage = UIImage(data: artwork.value as! NSData)! } else if artwork.keySpace == AVMetadataKeySpaceiTunes { } return artworkImage! } func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { activeIndex = indexPath.row return indexPath } }
gpl-2.0
1e4b079f5b496a5089d9666f846d2950
36.071429
174
0.66185
5.153923
false
false
false
false
stuart-grey/shinobicharts-style-guide
case-studies/StyleGuru/StyleGuru/sparklines/SparkChartsViewController.swift
1
1338
// // Copyright 2015 Scott Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit class SparkChartsViewController: UIViewController { @IBOutlet var charts: [ShinobiChart]! var chartDatasources = [SparkChartDatasource]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. for chartType in SparkChartType.allValues { chartDatasources.append(SparkChartDatasource.defaultData(chartType)!) } for i in 0..<charts.count { charts[i].datasource = chartDatasources[i] } prepareCharts() } private func prepareCharts() { for chart in charts { let xAxis = SChartDateTimeAxis() chart.xAxis = xAxis let yAxis = SChartNumberAxis() chart.yAxis = yAxis } } }
apache-2.0
305c02267faf4b0aa6ab08ea07a05538
25.235294
75
0.692078
4.372549
false
false
false
false
kandelvijaya/XcodeFormatter
XcodeFormatter/Core/Regex/MatchPattern.swift
1
1629
// // MatchPattern.swift // Swinter // // Created by Vijaya Prakash Kandel on 9/27/16. // Copyright © 2016 Vijaya Prakash Kandel. All rights reserved. // import Foundation /// Try it on www.regex101.com /// Capture Groups are important. They are used as index /// in MatchCorrectionRule. That index starts from 1. Not 0. enum MatchPattern: String { /// Space matcher patterns /// capture groups 1 , 2 , 3 matches lhs space, identifier and rhs space /// Example: let i : Int /// CP1 = ` ` CP2 = `:` CP3 = ` ` /// case colon = "[\\S]([ ]*)(:)([ ]*)(?=[\\S])" case comma = "[\\S]([ ]*)(,)([ ]*)(?=[\\S])" case functionReturnArrow = "[\\S]([ ]*)(->)([ ]*)(?=[\\S])" case trailingCurlyBracket = "([^ \\.\\(\\[])([ ]*)\\{$" /// Ternary Operator pattern /// capture groups 1,2,3,4 matches the space inbetween from left to right /// Example: true ? 1 : 0 /// CP1 = ` ` CP2 = ` ` CP3 = ` ` CP4 = ` ` /// /// This wont match /// [someOpt?.map{ $0 } : "xyz"] /// let dict = [(model as? AModelType) ?? AModelType : BModelType ] /// case ternaryOperator = "[^\\?](?<! as)([\\s]*)(?:\\?)([\\s]*)(?:[^\\s:.\\[]+)([\\s]*)(?::)([\\s]*)[\\S]" // Mathces all occurances of \" but not \\", \\\" case stringQuote = "([^\\\\]\\\")|(^\\\")" case singleLineComment = "//" case fileComment = "^(\\/\\/\\n)\\/\\/.*.swift\\n\\/\\/.*\\n\\/\\/\\n\\/\\/.*\\n(\\/\\/.*\\n\\/\\/\n)" var regex: NSRegularExpression? { return NSRegularExpression.regexFrom(pattern: self.rawValue) } }
mit
6f815373ec4abfb004430ad48b48a992
31.56
108
0.487101
3.363636
false
false
false
false
dongdonggaui/BiblioArchiver
Carthage/Checkouts/Fuzi/Fuzi/Element.swift
1
5907
// Element.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 /// Represents an element in `XMLDocument` or `HTMLDocument` open class XMLElement: XMLNode { /// The element's namespace. open fileprivate(set) lazy var namespace: String? = { return ^-^((self.cNode.pointee.ns != nil ?self.cNode.pointee.ns.pointee.prefix :nil)!) }() /// The element's tag. open fileprivate(set) lazy var tag: String? = { return ^-^self.cNode.pointee.name }() // MARK: - Accessing Attributes /// All attributes for the element. open fileprivate(set) lazy var attributes: [String : String] = { var attributes = [String: String]() var attribute = self.cNode.pointee.properties while attribute != nil { if let key = ^-^attribute?.pointee.name, let value = self.attr(key) { attributes[key] = value } attribute = attribute?.pointee.next } return attributes }() /** Returns the value for the attribute with the specified key. - parameter name: The attribute name. - parameter ns: The namespace, or `nil` by default if not using a namespace - returns: The attribute value, or `nil` if the attribute is not defined. */ open func attr(_ name: String, namespace ns: String? = nil) -> String? { var value: String? = nil let xmlValue: UnsafeMutablePointer<xmlChar>? if let ns = ns { xmlValue = xmlGetNsProp(cNode, name, ns) } else { xmlValue = xmlGetProp(cNode, name) } if xmlValue != nil { value = ^-^xmlValue xmlFree(xmlValue) } return value } // MARK: - Accessing Children /// The element's children elements. open var children: [XMLElement] { return LinkedCNodes(head: cNode.pointee.children).flatMap { XMLElement(cNode: $0, document: self.document) } } /** Get the element's child nodes of specified types - parameter types: type of nodes that should be fetched (e.g. .Element, .Text, .Comment) - returns: all children of specified types */ open func childNodes(ofTypes types: [XMLNodeType]) -> [XMLNode] { return LinkedCNodes(head: cNode.pointee.children, types: types).flatMap { node in switch node.pointee.type { case XMLNodeType.Element: return XMLElement(cNode: node, document: self.document) default: return XMLNode(cNode: node, document: self.document, type: node.pointee.type) } } } /** Returns the first child element with a tag, or `nil` if no such element exists. - parameter tag: The tag name. - parameter ns: The namespace, or `nil` by default if not using a namespace - returns: The child element. */ open func firstChild(tag: String, inNamespace ns: String? = nil) -> XMLElement? { var nodePtr = cNode.pointee.children while nodePtr != nil { if cXMLNodeMatchesTagInNamespace(nodePtr, tag: tag, ns: ns) { return XMLElement(cNode: nodePtr!, document: self.document) } nodePtr = nodePtr?.pointee.next } return nil } /** Returns all children elements with the specified tag. - parameter tag: The tag name. - parameter ns: The namepsace, or `nil` by default if not using a namespace - returns: The children elements. */ open func children(tag: String, inNamespace ns: String? = nil) -> [XMLElement] { return LinkedCNodes(head: cNode.pointee.children).flatMap { cXMLNodeMatchesTagInNamespace($0, tag: tag, ns: ns) ? XMLElement(cNode: $0, document: self.document) : nil } } // MARK: - Accessing Content /// Whether the element has a value. open var isBlank: Bool { return stringValue.isEmpty } /// A number representation of the element's value, which is generated from the document's `numberFormatter` property. open fileprivate(set) lazy var numberValue: NSNumber? = { return self.document.numberFormatter.number(from: self.stringValue) }() /// A date representation of the element's value, which is generated from the document's `dateFormatter` property. open fileprivate(set) lazy var dateValue: Date? = { return self.document.dateFormatter.date(from: self.stringValue) }() /** Returns the child element at the specified index. - parameter idx: The index. - returns: The child element. */ open subscript (idx: Int) -> XMLElement? { return children[idx] } /** Returns the value for the attribute with the specified key. - parameter name: The attribute name. - returns: The attribute value, or `nil` if the attribute is not defined. */ open subscript (name: String) -> String? { return attr(name) } internal init?(cNode: xmlNodePtr, document: XMLDocument) { super.init(cNode: cNode, document: document, type: .Element) } }
mit
19258be23c0aa5af7ad7defa68f9436b
32
120
0.679871
4.159859
false
false
false
false
Ryanair/RYRCalendar
RYRCalendar/Classes/RYRDayCell.swift
1
2423
// // RYRCalendarDayCell.swift // RYRCalendar // // Created by Miquel, Aram on 01/06/2016. // Copyright © 2016 Ryanair. All rights reserved. // import UIKit class RYRDayCell: UICollectionViewCell { class var cellIndentifier: String { get { return "RYRCalendarDayCellIndentifier" } } private var dayNumberLabel: UILabel! private var backgroundImage: UIImageView? var dayNumber: Int = 0 { didSet { updateDayNumberLabel() } } var style: RYRDayCellStyle? { didSet { updateStyle(style!) } } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { dayNumberLabel = UILabel(frame: CGRectMake(0, 0, 40, 40)) dayNumberLabel.textAlignment = NSTextAlignment.Center addSubview(dayNumberLabel) dayNumberLabel.translatesAutoresizingMaskIntoConstraints = false addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[dayNumberLabel]-0-|", options: [], metrics: nil, views: ["dayNumberLabel": dayNumberLabel])) addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[dayNumberLabel]-0-|", options: [], metrics: nil, views: ["dayNumberLabel": dayNumberLabel])) } private func updateDayNumberLabel() { dayNumberLabel.text = "\(dayNumber)" } private func updateStyle(newStyle: RYRDayCellStyle) { backgroundColor = newStyle.backgroundColor dayNumberLabel.font = newStyle.textFont dayNumberLabel.textColor = newStyle.textColor backgroundImage?.removeFromSuperview() if let newBackgroundImage = newStyle.backgroundImage { backgroundImage = UIImageView(image: newBackgroundImage) backgroundImage?.contentMode = newStyle.backgroundImageContentMode addSubview(backgroundImage!) backgroundImage?.translatesAutoresizingMaskIntoConstraints = false addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[backgroundImage]-0-|", options: [], metrics: nil, views: ["backgroundImage": backgroundImage!])) addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[backgroundImage]-0-|", options: [], metrics: nil, views: ["backgroundImage": backgroundImage!])) sendSubviewToBack(backgroundImage!) } } }
apache-2.0
c352760ab7197432e6b4b34805aa6551
36.859375
175
0.699835
5.28821
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Filters.playground/Pages/Formant Filter.xcplaygroundpage/Contents.swift
2
1642
//: ## Formant Filter //: ## import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true var filter = AKFormantFilter(player) AudioKit.output = filter AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Formant Filter") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: filtersPlaygroundFiles)) addSubview(AKBypassButton(node: filter)) addSubview(AKPropertySlider( property: "Center Frequency", format: "%0.1f Hz", value: filter.centerFrequency, maximum: 8000, color: AKColor.yellowColor() ) { sliderValue in filter.centerFrequency = sliderValue }) addSubview(AKPropertySlider( property: "Attack", format: "%0.3f s", value: filter.attackDuration, maximum: 0.1, color: AKColor.greenColor() ) { duration in filter.attackDuration = duration }) addSubview(AKPropertySlider( property: "Decay", format: "%0.3f s", value: filter.decayDuration, maximum: 0.1, color: AKColor.cyanColor() ) { duration in filter.decayDuration = duration }) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
a43bd319a872187570f81e643be23b9f
25.483871
67
0.609622
5.03681
false
false
false
false
NextLevel/NextLevel
Sources/NextLevel+AVFoundation.swift
1
12260
// // NextLevel+AVFoundation.swift // NextLevel (http://github.com/NextLevel/) // // Copyright (c) 2016-present patrick piemonte (http://patrickpiemonte.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import Foundation import AVFoundation extension AVCaptureConnection { /// Returns the capture connection for the desired media type, otherwise nil. /// /// - Parameters: /// - mediaType: Specified media type. (i.e. AVMediaTypeVideo, AVMediaTypeAudio, etc.) /// - connections: Array of `AVCaptureConnection` objects to search /// - Returns: Capture connection for the desired media type, otherwise nil public class func connection(withMediaType mediaType: AVMediaType, fromConnections connections: [AVCaptureConnection]) -> AVCaptureConnection? { for connection: AVCaptureConnection in connections { for port: AVCaptureInput.Port in connection.inputPorts { if port.mediaType == mediaType { return connection } } } return nil } } extension AVCaptureDeviceInput { /// Returns the capture device input for the desired media type and capture session, otherwise nil. /// /// - Parameters: /// - mediaType: Specified media type. (i.e. AVMediaTypeVideo, AVMediaTypeAudio, etc.) /// - captureSession: Capture session for which to query /// - Returns: Desired capture device input for the associated media type, otherwise nil public class func deviceInput(withMediaType mediaType: AVMediaType, captureSession: AVCaptureSession) -> AVCaptureDeviceInput? { if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] { for deviceInput in inputs { if deviceInput.device.hasMediaType(mediaType) { return deviceInput } } } return nil } } extension AVCaptureDevice { // MARK: - device lookup /// Returns the capture device for the desired device type and position. /// #protip, NextLevelDevicePosition.avfoundationType can provide the AVFoundation type. /// /// - Parameters: /// - deviceType: Specified capture device type, (i.e. builtInMicrophone, builtInWideAngleCamera, etc.) /// - position: Desired position of device /// - Returns: Capture device for the specified type and position, otherwise nil public class func captureDevice(withType deviceType: AVCaptureDevice.DeviceType, forPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? { let deviceTypes: [AVCaptureDevice.DeviceType] = [deviceType] if let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: deviceTypes, mediaType: AVMediaType.video, position: position).devices.first { return discoverySession } return nil } /// Returns the default wide angle video device for the desired position, otherwise nil. /// /// - Parameter position: Desired position of the device /// - Returns: Wide angle video capture device, otherwise nil public class func wideAngleVideoDevice(forPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? { let deviceTypes: [AVCaptureDevice.DeviceType] = [AVCaptureDevice.DeviceType.builtInWideAngleCamera] if let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: deviceTypes, mediaType: AVMediaType.video, position: position).devices.first { return discoverySession } return nil } /// Returns the default telephoto video device for the desired position, otherwise nil. /// /// - Parameter position: Desired position of the device /// - Returns: Telephoto video capture device, otherwise nil public class func telephotoVideoDevice(forPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? { let deviceTypes: [AVCaptureDevice.DeviceType] = [AVCaptureDevice.DeviceType.builtInTelephotoCamera] if let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: deviceTypes, mediaType: AVMediaType.video, position: position).devices.first { return discoverySession } return nil } /// Returns the first available camera device of specified types. /// /// - Parameters: /// - position: Desired position of the device /// - prioritizedDeviceTypes: Device types of interest, in descending order /// - Returns: Primary video capture device found, otherwise nil public class func primaryVideoDevice(forPosition position: AVCaptureDevice.Position, prioritizedDeviceTypes: [AVCaptureDevice.DeviceType] = [/* .builtInTripleCamera,*/ .builtInDualCamera, .builtInWideAngleCamera]) -> AVCaptureDevice? { AVCaptureDevice.DiscoverySession(deviceTypes: prioritizedDeviceTypes, mediaType: AVMediaType.video, position: position).devices.first } /// Returns the default video capture device, otherwise nil. /// /// - Returns: Default video capture device, otherwise nil public class func videoDevice() -> AVCaptureDevice? { AVCaptureDevice.default(for: AVMediaType.video) } /// Returns the default audio capture device, otherwise nil. /// /// - Returns: default audio capture device, otherwise nil public class func audioDevice() -> AVCaptureDevice? { AVCaptureDevice.default(for: AVMediaType.audio) } // MARK: - utilities /// Calculates focal length and principle point camera intrinsic parameters for OpenCV. /// (see Hartley's Mutiple View Geometry, Chapter 6) /// /// - Parameters: /// - focalLengthX: focal length along the x-axis /// - focalLengthY: focal length along the y-axis /// - principlePointX: principle point x-coordinate /// - principlePointY: principle point y-coordinate /// - Returns: `true` when the focal length and principle point parameters are successfully calculated. public func focalLengthAndPrinciplePoint(focalLengthX: inout Float, focalLengthY: inout Float, principlePointX: inout Float, principlePointY: inout Float) { let dimensions = CMVideoFormatDescriptionGetPresentationDimensions(self.activeFormat.formatDescription, usePixelAspectRatio: true, useCleanAperture: true) principlePointX = Float(dimensions.width) * 0.5 principlePointY = Float(dimensions.height) * 0.5 let horizontalFieldOfView = self.activeFormat.videoFieldOfView let verticalFieldOfView = (horizontalFieldOfView / principlePointX) * principlePointY focalLengthX = abs( Float(dimensions.width) / (2.0 * tan(horizontalFieldOfView / 180.0 * .pi / 2 )) ) focalLengthY = abs( Float(dimensions.height) / (2.0 * tan(verticalFieldOfView / 180.0 * .pi / 2 )) ) } } extension AVCaptureDevice.Format { /// Returns the maximum capable framerate for the desired capture format and minimum, otherwise zero. /// /// - Parameters: /// - format: Capture format to evaluate for a specific framerate. /// - minFrameRate: Lower bound time scale or minimum desired framerate. /// - Returns: Maximum capable framerate within the desired format and minimum constraints. public class func maxFrameRate(forFormat format: AVCaptureDevice.Format, minFrameRate: CMTimeScale) -> CMTimeScale { var lowestTimeScale: CMTimeScale = 0 for range in format.videoSupportedFrameRateRanges { if range.minFrameDuration.timescale >= minFrameRate && (lowestTimeScale == 0 || range.minFrameDuration.timescale < lowestTimeScale) { lowestTimeScale = range.minFrameDuration.timescale } } return lowestTimeScale } /// Checks if the specified capture device format supports a desired framerate and dimensions. /// /// - Parameters: /// - frameRate: Desired frame rate /// - dimensions: Desired video dimensions /// - Returns: `true` if the capture device format supports the given criteria, otherwise false public func isSupported(withFrameRate frameRate: CMTimeScale, dimensions: CMVideoDimensions = CMVideoDimensions(width: 0, height: 0)) -> Bool { let formatDimensions = CMVideoFormatDescriptionGetDimensions(self.formatDescription) if formatDimensions.width >= dimensions.width && formatDimensions.height >= dimensions.height { for frameRateRange in self.videoSupportedFrameRateRanges { if frameRateRange.minFrameDuration.timescale >= frameRate && frameRateRange.maxFrameDuration.timescale <= frameRate { return true } } } return false } } extension AVCaptureDevice.Position { /// Checks if a camera device is available for a position. /// /// - Parameter devicePosition: Camera device position to query. /// - Returns: `true` if the camera device exists, otherwise false. public var isCameraDevicePositionAvailable: Bool { UIImagePickerController.isCameraDeviceAvailable(self.uikitType) } /// UIKit device equivalent type public var uikitType: UIImagePickerController.CameraDevice { switch self { case .front: return .front case .unspecified: fallthrough case .back: fallthrough @unknown default: return .rear } } } extension AVCaptureDevice.WhiteBalanceGains { /// Normalize gain values for a capture device. /// /// - Parameter captureDevice: Device used for adjustment. /// - Returns: Normalized gains. public func normalize(_ captureDevice: AVCaptureDevice) -> AVCaptureDevice.WhiteBalanceGains { var newGains = self newGains.redGain = Swift.min(captureDevice.maxWhiteBalanceGain, Swift.max(1.0, newGains.redGain)) newGains.greenGain = Swift.min(captureDevice.maxWhiteBalanceGain, Swift.max(1.0, newGains.greenGain)) newGains.blueGain = Swift.min(captureDevice.maxWhiteBalanceGain, Swift.max(1.0, newGains.blueGain)) return newGains } } extension AVCaptureVideoOrientation { /// UIKit orientation equivalent type public var uikitType: UIDeviceOrientation { switch self { case .portrait: return .portrait case .landscapeLeft: return .landscapeLeft case .landscapeRight: return .landscapeRight case .portraitUpsideDown: return .portraitUpsideDown @unknown default: return .unknown } } internal static func avorientationFromUIDeviceOrientation(_ orientation: UIDeviceOrientation) -> AVCaptureVideoOrientation { var avorientation: AVCaptureVideoOrientation = .portrait switch orientation { case .portrait: break case .landscapeLeft: avorientation = .landscapeRight break case .landscapeRight: avorientation = .landscapeLeft break case .portraitUpsideDown: avorientation = .portraitUpsideDown break default: break } return avorientation } }
mit
180b45d4cc75352503146cba4290ddcb
42.017544
236
0.693148
5.078708
false
false
false
false
fritzgerald/CustomLoader
Source/ProgressBoxView.swift
1
5064
// // ProgressBoxView.swift // CustomLoader // // Created by fritzgerald muiseroux on 24/01/2017. // Copyright © 2017 fritzgerald muiseroux. All rights reserved. // import UIKit /** A Boxed view that present a view stacked with two labels */ public class ProgressBoxView: UIView { /** The loading indicator view*/ public let loaderView: UIView! /** Main text*/ public let label = UILabel() /** sub text */ public let subLabel = UILabel() internal var contentView: UIView! /** Initialize the loading box with the given view - Parameter loader: the loading indicator */ public init(loader: UIView) { loaderView = loader super.init(frame: CGRect.zero) initializeStyle() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initializeStyle() { contentView = UIView() contentView.translatesAutoresizingMaskIntoConstraints = false addSubview(contentView) label.standardStyle(withFont: UIFont.boldSystemFont(ofSize: 15)) subLabel.standardStyle(withFont: UIFont.boldSystemFont(ofSize: 12)) contentView.stackViews([loaderView , label, subLabel]) let centerYConstraint = NSLayoutConstraint(item: contentView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0) let centerXConstraint = NSLayoutConstraint(item: contentView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0) let vContraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[view]-|", options: .directionLeadingToTrailing, metrics: nil, views: ["view": contentView]) let hContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[view]-|", options: .directionLeadingToTrailing, metrics: nil, views: ["view": contentView]) addConstraints(vContraints) addConstraints(hContraints) addConstraints([centerYConstraint, centerXConstraint]) layer.cornerRadius = 10 } public override var intrinsicContentSize: CGSize { return CGSize(width: 100, height: 100) } } public extension ProgressBoxView { /** A progress box with a light loading ring as indicator */ public static var standard: ProgressBoxView { let view = ProgressBoxView(loader: ProgressRingView.light) view.backgroundColor = UIColor.lightGray return view } /** A progress box with an Activity indicator View - Parameter withStyle: the Activity indicator style */ public static func system(withStyle style: UIActivityIndicatorView.Style) -> ProgressBoxView { let loaderView = UIActivityIndicatorView(style: style) loaderView.startAnimating() let view = ProgressBoxView(loader: loaderView) view.backgroundColor = UIColor.lightGray return view } } extension UILabel { func standardStyle(withFont font: UIFont) { self.font = font self.textColor = UIColor.white self.numberOfLines = 0 self.textAlignment = .center } } extension UIView { func stackViews(_ views:[UIView]) { var lastView: UIView? = nil var stackConstraints = [NSLayoutConstraint]() views.forEach({ view in view.translatesAutoresizingMaskIntoConstraints = false self.addSubview(view) }) views.forEach { view in if let lastView = lastView { let topConstraint = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: lastView, attribute: .bottom, multiplier: 1.0, constant: 0) stackConstraints.append(topConstraint) } else { let topConstraint = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: self, attribute: .topMargin, multiplier: 1.0, constant: 0) stackConstraints.append(topConstraint) } let centerXConstraint = NSLayoutConstraint(item: view, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0) stackConstraints.append(centerXConstraint) let horizontalCOnstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|->=0-[view]->=0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["view": view]) stackConstraints.append(contentsOf: horizontalCOnstraints) lastView = view } if let lastView = lastView { let bottom = NSLayoutConstraint(item: lastView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottomMargin, multiplier: 1.0, constant: 0) stackConstraints.append(bottom) } self.addConstraints(stackConstraints) } }
mit
c472cf093bad804c9bfe0cfb0fdfeda0
35.688406
187
0.6508
5.093561
false
false
false
false
Gilbertat/SYKanZhiHu
SYKanZhihu/Pods/EasyPull/EasyPull/EasyPull/EasyObserver.swift
1
9785
// // EasyObserver.swift // Demo // // Created by 荣浩 on 16/2/25. // Copyright © 2016年 荣浩. All rights reserved. // import UIKit // MARK: protocol public protocol EasyViewManual { func showManualPulling(_ progress:CGFloat) func showManualPullingOver() func showManualExcuting() func resetManual() } public protocol EasyViewAutomatic { func showAutomaticPulling(_ progress:CGFloat) func showAutomaticExcuting() func showAutomaticUnable() func resetAutomatic() } // MARK: enum internal enum EasyUpPullMode { case easyUpPullModeAutomatic case easyUpPullModeManual } internal enum EasyState { case dropPulling(CGFloat) case dropPullingOver case dropPullingExcuting case dropPullingFree case upPulling(CGFloat) case upPullingOver case upPullingExcuting case upPullingFree } open class EasyObserver: NSObject { // MARK: - constant and veriable and property fileprivate var scrollView: UIScrollView? lazy fileprivate var dropViewSize: CGSize = CGSize(width: UIScreen.main.bounds.size.width, height: 65.0) lazy fileprivate var upViewSize: CGSize = CGSize(width: UIScreen.main.bounds.size.width, height: 65.0) internal var upPullMode: EasyUpPullMode = .easyUpPullModeAutomatic internal var dropPullEnable: Bool = false internal var upPullEnable: Bool = false internal var dropAction: (() ->Void)? internal var upAction: (() ->Void)? fileprivate var dropView: EasyViewManual? internal var DropView: EasyViewManual { get { if dropView == nil { dropView = DefaultDropView(frame: CGRect(x: 0, y: -dropViewSize.height, width: dropViewSize.width, height: dropViewSize.height)) } if let view = dropView as? UIView { if view.superview == nil && dropPullEnable { scrollView?.addSubview(view) } } return dropView! } set { if let view = newValue as? UIView { dropView = newValue dropViewSize = view.frame.size } } } fileprivate var upViewForManual: EasyViewManual? internal var UpViewForManual: EasyViewManual { get { if upViewForManual == nil { upViewForManual = DefaultUpView(frame: CGRect(x: 0, y: scrollView!.contentSize.height, width: upViewSize.width, height: upViewSize.height)) } if let view = upViewForManual as? UIView { if view.superview == nil && upPullEnable { scrollView!.addSubview(view) } view.frame.origin.y = scrollView!.contentSize.height } return upViewForManual! } set { if let view = newValue as? UIView { upViewForManual = newValue upViewSize = view.frame.size } } } fileprivate var upViewForAutomatic: EasyViewAutomatic? internal var UpViewForAutomatic: EasyViewAutomatic { get { if upViewForAutomatic == nil { upViewForAutomatic = DefaultUpView(frame: CGRect(x: 0, y: scrollView!.contentSize.height, width: upViewSize.width, height: upViewSize.height)) } if let view = upViewForAutomatic as? UIView { if view.superview == nil && upPullEnable { scrollView!.addSubview(view) } view.frame.origin.y = scrollView!.contentSize.height } return upViewForAutomatic! } set { if let view = newValue as? UIView { upViewForAutomatic = newValue upViewSize = view.frame.size } } } fileprivate var state: EasyState = .dropPullingFree internal var State: EasyState { get { return state } set { state = newValue switch state { case .dropPulling(let progress): DropView.showManualPulling(progress) case .dropPullingOver: DropView.showManualPullingOver() case .dropPullingExcuting: DispatchQueue.main.async(execute: { () -> Void in UIView.animate(withDuration: 0.2, animations: { () -> Void in self.scrollView!.contentInset.top = self.dropViewSize.height }) }) DropView.showManualExcuting() dropAction?() case .dropPullingFree: DropView.resetManual() (DropView as! UIView).removeFromSuperview() UIView.animate(withDuration: 0.2, animations: { () -> Void in self.scrollView!.contentInset.top = 0 }) case .upPulling(let progress): if upPullMode == .easyUpPullModeAutomatic { scrollView!.contentInset.bottom = upViewSize.height UpViewForAutomatic.showAutomaticPulling(progress) } else { UpViewForManual.showManualPulling(progress) } case .upPullingOver: if upPullMode == .easyUpPullModeManual { UpViewForManual.showManualPullingOver() } else { UpViewForAutomatic.showAutomaticExcuting() upAction?() } case .upPullingExcuting: if upPullMode == .easyUpPullModeManual { DispatchQueue.main.async(execute: { () -> Void in UIView.animate(withDuration: 0.2, animations: { () -> Void in self.scrollView!.contentInset.bottom = self.upViewSize.height }) }) UpViewForManual.showManualExcuting() upAction?() } case .upPullingFree: if upPullMode == .easyUpPullModeAutomatic { UpViewForAutomatic.resetAutomatic() (UpViewForAutomatic as! UIView).removeFromSuperview() } else { UpViewForManual.resetManual() (UpViewForManual as! UIView).removeFromSuperview() UIView.animate(withDuration: 0.2, animations: { () -> Void in self.scrollView!.contentInset.bottom = 0 }) } } } } // MARK: - life cycle init(scrollView: UIScrollView) { super.init() self.scrollView = scrollView } // MARK: - observer open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "contentOffset" { switch State { case .upPullingExcuting, .dropPullingExcuting: return default: break } let newPoint = (change![NSKeyValueChangeKey.newKey] as AnyObject).cgPointValue let yOffset = newPoint?.y == nil ? 0 : (newPoint?.y)! let frameHeight = scrollView!.frame.size.height let contentHeight = scrollView!.contentSize.height let pullLength = yOffset + frameHeight - contentHeight if contentHeight >= frameHeight && pullLength >= upViewSize.height && upPullEnable { if scrollView!.isDragging { switch State { case .upPullingOver: break default: State = .upPullingOver } } else { State = .upPullingExcuting } } else if contentHeight >= frameHeight && pullLength > 0 && pullLength < upViewSize.height && upPullEnable { State = .upPulling(pullLength / upViewSize.height) } else if yOffset <= -dropViewSize.height && dropPullEnable { if scrollView!.isDragging { switch State { case .dropPullingOver: break default: State = .dropPullingOver } } else { State = .dropPullingExcuting } } else if yOffset < 0 && yOffset > -dropViewSize.height && dropPullEnable { State = .dropPulling(-yOffset / dropViewSize.height) } } } // MARK: - private method // MARK: - public method open func stopDropExcuting() { State = .dropPullingFree } open func stopUpExcuting() { State = .upPullingFree } open func enableUpExcuting() { upPullEnable = true State = .upPullingFree } open func unableUpExcuting() { upPullEnable = false UpViewForAutomatic.showAutomaticUnable() scrollView!.contentInset.bottom = self.upViewSize.height } open func triggerDropExcuting() { State = .dropPullingExcuting scrollView?.setContentOffset(CGPoint(x: 0, y: -dropViewSize.height), animated: true) } }
mit
4627814e492ec1a3912c7f6f093c18e6
33.055749
158
0.529057
5.155063
false
false
false
false
barracksiot/ios-osx-client
Client/Source/BarracksClient.swift
1
1971
/* * Copyright 2016 Barracks Solutions Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import Alamofire /** The main entry point for using Barracks' SDK. This class provides methods to help you getting information about the available updates for a specific configuration. */ open class BarracksClient { /// Your account's API key let apiKey:String /// The base URL for contacting the Barracks service let baseUrl:String /// Flag to ignore SSL certificate check let ignoreSSL:Bool /// Network Session Manager public var networkSessionManager:SessionManager /** Create a client using the parameters provided by the Barracks platform. - parameter apiKey: Your account's API key - parameter baseUrl: The base URL for Barracks, if you have set one up - parameter ignoreSSL: Flag to ignore SSL certificate check */ public init(_ apiKey:String, baseUrl:String = "https://app.barracks.io/api/device/update/check", ignoreSSL:Bool = false) { self.apiKey = apiKey self.baseUrl = baseUrl self.ignoreSSL = ignoreSSL let domain = NSURL(string: baseUrl)!.host! self.networkSessionManager = ignoreSSL ? SessionManager(serverTrustPolicyManager: ServerTrustPolicyManager(policies: [domain:ServerTrustPolicy.disableEvaluation])) : Alamofire.SessionManager.default } }
apache-2.0
f22183a96e2fe965f764ddba97ff6505
36.903846
206
0.704718
4.60514
false
false
false
false
ashfurrow/eidolon
KioskTests/Bid Fulfillment/LoadingViewControllerTests.swift
2
7317
import Quick import Nimble @testable import Kiosk import Moya import RxSwift import Nimble_Snapshots import Forgeries class LoadingViewControllerTests: QuickSpec { override func spec() { var subject: LoadingViewController! beforeEach { subject = testLoadingViewController() subject.animate = false } describe("default") { it("placing a bid") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) stubViewModel.completes = false subject.viewModel = stubViewModel expect(subject).to( haveValidSnapshot(usesDrawRect: true) ) } it("registering a user") { subject.placingBid = false let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) stubViewModel.completes = false subject.viewModel = stubViewModel expect(subject).to(haveValidSnapshot()) } } describe("errors") { it("correctly placing a bid") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) stubViewModel.errors = true subject.viewModel = stubViewModel expect(subject).to( haveValidSnapshot(usesDrawRect: true) ) } it("correctly registering a user") { subject.placingBid = false let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) stubViewModel.errors = true subject.viewModel = stubViewModel expect(subject).to( haveValidSnapshot(usesDrawRect: true) ) } } describe("ending") { it("placing bid success highest") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) stubViewModel.bidIsResolved.value = true stubViewModel.isHighestBidder.value = true subject.viewModel = stubViewModel expect(subject).to( haveValidSnapshot(usesDrawRect: true) ) } it("dismisses by tapping green checkmark when bidding was a success") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) stubViewModel.bidIsResolved.value = true stubViewModel.isHighestBidder.value = true subject.viewModel = stubViewModel var closed = false subject.closeSelf = { closed = true } let testingRecognizer = ForgeryTapGestureRecognizer() subject.recognizer = testingRecognizer subject.loadViewProgrammatically() testingRecognizer.invoke() expect(closed).to( beTrue() ) } it("placing bid success not highest") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) stubViewModel.bidIsResolved.value = true stubViewModel.isHighestBidder.value = false subject.viewModel = stubViewModel expect(subject).to( haveValidSnapshot(usesDrawRect: true) ) } it("placing bid error due to outbid") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) subject.viewModel = stubViewModel subject.loadViewProgrammatically() let error = NSError(domain: OutbidDomain, code: 0, userInfo: nil) subject.bidderError(error) expect(subject).to( haveValidSnapshot(usesDrawRect: true) ) } it("placing bid succeeded but not resolved") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) stubViewModel.bidIsResolved.value = false subject.viewModel = stubViewModel expect(subject).to( haveValidSnapshot(usesDrawRect: true) ) } it("registering user success") { subject.placingBid = false let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) stubViewModel.createdNewBidder.value = true stubViewModel.bidIsResolved.value = true subject.viewModel = stubViewModel expect(subject).to( haveValidSnapshot(usesDrawRect: true) ) } it("registering user not resolved") { subject.placingBid = false let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidDetails: fulfillmentController.bidDetails) stubViewModel.bidIsResolved.value = true subject.viewModel = stubViewModel expect(subject).to( haveValidSnapshot(usesDrawRect: true) ) } } } } let loadingViewControllerTestImage = UIImage.testImage(named: "artwork", ofType: "jpg") func testLoadingViewController() -> LoadingViewController { let controller = UIStoryboard.fulfillment().viewController(withID: .LoadingBidsorRegistering).wrapInFulfillmentNav() as! LoadingViewController return controller } class StubLoadingViewModel: LoadingViewModelType { var errors = false var completes = true // LoadingViewModelType conformance let createdNewBidder = Variable(false) let bidIsResolved = Variable(false) let isHighestBidder = Variable(false) let reserveNotMet = Variable(false) var bidDetails: BidDetails init(bidDetails: BidDetails) { self.bidDetails = bidDetails } func performActions() -> Observable<Void> { if completes { if errors { return Observable.error(NSError(domain: "", code: 0, userInfo: nil) as Swift.Error) } else { return Observable.empty() } } else { return Observable.never() } } }
mit
3bb592f37ae357396b06f377d2a8bd21
36.716495
146
0.612409
5.977941
false
false
false
false
huonw/swift
benchmark/single-source/NSError.swift
34
1216
//===--- NSError.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 import Foundation public let NSErrorTest = BenchmarkInfo( name: "NSError", runFunction: run_NSError, tags: [.validation, .exceptions, .bridging]) protocol P { func buzz() throws -> Int } class K : P { init() {} func buzz() throws -> Int { throw NSError(domain: "AnDomain", code: 42, userInfo: nil) } } class G : K { override init() {} override func buzz() throws -> Int { return 0 } } func caller(_ x: P) throws { _ = try x.buzz() } @inline(never) public func run_NSError(_ N: Int) { for _ in 1...N*1000 { let k = K() let g = G() do { try caller(g) try caller(k) } catch _ { continue } } }
apache-2.0
b3c1aa3dba1f9b9679424178639d0540
21.943396
80
0.552632
3.948052
false
false
false
false
networkextension/SFSocket
SFSocket/tcp/CHTTPProxConnector.swift
1
1045
// // CHTTPProxConnector.swift // SFSocket // // Created by 孔祥波 on 27/03/2017. // Copyright © 2017 Kong XiangBo. All rights reserved. // import Foundation class CHTTPProxConnector: HTTPProxyConnector { var adapter:Adapter? public static func create(targetHostname hostname:String, targetPort port:UInt16,p:SFProxy,adapter:Adapter) ->CHTTPProxConnector{ let c:CHTTPProxConnector = CHTTPProxConnector(p: p) //c.manager = man //c.cIDFunc() c.targetHost = hostname c.targetPort = port c.adapter = adapter //c.start() return c } override func readCallback(data: Data?, tag: Int) { guard let adapter = adapter else { return } let newdata = adapter.recv(data!) super.readCallback(data: newdata, tag: tag) } public override func sendData(data: Data, withTag tag: Int) { guard let adapter = adapter else { return } let newdata = adapter.send(data) super.sendData(data: newdata , withTag: tag) } }
bsd-3-clause
61ca91deffcfe461ee23072ddcc76c86
30.454545
133
0.643545
3.604167
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Extensions/UIColor+Extensions.swift
1
7481
// // Xcore // Copyright © 2014 Xcore // MIT license, see LICENSE file for details // import UIKit // MARK: - Hex Support extension UIColor { public convenience init(hex: Int64) { let (r, g, b, a) = Self.components(hex: hex) self.init(red: r, green: g, blue: b, alpha: a) } public convenience init(hex: Int64, alpha: CGFloat) { let (r, g, b, a) = Self.components(hex: hex, alpha: alpha) self.init(red: r, green: g, blue: b, alpha: a) } @nonobjc public convenience init(hex: String) { self.init(hex: Self.components(hex: hex)) } @nonobjc public convenience init(hex: String, alpha: CGFloat) { self.init(hex: Self.components(hex: hex), alpha: alpha) } public var hex: String { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 guard getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { return "#000000" } func round(_ value: CGFloat) -> Int { lround(Double(value) * 255) } if alpha == 1 { return String(format: "#%02lX%02lX%02lX", round(red), round(green), round(blue)) } else { return String(format: "#%02lX%02lX%02lX%02lX", round(red), round(green), round(blue), round(alpha)) } } private static func components(hex: Int64, alpha: CGFloat? = nil) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { let preferredAlpha = alpha let r: CGFloat let g: CGFloat let b: CGFloat let a: CGFloat let isRGBA = CGFloat(hex & 0xff000000) != 0 if isRGBA { r = CGFloat((hex & 0xff000000) >> 24) / 255 g = CGFloat((hex & 0xff0000) >> 16) / 255 b = CGFloat((hex & 0xff00) >> 8) / 255 a = preferredAlpha ?? CGFloat(hex & 0xff) / 255 } else { r = CGFloat((hex & 0xff0000) >> 16) / 255 g = CGFloat((hex & 0xff00) >> 8) / 255 b = CGFloat(hex & 0xff) / 255 a = preferredAlpha ?? 1 } return (r, g, b, a) } private static func components(hex: String) -> Int64 { Int64(hex.droppingPrefix("#"), radix: 16) ?? 0x000000 } private func components(normalize: Bool = true) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) if normalize { r *= 255 g *= 255 b *= 255 } return (r, g, b, a) } } // MARK: - Alpha extension UIColor { public var alpha: CGFloat { get { cgColor.alpha } set { withAlphaComponent(newValue) } } public func alpha(_ value: CGFloat) -> UIColor { withAlphaComponent(value) } } // MARK: - Lighter & Darker extension UIColor { // Credit: http://stackoverflow.com/a/31466450 public func lighter(_ amount: CGFloat = 0.25) -> UIColor { hueColorWithBrightness(1 + amount) } public func darker(_ amount: CGFloat = 0.25) -> UIColor { hueColorWithBrightness(1 - amount) } private func hueColorWithBrightness(_ amount: CGFloat) -> UIColor { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor(hue: hue, saturation: saturation, brightness: brightness * amount, alpha: alpha) } else { return self } } public func isLight(threshold: CGFloat = 0.6) -> Bool { var white: CGFloat = 0 getWhite(&white, alpha: nil) return white > threshold } } // MARK: - Blend extension UIColor { /// Blend multiply given color with `self`. public func multiply(_ color: UIColor, alpha: CGFloat = 1) -> UIColor { let bg = components(normalize: false) let fg = color.components(normalize: false) let r = bg.r * fg.r let g = bg.g * fg.g let b = bg.b * fg.b let a = alpha * fg.a + (1 - alpha) * bg.a return UIColor( red: r.clamped(to: 0...255), green: g.clamped(to: 0...255), blue: b.clamped(to: 0...255), alpha: a ) } } // MARK: - Random extension UIColor { public static func randomColor() -> UIColor { let hue = CGFloat(arc4random() % 256) / 256 let saturation = CGFloat(arc4random() % 128) / 256 + 0.5 let brightness = CGFloat(arc4random() % 128) / 256 + 0.5 return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1) } } // MARK: - Cross Fade extension UIColor { /// A convenience function to cross fade to the given color by the specified /// delta. /// /// - Parameters: /// - color: The color to which self should cross fade. /// - percentage: The delta of the cross fade. /// - Returns: An instance of cross faded `UIColor`. open func crossFade(to color: UIColor, delta percentage: CGFloat) -> UIColor { let fromColor = self let toColor = color var fromRed: CGFloat = 0 var fromGreen: CGFloat = 0 var fromBlue: CGFloat = 0 var fromAlpha: CGFloat = 0 fromColor.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha) var toRed: CGFloat = 0 var toGreen: CGFloat = 0 var toBlue: CGFloat = 0 var toAlpha: CGFloat = 0 toColor.getRed(&toRed, green: &toGreen, blue: &toBlue, alpha: &toAlpha) // Calculate the actual RGBA values of the fade colour let red = (toRed - fromRed) * percentage + fromRed let green = (toGreen - fromGreen) * percentage + fromGreen let blue = (toBlue - fromBlue) * percentage + fromBlue let alpha = (toAlpha - fromAlpha) * percentage + fromAlpha return UIColor(red: red, green: green, blue: blue, alpha: alpha) } } // MARK: - Color Scheme Mode extension UIColor { /// Creates a color object that generates its color data dynamically using the /// specified colors. /// /// - Parameters: /// - light: The color for light mode. /// - dark: The color for dark mode. public convenience init( light: @autoclosure @escaping () -> UIColor, dark: @autoclosure @escaping () -> UIColor ) { self.init { switch $0.userInterfaceStyle { case .dark: return dark() default: return light() } } } /// Returns the version of the current color that takes the specified user /// interface style into account. /// /// - Parameter userInterfaceStyle: The style to use when resolving the color /// information. /// - Returns: The version of the color to display for the specified style. public func resolve(for userInterfaceStyle: UIUserInterfaceStyle) -> UIColor { resolvedColor(with: .init(userInterfaceStyle: userInterfaceStyle)) } } extension Array where Element: UIColor { /// The Quartz color reference that corresponds to the receiver’s color. public var cgColor: [CGColor] { map(\.cgColor) } }
mit
90befca93144ac2de3a7057b8e9f6127
28.210938
123
0.56713
3.967109
false
false
false
false
hpux735/PMJSON
Tests/JSONAccessorTests.swift
1
15509
// // JSONAccessorTests.swift // PMJSON // // Created by Kevin Ballard on 11/3/16. // Copyright © 2016 Postmates. All rights reserved. // import XCTest import PMJSON class JSONAccessorTests: XCTestCase { func testConvenienceAccessors() { let dict: JSON = [ "xs": [["x": 1], ["x": 2], ["x": 3]], "ys": [["y": 1], ["y": nil], ["y": 3], [:]], "zs": nil, "s": "Hello", "array": [ [["x": 1], ["x": 2], ["x": 3]], [["y": 1], ["y": nil], ["y": 3], [:]], [["x": [1,2]], ["x": []], ["x": [3]], ["x": [4,5,6]]], nil, "Hello", [2,4,6] ], "concat": [["x": [1]], ["x": [2,3]], ["x": []], ["x": [4,5,6]]], "integers": [5,4,3] ] struct DummyError: Error {} // object-style accessors XCTAssertEqual([1,2,3], try dict.mapArray("xs", { try $0.getInt("x") })) XCTAssertThrowsError(try dict.mapArray("ys", { try $0.getInt("y") })) XCTAssertThrowsError(try dict.mapArray("s", { _ in 1 })) XCTAssertThrowsError(try dict.mapArray("invalid", { _ in 1 })) XCTAssertThrowsError(try dict.mapArray("xs", { _ in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertEqual([1,2,3], try dict.object!.mapArray("xs", { try $0.getInt("x") })) XCTAssertThrowsError(try dict.object!.mapArray("ys", { try $0.getInt("y") })) XCTAssertThrowsError(try dict.object!.mapArray("s", { _ in 1 })) XCTAssertThrowsError(try dict.object!.mapArray("invalid", { _ in 1 })) XCTAssertThrowsError(try dict.object!.mapArray("xs", { _ in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertEqual([1,2,3], try dict.mapArrayOrNil("xs", { try $0.getInt("x") }) ?? [-1]) XCTAssertThrowsError(try dict.mapArrayOrNil("ys", { try $0.getInt("y") }) ?? [-1]) XCTAssertNil(try dict.mapArrayOrNil("zs", { try $0.getInt("z") })) XCTAssertNil(try dict.mapArrayOrNil("invalid", { try $0.getInt("z") })) XCTAssertThrowsError(try dict.mapArrayOrNil("s", { _ in 1 })!) XCTAssertThrowsError(try dict.mapArrayOrNil("xs", { _ in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertEqual([1,2,3], try dict.object!.mapArrayOrNil("xs", { try $0.getInt("x") }) ?? [-1]) XCTAssertThrowsError(try dict.object!.mapArrayOrNil("ys", { try $0.getInt("y") }) ?? [-1]) XCTAssertNil(try dict.object!.mapArrayOrNil("zs", { try $0.getInt("z") })) XCTAssertNil(try dict.object!.mapArrayOrNil("invalid", { try $0.getInt("z") })) XCTAssertThrowsError(try dict.object!.mapArrayOrNil("s", { _ in 1 })!) XCTAssertThrowsError(try dict.object!.mapArrayOrNil("xs", { _ in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertEqual([1,3], try dict.flatMapArray("ys", { try $0.getIntOrNil("y") })) XCTAssertEqual([1,2,3,4,5,6], try dict.flatMapArray("concat", { try $0.mapArray("x", { try $0.getInt() }) })) XCTAssertThrowsError(try dict.flatMapArray("zs", { _ in [1] })) XCTAssertThrowsError(try dict.flatMapArray("s", { _ in [1] })) XCTAssertThrowsError(try dict.flatMapArray("invalid", { _ in [1] })) XCTAssertThrowsError(try dict.flatMapArray("xs", { _ -> [Int] in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertEqual([1,3], try dict.object!.flatMapArray("ys", { try $0.getIntOrNil("y") })) XCTAssertEqual([1,2,3,4,5,6], try dict.object!.flatMapArray("concat", { try $0.mapArray("x", { try $0.getInt() }) })) XCTAssertThrowsError(try dict.object!.flatMapArray("zs", { _ in [1] })) XCTAssertThrowsError(try dict.object!.flatMapArray("s", { _ in [1] })) XCTAssertThrowsError(try dict.object!.flatMapArray("invalid", { _ in [1] })) XCTAssertThrowsError(try dict.object!.flatMapArray("xs", { _ -> [Int] in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertEqual([1,3], try dict.flatMapArrayOrNil("ys", { try $0.getIntOrNil("y") }) ?? []) XCTAssertEqual([1,2,3,4,5,6], try dict.flatMapArrayOrNil("concat", { try $0.mapArray("x", { try $0.getInt() }) }) ?? []) XCTAssertNil(try dict.flatMapArrayOrNil("zs", { _ in [1] })) XCTAssertThrowsError(try dict.flatMapArrayOrNil("s", { _ in [1] })) XCTAssertNil(try dict.flatMapArrayOrNil("invalid", { _ in [1] })) XCTAssertThrowsError(try dict.flatMapArrayOrNil("xs", { _ -> [Int] in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertEqual([1,3], try dict.object!.flatMapArrayOrNil("ys", { try $0.getIntOrNil("y") }) ?? []) XCTAssertEqual([1,2,3,4,5,6], try dict.object!.flatMapArrayOrNil("concat", { try $0.mapArray("x", { try $0.getInt() }) }) ?? []) XCTAssertNil(try dict.object!.flatMapArrayOrNil("zs", { _ in [1] })) XCTAssertThrowsError(try dict.object!.flatMapArrayOrNil("s", { _ in [1] })) XCTAssertNil(try dict.object!.flatMapArrayOrNil("invalid", { _ in [1] })) XCTAssertThrowsError(try dict.object!.flatMapArrayOrNil("xs", { _ -> [Int] in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } do { var elts: [Int] = [], indices: [Int] = [] try dict.forEachArray("integers") { (elt, idx) in elts.append(try elt.getInt()) indices.append(idx) } XCTAssertEqual(elts, [5,4,3]) XCTAssertEqual(indices, [0,1,2]) (elts, indices) = ([], []) try dict.object!.forEachArray("integers") { (elt, idx) in elts.append(try elt.getInt()) indices.append(idx) } XCTAssertEqual(elts, [5,4,3]) XCTAssertEqual(indices, [0,1,2]) (elts, indices) = ([], []) XCTAssertTrue(try dict.forEachArrayOrNil("integers", { (elt, idx) in elts.append(try elt.getInt()) indices.append(idx) })) XCTAssertEqual(elts, [5,4,3]) XCTAssertEqual(indices, [0,1,2]) XCTAssertFalse(try dict.forEachArrayOrNil("invalid", { _ in XCTFail("this shouldn't be invoked") })) (elts, indices) = ([], []) XCTAssertTrue(try dict.object!.forEachArrayOrNil("integers", { (elt, idx) in elts.append(try elt.getInt()) indices.append(idx) })) XCTAssertEqual(elts, [5,4,3]) XCTAssertEqual(indices, [0,1,2]) XCTAssertFalse(try dict.object!.forEachArrayOrNil("invalid", { _ in XCTFail("this shouldn't be invoked") })) } catch { XCTFail("unexpected error: \(error)") } XCTAssertThrowsError(try dict["array"]!.mapArray("xs", { _ in 1 })) XCTAssertThrowsError(try dict["array"]!.mapArrayOrNil("xs", { _ in 1 })) XCTAssertThrowsError(try dict["array"]!.flatMapArray("xs", { _ -> Int? in 1 })) XCTAssertThrowsError(try dict["array"]!.flatMapArray("xs", { _ in [1] })) XCTAssertThrowsError(try dict["array"]!.flatMapArrayOrNil("xs", { _ -> Int? in 1 })) XCTAssertThrowsError(try dict["array"]!.flatMapArrayOrNil("xs", { _ in [1] })) XCTAssertThrowsError(try dict["array"]!.forEachArray("xs", { _ in () })) XCTAssertThrowsError(try dict["array"]!.forEachArrayOrNil("xs", { _ in () })) // array-style accessors let array = dict["array"]! XCTAssertEqual([1,2,3], try array.mapArray(0, { try $0.getInt("x") })) XCTAssertThrowsError(try array.mapArray(1, { try $0.getInt("y") })) XCTAssertEqual([2,0,1,3], try array.mapArray(2, { try $0.getArray("x").count })) XCTAssertThrowsError(try array.mapArray(3, { _ in 1 })) // null XCTAssertThrowsError(try array.mapArray(4, { _ in 1 })) // string XCTAssertThrowsError(try array.mapArray(100, { _ in 1 })) // out of bounds XCTAssertThrowsError(try array.mapArray(0, { _ in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertEqual([1,2,3], try array.mapArrayOrNil(0, { try $0.getInt("x") }) ?? []) XCTAssertThrowsError(try array.mapArrayOrNil(1, { try $0.getInt("y") })) XCTAssertEqual([2,0,1,3], try array.mapArrayOrNil(2, { try $0.getArray("x").count }) ?? []) XCTAssertNil(try array.mapArrayOrNil(3, { _ in 1 })) // null XCTAssertThrowsError(try array.mapArrayOrNil(4, { _ in 1 })) // string XCTAssertNil(try array.mapArrayOrNil(100, { _ in 1 })) // out of bounds XCTAssertThrowsError(try array.mapArrayOrNil(0, { _ in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertEqual([1,3], try array.flatMapArray(1, { try $0.getIntOrNil("y") })) XCTAssertEqual([1,2,3,4,5,6], try array.flatMapArray(2, { try $0.mapArray("x", { try $0.getInt() }) })) XCTAssertThrowsError(try array.flatMapArray(3, { _ in [1] })) // null XCTAssertThrowsError(try array.flatMapArray(4, { _ in [1] })) // string XCTAssertThrowsError(try array.flatMapArray(100, { _ in [1] })) // out of bounds XCTAssertThrowsError(try array.flatMapArray(0, { _ -> [Int] in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertEqual([1,3], try array.flatMapArrayOrNil(1, { try $0.getIntOrNil("y") }) ?? []) XCTAssertEqual([1,2,3,4,5,6], try array.flatMapArrayOrNil(2, { try $0.mapArray("x", { try $0.getInt() }) }) ?? []) XCTAssertNil(try array.flatMapArrayOrNil(3, { _ in [1] })) // null XCTAssertThrowsError(try array.flatMapArrayOrNil(4, { _ in [1] })) // string XCTAssertNil(try array.flatMapArrayOrNil(100, { _ in [1] })) // out of bounds XCTAssertThrowsError(try array.flatMapArrayOrNil(0, { _ -> [Int] in throw DummyError() })) { error in XCTAssert(error is DummyError, "expected DummyError, found \(error)") } XCTAssertThrowsError(try dict.mapArray(0, { _ in 1 })) XCTAssertThrowsError(try dict.mapArrayOrNil(0, { _ in 1 })) XCTAssertThrowsError(try dict.flatMapArray(0, { _ in 1 })) XCTAssertThrowsError(try dict.flatMapArrayOrNil(0, { _ in 1 })) do { var elts: [Int] = [], indices: [Int] = [] try array.forEachArray(5) { (elt, idx) in elts.append(try elt.getInt()) indices.append(idx) } XCTAssertEqual(elts, [2, 4, 6]) XCTAssertEqual(indices, [0,1,2]) XCTAssertThrowsError(try array.forEachArray(3, { _ in // null XCTFail("this shouldn't be invoked") })) XCTAssertThrowsError(try array.forEachArray(4, { _ in // string XCTFail("this shouldn't be invoked") })) XCTAssertThrowsError(try array.forEachArray(100, { _ in // out of bounds XCTFail("this shouldn't be invoked") })) (elts, indices) = ([], []) XCTAssertTrue(try array.forEachArrayOrNil(5, { (elt, idx) in elts.append(try elt.getInt()) indices.append(idx) })) XCTAssertEqual(elts, [2, 4, 6]) XCTAssertEqual(indices, [0,1,2]) XCTAssertFalse(try array.forEachArrayOrNil(3, { _ in // null XCTFail("this shouldn't be invoked") })) XCTAssertThrowsError(try array.forEachArrayOrNil(4, { _ in // string XCTFail("this shouldn't be invoked") })) XCTAssertFalse(try array.forEachArrayOrNil(100, { _ in // out of bounds XCTFail("this shouldn't be invoked") })) } catch { XCTFail("unexpected error: \(error)") } } func testConvenienceAccessorAssignments() { var json: JSON = "test" XCTAssertNil(json.bool) json.bool = true XCTAssertEqual(json, true) json.bool = nil XCTAssertEqual(json, JSON.null) XCTAssertNil(json.string) json.string = "foo" XCTAssertEqual(json, "foo") json.string = nil XCTAssertEqual(json, JSON.null) XCTAssertNil(json.int64) json.int64 = 42 XCTAssertEqual(json, 42) json.int64 = nil XCTAssertEqual(json, JSON.null) XCTAssertNil(json.int) json.int = 42 XCTAssertEqual(json, 42) json.int = nil XCTAssertEqual(json, JSON.null) XCTAssertNil(json.double) json.double = 42 XCTAssertEqual(json, 42) json.double = nil XCTAssertEqual(json, JSON.null) #if os(iOS) || os(OSX) || os(watchOS) || os(tvOS) XCTAssertNil(json.decimal) json.decimal = 42 XCTAssertEqual(json, 42) json.decimal = nil XCTAssertEqual(json, JSON.null) #endif XCTAssertNil(json.object) json.object = ["foo": "bar"] XCTAssertEqual(json, ["foo": "bar"]) json.object = nil XCTAssertEqual(json, JSON.null) XCTAssertNil(json.array) json.array = [1,2,3] XCTAssertEqual(json, [1,2,3]) json.array = nil XCTAssertEqual(json, JSON.null) json = ["foo": "bar"] json.object?["baz"] = "qux" XCTAssertEqual(json, ["foo": "bar", "baz": "qux"]) json = ["value": ["array": [1,2]]] json.object?["value"]?.object?["array"]?.array?.append(3) XCTAssertEqual(json, ["value": ["array": [1,2,3]]]) } func testMixedTypeEquality() { XCTAssertEqual(JSON.int64(42), JSON.double(42)) XCTAssertNotEqual(JSON.int64(42), JSON.double(42.1)) XCTAssertEqual(JSON.int64(42), JSON.decimal(42)) XCTAssertEqual(JSON.int64(Int64.max), JSON.decimal(Decimal(string: "9223372036854775807")!)) // Decimal(Int64.max) produces the wrong value XCTAssertEqual(JSON.int64(7393662029337442), JSON.decimal(Decimal(string: "7393662029337442")!)) XCTAssertNotEqual(JSON.int64(42), JSON.decimal(42.1)) XCTAssertEqual(JSON.double(42), JSON.decimal(42)) XCTAssertEqual(JSON.double(42.1), JSON.decimal(42.1)) XCTAssertEqual(JSON.double(1e100), JSON.decimal(Decimal(string: "1e100")!)) // Decimal(_: Double) can produce incorrect values } }
apache-2.0
3debfc7ab096de71bf9d187183fcd986
48.705128
147
0.556422
4.068206
false
false
false
false
banxi1988/BXForm
Pod/Classes/View/ExpandableTextView.swift
3
4422
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit open class ExpandableTextView: UITextView { fileprivate let placeholder: UITextView = UITextView() public init(frame: CGRect) { super.init(frame: frame, textContainer: nil) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } override open var contentSize: CGSize { didSet { self.invalidateIntrinsicContentSize() self.onContentSizeChangedCallback?(contentSize) self.layoutIfNeeded() // needed? } } open var onContentSizeChangedCallback:( (CGSize) -> Void )? open var onTextDidChangeCallback: ((String) -> Void)? deinit { NotificationCenter.default.removeObserver(self) } fileprivate func commonInit() { NotificationCenter.default.addObserver(self, selector: #selector(ExpandableTextView.textDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: self) self.configurePlaceholder() self.updatePlaceholderVisibility() } override open func layoutSubviews() { super.layoutSubviews() self.placeholder.frame = self.bounds } override open var intrinsicContentSize : CGSize { return self.contentSize } override open var text: String! { didSet { self.textDidChange() } } override open var textContainerInset: UIEdgeInsets { didSet { self.configurePlaceholder() } } override open var textAlignment: NSTextAlignment { didSet { self.configurePlaceholder() } } open func setTextPlaceholder(_ textPlaceholder: String) { self.placeholder.text = textPlaceholder } open func setTextPlaceholderColor(_ color: UIColor) { self.placeholder.textColor = color } open func setTextPlaceholderFont(_ font: UIFont) { self.placeholder.font = font } func textDidChange() { self.updatePlaceholderVisibility() self.scrollToCaret() onTextDidChangeCallback?(text) } fileprivate func scrollToCaret() { if selectedTextRange != nil { var rect = caretRect(for: self.selectedTextRange!.end) rect = CGRect(origin: rect.origin, size: CGSize(width: rect.width, height: rect.height + textContainerInset.bottom)) self.scrollRectToVisible(rect, animated: false) } } fileprivate func updatePlaceholderVisibility() { if text == "" { self.showPlaceholder() } else { self.hidePlaceholder() } } fileprivate func showPlaceholder() { self.addSubview(placeholder) } fileprivate func hidePlaceholder() { self.placeholder.removeFromSuperview() } fileprivate func configurePlaceholder() { self.placeholder.translatesAutoresizingMaskIntoConstraints = false self.placeholder.isEditable = false self.placeholder.isSelectable = false self.placeholder.isUserInteractionEnabled = false self.placeholder.textAlignment = textAlignment self.placeholder.textContainerInset = textContainerInset self.placeholder.backgroundColor = UIColor.clear } }
mit
9a1eab24baa9455079bdd86a106fdc12
30.140845
172
0.683627
5.289474
false
false
false
false
Nexmind/Swiftizy
Example/Swiftizy/TableViewController.swift
1
1591
// // TableViewController.swift // Swiftizy // // Created by Julien Henrard on 27/04/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import UIKit import Swiftizy class TableViewController: UITableViewController { var books : [Book]? = nil override func viewDidLoad() { super.viewDidLoad() self.books = CoreDataManager.Fetch.all(entity: Book.self) as? [Book] print("NUM OF BOOKS: \(self.books?.count)") } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return books!.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath) cell.textLabel?.text = books![indexPath.row].pk_title! return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let book = books![indexPath.row] let publisher = (book.publishers?.allObjects as! [Publisher])[0] let alert = UIAlertController(title: "Book details", message: "Title: \(book.pk_title!)\n Pages: \(book.number_of_pages)\n Publisher: \(publisher.name!)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } }
mit
a0ec66f6dddeec3fa2e166693b1cac8f
32.829787
186
0.66478
4.441341
false
false
false
false
chrisjmendez/swift-exercises
Animation/TextureAtlas/TextureAtlas/GameScene.swift
1
1693
// // GameScene.swift // TextureAtlas // // Created by Tommy Trojan on 10/15/15. // Copyright (c) 2015 Chris Mendez. All rights reserved. // // Resources // https://www.codeandweb.com/blog/2014/12/18/spritekit-textureatlases-with-swift import SpriteKit class GameScene: SKScene { let sheet = Hero() func initAnimation(){ let flappingSpeed = 0.06 let flap = SKAction.animate(with: sheet.Wings(), timePerFrame: flappingSpeed) let flapping = SKAction.repeat(flap, count: 5) //Actions let moveRight = SKAction.moveTo(x: 500, duration: flap.duration) let moveLeft = SKAction.moveTo(x: 100, duration: flap.duration) let mirrorDirection = SKAction.scaleX(to: -1, duration: 0.0) let resetDirection = SKAction.scaleX(to: 1, duration: 0.0) //Group of animations let walkAndMoveRight = SKAction.group([resetDirection, flapping, moveRight]) let walkAndMoveLeft = SKAction.group([mirrorDirection, flapping, moveLeft]) let sequence = SKAction.repeatForever(SKAction.sequence([walkAndMoveRight, walkAndMoveLeft])) let sprite = SKSpriteNode(texture: sheet.Wings01()) sprite.position = CGPoint(x: 100.0, y: CGFloat(arc4random() % 100) + 200.0) sprite.run(sequence) self.addChild(sprite) } override func didMove(to view: SKView) { initAnimation() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { } override func update(_ currentTime: TimeInterval) { /* Called before each frame is rendered */ } }
mit
5e379ba9375919250cc9d92e065180b6
29.232143
101
0.629061
4.089372
false
false
false
false
dtrauger/Charts
Source/Charts/Components/Description.swift
1
1284
// // Description.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(ChartDescription) open class Description: ComponentBase { public override init() { #if os(tvOS) // 23 is the smallest recommended font size on the TV font = NSUIFont.systemFont(ofSize: 23) #elseif os(OSX) font = NSUIFont.systemFont(ofSize: NSUIFont.systemFontSize()) #else font = NSUIFont.systemFont(ofSize: 8.0) #endif super.init() } /// The text to be shown as the description. @objc open var text: String? = "Description Label" /// Custom position for the description text in pixels on the screen. open var position: CGPoint? = nil /// The text alignment of the description text. Default RIGHT. @objc open var textAlign: NSTextAlignment = NSTextAlignment.right /// Font object used for drawing the description text. @objc open var font: NSUIFont /// Text color used for drawing the description text @objc open var textColor = NSUIColor.black }
apache-2.0
7dbdf599458be53b406a659555096f55
26.913043
73
0.649533
4.585714
false
false
false
false
MartinOSix/DemoKit
dSwift/SwiftDemoKit/SwiftDemoKit/MyCollectionViewController.swift
1
6164
// // MyCollectionViewController.swift // SwiftDemoKit // // Created by runo on 17/5/27. // Copyright © 2017年 com.runo. All rights reserved. // import UIKit let SectionBackground = "SectionBackground" class SBCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes { var backgroundColor = UIColor.clear } class SBCollectionReusableView: UICollectionReusableView { override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { super.apply(layoutAttributes) guard let attr = layoutAttributes as? SBCollectionViewLayoutAttributes else { return } self.backgroundColor = attr.backgroundColor } } protocol SBCollectionViewDelegateFlowLayout: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor } class SBCollectionViewFlowLayout: UICollectionViewFlowLayout { private var decorationViewAttrs: [UICollectionViewLayoutAttributes] = [] override func prepare() { super.prepare() guard let numberOfSections = self.collectionView?.numberOfSections, let delegate = self.collectionView?.delegate as? SBCollectionViewDelegateFlowLayout else { return } // 1、注册section背景view self.register(SBCollectionReusableView.classForCoder(), forDecorationViewOfKind: SectionBackground) //清除之前的属性 self.decorationViewAttrs.removeAll() //遍历所有的section for section in 0..<numberOfSections { //获取section中的第一个和最后一个item的Attribute guard let numberOfItems = self.collectionView?.numberOfItems(inSection: section), numberOfItems > 0, let firstItem = self.layoutAttributesForItem(at: IndexPath(item: 0, section: section)), let lastItem = self.layoutAttributesForItem(at: IndexPath(item: numberOfItems - 1, section: section)) else { continue } //获取section边距 var sectionInset = self.sectionInset if let inset = delegate.collectionView?(self.collectionView!, layout: self, insetForSectionAt: section) { sectionInset = inset } //联合,计算出这两个frame所包含的所有位置 var sectionFrame = firstItem.frame.union(lastItem.frame) sectionFrame.origin.x -= sectionInset.left sectionFrame.origin.y -= sectionInset.top if self.scrollDirection == .horizontal { sectionFrame.size.width += sectionInset.left + sectionInset.right sectionFrame.size.height = self.collectionView!.frame.height } else { sectionFrame.size.width = self.collectionView!.frame.width sectionFrame.size.height += sectionInset.top + sectionInset.bottom } // 2、定义 let attr = SBCollectionViewLayoutAttributes(forDecorationViewOfKind: SectionBackground, with: IndexPath(item: 0, section: section)) attr.frame = sectionFrame attr.zIndex = -1 attr.backgroundColor = delegate.collectionView(self.collectionView!, layout: self, backgroundColorForSectionAt: section) self.decorationViewAttrs.append(attr) } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attrs = super.layoutAttributesForElements(in: rect) for attr in self.decorationViewAttrs { if rect.intersects(attr.frame) { // 3、返回 attrs?.append(attr) } } return attrs } } class MyCollectionViewController: UIViewController,SBCollectionViewDelegateFlowLayout,UICollectionViewDataSource { var collection :UICollectionView? = nil override func viewDidLoad(){ super.viewDidLoad() let collectionLayout = SBCollectionViewFlowLayout.init() collectionLayout.itemSize = CGSize.init(width: 50, height: 50) collectionLayout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)//section边界 collectionLayout.scrollDirection = .vertical collectionLayout.minimumLineSpacing = 10 collectionLayout.minimumInteritemSpacing = 10 self.collection = UICollectionView.init(frame: kScreenBounds, collectionViewLayout: collectionLayout) self.collection?.backgroundColor = UIColor.white self.view.addSubview(self.collection!) self.collection?.dataSource = self self.collection?.delegate = self self.collection?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell") self.view.backgroundColor = UIColor.white } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in collectionView: UICollectionView) -> Int { return 3 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 8 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) cell.backgroundColor = UIColor.gray return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor{ switch section { case 1: return UIColor.red default: return UIColor.blue } } }
apache-2.0
08c8de839ec2ed0e0725223665046309
34.757396
166
0.653649
5.989098
false
false
false
false
zhangzhongfu/SwiftProject
TodayNewsSwift/TodayNewsSwift/Class/Main/Controller/DFTabbarViewController.swift
1
2259
// // DFTabbarViewController.swift // TodayNewsSwift // // Created by zzf on 2017/6/7. // Copyright © 2017年 zzf. All rights reserved. // import UIKit class DFTabbarViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.createTabbarItem() self.tabBar.tintColor = UIColor.red } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func createTabbarItem() { self.addItem(controller: DFHomeViewController(), title: "首页", image: "like", selectImage: "like_press") self.addItem(controller: DFMovieViewController(), title: "视频", image: "like", selectImage: "like_press") self.addItem(controller: DFMicroNewsViewController(), title: "微头条", image: "like", selectImage: "like_press") self.addItem(controller: DFMineViewController(), title: "我的", image: "like", selectImage: "like_press") } func addItem(controller: UIViewController, title: String, image: String, selectImage: String) { let nav = DFNavigationViewController.init(rootViewController: controller) controller.tabBarItem.image = UIImage.init(named: image) controller.tabBarItem.selectedImage = UIImage.init(named: selectImage) controller.title = title self.addChildViewController(nav) } // //1.分析 NSArray 是一个闭包的返回值,而这是一个没有参数的闭包 // lazy var dataArray:NSArray = { [] }() // //2.也可以写成这样 lazy var dataArray:NSArray = { return NSArray() }() // // //3.从plist文件加载 // lazy var dataArray:Array<XWWine> = { // let winePath = NSBundle.mainBundle().pathForResource("wine.plist", ofType: nil)! // let winesM = NSMutableArray(contentsOfFile: winePath); // var tmpArray:Array<XWWine>! = [] // for tmpWineDict in winesM! { // var wine:XWWine = XWWine.wineWithDict(tmpWineDict as! NSDictionary) // tmpArray.append(wine) // } // print("我就运行一次") // return tmpArray }() }
mit
6a318ed20c361d469b919f0778192e3d
35.508475
117
0.648097
4.079545
false
false
false
false
ALiOSDev/ALTableView
ALTableViewSwift/ALTableView/ALTableView/ALTableViewClasses/ALTableView/ALTableView.swift
1
1925
// // ALTableView.swift // ALTableView // // Created by lorenzo villarroel perez on 7/3/18. // Copyright © 2018 lorenzo villarroel perez. All rights reserved. // import UIKit @objc public protocol ALTableViewProtocol: class { @objc optional func tableViewPullToRefresh() @objc optional func tableViewDidReachEnd() } public class ALTableView: NSObject { //MARK: - Properties internal var sectionElements: Array<ALSectionElement> public weak var delegate: ALTableViewProtocol? public weak var editingDelegate: ALTableViewRowEditingProtocol? public weak var viewController: UIViewController? public weak var tableView: UITableView? public var movingRowsAllowed: Bool //MARK: - Initializers public init(sectionElements: Array<ALSectionElement>, viewController: UIViewController, tableView: UITableView, movingRowsAllowed: Bool = false) { self.sectionElements = sectionElements self.movingRowsAllowed = movingRowsAllowed super.init() self.viewController = viewController tableView.delegate = self tableView.dataSource = self self.tableView = tableView self.sectionElements.forEach { (sectionElement: ALSectionElement) in sectionElement.delegate = self } } //MARK: - Public methods public func registerCell(nibName: String, reuseIdentifier: String) { let nib = UINib(nibName: nibName, bundle: nil) self.tableView?.register(nib, forCellReuseIdentifier: reuseIdentifier) } public func registerHeaderFooter(nibName: String, reuseIdentifier: String) { let nib = UINib(nibName: nibName, bundle: nil) self.tableView?.register(nib, forHeaderFooterViewReuseIdentifier: reuseIdentifier) } //MARK: - Private methods }
mit
a9dbdc50845de3d56a28427ec2fd4d69
23.35443
90
0.673077
4.984456
false
false
false
false
mircealungu/Zeeguu-API-iOS
ZeeguuAPI/ZeeguuAPI/Feed.swift
2
5646
// // Feed.swift // ZeeguuAPI // // Created by Jorrit Oosterhof on 18-01-16. // Copyright © 2015 Jorrit Oosterhof. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit /// Adds support for comparing `Feed` objects using the equals operator (`==`) /// /// - parameter lhs: The left `Feed` operand of the `==` operator (left hand side) <pre><b>lhs</b> == rhs</pre> /// - parameter rhs: The right `Feed` operand of the `==` operator (right hand side) <pre>lhs == <b>rhs</b></pre> /// - returns: A `Bool` that states whether the two `Feed` objects are equal public func ==(lhs: Feed, rhs: Feed) -> Bool { return lhs.title == rhs.title && lhs.url == rhs.url && lhs.feedDescription == rhs.feedDescription && lhs.language == rhs.language && lhs.imageURL == rhs.imageURL } /// The `Feed` class represents an RSS feed. It holds the `id`, `title`, `url`, `feedDescription`, `language` and more about the feed. public class Feed: CustomStringConvertible, Equatable, ZGSerializable { // MARK: Properties - /// The id of this feed public var id: String? /// The title of this feed public var title: String /// The url of this feed public var url: String /// The description of this feed public var feedDescription: String /// The language of this feed public var language: String private var imageURL: String private var image: UIImage? /// The description of this `Feed` object. The value of this property will be used whenever the system tries to print this `Feed` object or when the system tries to convert this `Feed` object to a `String`. public var description: String { return "Feed: {\n\tid: \"\(id)\",\n\ttitle: \"\(title)\",\n\turl: \"\(url)\",\n\tdescription: \"\(feedDescription)\",\n\tlanguage: \"\(language)\",\n\timageURL: \"\(imageURL)\"\n}" } // MARK: Constructors - /** Construct a new `Feed` object. - parameter id: The id of this feed - parameter title: The title of the feed - parameter url: The url of the feed - parameter description: The description of the feed - parameter language: The language of the feed - parameter imageURL: The url for the image of the feed */ public init(id: String? = nil, title: String, url: String, description: String, language: String, imageURL: String) { self.id = id self.title = title self.url = url self.feedDescription = description self.language = language self.imageURL = imageURL } /** Construct a new `Feed` object from the data in the dictionary. - parameter dictionary: The dictionary that contains the data from which to construct an `Feed` object. */ @objc public required init?(dictionary dict: [String : AnyObject]) { guard let title = dict["title"] as? String, url = dict["url"] as? String, feedDescription = dict["feedDescription"] as? String, language = dict["language"] as? String, imageURL = dict["imageURL"] as? String else { return nil } self.id = dict["id"] as? String self.title = title self.url = url self.feedDescription = feedDescription self.language = language self.imageURL = imageURL self.image = dict["image"] as? UIImage } // MARK: Methods - /** The dictionary representation of this `Feed` object. - returns: A dictionary that contains all data of this `Feed` object. */ @objc public func dictionaryRepresentation() -> [String: AnyObject] { var dict = [String: AnyObject]() dict["id"] = self.id dict["title"] = self.title dict["url"] = self.url dict["feedDescription"] = self.feedDescription dict["language"] = self.language dict["imageURL"] = self.imageURL dict["image"] = self.image return dict } /** Get the image of this feed. This method will make sure that the image url is cached within this `Feed` object, so calling this method again will not retrieve the image again, but will return the cached version instead. - parameter completion: A closure that will be called once the image has been retrieved. If there was no image to retrieve, `image` is `nil`. Otherwise, it contains the feed image. */ public func getImage(completion: (image: UIImage?) -> Void) { if let imURL = NSURL(string: self.imageURL) { let request = NSMutableURLRequest(URL: imURL) ZeeguuAPI.sharedAPI().sendAsynchronousRequestWithDataResponse(request) { (data, error) -> Void in if let res = data { completion(image: UIImage(data: res)) } else { if ZeeguuAPI.sharedAPI().enableDebugOutput { print("Could not get image with url '\(self.imageURL)', error: \(error)") } completion(image: nil) } } } else { completion(image: nil) } } }
mit
b54e1802a271f731f0f9a52cbcb634a6
37.664384
219
0.699026
3.755822
false
false
false
false
jairoeli/Habit
ZeroTests/Sources/Tests/HabitListViewReactorTests.swift
1
2906
// // TaskListViewReactorTests.swift // Zero // // Created by Jairo Eli de Leon on 6/8/17. // Copyright © 2017 Jairo Eli de León. All rights reserved. // import XCTest @testable import Zero import RxCocoa import RxExpect import RxSwift import RxTest class TaskListViewReactorTests: XCTestCase { func testFetchHabits() { RxExpect("it should fetch saved habits") { test in let provider = MockServiceProvider() let reactor = test.retain(HabitListViewReactor(provider: provider)) // input test.input(reactor.action, [next(100, .refresh)]) // assertion let habitCount = reactor.state.map { $0.sections.first!.items.count } test.assert(habitCount) .since(100) .filterNext() .equal([3]) } } func testHabitIncreaseValue() { RxExpect("Tap cell to increase value") { test in let provider = MockServiceProvider() let reactor = test.retain(HabitListViewReactor(provider: provider)) // input test.input(reactor.action, [ next(100, .refresh), // prepare seed data next(200, .habitIncreaseValue(IndexPath(item: 0, section: 0))), next(300, .habitIncreaseValue(IndexPath(item: 0, section: 0))), next(400, .habitIncreaseValue(IndexPath(item: 2, section: 0))), ]) // assert let isIncrement = reactor.state.map { state in return state.sections[0].items.map { cellReactor in return cellReactor.currentState.value } } test.assert(isIncrement) .since(100) .filterNext() .equal([ [0, 0, 0], [1, 0, 0], [2, 0, 0], [2, 0, 1], ]) } } func testDeleteHabit() { RxExpect("it should delete the habit") { test in let provider = MockServiceProvider() let reactor = test.retain(HabitListViewReactor(provider: provider)) // input test.input(reactor.action, [ next(100, .refresh), // prepare seed data next(200, .deleteHabit(IndexPath(item: 0, section: 0))), ]) // assert let itemCount = reactor.state.map { $0.sections[0].items.count } test.assert(itemCount) .since(100) .filterNext() .equal([ 3, // initial 2, // after delete ]) } } func testCanSubmit() { RxExpect("it should adjust canSubmit when typing a new habit") { test in let provider = MockServiceProvider() let reactor = test.retain(HabitListViewReactor(provider: provider)) // input test.input(reactor.action, [ next(100, .updateHabitTitle("a")), next(200, .updateHabitTitle("")), ]) // assert test.assert(reactor.state.map { $0.canSubmit }) .filterNext() .equal([ false, // initial true, // "a" false, // "" ]) } } }
mit
28aca40e1475c42faca048fb9483c098
24.699115
76
0.584366
3.961801
false
true
false
false
tkach/SimpleRedditClient
SimpleRedditClient/Modules/EntryDetails/Assembly/EntryDetailsAssembly.swift
1
696
// // Created by Alexander Tkachenko on 9/10/17. // import UIKit final class EntryDetailsAssembly { private let imageLoader: ImageLoader init(imageLoader: ImageLoader) { self.imageLoader = imageLoader } func build(with coder: NSCoder) -> UIViewController { let item = EntryItemCoding.entryItem(with: coder) return build(with: item) } func build(with item: EntryItem) -> UIViewController { let controller = EntryDetailsViewController.fromStoryboard() let presenter = EntryDetailsPresenterImpl(view: controller, item: item, imageLoader: imageLoader) controller.presenter = presenter return controller } }
mit
61362b56384beba5e5f0a22a3925ee56
26.84
105
0.688218
4.702703
false
false
false
false
SuPair/firefox-ios
Client/Frontend/Browser/Toast.swift
3
2544
/* 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 SnapKit class Toast: UIView { var animationConstraint: Constraint? var completionHandler: ((Bool) -> Void)? weak var viewController: UIViewController? var dismissed = false lazy var gestureRecognizer: UITapGestureRecognizer = { let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap)) gestureRecognizer.cancelsTouchesInView = false return gestureRecognizer }() lazy var toastView: UIView = { let toastView = UIView() toastView.backgroundColor = SimpleToastUX.ToastDefaultColor return toastView }() override func didMoveToSuperview() { super.didMoveToSuperview() superview?.addGestureRecognizer(gestureRecognizer) } func showToast(viewController: UIViewController? = nil, delay: DispatchTimeInterval, duration: DispatchTimeInterval?, makeConstraints: @escaping (SnapKit.ConstraintMaker) -> Swift.Void) { self.viewController = viewController DispatchQueue.main.asyncAfter(deadline: .now() + delay) { viewController?.view.addSubview(self) self.snp.makeConstraints(makeConstraints) self.layoutIfNeeded() UIView.animate(withDuration: SimpleToastUX.ToastAnimationDuration, animations: { self.animationConstraint?.update(offset: 0) self.layoutIfNeeded() }) { finished in if let duration = duration { DispatchQueue.main.asyncAfter(deadline: .now() + duration) { self.dismiss(false) } } } } } func dismiss(_ buttonPressed: Bool) { guard !dismissed else { return } dismissed = true superview?.removeGestureRecognizer(gestureRecognizer) UIView.animate(withDuration: SimpleToastUX.ToastAnimationDuration, animations: { self.animationConstraint?.update(offset: SimpleToastUX.ToastHeight) self.layoutIfNeeded() }) { finished in self.removeFromSuperview() if !buttonPressed { self.completionHandler?(false) } } } @objc func handleTap(_ gestureRecognizer: UIGestureRecognizer) { dismiss(false) } }
mpl-2.0
815480707ffbeec00fc9f009cb9cdae2
33.378378
191
0.640723
5.653333
false
false
false
false
dabing1022/AlgorithmRocks
DataStructureAlgorithm/Sources/BinaryTreeNode.swift
1
547
// // TreeNode.swift // AlgorithmRocks // // Created by ChildhoodAndy on 16/2/3. // Copyright © 2016年 ChildhoodAndy. All rights reserved. // import Foundation class BinaryTreeNode<T: Equatable> { var key: T var left: BinaryTreeNode? var right: BinaryTreeNode? init (_ key: T) { self.key = key self.left = nil self.right = nil } convenience init (key: T, left: BinaryTreeNode?, right: BinaryTreeNode?) { self.init(key) self.left = left self.right = right } }
mit
ce1121bf10dd88a0d67d2dff4616d356
19.961538
78
0.602941
3.675676
false
false
false
false
garoor/ios
GarageDoorRemote/ViewController.swift
1
2021
// // ViewController.swift // GarageDoorRemote // // Created by Nate Armstrong on 12/11/14. // Copyright (c) 2014 Nate Armstrong. All rights reserved. // import UIKit class ViewController: UIViewController, GarageDoorStateMachineDelegate { @IBOutlet weak var closedImage: UIImageView! @IBOutlet weak var doorConstraint: NSLayoutConstraint! @IBOutlet weak var mainButton: UIButton! var meteorClient: MeteorClient! var state = GarageDoorStateMachine() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) closedImage.superview!.clipsToBounds = true NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveUpdate:", name: "added", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveUpdate:", name: "changed", object: nil) state.delegate = self } @IBAction func didPressButton(sender: AnyObject) { meteorClient.callMethodName("updateActivity", parameters: [["phone": NSDate().description, "pi": NSNull()]], nil) } func didReceiveUpdate(notification: NSNotification) { state.update(notification.userInfo) } func stateDidUpdate() { updateUI() } func updateUI() { if state.pi != nil { animateDoor(state.garage) } let bgColor = state.pi != nil ? UIColor(red: 74/255.0, green: 144/255.0, blue: 226/255.0, alpha: 1.0) : UIColor(red: 85/255.0, green: 98/255.0, blue: 112/255.0, alpha: 1.0) UIView.animateWithDuration(0.75, delay: 0.0, options: .CurveEaseOut, animations: { self.view.backgroundColor = bgColor }, completion: nil) mainButton.setTitle((!state.garage).toActionString(), forState: .Normal) } func animateDoor(position: GarageDoorState) { let constant = position == .Open ? -self.closedImage.frame.size.height : 0.0 UIView.animateWithDuration(2.0, delay: 0.0, options: .CurveEaseInOut, animations: { self.doorConstraint.constant = constant self.view.layoutIfNeeded() }, completion: nil) } }
gpl-2.0
56228b1e9185582ed308a8e1760bd489
32.683333
119
0.710045
3.978346
false
false
false
false
salemoh/GoldenQuraniOS
GoldenQuranSwift/GoldenQuranSwift/ManageNotificationsViewController.swift
1
4902
// // ManageNotificationsViewController.swift // GoldenQuranSwift // // Created by Omar Fraiwan on 4/9/17. // Copyright © 2017 Omar Fraiwan. All rights reserved. // import UIKit enum ManageNotificationsViewControllerCell:String { case fridayNotification = "fridayNotification" case dailyNotification = "dailyNotification" case longTimeNotReading = "longTimeNotReading" case athanNotifications = "athanNotifications" } class ManageNotificationsViewController: UIViewController { @IBOutlet weak var tableView:UITableView! var cells = [ManageNotificationsViewControllerCell]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. cells.append(.fridayNotification) cells.append(.dailyNotification) cells.append(.longTimeNotReading) cells.append(.athanNotifications) self.tableView.reloadData() self.tableView.estimatedRowHeight = 85 self.title = NSLocalizedString("MANAGE_NOTIFICATIONS_TITLE", comment: "") } 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. } */ } extension ManageNotificationsViewController:UITableViewDelegate{ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{ return UITableViewAutomaticDimension } } extension ManageNotificationsViewController:UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return cells.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCell(withIdentifier: "ManageNotificationsTableViewCell") as! ManageNotificationsTableViewCell switch cells[indexPath.row] { case .fridayNotification: cell.lblTitle.text = NSLocalizedString("MANAGE_NOTIFICATION_FRIDAY_READING_TITLE", comment: "") cell.lblSubTitle.text = NSLocalizedString("MANAGE_NOTIFICATION_FRIDAY_READING_SUBTITLE", comment: "") cell.switchControl.isOn = !UserDefaults.standard.bool(forKey:Constants.userDefaultsKeys.notificationsFridayDisabled) cell.actionsHandler = {(isOn: Bool) -> Void in UserDefaults.standard.set(!isOn, forKey: Constants.userDefaultsKeys.notificationsFridayDisabled) UserDefaults.standard.synchronize() } case .dailyNotification: cell.lblTitle.text = NSLocalizedString("MANAGE_NOTIFICATION_DAILY_TITLE", comment: "") cell.lblSubTitle.text = NSLocalizedString("MANAGE_NOTIFICATION_DAILY_SUBTITLE", comment: "") cell.switchControl.isOn = !UserDefaults.standard.bool(forKey:Constants.userDefaultsKeys.notificationsDailyDisabled) cell.actionsHandler = {(isOn: Bool) -> Void in UserDefaults.standard.set(!isOn, forKey: Constants.userDefaultsKeys.notificationsDailyDisabled) UserDefaults.standard.synchronize() } case .longTimeNotReading: cell.lblTitle.text = NSLocalizedString("MANAGE_NOTIFICATION_LONG_TIME_TITLE", comment: "") cell.lblSubTitle.text = NSLocalizedString("MANAGE_NOTIFICATION_LONG_TIME_SUBTITLE", comment: "") cell.switchControl.isOn = !UserDefaults.standard.bool(forKey:Constants.userDefaultsKeys.notificationsLongTimeReadingDisabled) cell.actionsHandler = {(isOn: Bool) -> Void in UserDefaults.standard.set(!isOn, forKey: Constants.userDefaultsKeys.notificationsLongTimeReadingDisabled) UserDefaults.standard.synchronize() } case .athanNotifications: cell.lblTitle.text = NSLocalizedString("MANAGE_NOTIFICATION_ATHAN_TITLE", comment: "") cell.lblSubTitle.text = NSLocalizedString("MANAGE_NOTIFICATION_ATHAN_SUBTITLE", comment: "") cell.switchControl.isOn = !UserDefaults.standard.bool(forKey:Constants.userDefaultsKeys.notificationsAthanDisabled) cell.actionsHandler = {(isOn: Bool) -> Void in UserDefaults.standard.set(!isOn, forKey: Constants.userDefaultsKeys.notificationsAthanDisabled) UserDefaults.standard.synchronize() } } cell.setNeedsLayout() return cell } }
mit
41a04839087b080284c8e75d7ef524fc
40.533898
137
0.690267
5.191737
false
false
false
false
fyl00/MonkeyKing
China/AlipayViewController.swift
1
2687
// // AlipayViewController.swift // China // // Created by Cai Linfeng on 1/26/16. // Copyright © 2016 nixWork. All rights reserved. // import UIKit import MonkeyKing class AlipayViewController: UIViewController { @IBOutlet fileprivate var segmentedControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() let account = MonkeyKing.Account.alipay(appID: Configs.Alipay.appID) MonkeyKing.registerAccount(account) } @IBAction func shareTextToAlipay(_ sender: UIButton) { let info = MonkeyKing.Info( title: "Friends Text, \(UUID().uuidString)", description: nil, thumbnail: nil, media: nil ) self.shareInfo(info) } @IBAction func shareImageToAlipay(_ sender: UIButton) { let info = MonkeyKing.Info( title: nil, description: nil, thumbnail: nil, media: .image(UIImage(named: "rabbit")!) ) self.shareInfo(info) } @IBAction func shareURLToAlipay(_ sender: UIButton) { let info = MonkeyKing.Info( title: "Friends URL, \(UUID().uuidString)", description: "Description URL, \(UUID().uuidString)", thumbnail: UIImage(named: "rabbit"), media: .url(URL(string: "http://soyep.com")!) ) self.shareInfo(info) } fileprivate func shareInfo(_ info: MonkeyKing.Info) { var message: MonkeyKing.Message? switch segmentedControl.selectedSegmentIndex { case 0: message = MonkeyKing.Message.alipay(.friends(info: info)) case 1: guard let _ = info.media else { print("目前支付宝生活圈还不支持纯文本的分享") break } message = MonkeyKing.Message.alipay(.timeline(info: info)) default: break } if let message = message { MonkeyKing.deliver(message) { result in print("result: \(result)") } } } // MARK: Pay @IBAction func pay(_ sender: UIButton) { do { let data = try NSURLConnection.sendSynchronousRequest(URLRequest(url: URL(string: "http://www.example.com/pay.php?payType=alipay")!), returning: nil) let urlString = String(data: data, encoding: .utf8)! let order = MonkeyKing.Order.alipay(urlString: urlString, scheme: nil) MonkeyKing.deliver(order) { result in print("result: \(result)") } } catch { print(error) } } }
mit
42a635f826f6d22909fb03936dea649b
27.494624
161
0.561887
4.632867
false
false
false
false
weizhangCoder/DYZB_ZW
DYZB_ZW/DYZB_ZW/Home/Controller/AmuseViewController.swift
1
1368
// // AmuseViewController.swift // DYZB_ZW // // Created by zhangwei on 17/8/7. // Copyright © 2017年 jyall. All rights reserved. // import UIKit private let kMenuViewH : CGFloat = 200 class AmuseViewController: BaseAnchorViewController{ fileprivate var amuseVM :AmuseViewModel = AmuseViewModel() fileprivate var amuseView : AmuseMenuView = { let amuseView = AmuseMenuView.amuseMenuView() amuseView.frame = CGRect(x: 0, y: -kMenuViewH, width: KscreenW, height: kMenuViewH) return amuseView }() override func viewDidLoad() { super.viewDidLoad() } } extension AmuseViewController{ override func setupUI() { super.setupUI() collectionView.addSubview(amuseView) collectionView.contentInset = UIEdgeInsetsMake(kMenuViewH, 0, 0, 0) } } extension AmuseViewController{ override func loadData() { baseVM = amuseVM amuseVM.loadAmuseData { self.collectionView.reloadData() // 2.2.调整数据 var tempGroups = self.amuseVM.anchorGroups tempGroups.removeFirst() self.amuseView.groups = tempGroups //3.消失动画 请求数据完成 self.loadDataFinished() } } }
mit
d0bd1e3357bb8eec77c1767297ecd9cc
21.283333
91
0.595363
4.879562
false
false
false
false
XSega/Words
Words/AppRouter.swift
1
1566
// // AppRouter.swift // Words // // Created by Sergey Ilyushin on 27/07/2017. // Copyright © 2017 Sergey Ilyushin. All rights reserved. // import UIKit class AppRouter: NSObject { let api = SkyengAPI(session: AlamofireSession()) func startApp(window: UIWindow?) { if let _ = UserDefaults.standard.string(forKey: Keys.User.Dictionary) { navigateToMenu(window: window) return } // Get stored user data let email = UserDefaults.standard.string(forKey: Keys.User.Email) let token = UserDefaults.standard.string(forKey: Keys.User.Token) if let _ = email, let _ = token { navigateToLaunch(window: window) } else { navigateToLogin(window: window) } } func navigateToLaunch(window: UIWindow?) { window?.makeKeyAndVisible() let storyboard = UIStoryboard(name: "Launch", bundle: nil) window?.rootViewController = storyboard.instantiateInitialViewController() } func navigateToMenu(window: UIWindow?) { window?.makeKeyAndVisible() let storyboard = UIStoryboard(name: "Main", bundle: nil) window?.rootViewController = storyboard.instantiateInitialViewController() } func navigateToLogin(window: UIWindow?) { window?.makeKeyAndVisible() let storyboard = UIStoryboard(name: "Login", bundle: nil) window?.rootViewController = storyboard.instantiateInitialViewController() } }
mit
ad01dfd990e3ff544a9261c2629aeb82
27.454545
82
0.623003
4.984076
false
false
false
false
billCTG/braintree_ios
UITests/BraintreeThreeDSecure_UITests.swift
1
20664
/* IMPORTRANT Hardware keyboard should be disabled on simulator for tests to run reliably. */ import XCTest class BraintreeThreeDSecurePaymentFlow_UITests: XCTestCase { var app: XCUIApplication! let timeout: TimeInterval = 20 override func setUp() { super.setUp() continueAfterFailure = false app = XCUIApplication() app.launchArguments.append("-EnvironmentSandbox") app.launchArguments.append("-ClientToken") app.launchArguments.append("-Integration:BraintreeDemoThreeDSecurePaymentFlowViewController") self.app.launch() sleep(1) self.waitForElementToBeHittable(app.textFields["Card Number"]) sleep(2) } func getPasswordFieldQuery() -> XCUIElementQuery { return app.webViews.element.otherElements.children(matching: .other).children(matching: .secureTextField) } func getSubmitButton() -> XCUIElement { return app.webViews.element.otherElements.children(matching: .other).children(matching: .other).buttons["Submit"] } func testThreeDSecurePaymentFlow_completesAuthentication_receivesNonce() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000002") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(getPasswordFieldQuery().element, timeout: timeout) let passwordTextField = getPasswordFieldQuery().element passwordTextField.forceTapElement() sleep(2) passwordTextField.typeText("1234") getSubmitButton().tap() self.waitForElementToAppear(app.buttons["Liability shift possible and liability shifted"]) } func testThreeDSecurePaymentFlow_failsAuthentication() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000010") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(getPasswordFieldQuery().element, timeout: timeout) let passwordTextField = getPasswordFieldQuery().element passwordTextField.forceTapElement() sleep(1) passwordTextField.typeText("1234") getSubmitButton().tap() self.waitForElementToAppear(app.buttons["Failed to authenticate, please try a different form of payment."]) } func testThreeDSecurePaymentFlow_bypassesAuthentication_notEnrolled() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000051") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } func testThreeDSecurePaymentFlow_bypassesAuthentication_lookupFailed() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000077") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } func testThreeDSecurePaymentFlow_incorrectPassword_callsBackWithError_exactlyOnce() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000028") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(getPasswordFieldQuery().element, timeout: timeout) let passwordTextField = getPasswordFieldQuery().element passwordTextField.forceTapElement() sleep(1) passwordTextField.typeText("1234") getSubmitButton().tap() self.waitForElementToAppear(app.buttons["Failed to authenticate, please try a different form of payment."]) sleep(2) self.waitForElementToAppear(app.staticTexts["Callback Count: 1"]) } func testThreeDSecurePaymentFlow_passiveAuthentication_notPromptedForAuthentication() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000101") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["Liability shift possible and liability shifted"]) } func testThreeDSecurePaymentFlow_returnsNonce_whenIssuerDown() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000036") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(getPasswordFieldQuery().element, timeout: timeout) let passwordTextField = getPasswordFieldQuery().element passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmitButton().tap() self.waitForElementToAppear(app.buttons["An unexpected error occurred"]) } func testThreeDSecurePaymentFlow_acceptsPassword_failsToAuthenticateNonce_dueToCardinalError() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000093") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(getPasswordFieldQuery().element, timeout: timeout) let passwordTextField = getPasswordFieldQuery().element passwordTextField.forceTapElement() sleep(2) passwordTextField.typeText("1234") getSubmitButton().tap() self.waitForElementToAppear(app.buttons["An unexpected error occurred"]) } func testThreeDSecurePaymentFlow_returnsToApp_whenCancelTapped() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000002") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(app.buttons["Done"]) app.buttons["Done"].forceTapElement() self.waitForElementToAppear(app.buttons["Cancelled🎲"]) XCTAssertTrue(app.buttons["Cancelled🎲"].exists); } func testThreeDSecurePaymentFlow_bypassedAuthentication() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000990000000004") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } func testThreeDSecurePaymentFlow_lookupError() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000085") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } func testThreeDSecurePaymentFlow_unavailable() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000069") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } func testThreeDSecurePaymentFlow_timeout() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000044") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(5) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) } } class BraintreeThreeDSecure_UITests: XCTestCase { var app: XCUIApplication! override func setUp() { super.setUp() continueAfterFailure = false app = XCUIApplication() app.launchArguments.append("-EnvironmentSandbox") app.launchArguments.append("-ClientToken") app.launchArguments.append("-Integration:BraintreeDemoThreeDSecureViewController") self.app.launch() sleep(1) self.waitForElementToBeHittable(app.textFields["Card Number"]) sleep(2) } func getPasswordFieldQuery() -> XCUIElementQuery { return app.webViews.element.otherElements.children(matching: .other).children(matching: .secureTextField) } func getSubmitButton() -> XCUIElement { return app.webViews.element.otherElements.children(matching: .other).children(matching: .other).buttons["Submit"] } func testThreeDSecure_completesAuthentication_receivesNonce() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000002") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(getPasswordFieldQuery().element) let passwordTextField = getPasswordFieldQuery().element passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmitButton().tap() self.waitForElementToAppear(app.buttons["Liability shift possible and liability shifted"]) XCTAssertTrue(app.buttons["Liability shift possible and liability shifted"].exists); } func testThreeDSecure_failsAuthentication() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000010") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(getPasswordFieldQuery().element) let passwordTextField = getPasswordFieldQuery().element passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmitButton().tap() self.waitForElementToAppear(app.buttons["Failed to authenticate, please try a different form of payment."]) XCTAssertTrue(app.buttons["Failed to authenticate, please try a different form of payment."].exists); } func testThreeDSecure_bypassesAuthentication_notEnrolled() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000051") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } func testThreeDSecure_bypassesAuthentication_lookupFailed() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000077") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } func testThreeDSecure_incorrectPassword_callsBackWithError_exactlyOnce() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000028") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(getPasswordFieldQuery().element) let passwordTextField = getPasswordFieldQuery().element passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmitButton().tap() self.waitForElementToAppear(app.buttons["Failed to authenticate, please try a different form of payment."]) XCTAssertTrue(app.buttons["Failed to authenticate, please try a different form of payment."].exists); sleep(2) self.waitForElementToAppear(app.staticTexts["Callback Count: 1"]) XCTAssertTrue(app.staticTexts["Callback Count: 1"].exists); } func testThreeDSecure_passiveAuthentication_notPromptedForAuthentication() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000101") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["Liability shift possible and liability shifted"]) XCTAssertTrue(app.buttons["Liability shift possible and liability shifted"].exists); } func testThreeDSecure_returnsNonce_whenIssuerDown() { let app = XCUIApplication() self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000036") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(getPasswordFieldQuery().element) let passwordTextField = getPasswordFieldQuery().element passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmitButton().tap() self.waitForElementToAppear(app.buttons["An unexpected error occurred"]) XCTAssertTrue(app.buttons["An unexpected error occurred"].exists); } func testThreeDSecure_acceptsPassword_failsToAuthenticateNonce_dueToCardinalError() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000093") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() self.waitForElementToAppear(getPasswordFieldQuery().element) let passwordTextField = getPasswordFieldQuery().element passwordTextField.tap() sleep(1) passwordTextField.typeText("1234") getSubmitButton().tap() self.waitForElementToAppear(app.buttons["An unexpected error occurred"]) XCTAssertTrue(app.buttons["An unexpected error occurred"].exists); } func testThreeDSecure_returnsToApp_whenCancelTapped() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000002") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToBeHittable(app.buttons["Cancel"]) app.buttons["Cancel"].forceTapElement() self.waitForElementToAppear(app.buttons["Cancelled🎲"]) XCTAssertTrue(app.buttons["Cancelled🎲"].exists); } func testThreeDSecure_bypassedAuthentication() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000990000000004") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } func testThreeDSecure_lookupError() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000085") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } func testThreeDSecure_unavailable() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000069") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(2) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } func testThreeDSecure_timeout() { self.waitForElementToAppear(app.textFields["Card Number"]) let cardNumberTextField = app.textFields["Card Number"] cardNumberTextField.tap() cardNumberTextField.typeText("4000000000000044") app.textFields["MM/YY"].typeText("012020") app.buttons["Tokenize and Verify New Card"].tap() sleep(5) self.waitForElementToAppear(app.buttons["3D Secure authentication was attempted but liability shift is not possible"]) XCTAssertTrue(app.buttons["3D Secure authentication was attempted but liability shift is not possible"].exists); } }
mit
3155accf483adeda656ee1e8cf614e89
40.139442
126
0.693395
5.080443
false
true
false
false
gdamron/PaulaSynth
PaulaSynth/SythSound.swift
1
1778
// // SythSound.swift // AudioEngine2 // // Created by Grant Damron on 10/10/16. // Copyright © 2016 Grant Damron. All rights reserved. // import Foundation import AudioKit enum SynthSound: String { case Square, Triangle, Sawtooth, FM, Sine, TwentySixHundred static var keys: [String] { return ["Square", "Triangle", "Sawtooth", "FM", "Sine", "2600"] } var waveform: AKTable { switch self { case .Square: return AKTable(.square) case .Triangle: return AKTable(.triangle) case .Sawtooth: return AKTable(.sawtooth) case .FM: return AKTable(.square) case .Sine: return AKTable(.sine) case .TwentySixHundred: return AKTable(.reverseSawtooth) } } var name: String { switch self { case .Square: return SynthSound.keys[0] case .Triangle: return SynthSound.keys[1] case .Sawtooth: return SynthSound.keys[2] case .FM: return SynthSound.keys[3] case .Sine: return SynthSound.keys[4] case .TwentySixHundred: return SynthSound.keys[5] } } var velocity: UInt8 { switch self { case .Square: return 64 case .Triangle: return 96 case .Sawtooth: return 64 case .FM: return 64 case .Sine: return 96 case .TwentySixHundred: return 72 } } init(key: String) { switch key { case SynthSound.keys[0]: self = .Square case SynthSound.keys[1]: self = .Triangle case SynthSound.keys[2]: self = .Sawtooth case SynthSound.keys[3]: self = .FM case SynthSound.keys[4]: self = .Sine case SynthSound.keys[5]: self = .TwentySixHundred default: self = .Square } } }
apache-2.0
82794d4abf68b8b5c863d25924cde95c
27.206349
71
0.591446
3.940133
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 2/4-3 Playgrounds/Functions 2.playground/Pages/Section 3 - Generic Functions.xcplaygroundpage/Contents.swift
1
1395
//: [Previous](@previous) import UIKit import XCPlayground //: ![Functions Part 2](banner.png) //: # Functions Part 2 - Section 3 //: Version 2 - updated for Swift 2 //: //: 23-11-2015 //: //: This playground is designed to support the materials of the lecure "Functions 2". //: ## Generic Functions //: Consider the following function func swapInt( tupleValue : (Int, Int) ) -> (Int, Int) { let y = (tupleValue.1, tupleValue.0) return y } let u2 = (2,3) let v2 = swapInt( u2 ) //: This function only works with type Int. It cannot be used for other types. This is where Generics come in. The compiler will generate alternative versions using the required types (where appropriate). //: ### Generic Functions without constraints func swap<U,V>( tupleValue : (U, V) ) -> (V, U) { let y = (tupleValue.1, tupleValue.0) return y } swap( (1, "Fred") ) //: ### Generic Functions with constraints func compareAnything<U:Equatable>(a : U, b : U) -> Bool { return a == b } compareAnything(10, b: 10) //: ### Generic Functions with custom constraints protocol CanMultiply { func *(left: Self, right: Self) -> Self } extension Double : CanMultiply {} extension Int : CanMultiply {} extension Float : CanMultiply {} func cuboidVolume<T:CanMultiply>(width:T, _ height:T, _ depth:T) -> T { return (width*height*depth) } cuboidVolume(2.1, 3.1, 4.1) cuboidVolume(2.1, 3, 4)
mit
14df1c53f3f265b2c9258c4711cce768
23.051724
204
0.671685
3.361446
false
false
false
false
ngageoint/fog-machine
Demo/FogViewshed/FogViewshed/Models/Viewshed/VanKreveld/KreveldActiveBinaryTree.swift
1
16092
import Foundation // based on the paper : http://www.cs.uu.nl/research/techreps/repo/CS-1996/1996-22.pdf public struct KreveldActiveBinaryTree { static let FLAG_FALSE: Bool = false static let FLAG_TRUE: Bool = true private var root: VanKreveldStatusEntry? private var reference: VanKreveldCell init(reference: VanKreveldCell) { self.reference = reference } public mutating func insert (value: VanKreveldCell) { // ecludian distance in grid units let key : Double = sqrt(pow(Double(self.reference.x) - Double(value.x), 2) + pow(Double(self.reference.y) - Double(value.y), 2)) let oppositeInMeters:Double = value.h - self.reference.h // find the slope of the line from the current cell to the observer let slopeMonotonicMeasure:Double = oppositeInMeters/key var y: VanKreveldStatusEntry? = nil var x: VanKreveldStatusEntry? = self.root while x !== nil { y = x y!.maxSlope = max(y!.maxSlope, slopeMonotonicMeasure) if (key < x!.key) { x = x!.left } else { x = x!.right } } let z: VanKreveldStatusEntry = VanKreveldStatusEntry(key: key, value: value, slope: slopeMonotonicMeasure, parent: y) if (y == nil) { self.root = z; } else { if (key < y!.key) { y!.left = z } else { y!.right = z } } self.fixAfterInsertion(z) } private mutating func fixAfterInsertion(xx: VanKreveldStatusEntry?) { var xx = xx while xx != nil && xx !== self.root && xx!.parent !== nil && xx!.parent!.flag == KreveldActiveBinaryTree.FLAG_FALSE { let greatGreatLeft :VanKreveldStatusEntry? = self.leftOf(self.parentOf(self.parentOf(xx))) if (self.parentOf(xx) === greatGreatLeft) { let y:VanKreveldStatusEntry? = self.rightOf(self.parentOf(self.parentOf(xx))) if self.flagOf(y) == KreveldActiveBinaryTree.FLAG_FALSE { self.setFlag(self.parentOf(xx), c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(y, c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(self.parentOf(self.parentOf(xx)), c: KreveldActiveBinaryTree.FLAG_FALSE) xx = self.parentOf(self.parentOf(xx)) } else { if xx === self.rightOf(self.parentOf(xx)) { xx = self.parentOf(xx) self.rotateLeft(xx) } self.setFlag(self.parentOf(xx), c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(self.parentOf(self.parentOf(xx)), c: KreveldActiveBinaryTree.FLAG_FALSE) self.rotateRight(self.parentOf(self.parentOf(xx))) } } else { let y:VanKreveldStatusEntry? = self.leftOf(self.parentOf(self.parentOf(xx))) if self.flagOf(y) == KreveldActiveBinaryTree.FLAG_FALSE { self.setFlag(self.parentOf(xx), c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(y, c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(self.parentOf(self.parentOf(xx)), c: KreveldActiveBinaryTree.FLAG_FALSE) xx = self.parentOf(self.parentOf(xx)) } else { if xx === self.leftOf(self.parentOf(xx)) { xx = self.parentOf(xx) self.rotateRight(xx) } self.setFlag(self.parentOf(xx), c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(self.parentOf(self.parentOf(xx)), c: KreveldActiveBinaryTree.FLAG_FALSE) self.rotateLeft(self.parentOf(self.parentOf(xx))) } } } if self.root != nil { self.root!.flag = KreveldActiveBinaryTree.FLAG_TRUE } } public mutating func delete (pt: VanKreveldCell) { // verify if all the 'nil' check necessary var p: VanKreveldStatusEntry? = self.getEntry(pt) if p == nil { return } // If strictly internal, copy successor's element to p and then make p // point to successor. // Because of (p.right != null) the successor of p is the minimum of p.right if p!.left != nil && p!.right != nil { let s:VanKreveldStatusEntry! = self.getMinimum(p!.right) // = successor(p) p!.key = s.key p!.value = s.value p!.slope = s.slope p = s } // update maxSlope p!.maxSlope = max(self.maxSlopeOf(p!.left), self.maxSlopeOf(p!.right)); // dummy value var x: VanKreveldStatusEntry? = p!.parent; while (x != nil) { x!.maxSlope = max( x!.slope, max(self.maxSlopeOf(x!.left), self.maxSlopeOf(x!.right)) ); x = x!.parent; } // Start fixup at replacement node, if it exists. let replacement: VanKreveldStatusEntry? = (p!.left != nil ? p!.left : p!.right); if (replacement != nil) { // Here p has exactly one child. Otherwise p would point to its successor, which has no left child. // Link replacement to parent replacement!.parent = p!.parent; if (p!.parent == nil) { self.root = replacement } else if (p === p!.parent!.left) { p!.parent!.left = replacement } else { p!.parent!.right = replacement } // nil out links so they are OK to use by fixAfterDeletion. p!.left = nil p!.right = nil p!.parent = nil // Fix replacement if (p!.flag == KreveldActiveBinaryTree.FLAG_TRUE) { self.fixAfterDeletion(replacement) } } else if (p!.parent == nil) { // return if we are the only node. self.root = nil } else { // No children. Use self as phantom replacement and unlink. if (p!.flag == KreveldActiveBinaryTree.FLAG_TRUE) { self.fixAfterDeletion(p) } if (p!.parent != nil) { if (p === p!.parent!.left) { p!.parent!.left = nil } else if (p === p!.parent!.right) { p!.parent!.right = nil } p!.parent = nil } } } // Searches the status structure for a point p and returns the corresponding StatusEntry. // param p HeightedPoint to be searched // returns StatusEntry private func getEntry(let p: VanKreveldCell) -> VanKreveldStatusEntry? { let key: Double = sqrt(pow(Double(self.reference.x) - Double(p.x), 2) + pow(Double(self.reference.y) - Double(p.y), 2)) var t: VanKreveldStatusEntry? = self.root while (t != nil) { if (key < t!.key) { t = t!.left } else if (key > t!.key) { t = t!.right } else if (p.x == t!.value.x && p.y == t!.value.y) { return t // found it! } else { //search to the left and to the right if (t!.left != nil && p.x == t!.left!.value.x && p.y == t!.left!.value.y) { return t!.left } if (t!.right != nil && p.x == t!.right!.value.x && p.y == t!.right!.value.y) { return t!.right } return nil // assuming the searched point can only be in one of the children } } return nil } private func getMinimum (let p: VanKreveldStatusEntry?) -> VanKreveldStatusEntry? { if (p == nil) { return nil } var min: VanKreveldStatusEntry? = p while (min!.left != nil) { min = min!.left } return min! } private func maxSlopeOf(p: VanKreveldStatusEntry?) -> Double { return (p == nil ? -Double.infinity: p!.maxSlope); } private func flagOf(p: VanKreveldStatusEntry?) -> Bool { return (p == nil ? KreveldActiveBinaryTree.FLAG_TRUE : p!.flag); } private func setFlag(let p: VanKreveldStatusEntry?, c:Bool) { if p != nil { p!.flag = c } } private func parentOf(let p: VanKreveldStatusEntry?) -> VanKreveldStatusEntry? { if p == nil { return nil } else { var tmp:VanKreveldStatusEntry? = nil if p!.parent !== nil { tmp = p!.parent } else { return nil } return tmp } } private func leftOf(let p: VanKreveldStatusEntry?) -> VanKreveldStatusEntry? { return (p == nil) ? nil: p!.left } private func rightOf(let p: VanKreveldStatusEntry?) -> VanKreveldStatusEntry? { return (p == nil) ? nil: p!.right } mutating private func rotateLeft(let p: VanKreveldStatusEntry?) { if p != nil { let r: VanKreveldStatusEntry? = p!.right // verify if all the 'nil' check necessary if r != nil { p!.right = r!.left if r!.left != nil { r!.left!.parent = p } r!.parent = p!.parent } // verify if all the 'nil' check necessary if p!.parent == nil { self.root = r } else if p!.parent!.left === p { p!.parent!.left = r } else { p!.parent!.right = r } if r != nil { r!.left = p } p!.parent = r if r != nil { r!.maxSlope = p!.maxSlope } p!.maxSlope = max( p!.slope, max(self.maxSlopeOf(p!.left), self.maxSlopeOf(p!.right)) ) } } private mutating func rotateRight(let p: VanKreveldStatusEntry?) { if p != nil { let l: VanKreveldStatusEntry? = p!.left if l != nil { p!.left = l!.right if l!.right != nil { l!.right!.parent = p } else { } } else { p!.left = nil } if (p!.parent != nil) { if l != nil { l!.parent = p!.parent } else { } } else { if l != nil { if l!.parent != nil { l!.parent = nil } } } if p!.parent == nil { self.root = l } else if p!.parent!.right === p { p!.parent!.right = l } else { p!.parent!.left = l } if l != nil { l!.right = p } l!.right = p p!.parent = l if l != nil { l!.maxSlope = p!.maxSlope } p!.maxSlope = max( p!.slope, max(self.maxSlopeOf(p!.left), self.maxSlopeOf(p!.right)) ) } } private mutating func fixAfterDeletion(xx: VanKreveldStatusEntry?) { var xx = xx while (xx !== self.root && self.flagOf(xx) == KreveldActiveBinaryTree.FLAG_TRUE) { if (xx === self.leftOf(self.parentOf(xx))) { var sib: VanKreveldStatusEntry? = self.rightOf(self.parentOf(xx)) if self.flagOf(sib) == KreveldActiveBinaryTree.FLAG_FALSE { self.setFlag(sib, c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(self.parentOf(xx), c: KreveldActiveBinaryTree.FLAG_FALSE) self.rotateLeft(self.parentOf(xx)) sib = self.rightOf(self.parentOf(xx)) } if (self.flagOf(self.leftOf(sib)) == KreveldActiveBinaryTree.FLAG_TRUE && self.flagOf(self.rightOf(sib)) == KreveldActiveBinaryTree.FLAG_TRUE) { self.setFlag(sib, c: KreveldActiveBinaryTree.FLAG_FALSE) xx = self.parentOf(xx) } else { if (self.flagOf(self.rightOf(sib)) == KreveldActiveBinaryTree.FLAG_TRUE) { self.setFlag(self.leftOf(sib), c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(sib, c: KreveldActiveBinaryTree.FLAG_FALSE) self.rotateRight(sib) sib = self.rightOf(self.parentOf(xx)) } self.setFlag(sib, c: self.flagOf(self.parentOf(xx))) self.setFlag(self.parentOf(xx), c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(self.rightOf(sib), c: KreveldActiveBinaryTree.FLAG_TRUE) self.rotateLeft(self.parentOf(xx)) xx = self.root } } else { // symmetric var sib: VanKreveldStatusEntry? = self.leftOf(self.parentOf(xx)) if (self.flagOf(sib) == KreveldActiveBinaryTree.FLAG_FALSE) { self.setFlag(sib, c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(self.parentOf(xx), c: KreveldActiveBinaryTree.FLAG_FALSE) self.rotateRight(self.parentOf(xx)) sib = self.leftOf(self.parentOf(xx)) } if (self.flagOf(self.rightOf(sib)) == KreveldActiveBinaryTree.FLAG_TRUE && self.flagOf(self.leftOf(sib)) == KreveldActiveBinaryTree.FLAG_TRUE) { self.setFlag(sib, c: KreveldActiveBinaryTree.FLAG_FALSE) xx = self.parentOf(xx) } else { if (self.flagOf(self.leftOf(sib)) == KreveldActiveBinaryTree.FLAG_TRUE) { self.setFlag(self.rightOf(sib), c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(sib, c: KreveldActiveBinaryTree.FLAG_FALSE) self.rotateLeft(sib) sib = self.leftOf(self.parentOf(xx)) } self.setFlag(sib, c: self.flagOf(self.parentOf(xx))) self.setFlag(self.parentOf(xx), c: KreveldActiveBinaryTree.FLAG_TRUE) self.setFlag(self.leftOf(sib), c: KreveldActiveBinaryTree.FLAG_TRUE) self.rotateRight(self.parentOf(xx)) xx = self.root } } } self.setFlag(xx, c: KreveldActiveBinaryTree.FLAG_TRUE) } // check the visibility of this cell to the observer public func isVisible(pt: VanKreveldCell) -> Bool { var isVisible: Bool = false let key: Double = sqrt(pow(Double(self.reference.x) - Double(pt.x), 2) + pow(Double(self.reference.y) - Double(pt.y), 2)) var x: VanKreveldStatusEntry? = self.root if (x === nil) { return isVisible } var maxSlope: Double = -Double.infinity // parent var parent: VanKreveldStatusEntry? = x while (x !== nil) { if (key < x!.key) { parent = x x = x!.left } else { parent = x x = x!.right maxSlope = max(maxSlope, self.maxSlopeOf(parent!.left)) } } if maxSlope <= parent!.slope { isVisible = true } return isVisible } }
mit
9334908d381d90a43a70dbfb316ddf28
38.635468
162
0.490989
4.22584
false
false
false
false
shlyren/ONE-Swift
ONE_Swift/Classes/Movie-电影/Model/JENMovieItem.swift
1
1667
// // JENMovieItem.swift // ONE_Swift // // Created by 任玉祥 on 16/5/11. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit // MARK: - 电影列表模型 class JENMovieListItem: NSObject { /// id var detail_id: String? /// 标题 var title: String? /// 评分 var score: String? /// 图片url var cover: String? // var releasetime: String? // var scoretime: String? // var servertime: Int = 0 // var revisedscore: String? // var verse: String? // var verse_en: String? } // MARK: - 详情模型 class JENMovieDetailItem: JENMovieListItem { var detailcover: String? var keywords: String? var movie_id: String? var info: String? var charge_edt: String? var praisenum = 0 var sort: String? var maketime: String? var photo = [String]() var sharenum = 0 var commentnum = 0 var servertime = 0 // var indexcover: String? // var video: String? // var review: String? // var officialstory: String? // var web_url: String? // var releasetime: String? // var scoretime: String? // var last_update_date: String? // var read_num: String? // var push_id: String? } class JENMovieStroyResult: NSObject { var count = 0 var data = [JENMovieStoryItem]() } class JENMovieStoryItem: NSObject { /// id var story_id: String? var movie_id: String? var title: String? var content: String? var user_id: String? var sort: String? var praisenum = 0 var input_date: String? var story_type: String? var user = JENAuthorItem() }
mit
0a6beb443c3c13c31a90c17b45aaa486
17.848837
47
0.595679
3.340206
false
false
false
false
kstaring/swift
test/DebugInfo/protocolarg.swift
7
1104
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s func markUsed<T>(_ t: T) {} func use<T>(_ t: inout T) {} public protocol IGiveOutInts { func callMe() -> Int64 } // CHECK: define {{.*}}@_TF11protocolarg16printSomeNumbersFPS_12IGiveOutInts_T_ // CHECK: @llvm.dbg.declare(metadata %P11protocolarg12IGiveOutInts_* % // CHECK-SAME: metadata ![[VAR:.*]], metadata ![[EMPTY:.*]]) // CHECK: @llvm.dbg.declare(metadata %P11protocolarg12IGiveOutInts_** % // CHECK-SAME: metadata ![[ARG:.*]], metadata ![[DEREF:.*]]) // CHECK: ![[EMPTY]] = !DIExpression() public func printSomeNumbers(_ gen: IGiveOutInts) { var gen = gen // CHECK: ![[VAR]] = !DILocalVariable(name: "gen", {{.*}} line: [[@LINE-1]] // FIXME: Should be DW_TAG_interface_type // CHECK: ![[PT:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "IGiveOutInts" // CHECK: ![[ARG]] = !DILocalVariable(name: "gen", arg: 1, // CHECK-SAME: line: [[@LINE-6]], type: ![[PT]] // CHECK: ![[DEREF]] = !DIExpression(DW_OP_deref) markUsed(gen.callMe()) use(&gen) }
apache-2.0
56a847a28be5da75923eb59171dd7dfc
37.068966
90
0.600543
3.2
false
false
false
false
Johennes/firefox-ios
Client/Frontend/Widgets/AlternateSimpleHighlightCell.swift
1
9020
/* 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 import Storage struct AlternateSimpleHighlightCellUX { static let LabelColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : UIColor(rgb: 0x353535) static let BorderWidth: CGFloat = 0.5 static let CellSideOffset = 20 static let TitleLabelOffset = 2 static let CellTopBottomOffset = 12 static let SiteImageViewSize: CGSize = CGSize(width: 99, height: 76) static let StatusIconSize = 12 static let DescriptionLabelColor = UIColor(colorString: "919191") static let TimestampColor = UIColor(colorString: "D4D4D4") static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25) static let CornerRadius: CGFloat = 3 static let BorderColor = UIColor(white: 0, alpha: 0.1) } class AlternateSimpleHighlightCell: UITableViewCell { private lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFontMediumBoldActivityStream titleLabel.textColor = AlternateSimpleHighlightCellUX.LabelColor titleLabel.textAlignment = .Left titleLabel.numberOfLines = 3 return titleLabel }() private lazy var descriptionLabel: UILabel = { let descriptionLabel = UILabel() descriptionLabel.font = DynamicFontHelper.defaultHelper.DeviceFontDescriptionActivityStream descriptionLabel.textColor = AlternateSimpleHighlightCellUX.DescriptionLabelColor descriptionLabel.textAlignment = .Left descriptionLabel.numberOfLines = 1 return descriptionLabel }() private lazy var domainLabel: UILabel = { let descriptionLabel = UILabel() descriptionLabel.font = DynamicFontHelper.defaultHelper.DeviceFontDescriptionActivityStream descriptionLabel.textColor = AlternateSimpleHighlightCellUX.DescriptionLabelColor descriptionLabel.textAlignment = .Left descriptionLabel.numberOfLines = 1 return descriptionLabel }() private lazy var timeStamp: UILabel = { let timeStamp = UILabel() timeStamp.font = DynamicFontHelper.defaultHelper.DeviceFontSmallActivityStream timeStamp.textColor = AlternateSimpleHighlightCellUX.TimestampColor timeStamp.textAlignment = .Right return timeStamp }() lazy var siteImageView: UIImageView = { let siteImageView = UIImageView() siteImageView.contentMode = UIViewContentMode.ScaleAspectFit siteImageView.clipsToBounds = true siteImageView.contentMode = UIViewContentMode.Center siteImageView.layer.cornerRadius = AlternateSimpleHighlightCellUX.CornerRadius siteImageView.layer.borderColor = AlternateSimpleHighlightCellUX.BorderColor.CGColor siteImageView.layer.borderWidth = AlternateSimpleHighlightCellUX.BorderWidth siteImageView.layer.masksToBounds = true return siteImageView }() private lazy var statusIcon: UIImageView = { let statusIcon = UIImageView() statusIcon.contentMode = UIViewContentMode.ScaleAspectFit statusIcon.clipsToBounds = true statusIcon.layer.cornerRadius = AlternateSimpleHighlightCellUX.CornerRadius return statusIcon }() private lazy var selectedOverlay: UIView = { let selectedOverlay = UIView() selectedOverlay.backgroundColor = AlternateSimpleHighlightCellUX.SelectedOverlayColor selectedOverlay.hidden = true return selectedOverlay }() override var selected: Bool { didSet { self.selectedOverlay.hidden = !selected } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layer.shouldRasterize = true layer.rasterizationScale = UIScreen.mainScreen().scale isAccessibilityElement = true contentView.addSubview(siteImageView) contentView.addSubview(descriptionLabel) contentView.addSubview(selectedOverlay) contentView.addSubview(titleLabel) contentView.addSubview(timeStamp) contentView.addSubview(statusIcon) contentView.addSubview(domainLabel) siteImageView.snp_makeConstraints { make in make.top.equalTo(contentView).offset(AlternateSimpleHighlightCellUX.CellTopBottomOffset) make.bottom.lessThanOrEqualTo(contentView).offset(-AlternateSimpleHighlightCellUX.CellTopBottomOffset) make.leading.equalTo(contentView).offset(AlternateSimpleHighlightCellUX.CellSideOffset) make.size.equalTo(AlternateSimpleHighlightCellUX.SiteImageViewSize) } selectedOverlay.snp_makeConstraints { make in make.edges.equalTo(contentView) } domainLabel.snp_makeConstraints { make in make.leading.equalTo(siteImageView.snp_trailing).offset(AlternateSimpleHighlightCellUX.CellTopBottomOffset) make.top.equalTo(siteImageView).offset(-2) make.bottom.equalTo(titleLabel.snp_top).offset(-4) } titleLabel.snp_makeConstraints { make in make.leading.equalTo(siteImageView.snp_trailing).offset(AlternateSimpleHighlightCellUX.CellTopBottomOffset) make.trailing.equalTo(contentView).inset(AlternateSimpleHighlightCellUX.CellSideOffset) } descriptionLabel.snp_makeConstraints { make in make.leading.equalTo(statusIcon.snp_trailing).offset(AlternateSimpleHighlightCellUX.TitleLabelOffset) make.bottom.equalTo(statusIcon) } timeStamp.snp_makeConstraints { make in make.trailing.equalTo(contentView).inset(AlternateSimpleHighlightCellUX.CellSideOffset) make.bottom.equalTo(descriptionLabel) } statusIcon.snp_makeConstraints { make in make.size.equalTo(SimpleHighlightCellUX.StatusIconSize) make.leading.equalTo(titleLabel) make.bottom.equalTo(siteImageView).priorityLow() make.top.greaterThanOrEqualTo(titleLabel.snp_bottom).offset(6).priorityHigh() make.bottom.lessThanOrEqualTo(contentView).offset(-AlternateSimpleHighlightCellUX.CellTopBottomOffset).priorityHigh() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setImageWithURL(url: NSURL) { siteImageView.sd_setImageWithURL(url) { (img, err, type, url) -> Void in guard let img = img else { return } // Resize an Image to a specfic size to make sure that it doesnt appear bigger than it needs to (32px) inside a larger frame (48px). self.siteImageView.image = img.createScaled(CGSize(width: 32, height: 32)) self.siteImageView.image?.getColors(CGSizeMake(25, 25)) { colors in self.siteImageView.backgroundColor = colors.backgroundColor ?? UIColor.lightGrayColor() } } } override func prepareForReuse() { super.prepareForReuse() self.siteImageView.image = nil self.timeStamp.text = nil } func configureWithSite(site: Site) { if let icon = site.icon, let url = NSURL(string:icon.url) { self.setImageWithURL(url) } else { let url = site.url.asURL! self.siteImageView.image = FaviconFetcher.getDefaultFavicon(url) self.siteImageView.backgroundColor = FaviconFetcher.getDefaultColor(url) } self.domainLabel.text = site.tileURL.extractDomainName() self.titleLabel.text = site.title.characters.count <= 1 ? site.url : site.title if let bookmarked = site.bookmarked where bookmarked { self.descriptionLabel.text = "Bookmarked" self.statusIcon.image = UIImage(named: "context_bookmark") } else { self.descriptionLabel.text = "Visited" self.statusIcon.image = UIImage(named: "context_viewed") } if let date = site.latestVisit?.date { self.timeStamp.text = NSDate.fromMicrosecondTimestamp(date).toRelativeTimeString() } } } // Save background color on UITableViewCell "select" because it disappears in the default behavior extension AlternateSimpleHighlightCell { override func setHighlighted(highlighted: Bool, animated: Bool) { let color = self.siteImageView.backgroundColor super.setHighlighted(highlighted, animated: animated) self.siteImageView.backgroundColor = color } override func setSelected(selected: Bool, animated: Bool) { let color = self.siteImageView.backgroundColor super.setSelected(selected, animated: animated) self.siteImageView.backgroundColor = color } }
mpl-2.0
ab110cc21750161b8e1a1bd3c1e1b021
41.54717
144
0.702772
5.163137
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/NUX/LoginProloguePageViewController.swift
2
4635
import UIKit class LoginProloguePageViewController: UIPageViewController { var pages: [UIViewController] = [] fileprivate var pageControl: UIPageControl? fileprivate var bgAnimation: UIViewPropertyAnimator? fileprivate struct Constants { static let pagerPadding: CGFloat = 9.0 static let pagerHeight: CGFloat = 0.13 } override func viewDidLoad() { super.viewDidLoad() dataSource = self delegate = self pages.append(LoginProloguePromoViewController(as: .post)) pages.append(LoginProloguePromoViewController(as: .stats)) pages.append(LoginProloguePromoViewController(as: .reader)) pages.append(LoginProloguePromoViewController(as: .notifications)) pages.append(LoginProloguePromoViewController(as: .jetpack)) setViewControllers([pages[0]], direction: .forward, animated: false) view.backgroundColor = backgroundColor(for: 0) addPageControl() } func addPageControl() { let newControl = UIPageControl() newControl.translatesAutoresizingMaskIntoConstraints = false view.addSubview(newControl) newControl.topAnchor.constraint(equalTo: view.topAnchor, constant: Constants.pagerPadding).isActive = true newControl.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true newControl.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true newControl.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: Constants.pagerHeight).isActive = true newControl.numberOfPages = pages.count newControl.addTarget(self, action: #selector(handlePageControlValueChanged(sender:)), for: UIControlEvents.valueChanged) pageControl = newControl } func handlePageControlValueChanged(sender: UIPageControl) { guard let currentPage = viewControllers?.first, let currentIndex = pages.index(of: currentPage) else { return } let direction: UIPageViewControllerNavigationDirection = sender.currentPage > currentIndex ? .forward : .reverse setViewControllers([pages[sender.currentPage]], direction: direction, animated: true) WPAppAnalytics.track(.loginProloguePaged) } fileprivate func animateBackground(for index: Int, duration: TimeInterval = 0.5) { bgAnimation?.stopAnimation(true) bgAnimation = UIViewPropertyAnimator(duration: 0.5, curve: .easeOut) { [weak self] in self?.view.backgroundColor = self?.backgroundColor(for: index) } bgAnimation?.startAnimation() } fileprivate func backgroundColor(for index: Int) -> UIColor { switch index % 2 { case 0: return WPStyleGuide.lightBlue() case 1: fallthrough default: return WPStyleGuide.wordPressBlue() } } } extension LoginProloguePageViewController: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = pages.index(of: viewController) else { return nil } if index > 0 { return pages[index - 1] } return nil } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = pages.index(of: viewController) else { return nil } if index < pages.count - 1 { return pages[index + 1] } return nil } } extension LoginProloguePageViewController: UIPageViewControllerDelegate { func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { let toVC = previousViewControllers[0] guard let index = pages.index(of: toVC) else { return } if !completed { pageControl?.currentPage = index animateBackground(for: index, duration: 0.2) } else { WPAppAnalytics.track(.loginProloguePaged) } } func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { let toVC = pendingViewControllers[0] guard let index = pages.index(of: toVC) else { return } animateBackground(for: index) pageControl?.currentPage = index } }
gpl-2.0
30b125d89d44f99d7f2460b9afc87acd
36.991803
190
0.681122
5.485207
false
false
false
false
natecook1000/WWDC
WWDC/SlidesDownloader.swift
1
1661
// // SlidesDownloader.swift // WWDC // // Created by Guilherme Rambo on 10/3/15. // Copyright © 2015 Guilherme Rambo. All rights reserved. // import Cocoa import Alamofire class SlidesDownloader { typealias ProgressHandler = (downloaded: Double, total: Double) -> Void typealias CompletionHandler = (success: Bool, data: NSData?) -> Void var session: Session init(session: Session) { self.session = session } func downloadSlides(completionHandler: CompletionHandler, progressHandler: ProgressHandler?) { guard session.slidesURL != "" else { return completionHandler(success: false, data: nil) } guard let slidesURL = NSURL(string: session.slidesURL) else { return completionHandler(success: false, data: nil) } Alamofire.download(Method.GET, slidesURL.absoluteString) { tempURL, response in if let data = NSData(contentsOfURL: tempURL) { mainQ { WWDCDatabase.sharedDatabase.doChanges { self.session.slidesPDFData = data } completionHandler(success: true, data: data) } } else { completionHandler(success: false, data: nil) } do { try NSFileManager.defaultManager().removeItemAtURL(tempURL) } catch { print("Error removing temporary PDF file") } return tempURL }.progress { _, totalBytesRead, totalBytesExpected in mainQ { progressHandler?(downloaded: Double(totalBytesRead), total: Double(totalBytesExpected)) } } } }
bsd-2-clause
b66503e9738a0d6c1a7772d71d8c8501
32.897959
123
0.612048
5.139319
false
false
false
false
optimizely/swift-sdk
Sources/Customization/DefaultLogger.swift
1
1884
// // Copyright 2019, 2021, Optimizely, Inc. and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import os.log open class DefaultLogger: OPTLogger { private static var _logLevel: OptimizelyLogLevel? public static var logLevel: OptimizelyLogLevel { get { return _logLevel ?? .info } set (newLevel) { if _logLevel == nil { _logLevel = newLevel } } } required public init() {} open func log(level: OptimizelyLogLevel, message: String) { if level > DefaultLogger.logLevel { return } clog(level: level, message: message) } func clog(level: OptimizelyLogLevel, message: String) { var osLogType: OSLogType switch level { case .error: osLogType = .error case .info: osLogType = .info case .debug: osLogType = .debug default: osLogType = .default } os_log("[%{public}@] %{public}@", log: .optimizely, type: osLogType, level.name, message) } // test support static func setLogLevel(_ level: OptimizelyLogLevel) { _logLevel = level } } extension OSLog { static let optimizely = OSLog(subsystem: "com.optimizely.swift-sdk", category: "OPTIMIZELY") }
apache-2.0
55180a5528526e5836361ec42e1af015
27.984615
97
0.620488
4.453901
false
false
false
false
anthrgrnwrld/shootSpeed
Renda/ViewController.swift
1
28812
// // ViewController.swift // Renda // // Created by Masaki Horimoto on 2015/07/30. // Copyright (c) 2015年 Masaki Horimoto. All rights reserved. // import UIKit import GameKit import AudioToolbox import Social class ViewController: UIViewController, GKGameCenterControllerDelegate, GADBannerViewDelegate,GADInterstitialDelegate { @IBOutlet var counterDigit: [UIImageView]! @IBOutlet var decimalPlace: [UIImageView]! @IBOutlet weak var positionBeeMostLeft: UIView! @IBOutlet weak var positionBeeMostRight: UIView! @IBOutlet weak var imageBee: UIImageView! @IBOutlet weak var buttonA: UIButton! @IBOutlet weak var buttonB: UIButton! @IBOutlet weak var displayView: UIView! @IBOutlet weak var displayFrameView: UIView! @IBOutlet weak var buttanStart: UIButton! @IBOutlet weak var buttonTweet: UIButton! @IBOutlet weak var buttonGameCenter: UIButton! @IBOutlet weak var buttonFacebook: UIButton! let YOUR_BARNER_ID = "ca-app-pub-4555831884532149/4862920516" // Enter Ad's ID here let YOUR_INTERSTITIAL_ID = "ca-app-pub-4555831884532149/5150752517" // Enter Ad's ID here let TEST_DEVICE_ID = "61b0154xxxxxxxxxxxxxxxxxxxxxxxe0" // Enter Test ID here let AdMobTest:Bool = false let SimulatorTest:Bool = false var _interstitial: GADInterstitial? var countPushing = 0 var countupTimer = 0 var timer = Timer() let ud = UserDefaults.standard var timerState = false //timerStateがfalseの時にはTimerをスタート。trueの時には無視する。 var startState = false //startStateがtrueの時にはゲーム開始できる var highScore = 0 let udKey = "HIGHSCORE" let leaderboardid = "shootspeed.highscore" var kosuri:KosuriGestureRecognizer? = nil //コスリクラスのインスタンス let buttonAImage :UIImage? = UIImage(named:"buttonA.png") let buttonBImage :UIImage? = UIImage(named:"buttonB.png") let buttonStartImage :UIImage? = UIImage(named:"buttonStart.png") let buttonAImageSelected :UIImage? = UIImage(named:"buttonA_selected.png") let buttonBImageSelected :UIImage? = UIImage(named:"buttonB_selected.png") let buttonStartImageSelected :UIImage? = UIImage(named:"buttonStart_selected.png") var capturedImage: UIImage? var count = 0 var highScoreFlag = false override func viewDidLoad() { super.viewDidLoad() firstDisplayLoad() let bannerView:GADBannerView = getAdBannerView() self.view.addSubview(bannerView) self.kosuri = KosuriGestureRecognizer(_targetViewA: self.buttonA, _targetViewB: self.buttonB, didPush: { self.pressButtonFunc() }) capturedImage = GetImage() as UIImage // キャプチャ画像を取得. _interstitial = createAndLoadInterstitial() } /** スクリーンキャプチャ用関数 :returns: UIImage */ func GetImage() -> UIImage { // キャプチャする範囲を取得. let rect = self.view.bounds // ビットマップ画像のcontextを作成. UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) let context: CGContext = UIGraphicsGetCurrentContext()! // 対象のview内の描画をcontextに複写する. self.view.layer.render(in: context) // 現在のcontextのビットマップをUIImageとして取得. let capturedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()! // contextを閉じる. UIGraphicsEndImageContext() return capturedImage } /** 初期表示用関数 */ func firstDisplayLoad() { highScore = ud.integer(forKey: udKey) //保存済みのハイスコアを取得 print("highScore is \(highScore)") let tmpNum = counterDigit != nil ? counterDigit.count : 0 //スコアを表示しているViewの枠線を描写 displayView.layer.borderWidth = 1.0 displayView.layer.borderColor = UIColor.gray.cgColor let highScoreAfterEdit = editCount(highScore, digitNum: tmpNum) updateCounter(highScoreAfterEdit) //カウンタを初期表示にアップデート updateTimerLabel(0) //タイマーの初期表示をアップデート buttonDisplay() //ボタン画像表示 adjustImageBee() //デバイス依存のimageBee調整処理 } /** ボタン画像表示用関数 */ func buttonDisplay() { buttonA.setImage(buttonAImage!, for: UIControlState()) buttonA.setImage(buttonAImageSelected!, for: .highlighted) buttonB.setImage(buttonBImage!, for: UIControlState()) buttonB.setImage(buttonBImageSelected!, for: .highlighted) buttanStart.setImage(buttonStartImage!, for: UIControlState()) buttanStart.setImage(buttonStartImageSelected!, for: .highlighted) buttonTweet.imageView?.contentMode = UIViewContentMode.scaleAspectFit buttonGameCenter.imageView?.contentMode = UIViewContentMode.scaleAspectFit buttonFacebook.imageView?.contentMode = UIViewContentMode.scaleAspectFit } /** AdMob表示用関数 :returns: GADBannerView */ fileprivate func getAdBannerView() -> GADBannerView { var bannerView: GADBannerView = GADBannerView() let myBoundSize = UIScreen.main.bounds.size // Windowの表示領域を取得する。(広告の表示サイズのために使用する) if myBoundSize.width > 320 {bannerView = GADBannerView(adSize:kGADAdSizeFullBanner)} else {bannerView = GADBannerView(adSize:kGADAdSizeBanner)} bannerView.frame.origin = CGPoint(x: 0, y: 20) bannerView.frame.size = CGSize(width: self.view.frame.width, height: bannerView.frame.height) bannerView.adUnitID = "\(YOUR_BARNER_ID)" bannerView.delegate = self bannerView.rootViewController = self let request:GADRequest = GADRequest() if AdMobTest { if SimulatorTest { request.testDevices = [kGADSimulatorID] } else { request.testDevices = [TEST_DEVICE_ID] } } bannerView.load(request) return bannerView } func adViewDidReceiveAd(_ adView: GADBannerView){ print("adViewDidReceiveAd:\(adView)") } func adView(_ adView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError){ print("error:\(error)") } func adViewWillPresentScreen(_ adView: GADBannerView){ print("adViewWillPresentScreen") } func adViewWillDismissScreen(_ adView: GADBannerView){ print("adViewWillDismissScreen") } func adViewDidDismissScreen(_ adView: GADBannerView){ print("adViewDidDismissScreen") } func adViewWillLeaveApplication(_ adView: GADBannerView){ print("adViewWillLeaveApplication") } override func viewDidLayoutSubviews() { adjustImageBee() } /** imageBeeのサイズ調整処理。320x480の解像度のデバイスのみ */ func adjustImageBee() { let myBoundSize = UIScreen.main.bounds.size // Windowの表示領域を取得する。(imageBeeの表示サイズのために使用する) if myBoundSize.height <= 480 { imageBee.bounds.size.height = 28 //320*480の表示時のみimageBeeの大きさを変更する imageBee.bounds.size.width = 28 } } /** Startボタンを押した時に実行する関数 その1 */ @IBAction func buttonStart(_ sender: AnyObject) { if startState != false { //starStateがtrueの時には処理を終了 return } highScoreFlag = false //Viewの点滅を終了する。 finishBlinkAnimationWithView(imageBee) for (_, view) in self.counterDigit.enumerated() { finishBlinkAnimationWithView(view) } startState = true //startStateがtrueにし、Gameが開始できる状態にする countPushing = 0 countupTimer = 0 updateCounter([0,0,0,0]) //カウンタを初期表示にアップデート updateTimerLabel(10) //タイマーの初期表示をアップデート imageBee.center = positionBeeMostRight.center //imageBeeの表示位置を初期値に戻す } /** Startボタンを押した時に実行する関数 その2 (音声再生用) */ @IBAction func buttonStart2(_ sender: AnyObject) { AudioServicesPlaySystemSoundWithoutVibration("Tink.caf") } /** Aボタンを押した時に実行する関数 */ @IBAction func pressButtonA(_ sender: AnyObject) { pressButtonFunc() } /** Bボタンを押した時に実行する関数 */ @IBAction func pressButtonB(_ sender: AnyObject) { pressButtonFunc() } /** Aボタン及びBボタンを押した時に実行する関数 */ func pressButtonFunc() { //println("\(__FUNCTION__) is called") //timerStateがfalseの時にはTimerをスタート。trueの時には無視する。 if timerState == false && startState { timerState = true timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.updateTimer), userInfo: nil, repeats: true) } if timerState && startState { countPushing += 1 //countPushingをインクリメント let tmpNum = counterDigit != nil ? counterDigit.count : 0 let countAfterEdit = editCount(countPushing, digitNum: tmpNum) //カウントを表示用にEdit updateCounter(countAfterEdit) //カウンタをアップデートする moveImageBeeWithCountPushing(countPushing) //imageBeeの表示位置をアップデートする } AudioServicesPlaySystemSoundWithoutVibration("Tink.caf") } /** バイブレーション無しでシステムサウンドを再生する。 http://iphonedevwiki.net/index.php/AudioServices 参照 :param: soundName:再生したいシステムサウンドのファイル名 */ func AudioServicesPlaySystemSoundWithoutVibration(_ soundName :String) { var soundIdRing:SystemSoundID = 0 let soundUrl = URL(fileURLWithPath: "/System/Library/Audio/UISounds/\(soundName)") AudioServicesCreateSystemSoundID(soundUrl as CFURL, &soundIdRing) AudioServicesPlaySystemSound(soundIdRing) } /** 表示用にカウント数を10進数の桁毎に数値を分割する。表示桁数を超えた場合にはゼロに戻す。 digiNum >= count となるようにして使用のこと。 :param: count:カウント数 :param: digitNum:変換する桁数 :returns: digitArray:変換結果を入れる配列 */ func editCount(_ count :Int, digitNum :Int) -> [Int] { var count = count var digitArray = [Int]() for index in 0 ... (digitNum) { let tmpDec = pow(10.0, Double(digitNum - index)) if index != 0 {digitArray.append(count / Int(tmpDec))} count = count % Int(tmpDec) } return digitArray } /** カウンタの表示LabelをUpdateする。 countArrayの要素数 = counterDigitの要素数となるよう使用のこと。 :param: countArray:配列に編集済みのカウント配列*要editCount */ func updateCounter(_ countArray :[Int]) { if counterDigit != nil && countArray.count == counterDigit.count { for index in 0 ... (countArray.count - 1) { counterDigit[index].tag = countArray[index] counterDigit[index].image = UIImage(named: "\(counterDigit[index].tag).png") } } else if counterDigit != nil && countArray.count != counterDigit.count { for index in 0 ... (countArray.count - 1) { counterDigit[index].tag = 0x0e counterDigit[index].image = UIImage(named: "\(counterDigit[index].tag).png") } print("Error") } else { //counterDigit == nil //Do nothing } undisplayZero(countArray) } /** カウンタの表示Labelで不要な0を非表示にする。 countArrayの要素数 = counterDigitの要素数となるよう使用のこと。 :param: countArray:配列に編集済みのカウント配列*要editCount */ func undisplayZero(_ countArray :[Int]) { for index in 0 ... (countArray.count - 1) {counterDigit[index].alpha = 1.0} if countArray[0] == 0 { counterDigit[0].alpha = 0 if countArray[1] == 0 { counterDigit[1].alpha = 0 if countArray[2] == 0 { counterDigit[2].alpha = 0 } } } } /** タイマー関数。1秒毎に呼び出される。 */ func updateTimer() { //println("\(__FUNCTION__) is called") countupTimer += 1 //countupTimerをインクリメント let countdownTimer = editTimerCount(countupTimer) //カウントアップ表記をカウントダウン表記へ変換 updateTimerLabel(countdownTimer) //タイマー表示ラベルをアップデート if countdownTimer <= 0 {timeupFunc()} //ゲーム開始より10秒経過後、ゲーム完了処理を実行 print("\(#function) is called! \(countupTimer)") } /** ゲーム完了時に実行する関数。 */ func timeupFunc() { highScoreFlag = countPushing > highScore ? true : false highScore = countPushing > highScore ? countPushing : highScore timerState = false startState = false timer.invalidate() print("highScore is \(highScore)") ud.set(highScore, forKey: udKey) //ハイスコアをNSUserDefaultsのインスタンスに保存 ud.synchronize() //保存する情報の反映 GKScoreUtil.reportScores(highScore, leaderboardid: leaderboardid) //GameCenter Score Transration //ハイスコア更新の場合にはimageBeeとカウンタ表示を点滅させる & サウンドを再生する & スクリーンキャプチャ if highScoreFlag { capturedImage = GetImage() as UIImage // キャプチャ画像を取得. AudioServicesPlaySystemSoundWithoutVibration("alarm.caf") blinkAnimationWithView(imageBee) for (_, view) in self.counterDigit.enumerated() { blinkAnimationWithView(view) } } count += 1 if count > 2 { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { self.presentInterstitial() } } } func interstitialDidDismissScreen(_ ad: GADInterstitial!) { //ハイスコア更新の場合にはimageBeeとカウンタ表示を点滅させる if highScoreFlag { finishBlinkAnimationWithView(imageBee) firstDisplayLoad() blinkAnimationWithView(imageBee) for (_, view) in self.counterDigit.enumerated() { blinkAnimationWithView(view) } } } /** 指定されたViewを1秒間隔で点滅させる :param: view:点滅させるView */ func blinkAnimationWithView(_ view :UIView) { UIView.animate(withDuration: 1.0, delay: 0.0, options: UIViewAnimationOptions.repeat, animations: { () -> Void in view.alpha = 0 }, completion: nil) } /** 指定されたViewの点滅アニメーションを終了する :param: view:点滅を終了するView */ func finishBlinkAnimationWithView(_ view :UIView) { UIView.setAnimationBeginsFromCurrentState(true) UIView.animate(withDuration: 0.001, animations: { view.alpha = 1.0 }) // //こっちの方法でもOK // view.layer.removeAllAnimations() // view.alpha = 1.0 } /** カウントアップタイマーを1カウントダウン表記(Start 10)に変更する。 timerCount > 10 の場合には0をReturnする :param: timerCount:カウントアップタイマ値 :returns: digitArray:カウントダウンタイマ値(Start 10) */ func editTimerCount(_ timerCount: Int) -> Int { var timerCountAfterEdit: Int? if 10 >= timerCount {timerCountAfterEdit = 10 - timerCount} else {timerCountAfterEdit = 0} return timerCountAfterEdit! } /** タイマーの表示LabelをUpdateする。 :param: countArray:配列に編集済みのカウント配列*要editCount */ func updateTimerLabel(_ timerCount: Int) { if decimalPlace != nil { decimalPlace[0].tag = timerCount/10 decimalPlace[1].tag = timerCount%10 decimalPlace[0].image = UIImage(named: "\(decimalPlace[0].tag).png") decimalPlace[1].image = UIImage(named: "\(decimalPlace[1].tag).png") } decimalPlace[0].alpha = 1.0 if timerCount < 10 {decimalPlace[0].alpha = 0} } /** GameCenterボタンを押した時に実行する関数 */ @IBAction func pressGameCenter(_ sender: AnyObject) { AudioServicesPlaySystemSoundWithoutVibration("Tink.caf") showLeaderboardScore() } /** GKScoreにてスコアが送信されたデータスコアをLeaderboardで確認する */ func showLeaderboardScore() { if timerState { //timerStateがtrueの時(=ゲーム実行中)は処理を終了 return } let localPlayer = GKLocalPlayer() localPlayer.loadDefaultLeaderboardIdentifier { (leaderboardIdentifier : String?, error : Error?) -> Void in if error != nil { print(error!.localizedDescription) let iOSVersion: NSString! = UIDevice.current.systemVersion as NSString print("iOSVersion is \(iOSVersion)") //Verによってアラート動作を変える // if iOSVersion.floatValue < 8.0 { self.showAlertIOS7() } // else { self.showAlertIOS8() } self.showAlert() } else { let gameCenterController:GKGameCenterViewController = GKGameCenterViewController() gameCenterController.gameCenterDelegate = self //このViewControllerにはGameCenterControllerDelegateが実装されている必要があります gameCenterController.viewState = GKGameCenterViewControllerState.leaderboards gameCenterController.leaderboardIdentifier = self.leaderboardid //該当するLeaderboardのIDを指定します self.present(gameCenterController, animated: true, completion: nil); } } } let alertTitle:String = NSLocalizedString("alertTitle", comment: "アラートのタイトル") let alertMessage:String = NSLocalizedString("alertMessage", comment: "アラートのメッセージ") let actionTitle = "OK" func showAlert() { if #available(iOS 8.0, *) { // Style Alert let alert: UIAlertController = UIAlertController(title:alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert ) // Default 複数指定可 let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{ (action:UIAlertAction!) -> Void in print("OK") }) // AddAction 記述順に反映される alert.addAction(defaultAction) // Display present(alert, animated: true, completion: nil) } else { // Fallback on earlier versions let alert = UIAlertView() alert.title = alertTitle alert.message = alertMessage alert.addButton(withTitle: actionTitle) alert.show() } } @IBAction func pressHowToPlay(_ sender: AnyObject) { AudioServicesPlaySystemSoundWithoutVibration("Tink.caf") //Verによってアラート動作を変える // let iOSVersion: NSString! = UIDevice.currentDevice().systemVersion as NSString // print("iOSVersion is \(iOSVersion)") // if iOSVersion.floatValue < 8.0 { self.showHowToPlayIOS8() } // else { self.showHowToPlayIOS7() } self.showHowToPlay() } let howToPlayTitle:String = NSLocalizedString("howToPlayTitle", comment: "How to playのタイトル") let howToPlayMessage:String = NSLocalizedString("howToPlayMessage", comment: "How to playのメッセージ") let howToPlayActionTitle = "OK" func showHowToPlay() { if timerState { //timerStateがtrueの時(=ゲーム実行中)は処理を終了 return } // Style Alert if #available(iOS 8.0, *) { let alert: UIAlertController = UIAlertController(title:howToPlayTitle, message: howToPlayMessage, preferredStyle: UIAlertControllerStyle.alert ) // Default 複数指定可 let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{ (action:UIAlertAction!) -> Void in print("OK") }) // AddAction 記述順に反映される alert.addAction(defaultAction) // Display present(alert, animated: true, completion: nil) } else { // Fallback on earlier versions let alert = UIAlertView() alert.title = howToPlayTitle alert.message = howToPlayMessage alert.addButton(withTitle: howToPlayActionTitle) alert.show() } } /** Leaderboardを"DONE"押下後にCloseする */ func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) { print("\(#function) is called") //code to dismiss your gameCenterViewController gameCenterViewController.dismiss(animated: true, completion: nil); } /** imageBeeの表示位置を変更する。 :param: countPushing:Pushカウント数 */ func moveImageBeeWithCountPushing(_ countPushing: Int) { print("countPushing is \(countPushing)") let deltaXperOnePushing = (positionBeeMostRight.center.x - positionBeeMostLeft.center.x)/160 //1Push当たりのx移動量 if (countPushing - 1) % 160 == 0 {imageBee.center.x = positionBeeMostRight.center.x} //160回毎にpositionBeeMostLeftに位置を戻す *16連射目標のため imageBee.center.x -= deltaXperOnePushing //imageBeeの表示位置を移動する } @IBAction func pressTweet(_ sender: AnyObject) { AudioServicesPlaySystemSoundWithoutVibration("Tink.caf") if timerState { //timerStateがtrueの時(=ゲーム実行中)は処理を終了 return } let twitterPostView:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)! let tweetDescription0:String = NSLocalizedString("shareDescription0", comment: "ツイート内容0") let tweetDescription1:String = NSLocalizedString("shareDescription1", comment: "ツイート内容1") let tweetDescription2:String = NSLocalizedString("shareDescription2", comment: "ツイート内容2") let tweetDescription3:String = NSLocalizedString("shareDescription3", comment: "ツイート内容3") let tweetDescription4:String = NSLocalizedString("shareDescription4", comment: "ツイート内容4") let tweetURL:URL = URL(string: "https://itunes.apple.com/us/app/get-high-score!-how-many-times/id1029309778?l=ja&ls=1&mt=8")! //ハイスコアが160回超えた時とそれ以下で表示メッセージを変える。 if highScore > 160 { twitterPostView.setInitialText("\(tweetDescription0)\(highScore)\(tweetDescription3)\(abs(160 - highScore))\(tweetDescription4)") } else { twitterPostView.setInitialText("\(tweetDescription0)\(highScore)\(tweetDescription1)\(abs(160 - highScore))\(tweetDescription2)") } twitterPostView.add(tweetURL) twitterPostView.add(capturedImage) self.present(twitterPostView, animated: true, completion: nil) } @IBAction func pressFacebook(_ sender: AnyObject) { AudioServicesPlaySystemSoundWithoutVibration("Tink.caf") if timerState { //timerStateがtrueの時(=ゲーム実行中)は処理を終了 return } let facebookPostView:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)! let facebookDescription0:String = NSLocalizedString("shareDescription0", comment: "ツイート内容0") let facebookDescription1:String = NSLocalizedString("shareDescription1", comment: "ツイート内容1") let facebookDescription2:String = NSLocalizedString("shareDescription2", comment: "ツイート内容2") let facebookDescription3:String = NSLocalizedString("shareDescription3", comment: "ツイート内容3") let facebookDescription4:String = NSLocalizedString("shareDescription4", comment: "ツイート内容4") let facebookURL:URL = URL(string: "https://itunes.apple.com/us/app/shootspeed-get-high-score!/id1029309778?l=ja&ls=1&mt=8")! //ハイスコアが160回超えた時とそれ以下で表示メッセージを変える。 if highScore > 160 { facebookPostView.setInitialText("\(facebookDescription0)\(highScore)\(facebookDescription3)\(abs(160 - highScore))\(facebookDescription4)") } else { facebookPostView.setInitialText("\(facebookDescription0)\(highScore)\(facebookDescription1)\(abs(160 - highScore))\(facebookDescription2)") } facebookPostView.add(facebookURL) facebookPostView.add(capturedImage) self.present(facebookPostView, animated: true, completion: nil) } fileprivate func createAndLoadInterstitial()->GADInterstitial { let interstitial = GADInterstitial(adUnitID: YOUR_INTERSTITIAL_ID) interstitial?.delegate = self let request:GADRequest = GADRequest() if AdMobTest { if SimulatorTest { request.testDevices = [kGADSimulatorID] } else { request.testDevices = [TEST_DEVICE_ID] } } interstitial?.load(request) return interstitial! } fileprivate func presentInterstitial() { guard let interstitial = _interstitial else { print ("_interstitial is nil.") return } interstitial.present(fromRootViewController: self) } }
mit
55fefb840cff89c80504ffba7d273b0c
32.187661
151
0.60093
4.399387
false
false
false
false
L3-DANT/findme-app
findme/Assets/Font Awesome/Enum.swift
7
46359
// Enum.swift // // Copyright (c) 2014-2015 Thi Doan // // 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. /// An enumaration of FontAwesome icon names. public enum FontAwesome: String { case FiveHundredPixels = "\u{f26e}" case Adjust = "\u{f042}" case ADN = "\u{f170}" case AlignCenter = "\u{f037}" case AlignJustify = "\u{f039}" case AlignLeft = "\u{f036}" case AlignRight = "\u{f038}" case Amazon = "\u{f270}" case Ambulance = "\u{f0f9}" case Anchor = "\u{f13d}" case Android = "\u{f17b}" case Angellist = "\u{f209}" case AngleDoubleDown = "\u{f103}" case AngleDoubleLeft = "\u{f100}" case AngleDoubleRight = "\u{f101}" case AngleDoubleUp = "\u{f102}" case AngleDown = "\u{f107}" case AngleLeft = "\u{f104}" case AngleRight = "\u{f105}" case AngleUp = "\u{f106}" case Apple = "\u{f179}" case Archive = "\u{f187}" case AreaChart = "\u{f1fe}" case ArrowCircleDown = "\u{f0ab}" case ArrowCircleLeft = "\u{f0a8}" case ArrowCircleODown = "\u{f01a}" case ArrowCircleOLeft = "\u{f190}" case ArrowCircleORight = "\u{f18e}" case ArrowCircleOUp = "\u{f01b}" case ArrowCircleRight = "\u{f0a9}" case ArrowCircleUp = "\u{f0aa}" case ArrowDown = "\u{f063}" case ArrowLeft = "\u{f060}" case ArrowRight = "\u{f061}" case ArrowUp = "\u{f062}" case Arrows = "\u{f047}" case ArrowsAlt = "\u{f0b2}" case ArrowsH = "\u{f07e}" case ArrowsV = "\u{f07d}" case Asterisk = "\u{f069}" case At = "\u{f1fa}" case Automobile = "\u{f1b9}" case Backward = "\u{f04a}" case BalanceScale = "\u{f24e}" case Ban = "\u{f05e}" case Bank = "\u{f19c}" case BarChart = "\u{f080}" case BarChartO = "\u{f080}A" case Barcode = "\u{f02a}" case Bars = "\u{f0c9}" case Battery0 = "\u{f244}" case Battery1 = "\u{f243}" case Battery2 = "\u{f242}" case Battery3 = "\u{f241}" case Battery4 = "\u{f240}" case BatteryEmpty = "\u{f244}A" case BatteryFull = "\u{f240}A" case BatteryHalf = "\u{f242}A" case BatteryQuarter = "\u{f243}A" case BatteryThreeQuarters = "\u{f241}A" case Bed = "\u{f236}" case Beer = "\u{f0fc}" case Behance = "\u{f1b4}" case BehanceSquare = "\u{f1b5}" case Bell = "\u{f0f3}" case BellO = "\u{f0a2}" case BellSlash = "\u{f1f6}" case BellSlashO = "\u{f1f7}" case Bicycle = "\u{f206}" case Binoculars = "\u{f1e5}" case BirthdayCake = "\u{f1fd}" case Bitbucket = "\u{f171}" case BitbucketSquare = "\u{f172}" case Bitcoin = "\u{f15a}" case BlackTie = "\u{f27e}" case Bold = "\u{f032}" case Bolt = "\u{f0e7}" case Bomb = "\u{f1e2}" case Book = "\u{f02d}" case Bookmark = "\u{f02e}" case BookmarkO = "\u{f097}" case Briefcase = "\u{f0b1}" case BTC = "\u{f15a}A" case Bug = "\u{f188}" case Building = "\u{f1ad}" case BuildingO = "\u{f0f7}" case Bullhorn = "\u{f0a1}" case Bullseye = "\u{f140}" case Bus = "\u{f207}" case Buysellads = "\u{f20d}" case Cab = "\u{f1ba}" case Calculator = "\u{f1ec}" case Calendar = "\u{f073}" case CalendarCheckO = "\u{f274}" case CalendarMinusO = "\u{f272}" case CalendarO = "\u{f133}" case CalendarPlusO = "\u{f271}" case CalendarTimesO = "\u{f273}" case Camera = "\u{f030}" case CameraRetro = "\u{f083}" case Car = "\u{f1b9}A" case CaretDown = "\u{f0d7}" case CaretLeft = "\u{f0d9}" case CaretRight = "\u{f0da}" case CaretSquareODown = "\u{f150}" case CaretSquareOLeft = "\u{f191}" case CaretSquareORight = "\u{f152}" case CaretSquareOUp = "\u{f151}" case CaretUp = "\u{f0d8}" case CartArrowDown = "\u{f218}" case CartPlus = "\u{f217}" case CC = "\u{f20a}" case CCAmex = "\u{f1f3}" case CCDinersClub = "\u{f24c}" case CCDiscover = "\u{f1f2}" case CCJCB = "\u{f24b}" case CCMasterCard = "\u{f1f1}" case CCPaypal = "\u{f1f4}" case CCStripe = "\u{f1f5}" case CCVisa = "\u{f1f0}" case Certificate = "\u{f0a3}" case Chain = "\u{f0c1}" case ChainBroken = "\u{f127}" case Check = "\u{f00c}" case CheckCircle = "\u{f058}" case CheckCircleO = "\u{f05d}" case CheckSquare = "\u{f14a}" case CheckSquareO = "\u{f046}" case ChevronCircleDown = "\u{f13a}" case ChevronCircleLeft = "\u{f137}" case ChevronCircleRight = "\u{f138}" case ChevronCircleUp = "\u{f139}" case ChevronDown = "\u{f078}" case ChevronLeft = "\u{f053}" case ChevronRight = "\u{f054}" case ChevronUp = "\u{f077}" case Child = "\u{f1ae}" case Chrome = "\u{f268}" case Circle = "\u{f111}" case CircleO = "\u{f10c}" case CircleONotch = "\u{f1ce}" case CircleThin = "\u{f1db}" case Clipboard = "\u{f0ea}" case ClockO = "\u{f017}" case Clone = "\u{f24d}" case Close = "\u{f00d}" case Cloud = "\u{f0c2}" case CloudDownload = "\u{f0ed}" case CloudUpload = "\u{f0ee}" case CNY = "\u{f157}" case Code = "\u{f121}" case CodeFork = "\u{f126}" case Codepen = "\u{f1cb}" case Coffee = "\u{f0f4}" case Cog = "\u{f013}" case Cogs = "\u{f085}" case Columns = "\u{f0db}" case Comment = "\u{f075}" case CommentO = "\u{f0e5}" case Commenting = "\u{f27a}" case CommentingO = "\u{f27b}" case Comments = "\u{f086}" case CommentsO = "\u{f0e6}" case Compass = "\u{f14e}" case Compress = "\u{f066}" case Connectdevelop = "\u{f20e}" case Contao = "\u{f26d}" case Copy = "\u{f0c5}" case Copyright = "\u{f1f9}" case CreativeCommons = "\u{f25e}" case CreditCard = "\u{f09d}" case Crop = "\u{f125}" case Crosshairs = "\u{f05b}" case Css3 = "\u{f13c}" case Cube = "\u{f1b2}" case Cubes = "\u{f1b3}" case Cut = "\u{f0c4}" case Cutlery = "\u{f0f5}" case Dashboard = "\u{f0e4}" case Dashcube = "\u{f210}" case Database = "\u{f1c0}" case Dedent = "\u{f03b}" case Delicious = "\u{f1a5}" case Desktop = "\u{f108}" case Deviantart = "\u{f1bd}" case Diamond = "\u{f219}" case Digg = "\u{f1a6}" case Dollar = "\u{f155}" case DotCircleO = "\u{f192}" case Download = "\u{f019}" case Dribbble = "\u{f17d}" case Dropbox = "\u{f16b}" case Drupal = "\u{f1a9}" case Edit = "\u{f044}" case Eject = "\u{f052}" case EllipsisH = "\u{f141}" case EllipsisV = "\u{f142}" case Empire = "\u{f1d1}" case Envelope = "\u{f0e0}" case EnvelopeO = "\u{f003}" case EnvelopeSquare = "\u{f199}" case Eraser = "\u{f12d}" case EUR = "\u{f153}" case Euro = "\u{f153}A" case Exchange = "\u{f0ec}" case Exclamation = "\u{f12a}" case ExclamationCircle = "\u{f06a}" case ExclamationTriangle = "\u{f071}" case Expand = "\u{f065}" case ExpeditedSSL = "\u{f23e}" case ExternalLink = "\u{f08e}" case ExternalLinkSquare = "\u{f14c}" case Eye = "\u{f06e}" case EyeSlash = "\u{f070}" case Eyedropper = "\u{f1fb}" case Facebook = "\u{f09a}" case FacebookF = "\u{f09a}A" case FacebookOfficial = "\u{f230}" case FacebookSquare = "\u{f082}" case FastBackward = "\u{f049}" case FastForward = "\u{f050}" case Fax = "\u{f1ac}" case Feed = "\u{f09e}" case Female = "\u{f182}" case FighterJet = "\u{f0fb}" case File = "\u{f15b}" case FileArchiveO = "\u{f1c6}" case FileAudioO = "\u{f1c7}" case FileCodeO = "\u{f1c9}" case FileExcelO = "\u{f1c3}" case FileImageO = "\u{f1c5}" case FileMovieO = "\u{f1c8}" case FileO = "\u{f016}" case FilePdfO = "\u{f1c1}" case FilePhotoO = "\u{f1c5}A" case FilePictureO = "\u{f1c5}B" case FilePowerpointO = "\u{f1c4}" case FileSoundO = "\u{f1c7}A" case FileText = "\u{f15c}" case FileTextO = "\u{f0f6}" case FileVideoO = "\u{f1c8}A" case FileWordO = "\u{f1c2}" case FileZipO = "\u{f1c6}A" case FilesO = "\u{f0c5}A" case Film = "\u{f008}" case Filter = "\u{f0b0}" case Fire = "\u{f06d}" case FireExtinguisher = "\u{f134}" case Firefox = "\u{f269}" case Flag = "\u{f024}" case FlagCheckered = "\u{f11e}" case FlagO = "\u{f11d}" case Flash = "\u{f0e7}A" case Flask = "\u{f0c3}" case Flickr = "\u{f16e}" case FloppyO = "\u{f0c7}" case Folder = "\u{f07b}" case FolderO = "\u{f114}" case FolderOpen = "\u{f07c}" case FolderOpenO = "\u{f115}" case Font = "\u{f031}" case Fonticons = "\u{f280}" case Forumbee = "\u{f211}" case Forward = "\u{f04e}" case Foursquare = "\u{f180}" case FrownO = "\u{f119}" case FutbolO = "\u{f1e3}" case Gamepad = "\u{f11b}" case Gavel = "\u{f0e3}" case GBP = "\u{f154}" case Ge = "\u{f1d1}A" case Gear = "\u{f013}A" case Gears = "\u{f085}A" case Genderless = "\u{f22d}" case GetPocket = "\u{f265}" case GG = "\u{f260}" case GGCircle = "\u{f261}" case Gift = "\u{f06b}" case Git = "\u{f1d3}" case GitSquare = "\u{f1d2}" case Github = "\u{f09b}" case GithubAlt = "\u{f113}" case GithubSquare = "\u{f092}" case Gittip = "\u{f184}" case Glass = "\u{f000}" case Globe = "\u{f0ac}" case Google = "\u{f1a0}" case GooglePlus = "\u{f0d5}" case GooglePlusSquare = "\u{f0d4}" case GoogleWallet = "\u{f1ee}" case GraduationCap = "\u{f19d}" case Gratipay = "\u{f184}A" case Group = "\u{f0c0}" case HSquare = "\u{f0fd}" case HackerNews = "\u{f1d4}" case HandGrabO = "\u{f255}" case HandLizardO = "\u{f258}" case HandODown = "\u{f0a7}" case HandOLeft = "\u{f0a5}" case HandORight = "\u{f0a4}" case HandOUp = "\u{f0a6}" case HandPaperO = "\u{f256}" case HandPeaceO = "\u{f25b}" case HandPointerO = "\u{f25a}" case HandRockO = "\u{f255}A" case HandScissorsO = "\u{f257}" case HandSpockO = "\u{f259}" case HandStopO = "\u{f256}A" case HddO = "\u{f0a0}" case Header = "\u{f1dc}" case Headphones = "\u{f025}" case Heart = "\u{f004}" case HeartO = "\u{f08a}" case Heartbeat = "\u{f21e}" case History = "\u{f1da}" case Home = "\u{f015}" case HospitalO = "\u{f0f8}" case Hotel = "\u{f236}A" case Hourglass = "\u{f254}" case Hourglass1 = "\u{f251}" case Hourglass2 = "\u{f252}" case Hourglass3 = "\u{f253}" case HourglassEnd = "\u{f253}A" case HourglassHalf = "\u{f252}A" case HourglassO = "\u{f250}" case HourglassStart = "\u{f251}A" case Houzz = "\u{f27c}" case Html5 = "\u{f13b}" case ICursor = "\u{f246}" case ILS = "\u{f20b}" case Image = "\u{f03e}" case Inbox = "\u{f01c}" case Indent = "\u{f03c}" case Industry = "\u{f275}" case Info = "\u{f129}" case InfoCircle = "\u{f05a}" case INR = "\u{f156}" case Instagram = "\u{f16d}" case Institution = "\u{f19c}A" case InternetExplorer = "\u{f26b}" case Intersex = "\u{f224}" case Ioxhost = "\u{f208}" case Italic = "\u{f033}" case Joomla = "\u{f1aa}" case JPY = "\u{f157}A" case Jsfiddle = "\u{f1cc}" case Key = "\u{f084}" case KeyboardO = "\u{f11c}" case KRW = "\u{f159}" case Language = "\u{f1ab}" case Laptop = "\u{f109}" case LastFM = "\u{f202}" case LastFMSquare = "\u{f203}" case Leaf = "\u{f06c}" case Leanpub = "\u{f212}" case Legal = "\u{f0e3}A" case LemonO = "\u{f094}" case LevelDown = "\u{f149}" case LevelUp = "\u{f148}" case LifeBouy = "\u{f1cd}" case LifeBuoy = "\u{f1cd}A" case LifeRing = "\u{f1cd}B" case LifeSaver = "\u{f1cd}C" case LightbulbO = "\u{f0eb}" case LineChart = "\u{f201}" case Link = "\u{f0c1}A" case LinkedIn = "\u{f0e1}" case LinkedInSquare = "\u{f08c}" case Linux = "\u{f17c}" case List = "\u{f03a}" case ListAlt = "\u{f022}" case ListOL = "\u{f0cb}" case ListUL = "\u{f0ca}" case LocationArrow = "\u{f124}" case Lock = "\u{f023}" case LongArrowDown = "\u{f175}" case LongArrowLeft = "\u{f177}" case LongArrowRight = "\u{f178}" case LongArrowUp = "\u{f176}" case Magic = "\u{f0d0}" case Magnet = "\u{f076}" case MailForward = "\u{f064}" case MailReply = "\u{f112}" case MailReplyAll = "\u{f122}" case Male = "\u{f183}" case Map = "\u{f279}" case MapMarker = "\u{f041}" case MapO = "\u{f278}" case MapPin = "\u{f276}" case MapSigns = "\u{f277}" case Mars = "\u{f222}" case MarsDouble = "\u{f227}" case MarsStroke = "\u{f229}" case MarsStrokeH = "\u{f22b}" case MarsStrokeV = "\u{f22a}" case Maxcdn = "\u{f136}" case Meanpath = "\u{f20c}" case Medium = "\u{f23a}" case Medkit = "\u{f0fa}" case MehO = "\u{f11a}" case Mercury = "\u{f223}" case Microphone = "\u{f130}" case MicrophoneSlash = "\u{f131}" case Minus = "\u{f068}" case MinusCircle = "\u{f056}" case MinusSquare = "\u{f146}" case MinusSquareO = "\u{f147}" case Mobile = "\u{f10b}" case MobilePhone = "\u{f10b}A" case Money = "\u{f0d6}" case MoonO = "\u{f186}" case MortarBoard = "\u{f19d}A" case Motorcycle = "\u{f21c}" case MousePointer = "\u{f245}" case Music = "\u{f001}" case Navicon = "\u{f0c9}A" case Neuter = "\u{f22c}" case NewspaperO = "\u{f1ea}" case ObjectGroup = "\u{f247}" case ObjectUngroup = "\u{f248}" case Odnoklassniki = "\u{f263}" case OdnoklassnikiSquare = "\u{f264}" case OpenCart = "\u{f23d}" case OpenID = "\u{f19b}" case Opera = "\u{f26a}" case OptinMonster = "\u{f23c}" case Outdent = "\u{f03b}A" case Pagelines = "\u{f18c}" case PaintBrush = "\u{f1fc}" case PaperPlane = "\u{f1d8}" case PaperPlaneO = "\u{f1d9}" case Paperclip = "\u{f0c6}" case Paragraph = "\u{f1dd}" case Paste = "\u{f0ea}A" case Pause = "\u{f04c}" case Paw = "\u{f1b0}" case Paypal = "\u{f1ed}" case Pencil = "\u{f040}" case PencilSquare = "\u{f14b}" case PencilSquareO = "\u{f044}A" case Phone = "\u{f095}" case PhoneSquare = "\u{f098}" case Photo = "\u{f03e}A" case PictureO = "\u{f03e}B" case PieChart = "\u{f200}" case PiedPiper = "\u{f1a7}" case PiedPiperAlt = "\u{f1a8}" case Pinterest = "\u{f0d2}" case PinterestP = "\u{f231}" case PinterestSquare = "\u{f0d3}" case Plane = "\u{f072}" case Play = "\u{f04b}" case PlayCircle = "\u{f144}" case PlayCircleO = "\u{f01d}" case Plug = "\u{f1e6}" case Plus = "\u{f067}" case PlusCircle = "\u{f055}" case PlusSquare = "\u{f0fe}" case PlusSquareO = "\u{f196}" case PowerOff = "\u{f011}" case Print = "\u{f02f}" case PuzzlePiece = "\u{f12e}" case Qq = "\u{f1d6}" case Qrcode = "\u{f029}" case Question = "\u{f128}" case QuestionCircle = "\u{f059}" case QuoteLeft = "\u{f10d}" case QuoteRight = "\u{f10e}" case Ra = "\u{f1d0}" case Random = "\u{f074}" case Rebel = "\u{f1d0}A" case Recycle = "\u{f1b8}" case Reddit = "\u{f1a1}" case RedditSquare = "\u{f1a2}" case Refresh = "\u{f021}" case Registered = "\u{f25d}" case Remove = "\u{f00d}A" case Renren = "\u{f18b}" case Reorder = "\u{f0c9}B" case Repeat = "\u{f01e}" case Reply = "\u{f112}A" case ReplyAll = "\u{f122}A" case Retweet = "\u{f079}" case RMB = "\u{f157}B" case Road = "\u{f018}" case Rocket = "\u{f135}" case RotateLeft = "\u{f0e2}" case RotateRight = "\u{f01e}A" case Rouble = "\u{f158}" case RSS = "\u{f09e}A" case RSSSquare = "\u{f143}" case RUB = "\u{f158}A" case Ruble = "\u{f158}B" case Rupee = "\u{f156}A" case Safari = "\u{f267}" case Save = "\u{f0c7}A" case Scissors = "\u{f0c4}A" case Search = "\u{f002}" case SearchMinus = "\u{f010}" case SearchPlus = "\u{f00e}" case Sellsy = "\u{f213}" case Send = "\u{f1d8}A" case SendO = "\u{f1d9}A" case Server = "\u{f233}" case Share = "\u{f064}A" case ShareAlt = "\u{f1e0}" case ShareAltSquare = "\u{f1e1}" case ShareSquare = "\u{f14d}" case ShareSquareO = "\u{f045}" case Shekel = "\u{f20b}A" case Sheqel = "\u{f20b}B" case Shield = "\u{f132}" case Ship = "\u{f21a}" case Shirtsinbulk = "\u{f214}" case ShoppingCart = "\u{f07a}" case SignIn = "\u{f090}" case SignOut = "\u{f08b}" case Signal = "\u{f012}" case Simplybuilt = "\u{f215}" case Sitemap = "\u{f0e8}" case Skyatlas = "\u{f216}" case Skype = "\u{f17e}" case Slack = "\u{f198}" case Sliders = "\u{f1de}" case Slideshare = "\u{f1e7}" case SmileO = "\u{f118}" case SoccerBallO = "\u{f1e3}A" case Sort = "\u{f0dc}" case SortAlphaAsc = "\u{f15d}" case SortAlphaDesc = "\u{f15e}" case SortAmountAsc = "\u{f160}" case SortAmountDesc = "\u{f161}" case SortAsc = "\u{f0de}" case SortDesc = "\u{f0dd}" case SortDown = "\u{f0dd}A" case SortNumericAsc = "\u{f162}" case SortNumericDesc = "\u{f163}" case SortUp = "\u{f0de}A" case SoundCloud = "\u{f1be}" case SpaceShuttle = "\u{f197}" case Spinner = "\u{f110}" case Spoon = "\u{f1b1}" case Spotify = "\u{f1bc}" case Square = "\u{f0c8}" case SquareO = "\u{f096}" case StackExchange = "\u{f18d}" case StackOverflow = "\u{f16c}" case Star = "\u{f005}" case StarHalf = "\u{f089}" case StarHalfEmpty = "\u{f123}" case StarHalfFull = "\u{f123}A" case StarHalfO = "\u{f123}B" case StarO = "\u{f006}" case Steam = "\u{f1b6}" case SteamSquare = "\u{f1b7}" case StepBackward = "\u{f048}" case StepForward = "\u{f051}" case Stethoscope = "\u{f0f1}" case StickyNote = "\u{f249}" case StickyNoteO = "\u{f24a}" case Stop = "\u{f04d}" case StreetView = "\u{f21d}" case Strikethrough = "\u{f0cc}" case StumbleUpon = "\u{f1a4}" case StumbleUponCircle = "\u{f1a3}" case Subscript = "\u{f12c}" case Subway = "\u{f239}" case Suitcase = "\u{f0f2}" case SunO = "\u{f185}" case Superscript = "\u{f12b}" case Support = "\u{f1cd}D" case Table = "\u{f0ce}" case Tablet = "\u{f10a}" case Tachometer = "\u{f0e4}A" case Tag = "\u{f02b}" case Tags = "\u{f02c}" case Tasks = "\u{f0ae}" case Taxi = "\u{f1ba}A" case Television = "\u{f26c}" case TencentWeibo = "\u{f1d5}" case Terminal = "\u{f120}" case TextHeight = "\u{f034}" case TextWidth = "\u{f035}" case Th = "\u{f00a}" case ThLarge = "\u{f009}" case ThList = "\u{f00b}" case ThumbTack = "\u{f08d}" case ThumbsDown = "\u{f165}" case ThumbsODown = "\u{f088}" case ThumbsOUp = "\u{f087}" case ThumbsUp = "\u{f164}" case Ticket = "\u{f145}" case Times = "\u{f00d}B" case TimesCircle = "\u{f057}" case TimesCircleO = "\u{f05c}" case Tint = "\u{f043}" case ToggleDown = "\u{f150}A" case ToggleLeft = "\u{f191}A" case ToggleOff = "\u{f204}" case ToggleOn = "\u{f205}" case ToggleRight = "\u{f152}A" case ToggleUp = "\u{f151}A" case Trademark = "\u{f25c}" case Train = "\u{f238}" case Transgender = "\u{f224}A" case TransgenderAlt = "\u{f225}" case Trash = "\u{f1f8}" case TrashO = "\u{f014}" case Tree = "\u{f1bb}" case Trello = "\u{f181}" case TripAdvisor = "\u{f262}" case Trophy = "\u{f091}" case Truck = "\u{f0d1}" case TRY = "\u{f195}" case TTY = "\u{f1e4}" case Tumblr = "\u{f173}" case TumblrSquare = "\u{f174}" case TurkishLira = "\u{f195}A" case Tv = "\u{f26c}A" case Twitch = "\u{f1e8}" case Twitter = "\u{f099}" case TwitterSquare = "\u{f081}" case Umbrella = "\u{f0e9}" case Underline = "\u{f0cd}" case Undo = "\u{f0e2}A" case University = "\u{f19c}B" case Unlink = "\u{f127}A" case Unlock = "\u{f09c}" case UnlockAlt = "\u{f13e}" case Unsorted = "\u{f0dc}A" case Upload = "\u{f093}" case USD = "\u{f155}A" case User = "\u{f007}" case UserMd = "\u{f0f0}" case UserPlus = "\u{f234}" case UserSecret = "\u{f21b}" case UserTimes = "\u{f235}" case Users = "\u{f0c0}A" case Venus = "\u{f221}" case VenusDouble = "\u{f226}" case VenusMars = "\u{f228}" case Viacoin = "\u{f237}" case VideoCamera = "\u{f03d}" case Vimeo = "\u{f27d}" case VimeoSquare = "\u{f194}" case Vine = "\u{f1ca}" case Vk = "\u{f189}" case VolumeDown = "\u{f027}" case VolumeOff = "\u{f026}" case VolumeUp = "\u{f028}" case Warning = "\u{f071}A" case Wechat = "\u{f1d7}" case Weibo = "\u{f18a}" case Weixin = "\u{f1d7}A" case Whatsapp = "\u{f232}" case Wheelchair = "\u{f193}" case Wifi = "\u{f1eb}" case WikipediaW = "\u{f266}" case Windows = "\u{f17a}" case Won = "\u{f159}A" case Wordpress = "\u{f19a}" case Wrench = "\u{f0ad}" case Xing = "\u{f168}" case XingSquare = "\u{f169}" case YCombinator = "\u{f23b}" case YCombinatorSquare = "\u{f1d4}A" case Yahoo = "\u{f19e}" case YC = "\u{f23b}A" case YCSquare = "\u{f1d4}B" case Yelp = "\u{f1e9}" case Yen = "\u{f157}C" case YouTube = "\u{f167}" case YouTubePlay = "\u{f16a}" case YouTubeSquare = "\u{f166}" case RedditAlien = "\u{f281}" case Edge = "\u{f282}" case CreditCardAlt = "\u{f283}" case Codiepie = "\u{f284}" case Modx = "\u{f285}" case FortAwesome = "\u{f286}" case Usb = "\u{f287}" case ProductHunt = "\u{f288}" case Mixcloud = "\u{f289}" case Scribd = "\u{f28a}" case PauseCircle = "\u{f28b}" case PauseCircleO = "\u{f28c}" case StopCircle = "\u{f28d}" case StopCircleO = "\u{f28e}" case ShoppingBag = "\u{f290}" case ShoppingBasket = "\u{f291}" case Hashtag = "\u{f292}" case Bluetooth = "\u{f293}" case BluetoothB = "\u{f294}" case Percent = "\u{f295}" /// Get a FontAwesome string from the given CSS icon code. Icon code can be found here: http://fontawesome.io/icons/ /// /// - parameter code: The preferred icon name. /// - returns: FontAwesome icon. public static func fromCode(code: String) -> FontAwesome? { guard let raw = FontAwesomeIcons[code], icon = FontAwesome(rawValue: raw) else { return nil } return icon } } /// An array of FontAwesome icon codes. public let FontAwesomeIcons = [ "fa-500px" : "\u{f26e}", "fa-adjust" : "\u{f042}", "fa-adn" : "\u{f170}", "fa-align-center" : "\u{f037}", "fa-align-justify" : "\u{f039}", "fa-align-left" : "\u{f036}", "fa-align-right" : "\u{f038}", "fa-amazon" : "\u{f270}", "fa-ambulance" : "\u{f0f9}", "fa-anchor" : "\u{f13d}", "fa-android" : "\u{f17b}", "fa-angellist" : "\u{f209}", "fa-angle-double-down" : "\u{f103}", "fa-angle-double-left" : "\u{f100}", "fa-angle-double-right" : "\u{f101}", "fa-angle-double-up" : "\u{f102}", "fa-angle-down" : "\u{f107}", "fa-angle-left" : "\u{f104}", "fa-angle-right" : "\u{f105}", "fa-angle-up" : "\u{f106}", "fa-apple" : "\u{f179}", "fa-archive" : "\u{f187}", "fa-area-chart" : "\u{f1fe}", "fa-arrow-circle-down" : "\u{f0ab}", "fa-arrow-circle-left" : "\u{f0a8}", "fa-arrow-circle-o-down" : "\u{f01a}", "fa-arrow-circle-o-left" : "\u{f190}", "fa-arrow-circle-o-right" : "\u{f18e}", "fa-arrow-circle-o-up" : "\u{f01b}", "fa-arrow-circle-right" : "\u{f0a9}", "fa-arrow-circle-up" : "\u{f0aa}", "fa-arrow-down" : "\u{f063}", "fa-arrow-left" : "\u{f060}", "fa-arrow-right" : "\u{f061}", "fa-arrow-up" : "\u{f062}", "fa-arrows" : "\u{f047}", "fa-arrows-alt" : "\u{f0b2}", "fa-arrows-h" : "\u{f07e}", "fa-arrows-v" : "\u{f07d}", "fa-asterisk" : "\u{f069}", "fa-at" : "\u{f1fa}", "fa-automobile" : "\u{f1b9}", "fa-backward" : "\u{f04a}", "fa-balance-scale" : "\u{f24e}", "fa-ban" : "\u{f05e}", "fa-bank" : "\u{f19c}", "fa-bar-chart" : "\u{f080}", "fa-bar-chart-o" : "\u{f080}", "fa-barcode" : "\u{f02a}", "fa-bars" : "\u{f0c9}", "fa-battery-0" : "\u{f244}", "fa-battery-1" : "\u{f243}", "fa-battery-2" : "\u{f242}", "fa-battery-3" : "\u{f241}", "fa-battery-4" : "\u{f240}", "fa-battery-empty" : "\u{f244}", "fa-battery-full" : "\u{f240}", "fa-battery-half" : "\u{f242}", "fa-battery-quarter" : "\u{f243}", "fa-battery-three-quarters" : "\u{f241}", "fa-bed" : "\u{f236}", "fa-beer" : "\u{f0fc}", "fa-behance" : "\u{f1b4}", "fa-behance-square" : "\u{f1b5}", "fa-bell" : "\u{f0f3}", "fa-bell-o" : "\u{f0a2}", "fa-bell-slash" : "\u{f1f6}", "fa-bell-slash-o" : "\u{f1f7}", "fa-bicycle" : "\u{f206}", "fa-binoculars" : "\u{f1e5}", "fa-birthday-cake" : "\u{f1fd}", "fa-bitbucket" : "\u{f171}", "fa-bitbucket-square" : "\u{f172}", "fa-bitcoin" : "\u{f15a}", "fa-black-tie" : "\u{f27e}", "fa-bold" : "\u{f032}", "fa-bolt" : "\u{f0e7}", "fa-bomb" : "\u{f1e2}", "fa-book" : "\u{f02d}", "fa-bookmark" : "\u{f02e}", "fa-bookmark-o" : "\u{f097}", "fa-briefcase" : "\u{f0b1}", "fa-btc" : "\u{f15a}", "fa-bug" : "\u{f188}", "fa-building" : "\u{f1ad}", "fa-building-o" : "\u{f0f7}", "fa-bullhorn" : "\u{f0a1}", "fa-bullseye" : "\u{f140}", "fa-bus" : "\u{f207}", "fa-buysellads" : "\u{f20d}", "fa-cab" : "\u{f1ba}", "fa-calculator" : "\u{f1ec}", "fa-calendar" : "\u{f073}", "fa-calendar-check-o" : "\u{f274}", "fa-calendar-minus-o" : "\u{f272}", "fa-calendar-o" : "\u{f133}", "fa-calendar-plus-o" : "\u{f271}", "fa-calendar-times-o" : "\u{f273}", "fa-camera" : "\u{f030}", "fa-camera-retro" : "\u{f083}", "fa-car" : "\u{f1b9}", "fa-caret-down" : "\u{f0d7}", "fa-caret-left" : "\u{f0d9}", "fa-caret-right" : "\u{f0da}", "fa-caret-square-o-down" : "\u{f150}", "fa-caret-square-o-left" : "\u{f191}", "fa-caret-square-o-right" : "\u{f152}", "fa-caret-square-o-up" : "\u{f151}", "fa-caret-up" : "\u{f0d8}", "fa-cart-arrow-down" : "\u{f218}", "fa-cart-plus" : "\u{f217}", "fa-cc" : "\u{f20a}", "fa-cc-amex" : "\u{f1f3}", "fa-cc-diners-club" : "\u{f24c}", "fa-cc-discover" : "\u{f1f2}", "fa-cc-jcb" : "\u{f24b}", "fa-cc-mastercard" : "\u{f1f1}", "fa-cc-paypal" : "\u{f1f4}", "fa-cc-stripe" : "\u{f1f5}", "fa-cc-visa" : "\u{f1f0}", "fa-certificate" : "\u{f0a3}", "fa-chain" : "\u{f0c1}", "fa-chain-broken" : "\u{f127}", "fa-check" : "\u{f00c}", "fa-check-circle" : "\u{f058}", "fa-check-circle-o" : "\u{f05d}", "fa-check-square" : "\u{f14a}", "fa-check-square-o" : "\u{f046}", "fa-chevron-circle-down" : "\u{f13a}", "fa-chevron-circle-left" : "\u{f137}", "fa-chevron-circle-right" : "\u{f138}", "fa-chevron-circle-up" : "\u{f139}", "fa-chevron-down" : "\u{f078}", "fa-chevron-left" : "\u{f053}", "fa-chevron-right" : "\u{f054}", "fa-chevron-up" : "\u{f077}", "fa-child" : "\u{f1ae}", "fa-chrome" : "\u{f268}", "fa-circle" : "\u{f111}", "fa-circle-o" : "\u{f10c}", "fa-circle-o-notch" : "\u{f1ce}", "fa-circle-thin" : "\u{f1db}", "fa-clipboard" : "\u{f0ea}", "fa-clock-o" : "\u{f017}", "fa-clone" : "\u{f24d}", "fa-close" : "\u{f00d}", "fa-cloud" : "\u{f0c2}", "fa-cloud-download" : "\u{f0ed}", "fa-cloud-upload" : "\u{f0ee}", "fa-cny" : "\u{f157}", "fa-code" : "\u{f121}", "fa-code-fork" : "\u{f126}", "fa-codepen" : "\u{f1cb}", "fa-coffee" : "\u{f0f4}", "fa-cog" : "\u{f013}", "fa-cogs" : "\u{f085}", "fa-columns" : "\u{f0db}", "fa-comment" : "\u{f075}", "fa-comment-o" : "\u{f0e5}", "fa-commenting" : "\u{f27a}", "fa-commenting-o" : "\u{f27b}", "fa-comments" : "\u{f086}", "fa-comments-o" : "\u{f0e6}", "fa-compass" : "\u{f14e}", "fa-compress" : "\u{f066}", "fa-connectdevelop" : "\u{f20e}", "fa-contao" : "\u{f26d}", "fa-copy" : "\u{f0c5}", "fa-copyright" : "\u{f1f9}", "fa-creative-commons" : "\u{f25e}", "fa-credit-card" : "\u{f09d}", "fa-crop" : "\u{f125}", "fa-crosshairs" : "\u{f05b}", "fa-css3" : "\u{f13c}", "fa-cube" : "\u{f1b2}", "fa-cubes" : "\u{f1b3}", "fa-cut" : "\u{f0c4}", "fa-cutlery" : "\u{f0f5}", "fa-dashboard" : "\u{f0e4}", "fa-dashcube" : "\u{f210}", "fa-database" : "\u{f1c0}", "fa-dedent" : "\u{f03b}", "fa-delicious" : "\u{f1a5}", "fa-desktop" : "\u{f108}", "fa-deviantart" : "\u{f1bd}", "fa-diamond" : "\u{f219}", "fa-digg" : "\u{f1a6}", "fa-dollar" : "\u{f155}", "fa-dot-circle-o" : "\u{f192}", "fa-download" : "\u{f019}", "fa-dribbble" : "\u{f17d}", "fa-dropbox" : "\u{f16b}", "fa-drupal" : "\u{f1a9}", "fa-edit" : "\u{f044}", "fa-eject" : "\u{f052}", "fa-ellipsis-h" : "\u{f141}", "fa-ellipsis-v" : "\u{f142}", "fa-empire" : "\u{f1d1}", "fa-envelope" : "\u{f0e0}", "fa-envelope-o" : "\u{f003}", "fa-envelope-square" : "\u{f199}", "fa-eraser" : "\u{f12d}", "fa-eur" : "\u{f153}", "fa-euro" : "\u{f153}", "fa-exchange" : "\u{f0ec}", "fa-exclamation" : "\u{f12a}", "fa-exclamation-circle" : "\u{f06a}", "fa-exclamation-triangle" : "\u{f071}", "fa-expand" : "\u{f065}", "fa-expeditedssl" : "\u{f23e}", "fa-external-link" : "\u{f08e}", "fa-external-link-square" : "\u{f14c}", "fa-eye" : "\u{f06e}", "fa-eye-slash" : "\u{f070}", "fa-eyedropper" : "\u{f1fb}", "fa-facebook" : "\u{f09a}", "fa-facebook-f" : "\u{f09a}", "fa-facebook-official" : "\u{f230}", "fa-facebook-square" : "\u{f082}", "fa-fast-backward" : "\u{f049}", "fa-fast-forward" : "\u{f050}", "fa-fax" : "\u{f1ac}", "fa-feed" : "\u{f09e}", "fa-female" : "\u{f182}", "fa-fighter-jet" : "\u{f0fb}", "fa-file" : "\u{f15b}", "fa-file-archive-o" : "\u{f1c6}", "fa-file-audio-o" : "\u{f1c7}", "fa-file-code-o" : "\u{f1c9}", "fa-file-excel-o" : "\u{f1c3}", "fa-file-image-o" : "\u{f1c5}", "fa-file-movie-o" : "\u{f1c8}", "fa-file-o" : "\u{f016}", "fa-file-pdf-o" : "\u{f1c1}", "fa-file-photo-o" : "\u{f1c5}", "fa-file-picture-o" : "\u{f1c5}", "fa-file-powerpoint-o" : "\u{f1c4}", "fa-file-sound-o" : "\u{f1c7}", "fa-file-text" : "\u{f15c}", "fa-file-text-o" : "\u{f0f6}", "fa-file-video-o" : "\u{f1c8}", "fa-file-word-o" : "\u{f1c2}", "fa-file-zip-o" : "\u{f1c6}", "fa-files-o" : "\u{f0c5}", "fa-film" : "\u{f008}", "fa-filter" : "\u{f0b0}", "fa-fire" : "\u{f06d}", "fa-fire-extinguisher" : "\u{f134}", "fa-firefox" : "\u{f269}", "fa-flag" : "\u{f024}", "fa-flag-checkered" : "\u{f11e}", "fa-flag-o" : "\u{f11d}", "fa-flash" : "\u{f0e7}", "fa-flask" : "\u{f0c3}", "fa-flickr" : "\u{f16e}", "fa-floppy-o" : "\u{f0c7}", "fa-folder" : "\u{f07b}", "fa-folder-o" : "\u{f114}", "fa-folder-open" : "\u{f07c}", "fa-folder-open-o" : "\u{f115}", "fa-font" : "\u{f031}", "fa-fonticons" : "\u{f280}", "fa-forumbee" : "\u{f211}", "fa-forward" : "\u{f04e}", "fa-foursquare" : "\u{f180}", "fa-frown-o" : "\u{f119}", "fa-futbol-o" : "\u{f1e3}", "fa-gamepad" : "\u{f11b}", "fa-gavel" : "\u{f0e3}", "fa-gbp" : "\u{f154}", "fa-ge" : "\u{f1d1}", "fa-gear" : "\u{f013}", "fa-gears" : "\u{f085}", "fa-genderless" : "\u{f22d}", "fa-get-pocket" : "\u{f265}", "fa-gg" : "\u{f260}", "fa-gg-circle" : "\u{f261}", "fa-gift" : "\u{f06b}", "fa-git" : "\u{f1d3}", "fa-git-square" : "\u{f1d2}", "fa-github" : "\u{f09b}", "fa-github-alt" : "\u{f113}", "fa-github-square" : "\u{f092}", "fa-gittip" : "\u{f184}", "fa-glass" : "\u{f000}", "fa-globe" : "\u{f0ac}", "fa-google" : "\u{f1a0}", "fa-google-plus" : "\u{f0d5}", "fa-google-plus-square" : "\u{f0d4}", "fa-google-wallet" : "\u{f1ee}", "fa-graduation-cap" : "\u{f19d}", "fa-gratipay" : "\u{f184}", "fa-group" : "\u{f0c0}", "fa-h-square" : "\u{f0fd}", "fa-hacker-news" : "\u{f1d4}", "fa-hand-grab-o" : "\u{f255}", "fa-hand-lizard-o" : "\u{f258}", "fa-hand-o-down" : "\u{f0a7}", "fa-hand-o-left" : "\u{f0a5}", "fa-hand-o-right" : "\u{f0a4}", "fa-hand-o-up" : "\u{f0a6}", "fa-hand-paper-o" : "\u{f256}", "fa-hand-peace-o" : "\u{f25b}", "fa-hand-pointer-o" : "\u{f25a}", "fa-hand-rock-o" : "\u{f255}", "fa-hand-scissors-o" : "\u{f257}", "fa-hand-spock-o" : "\u{f259}", "fa-hand-stop-o" : "\u{f256}", "fa-hdd-o" : "\u{f0a0}", "fa-header" : "\u{f1dc}", "fa-headphones" : "\u{f025}", "fa-heart" : "\u{f004}", "fa-heart-o" : "\u{f08a}", "fa-heartbeat" : "\u{f21e}", "fa-history" : "\u{f1da}", "fa-home" : "\u{f015}", "fa-hospital-o" : "\u{f0f8}", "fa-hotel" : "\u{f236}", "fa-hourglass" : "\u{f254}", "fa-hourglass-1" : "\u{f251}", "fa-hourglass-2" : "\u{f252}", "fa-hourglass-3" : "\u{f253}", "fa-hourglass-end" : "\u{f253}", "fa-hourglass-half" : "\u{f252}", "fa-hourglass-o" : "\u{f250}", "fa-hourglass-start" : "\u{f251}", "fa-houzz" : "\u{f27c}", "fa-html5" : "\u{f13b}", "fa-i-cursor" : "\u{f246}", "fa-ils" : "\u{f20b}", "fa-image" : "\u{f03e}", "fa-inbox" : "\u{f01c}", "fa-indent" : "\u{f03c}", "fa-industry" : "\u{f275}", "fa-info" : "\u{f129}", "fa-info-circle" : "\u{f05a}", "fa-inr" : "\u{f156}", "fa-instagram" : "\u{f16d}", "fa-institution" : "\u{f19c}", "fa-internet-explorer" : "\u{f26b}", "fa-intersex" : "\u{f224}", "fa-ioxhost" : "\u{f208}", "fa-italic" : "\u{f033}", "fa-joomla" : "\u{f1aa}", "fa-jpy" : "\u{f157}", "fa-jsfiddle" : "\u{f1cc}", "fa-key" : "\u{f084}", "fa-keyboard-o" : "\u{f11c}", "fa-krw" : "\u{f159}", "fa-language" : "\u{f1ab}", "fa-laptop" : "\u{f109}", "fa-lastfm" : "\u{f202}", "fa-lastfm-square" : "\u{f203}", "fa-leaf" : "\u{f06c}", "fa-leanpub" : "\u{f212}", "fa-legal" : "\u{f0e3}", "fa-lemon-o" : "\u{f094}", "fa-level-down" : "\u{f149}", "fa-level-up" : "\u{f148}", "fa-life-bouy" : "\u{f1cd}", "fa-life-buoy" : "\u{f1cd}", "fa-life-ring" : "\u{f1cd}", "fa-life-saver" : "\u{f1cd}", "fa-lightbulb-o" : "\u{f0eb}", "fa-line-chart" : "\u{f201}", "fa-link" : "\u{f0c1}", "fa-linkedin" : "\u{f0e1}", "fa-linkedin-square" : "\u{f08c}", "fa-linux" : "\u{f17c}", "fa-list" : "\u{f03a}", "fa-list-alt" : "\u{f022}", "fa-list-ol" : "\u{f0cb}", "fa-list-ul" : "\u{f0ca}", "fa-location-arrow" : "\u{f124}", "fa-lock" : "\u{f023}", "fa-long-arrow-down" : "\u{f175}", "fa-long-arrow-left" : "\u{f177}", "fa-long-arrow-right" : "\u{f178}", "fa-long-arrow-up" : "\u{f176}", "fa-magic" : "\u{f0d0}", "fa-magnet" : "\u{f076}", "fa-mail-forward" : "\u{f064}", "fa-mail-reply" : "\u{f112}", "fa-mail-reply-all" : "\u{f122}", "fa-male" : "\u{f183}", "fa-map" : "\u{f279}", "fa-map-marker" : "\u{f041}", "fa-map-o" : "\u{f278}", "fa-map-pin" : "\u{f276}", "fa-map-signs" : "\u{f277}", "fa-mars" : "\u{f222}", "fa-mars-double" : "\u{f227}", "fa-mars-stroke" : "\u{f229}", "fa-mars-stroke-h" : "\u{f22b}", "fa-mars-stroke-v" : "\u{f22a}", "fa-maxcdn" : "\u{f136}", "fa-meanpath" : "\u{f20c}", "fa-medium" : "\u{f23a}", "fa-medkit" : "\u{f0fa}", "fa-meh-o" : "\u{f11a}", "fa-mercury" : "\u{f223}", "fa-microphone" : "\u{f130}", "fa-microphone-slash" : "\u{f131}", "fa-minus" : "\u{f068}", "fa-minus-circle" : "\u{f056}", "fa-minus-square" : "\u{f146}", "fa-minus-square-o" : "\u{f147}", "fa-mobile" : "\u{f10b}", "fa-mobile-phone" : "\u{f10b}", "fa-money" : "\u{f0d6}", "fa-moon-o" : "\u{f186}", "fa-mortar-board" : "\u{f19d}", "fa-motorcycle" : "\u{f21c}", "fa-mouse-pointer" : "\u{f245}", "fa-music" : "\u{f001}", "fa-navicon" : "\u{f0c9}", "fa-neuter" : "\u{f22c}", "fa-newspaper-o" : "\u{f1ea}", "fa-object-group" : "\u{f247}", "fa-object-ungroup" : "\u{f248}", "fa-odnoklassniki" : "\u{f263}", "fa-odnoklassniki-square" : "\u{f264}", "fa-opencart" : "\u{f23d}", "fa-openid" : "\u{f19b}", "fa-opera" : "\u{f26a}", "fa-optin-monster" : "\u{f23c}", "fa-outdent" : "\u{f03b}", "fa-pagelines" : "\u{f18c}", "fa-paint-brush" : "\u{f1fc}", "fa-paper-plane" : "\u{f1d8}", "fa-paper-plane-o" : "\u{f1d9}", "fa-paperclip" : "\u{f0c6}", "fa-paragraph" : "\u{f1dd}", "fa-paste" : "\u{f0ea}", "fa-pause" : "\u{f04c}", "fa-paw" : "\u{f1b0}", "fa-paypal" : "\u{f1ed}", "fa-pencil" : "\u{f040}", "fa-pencil-square" : "\u{f14b}", "fa-pencil-square-o" : "\u{f044}", "fa-phone" : "\u{f095}", "fa-phone-square" : "\u{f098}", "fa-photo" : "\u{f03e}", "fa-picture-o" : "\u{f03e}", "fa-pie-chart" : "\u{f200}", "fa-pied-piper" : "\u{f1a7}", "fa-pied-piper-alt" : "\u{f1a8}", "fa-pinterest" : "\u{f0d2}", "fa-pinterest-p" : "\u{f231}", "fa-pinterest-square" : "\u{f0d3}", "fa-plane" : "\u{f072}", "fa-play" : "\u{f04b}", "fa-play-circle" : "\u{f144}", "fa-play-circle-o" : "\u{f01d}", "fa-plug" : "\u{f1e6}", "fa-plus" : "\u{f067}", "fa-plus-circle" : "\u{f055}", "fa-plus-square" : "\u{f0fe}", "fa-plus-square-o" : "\u{f196}", "fa-power-off" : "\u{f011}", "fa-print" : "\u{f02f}", "fa-puzzle-piece" : "\u{f12e}", "fa-qq" : "\u{f1d6}", "fa-qrcode" : "\u{f029}", "fa-question" : "\u{f128}", "fa-question-circle" : "\u{f059}", "fa-quote-left" : "\u{f10d}", "fa-quote-right" : "\u{f10e}", "fa-ra" : "\u{f1d0}", "fa-random" : "\u{f074}", "fa-rebel" : "\u{f1d0}", "fa-recycle" : "\u{f1b8}", "fa-reddit" : "\u{f1a1}", "fa-reddit-square" : "\u{f1a2}", "fa-refresh" : "\u{f021}", "fa-registered" : "\u{f25d}", "fa-remove" : "\u{f00d}", "fa-renren" : "\u{f18b}", "fa-reorder" : "\u{f0c9}", "fa-repeat" : "\u{f01e}", "fa-reply" : "\u{f112}", "fa-reply-all" : "\u{f122}", "fa-retweet" : "\u{f079}", "fa-rmb" : "\u{f157}", "fa-road" : "\u{f018}", "fa-rocket" : "\u{f135}", "fa-rotate-left" : "\u{f0e2}", "fa-rotate-right" : "\u{f01e}", "fa-rouble" : "\u{f158}", "fa-rss" : "\u{f09e}", "fa-rss-square" : "\u{f143}", "fa-rub" : "\u{f158}", "fa-ruble" : "\u{f158}", "fa-rupee" : "\u{f156}", "fa-safari" : "\u{f267}", "fa-save" : "\u{f0c7}", "fa-scissors" : "\u{f0c4}", "fa-search" : "\u{f002}", "fa-search-minus" : "\u{f010}", "fa-search-plus" : "\u{f00e}", "fa-sellsy" : "\u{f213}", "fa-send" : "\u{f1d8}", "fa-send-o" : "\u{f1d9}", "fa-server" : "\u{f233}", "fa-share" : "\u{f064}", "fa-share-alt" : "\u{f1e0}", "fa-share-alt-square" : "\u{f1e1}", "fa-share-square" : "\u{f14d}", "fa-share-square-o" : "\u{f045}", "fa-shekel" : "\u{f20b}", "fa-sheqel" : "\u{f20b}", "fa-shield" : "\u{f132}", "fa-ship" : "\u{f21a}", "fa-shirtsinbulk" : "\u{f214}", "fa-shopping-cart" : "\u{f07a}", "fa-sign-in" : "\u{f090}", "fa-sign-out" : "\u{f08b}", "fa-signal" : "\u{f012}", "fa-simplybuilt" : "\u{f215}", "fa-sitemap" : "\u{f0e8}", "fa-skyatlas" : "\u{f216}", "fa-skype" : "\u{f17e}", "fa-slack" : "\u{f198}", "fa-sliders" : "\u{f1de}", "fa-slideshare" : "\u{f1e7}", "fa-smile-o" : "\u{f118}", "fa-soccer-ball-o" : "\u{f1e3}", "fa-sort" : "\u{f0dc}", "fa-sort-alpha-asc" : "\u{f15d}", "fa-sort-alpha-desc" : "\u{f15e}", "fa-sort-amount-asc" : "\u{f160}", "fa-sort-amount-desc" : "\u{f161}", "fa-sort-asc" : "\u{f0de}", "fa-sort-desc" : "\u{f0dd}", "fa-sort-down" : "\u{f0dd}", "fa-sort-numeric-asc" : "\u{f162}", "fa-sort-numeric-desc" : "\u{f163}", "fa-sort-up" : "\u{f0de}", "fa-soundcloud" : "\u{f1be}", "fa-space-shuttle" : "\u{f197}", "fa-spinner" : "\u{f110}", "fa-spoon" : "\u{f1b1}", "fa-spotify" : "\u{f1bc}", "fa-square" : "\u{f0c8}", "fa-square-o" : "\u{f096}", "fa-stack-exchange" : "\u{f18d}", "fa-stack-overflow" : "\u{f16c}", "fa-star" : "\u{f005}", "fa-star-half" : "\u{f089}", "fa-star-half-empty" : "\u{f123}", "fa-star-half-full" : "\u{f123}", "fa-star-half-o" : "\u{f123}", "fa-star-o" : "\u{f006}", "fa-steam" : "\u{f1b6}", "fa-steam-square" : "\u{f1b7}", "fa-step-backward" : "\u{f048}", "fa-step-forward" : "\u{f051}", "fa-stethoscope" : "\u{f0f1}", "fa-sticky-note" : "\u{f249}", "fa-sticky-note-o" : "\u{f24a}", "fa-stop" : "\u{f04d}", "fa-street-view" : "\u{f21d}", "fa-strikethrough" : "\u{f0cc}", "fa-stumbleupon" : "\u{f1a4}", "fa-stumbleupon-circle" : "\u{f1a3}", "fa-subscript" : "\u{f12c}", "fa-subway" : "\u{f239}", "fa-suitcase" : "\u{f0f2}", "fa-sun-o" : "\u{f185}", "fa-superscript" : "\u{f12b}", "fa-support" : "\u{f1cd}", "fa-table" : "\u{f0ce}", "fa-tablet" : "\u{f10a}", "fa-tachometer" : "\u{f0e4}", "fa-tag" : "\u{f02b}", "fa-tags" : "\u{f02c}", "fa-tasks" : "\u{f0ae}", "fa-taxi" : "\u{f1ba}", "fa-television" : "\u{f26c}", "fa-tencent-weibo" : "\u{f1d5}", "fa-terminal" : "\u{f120}", "fa-text-height" : "\u{f034}", "fa-text-width" : "\u{f035}", "fa-th" : "\u{f00a}", "fa-th-large" : "\u{f009}", "fa-th-list" : "\u{f00b}", "fa-thumb-tack" : "\u{f08d}", "fa-thumbs-down" : "\u{f165}", "fa-thumbs-o-down" : "\u{f088}", "fa-thumbs-o-up" : "\u{f087}", "fa-thumbs-up" : "\u{f164}", "fa-ticket" : "\u{f145}", "fa-times" : "\u{f00d}", "fa-times-circle" : "\u{f057}", "fa-times-circle-o" : "\u{f05c}", "fa-tint" : "\u{f043}", "fa-toggle-down" : "\u{f150}", "fa-toggle-left" : "\u{f191}", "fa-toggle-off" : "\u{f204}", "fa-toggle-on" : "\u{f205}", "fa-toggle-right" : "\u{f152}", "fa-toggle-up" : "\u{f151}", "fa-trademark" : "\u{f25c}", "fa-train" : "\u{f238}", "fa-transgender" : "\u{f224}", "fa-transgender-alt" : "\u{f225}", "fa-trash" : "\u{f1f8}", "fa-trash-o" : "\u{f014}", "fa-tree" : "\u{f1bb}", "fa-trello" : "\u{f181}", "fa-tripadvisor" : "\u{f262}", "fa-trophy" : "\u{f091}", "fa-truck" : "\u{f0d1}", "fa-try" : "\u{f195}", "fa-tty" : "\u{f1e4}", "fa-tumblr" : "\u{f173}", "fa-tumblr-square" : "\u{f174}", "fa-turkish-lira" : "\u{f195}", "fa-tv" : "\u{f26c}", "fa-twitch" : "\u{f1e8}", "fa-twitter" : "\u{f099}", "fa-twitter-square" : "\u{f081}", "fa-umbrella" : "\u{f0e9}", "fa-underline" : "\u{f0cd}", "fa-undo" : "\u{f0e2}", "fa-university" : "\u{f19c}", "fa-unlink" : "\u{f127}", "fa-unlock" : "\u{f09c}", "fa-unlock-alt" : "\u{f13e}", "fa-unsorted" : "\u{f0dc}", "fa-upload" : "\u{f093}", "fa-usd" : "\u{f155}", "fa-user" : "\u{f007}", "fa-user-md" : "\u{f0f0}", "fa-user-plus" : "\u{f234}", "fa-user-secret" : "\u{f21b}", "fa-user-times" : "\u{f235}", "fa-users" : "\u{f0c0}", "fa-venus" : "\u{f221}", "fa-venus-double" : "\u{f226}", "fa-venus-mars" : "\u{f228}", "fa-viacoin" : "\u{f237}", "fa-video-camera" : "\u{f03d}", "fa-vimeo" : "\u{f27d}", "fa-vimeo-square" : "\u{f194}", "fa-vine" : "\u{f1ca}", "fa-vk" : "\u{f189}", "fa-volume-down" : "\u{f027}", "fa-volume-off" : "\u{f026}", "fa-volume-up" : "\u{f028}", "fa-warning" : "\u{f071}", "fa-wechat" : "\u{f1d7}", "fa-weibo" : "\u{f18a}", "fa-weixin" : "\u{f1d7}", "fa-whatsapp" : "\u{f232}", "fa-wheelchair" : "\u{f193}", "fa-wifi" : "\u{f1eb}", "fa-wikipedia-w" : "\u{f266}", "fa-windows" : "\u{f17a}", "fa-won" : "\u{f159}", "fa-wordpress" : "\u{f19a}", "fa-wrench" : "\u{f0ad}", "fa-xing" : "\u{f168}", "fa-xing-square" : "\u{f169}", "fa-y-combinator" : "\u{f23b}", "fa-y-combinator-square" : "\u{f1d4}", "fa-yahoo" : "\u{f19e}", "fa-yc" : "\u{f23b}", "fa-yc-square" : "\u{f1d4}", "fa-yelp" : "\u{f1e9}", "fa-yen" : "\u{f157}", "fa-youtube" : "\u{f167}", "fa-youtube-play" : "\u{f16a}", "fa-youtube-square" : "\u{f166}", "fa-reddit-alien" : "\u{f281}", "fa-edge" : "\u{f282}", "fa-credit-card-alt" : "\u{f283}", "fa-codiepie" : "\u{f284}", "fa-modx" : "\u{f285}", "fa-fort-awesome" : "\u{f286}", "fa-usb" : "\u{f287}", "fa-product-hunt" : "\u{f288}", "fa-mixcloud" : "\u{f289}", "fa-scribd" : "\u{f28a}", "fa-pause-circle" : "\u{f28b}", "fa-pause-circle-o" : "\u{f28c}", "fa-stop-circle" : "\u{f28d}", "fa-stop-circle-o" : "\u{f28e}", "fa-shopping-bag" : "\u{f290}", "fa-shopping-basket" : "\u{f291}", "fa-hashtag" : "\u{f292}", "fa-bluetooth" : "\u{f293}", "fa-bluetooth-b" : "\u{f294}", "fa-percent" : "\u{f295}" ]
mit
a21f82e83ec483f3c6284501f048ffcc
31.441568
120
0.515822
2.403266
false
false
false
false
carabina/Mirror
Mirror/Mirror.swift
1
3998
// // File.swift // Mirror // // Created by Kostiantyn Koval on 05/07/15. // // import Foundation public struct MirrorItem { public let name: String public let type: Any.Type public let value: Any init(_ tup: (String, MirrorType)) { self.name = tup.0 self.type = tup.1.valueType self.value = tup.1.value } } extension MirrorItem : Printable { public var description: String { return "\(name): \(type) = \(value)" } } //MARK: - public struct Mirror<T> { private let mirror: MirrorType let instance: T public init (_ x: T) { instance = x mirror = reflect(x) } //MARK: - Type Info /// Instance type full name, include Module public var name: String { return "\(instance.dynamicType)" } /// Instance type short name, just a type name, without Module public var shortName: String { let name = "\(instance.dynamicType)" let shortName = name.convertOptionals() return shortName.pathExtension } } extension Mirror { public var isClass: Bool { return mirror.objectIdentifier != nil } public var isStruct: Bool { return mirror.objectIdentifier == nil } public var isOptional: Bool { return name.hasPrefix("Swift.Optional<") } public var isArray: Bool { return name.hasPrefix("Swift.Array<") } public var isDictionary: Bool { return name.hasPrefix("Swift.Dictionary<") } public var isSet: Bool { return name.hasPrefix("Swift.Set<") } } extension Mirror { /// Type properties count public var childrenCount: Int { return mirror.count } public var memorySize: Int { return sizeofValue(instance) } //MARK: - Children Inpection /// Properties Names public var names: [String] { return map(self) { $0.name } } /// Properties Values public var values: [Any] { return map(self) { $0.value } } /// Properties Types public var types: [Any.Type] { return map(self) { $0.type } } /// Short style for type names public var typesShortName: [String] { return map(self) { "\($0.type)".convertOptionals().pathExtension } } /// Mirror types for every children property public var children: [MirrorItem] { return map(self) { $0 } } //MARK: - Quering /// Returns a property value for a property name public subscript (key: String) -> Any? { let res = findFirst(self) { $0.name == key } return res.map { $0.value } } /// Returns a property value for a property name with a Genereci type /// No casting needed public func get<U>(key: String) -> U? { let res = findFirst(self) { $0.name == key } return res.flatMap { $0.value as? U } } /// Convert to a dicitonary with [PropertyName : PropertyValue] notation public var toDictionary: [String : Any] { var result: [String : Any] = [ : ] for item in self { result[item.name] = item.value } return result } /// Convert to NSDictionary. /// Useful for saving it to Plist public var toNSDictionary: NSDictionary { var result: [String : AnyObject] = [ : ] for item in self { result[item.name] = item.value as? AnyObject } return result } } extension Mirror : CollectionType, SequenceType { public func generate() -> IndexingGenerator<[MirrorItem]> { return children.generate() } public var startIndex: Int { return 0 } public var endIndex: Int { return mirror.count } public subscript (i: Int) -> MirrorItem { return MirrorItem(mirror[i]) } } extension String { func contains(x: String) -> Bool { return self.rangeOfString(x) != nil } func convertOptionals() -> String { var x = self while let range = x.rangeOfString("Optional<") { if let endOfOptional = x.rangeOfString(">", range: range.startIndex..<x.endIndex) { x.replaceRange(endOfOptional, with: "?") } x.removeRange(range) } return x } }
mit
a1a84eb5cc8545ee0f714cf2ee545ad9
19.294416
89
0.622811
3.923454
false
false
false
false
kaich/CKPhotoGallery
CKPhotoGallery/Classes/CKScalingImageView.swift
1
4187
// // CKScalingImageView.swift // Pods // // Created by mac on 16/10/17. // // import UIKit private func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } class CKScalingImageView: UIScrollView { fileprivate let imageViewImageKeyPath = "imageView.image" lazy var imageView: UIImageView = { let imageView = UIImageView(frame: self.bounds) imageView.contentMode = .center self.addSubview(imageView) return imageView }() var image: UIImage? { didSet { updateImage(image) } } override var frame: CGRect { didSet { updateZoomScale() centerScrollViewContents() } } override init(frame: CGRect) { super.init(frame: frame) addObserver(self, forKeyPath: imageViewImageKeyPath, options: .new, context: nil) setupImageScrollView() updateZoomScale() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupImageScrollView() updateZoomScale() } deinit { removeObserver(self, forKeyPath: "imageView.image") } override func didAddSubview(_ subview: UIView) { super.didAddSubview(subview) centerScrollViewContents() } private func setupImageScrollView() { showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false; bouncesZoom = true; decelerationRate = UIScrollViewDecelerationRateFast; } func centerScrollViewContents() { var horizontalInset: CGFloat = 0; var verticalInset: CGFloat = 0; if (contentSize.width < bounds.width) { horizontalInset = (bounds.width - contentSize.width) * 0.5; } if (self.contentSize.height < bounds.height) { verticalInset = (bounds.height - contentSize.height) * 0.5; } if (window?.screen.scale < 2) { horizontalInset = floor(horizontalInset); verticalInset = floor(verticalInset); } // Use `contentInset` to center the contents in the scroll view. Reasoning explained here: http://petersteinberger.com/blog/2013/how-to-center-uiscrollview/ self.contentInset = UIEdgeInsetsMake(verticalInset, horizontalInset, verticalInset, horizontalInset); } private func updateImage(_ image: UIImage?) { let size = image?.size ?? CGSize.zero imageView.transform = CGAffineTransform.identity imageView.frame = CGRect(origin: CGPoint.zero, size: size) self.contentSize = size updateZoomScale() centerScrollViewContents() } private func updateZoomScale() { if let image = imageView.image { let scrollViewFrame = self.bounds let scaleWidth = scrollViewFrame.size.width / image.size.width let scaleHeight = scrollViewFrame.size.height / image.size.height let minimumScale = min(scaleWidth, scaleHeight) self.minimumZoomScale = minimumScale self.maximumZoomScale = max(minimumScale, self.maximumZoomScale) self.zoomScale = minimumZoomScale // scrollView.panGestureRecognizer.enabled is on by default and enabled by // viewWillLayoutSubviews in the container controller so disable it here // to prevent an interference with the container controller's pan gesture. // // This is enabled in scrollViewWillBeginZooming so panning while zoomed-in // is unaffected. self.panGestureRecognizer.isEnabled = false } } //MARK: - Observer override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == imageViewImageKeyPath { image = imageView.image } } }
mit
580b70568d9f3ca74cfa2fabeacc618a
30.481203
164
0.60855
5.2733
false
false
false
false
quickthyme/PUTcat
PUTcat/Presentation/Project/ProjectViewController+TableView.swift
1
3078
import UIKit // MARK: - DataSource extension ProjectViewController { override func numberOfSections(in tableView: UITableView) -> Int { return sceneData.numberOfSections() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sceneData.numberOfItemsInSection(section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = sceneData.getItem(forIndexPath: indexPath) let refID = item.refID let cell = tableView.dequeueReusableCell(withIdentifier: item.cellID, for: indexPath) if let cell = cell as? ProjectSceneDataItemConfigurable { cell.configure(projectSceneDataItem: item) } if let cell = cell as? ProjectSceneDataItemEditable { cell.textChanged = { [weak self] newText in if let `self` = self, let item = self.sceneData.updateItem(title: newText, forRefID: refID) { self.delegate?.scene(self, didUpdate: item) } } } return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sceneData.getSectionTitle(section) } } // MARK: - Editing extension ProjectViewController { override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) as? ProjectSceneDataItemEditable { cell.hideTextField() } switch (editingStyle) { case .delete: let deletedItem = sceneData.deleteItem(indexPath: indexPath) delegate?.scene(self, didDelete: deletedItem) tableView.deleteRows(at: [indexPath], with: .left) default: break } } } // MARK: - Moving extension ProjectViewController { override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { sceneData.moveItem(fromIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath) delegate?.scene(self, didUpdateOrdinality: sceneData) } } // MARK: - Selection extension ProjectViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if self.isEditing { (tableView.cellForRow(at: indexPath) as? ProjectSceneDataItemEditable)? .showTextField() } else { self.selectedSceneDataItem = sceneData.getItem(forIndexPath: indexPath) if let item = selectedSceneDataItem { delegate?.scene(self, didSelect: item) } } } }
apache-2.0
0256c743ebdd62ba9875dce7ce3449e0
34.37931
136
0.662443
5.297762
false
false
false
false
HotCatLX/SwiftStudy
18-EasyTableView/EasyTableView/HeaderS.swift
1
2465
// // HeaderS.swift // EasyTableView // // Created by suckerl on 2017/5/22. // Copyright © 2017年 suckel. All rights reserved. // import UIKit import SnapKit protocol HeaderSDelegate { func buttonClick(button : UIButton) } class HeaderS: UITableViewHeaderFooterView { public var delegate : HeaderSDelegate? public lazy var button :UIButton = { let button = UIButton() button.setImage(UIImage.init(named: "back"), for: .normal) button.addTarget(self, action: #selector(HeaderS.buttonClick(button:)), for: .touchUpInside) return button }() public lazy var label :UILabel = { let label = UILabel() label.textColor = UIColor.darkGray label.text = "Tset" label.backgroundColor = UIColor.green label.alpha = 0.4 label.layer.cornerRadius = 5 label.clipsToBounds = true label.font = UIFont.systemFont(ofSize: 15) return label }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) self.addSubview(button) self.addSubview(label) self.constructLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension HeaderS { func constructLayout() { button.snp.makeConstraints { (make) in make.left.equalTo(self.contentView).offset(5) make.top.equalTo(self.contentView).offset(5) make.bottom.equalTo(self.contentView).offset(-5) make.width.equalTo(30) } label.snp.makeConstraints { (make) in make.left.equalTo(button.snp.right).offset(5) make.top.equalTo(button.snp.top) make.width.equalTo(100) make.height.equalTo(30) } // button.frame = CGRect(x: 5, y: 5, width: 30, height: 30) // let space : CGFloat = 10 // let X = button.frame.width + space // let Y = button.frame.origin.y + space * 0.5 // let str : String = label.text! // let originalString : NSString = str as NSString // let size : CGSize = originalString.size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 15)]) // label.frame = CGRect(x: X, y: Y, width: size.width, height: size.height) } func buttonClick(button : UIButton) { delegate?.buttonClick(button: button) } }
mit
b9231df5275291602ce707d0c4deb06d
29.02439
115
0.612104
4.076159
false
false
false
false
apple/swift
validation-test/compiler_crashers_2_fixed/issue-55167.swift
2
3337
// RUN: %target-swift-emit-silgen %s -verify // https://github.com/apple/swift/issues/55167 func thin(_: (@convention(thin) () -> Void) -> Void) {} func block(_: (@convention(block) () -> Void) -> Void) {} func c(_: (@convention(c) () -> Void) -> Void) {} func function(_: () -> Void) {} func context() { c(function) block(function) thin(function) } struct C { let function: (@convention(c) () -> Void) -> Void } struct Thin { let function: (@convention(thin) () -> Void) -> Void } struct Block { let function: (@convention(block) () -> Void) -> Void } func proxy(_ f: (() -> Void) -> Void) { let a = 1 f { print(a) } } func cContext() { let c = C { app in app() } proxy(c.function) // expected-error@-1 {{converting non-escaping value to '@convention(c) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to expected argument type '(() -> Void) -> Void'}} let _ : (@convention(block) () -> Void) -> Void = c.function // expected-error@-1 {{converting non-escaping value to '@convention(c) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to specified type '(@convention(block) () -> Void) -> Void'}} let _ : (@convention(c) () -> Void) -> Void = c.function // OK let _ : (@convention(thin) () -> Void) -> Void = c.function // OK let _ : (() -> Void) -> Void = c.function // expected-error@-1 {{converting non-escaping value to '@convention(c) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to specified type '(() -> Void) -> Void'}} } func thinContext() { let thin = Thin { app in app() } proxy(thin.function) // expected-error@-1 {{converting non-escaping value to '@convention(thin) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@escaping @convention(thin) () -> Void) -> Void' to expected argument type '(() -> Void) -> Void'}} let _ : (@convention(block) () -> Void) -> Void = thin.function // expected-error@-1 {{converting non-escaping value to '@convention(thin) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@escaping @convention(thin) () -> Void) -> Void' to specified type '(@convention(block) () -> Void) -> Void'}} let _ : (@convention(c) () -> Void) -> Void = thin.function // OK let _ : (@convention(thin) () -> Void) -> Void = thin.function // OK let _ : (() -> Void) -> Void = thin.function // expected-error@-1 {{converting non-escaping value to '@convention(thin) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@escaping @convention(thin) () -> Void) -> Void' to specified type '(() -> Void) -> Void'}} } func blockContext() { let block = Block { app in app() } proxy(block.function) let _ : (@convention(block) () -> Void) -> Void = block.function // OK let _ : (@convention(c) () -> Void) -> Void = block.function // OK let _ : (@convention(thin) () -> Void) -> Void = block.function // OK let _ : (() -> Void) -> Void = block.function // OK }
apache-2.0
10148a1cbdce89389f2a789e0fcd07ab
36.494382
168
0.579263
3.55
false
false
false
false
OrRon/NexmiiHack
NexmiiHack/AppDelegate.swift
1
3937
// // AppDelegate.swift // NexmiiHack // // Created by Or on 27/10/2016. // Copyright © 2016 Or. All rights reserved. // import UIKit import Firebase import OneSignal @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let speech = SpeechToText() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //OneSignal.initWithLaunchOptions(launchOptions, appId: "f5920934-0fb0-4bea-8079-46ecb3238464") // speech.authorize() // speech.start(locale: "en-US") // // DispatchQueue.main.asyncAfter(deadline: .now() + 5) { // print(self.speech.stop()) // } OneSignal.initWithLaunchOptions(launchOptions, appId: "f5920934-0fb0-4bea-8079-46ecb3238464", handleNotificationReceived: { (notification) in NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Push"), object: nil, userInfo: ["msg" : notification?.payload.title]) print("Received Notification - \(notification?.payload.title)") }, handleNotificationAction: { (result) in // This block gets called when the user reacts to a notification received let payload = result?.notification.payload var fullMessage = payload?.title //Try to fetch the action selected if let additionalData = payload?.additionalData, let actionSelected = additionalData["actionSelected"] as? String { fullMessage = fullMessage! + "\nPressed ButtonId:\(actionSelected)" } print(fullMessage) }, settings: [kOSSettingsKeyAutoPrompt : false, kOSSettingsKeyInFocusDisplayOption : 0]) //FIRApp.configure() return true } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { print("GOT IT") } 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:. } }
mit
08d456d8e552c808e1b92958573d345d
48.2
285
0.691565
5.248
false
false
false
false
iosprogrammingwithswift/iosprogrammingwithswift
04_Swift2015_Final.playground/Pages/06_Functions.xcplaygroundpage/Contents.swift
1
5542
//: [Previous](@previous) | [Next](@next) //: ## Functions and Closures //: //: Use `func` to declare a function. Call a function by following its name with a list of arguments in parentheses. Use `->` to separate the parameter names and types from the function’s return type. //: func sayHelloAgain(personName: String) -> String { return "Hello again, " + personName + "!" } print(sayHelloAgain("Anna")) // prints "Hello again, Anna!" func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } greet("Bob", day: "Tuesday") //: > **Experiment**: //: > Remove the `day` parameter. Add a parameter to include today’s lunch special in the greeting. //: //: Specifying External Parameter Names & Omitting External Parameter Names func sayHello(to person: String, and anotherPerson: String, _ thirdParamterName: Int) -> String { return "Hello \(person) and \(anotherPerson)! -> \(thirdParamterName)" } let result = sayHello(to: "Bill", and: "Ted", 7) print(result) // prints "Hello Bill and Ted!" //: Functions with Multiple Return Values //: Use a tuple to make a compound value—for example, to return multiple values from a function. The elements of a tuple can be referred to either by name or by number. //: func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { var min = scores[0] var max = scores[0] var sum = 0 for score in scores { if score > max { max = score } else if score < min { min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics([5, 3, 100, 3, 9]) print(statistics.sum) print(statistics.2) //: Variadic Parameters //: Functions can also take a variable number of arguments, collecting them into an array. //: func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } sumOf() sumOf(42, 597, 12) //: > **Experiment**: //: > Write a function that calculates the average of its arguments. //: //: Functions can be nested. Nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex. //: func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen() //: inout func swapTwoInts(inout a: Int, inout _ b: Int) { let temporaryA = a a = b b = temporaryA } var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt, &anotherInt) print("someInt is now \(someInt), and anotherInt is now \(anotherInt)") // prints "someInt is now 107, and anotherInt is now 3" //: Function Types //: Functions are a first-class type. This means that a function can return another function as its value. //: func makeIncrementer() -> ((Int) -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7) //: A function can take another function as one of its arguments. //: func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers, condition: lessThanTen) func doStuffFromAGivenMethod(list:[Int], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func moreThanTen(number: Int) -> Bool { return number > 10 } func isEqualThree(number: Int) -> Bool { return number == 3 } func isEqualTwelve(number: Int) -> Bool { return number == 12 } doStuffFromAGivenMethod(numbers, condition: lessThanTen) doStuffFromAGivenMethod(numbers, condition: moreThanTen) doStuffFromAGivenMethod(numbers, condition: isEqualThree) doStuffFromAGivenMethod(numbers, condition: isEqualTwelve) /*: Currying * one of those weird words you avoid because people who say it are sometimes jerks * it is actually a preetty straightforward concept * currying is a function that returns another function * useful for sharing code that is mostly the same TODO: https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-ID363 */ func containsAtSign(string:String) -> Bool { return string.characters.contains("@") } containsAtSign("Toll") containsAtSign("[email protected]") var input = ["Six Eggs", "Mil@k", "Flour", "Bak@ing Powder", "Bananas"] //: Before currying input.filter(containsAtSign) /* func containsAtSign2(substring:String) -> (String -> Bool) { return { string -> Bool in return string.characters.contains(substring) } } func containsAtSign3(substring:String)(string -> Bool) -> Bool { return string.characters.contains(substring) } input.filter(containsAtSign2("@")) input.filter(containsAtSign3("@")) */ /*: largely Based of [Apple's Swift Language Guide: Functions](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID158 ) & [Apple's A Swift Tour](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1 ) */ //: [Previous](@previous) | [Next](@next)
mit
cdf1cf0d4f68c687d058fe5ac426fbe0
28.446809
395
0.6819
3.74307
false
false
false
false
shopgun/shopgun-ios-sdk
Sources/TjekAPI/Models/v2Models.swift
1
23205
/// /// Copyright (c) 2021 Tjek. All rights reserved. /// import Foundation /// A `Publication` is a catalog, that can be rendered in multiple forms, paged or incito. public struct Publication_v2: Equatable { public typealias ID = PublicationId public enum PublicationType: String, Codable, CaseIterable { case paged case incito } /// The unique identifier of this Publication. public var id: ID /// The name of the publication. eg. "Christmas Special". public var label: String? /// How many pages this publication has. public var pageCount: Int /// How many `Offer`s are in this publication. public var offerCount: Int /// The range of dates that this publication is valid from and until. public var runDateRange: Range<Date> /// The ratio of width to height for the page-images. So if an image is (w:100, h:200), the aspectRatio is 0.5 (width/height). public var aspectRatio: Double /// The branding information for the publication's dealer. public var branding: Branding_v2 /// A set of URLs for the different sized images for the cover of the publication. public var frontPageImages: Set<ImageURL> /// Whether this publication is available in all stores, or just in a select few stores. public var isAvailableInAllStores: Bool /// The unique identifier of the business that published this publication. public var businessId: Business_v2.ID /// The unique identifier of the nearest store. This will only contain a value if the `Publication` was fetched with a request that includes store information (eg. one that takes a precise location as a parameter). public var storeId: Store_v2.ID? /// Defines what types of publication this represents. /// If it contains `paged`, the `id` can be used to view this in a PagedPublicationViewer /// If it contains `incito`, the `id` can be used to view this with the IncitoViewer /// If it ONLY contains `incito`, this cannot be viewed in a PagedPublicationViewer (see `isOnlyIncito`) public var types: Set<PublicationType> } extension Publication_v2 { /// True if this publication can only be viewed as an incito (if viewed in a PagedPublication view it would appear as a single-page pdf) public var isOnlyIncitoPublication: Bool { return types == [.incito] } /// True if this publication can be viewed as an incito public var hasIncitoPublication: Bool { types.contains(.incito) } /// True if this publication can be viewed as an paged publication public var hasPagedPublication: Bool { types.contains(.paged) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Publication_v2: Identifiable { } extension Publication_v2: Decodable { enum CodingKeys: String, CodingKey { case id case label = "label" case branding case pageCount = "page_count" case offerCount = "offer_count" case runFromDateStr = "run_from" case runTillDateStr = "run_till" case businessId = "dealer_id" case storeId = "store_id" case availableAllStores = "all_stores" case dimensions case frontPageImageURLs = "images" case types } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.id = try values.decode(ID.self, forKey: .id) self.label = try? values.decode(String.self, forKey: .label) self.branding = try values.decode(Branding_v2.self, forKey: .branding) self.pageCount = (try? values.decode(Int.self, forKey: .pageCount)) ?? 0 self.offerCount = (try? values.decode(Int.self, forKey: .offerCount)) ?? 0 let fromDate = (try? values.decode(Date.self, forKey: .runFromDateStr)) ?? Date.distantPast let tillDate = (try? values.decode(Date.self, forKey: .runTillDateStr)) ?? Date.distantFuture // make sure range is not malformed self.runDateRange = min(tillDate, fromDate) ..< max(tillDate, fromDate) if let dimDict = try? values.decode([String: Double].self, forKey: .dimensions), let width = dimDict["width"], let height = dimDict["height"] { self.aspectRatio = (width > 0 && height > 0) ? width / height : 1.0 } else { self.aspectRatio = 1.0 } self.isAvailableInAllStores = (try? values.decode(Bool.self, forKey: .availableAllStores)) ?? true self.businessId = try values.decode(Business_v2.ID.self, forKey: .businessId) self.storeId = try? values.decode(Store_v2.ID.self, forKey: .storeId) self.frontPageImages = (try? values.decode(v2ImageURLs.self, forKey: .frontPageImageURLs))?.imageURLSet ?? [] self.types = (try? values.decode(Set<PublicationType>.self, forKey: .types)) ?? [.paged] } } // MARK: - public struct Branding_v2: Equatable { public var name: String? public var website: URL? public var description: String? public var logoURL: URL? public var colorHex: String? public init(name: String?, website: URL?, description: String?, logoURL: URL?, colorHex: String?) { self.name = name self.website = website self.description = description self.logoURL = logoURL self.colorHex = colorHex } } extension Branding_v2: Decodable { enum CodingKeys: String, CodingKey { case name case website case description case logoURL = "logo" case colorStr = "color" } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.name = try? values.decode(String.self, forKey: .name) self.website = try? values.decode(URL.self, forKey: .website) self.description = try? values.decode(String.self, forKey: .description) self.logoURL = try? values.decode(URL.self, forKey: .logoURL) self.colorHex = try? values.decode(String.self, forKey: .colorStr) } } #if canImport(UIKit) import UIKit extension Branding_v2 { public var color: UIColor? { colorHex.flatMap(UIColor.init(hex:)) } } #endif // MARK: - public struct Offer_v2: Equatable { public typealias ID = OfferId public var id: ID public var heading: String public var description: String? public var images: Set<ImageURL> public var webshopURL: URL? public var runDateRange: Range<Date> public var publishDate: Date? public var price: Price? public var quantity: Quantity? public var branding: Branding_v2? public var publicationId: Publication_v2.ID? public var publicationPageIndex: Int? public var incitoViewId: String? public var businessId: Business_v2.ID /// The id of the nearest store. Only available if a location was provided when fetching the offer. public var storeId: Store_v2.ID? } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Offer_v2: Identifiable { } extension Offer_v2: Decodable { enum CodingKeys: String, CodingKey { case id case heading case description case images case links case runFromDateStr = "run_from" case runTillDateStr = "run_till" case publishDateStr = "publish" case price = "pricing" case quantity case branding case catalogId = "catalog_id" case catalogPage = "catalog_page" case catalogViewId = "catalog_view_id" case dealerId = "dealer_id" case storeId = "store_id" } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.id = try values.decode(ID.self, forKey: .id) self.heading = try values.decode(String.self, forKey: .heading) self.description = try? values.decode(String.self, forKey: .description) self.images = (try? values.decode(v2ImageURLs.self, forKey: .images))?.imageURLSet ?? [] if let links = try? values.decode([String: URL].self, forKey: .links) { self.webshopURL = links["webshop"] } let fromDate = (try? values.decode(Date.self, forKey: .runFromDateStr)) ?? Date.distantPast let tillDate = (try? values.decode(Date.self, forKey: .runTillDateStr)) ?? Date.distantFuture // make sure range is not malformed self.runDateRange = min(tillDate, fromDate) ..< max(tillDate, fromDate) self.publishDate = try? values.decode(Date.self, forKey: .publishDateStr) self.price = try? values.decode(Price.self, forKey: .price) self.quantity = try? values.decode(Quantity.self, forKey: .quantity) self.branding = try? values.decode(Branding_v2.self, forKey: .branding) self.publicationId = try? values.decode(Publication_v2.ID.self, forKey: .catalogId) // incito publications have pageNum == 0, so in that case set to nil. // otherwise, convert pageNum to index. self.publicationPageIndex = (try? values.decode(Int.self, forKey: .catalogPage)).flatMap({ $0 > 0 ? $0 - 1 : nil }) self.incitoViewId = try? values.decode(String.self, forKey: .catalogViewId) self.businessId = try values.decode(Business_v2.ID.self, forKey: .dealerId) self.storeId = try? values.decode(Store_v2.ID.self, forKey: .storeId) } } extension Offer_v2 { public struct Price: Hashable, Codable, Equatable { public var currency: String public var price: Double public var prePrice: Double? public init(currency: String, price: Double, prePrice: Double?) { self.currency = currency self.price = price self.prePrice = prePrice } enum CodingKeys: String, CodingKey { case currency case price case prePrice = "pre_price" } } public struct Quantity: Decodable, Equatable { public var unit: QuantityUnit? public var size: QuantityRange public var pieces: QuantityRange public struct QuantityRange: Equatable { public var from: Double? public var to: Double? public init(from: Double?, to: Double?) { self.from = from self.to = to } } public init(unit: QuantityUnit?, size: QuantityRange, pieces: QuantityRange) { self.unit = unit self.size = size self.pieces = pieces } enum CodingKeys: String, CodingKey { case unit case size case pieces } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.unit = try? values.decode(QuantityUnit.self, forKey: .unit) if let sizeDict = try? values.decode([String: Double].self, forKey: .size) { self.size = QuantityRange(from: sizeDict["from"], to: sizeDict["to"]) } else { self.size = QuantityRange(from: nil, to: nil) } if let piecesDict = try? values.decode([String: Double].self, forKey: .pieces) { self.pieces = QuantityRange(from: piecesDict["from"], to: piecesDict["to"]) } else { self.pieces = QuantityRange(from: nil, to: nil) } } } public struct QuantityUnit: Decodable, Equatable { public var symbol: String public var siUnit: SIUnit public struct SIUnit: Decodable, Equatable { public var symbol: String public var factor: Double public init(symbol: String, factor: Double) { self.symbol = symbol self.factor = factor } } public init(symbol: String, siUnit: SIUnit) { self.symbol = symbol self.siUnit = siUnit } enum CodingKeys: String, CodingKey { case symbol case si } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.symbol = try values.decode(String.self, forKey: .symbol) self.siUnit = try values.decode(SIUnit.self, forKey: .si) } } } // MARK: - public struct Business_v2: Equatable { public typealias ID = BusinessId public var id: ID public var name: String public var website: URL? public var description: String? public var descriptionMarkdown: String? public var logoOnWhite: URL public var logoOnBrandColor: URL public var brandColorHex: String? public var country: String } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Business_v2: Identifiable { } extension Business_v2: Decodable { enum CodingKeys: String, CodingKey { case id case name case website case description case descriptionMarkdown = "description_markdown" case logoOnWhite = "logo" case colorStr = "color" case pageFlip = "pageflip" case country enum PageFlipKeys: String, CodingKey { case logo case colorStr = "color" } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.id = try values.decode(ID.self, forKey: .id) self.name = try values.decode(String.self, forKey: .name) self.website = try? values.decode(URL.self, forKey: .website) self.description = try? values.decode(String.self, forKey: .description) self.descriptionMarkdown = try? values.decode(String.self, forKey: .descriptionMarkdown) self.logoOnWhite = try values.decode(URL.self, forKey: .logoOnWhite) self.brandColorHex = try? values.decode(String.self, forKey: .colorStr) let pageflipValues = try values.nestedContainer(keyedBy: CodingKeys.PageFlipKeys.self, forKey: .pageFlip) self.logoOnBrandColor = try pageflipValues.decode(URL.self, forKey: .logo) self.country = (try values.decode(Country_v2.self, forKey: .country)).id } } #if canImport(UIKit) import UIKit extension Business_v2 { public var brandColor: UIColor? { brandColorHex.flatMap(UIColor.init(hex:)) } } #endif // MARK: - public struct Store_v2: Equatable { public typealias ID = StoreId public var id: ID public var street: String? public var city: String? public var zipCode: String? public var country: String public var coordinate: Coordinate public var businessId: Business_v2.ID public var branding: Branding_v2 public var openingHours: [OpeningHours_v2] public var contact: String? public init(id: ID, street: String?, city: String?, zipCode: String?, country: String, coordinate: Coordinate, businessId: Business_v2.ID, branding: Branding_v2, openingHours: [OpeningHours_v2], contact: String?) { self.id = id self.street = street self.city = city self.zipCode = zipCode self.country = country self.coordinate = coordinate self.businessId = businessId self.branding = branding self.openingHours = openingHours self.contact = contact } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Store_v2: Identifiable { } extension Store_v2: Decodable { enum CodingKeys: String, CodingKey { case id case street case city case zipCode = "zip_code" case country case latitude case longitude case dealerId = "dealer_id" case branding case openingHours = "opening_hours" case contact } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.id = try container.decode(Store_v2.ID.self, forKey: .id) self.street = try? container.decode(String.self, forKey: .street) self.city = try? container.decode(String.self, forKey: .city) self.zipCode = try? container.decode(String.self, forKey: .zipCode) self.country = (try container.decode(Country_v2.self, forKey: .country)).id let lat = try container.decode(Double.self, forKey: .latitude) let lng = try container.decode(Double.self, forKey: .longitude) self.coordinate = Coordinate(latitude: lat, longitude: lng) self.businessId = try container.decode(Business_v2.ID.self, forKey: .dealerId) self.branding = try container.decode(Branding_v2.self, forKey: .branding) self.openingHours = (try? container.decode([OpeningHours_v2].self, forKey: .openingHours)) ?? [] self.contact = try? container.decode(String.self, forKey: .contact) } } public struct OpeningHours_v2: Hashable { public enum Period: Hashable { case dayOfWeek(DayOfWeek) case dateRange(ClosedRange<Date>) public func contains(date: Date) -> Bool { var cal = Calendar(identifier: .gregorian) cal.firstWeekday = 2 // Monday switch self { case .dayOfWeek(let dayOfWeek): let weekDay = cal.component(.weekday, from: date) return dayOfWeek.weekdayComponent == weekDay case .dateRange(let dateRange): return dateRange.contains(date) } } } public enum DayOfWeek: String, CaseIterable, Hashable, Decodable { case sunday, monday, tuesday, wednesday, thursday, friday, saturday // sunday = 1 public init?(weekdayComponent: Int) { let allDays = Self.allCases guard weekdayComponent <= allDays.count else { return nil } self = allDays[weekdayComponent - 1] } // sunday = 1 public var weekdayComponent: Int { return (DayOfWeek.allCases.firstIndex(of: self) ?? 0) + 1 } // i.e. Monday public func localizedWeekdaySymbol(for locale: Locale = .autoupdatingCurrent) -> String { var cal = Calendar(identifier: .gregorian) cal.locale = locale return cal.weekdaySymbols[self.weekdayComponent - 1] } public func date(relativeTo date: Date = Date()) -> Date? { var cal = Calendar(identifier: .gregorian) cal.firstWeekday = 2 if cal.component(.weekday, from: date) == self.weekdayComponent { return date } else { // Get the next day matching this weekday let components = DateComponents(weekday: self.weekdayComponent) return cal.nextDate(after: date, matching: components, matchingPolicy: .nextTime) } } } public struct TimeOfDay: Hashable { public var hours: Int public var minutes: Int public var seconds: Int public init(string: String) { let components = string.components(separatedBy: ":").compactMap(Int.init) self.hours = components.count > 0 ? components[0] : 0 self.minutes = components.count > 1 ? components[1] : 0 self.seconds = components.count > 2 ? components[2] : 0 } public func date(on day: Date, usingCalendar: Calendar = .autoupdatingCurrent) -> Date? { return usingCalendar.date(bySettingHour: hours, minute: minutes, second: seconds, of: day) } public func toString() -> String { if hours == 23 && minutes == 59 { return "24:00" } return String(format: "%d:%02d", hours, minutes) } } public var period: Period public var opens: TimeOfDay? public var closes: TimeOfDay? public init(period: Period, opens: TimeOfDay?, closes: TimeOfDay?) { self.period = period self.opens = opens self.closes = closes } public func contains(date: Date) -> Bool { guard let openTime = opens, let closeTime = closes, period.contains(date: date) else { return false } let cal = Calendar(identifier: .gregorian) let openDate = cal.date(bySettingHour: openTime.hours, minute: openTime.minutes, second: openTime.seconds, of: date) ?? .distantPast let closeDate = cal.date(bySettingHour: closeTime.hours, minute: closeTime.minutes, second: closeTime.seconds, of: date) ?? .distantFuture return date >= openDate && date <= closeDate } } extension OpeningHours_v2: Decodable { enum CodingKeys: String, CodingKey { case dayOfWeek = "day_of_week" case validFrom = "valid_from" case validUntil = "valid_until" case opens case closes } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) if let validFrom = try? values.decode(Date.self, forKey: .validFrom), let validUntil = try? values.decode(Date.self, forKey: .validUntil) { self.period = .dateRange(min(validFrom, validUntil)...max(validFrom, validUntil)) } else if let dayOfWeek = try? values.decode(DayOfWeek.self, forKey: .dayOfWeek) { self.period = .dayOfWeek(dayOfWeek) } else { self.period = .dateRange(.distantPast ... .distantPast) } if let openHour = try? values.decode(String.self, forKey: .opens), let closeHour = try? values.decode(String.self, forKey: .closes) { self.opens = TimeOfDay(string: openHour) self.closes = TimeOfDay(string: closeHour) } } } /// Used to convert the v2 image response dictionary into a set of sized image urls public struct v2ImageURLs: Decodable { public let thumb: URL? public let view: URL? public let zoom: URL? public var imageURLSet: Set<ImageURL> { Set([ thumb.map({ ImageURL(url: $0, width: 177) }), view.map({ ImageURL(url: $0, width: 768) }), zoom.map({ ImageURL(url: $0, width: 1536) }) ].compactMap({ $0 })) } } /// Just needed for decoding purposes fileprivate struct Country_v2: Decodable { var id: String }
mit
a38e6b6f9293f1aa43dd14e26102d6f1
35.314554
218
0.60905
4.348763
false
false
false
false
michals92/iOS_skautIS
Pods/Locksmith/Pod/Classes/Locksmith.swift
2
13373
// // Locksmith.swift // // Created by Matthew Palmer on 26/10/2014. // Copyright (c) 2014 Colour Coding. All rights reserved. // import UIKit import Security public let LocksmithErrorDomain = "com.locksmith.error" public let LocksmithDefaultService = NSBundle.mainBundle().infoDictionary![kCFBundleIdentifierKey] as! String public class Locksmith: NSObject { // MARK: Perform request public class func performRequest(request: LocksmithRequest) -> (NSDictionary?, NSError?) { let type = request.type //var result: Unmanaged<AnyObject>? = nil var result: AnyObject? var status: OSStatus? var parsedRequest: NSMutableDictionary = parseRequest(request) var requestReference = parsedRequest as CFDictionaryRef switch type { case .Create: status = withUnsafeMutablePointer(&result) { SecItemAdd(requestReference, UnsafeMutablePointer($0)) } case .Read: status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(requestReference, UnsafeMutablePointer($0)) } case .Delete: status = SecItemDelete(requestReference) case .Update: status = Locksmith.performUpdate(requestReference, result: &result) default: status = nil } if let status = status { var statusCode = Int(status) let error = Locksmith.keychainError(forCode: statusCode) var resultsDictionary: NSDictionary? if result != nil { if type == .Read && status == errSecSuccess { if let data = result as? NSData { // Convert the retrieved data to a dictionary resultsDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSDictionary } } } return (resultsDictionary, error) } else { let code = LocksmithErrorCode.TypeNotFound.rawValue let message = internalErrorMessage(forCode: code) return (nil, NSError(domain: LocksmithErrorDomain, code: code, userInfo: ["message": message])) } } private class func performUpdate(request: CFDictionaryRef, inout result: AnyObject?) -> OSStatus { // We perform updates to the keychain by first deleting the matching object, then writing to it with the new value. SecItemDelete(request) // Even if the delete request failed (e.g. if the item didn't exist before), still try to save the new item. // If we get an error saving, we'll tell the user about it. var status: OSStatus = withUnsafeMutablePointer(&result) { SecItemAdd(request, UnsafeMutablePointer($0)) } return status } // MARK: Error Lookup enum ErrorMessage: String { case Allocate = "Failed to allocate memory." case AuthFailed = "Authorization/Authentication failed." case Decode = "Unable to decode the provided data." case Duplicate = "The item already exists." case InteractionNotAllowed = "Interaction with the Security Server is not allowed." case NoError = "No error." case NotAvailable = "No trust results are available." case NotFound = "The item cannot be found." case Param = "One or more parameters passed to the function were not valid." case Unimplemented = "Function or operation not implemented." } enum LocksmithErrorCode: Int { case RequestNotSet = 1 case TypeNotFound = 2 case UnableToClear = 3 } enum LocksmithErrorMessage: String { case RequestNotSet = "keychainRequest was not set." case TypeNotFound = "The type of request given was undefined." case UnableToClear = "Unable to clear the keychain" } class func keychainError(forCode statusCode: Int) -> NSError? { var error: NSError? if statusCode != Int(errSecSuccess) { let message = errorMessage(statusCode) // println("Keychain request failed. Code: \(statusCode). Message: \(message)") error = NSError(domain: LocksmithErrorDomain, code: statusCode, userInfo: ["message": message]) } return error } // MARK: Private methods private class func internalErrorMessage(forCode statusCode: Int) -> NSString { switch statusCode { case LocksmithErrorCode.RequestNotSet.rawValue: return LocksmithErrorMessage.RequestNotSet.rawValue case LocksmithErrorCode.UnableToClear.rawValue: return LocksmithErrorMessage.UnableToClear.rawValue default: return "Error message for code \(statusCode) not set" } } private class func parseRequest(request: LocksmithRequest) -> NSMutableDictionary { var parsedRequest = NSMutableDictionary() var options = [String: AnyObject?]() options[String(kSecAttrAccount)] = request.userAccount options[String(kSecAttrAccessGroup)] = request.group options[String(kSecAttrService)] = request.service options[String(kSecAttrSynchronizable)] = request.synchronizable options[String(kSecClass)] = securityCode(request.securityClass) if let accessibleMode = request.accessible { options[String(kSecAttrAccessible)] = accessible(accessibleMode) } for (key, option) in options { parsedRequest.setOptional(option, forKey: key) } switch request.type { case .Create: parsedRequest = parseCreateRequest(request, inDictionary: parsedRequest) case .Delete: parsedRequest = parseDeleteRequest(request, inDictionary: parsedRequest) case .Update: parsedRequest = parseCreateRequest(request, inDictionary: parsedRequest) default: // case .Read: parsedRequest = parseReadRequest(request, inDictionary: parsedRequest) } return parsedRequest } private class func parseCreateRequest(request: LocksmithRequest, inDictionary dictionary: NSMutableDictionary) -> NSMutableDictionary { if let data = request.data { let encodedData = NSKeyedArchiver.archivedDataWithRootObject(data) dictionary.setObject(encodedData, forKey: String(kSecValueData)) } return dictionary } private class func parseReadRequest(request: LocksmithRequest, inDictionary dictionary: NSMutableDictionary) -> NSMutableDictionary { dictionary.setOptional(kCFBooleanTrue, forKey: String(kSecReturnData)) switch request.matchLimit { case .One: dictionary.setObject(kSecMatchLimitOne, forKey: String(kSecMatchLimit)) case .Many: dictionary.setObject(kSecMatchLimitAll, forKey: String(kSecMatchLimit)) } return dictionary } private class func parseDeleteRequest(request: LocksmithRequest, inDictionary dictionary: NSMutableDictionary) -> NSMutableDictionary { return dictionary } private class func errorMessage(code: Int) -> NSString { switch code { case Int(errSecAllocate): return ErrorMessage.Allocate.rawValue case Int(errSecAuthFailed): return ErrorMessage.AuthFailed.rawValue case Int(errSecDecode): return ErrorMessage.Decode.rawValue case Int(errSecDuplicateItem): return ErrorMessage.Duplicate.rawValue case Int(errSecInteractionNotAllowed): return ErrorMessage.InteractionNotAllowed.rawValue case Int(errSecItemNotFound): return ErrorMessage.NotFound.rawValue case Int(errSecNotAvailable): return ErrorMessage.NotAvailable.rawValue case Int(errSecParam): return ErrorMessage.Param.rawValue case Int(errSecSuccess): return ErrorMessage.NoError.rawValue case Int(errSecUnimplemented): return ErrorMessage.Unimplemented.rawValue default: return "Undocumented error with code \(code)." } } private class func securityCode(securityClass: SecurityClass) -> CFStringRef { switch securityClass { case .GenericPassword: return kSecClassGenericPassword case .Certificate: return kSecClassCertificate case .Identity: return kSecClassIdentity case .InternetPassword: return kSecClassInternetPassword case .Key: return kSecClassKey default: return kSecClassGenericPassword } } private class func accessible(accessible: Accessible) -> CFStringRef { switch accessible { case .WhenUnlock: return kSecAttrAccessibleWhenUnlocked case .AfterFirstUnlock: return kSecAttrAccessibleAfterFirstUnlock case .Always: return kSecAttrAccessibleAlways case .WhenPasscodeSetThisDeviceOnly: return kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly case .WhenUnlockedThisDeviceOnly: return kSecAttrAccessibleWhenUnlockedThisDeviceOnly case .AfterFirstUnlockThisDeviceOnly: return kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly case .AlwaysThisDeviceOnly: return kSecAttrAccessibleAlwaysThisDeviceOnly } } } // MARK: Convenient Class Methods extension Locksmith { public class func saveData(data: Dictionary<String, String>, forUserAccount userAccount: String, inService service: String = LocksmithDefaultService) -> NSError? { let saveRequest = LocksmithRequest(userAccount: userAccount, requestType: .Create, data: data, service: service) let (dictionary, error) = Locksmith.performRequest(saveRequest) return error } public class func loadDataForUserAccount(userAccount: String, inService service: String = LocksmithDefaultService) -> (NSDictionary?, NSError?) { let readRequest = LocksmithRequest(userAccount: userAccount, service: service) return Locksmith.performRequest(readRequest) } public class func deleteDataForUserAccount(userAccount: String, inService service: String = LocksmithDefaultService) -> NSError? { let deleteRequest = LocksmithRequest(userAccount: userAccount, requestType: .Delete, service: service) let (dictionary, error) = Locksmith.performRequest(deleteRequest) return error } public class func updateData(data: Dictionary<String, String>, forUserAccount userAccount: String, inService service: String = LocksmithDefaultService) -> NSError? { let updateRequest = LocksmithRequest(userAccount: userAccount, requestType: .Update, data: data, service: service) let (dictionary, error) = Locksmith.performRequest(updateRequest) return error } public class func clearKeychain() -> NSError? { // Delete all of the keychain data of the given class func deleteDataForSecClass(secClass: CFTypeRef) -> NSError? { var request = NSMutableDictionary() request.setObject(secClass, forKey: String(kSecClass)) var status: OSStatus? = SecItemDelete(request as CFDictionaryRef) if let status = status { var statusCode = Int(status) return Locksmith.keychainError(forCode: statusCode) } return nil } // For each of the sec class types, delete all of the saved items of that type let classes = [kSecClassGenericPassword, kSecClassInternetPassword, kSecClassCertificate, kSecClassKey, kSecClassIdentity] let errors: [NSError?] = classes.map({ return deleteDataForSecClass($0) }) // Remove those that were successful, or failed with an acceptable error code let filtered = errors.filter({ if let error = $0 { // There was an error // If the error indicates that there was no item with that sec class, that's fine. // Some of the sec classes will have nothing in them in most cases. return error.code != Int(errSecItemNotFound) ? true : false } // There was no error return false }) // If the filtered array is empty, then everything went OK if filtered.isEmpty { return nil } // At least one of the delete operations failed let code = LocksmithErrorCode.UnableToClear.rawValue let message = internalErrorMessage(forCode: code) return NSError(domain: LocksmithErrorDomain, code: code, userInfo: ["message": message]) } } // MARK: Dictionary Extensions extension NSMutableDictionary { func setOptional(optional: AnyObject?, forKey key: NSCopying) { if let object: AnyObject = optional { self.setObject(object, forKey: key) } } }
bsd-3-clause
a072b8831b1ad06e82e780505e6505a6
39.896024
169
0.644881
5.712516
false
false
false
false
crazypoo/PTools
Pods/PhoneNumberKit/PhoneNumberKit/PhoneNumberKit.swift
1
15629
// // PhoneNumberKit.swift // PhoneNumberKit // // Created by Roy Marmelstein on 03/10/2015. // Copyright © 2021 Roy Marmelstein. All rights reserved. // import Foundation #if os(iOS) import CoreTelephony #endif public typealias MetadataCallback = (() throws -> Data?) public final class PhoneNumberKit: NSObject { // Manager objects let metadataManager: MetadataManager let parseManager: ParseManager let regexManager = RegexManager() // MARK: Lifecycle public init(metadataCallback: @escaping MetadataCallback = PhoneNumberKit.defaultMetadataCallback) { self.metadataManager = MetadataManager(metadataCallback: metadataCallback) self.parseManager = ParseManager(metadataManager: self.metadataManager, regexManager: self.regexManager) } // MARK: Parsing /// Parses a number string, used to create PhoneNumber objects. Throws. /// /// - Parameters: /// - numberString: the raw number string. /// - region: ISO 639 compliant region code. /// - ignoreType: Avoids number type checking for faster performance. /// - Returns: PhoneNumber object. public func parse(_ numberString: String, withRegion region: String = PhoneNumberKit.defaultRegionCode(), ignoreType: Bool = false) throws -> PhoneNumber { var numberStringWithPlus = numberString do { return try self.parseManager.parse(numberString, withRegion: region, ignoreType: ignoreType) } catch { if numberStringWithPlus.first != "+" { numberStringWithPlus = "+" + numberStringWithPlus } } return try self.parseManager.parse(numberStringWithPlus, withRegion: region, ignoreType: ignoreType) } /// Parses an array of number strings. Optimised for performance. Invalid numbers are ignored in the resulting array /// /// - parameter numberStrings: array of raw number strings. /// - parameter region: ISO 639 compliant region code. /// - parameter ignoreType: Avoids number type checking for faster performance. /// /// - returns: array of PhoneNumber objects. public func parse(_ numberStrings: [String], withRegion region: String = PhoneNumberKit.defaultRegionCode(), ignoreType: Bool = false, shouldReturnFailedEmptyNumbers: Bool = false) -> [PhoneNumber] { return self.parseManager.parseMultiple(numberStrings, withRegion: region, ignoreType: ignoreType, shouldReturnFailedEmptyNumbers: shouldReturnFailedEmptyNumbers) } // MARK: Checking /// Checks if a number string is a valid PhoneNumber object /// /// - Parameters: /// - numberString: the raw number string. /// - region: ISO 639 compliant region code. /// - ignoreType: Avoids number type checking for faster performance. /// - Returns: Bool public func isValidPhoneNumber(_ numberString: String, withRegion region: String = PhoneNumberKit.defaultRegionCode(), ignoreType: Bool = false) -> Bool { return (try? self.parse(numberString, withRegion: region, ignoreType: ignoreType)) != nil } // MARK: Formatting /// Formats a PhoneNumber object for dispaly. /// /// - parameter phoneNumber: PhoneNumber object. /// - parameter formatType: PhoneNumberFormat enum. /// - parameter prefix: whether or not to include the prefix. /// /// - returns: Formatted representation of the PhoneNumber. public func format(_ phoneNumber: PhoneNumber, toType formatType: PhoneNumberFormat, withPrefix prefix: Bool = true) -> String { if formatType == .e164 { let formattedNationalNumber = phoneNumber.adjustedNationalNumber() if prefix == false { return formattedNationalNumber } return "+\(phoneNumber.countryCode)\(formattedNationalNumber)" } else { let formatter = Formatter(phoneNumberKit: self) let regionMetadata = self.metadataManager.mainTerritoryByCode[phoneNumber.countryCode] let formattedNationalNumber = formatter.format(phoneNumber: phoneNumber, formatType: formatType, regionMetadata: regionMetadata) if formatType == .international, prefix == true { return "+\(phoneNumber.countryCode) \(formattedNationalNumber)" } else { return formattedNationalNumber } } } // MARK: Country and region code /// Get a list of all the countries in the metadata database /// /// - returns: An array of ISO 639 compliant region codes. public func allCountries() -> [String] { let results = self.metadataManager.territories.map { $0.codeID } return results } /// Get an array of ISO 639 compliant region codes corresponding to a given country code. /// /// - parameter countryCode: international country code (e.g 44 for the UK). /// /// - returns: optional array of ISO 639 compliant region codes. public func countries(withCode countryCode: UInt64) -> [String]? { let results = self.metadataManager.filterTerritories(byCode: countryCode)?.map { $0.codeID } return results } /// Get an main ISO 639 compliant region code for a given country code. /// /// - parameter countryCode: international country code (e.g 1 for the US). /// /// - returns: ISO 639 compliant region code string. public func mainCountry(forCode countryCode: UInt64) -> String? { let country = self.metadataManager.mainTerritory(forCode: countryCode) return country?.codeID } /// Get an international country code for an ISO 639 compliant region code /// /// - parameter country: ISO 639 compliant region code. /// /// - returns: international country code (e.g. 33 for France). public func countryCode(for country: String) -> UInt64? { let results = self.metadataManager.filterTerritories(byCountry: country)?.countryCode return results } /// Get leading digits for an ISO 639 compliant region code. /// /// - parameter country: ISO 639 compliant region code. /// /// - returns: leading digits (e.g. 876 for Jamaica). public func leadingDigits(for country: String) -> String? { let leadingDigits = self.metadataManager.filterTerritories(byCountry: country)?.leadingDigits return leadingDigits } /// Determine the region code of a given phone number. /// /// - parameter phoneNumber: PhoneNumber object /// /// - returns: Region code, eg "US", or nil if the region cannot be determined. public func getRegionCode(of phoneNumber: PhoneNumber) -> String? { return self.parseManager.getRegionCode(of: phoneNumber.nationalNumber, countryCode: phoneNumber.countryCode, leadingZero: phoneNumber.leadingZero) } /// Get an example phone number for an ISO 639 compliant region code. /// /// - parameter countryCode: ISO 639 compliant region code. /// - parameter type: The `PhoneNumberType` desired. default: `.mobile` /// /// - returns: An example phone number public func getExampleNumber(forCountry countryCode: String, ofType type: PhoneNumberType = .mobile) -> PhoneNumber? { let metadata = self.metadata(for: countryCode) let example: String? switch type { case .fixedLine: example = metadata?.fixedLine?.exampleNumber case .mobile: example = metadata?.mobile?.exampleNumber case .fixedOrMobile: example = metadata?.mobile?.exampleNumber case .pager: example = metadata?.pager?.exampleNumber case .personalNumber: example = metadata?.personalNumber?.exampleNumber case .premiumRate: example = metadata?.premiumRate?.exampleNumber case .sharedCost: example = metadata?.sharedCost?.exampleNumber case .tollFree: example = metadata?.tollFree?.exampleNumber case .voicemail: example = metadata?.voicemail?.exampleNumber case .voip: example = metadata?.voip?.exampleNumber case .uan: example = metadata?.uan?.exampleNumber case .unknown: return nil case .notParsed: return nil } do { return try example.flatMap { try parse($0, withRegion: countryCode, ignoreType: false) } } catch { print("[PhoneNumberKit] Failed to parse example number for \(countryCode) region") return nil } } /// Get a formatted example phone number for an ISO 639 compliant region code. /// /// - parameter countryCode: ISO 639 compliant region code. /// - parameter type: `PhoneNumberType` desired. default: `.mobile` /// - parameter format: `PhoneNumberFormat` to use for formatting. default: `.international` /// - parameter prefix: Whether or not to include the prefix. /// /// - returns: A formatted example phone number public func getFormattedExampleNumber( forCountry countryCode: String, ofType type: PhoneNumberType = .mobile, withFormat format: PhoneNumberFormat = .international, withPrefix prefix: Bool = true ) -> String? { return self.getExampleNumber(forCountry: countryCode, ofType: type) .flatMap { self.format($0, toType: format, withPrefix: prefix) } } /// Get the MetadataTerritory objects for an ISO 639 compliant region code. /// /// - parameter country: ISO 639 compliant region code (e.g "GB" for the UK). /// /// - returns: A MetadataTerritory object, or nil if no metadata was found for the country code public func metadata(for country: String) -> MetadataTerritory? { return self.metadataManager.filterTerritories(byCountry: country) } /// Get an array of MetadataTerritory objects corresponding to a given country code. /// /// - parameter countryCode: international country code (e.g 44 for the UK) public func metadata(forCode countryCode: UInt64) -> [MetadataTerritory]? { return self.metadataManager.filterTerritories(byCode: countryCode) } /// Get an array of possible phone number lengths for the country, as specified by the parameters. /// /// - parameter country: ISO 639 compliant region code. /// - parameter phoneNumberType: PhoneNumberType enum. /// - parameter lengthType: PossibleLengthType enum. /// /// - returns: Array of possible lengths for the country. May be empty. public func possiblePhoneNumberLengths(forCountry country: String, phoneNumberType: PhoneNumberType, lengthType: PossibleLengthType) -> [Int] { guard let territory = metadataManager.filterTerritories(byCountry: country) else { return [] } let possibleLengths = possiblePhoneNumberLengths(forTerritory: territory, phoneNumberType: phoneNumberType) switch lengthType { case .national: return possibleLengths?.national.flatMap { self.parsePossibleLengths($0) } ?? [] case .localOnly: return possibleLengths?.localOnly.flatMap { self.parsePossibleLengths($0) } ?? [] } } private func possiblePhoneNumberLengths(forTerritory territory: MetadataTerritory, phoneNumberType: PhoneNumberType) -> MetadataPossibleLengths? { switch phoneNumberType { case .fixedLine: return territory.fixedLine?.possibleLengths case .mobile: return territory.mobile?.possibleLengths case .pager: return territory.pager?.possibleLengths case .personalNumber: return territory.personalNumber?.possibleLengths case .premiumRate: return territory.premiumRate?.possibleLengths case .sharedCost: return territory.sharedCost?.possibleLengths case .tollFree: return territory.tollFree?.possibleLengths case .voicemail: return territory.voicemail?.possibleLengths case .voip: return territory.voip?.possibleLengths case .uan: return territory.uan?.possibleLengths case .fixedOrMobile: return nil // caller needs to combine results for .fixedLine and .mobile case .unknown: return nil case .notParsed: return nil } } /// Parse lengths string into array of Int, e.g. "6,[8-10]" becomes [6,8,9,10] private func parsePossibleLengths(_ lengths: String) -> [Int] { let components = lengths.components(separatedBy: ",") let results = components.reduce([Int](), { result, component in let newComponents = parseLengthComponent(component) return result + newComponents }) return results } /// Parses numbers and ranges into array of Int private func parseLengthComponent(_ component: String) -> [Int] { if let int = Int(component) { return [int] } else { let trimmedComponent = component.trimmingCharacters(in: CharacterSet(charactersIn: "[]")) let rangeLimits = trimmedComponent.components(separatedBy: "-").compactMap { Int($0) } guard rangeLimits.count == 2, let rangeStart = rangeLimits.first, let rangeEnd = rangeLimits.last else { return [] } return Array(rangeStart...rangeEnd) } } // MARK: Class functions /// Get a user's default region code /// /// - returns: A computed value for the user's current region - based on the iPhone's carrier and if not available, the device region. public class func defaultRegionCode() -> String { #if os(iOS) && !targetEnvironment(simulator) && !targetEnvironment(macCatalyst) let networkInfo = CTTelephonyNetworkInfo() var carrier: CTCarrier? = nil if #available(iOS 12.0, *) { carrier = networkInfo.serviceSubscriberCellularProviders?.values.compactMap({ $0 }).first } else { carrier = networkInfo.subscriberCellularProvider } if let isoCountryCode = carrier?.isoCountryCode { return isoCountryCode.uppercased() } #endif let currentLocale = Locale.current if #available(iOS 10.0, *), let countryCode = currentLocale.regionCode { return countryCode.uppercased() } else { if let countryCode = (currentLocale as NSLocale).object(forKey: .countryCode) as? String { return countryCode.uppercased() } } return PhoneNumberConstants.defaultCountry } /// Default metadta callback, reads metadata from PhoneNumberMetadata.json file in bundle /// /// - returns: an optional Data representation of the metadata. public static func defaultMetadataCallback() throws -> Data? { let frameworkBundle = Bundle.module guard let jsonPath = frameworkBundle.path(forResource: "PhoneNumberMetadata", ofType: "json") else { throw PhoneNumberError.metadataNotFound } let data = try Data(contentsOf: URL(fileURLWithPath: jsonPath)) return data } } #if canImport(UIKit) extension PhoneNumberKit { /// Configuration for the CountryCodePicker presented from PhoneNumberTextField if `withDefaultPickerUI` is `true` public enum CountryCodePicker { /// Common Country Codes are shown below the Current section in the CountryCodePicker by default public static var commonCountryCodes: [String] = [] /// When the Picker is shown from the textfield it is presented modally public static var forceModalPresentation: Bool = false } } #endif
mit
b0ef486314354c53df1f7fb5d2440427
44.16763
203
0.668608
4.948702
false
false
false
false
DannyVancura/SwifTrix
SwifTrix/Network+Database/STJSONParser.swift
1
5314
// // STJSONParser.swift // SwifTrix // // The MIT License (MIT) // // Copyright © 2015 Daniel Vancura // // 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 /** A function to parse some object from a JSON object. This is simply a function of type (jsonObject: AnyObject) throws -> AnyObject? */ public typealias STJSONParsingFunction = (AnyObject) throws -> (AnyObject?) /** A JSON parser can use STJSONPackages or Dictionaries of kind [String:AnyObject] and parses any kind of objects from them. Example: ``` let jsonDict: [String:AnyObject] = ["Branch":5] let jsonParser = STJSONParser() jsonParser.registerFactoryMethod({print($0); return $0}, forKey: "Branch") try jsonParser.parse(dictionary: jsonDict) // Prints "5" and returns [5] ``` */ public class STJSONParser: NSObject { // MARK: - // MARK: Public variables public private(set) var parsedObjects: [AnyObject] // MARK: Private variables private var factoryMethods : [String:STJSONParsingFunction] // MARK: - // MARK: Initialization public override init() { self.parsedObjects = [] self.factoryMethods = [:] } // MARK: - // MARK: Setup for parsing /** Registers a factory method for a certain key. If parse() encounters the specified key, the factory method is called with this branch to create an object that is stored in parsedObjects. Example: ``` let jsonDict: [String:AnyObject] = ["Branch":5] let jsonParser = STJSONParser() jsonParser.registerFactoryMethod({print($0); return $0}, forKey: "Branch") try jsonParser.parse(dictionary: jsonDict) // Prints "5" and returns [5] ``` - parameter factoryMethod: a factory method that takes the branch of a JSON object */ public func registerFactoryMethod(factoryMethod: STJSONParsingFunction, forKey key: String) { self.factoryMethods.updateValue(factoryMethod, forKey: key) } /** Unregisters the factory method that is registered for the specified key. - parameter key: The key for the factory method that should be deleted */ public func unregisterFactoryMethodForKey(key: String) { self.factoryMethods.removeValueForKey(key) } // MARK: - // MARK: Parsing /** Parses a dictionary and creates objects with the registered factory methods. Example: ``` let jsonDict: [String:AnyObject] = ["Branch":5] let jsonParser = STJSONParser() jsonParser.registerFactoryMethod({print($0); return $0}, forKey: "Branch") try jsonParser.parse(dictionary: jsonDict) // Prints "5" and returns [5] ``` - parameter dictionary: the dictionary that should be parsed for contained objects - returns: an array of all objects that were parsed during this call of parse(...).</br>**Important:** This is not equal to *parsedObjects*, which contains the values that were parsed during all calls to *parse(...)*. - throws: any error that you throw in registered factory methods. Be aware that this cancels parsing right as soon as the error occurs */ public func parse(dictionary dict: [String:AnyObject]) throws -> [AnyObject] { var parsed: [AnyObject] = [] // Parse each key for key in dict.keys { guard let value = dict[key] else { continue } // If there is a parsing function that handles this key, call it if let parsingFunction: STJSONParsingFunction = self.factoryMethods[key] { if let parsedObject = try parsingFunction(value) { parsed.append(parsedObject) } } } self.parsedObjects.appendContentsOf(parsed) return parsed } /** Parses a JSON package and creates objects with the registered factory methods. - parameter jsonPackage: the JSON package that should be parsed for contained objects */ public func parse(jsonPackage jsonPackage: STJSONPackage) throws -> [AnyObject] { let attributes: [String:AnyObject] = jsonPackage.attributes return try self.parse(dictionary: attributes) } }
mit
ca3a8792e3fccd26d6cf4f6ebf3b3087
36.680851
189
0.673254
4.68932
false
false
false
false