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
ExTEnS10N/USMenuBar
USMenuBar.swift
1
7136
// // USMenuBar.swift // UsayUI // // Created by macsjh on 16/2/17. // Copyright © 2016年 TurboExtension. All rights reserved. // import UIKit protocol USMenuBarDataSource:class{ func numberOfItemInMenuBar(menuBar:USMenuBar) -> Int func uSMenuBar(menuBar:USMenuBar, titleForItemAtIndex index:Int) -> String } @objc protocol USMenuBarDelegate:class{ optional func uSMenuBar(menuBar:USMenuBar, willSelectRowAtIndex index:Int) optional func uSMenuBar(menuBar:USMenuBar, didSelectRowAtIndex index:Int) } class USMenuBar: UIView { private var _dataSource:USMenuBarDataSource? {didSet{setNeedsDisplay()}} var dataSource:USMenuBarDataSource?{ get{return _dataSource} set{_dataSource = newValue} } private var _delegate:USMenuBarDelegate? var delegate:USMenuBarDelegate?{ get{return _delegate} set{_delegate = newValue} } private let slider = UIView() private var sliderCenter:NSLayoutConstraint? private var sliderWidth:NSLayoutConstraint? private var _selectedIndex:Int = -1 var selectedIndex:Int{ get{return _selectedIndex} set{ slideToItem(indexOfItemToSlide: newValue, animated: true) } } func reloadData(){ for (var i = 0; i < self.subviews.count; ++i){ self.subviews[i].removeFromSuperview() } guard dataSource != nil else{return} let itemsCount = dataSource!.numberOfItemInMenuBar(self) guard itemsCount != 0 else {return} for (var i = 0; i < itemsCount; ++i){ let button = UIButton(type: .Custom) button.backgroundColor = self.backgroundColor button.setTitle(dataSource?.uSMenuBar(self, titleForItemAtIndex: i), forState: .Normal) button.setTitleColor(UIColor(white: 0.67, alpha: 1.0), forState: .Normal) button.tag = 154 + i button.addTarget(self, action: "prepareForSelectedItem:", forControlEvents: .TouchUpInside) button.translatesAutoresizingMaskIntoConstraints = false self.addSubview(button) let width = NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: self.bounds.width / CGFloat(itemsCount)) let height = NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: self.bounds.height) let leading = NSLayoutConstraint(item: button, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: (self.bounds.width * CGFloat(i)) / CGFloat(itemsCount)) let top = NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0) self.addConstraints([width, height, leading, top]) } _selectedIndex = 154 let firstButton = self.viewWithTag(_selectedIndex) as! UIButton firstButton.setTitleColor(self.tintColor, forState: .Normal) slider.frame = CGRect(x: 0.0, y: self.bounds.height - 5, width: firstButton.bounds.width, height: 5.0) slider.backgroundColor = self.tintColor slider.translatesAutoresizingMaskIntoConstraints = false self.addSubview(slider) sliderWidth = NSLayoutConstraint(item: slider, attribute: .Width, relatedBy: .Equal, toItem: firstButton.titleLabel, attribute: .Width, multiplier: 1.0, constant: 0) sliderCenter = NSLayoutConstraint(item: slider, attribute: .CenterX, relatedBy: .Equal, toItem: firstButton, attribute: .CenterX, multiplier: 1.0, constant: 0) let sliderHeight = NSLayoutConstraint(item: slider, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 5) let sliderBottom = NSLayoutConstraint(item: slider, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0) self.addConstraints([sliderWidth!, sliderCenter!, sliderHeight, sliderBottom]) } /// 滑动变更当前选中项到其隔壁项,并限定滑动进度,无动画效果 /// /// - parameter leftNeighbourOrNot: 前往左隔壁还是右隔壁,true为左,否则为右 /// - parameter progress: 滑动进度 func slideToNeighbourOnProgress(leftNeighbourOrNot isLeft:Bool, progress:CGFloat){ self.removeConstraints([sliderCenter!, sliderWidth!]) let lrIndex:Int = isLeft ? -1 : 1 guard let button = self.viewWithTag(_selectedIndex + lrIndex) as? UIButton else {fatalError("The menu item sliding to is unexist")} sliderCenter = NSLayoutConstraint(item: slider, attribute: .CenterX, relatedBy: .Equal, toItem: button, attribute: .CenterX, multiplier: 1.0, constant: 0.0) sliderWidth = NSLayoutConstraint(item: slider, attribute: .Width, relatedBy: .Equal, toItem: button.titleLabel, attribute: .Width, multiplier: 1.0, constant: 0) self.addConstraints([sliderCenter!, sliderWidth!]) self.layoutIfNeeded() _selectedIndex = _selectedIndex + lrIndex } /// 滑动到指定索引值的菜单项 /// /// - parameter indexOfItemToSlide: 菜单项索引值 /// - parameter animated: 是否播放滑动动画 func slideToItem(indexOfItemToSlide index:Int, animated: Bool){ guard let button = self.viewWithTag(index + 154) as? UIButton else {fatalError("The menu item sliding to is unexist")} self.removeConstraints([sliderCenter!, sliderWidth!]) sliderCenter = NSLayoutConstraint(item: slider, attribute: .CenterX, relatedBy: .Equal, toItem: button, attribute: .CenterX, multiplier: 1.0, constant: 0.0) sliderWidth = NSLayoutConstraint(item: slider, attribute: .Width, relatedBy: .Equal, toItem: button.titleLabel, attribute: .Width, multiplier: 1.0, constant: 0) self.addConstraints([sliderCenter!, sliderWidth!]) if animated{ UIView.animateWithDuration( 0.25, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in self.layoutIfNeeded() }, completion: nil ) } _selectedIndex = index } func prepareForSelectedItem(button:UIButton){ guard delegate != nil else{return} delegate?.uSMenuBar?(self, willSelectRowAtIndex: button.tag - 154) for perView in self.subviews{ if perView.isKindOfClass(UIButton){ let perButton = perView as! UIButton perButton.setTitleColor(UIColor(white: 0.67, alpha: 1.0), forState: .Normal) } } self.removeConstraints([sliderCenter!, sliderWidth!]) sliderCenter = NSLayoutConstraint(item: slider, attribute: .CenterX, relatedBy: .Equal, toItem: button, attribute: .CenterX, multiplier: 1.0, constant: 0.0) sliderWidth = NSLayoutConstraint(item: slider, attribute: .Width, relatedBy: .Equal, toItem: button.titleLabel, attribute: .Width, multiplier: 1.0, constant: 0) self.addConstraints([sliderCenter!, sliderWidth!]) UIView.animateWithDuration( 0.25, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in self.layoutIfNeeded() }, completion: { (Bool) -> Void in button.setTitleColor(self.tintColor, forState: .Normal) self.delegate?.uSMenuBar?(self, didSelectRowAtIndex: button.tag - 154) }) } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { reloadData() } }
unlicense
e88e8315e800cfa64b0ed97f19b5a546
41.567073
207
0.737287
3.747182
false
false
false
false
solidcell/Laurine
Example/Laurine/Classes/Views/Cells/ContributorCell.swift
2
2250
// // PersonCell.swift // Laurine Example Project // // Created by Jiří Třečák. // Copyright © 2015 Jiri Trecak. All rights reserved. // // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Imports import Foundation import UIKit import Haneke // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Definitions // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Extension // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Protocols // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Implementation class ContributorCell: UITableViewCell { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Properties @IBOutlet fileprivate weak var personNameLb : UILabel! @IBOutlet fileprivate weak var personContributions : UILabel! @IBOutlet fileprivate weak var personIconIV : UIImageView! // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Public // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Actions func configureWithContributor(_ contributor : Contributor) { // Set username self.personNameLb.text = contributor.username // Set number of contribution self.personContributions.text = contributor.contributions == 1 ? Localizations.Contributors.Contributor.Contributed.Singular : Localizations.Contributors.Contributor.Contributed.Plural(contributor.contributions) // Set profile picture, if available if let profilePictureURL = URL(string: contributor.avatarURL) { self.personIconIV.hnk_setImageFromURL(profilePictureURL) } } }
mit
d41be658798c7cc5dac5898c55a2b939
30.166667
114
0.381907
4.461233
false
false
false
false
huanghaisheng/HSSwiftExtensions
HSSwiftExtensions/HSSwiftExtensions/ColorExtension.swift
1
2166
// // ColorExtension.swift // SwiftExtensions // // Created by haisheng huang on 2016/11/1. // Copyright © 2016年 haisheng huang. All rights reserved. // import Foundation @available(iOS 8.0, *) public extension UIColor { //通过字符串“#fafafa”,“0xfafafa”获取颜色, alpha透明度,默认1.0 static func color(with hexString: String, alpha: Float) -> UIColor { var cString: String = hexString.trimmingCharacters(in: CharacterSet.whitespaces).uppercased() if cString.characters.count < 6 { return UIColor.white } if cString.hasPrefix("0X") { cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 2)) } if cString.hasPrefix("#") { cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 1)) } if cString.characters.count != 6 { return UIColor.white } var tempRange: Range = cString.startIndex..<cString.index(cString.startIndex, offsetBy: 2) let rString: String = cString.substring(with: tempRange) tempRange = cString.index(cString.startIndex, offsetBy: 2)..<cString.index(cString.startIndex, offsetBy: 4) let gString: String = cString.substring(with: tempRange) tempRange = cString.index(cString.startIndex, offsetBy: 4)..<cString.index(cString.startIndex, offsetBy: 6) let bString: String = cString.substring(with: tempRange) var red: uint = 0 var green: uint = 0 var blue: uint = 0 Scanner(string: rString).scanHexInt32(&red) Scanner(string: gString).scanHexInt32(&green) Scanner(string: bString).scanHexInt32(&blue) return UIColor.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: CGFloat(alpha)) } //通过字符串“#fafafa”,“0xfafafa”获取颜色 alpha透明度,默认1.0 static func color(with hexString: String) -> UIColor { return UIColor.color(with: hexString, alpha: 1.0) } }
mit
69fb40004c45e51f0edc6a325739fb8f
32.063492
131
0.6265
4.04466
false
false
false
false
icecrystal23/ios-charts
Source/Charts/Components/Legend.swift
2
14532
// // Legend.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 #if !os(OSX) import UIKit #endif @objc(ChartLegend) open class Legend: ComponentBase { @objc(ChartLegendForm) public enum Form: Int { /// Avoid drawing a form case none /// Do not draw the a form, but leave space for it case empty /// Use default (default dataset's form to the legend's form) case `default` /// Draw a square case square /// Draw a circle case circle /// Draw a horizontal line case line } @objc(ChartLegendHorizontalAlignment) public enum HorizontalAlignment: Int { case left case center case right } @objc(ChartLegendVerticalAlignment) public enum VerticalAlignment: Int { case top case center case bottom } @objc(ChartLegendOrientation) public enum Orientation: Int { case horizontal case vertical } @objc(ChartLegendDirection) public enum Direction: Int { case leftToRight case rightToLeft } /// The legend entries array @objc open var entries = [LegendEntry]() /// Entries that will be appended to the end of the auto calculated entries after calculating the legend. /// (if the legend has already been calculated, you will need to call notifyDataSetChanged() to let the changes take effect) @objc open var extraEntries = [LegendEntry]() /// Are the legend labels/colors a custom value or auto calculated? If false, then it's auto, if true, then custom. /// /// **default**: false (automatic legend) private var _isLegendCustom = false /// The horizontal alignment of the legend @objc open var horizontalAlignment: HorizontalAlignment = HorizontalAlignment.left /// The vertical alignment of the legend @objc open var verticalAlignment: VerticalAlignment = VerticalAlignment.bottom /// The orientation of the legend @objc open var orientation: Orientation = Orientation.horizontal /// Flag indicating whether the legend will draw inside the chart or outside @objc open var drawInside: Bool = false /// Flag indicating whether the legend will draw inside the chart or outside @objc open var isDrawInsideEnabled: Bool { return drawInside } /// The text direction of the legend @objc open var direction: Direction = Direction.leftToRight @objc open var font: NSUIFont = NSUIFont.systemFont(ofSize: 10.0) @objc open var textColor = NSUIColor.black /// The form/shape of the legend forms @objc open var form = Form.square /// The size of the legend forms @objc open var formSize = CGFloat(8.0) /// The line width for forms that consist of lines @objc open var formLineWidth = CGFloat(3.0) /// Line dash configuration for shapes that consist of lines. /// /// This is how much (in pixels) into the dash pattern are we starting from. @objc open var formLineDashPhase: CGFloat = 0.0 /// Line dash configuration for shapes that consist of lines. /// /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] @objc open var formLineDashLengths: [CGFloat]? @objc open var xEntrySpace = CGFloat(6.0) @objc open var yEntrySpace = CGFloat(0.0) @objc open var formToTextSpace = CGFloat(5.0) @objc open var stackSpace = CGFloat(3.0) @objc open var calculatedLabelSizes = [CGSize]() @objc open var calculatedLabelBreakPoints = [Bool]() @objc open var calculatedLineSizes = [CGSize]() public override init() { super.init() self.xOffset = 5.0 self.yOffset = 3.0 } @objc public init(entries: [LegendEntry]) { super.init() self.entries = entries } @objc open func getMaximumEntrySize(withFont font: NSUIFont) -> CGSize { var maxW = CGFloat(0.0) var maxH = CGFloat(0.0) var maxFormSize: CGFloat = 0.0 for entry in entries { let formSize = entry.formSize.isNaN ? self.formSize : entry.formSize if formSize > maxFormSize { maxFormSize = formSize } guard let label = entry.label else { continue } let size = (label as NSString).size(withAttributes: [.font: font]) if size.width > maxW { maxW = size.width } if size.height > maxH { maxH = size.height } } return CGSize( width: maxW + maxFormSize + formToTextSpace, height: maxH ) } @objc open var neededWidth = CGFloat(0.0) @objc open var neededHeight = CGFloat(0.0) @objc open var textWidthMax = CGFloat(0.0) @objc open var textHeightMax = CGFloat(0.0) /// flag that indicates if word wrapping is enabled /// this is currently supported only for `orientation == Horizontal`. /// you may want to set maxSizePercent when word wrapping, to set the point where the text wraps. /// /// **default**: true @objc open var wordWrapEnabled = true /// if this is set, then word wrapping the legend is enabled. @objc open var isWordWrapEnabled: Bool { return wordWrapEnabled } /// The maximum relative size out of the whole chart view in percent. /// If the legend is to the right/left of the chart, then this affects the width of the legend. /// If the legend is to the top/bottom of the chart, then this affects the height of the legend. /// /// **default**: 0.95 (95%) @objc open var maxSizePercent: CGFloat = 0.95 @objc open func calculateDimensions(labelFont: NSUIFont, viewPortHandler: ViewPortHandler) { let maxEntrySize = getMaximumEntrySize(withFont: labelFont) let defaultFormSize = self.formSize let stackSpace = self.stackSpace let formToTextSpace = self.formToTextSpace let xEntrySpace = self.xEntrySpace let yEntrySpace = self.yEntrySpace let wordWrapEnabled = self.wordWrapEnabled let entries = self.entries let entryCount = entries.count textWidthMax = maxEntrySize.width textHeightMax = maxEntrySize.height switch orientation { case .vertical: var maxWidth = CGFloat(0.0) var width = CGFloat(0.0) var maxHeight = CGFloat(0.0) let labelLineHeight = labelFont.lineHeight var wasStacked = false for i in 0 ..< entryCount { let e = entries[i] let drawingForm = e.form != .none let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize let label = e.label if !wasStacked { width = 0.0 } if drawingForm { if wasStacked { width += stackSpace } width += formSize } if label != nil { let size = (label! as NSString).size(withAttributes: [.font: labelFont]) if drawingForm && !wasStacked { width += formToTextSpace } else if wasStacked { maxWidth = max(maxWidth, width) maxHeight += labelLineHeight + yEntrySpace width = 0.0 wasStacked = false } width += size.width if i < entryCount - 1 { maxHeight += labelLineHeight + yEntrySpace } } else { wasStacked = true width += formSize if i < entryCount - 1 { width += stackSpace } } maxWidth = max(maxWidth, width) } neededWidth = maxWidth neededHeight = maxHeight case .horizontal: let labelLineHeight = labelFont.lineHeight let contentWidth: CGFloat = viewPortHandler.contentWidth * maxSizePercent // Prepare arrays for calculated layout if calculatedLabelSizes.count != entryCount { calculatedLabelSizes = [CGSize](repeating: CGSize(), count: entryCount) } if calculatedLabelBreakPoints.count != entryCount { calculatedLabelBreakPoints = [Bool](repeating: false, count: entryCount) } calculatedLineSizes.removeAll(keepingCapacity: true) // Start calculating layout let labelAttrs = [NSAttributedString.Key.font: labelFont] var maxLineWidth: CGFloat = 0.0 var currentLineWidth: CGFloat = 0.0 var requiredWidth: CGFloat = 0.0 var stackedStartIndex: Int = -1 for i in 0 ..< entryCount { let e = entries[i] let drawingForm = e.form != .none let label = e.label calculatedLabelBreakPoints[i] = false if stackedStartIndex == -1 { // we are not stacking, so required width is for this label only requiredWidth = 0.0 } else { // add the spacing appropriate for stacked labels/forms requiredWidth += stackSpace } // grouped forms have null labels if label != nil { calculatedLabelSizes[i] = (label! as NSString).size(withAttributes: labelAttrs) requiredWidth += drawingForm ? formToTextSpace + formSize : 0.0 requiredWidth += calculatedLabelSizes[i].width } else { calculatedLabelSizes[i] = CGSize() requiredWidth += drawingForm ? formSize : 0.0 if stackedStartIndex == -1 { // mark this index as we might want to break here later stackedStartIndex = i } } if label != nil || i == entryCount - 1 { let requiredSpacing = currentLineWidth == 0.0 ? 0.0 : xEntrySpace if (!wordWrapEnabled || // No word wrapping, it must fit. currentLineWidth == 0.0 || // The line is empty, it must fit. (contentWidth - currentLineWidth >= requiredSpacing + requiredWidth)) // It simply fits { // Expand current line currentLineWidth += requiredSpacing + requiredWidth } else { // It doesn't fit, we need to wrap a line // Add current line size to array calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight)) maxLineWidth = max(maxLineWidth, currentLineWidth) // Start a new line calculatedLabelBreakPoints[stackedStartIndex > -1 ? stackedStartIndex : i] = true currentLineWidth = requiredWidth } if i == entryCount - 1 { // Add last line size to array calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight)) maxLineWidth = max(maxLineWidth, currentLineWidth) } } stackedStartIndex = label != nil ? -1 : stackedStartIndex } neededWidth = maxLineWidth neededHeight = labelLineHeight * CGFloat(calculatedLineSizes.count) + yEntrySpace * CGFloat(calculatedLineSizes.count == 0 ? 0 : (calculatedLineSizes.count - 1)) } neededWidth += xOffset neededHeight += yOffset } /// MARK: - Custom legend /// Sets a custom legend's entries array. /// * A nil label will start a group. /// This will disable the feature that automatically calculates the legend entries from the datasets. /// Call `resetCustom(...)` to re-enable automatic calculation (and then `notifyDataSetChanged()` is needed). @objc open func setCustom(entries: [LegendEntry]) { self.entries = entries _isLegendCustom = true } /// Calling this will disable the custom legend entries (set by `setLegend(...)`). Instead, the entries will again be calculated automatically (after `notifyDataSetChanged()` is called). @objc open func resetCustom() { _isLegendCustom = false } /// **default**: false (automatic legend) /// - returns: `true` if a custom legend entries has been set @objc open var isLegendCustom: Bool { return _isLegendCustom } }
apache-2.0
8386294c5742a36212bb3883ae18d912
32.953271
190
0.523534
5.746145
false
false
false
false
varun-naharia/VNOfficeHourPicker
Example/VNOfficeHourPickerExample/Pods/VNOfficeHourPicker/VNOfficeHourPicker/VNOfficeHourPicker/VNOfficeHourViewController/VNOfficeHourViewController.swift
1
9082
// // VNOfficeHourViewController.swift // OfficeHourPicker // // Created by Varun Naharia on 14/07/17. // Copyright © 2017 Varun. All rights reserved. // import UIKit protocol VNOfficeHourViewDelegate { func save(arrData:[[String:Any]], numberOfRow:Int) } class VNOfficeHourViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK:- Delegate var delegate:VNOfficeHourViewDelegate? @IBOutlet weak var tableViewHours: UITableView! var rowCount = 1 var trueCount = 0 var arrayValuesForCell:[[String:Any]] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let bundle = Bundle(for: type(of: self)) tableViewHours.register(UINib(nibName: "VNOfficeHourTableViewCell", bundle: bundle), forCellReuseIdentifier: "Cell") if(!(arrayValuesForCell.count > 0)) { arrayValuesForCell = [ ["Mon":"false", "Tue":"false", "Wed":"false", "Thu":"false", "Fri":"false", "Sat":"false", "Sun":"false", "start":"", "end":""], ["Mon":"false", "Tue":"false", "Wed":"false", "Thu":"false", "Fri":"false", "Sat":"false", "Sun":"false", "start":"", "end":""], ["Mon":"false", "Tue":"false", "Wed":"false", "Thu":"false", "Fri":"false", "Sat":"false", "Sun":"false", "start":"", "end":""], ["Mon":"false", "Tue":"false", "Wed":"false", "Thu":"false", "Fri":"false", "Sat":"false", "Sun":"false", "start":"", "end":""], ["Mon":"false", "Tue":"false", "Wed":"false", "Thu":"false", "Fri":"false", "Sat":"false", "Sun":"false", "start":"", "end":""], ["Mon":"false", "Tue":"false", "Wed":"false", "Thu":"false", "Fri":"false", "Sat":"false", "Sun":"false", "start":"", "end":""], ["Mon":"false", "Tue":"false", "Wed":"false", "Thu":"false", "Fri":"false", "Sat":"false", "Sun":"false", "start":"", "end":""] ] } } 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. } */ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let bundle = Bundle(for: type(of: self)) let cell:VNOfficeHourTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! VNOfficeHourTableViewCell cell.btnMon.isEnabled = (arrayValuesForCell[indexPath.row]["Mon"] as! String != "nil") cell.btnTue.isEnabled = (arrayValuesForCell[indexPath.row]["Tue"] as! String != "nil") cell.btnWed.isEnabled = (arrayValuesForCell[indexPath.row]["Wed"] as! String != "nil") cell.btnThu.isEnabled = (arrayValuesForCell[indexPath.row]["Thu"] as! String != "nil") cell.btnFri.isEnabled = (arrayValuesForCell[indexPath.row]["Fri"] as! String != "nil") cell.btnSat.isEnabled = (arrayValuesForCell[indexPath.row]["Sat"] as! String != "nil") cell.btnSun.isEnabled = (arrayValuesForCell[indexPath.row]["Sun"] as! String != "nil") cell.btnMon.setImage((arrayValuesForCell[indexPath.row]["Mon"] as! String) == "true" ? UIImage(named: "checkboxselected", in: bundle, compatibleWith: nil) : UIImage(named: "checkbox", in: bundle, compatibleWith: nil), for: .normal) cell.btnTue.setImage((arrayValuesForCell[indexPath.row]["Tue"] as! String) == "true" ? UIImage(named: "checkboxselected", in: bundle, compatibleWith: nil) : UIImage(named: "checkbox", in: bundle, compatibleWith: nil), for: .normal) cell.btnWed.setImage((arrayValuesForCell[indexPath.row]["Wed"] as! String) == "true" ? UIImage(named: "checkboxselected", in: bundle, compatibleWith: nil) : UIImage(named: "checkbox", in: bundle, compatibleWith: nil), for: .normal) cell.btnThu.setImage((arrayValuesForCell[indexPath.row]["Thu"] as! String) == "true" ? UIImage(named: "checkboxselected", in: bundle, compatibleWith: nil) : UIImage(named: "checkbox", in: bundle, compatibleWith: nil), for: .normal) cell.btnFri.setImage((arrayValuesForCell[indexPath.row]["Fri"] as! String) == "true" ? UIImage(named: "checkboxselected", in: bundle, compatibleWith: nil) : UIImage(named: "checkbox", in: bundle, compatibleWith: nil), for: .normal) cell.btnSat.setImage((arrayValuesForCell[indexPath.row]["Sat"] as! String) == "true" ? UIImage(named: "checkboxselected", in: bundle, compatibleWith: nil) : UIImage(named: "checkbox", in: bundle, compatibleWith: nil), for: .normal) cell.btnSun.setImage((arrayValuesForCell[indexPath.row]["Sun"] as! String) == "true" ? UIImage(named: "checkboxselected", in: bundle, compatibleWith: nil) : UIImage(named: "checkbox", in: bundle, compatibleWith: nil), for: .normal) cell.txtStart.text = arrayValuesForCell[indexPath.row]["start"] as? String cell.txtEnd.text = arrayValuesForCell[indexPath.row]["end"] as? String cell.parentVC = self cell.indexPathRow = indexPath.row let datePickerView = UIDatePicker() datePickerView.datePickerMode = .time let toolBarStart = UIToolbar().addDoneButton() { if(cell.txtStart.text == "") { cell.startDate = datePickerView.date let dateFormatter = DateFormatter() // dateFormatter.timeZone = TimeZone(abbreviation: "GMT") dateFormatter.dateFormat = "hh:mm a" cell.txtStart.text = dateFormatter.string(from: datePickerView.date) self.arrayValuesForCell[indexPath.row]["start"] = cell.txtStart.text } self.view.endEditing(true) } let toolBarEnd = UIToolbar().addDoneButton() { if(cell.txtEnd.text == "") { cell.endDate = datePickerView.date let dateFormatter = DateFormatter() // dateFormatter.timeZone = TimeZone(abbreviation: "GMT") dateFormatter.dateFormat = "hh:mm a" cell.txtEnd.text = dateFormatter.string(from: datePickerView.date) self.arrayValuesForCell[indexPath.row]["end"] = cell.txtEnd.text } self.view.endEditing(true) } cell.txtStart.inputAccessoryView = toolBarStart cell.txtEnd.inputAccessoryView = toolBarEnd cell.txtStart.add(for: .editingDidBegin) { cell.txtStart.inputView = datePickerView if(cell.endDate != nil) { datePickerView.maximumDate = cell.endDate datePickerView.minimumDate = nil } datePickerView.add(for: .valueChanged, { if(cell.txtStart.isFirstResponder) { cell.startDate = datePickerView.date let dateFormatter = DateFormatter() // dateFormatter.timeZone = TimeZone(abbreviation: "GMT") dateFormatter.dateFormat = "hh:mm a" cell.txtStart.text = dateFormatter.string(from: datePickerView.date) self.arrayValuesForCell[indexPath.row]["start"] = cell.txtStart.text } }) } cell.txtEnd.add(for: .editingDidBegin) { cell.txtEnd.inputView = datePickerView if(cell.startDate != nil) { datePickerView.minimumDate = cell.startDate datePickerView.maximumDate = nil } datePickerView.add(for: .valueChanged, { if(cell.txtEnd.isFirstResponder) { cell.endDate = datePickerView.date let dateFormatter = DateFormatter() // dateFormatter.timeZone = TimeZone(abbreviation: "GMT") dateFormatter.dateFormat = "hh:mm a" cell.txtEnd.text = dateFormatter.string(from: datePickerView.date) self.arrayValuesForCell[indexPath.row]["end"] = cell.txtEnd.text } }) } return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rowCount } @IBAction func saveAction(_ sender: UIButton) { self.delegate?.save(arrData: arrayValuesForCell, numberOfRow: rowCount) self.dismiss(animated: true, completion: nil) } @IBAction func addMoreAction(_ sender: UIButton) { if(rowCount < 7 && trueCount < 7) { rowCount += 1 tableViewHours.reloadData() } } }
mit
c5de096b63e83598a279aa45bdc00f07
52.417647
239
0.600595
4.429756
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
MobilePeopleDirectory/ImageHelper.swift
1
2558
// // ImageHelper.swift // MobilePeopleDirectory // // Created by alejandro soto on 1/24/15. // Copyright (c) 2015 Rivet Logic. All rights reserved. // import UIKit import Foundation import CoreGraphics class ImageHelper: NSObject { private var _processedImages = [String: UIImage]() // Adds styles to list thubmnails func addThumbnailStyles(imageView: UIImageView!, radius: CGFloat!) { imageView?.layer.cornerRadius = radius imageView?.layer.masksToBounds = true imageView?.layer.borderColor = UIColor.lightGrayColor().CGColor imageView?.layer.borderWidth = 1.0 } // Adds blur style to bg portrait image func addBlurStyles(imageView: UIImageView!) { var ciContext = CIContext(options: nil) var image = CIImage(image: imageView?.image) var ciFilter = CIFilter(name: "CIGaussianBlur") ciFilter.setValue(image, forKey: kCIInputImageKey) ciFilter.setValue(1, forKey: "inputRadius") var cgImage = ciContext.createCGImage(ciFilter.outputImage, fromRect: image.extent()) var blurredImage = UIImage(CGImage: cgImage)! imageView?.image = blurredImage } // Convert to Gray Scale func convertImageToGrayScale(image: UIImage) -> UIImage { let imageRect: CGRect = CGRectMake(0, 0, image.size.width, image.size.height) let colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceGray(); let context:CGContextRef = CGBitmapContextCreate(nil, Int(image.size.width), Int(image.size.height), 8, 0, colorSpace, CGBitmapInfo(0)) CGContextDrawImage(context, imageRect, image.CGImage); let imageRef: CGImageRef = CGBitmapContextCreateImage(context); let newImage: UIImage = UIImage(CGImage: imageRef)! return newImage; } // add image to view from NSData func addImageFromData(imageView: UIImageView!, image: NSData!) { var image = UIImage(data: image!) imageView?.image = image } // get image data based on image url func getImageData(imageUrl: String) -> NSData { let url = NSURL(string: imageUrl) return NSData(contentsOfURL: url!)! } // verifies if image is default liferay image or custom portrait image, basically to avoid storing // default images on local storage func hasUserImage(userImage: NSString) -> Bool { return !userImage.containsString("img_id=0") && userImage.length > 0 } }
gpl-3.0
42c3f3b4739c4302fc88e0fb5d8e83a1
32.657895
143
0.658327
4.745826
false
false
false
false
Liqiankun/DLSwift
Swift/Swift3Twelve.playground/Contents.swift
1
422
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let supervieColor = #keyPath(UIView.superview.backgroundColor) let view = UIView(frame:CGRect(x: 0,y:0,width:100,height:100)) let label = UILabel(frame:CGRect(x :0,y:0,width:10,height:100)) view.backgroundColor = UIColor.blue view.addSubview(label) label.value(forKeyPath: supervieColor) label.superview?.backgroundColor
mit
a1ba834b46539b734373562a187ea614
27.2
63
0.770142
3.322835
false
false
false
false
duycao2506/SASCoffeeIOS
SAS CoffeeUITests/SAS_CoffeeUITests.swift
1
1574
// // SAS_CoffeeUITests.swift // SAS CoffeeUITests // // Created by Duy Cao on 8/30/17. // Copyright © 2017 Duy Cao. All rights reserved. // import XCTest class SAS_CoffeeUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. let app = XCUIApplication.init() let buttonGotit = app.buttons["Got it"] let exists = NSPredicate.init(format: "exists == true") expectation(for: exists, evaluatedWith: buttonGotit, handler: nil) waitForExpectations(timeout: 5, handler: nil) XCTAssert(buttonGotit.exists) } }
gpl-3.0
80ebb956b3511c08b974f5c984384e5e
35.534884
182
0.655633
4.703593
false
true
false
false
duycao2506/SASCoffeeIOS
SAS Coffee/Controller/HomeViewController.swift
1
7617
// // HomeViewController.swift // SAS Coffee // // Created by Duy Cao on 9/1/17. // Copyright © 2017 Duy Cao. All rights reserved. // import UIKit import SwiftPullToRefresh import FontAwesomeKit import PopupDialog import DrawerController import Firebase import FirebaseMessaging class HomeViewController: KasperTableViewController { var arrProfile : [Any]! var hashCell : [String] = [ TableViewCellIdetifier.basicInfoCell, TableViewCellIdetifier.pointCell, TableViewCellIdetifier.customerCodeCell, TableViewCellIdetifier.iconTitleCell ] static var NOTIFICATION_DATA : [String : Any] = [ "eventId" : -1, "newsId" : -1 ] override func viewDidLoad() { super.viewDidLoad() //MARK: Prepare ui self.title = "Home".localize() arrProfile = [ [GlobalUtils.getDefaultSizeImage(fakmat: FAKMaterialIcons.emailIcon(withSize: 24.0)), AppSetting.sharedInstance().mainUser.email], [GlobalUtils.getDefaultSizeImage(fakmat: FAKMaterialIcons.calendarIcon(withSize: 24.0)), AppSetting.sharedInstance().mainUser.birthday == nil ? "Not available".localize() : AppSetting.sharedInstance().mainUser.birthday?.string(custom: "dd/MM/yyyy") as Any], [GlobalUtils.getDefaultSizeImage(fakmat: FAKMaterialIcons.phoneIcon(withSize: 24.0)), AppSetting.sharedInstance().mainUser.phone], [GlobalUtils.getDefaultSizeImage(fakmat: FAKMaterialIcons.mapIcon(withSize: 24.0)), AppSetting.sharedInstance().mainUser.address]] //MARK: TableView Configuration self.tbView.rowHeight = UITableViewAutomaticDimension self.tbView.register(UINib.init(nibName: ViewNibNames.imageTitleCell, bundle: Bundle.main), forCellReuseIdentifier: TableViewCellIdetifier.iconTitleCell) self.view.startLoading(loadingView: GlobalUtils.getNVIndicatorView(color: Style.colorPrimary, type: .ballPulse), logo: #imageLiteral(resourceName: "logo.png"), tag: nil) RequestService.GET_news(memberType: AppSetting.sharedInstance().mainUser.userType, complete: { news -> Void in self.view.stopLoading(loadingViewTag: nil) if news != nil { // Prepare the popup assets let title = "Message for you".localize() let message = news as! String let image = UIImage.init(named: "splash_news") // Create the dialog let popup = PopupDialog(title: title, message: message, image: image) popup.transitionStyle = .bounceDown // Create buttons let buttonOK = DefaultButton(title: "Got it".localize()) { popup.dismiss() } buttonOK.titleLabel?.textColor = Style.colorSecondary // Add buttons to dialog // Alternatively, you can use popup.addButton(buttonOne) // to add a single button popup.addButton(buttonOK) // Present dialog self.present(popup, animated: true, completion: nil) } }) Messaging.messaging().subscribe(toTopic: AppSetting.sharedInstance().NOTI_ALL) Messaging.messaging().subscribe(toTopic: AppSetting.sharedInstance().NOTI_BRANCH + AppSetting.sharedInstance().mainUser.branchId.description) NotificationCenter.default.addObserver(self, selector: #selector(self.remoteNotiEvent(notification:)), name: NSNotification.Name(rawValue: EventConst.REMOTE_NOTI), object: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func remoteNotiEvent(notification : Notification){ if let eventId = notification.userInfo!["id"], (eventId as! NSString).integerValue > -1 { self.view.startLoading(loadingView: GlobalUtils.getNVIndicatorView(color: Style.colorPrimary, type: .ballPulse), logo: #imageLiteral(resourceName: "logo"), tag: 111) RequestService.GET_promo_by(userId: AppSetting.sharedInstance().mainUser.id.description, complete: { (data) in let resp = data as! [String : Any] let succ = resp["statuskey"] as! Bool if succ { let response = resp["promoList"] as! [[String:Any]] if let event = DataService.findEventByIdInPromotionList(id : (eventId as! NSString).integerValue, promotelistRaw: response) { let vc = AppStoryBoard.Promotion.instance.instantiateViewController(withIdentifier: VCIdentifiers.PromotionDetailVC.rawValue) as! PromotionDetailViewController vc.promotion = event self.present(vc, animated: true, completion: nil) HomeViewController.NOTIFICATION_DATA["eventId"] = -1 } } self.view.stopLoading(loadingViewTag: 111) }) } } deinit { NotificationCenter.default.removeObserver(self) } override func refreshData(){ RequestService.GET_login(endpoint: RequestService.GET_LOGIN_AUTO, token: AppSetting.sharedInstance().mainUser.token.toBase64(), complete: { data -> Void in DataService.assignUser(response: data as! [String : Any], vc: self) RealmWrapper.save(obj: AppSetting.sharedInstance().mainUser) self.tbView.spr_endRefreshing() }) } 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. } */ /** * Table view func */ func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 7 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print(indexPath.row) } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : SuperTableViewCell? = self.tbView.dequeueReusableCell(withIdentifier: hashCell[indexPath.row < 3 ? indexPath.row : 3]) as! SuperTableViewCell if cell is ImageTitleTableViewCell { cell?.updateData(anyObj: arrProfile[indexPath.row-3]) }else{ cell?.updateData(number: 0, str: "", obj: AppSetting.sharedInstance().mainUser) } return cell! } }
gpl-3.0
922c8e4e6b822135b6894e5dd42eeda1
38.05641
269
0.620273
5.053749
false
false
false
false
StevenUpForever/FBSimulatorControl
fbsimctl/FBSimulatorControlKit/Sources/Relay.swift
2
2399
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation import FBControlCore /** A Protocol for defining */ protocol Relay { func start() throws func stop() throws } /** A Relay that composes multiple relays. */ class CompositeRelay : Relay { let relays: [Relay] init(relays: [Relay]) { self.relays = relays } func start() throws { for relay in self.relays { try relay.start() } } func stop() throws { for relay in self.relays { // We want to stop all relays, so ignoring error propogation will ensure we clean up all of them. try? relay.stop() } } } /** Wraps an existing Relay, spinning the run loop after the underlying relay has started. */ class SynchronousRelay : Relay { let relay: Relay let reporter: EventReporter let awaitable: FBTerminationAwaitable? let started: (Void) -> Void init(relay: Relay, reporter: EventReporter, awaitable: FBTerminationAwaitable?, started: @escaping (Void) -> Void) { self.relay = relay self.reporter = reporter self.awaitable = awaitable self.started = started } func start() throws { // Setup the Signal Handling first, so sending a Signal cannot race with starting the relay. var signalled = false let handler = SignalHandler { info in self.reporter.reportSimple(.signalled, .discrete, info) signalled = true } handler.register() // Start the Relay and notify consumers. try self.relay.start() self.started() // Start the event loop. let awaitable = self.awaitable RunLoop.current.spinRunLoop(withTimeout: Double.greatestFiniteMagnitude, untilTrue: { // Check the awaitable (if present) if awaitable?.hasTerminated == true { return true } // Or return the current signal status. return signalled }) handler.unregister() } func stop() throws { try self.relay.stop() } } /** Bridges an Action Reader to a Relay */ extension FBiOSActionReader : Relay { func start() throws { try self.startListening() } func stop() throws { try self.stopListening() } }
bsd-3-clause
f339e2c11eec6c6dfe4e4f9c67171ab7
22.291262
118
0.671113
4.031933
false
false
false
false
gaolichuang/actor-platform
actor-apps/app-ios/ActorApp/Controllers Support/AANavigationController.swift
2
2065
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit class AANavigationController: UINavigationController { private let binder = Binder() override func viewDidLoad() { super.viewDidLoad() navigationBar.hideBottomHairline() view.backgroundColor = MainAppTheme.list.backyardColor // Enabling app state sync progress self.setPrimaryColor(MainAppTheme.navigation.progressPrimary) self.setSecondaryColor(MainAppTheme.navigation.progressSecondary) binder.bind(Actor.getAppState().isSyncing, valueModel2: Actor.getAppState().isConnecting) { (value1: JavaLangBoolean?, value2: JavaLangBoolean?) -> () in if value1!.booleanValue() || value2!.booleanValue() { self.showProgress() self.setIndeterminate(true) } else { self.finishProgress() } } } func makeBarTransparent() { navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) navigationBar.shadowImage = UIImage() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } } extension UINavigationBar { func hideBottomHairline() { let navigationBarImageView = hairlineImageViewInNavigationBar(self) navigationBarImageView!.hidden = true } func showBottomHairline() { let navigationBarImageView = hairlineImageViewInNavigationBar(self) navigationBarImageView!.hidden = false } private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? { if view.isKindOfClass(UIImageView) && view.bounds.height <= 1.0 { return (view as! UIImageView) } for subview: UIView in view.subviews { if let imageView: UIImageView = hairlineImageViewInNavigationBar(subview) { return imageView } } return nil } }
mit
6fcf46ecbb4ee00ab43becffd1c18442
30.30303
161
0.637288
5.551075
false
false
false
false
nestproject/Inquiline
Sources/Response.swift
1
1053
import Nest public struct Response : ResponseType { public var status:Status public var headers:[Header] public var body: PayloadType? public init(_ status:Status, headers:[Header]? = nil, contentType:String? = nil, content: PayloadConvertible? = nil) { self.status = status self.headers = headers ?? [] self.body = content?.toPayload() if let contentType = contentType { self.headers.append(("Content-Type", contentType)) } } public var statusLine:String { return status.description } public subscript(header: String) -> String? { get { return headers.filter { $0.0 == header }.first?.1 } set { if let newValue = newValue { headers.append((header, newValue)) } } } public var contentType:String? { get { return self["Content-Type"] } set { self["Content-Type"] = newValue } } public var cacheControl:String? { get { return self["Content-Type"] } set { self["Content-Type"] = newValue } } }
bsd-2-clause
608763c97a1d0358b55b0132b4a8afee
19.647059
120
0.607787
4.05
false
false
false
false
GrandCentralBoard/GrandCentralBoard
Pods/Operations/Sources/Core/Shared/ThreadSafety.swift
2
1821
// // ThreadSafety.swift // Operations // // Created by Daniel Thorpe on 14/02/2016. // // import Foundation protocol ReadWriteLock { mutating func read<T>(block: () -> T) -> T mutating func write(block: () -> Void, completion: (() -> Void)?) } extension ReadWriteLock { mutating func write(block: () -> Void) { write(block, completion: nil) } } struct Lock: ReadWriteLock { let queue = Queue.Initiated.concurrent("me.danthorpe.Operations.Lock") mutating func read<T>(block: () -> T) -> T { var object: T! dispatch_sync(queue) { object = block() } return object } mutating func write(block: () -> Void, completion: (() -> Void)?) { dispatch_barrier_async(queue) { block() if let completion = completion { dispatch_async(Queue.Main.queue, completion) } } } } internal class Protector<T> { private var lock: ReadWriteLock = Lock() private var ward: T init(_ ward: T) { self.ward = ward } func read<U>(block: T -> U) -> U { return lock.read { [unowned self] in block(self.ward) } } func write(block: (inout T) -> Void) { lock.write({ block(&self.ward) }) } func write(block: (inout T) -> Void, completion: (() -> Void)) { lock.write({ block(&self.ward) }, completion: completion) } } extension Protector where T: _ArrayType { func append(newElement: T.Generator.Element) { write({ (inout ward: T) in ward.append(newElement) }) } func appendContentsOf<S: SequenceType where S.Generator.Element == T.Generator.Element>(newElements: S) { write({ (inout ward: T) in ward.appendContentsOf(newElements) }) } }
gpl-3.0
691709b8c35b77df694c3bb6d9532d40
21.7625
109
0.564525
3.891026
false
false
false
false
tgyhlsb/iPath
iPath/iPath/Controllers/RouteDetailsViewController/RouteDetailsViewController+TableView.swift
1
1409
// // RouteDetailsViewController+TableView.swift // iPath // // Created by Tanguy Hélesbeux on 17/10/2016. // Copyright © 2016 Tanguy Helesbeux. All rights reserved. // import UIKit extension RouteDetailsViewController: UITableViewDataSource { // MARK: - PUBLIC - // MARK: - INTERNAL - internal func initializeTableView() { self.tableView.dataSource = self } internal func reloadTableView() { self.tableView.reloadData() } // MARK: - PRIVATE - // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let path = self.activePath else { return 0 } return path.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = "placeCell" var cell = tableView.dequeueReusableCell(withIdentifier: identifier) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: identifier) } cell?.textLabel?.text = self.place(for: indexPath)?.name return cell! } private func place(for indexPath: IndexPath) -> Place? { return self.activePath?[indexPath.row] } }
mit
fc1ab069c8dce722f70962b77f99853b
25.055556
100
0.624023
4.818493
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/IntroductionSheetViewController/IntroductionSheetViewModel.swift
1
628
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public struct IntroductionSheetViewModel { let title: String let description: String let thumbnail: UIImage let buttonTitle: String let onSelection: () -> Void public init( title: String, description: String, buttonTitle: String, thumbnail: UIImage, onSelection: @escaping () -> Void ) { self.title = title self.description = description self.buttonTitle = buttonTitle self.thumbnail = thumbnail self.onSelection = onSelection } }
lgpl-3.0
00f93449b116ea8b8107bd523b41cf0e
24.08
62
0.639553
5.139344
false
false
false
false
ankitthakur/LocationManager
LocationManager/Geocoder.swift
1
2605
// // Geocoder.swift // LocationManager // // Created by Ankit Thakur on 11/09/16. // Copyright © 2016 Ankit Thakur. All rights reserved. // import Foundation import CoreLocation let GEOCODER_TIMEOUT = 10 // in seconds public struct LocationError: Error { enum ErrorKind { case noAddress case reverseGeocode case noLocationFound } let kind: ErrorKind let message:String } internal class Geocoder: NSObject { var userLocation:CLLocation? var locationCallback: LocationCoorCallback? var geoCoder:CLGeocoder? var address:String = "" var event:EventType? var locationError:LocationError? func geocode(location:CLLocation, queue:DispatchQueue, eventType:EventType, callBack:@escaping LocationCoorCallback){ userLocation = location locationCallback = callBack event = eventType geoCoder = CLGeocoder() let group: DispatchGroup = DispatchGroup() group.enter() let timeout:DispatchTime = DispatchTime(uptimeNanoseconds: UInt64(GEOCODER_TIMEOUT*1000)) geoCoder?.reverseGeocodeLocation(userLocation!, completionHandler: { (placemarks:[CLPlacemark]?, error:Error?) in if error != nil { logger("Reverse geocoder failed with error: \(error!.localizedDescription)") self.locationError = LocationError(kind: .reverseGeocode, message: (error?.localizedDescription)!) // completion("[\(location.coordinate.latitude), \(location.coordinate.longitude)]") } if let placemarks = placemarks , placemarks.count > 0 { let placemark = placemarks[0] self.address = self.formalizedPlace(placemark: placemark) } else { self.locationError = LocationError(kind: .noAddress, message: "no placemark is found") } group.leave() }) _ = group.wait(timeout: timeout) group.notify(queue: queue) { queue.async { self.locationCallback!(self.userLocation, self.address, nil, self.event) } } } func formalizedPlace(placemark: CLPlacemark) -> String { let joiner = "|" if let lines = placemark.addressDictionary!["FormattedAddressLines"] as? [String] { return lines.joined(separator: joiner) }else{ return "" } } }
mit
49d3a58b4df6cce77c0cc8ba77d6c1ae
28.258427
121
0.588326
5.239437
false
false
false
false
zilaiyedaren/KRLCollectionViewGridLayout
Example/KRLCollectionViewGridLayoutDemo/GridLayoutCollectionViewController.swift
1
4366
// Copyright (c) 2015 Kevin Lundberg. import UIKit private let reuseIdentifier = "Cell" private let headerFooterIdentifier = "headerFooter" class GridLayoutCollectionViewController: UICollectionViewController, UIActionSheetDelegate { var layout: KRLCollectionViewGridLayout { return self.collectionView?.collectionViewLayout as! KRLCollectionViewGridLayout } override func viewDidLoad() { super.viewDidLoad() layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) let nib = UINib(nibName: "HeaderFooterView", bundle: nil) collectionView?.registerNib(nib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerFooterIdentifier) collectionView?.registerNib(nib, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: headerFooterIdentifier) } @IBAction func changeColumnsTapped(sender: AnyObject?) { let alert = UIAlertController(title: "Choose how many columns", message: nil, preferredStyle: .ActionSheet) for num in 1...6 { alert.addAction(UIAlertAction(title: num.description, style: .Default, handler: { action in self.layout.numberOfItemsPerLine = num })) } presentViewController(alert, animated: true, completion: nil) } // MARK: - UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 2 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 25 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UICollectionViewCell // Configure the cell if indexPath.section % 2 == 1 { cell.contentView.backgroundColor = UIColor.blueColor() } else { cell.contentView.backgroundColor = UIColor.redColor() } return cell } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: headerFooterIdentifier, forIndexPath: indexPath) as! HeaderFooterView view.label.text = kind return view } } extension GridLayoutCollectionViewController: KRLCollectionViewDelegateGridLayout { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { let inset = CGFloat((section + 1) * 10) return UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, interitemSpacingForSectionAtIndex section: Int) -> CGFloat { return CGFloat((section + 1) * 10) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, lineSpacingForSectionAtIndex section: Int) -> CGFloat { return CGFloat((section + 1) * 10) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceLengthForHeaderInSection section: Int) -> CGFloat { return CGFloat((section + 1) * 20) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceLengthForFooterInSection section: Int) -> CGFloat { return CGFloat((section + 1) * 20) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, numberItemsPerLineForSectionAtIndex section: Int) -> Int { return self.layout.numberOfItemsPerLine + (section * 1) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, aspectRatioForItemsInSectionAtIndex section: Int) -> CGFloat { return CGFloat(1 + section) } }
mit
64344a35aff3b9c522014b748b8f82f9
42.66
180
0.743014
6.030387
false
false
false
false
Flyreel/Player
Source/Player.swift
1
17281
// Player.swift // // Created by patrick piemonte on 11/26/14. // // The MIT License (MIT) // // Copyright (c) 2014-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 import CoreGraphics public enum PlaybackState: Int, CustomStringConvertible { case Stopped = 0 case Playing case Paused case Failed public var description: String { get { switch self { case Stopped: return "Stopped" case Playing: return "Playing" case Failed: return "Failed" case Paused: return "Paused" } } } } public enum BufferingState: Int, CustomStringConvertible { case Unknown = 0 case Ready case Delayed public var description: String { get { switch self { case Unknown: return "Unknown" case Ready: return "Ready" case Delayed: return "Delayed" } } } } public protocol PlayerDelegate { func playerReady(player: Player) func playerPlaybackStateDidChange(player: Player) func playerBufferingStateDidChange(player: Player) func playerPlaybackWillStartFromBeginning(player: Player) func playerPlaybackDidEnd(player: Player) } // KVO contexts private var PlayerObserverContext = 0 private var PlayerItemObserverContext = 0 private var PlayerLayerObserverContext = 0 // KVO player keys private let PlayerTracksKey = "tracks" private let PlayerPlayableKey = "playable" private let PlayerDurationKey = "duration" private let PlayerRateKey = "rate" // KVO player item keys private let PlayerStatusKey = "status" private let PlayerEmptyBufferKey = "playbackBufferEmpty" private let PlayerKeepUp = "playbackLikelyToKeepUp" // KVO player layer keys private let PlayerReadyForDisplay = "readyForDisplay" // MARK: - Player public class Player: UIViewController { public var delegate: PlayerDelegate! public func setUrl(url: NSURL) { // Make sure everything is reset beforehand if(self.playbackState == .Playing){ self.pause() } self.setupPlayerItem(nil) let asset = AVURLAsset(URL: url, options: .None) self.setupAsset(asset) } public var assetURL : NSURL? { get { return self.asset?.URL } } public var muted: Bool! { get { return self.player.muted } set { self.player.muted = newValue } } public var rate: Float! { get { return self.player.rate } set { self.player.rate = newValue } } public var fillMode: String! { get { return self.playerView.fillMode } set { self.playerView.fillMode = newValue } } public var playbackLoops: Bool! { get { return (self.player.actionAtItemEnd == .None) as Bool } set { if newValue.boolValue { self.player.actionAtItemEnd = .None } else { self.player.actionAtItemEnd = .Pause } } } public var playbackFreezesAtEnd: Bool! public var playbackState: PlaybackState! public var bufferingState: BufferingState! public var maximumDuration: NSTimeInterval! { get { if let playerItem = self.playerItem { return CMTimeGetSeconds(playerItem.duration) } else { return CMTimeGetSeconds(kCMTimeIndefinite) } } } public var currentTime : CMTime! { get { return self.player.currentTime() } set { if let playerItem = self.playerItem { playerItem.cancelPendingSeeks() self.player.seekToTime(newValue) } } } private var asset: AVURLAsset? private var playerItem: AVPlayerItem? private var player: AVPlayer! private var playerView: PlayerView! private var timeObserver: AnyObject? // MARK: object lifecycle public convenience init() { self.init(nibName: nil, bundle: nil) self.player = AVPlayer() self.player.actionAtItemEnd = .Pause self.player.addObserver(self, forKeyPath: PlayerRateKey, options: ([NSKeyValueObservingOptions.New, NSKeyValueObservingOptions.Old]) , context: &PlayerObserverContext) self.player.addObserver(self, forKeyPath: PlayerStatusKey, options: ([NSKeyValueObservingOptions.New, NSKeyValueObservingOptions.Old]) , context: &PlayerObserverContext) self.playbackLoops = false self.playbackFreezesAtEnd = false self.playbackState = .Stopped self.bufferingState = .Unknown } deinit { self.removeTimeObserver() self.playerView?.player = nil self.delegate = nil NSNotificationCenter.defaultCenter().removeObserver(self) self.playerView?.layer.removeObserver(self, forKeyPath: PlayerReadyForDisplay, context: &PlayerLayerObserverContext) self.player.removeObserver(self, forKeyPath: PlayerRateKey, context: &PlayerObserverContext) self.player.removeObserver(self, forKeyPath: PlayerStatusKey, context: &PlayerObserverContext) self.player.pause() self.setupPlayerItem(nil) } // MARK: view lifecycle public override func loadView() { self.playerView = PlayerView(frame: CGRectZero) self.playerView.fillMode = AVLayerVideoGravityResizeAspect self.playerView.playerLayer.hidden = true self.view = self.playerView self.playerView.layer.addObserver(self, forKeyPath: PlayerReadyForDisplay, options: ([NSKeyValueObservingOptions.New, NSKeyValueObservingOptions.Old]), context: &PlayerLayerObserverContext) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillResignActive:", name: UIApplicationWillResignActiveNotification, object: UIApplication.sharedApplication()) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterBackground:", name: UIApplicationDidEnterBackgroundNotification, object: UIApplication.sharedApplication()) } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) if self.playbackState == .Playing { self.pause() } } // MARK: methods public func playFromBeginning() { self.delegate?.playerPlaybackWillStartFromBeginning(self) self.player.seekToTime(kCMTimeZero) self.playFromCurrentTime() } public func playFromCurrentTime() { self.playbackState = .Playing self.delegate?.playerPlaybackStateDidChange(self) self.player.play() } public func pause() { if self.playbackState != .Playing { return } self.player.pause() self.playbackState = .Paused self.delegate?.playerPlaybackStateDidChange(self) } public func stop() { if self.playbackState == .Stopped { return } self.player.pause() self.playbackState = .Stopped self.delegate?.playerPlaybackStateDidChange(self) self.delegate?.playerPlaybackDidEnd(self) } public func addPeriodicTimeObserverForInterval(interval: CMTime, usingBlock block: ((CMTime) -> Void)!) { self.removeTimeObserver() self.timeObserver = self.player.addPeriodicTimeObserverForInterval(interval, queue: dispatch_get_main_queue(), usingBlock: block) } public func removeTimeObserver() { if let observer: AnyObject = self.timeObserver { self.player.removeTimeObserver(observer) self.timeObserver = nil } } // MARK: private setup private func setupAsset(asset: AVURLAsset) { if self.playbackState == .Playing { self.pause() } self.bufferingState = .Unknown self.delegate?.playerBufferingStateDidChange(self) self.asset = asset if let asset = self.asset { self.setupPlayerItem(nil) let keys: [String] = [PlayerTracksKey, PlayerPlayableKey, PlayerDurationKey] asset.loadValuesAsynchronouslyForKeys(keys, completionHandler: { () -> Void in dispatch_sync(dispatch_get_main_queue(), { () -> Void in for key in keys { var error: NSError? let status = asset.statusOfValueForKey(key, error:&error) if status == .Failed { self.playbackState = .Failed self.delegate?.playerPlaybackStateDidChange(self) return } } if asset.playable.boolValue == false { self.playbackState = .Failed self.delegate?.playerPlaybackStateDidChange(self) return } let playerItem: AVPlayerItem = AVPlayerItem(asset: asset) self.setupPlayerItem(playerItem) }) }) } } private func setupPlayerItem(playerItem: AVPlayerItem?) { if self.playerItem != nil { self.playerItem?.removeObserver(self, forKeyPath: PlayerEmptyBufferKey, context: &PlayerItemObserverContext) self.playerItem?.removeObserver(self, forKeyPath: PlayerKeepUp, context: &PlayerItemObserverContext) self.playerItem?.removeObserver(self, forKeyPath: PlayerStatusKey, context: &PlayerItemObserverContext) NSNotificationCenter.defaultCenter().removeObserver(self, name: AVPlayerItemDidPlayToEndTimeNotification, object: self.playerItem) NSNotificationCenter.defaultCenter().removeObserver(self, name: AVPlayerItemFailedToPlayToEndTimeNotification, object: self.playerItem) } self.playerItem = playerItem if self.playerItem != nil { self.playerItem?.addObserver(self, forKeyPath: PlayerEmptyBufferKey, options: ([NSKeyValueObservingOptions.New, NSKeyValueObservingOptions.Old]), context: &PlayerItemObserverContext) self.playerItem?.addObserver(self, forKeyPath: PlayerKeepUp, options: ([NSKeyValueObservingOptions.New, NSKeyValueObservingOptions.Old]), context: &PlayerItemObserverContext) self.playerItem?.addObserver(self, forKeyPath: PlayerStatusKey, options: ([NSKeyValueObservingOptions.New, NSKeyValueObservingOptions.Old]), context: &PlayerItemObserverContext) NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidPlayToEndTime:", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.playerItem) NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemFailedToPlayToEndTime:", name: AVPlayerItemFailedToPlayToEndTimeNotification, object: self.playerItem) } self.player.replaceCurrentItemWithPlayerItem(self.playerItem) if self.playbackLoops.boolValue == true { self.player.actionAtItemEnd = .None } else { self.player.actionAtItemEnd = .Pause } } // MARK: NSNotifications public func playerItemDidPlayToEndTime(aNotification: NSNotification) { if self.playbackLoops.boolValue == true || self.playbackFreezesAtEnd.boolValue == true { self.player.seekToTime(kCMTimeZero) } if self.playbackLoops.boolValue == false { self.stop() } } public func playerItemFailedToPlayToEndTime(aNotification: NSNotification) { self.playbackState = .Failed self.delegate?.playerPlaybackStateDidChange(self) } public func applicationWillResignActive(aNotification: NSNotification) { if self.playbackState == .Playing { self.pause() } } public func applicationDidEnterBackground(aNotification: NSNotification) { if self.playbackState == .Playing { self.pause() } } // MARK: KVO override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { let updatePlayerState : (Void) -> Void = { if let changeValues = change { let status = (changeValues[NSKeyValueChangeNewKey] as! NSNumber).integerValue as AVPlayerStatus.RawValue switch (status) { case AVPlayerStatus.ReadyToPlay.rawValue: self.playerView.playerLayer.player = self.player self.playerView.playerLayer.hidden = false case AVPlayerStatus.Failed.rawValue: self.playbackState = PlaybackState.Failed self.delegate?.playerPlaybackStateDidChange(self) default: true } } } switch (keyPath, context) { case (.Some(PlayerRateKey), &PlayerObserverContext): true case (.Some(PlayerStatusKey), &PlayerObserverContext): if self.player.status == .ReadyToPlay && self.playbackState == .Playing { self.playFromCurrentTime() } updatePlayerState() case (.Some(PlayerStatusKey), &PlayerItemObserverContext): true case (.Some(PlayerKeepUp), &PlayerItemObserverContext): if let item = self.playerItem { self.bufferingState = .Ready self.delegate?.playerBufferingStateDidChange(self) if item.playbackLikelyToKeepUp && self.playbackState == .Playing { self.playFromCurrentTime() } } updatePlayerState() case (.Some(PlayerEmptyBufferKey), &PlayerItemObserverContext): if let item = self.playerItem { if item.playbackBufferEmpty { self.bufferingState = .Delayed self.delegate?.playerBufferingStateDidChange(self) } } updatePlayerState() case (.Some(PlayerReadyForDisplay), &PlayerLayerObserverContext): if self.playerView.playerLayer.readyForDisplay { self.delegate?.playerReady(self) } default: super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } } extension Player { public func reset() { } } // MARK: - PlayerView internal class PlayerView: UIView { var player: AVPlayer! { get { return (self.layer as! AVPlayerLayer).player } set { (self.layer as! AVPlayerLayer).player = newValue } } var playerLayer: AVPlayerLayer! { get { return self.layer as! AVPlayerLayer } } var fillMode: String! { get { return (self.layer as! AVPlayerLayer).videoGravity } set { (self.layer as! AVPlayerLayer).videoGravity = newValue } } override class func layerClass() -> AnyClass { return AVPlayerLayer.self } // MARK: object lifecycle convenience init() { self.init(frame: CGRectZero) self.playerLayer.backgroundColor = UIColor.blackColor().CGColor } override init(frame: CGRect) { super.init(frame: frame) self.playerLayer.backgroundColor = UIColor.blackColor().CGColor } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
d0517804633a14199f5b6dd15884a5cd
31.667297
200
0.622881
5.279866
false
false
false
false
insidegui/AppleEvents
Dependencies/ChromeCastCore/ChromeCastCore/CastApp.swift
1
1167
// // CastApp.swift // ChromeCastCore // // Created by Guilherme Rambo on 21/10/16. // Copyright © 2016 Guilherme Rambo. All rights reserved. // import Foundation public enum CastAppIdentifier: String { case defaultMediaPlayer = "CC1AD845" case youTube = "YouTube" } @objcMembers public final class CastApp: NSObject, Codable { public var id: String = "" public var displayName: String = "" public var isIdleScreen: Bool = false public var sessionId: String = "" public var statusText: String = "" public var transportId: String = "" public enum CodingKeys: String, CodingKey { case id = "appId" case displayName case isIdleScreen case sessionId case statusText case transportId } public override var description: String { return """ CastApp(id: \(id), displayName:\(displayName), isIdleScreen: \(isIdleScreen), sessionId:\(sessionId), statusText:\(statusText), transportId:\(transportId)) """ } }
bsd-2-clause
633a3ee8f155f2d0943589d9ee249d32
24.911111
60
0.575472
4.858333
false
false
false
false
KoalaTeaCode/KoalaTeaPlayer
KoalaTeaPlayer/Classes/YTView/YTPlayerView.swift
1
14924
// // PlayerView.swift // KoalaTeaPlayer // // Created by Craig Holliday on 8/3/17. // Copyright © 2017 Koala Tea. All rights reserved. // import UIKit import AVFoundation import SnapKit public enum Direction { case up case left case none } public enum YTPlayerState { case landscapeLeft case landscapeRight case portrait case minimized case hidden } public protocol YTPlayerViewDelegate: NSObjectProtocol { func didMinimize() func didmaximize() func swipeToMinimize(translation: CGFloat, toState: YTPlayerState) func didEndedSwipe(toState: YTPlayerState) } public extension CGAffineTransform { init(from: CGRect, toRect to: CGRect) { self.init(translationX: to.minX-from.minX, y: to.minY-from.minY) self = self.scaledBy(x: to.width/from.width, y: to.height/from.height) } } public class YTPlayerView: UIView { /// The instance of `AssetPlaybackManager` that the app uses for managing playback. public var assetPlayer: AssetPlayer? public var remoteCommandManager: RemoteCommandManager? public var playerView: PlayerView? public var controlsView: ControlsView? public var skipView: SkipView? public weak var delegate: YTPlayerViewDelegate? public var direction = Direction.none public var state = YTPlayerState.portrait { didSet { self.animate(to: self.state) } } public var isRotated: Bool { get { return self.state == .landscapeLeft || self.state == .landscapeRight } } public var asset: Asset? { didSet { setupPlayback() } } public override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .white self.performLayout() self.setupGestureRecognizer() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { print("player view deinit") } public func deleteSelf() { self.assetPlayer?.stop() self.assetPlayer = nil self.remoteCommandManager = nil self.playerView = nil self.controlsView = nil self.skipView = nil self.delegate = nil self.removeFromSuperview() } // Mark: - Asset Playback Manager Setup public func setupPlayback() { self.assetPlayer = AssetPlayer(asset: asset) self.assetPlayer?.playerDelegate = self // Set playbackmanager for controls view so we can check state there self.controlsView?.assetPlaybackManager = assetPlayer setupRemoteCommandManager() setupPlayerView() } public func setupRemoteCommandManager() { // Initializer the `RemoteCommandManager`. guard let assetPlayer = assetPlayer else { return } remoteCommandManager = RemoteCommandManager(assetPlaybackManager: assetPlayer) // Always enable playback commands in MPRemoteCommandCenter. remoteCommandManager?.activatePlaybackCommands(true) remoteCommandManager?.toggleChangePlaybackPositionCommand(true) remoteCommandManager?.toggleSkipBackwardCommand(true, interval: 10) remoteCommandManager?.toggleSkipForwardCommand(true, interval: 10) } public override func performLayout() { skipView = SkipView() self.skipView?.delegate = self guard let skipView = skipView else { return } self.addSubview(skipView) self.skipView?.snp.makeConstraints { (make) in make.edges.equalToSuperview() } controlsView = ControlsView() self.controlsView?.delegate = self guard let controlsView = controlsView else { return } self.addSubview(controlsView) self.controlsView?.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } fileprivate func setupPlayerView() { self.playerView = assetPlayer?.playerView guard let playerView = playerView else { return } self.addSubview(playerView) self.playerView?.snp.makeConstraints { (make) in make.edges.equalToSuperview() } self.sendSubview(toBack: playerView) } fileprivate func handleAssetPlaybackManagerStateChange(to state: AssetPlayerPlaybackState) { print(state) switch state { case .setup: controlsView?.disableAllButtons() controlsView?.activityView.startAnimating() controlsView?.playButton.isHidden = false controlsView?.pauseButton.isHidden = true break case .playing: controlsView?.enableAllButtons() controlsView?.activityView.stopAnimating() controlsView?.playButton.isHidden = true controlsView?.pauseButton.isHidden = false self.controlsView?.waitAndFadeOut() break case .paused: controlsView?.activityView.stopAnimating() controlsView?.playButton.isHidden = false controlsView?.pauseButton.isHidden = true break case .interrupted: print("Interuppted state") break case .failed: break case .buffering: controlsView?.activityView.startAnimating() controlsView?.playButton.isHidden = true controlsView?.pauseButton.isHidden = true break case .stopped: break } } public func orientationChange() { switch UIDevice.current.orientation { case .landscapeLeft: self.state = .landscapeLeft break case .landscapeRight: self.state = .landscapeRight break case .portrait: self.state = .portrait break case .portraitUpsideDown: break case .unknown: break case .faceUp: break case .faceDown: break } } } extension YTPlayerView: AssetPlayerDelegate { public func currentAssetDidChange(_ player: AssetPlayer) { } public func playerIsSetup(_ player: AssetPlayer) { self.playerView = assetPlayer?.playerView self.controlsView?.playbackSliderView?.updateSlider(maxValue: player.maxSecondValue) } public func playerPlaybackStateDidChange(_ player: AssetPlayer) { guard let state = player.state else { return } self.handleAssetPlaybackManagerStateChange(to: state) } public func playerCurrentTimeDidChange(_ player: AssetPlayer) { self.controlsView?.playbackSliderView?.updateTimeLabels(currentTimeText: player.timeElapsedText, timeLeftText: player.timeLeftText) self.controlsView?.playbackSliderView?.updateSlider(currentValue: Float(player.currentTime)) } public func playerPlaybackDidEnd(_ player: AssetPlayer) { //@TODO: Add back current time tracking // podcastModel?.update(currentTime: 0.0) } public func playerIsLikelyToKeepUp(_ player: AssetPlayer) { //@TODO: Nothing to do here? } public func playerBufferTimeDidChange(_ player: AssetPlayer) { guard let assetPlayer = assetPlayer else { return } self.controlsView?.playbackSliderView?.updateBufferSlider(bufferValue: assetPlayer.bufferedTime) } } extension YTPlayerView: ControlsViewDelegate { public func minimizeButtonPressed() { self.minimize() } public func playButtonPressed() { self.assetPlayer?.play() } public func pauseButtonPressed() { self.assetPlayer?.pause() } public func playbackSliderValueChanged(value: Float) { assetPlayer?.seekTo(interval: TimeInterval(value)) } public func fullscreenButtonPressed() { switch self.isRotated { case true: self.state = .portrait case false: self.state = .landscapeLeft } } func handleStateChangeforControlView() { switch self.state { case .minimized: self.controlsView?.fadeSelfOut() self.controlsView?.fadeOutSliders() case .landscapeLeft, .landscapeRight: self.controlsView?.setRotatedConstraints() self.controlsView?.minimizeButton.isHidden = true case .portrait: self.controlsView?.fadeSelfIn() self.controlsView?.fadeInSliders() self.controlsView?.setDefaultConstraints() self.controlsView?.minimizeButton.isHidden = false case .hidden: break } } } extension YTPlayerView: SkipViewDelegate { public func skipForwardButtonPressed() { self.controlsView?.fadeSelfOut() self.assetPlayer?.skipForward(10) } public func skipBackwardButtonPressed() { self.controlsView?.fadeSelfOut() self.assetPlayer?.skipBackward(10) } public func singleTap() { guard self.state != .minimized else { self.state = .portrait self.delegate?.didmaximize() return } guard let controlsView = controlsView else { return } switch controlsView.isVisible { case true: self.controlsView?.fadeSelfOut() break case false: self.controlsView?.fadeSelfIn() break } } } extension YTPlayerView: UIGestureRecognizerDelegate { func animate(to: YTPlayerState) { guard let superView = self.superview else { return } let originPoint = CGPoint(x: 0, y: 0) self.layer.anchorPoint = originPoint switch self.state { case .minimized: UIView.animate(withDuration: 0.3, animations: { self.width = UIView.getValueScaledByScreenWidthFor(baseValue: 200) self.height = self.width / (16/9) let x = superView.frame.maxX - self.width - 10 let y = superView.frame.maxY - self.height - 10 self.layer.position = CGPoint(x: x, y: y) }) self.delegate?.didMinimize() case .landscapeLeft: self.controlsView?.isRotated = true UIView.animate(withDuration: 0.3, animations: { // This is an EXACT order for left and right // Transform > Change height and width > Change layer position let newTransform = CGAffineTransform(rotationAngle: (CGFloat.pi / 2)) self.transform = newTransform self.height = superView.width self.width = superView.height if #available(iOS 10.0, *) { self.height = superView.height self.width = superView.width } self.layer.position = CGPoint(x: superView.frame.maxX, y: 0) }) case .landscapeRight: self.controlsView?.isRotated = true UIView.animate(withDuration: 0.3, animations: { // This is an EXACT order for left and right // Transform > Change height and width > Change layer position let newTransform = CGAffineTransform(rotationAngle: -(CGFloat.pi / 2)) self.transform = newTransform self.height = superView.width self.width = superView.height if #available(iOS 10.0, *) { self.height = superView.height self.width = superView.width } self.layer.position = CGPoint(x: 0, y: superView.frame.maxY) }) case .portrait: self.controlsView?.isRotated = false UIView.animate(withDuration: 0.3, animations: { self.transform = CGAffineTransform.identity self.layer.position = CGPoint(x: 0, y: 0) self.height = superView.width / (16/9) self.width = superView.width }) self.delegate?.didmaximize() case .hidden: break } self.handleStateChangeforControlView() } func minimize() { self.state = .minimized self.delegate?.didMinimize() } func setupGestureRecognizer() { let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.minimizeGesture(_:))) gestureRecognizer.delegate = self self.addGestureRecognizer(gestureRecognizer) } @objc func minimizeGesture(_ sender: UIPanGestureRecognizer) { if sender.state == .began { let velocity = sender.velocity(in: nil) if abs(velocity.x) < abs(velocity.y) { self.direction = .up } else { self.direction = .left } } var finalState = YTPlayerState.portrait switch self.state { case .portrait: // let factor = (abs(sender.translation(in: nil).y) / UIScreen.main.bounds.height) // self.changeValues(scaleFactor: factor) // self.delegate?.swipeToMinimize(translation: factor, toState: .minimized) // finalState = .minimized break case .minimized: if self.direction == .left { finalState = .hidden let factor: CGFloat = sender.translation(in: nil).x self.delegate?.swipeToMinimize(translation: factor, toState: .hidden) } else { finalState = .portrait let factor = 1 - (abs(sender.translation(in: nil).y) / UIScreen.main.bounds.height) self.changeValues(scaleFactor: factor) self.delegate?.swipeToMinimize(translation: factor, toState: .portrait) } default: break } if sender.state == .ended { self.state = finalState self.delegate?.didEndedSwipe(toState: self.state) if self.state == .hidden { self.assetPlayer?.pause() } } } func changeValues(scaleFactor: CGFloat) { self.controlsView?.minimizeButton.alpha = 1 - scaleFactor // self.alpha = 1 - scaleFactor let scale = CGAffineTransform.init(scaleX: (1 - 0.5 * scaleFactor), y: (1 - 0.5 * scaleFactor)) let trasform = scale.concatenating(CGAffineTransform.init(translationX: -(self.bounds.width / 4 * scaleFactor), y: -(self.bounds.height / 4 * scaleFactor))) self.transform = trasform } }
mit
d711e581c19cc613ffbe32f268720183
32.23608
164
0.597936
5.070676
false
false
false
false
tolgaarikan/CountdownView
CountdownView/Classes/CountdownView.swift
1
20572
// // CountdownView.swift // Pods // // Created by Tolgahan Arıkan on 12/02/2017. // // import UIKit public class CountdownView: UIView { // MARK: Singleton public class var shared: CountdownView { struct Singleton { static let instance = CountdownView(frame: CGRect.zero) } return Singleton.instance } // MARK: Properties fileprivate weak var timer: Timer? fileprivate var timedTask: DispatchWorkItem! fileprivate var countdownFrom: Double! { didSet { counterLabel.text = "\(Int(countdownFrom!))" } } // MARK: Customizables Interface public var dismissStyle: DismissStyle = .none public var dismissStyleAnimation: Animation = .fadeOut public var frameSize = CGSize(width: 160.0, height: 160.0) public var framePosition = UIApplication.shared.keyWindow!.center public var backgroundViewColor: UIColor = UIColor(white: 0, alpha: 0.5) public var counterViewBackgroundColor: UIColor = .white public var counterViewShadowColor = UIColor.black.cgColor public var counterViewShadowRadius: CGFloat = 8 public var counterViewShadowOpacity: Float = 0.5 public var spinnerLineWidth: CGFloat = 8 public var spinnerInset: CGFloat = 8 public var spinnerStartColor = UIColor(red:0.15, green:0.27, blue:0.33, alpha:1.0).cgColor public var spinnerEndColor = UIColor(red:0.79, green:0.25, blue:0.25, alpha:1.0).cgColor public var colorTransition = false public var contentOffset: CGFloat? public var counterLabelOffset: CGFloat? public var counterLabelFont = UIFont.boldSystemFont(ofSize: 45) public var counterLabelTextColor = UIColor.black public var counterSubLabelText = "seconds" public var counterSubLabelFont = UIFont.systemFont(ofSize: 12) public var counterSubLabelTextColor = UIColor(red:0.48, green:0.48, blue:0.49, alpha:1.0) public var counterSubtitleLabelOffset: CGFloat? public var closeButtonTitleLabelText = "Skip" public var closeButtonTitleLabelFont = UIFont.systemFont(ofSize: 18) public var closeButtonTitleLabelColor = UIColor.white public var closeButtonTopAnchorConstant: CGFloat = 22 public var closeButtonLeftAnchorConstant: CGFloat = 10 public var closeButtonImage: UIImage? = nil public var closeButtonTintColor: UIColor = .white // MARK: Layout private var backgroundView = UIView() private var contentView = UIView() private var spinnerCircleView = UIView() private var counterView = UIView() private var labelContainer = UIView() private var spinnerCircle = CAShapeLayer() private var counterLabel = UILabel() private var counterSubLabel = UILabel() private var closeButton = UIButton(type: .system) private func setupViews() { addSubview(backgroundView) addSubview(contentView) addSubview(closeButton) backgroundView.alpha = 0 backgroundView.backgroundColor = backgroundViewColor contentView.frame.size = frameSize contentView.addSubview(counterView) contentView.addSubview(spinnerCircleView) counterView.frame.size = contentView.frame.size counterView.backgroundColor = counterViewBackgroundColor counterView.layer.cornerRadius = contentView.frame.size.width/2 counterView.layer.shadowPath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)).cgPath counterView.layer.shadowColor = counterViewShadowColor counterView.layer.shadowRadius = counterViewShadowRadius counterView.layer.shadowOpacity = counterViewShadowOpacity counterView.layer.shadowOffset = CGSize.zero spinnerCircleView.frame.size = contentView.frame.size spinnerCircle.path = UIBezierPath(ovalIn: CGRect(x: spinnerInset/2, y: spinnerInset/2, width: frameSize.width - spinnerInset, height: frameSize.height - spinnerInset)).cgPath spinnerCircle.lineWidth = spinnerLineWidth spinnerCircle.strokeStart = 0 spinnerCircle.strokeEnd = 0.33 spinnerCircle.lineCap = CAShapeLayerLineCap.round spinnerCircle.fillColor = UIColor.clear.cgColor spinnerCircle.strokeColor = spinnerStartColor spinnerCircleView.layer.addSublayer(spinnerCircle) counterView.addSubview(labelContainer) labelContainer.translatesAutoresizingMaskIntoConstraints = false labelContainer.widthAnchor.constraint(equalTo: counterView.widthAnchor).isActive = true labelContainer.centerXAnchor.constraint(equalTo: counterView.centerXAnchor).isActive = true labelContainer.centerYAnchor.constraint(equalTo: counterView.centerYAnchor).isActive = true labelContainer.addSubview(counterLabel) counterLabel.font = counterLabelFont counterLabel.textColor = counterLabelTextColor counterLabel.textAlignment = .center counterLabel.translatesAutoresizingMaskIntoConstraints = false counterLabel.topAnchor.constraint(equalTo: labelContainer.topAnchor).isActive = true counterLabel.centerXAnchor.constraint(equalTo: labelContainer.centerXAnchor).isActive = true labelContainer.addSubview(counterSubLabel) counterSubLabel.font = counterSubLabelFont counterSubLabel.textColor = counterSubLabelTextColor counterSubLabel.textAlignment = .center counterSubLabel.text = counterSubLabelText counterSubLabel.translatesAutoresizingMaskIntoConstraints = false counterSubLabel.topAnchor.constraint(equalTo: counterLabel.bottomAnchor).isActive = true counterSubLabel.centerXAnchor.constraint(equalTo: labelContainer.centerXAnchor).isActive = true counterSubLabel.bottomAnchor.constraint(equalTo: labelContainer.bottomAnchor).isActive = true if let image = closeButtonImage { closeButton.setImage(image, for: .normal) } closeButton.tintColor = closeButtonTintColor closeButton.setTitle(closeButtonTitleLabelText, for: .normal) closeButton.setTitleColor(closeButtonTitleLabelColor, for: .normal) closeButton.titleLabel?.font = closeButtonTitleLabelFont closeButton.titleLabel?.textAlignment = .center closeButton.translatesAutoresizingMaskIntoConstraints = false closeButton.topAnchor.constraint(equalTo: self.topAnchor, constant: closeButtonTopAnchorConstant).isActive = true closeButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: closeButtonLeftAnchorConstant).isActive = true } // // Observe the view frame and update the subviews layout // public override var frame: CGRect { didSet { if frame == CGRect.zero { return } backgroundView.frame = bounds contentView.center = framePosition } } // MARK: Custom superview private static weak var customSuperview: UIView? = nil private static func containerView() -> UIView? { return customSuperview ?? UIApplication.shared.keyWindow } public class func useContainerView(_ superview: UIView?) { customSuperview = superview } // MARK: Lifecycle override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Methods @discardableResult public class func show(countdownFrom: Double, spin: Bool, animation: Animation) -> CountdownView { let countdownView = CountdownView.shared countdownView.countdownFrom = countdownFrom countdownView.spin(spin) countdownView.updateFrame() countdownView.contentView.transform = CGAffineTransform.identity switch countdownView.dismissStyle { case .none: countdownView.closeButton.isHidden = true countdownView.backgroundView.isUserInteractionEnabled = false case .byButton: countdownView.closeButton.isHidden = false countdownView.backgroundView.isUserInteractionEnabled = false countdownView.closeButton.addTarget(countdownView, action: #selector(countdownView.didTapCloseButton), for: .touchUpInside) case .byTapOnOutside: countdownView.closeButton.isHidden = true countdownView.backgroundView.isUserInteractionEnabled = true countdownView.backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: countdownView, action: #selector(countdownView.didTapBackgroundView))) } if countdownView.superview == nil { CountdownView.shared.setupViews() guard let containerView = containerView() else { fatalError("\n`UIApplication.keyWindow` is `nil`. If you're trying to show a countdown view from your view controller's" + "`viewDidLoad` method, do that from `viewDidAppear` instead. Alternatively use `useContainerView` to set a view where the" + "countdown view should show") } containerView.addSubview(countdownView) if countdownView.dismissStyle == .byButton { countdownView.animate(countdownView.closeButton, animation: .fadeIn, options: (duration: 0.5, delay: 0), completion: nil) } countdownView.animate(countdownView.backgroundView, animation: .fadeIn, options: (duration: 0.5, delay: 0), completion: nil) countdownView.animate(countdownView.contentView, animation: animation, options: (duration: 0.5, delay: 0.2), completion: nil) #if os(iOS) // Orientation change observer NotificationCenter.default.addObserver( countdownView, selector: #selector(CountdownView.updateFrame), name: UIApplication.didChangeStatusBarOrientationNotification, object: nil) #endif } if countdownView.timer != nil { countdownView.timer!.invalidate() countdownView.timer = nil } countdownView.timer = Timer.scheduledTimer(timeInterval: 1, target: countdownView, selector: #selector(countdownView.updateCounter), userInfo: nil, repeats: true) return countdownView } fileprivate var currentCompletion: (()->())? public class func show(countdownFrom: Double, spin: Bool, animation: Animation, autoHide: Bool, completion: (()->())?) { show(countdownFrom: countdownFrom, spin: spin, animation: animation) if completion != nil { CountdownView.shared.currentCompletion = completion! } else { CountdownView.shared.currentCompletion = nil } if autoHide { var autoHideAnimation: Animation! switch animation { case .fadeIn: autoHideAnimation = .fadeOut case .fadeInLeft: autoHideAnimation = .fadeOutRight case .fadeInRight: autoHideAnimation = .fadeOutLeft case .zoomIn: autoHideAnimation = .zoomOut default: autoHideAnimation = .fadeOut } CountdownView.shared.timedTask = DispatchWorkItem { hide(animation: autoHideAnimation, options: (duration: 0.5, delay: 0.2)) { if completion != nil { completion!() } } } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + countdownFrom, execute: CountdownView.shared.timedTask) } else { CountdownView.shared.timedTask = DispatchWorkItem { if completion != nil { completion!() } } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + countdownFrom, execute: CountdownView.shared.timedTask) } } public class func hide(animation: Animation, options: (duration: Double, delay: Double), completion: (()->())?) { let countdownView = CountdownView.shared if countdownView.superview != nil { if countdownView.dismissStyle == .byButton { countdownView.animate(countdownView.closeButton, animation: animation, options: (duration: options.duration, delay: options.delay), completion: nil) } countdownView.animate(countdownView.contentView, animation: animation, options: (duration: options.duration, delay: options.delay), completion: nil) countdownView.animate(countdownView.backgroundView, animation: .fadeOut, options: (duration: options.duration, delay: options.delay)) { if completion != nil { completion!() } if countdownView.timer != nil { countdownView.timer!.invalidate() countdownView.timer = nil } countdownView.removeFromSuperview() } } } fileprivate func spin(_ spin: Bool) { if spin == true { spinnerCircle.removeAnimation(forKey: "strokeEnd") spinnerCircle.removeAnimation(forKey: "strokeColor") animate(spinnerCircleView, animation: .fadeIn, options: (duration: 0.4, delay: 0), completion: nil) startRotating(spinnerCircleView) } else { animate(spinnerCircleView, animation: .fadeOut, options: (duration: 0.4, delay: 0)) { self.stopRotating(self.spinnerCircleView) self.spinnerCircleView.transform = CGAffineTransform.identity } } } @objc fileprivate func updateCounter() { if countdownFrom == 2 { animateStrokeEnd(for: spinnerCircle, duration: 1.4) animateStrokeColor(for: spinnerCircle, duration: 0.6, from: spinnerStartColor, to: spinnerEndColor) } if countdownFrom == 1 { CountdownView.shared.timedTask = DispatchWorkItem { self.spin(false) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: CountdownView.shared.timedTask) } if countdownFrom > 0 { countdownFrom = countdownFrom - 1 } else { timer!.invalidate() } } func animateStrokeEnd(for shapeLayer: CAShapeLayer, duration: Double) { let strokeEndAnimation: CAAnimation = { let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = 0.33 animation.toValue = 1 animation.duration = duration animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) animation.repeatCount = 0 animation.fillMode = CAMediaTimingFillMode.forwards animation.isRemovedOnCompletion = false return animation }() shapeLayer.add(strokeEndAnimation, forKey: "strokeEnd") } func animateStrokeColor(for shapeLayer: CAShapeLayer, duration: Double, from: CGColor, to: CGColor) { let strokeColorAnimation: CAAnimation = { let animation = CABasicAnimation(keyPath: "strokeColor") animation.fromValue = from animation.toValue = to animation.duration = duration animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn) animation.repeatCount = 0 animation.fillMode = CAMediaTimingFillMode.forwards animation.isRemovedOnCompletion = false return animation }() shapeLayer.add(strokeColorAnimation, forKey: "strokeColor") } // MARK: Actions @objc fileprivate func didTapCloseButton() { CountdownView.hide(animation: dismissStyleAnimation, options: (duration: 0.5, delay: 0), completion: currentCompletion) CountdownView.shared.currentCompletion = nil CountdownView.shared.timedTask.cancel() } @objc fileprivate func didTapBackgroundView() { CountdownView.hide(animation: dismissStyleAnimation, options: (duration: 0.5, delay: 0), completion: currentCompletion) CountdownView.shared.currentCompletion = nil CountdownView.shared.timedTask.cancel() } // MARK: Util @objc public func updateFrame() { if let containerView = CountdownView.containerView() { CountdownView.shared.frame = containerView.bounds CountdownView.shared.contentView.center = containerView.center } } override public func layoutSubviews() { super.layoutSubviews() updateFrame() } } // MARK: Animations extension CountdownView { public enum Animation { case fadeIn case fadeOut case fadeInLeft case fadeInRight case fadeOutLeft case fadeOutRight case zoomIn case zoomOut } fileprivate func animate(_ view: UIView, animation: Animation, options: (duration: Double, delay: Double), completion: (()->())?) { switch animation { case .fadeIn: view.alpha = 0 UIView.animate(withDuration: options.duration, delay: options.delay, options: .transitionCrossDissolve, animations: { view.alpha = 1 }, completion: { _ in if completion != nil { completion!() } }) case .fadeOut: UIView.animate(withDuration: options.duration, delay: options.delay, options: .transitionCrossDissolve, animations: { view.alpha = 0 }, completion: { _ in if completion != nil { completion!() } }) case .fadeInLeft: view.center.x = view.center.x - bounds.width UIView.animate(withDuration: options.duration, delay: options.delay, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseIn, animations: { view.alpha = 1 view.center.x = view.center.x + self.bounds.width }, completion: { _ in if completion != nil { completion!() } }) case .fadeInRight: view.center.x = view.center.x + bounds.width UIView.animate(withDuration: options.duration, delay: options.delay, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseIn, animations: { view.alpha = 1 view.center.x = view.center.x - self.bounds.width }, completion: { _ in if completion != nil { completion!() } }) case .fadeOutLeft: UIView.animate(withDuration: options.duration, delay: options.delay, usingSpringWithDamping: 0.8, initialSpringVelocity: -1.2, options: .curveEaseIn, animations: { view.center.x = view.center.x - self.bounds.width }, completion: { _ in if completion != nil { completion!() } }) case .fadeOutRight: UIView.animate(withDuration: options.duration, delay: options.delay, usingSpringWithDamping: 0.8, initialSpringVelocity: -1.2, options: .curveEaseIn, animations: { view.center.x = view.center.x + self.bounds.width }, completion: { _ in if completion != nil { completion!() } }) case .zoomIn: view.alpha = 1 view.transform = CGAffineTransform(scaleX: 0, y: 0) UIView.animate(withDuration: options.duration, delay: options.delay, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseIn, animations: { view.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: { _ in if completion != nil { completion!() } }) case .zoomOut: view.alpha = 1 view.transform = CGAffineTransform.identity UIView.animate(withDuration: options.duration, delay: options.delay, usingSpringWithDamping: 0.8, initialSpringVelocity: -0.8, options: .curveEaseOut, animations: { view.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) }, completion: { _ in if completion != nil { completion!() } }) } } func startRotating(_ view: UIView, duration: Double = 1) { let kAnimationKey = "rotation" if view.layer.animation(forKey: kAnimationKey) == nil { let animate = CABasicAnimation(keyPath: "transform.rotation") animate.duration = duration animate.repeatCount = Float.infinity animate.fromValue = 0.0 animate.toValue = Float(.pi * 2.0) view.layer.add(animate, forKey: kAnimationKey) } } func stopRotating(_ view: UIView) { let kAnimationKey = "rotation" if view.layer.animation(forKey: kAnimationKey) != nil { view.layer.removeAnimation(forKey: kAnimationKey) } } } // MARK: Dismiss style extension CountdownView { public enum DismissStyle { case none case byButton case byTapOnOutside } }
mit
1ce98a5109810ff1351a3df1e457bcf7
36.333938
134
0.675271
5.012427
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Service/Network/BBNetworkError.swift
1
3410
//// /// BBNetworkError.swift // import Foundation import SwiftyJSON let BBNetworkErrorVersion = 1 public let BBErrorDomain = "com.bitboylabs.ios" public enum BBErrorCode: Int { case ImageMapping = 0 case JSONMapping case StringMapping case StatusCode case Data case NetworkFailure } extension NSError { class func networkError(error: AnyObject?, code: BBErrorCode) -> NSError { var userInfo: [NSObject : AnyObject]? if let error: AnyObject = error { userInfo = [NSLocalizedFailureReasonErrorKey as NSObject: error] } return NSError(domain: BBErrorDomain, code: code.rawValue, userInfo: userInfo) } } @objc (BBNetworkError) public class BBNetworkError: JSONAble { public enum CodeType: String { case blacklisted = "blacklisted" case invalidRequest = "invalid_request" case invalidResource = "invalid_resource" case invalidVersion = "invalid_version" case lockedOut = "locked_out" case missingParam = "missing_param" case noEndpoint = "no_endpoint" case notFound = "not_found" case notValid = "not_valid" case rateLimited = "rate_limited" case serverError = "server_error" case timeout = "timeout" case unauthenticated = "unauthenticated" case unauthorized = "unauthorized" case unavailable = "unavailable" case unknown = "unknown" } public let attrs: [String:[String]]? public let code: CodeType public let detail: String? public let messages: [String]? public let status: String? public let title: String init(attrs: [String:[String]]?, code: CodeType, detail: String?, messages: [String]?, status: String?, title: String ) { self.attrs = attrs self.code = code self.detail = detail self.messages = messages self.status = status self.title = title super.init(version: BBNetworkErrorVersion) } public required init(coder aDecoder: NSCoder) { let decoder = Coder(aDecoder) self.attrs = decoder.decodeOptionalKey(key: "attrs") self.code = decoder.decodeKey(key: "code") self.detail = decoder.decodeOptionalKey(key: "detail") self.messages = decoder.decodeOptionalKey(key: "messages") self.status = decoder.decodeOptionalKey(key: "status") self.title = decoder.decodeKey(key: "title") super.init(coder: aDecoder) } override public class func fromJSON(data: [String: AnyObject], fromLinked: Bool = false) -> JSONAble { let json = JSON(data) let title = json["title"].stringValue let codeType: CodeType if let actualCode = BBNetworkError.CodeType(rawValue: json["code"].stringValue) { codeType = actualCode } else { codeType = .unknown } let detail = json["detail"].string let status = json["status"].string let messages = json["messages"].object as? [String] let attrs = json["attrs"].object as? [String:[String]] return BBNetworkError( attrs: attrs, code: codeType, detail: detail, messages: messages, status: status, title: title ) } }
mit
02a44d6b5f86ab6c10550b335162e3e0
28.912281
106
0.609971
4.608108
false
false
false
false
BoxJeon/funjcam-ios
Domain/Usecase/Implementation/GoogleSearchImageResult.swift
1
1268
import Foundation import Entity import Usecase struct GoogleImageSearchResult: Decodable { var searchedImages: [SearchImage] var nextPages: [NextPage]? var next: Int? { return self.nextPages?.first?.startIndex } enum CodingKeys: String, CodingKey { case items case queries } private struct Image: Decodable { var link: String var image: Metadata var mime: String var displayLink: String } private struct Metadata: Decodable { var width: Int = 0 var height: Int = 0 var thumbnailLink: String = "" } struct Queries: Decodable { var nextPage: [NextPage] } struct NextPage: Decodable { var startIndex: Int? } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.searchedImages = (try values.decodeIfPresent([Image].self, forKey: .items) ?? []).map { item in return SearchImage( displayName: item.displayLink, urlString: item.link, pixelWidth: item.image.width, pixelHeight: item.image.height, thumbnailURLString: item.image.thumbnailLink ) } let queries = try values.decodeIfPresent(Queries.self, forKey: .queries) self.nextPages = queries?.nextPage } }
mit
316fd7e3fe8a077c0e896d46028bd73a
23.862745
104
0.670347
4.312925
false
false
false
false
Harshvk/CarsGalleryApp
ListToGridApp/GridCell.swift
1
1878
// // GridCell.swift // ListToGridApp // // Created by appinventiv on 13/02/17. // Copyright © 2017 appinventiv. All rights reserved. // import UIKit class GridCell: UICollectionViewCell { @IBOutlet weak var carPic: UIImageView! @IBOutlet weak var carName: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { self.backgroundColor = nil } func configureCell(withCar car: CarModel){ carPic.image = UIImage(named: car.image) carName.text = car.name carPic.layer.borderWidth = 1 carPic.layer.borderColor = UIColor.darkGray.cgColor } } class ProductsGridFlowLayout: UICollectionViewFlowLayout { override init() { super.init() setupLayout() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayout() } /** Sets up the layout for the collectionView. 1pt distance between each cell and 1pt distance between each row plus use a vertical layout */ func setupLayout() { minimumInteritemSpacing = 1 minimumLineSpacing = 1 scrollDirection = .vertical } /// here we define the width of each cell, creating a 2 column layout. In case you would create 3 columns, change the number 2 to 3 func itemWidth() -> CGFloat { return (collectionView!.frame.width/2)-1 } override var itemSize: CGSize { set { self.itemSize = CGSize(width: itemWidth(), height: 120) } get { return CGSize(width: itemWidth(), height: 120) } } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { return collectionView!.contentOffset } }
mit
02a5c53441dd7af053a2892cb3ed2c5a
23.376623
139
0.620139
4.875325
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Common/Common/Extension/NSObject+Runtime.swift
1
1690
// // NSObject+Runtime.swift // Common // // Created by wuyp on 2017/11/1. // Copyright © 2017年 raymond. All rights reserved. // import Foundation public extension NSObject { //MARK: 获取属性列表 @discardableResult public func propertyList() -> [String] { // if let cls = self.classForCoder is type(of: NSObject) { // return cls.propertyList() // } // return [] } @discardableResult class func propertyList() -> [String] { let cls: AnyClass = self var count: UInt32 = 0 let propertyList: UnsafeMutablePointer<objc_property_t>? = class_copyPropertyList(cls, &count) var propertyArr = [String]() for index in 0..<count { let property: UnsafePointer<Int8> = property_getName(propertyList![Int(index)]) propertyArr.append(String.init(format: "%s", property)) } return propertyArr } } public extension NSObject { public func exchangeInstanceMethod(originSelctor: Selector, newSelector: Selector) { let originMethod = class_getInstanceMethod(self.classForCoder, originSelctor)! let newMethod = class_getInstanceMethod(self.classForCoder, newSelector)! let addMethodSuccess = class_addMethod(self.classForCoder, originSelctor, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)) if addMethodSuccess { class_replaceMethod(self.classForCoder, newSelector, method_getImplementation(originMethod), method_getTypeEncoding(originMethod)) } else { method_exchangeImplementations(originMethod, newMethod) } } }
apache-2.0
71ca6e1e16ed3b86fa4d7fcb2c25ca58
31.843137
153
0.653731
4.564033
false
false
false
false
ktmswzw/FeelClient
FeelingClient/MVC/C/LoginViewController.swift
1
9239
// // LoginViewController.swift // FeelingClient // // Created by vincent on 13/2/16. // Copyright © 2016 xecoder. All rights reserved. // import UIKit import IBAnimatable import SwiftyJSON import Alamofire import SwiftyDB import Gifu class LoginViewController: DesignableViewController,UITextFieldDelegate { @IBOutlet weak var gifView: Gifu.AnimatableImageView! @IBOutlet var username: AnimatableTextField! @IBOutlet var password: AnimatableTextField! var actionButton: ActionButton! let database = SwiftyDB(databaseName: "UserInfo") var viewModel:LoginUserInfoViewModel! var gifList = ["boll","girl","night"] @IBOutlet weak var loginBtn: AnimatableButton! var userinfo: UserInfo! override func viewDidLoad() { super.viewDidLoad() let diceFaceCount: UInt32 = 3 let randomRoll = Int(arc4random_uniform(diceFaceCount)) gifView.animateWithImage(named: "\(gifList[randomRoll]).gif") let lookAnyWhere = ActionButtonItem(title: "随便看看", image: UIImage(named: "address")!) lookAnyWhere.action = { item in self.registerDervice() } let register = ActionButtonItem(title: "注册帐号", image: UIImage(named: "self")!) register.action = { item in self.performSegueWithIdentifier("register", sender: self) } let forget = ActionButtonItem(title: "忘记密码", image: UIImage(named: "readfire")!) forget.action = { item in self.view.makeToast("老板没给发薪,程序员罢工了", duration: 1, position: .Center) } actionButton = ActionButton(attachedToView: self.view, items: [register,lookAnyWhere,forget]) actionButton.action = { button in button.toggleMenu() } actionButton.setImage(UIImage(named: "new"), forState: .Normal) actionButton.backgroundColor = UIColor.lightGrayColor() username.delegate = self password.delegate = self viewModel = LoginUserInfoViewModel(delegate: self) } func registerDervice() { self.view.makeToastActivity(.Center) let uuid = UIDevice.currentDevice().identifierForVendor!.UUIDString self.viewModel.userName = uuid let password = "123456" self.viewModel.password = password.md5()! self.viewModel.register({ (r:BaseApi.Result) in switch (r) { case .Success(let r): if let userInfo = r as? UserInfo { self.userinfo = userInfo jwt.jwtTemp = userInfo.JWTToken jwt.imToken = userInfo.IMToken jwt.appUsername = self.viewModel.userName jwt.appPwd = self.viewModel.password jwt.userId = userInfo.id jwt.userName = userInfo.nickname self.database.addObject(userInfo, update: true) self.view.hideToastActivity() self.view.makeToast("默认注册成功,密码123456", duration: 1, position: .Center) self.performSegueWithIdentifier("login", sender: self) } if jwt.imToken.length != 0 { RCIM.sharedRCIM().connectWithToken(jwt.imToken, success: { (userId) -> Void in //设置当前登陆用户的信息 RCIM.sharedRCIM().currentUserInfo = RCUserInfo.init(userId: userId, name: self.userinfo.nickname, portrait: self.userinfo.avatar) }, error: { (status) -> Void in self.view.hideToastActivity() }, tokenIncorrect: { print("token错误") }) } loader = PhotoUpLoader.init()//初始化图片上传 break; case .Failure(let msg): print("\(msg)") self.view.hideToastActivity() self.view.makeToast("服务器离家出走", duration: 1, position: .Center) break; } }) } override func textFieldShouldReturn(textField: UITextField) -> Bool { if (textField === username) { password.becomeFirstResponder() } else if (textField === password) { password.resignFirstResponder() self.login(self) } else { // etc } return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func login(sender: AnyObject) { if username.text != "" && password.text != "" { if !self.password.validatePassword() { self.view.makeToast("密码必选大于6位数小于18的数字或字符", duration: 2, position: .Center) return } else{ //123456789001 //123456 let userNameText = username.text let passwordText = password.text!.md5() viewModel.userName = userNameText! viewModel.password = passwordText! self.loginBtn.enabled = false loginDelegate() } } else { self.view.makeToast("帐号或密码为空", duration: 2, position: .Center) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if jwt.appUsername.length > 0 && jwt.appPwd.length > 0 { username.text = jwt.appUsername // password.text = jwt.appPwd viewModel.userName = jwt.appUsername viewModel.password = jwt.appPwd self.loginBtn.enabled = false loginDelegate() } } override func viewWillAppear(animated: Bool) { if jwt.appUsername.length == 0 { // username.text = "" password.text = "" self.loginBtn.enabled = true } } @IBAction func tapImage(sender: AnyObject) { if gifView.isAnimatingGIF { gifView.stopAnimatingGIF() } else { gifView.startAnimatingGIF() } } } extension LoginViewController: LoginUserModelDelegate { func loginDelegate(){ self.view.makeToastActivity(.Center) self.viewModel.loginDelegate({ (r:BaseApi.Result) in switch (r) { case .Success(let r): if let userInfo = r as? UserInfo { self.userinfo = userInfo jwt.jwtTemp = userInfo.JWTToken jwt.imToken = userInfo.IMToken jwt.appUsername = self.viewModel.userName jwt.appPwd = self.viewModel.password jwt.userId = userInfo.id jwt.userName = userInfo.nickname self.database.asyncAddObject(self.userinfo) { (result) -> Void in if let error = result.error { self.view.makeToast("保存失败\(error)", duration: 2, position: .Center) } } self.view.hideToastActivity() self.view.makeToast("登陆成功", duration: 1, position: .Center) self.performSegueWithIdentifier("login", sender: self) } if jwt.imToken.length != 0 { RCIM.sharedRCIM().connectWithToken(jwt.imToken, success: { (userId) -> Void in //设置当前登陆用户的信息 RCIM.sharedRCIM().currentUserInfo = RCUserInfo.init(userId: userId, name: self.userinfo.nickname, portrait: self.userinfo.avatar) }, error: { (status) -> Void in self.view.hideToastActivity() }, tokenIncorrect: { print("token错误") }) } loader = PhotoUpLoader.init()//初始化图片上传 self.loginBtn.enabled = true break; case .Failure(let message): self.view.hideToastActivity() self.view.makeToast("\(message!)", duration: 1, position: .Center) self.loginBtn.enabled = true break; } }) } }
mit
2f90f4fb0df8a1c0468630c6c30bd690
35.200803
161
0.503883
5.349555
false
false
false
false
barabashd/WeatherApp
WeatherApp/LocationSearchTable.swift
1
2920
// // LocationSearchTableTableViewController.swift // WeatherApp // // Created by Dmytro on 2/20/17. // Copyright © 2017 Dmytro. All rights reserved. // import UIKit import MapKit class LocationSearchTable: UITableViewController { weak var handleMapSearchDelegate: HandleMapSearch? var matchingItems: [MKMapItem] = [] var mapView: MKMapView? func parseAddress(_ selectedItem:MKPlacemark) -> String { let firstSpace = (selectedItem.subThoroughfare != nil && selectedItem.thoroughfare != nil) ? " " : "" let comma = (selectedItem.subThoroughfare != nil || selectedItem.thoroughfare != nil) && (selectedItem.subAdministrativeArea != nil || selectedItem.administrativeArea != nil) ? ", " : "" let secondSpace = (selectedItem.subAdministrativeArea != nil && selectedItem.administrativeArea != nil) ? " " : "" let addressLine = String( format:"%@%@%@%@%@%@%@", selectedItem.subThoroughfare ?? "", firstSpace, selectedItem.thoroughfare ?? "", comma, selectedItem.locality ?? "", secondSpace, selectedItem.administrativeArea ?? "" ) return addressLine } } extension LocationSearchTable : UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { guard let mapView = mapView, let searchBarText = searchController.searchBar.text else { return } let request = MKLocalSearchRequest() request.naturalLanguageQuery = searchBarText request.region = mapView.region let search = MKLocalSearch(request: request) search.start { response, _ in guard let response = response else { return } self.matchingItems = response.mapItems self.tableView.reloadData() } } } extension LocationSearchTable { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return matchingItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! let selectedItem = matchingItems[indexPath.row].placemark cell.textLabel?.text = selectedItem.name cell.detailTextLabel?.text = parseAddress(selectedItem) return cell } } extension LocationSearchTable { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedItem = matchingItems[indexPath.row].placemark handleMapSearchDelegate?.dropPinZoomIn(selectedItem) dismiss(animated: true, completion: nil) } }
mit
84a030e8b1077b4f75c527e5d9b245ba
30.728261
109
0.628983
5.425651
false
false
false
false
thedistance/TheDistanceComponents
TDCAppDependencies/Implementations/AnalyticEntities.swift
1
2875
// // AnalyticEntities.swift // // Copyright © 2016 The Distance. All rights reserved. // import Foundation /// Simple struct to define an Analytic Event. This is a value type to ensure clear mutabililty implications. public struct AnalyticEvent: CustomStringConvertible, Equatable { /// The category for this event. This should be high level for filtering the events. This is defined as an enum for String safety. public let category:String /// The action for this event. This should be mid level for filtering the events within a given category. This is defined as an enum for String safety. public let action:String /// The label for this event. This should be low level identifying a specific event. public let label:String? /// Internal variable used to highlight the mutability implications of the addInfo(_:value:) and setUserInfo(_:) methods. fileprivate var _userInfo = [String:Any]() /// Extra info specifc to this analytic event. public var userInfo:[String:Any] { get { return _userInfo } } /** Designated initialiser for a general event. It is **strongly recommended** that event Category, Actions and Lables are defined using enums and this struct is extended with a convenience initialiser specific to the application being developed. - parameter category: The category for this event. - parameter action: The action for this event. - parameter label: The label for this event. - parameter userInfo: Extra info specifc to this event. */ public init(category:String, action:String, label:String?, userInfo:[String:Any]? = nil) { self.category = category self.action = action self.label = label if let info = userInfo { setUserInfo(info) } } /** Appends a new value to the userInfo. - parameter key: The key to which the value will be assigned. - parameter value: The value to be stored. */ public mutating func addInfo(_ key:String, value:Any) { _userInfo[key] = value } /** Assigns a new userInfo dictionary to this event. - parameter info: The info to be set. */ public mutating func setUserInfo(_ info:[String:Any]) { _userInfo = info } /// `CustomStringConvertible` variable. public var description:String { get { return "<Analytic: \(category) - \(action) - \(String(describing: label)), UserInfo: \(userInfo)>" } } } /// An `AnalyticEvent` is `Equatable` if its `category`, `action` and `label` are all equal. public func ==(a1:AnalyticEvent, a2:AnalyticEvent) -> Bool { return a1.category == a2.category && a1.action == a2.action && a1.label == a2.label }
mit
475a7f1fc0a94a5af9952b4a78d7db31
31.659091
202
0.644746
4.576433
false
false
false
false
ArthurXHK/AXRegex
Pod/RegexPattern.swift
1
1235
// // RegexPattern.swift // Pods // // Created by Arthur XU on 17/10/15. // // import Foundation public struct RegexPattern { public static let Email: String = { return "([a-zA-Z0-9_\\.-]+)@([a-zA-Z0-9\\.-]+)\\.([a-zA-Z\\.]{2,6})" }() public static let WebSite: String = { return "(https?:\\/\\/)?([a-zA-Z0-9\\.-]+)\\.([a-zA-Z\\.]{2,6})([\\/\\w \\.-]*)*\\/?" }() public static let IPAddress: String = { return "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" }() public static let HtmlTag: String = { return "<[\\/]?[a-zA-Z]+(\\s+[a-zA-Z]+\\s*[=]\\s*[\"]\\w+[\"])*\\s*(?:[\\/]?|>\\w*<\\/[a-zA-Z]+)>" }() public static let Number: String = { return "[0-9]+([.][0-9]+)?" }() public static let Chinese: String = { return "[\\u4e00-\\u9fa5]+" }() public static func userName(lowerLimit: UInt, upperLimit: UInt) -> String { return "[a-zA-Z][a-zA-Z0-9_]{\(lowerLimit-1),\(upperLimit-1)}" } public static func password(lowerLimit: UInt, upperLimit: UInt) -> String { return "[a-zA-Z0-9_]{\(lowerLimit-1),\(upperLimit-1)}" } }
apache-2.0
d5b005e8f5f30dbe9b16076dc0114030
30.666667
107
0.466397
2.892272
false
false
false
false
DaiYue/HAMLeetcodeSwiftSolutions
solutions/24_Swap_Node_In_Pairs.playground/Contents.swift
1
1137
// #24 Swap Node in Pairs https://leetcode.com/problems/swap-nodes-in-pairs/ // 非常简单的链表操作,一组两个 node,换过再往下,从头顺到尾即可。 // 发现单链表的题,前面加一个 dummy 真的应用很广泛,我已经用上瘾啦。 // 时间复杂度:O(n) 空间复杂度:O(1) public class ListNode { public var val: Int public var next: ListNode? public init(_ val: Int) { self.val = val self.next = nil } } class Solution { func swapPairs(_ head: ListNode?) -> ListNode? { let dummy = ListNode(0) dummy.next = head var prev = dummy // prev = A while prev.next != nil && prev.next?.next != nil { // A->B->C->D => A->C->B->D let current = prev.next! // current = B prev.next = current.next // A -> C current.next = current.next?.next // B -> D prev.next?.next = current // C -> B prev = current } return dummy.next } } Solution().swapPairs(ListNode(1))
mit
29ec9bb9cd5514668f29bab4cae08fd9
27.514286
86
0.504514
3.368243
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDATests/EditWordListTableViewStateTests.swift
1
3661
// // EditWordListTableViewStateTests.swift // HiPDA // // Created by leizh007 on 2016/12/14. // Copyright © 2016年 HiPDA. All rights reserved. // import XCTest @testable import HiPDA class EditWordListTableViewStateTests: XCTestCase { lazy var state: EditWordListTableViewState = { let section1 = EditWordListSection(header: "0", words: ["1", "2"]) let section2 = EditWordListSection(header: "1", words: ["3", "4", "5", "6"]) let section3 = EditWordListSection(header: "2", words: ["7", "8", "9"]) return EditWordListTableViewState(sections: [section1, section2, section3]) }() lazy var state1: EditWordListTableViewState = { let section1 = EditWordListSection(header: "0", words: ["1", "2", "10"]) let section2 = EditWordListSection(header: "1", words: ["3", "4", "5", "6"]) let section3 = EditWordListSection(header: "2", words: ["7", "8", "9"]) return EditWordListTableViewState(sections: [section1, section2, section3]) }() lazy var state2: EditWordListTableViewState = { let section1 = EditWordListSection(header: "0", words: ["1", "2", "10"]) let section2 = EditWordListSection(header: "1", words: ["3", "5", "6"]) let section3 = EditWordListSection(header: "2", words: ["7", "8", "9"]) return EditWordListTableViewState(sections: [section1, section2, section3]) }() lazy var state3: EditWordListTableViewState = { let section1 = EditWordListSection(header: "0", words: ["1", "2", "10"]) let section2 = EditWordListSection(header: "1", words: ["3", "5", "6"]) let section3 = EditWordListSection(header: "2", words: ["8", "9", "7"]) return EditWordListTableViewState(sections: [section1, section2, section3]) }() lazy var state4: EditWordListTableViewState = { let section1 = EditWordListSection(header: "0", words: ["1", "2", "9", "10"]) let section2 = EditWordListSection(header: "1", words: ["3", "5", "6"]) let section3 = EditWordListSection(header: "2", words: ["8", "7"]) return EditWordListTableViewState(sections: [section1, section2, section3]) }() lazy var state5: EditWordListTableViewState = { let section1 = EditWordListSection(header: "0", words: ["1"]) let section2 = EditWordListSection(header: "1", words: ["3", "5", "6"]) let section3 = EditWordListSection(header: "2", words: ["8", "7"]) return EditWordListTableViewState(sections: [section1, section2, section3]) }() func testStateCommands() { let addCommand = EditWordListTableViewEditingCommand.append("10", in: 0) let state1 = self.state.execute(addCommand) XCTAssert(state1 == self.state1) let deleteCommand = EditWordListTableViewEditingCommand.delete(with: IndexPath(row: 1, section: 1)) let state2 = state1.execute(deleteCommand) XCTAssert(state2 == self.state2) let moveCommand1 = EditWordListTableViewEditingCommand.move(from: IndexPath(row: 0, section: 2), to: IndexPath(row: 2, section: 2)) let state3 = state2.execute(moveCommand1) XCTAssert(state3 == self.state3) let moveCommand2 = EditWordListTableViewEditingCommand.move(from: IndexPath(row: 1, section: 2), to: IndexPath(row: 2, section: 0)) let state4 = state3.execute(moveCommand2) XCTAssert(state4 == self.state4) let replaceCommand = EditWordListTableViewEditingCommand.replace(self.state5) let state5 = state4.execute(replaceCommand) XCTAssert(state5 == self.state5) } }
mit
00762d219d5944493e7847b6e8e487f4
47.131579
139
0.640787
3.744115
false
true
false
false
antonio081014/LeetCode-CodeBase
Swift/remove-digit-from-number-to-maximize-result.swift
1
570
class Solution { func removeDigit(_ number: String, _ digit: Character) -> String { var num = Array(number) for (index, c) in number.enumerated() { if c == digit, index < num.count - 1, num[index + 1] > c { num.remove(at: index) return String(num) } } for index in stride(from: number.count - 1, through: 0, by: -1) { if num[index] == digit { num.remove(at: index) return String(num) } } return "" } }
mit
bf0e52bcf0df2b6add485ef029ad7995
30.666667
73
0.459649
3.986014
false
false
false
false
shunfan/Learning-iOS-Development
Tip Calculator/Tip Calculator/ViewController.swift
1
1847
// // ViewController.swift // TipCalculator // // Created by Shunfan Du on 9/19/15. // Copyright © 2015 Shunfan Du. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var amountTextField: UITextField! @IBOutlet weak var tipLabels: UIStackView! @IBOutlet weak var tip15Label: UILabel! @IBOutlet weak var tip17Label: UILabel! @IBOutlet weak var tip20Label: UILabel! override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } override func viewDidLoad() { super.viewDidLoad() tipLabels.hidden = true amountTextField.delegate = self tip15Label.adjustsFontSizeToFitWidth = true tip17Label.adjustsFontSizeToFitWidth = true tip20Label.adjustsFontSizeToFitWidth = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) let amount = NSString(string: amountTextField.text!).doubleValue calculateTip(amount) return true } func calculateTip(amount: Double) { let tip15 = amount * 0.15 let tip17 = amount * 0.17 let tip20 = amount * 0.20 let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle tip15Label.text = numberFormatter.stringFromNumber(tip15) tip17Label.text = numberFormatter.stringFromNumber(tip17) tip20Label.text = numberFormatter.stringFromNumber(tip20) tipLabels.hidden = false } }
mit
8f25d8aa1e2503aa37529ce8ece45916
27.84375
74
0.660347
5.2
false
false
false
false
snailjj/iOSDemos
SnailSwiftDemos/Pods/JTAppleCalendar/Sources/JTAppleCalendarView.swift
2
9174
// // JTAppleCalendarView.swift // // Copyright (c) 2016-2017 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar) // // 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. // let maxNumberOfDaysInWeek = 7 // Should not be changed let maxNumberOfRowsPerMonth = 6 // Should not be changed let developerErrorMessage = "There was an error in this code section. Please contact the developer on GitHub" let decorationViewID = "Are you ready for the life after this one?" let errorDelta: CGFloat = 0.0000001 /// An instance of JTAppleCalendarView (or simply, a calendar view) is a /// means for displaying and interacting with a gridstyle layout of date-cells open class JTAppleCalendarView: UICollectionView { /// Configures the size of your date cells @IBInspectable open var cellSize: CGFloat = 0 { didSet { if oldValue == cellSize { return } if scrollDirection == .horizontal { calendarViewLayout.cellSize.width = cellSize } else { calendarViewLayout.cellSize.height = cellSize } calendarViewLayout.invalidateLayout() calendarViewLayout.itemSizeWasSet = cellSize == 0 ? false: true } } /// The scroll direction of the sections in JTAppleCalendar. open var scrollDirection: UICollectionViewScrollDirection! /// Enables/Disables the stretching of date cells. When enabled cells will stretch to fit the width of a month in case of a <= 5 row month. open var allowsDateCellStretching = true /// Alerts the calendar that range selection will be checked. If you are /// not using rangeSelection and you enable this, /// then whenever you click on a datecell, you may notice a very fast /// refreshing of the date-cells both left and right of the cell you /// just selected. open var isRangeSelectionUsed: Bool = false /// The object that acts as the delegate of the calendar view. weak open var calendarDelegate: JTAppleCalendarViewDelegate? { didSet { lastMonthSize = sizesForMonthSection() } } /// The object that acts as the data source of the calendar view. weak open var calendarDataSource: JTAppleCalendarViewDataSource? { didSet { setupMonthInfoAndMap() } // Refetch the data source for a data source change } var lastSavedContentOffset: CGFloat = 0.0 var triggerScrollToDateDelegate: Bool? = true var isScrollInProgress = false var isReloadDataInProgress = false // keeps track of if didEndScroll is not yet completed. If isStillScrolling var didEndScollCount = 0 // Keeps track of scroll target location. If isScrolling, and user taps while scrolling var endScrollTargetLocation: CGFloat = 0 var generalDelayedExecutionClosure: [(() -> Void)] = [] var scrollDelayedExecutionClosure: [(() -> Void)] = [] let dateGenerator = JTAppleDateConfigGenerator() /// Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated. public init() { super.init(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) setupNewLayout(from: collectionViewLayout as! JTAppleCalendarLayoutProtocol) } /// Initializes and returns a newly allocated collection view object with the specified frame and layout. @available(*, unavailable, message: "Please use JTAppleCalendarView() instead. It manages its own layout.") public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout()) setupNewLayout(from: collectionViewLayout as! JTAppleCalendarLayoutProtocol) } /// Initializes using decoder object required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupNewLayout(from: collectionViewLayout as! JTAppleCalendarLayoutProtocol) } // Configuration parameters from the dataSource var cachedConfiguration: ConfigurationParameters! // Set the start of the month var startOfMonthCache: Date! // Set the end of month var endOfMonthCache: Date! var selectedCellData: [IndexPath:SelectedCellData] = [:] var pathsToReload: Set<IndexPath> = [] //Paths to reload because of prefetched cells var anchorDate: Date? var firstContentOffset: CGPoint { var retval: CGPoint = .zero guard let date = anchorDate else { return retval } // reset the initial scroll date once used. anchorDate = nil // Ensure date is within valid boundary let components = calendar.dateComponents([.year, .month, .day], from: date) let firstDayOfDate = calendar.date(from: components)! if !((firstDayOfDate >= startOfMonthCache!) && (firstDayOfDate <= endOfMonthCache!)) { return retval } // Get valid indexPath of date to scroll to let retrievedPathsFromDates = pathsFromDates([date]) if retrievedPathsFromDates.isEmpty { return retval } let sectionIndexPath = pathsFromDates([date])[0] if calendarViewLayout.thereAreHeaders && scrollDirection == .vertical { let indexPath = IndexPath(item: 0, section: sectionIndexPath.section) guard let attributes = calendarViewLayout.layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: indexPath) else { return retval } let maxYCalendarOffset = max(0, self.contentSize.height - self.frame.size.height) retval = CGPoint(x: attributes.frame.origin.x,y: min(maxYCalendarOffset, attributes.frame.origin.y)) // if self.scrollDirection == .horizontal { topOfHeader.x += extraAddedOffset} else { topOfHeader.y += extraAddedOffset } } else { switch scrollingMode { case .stopAtEach, .stopAtEachSection, .stopAtEachCalendarFrame: if scrollDirection == .horizontal || (scrollDirection == .vertical && !calendarViewLayout.thereAreHeaders) { retval = self.targetPointForItemAt(indexPath: sectionIndexPath) ?? .zero } default: break } } return retval } open var sectionInset: UIEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0) open var minimumInteritemSpacing: CGFloat = 0 open var minimumLineSpacing: CGFloat = 0 lazy var theData: CalendarData = { return self.setupMonthInfoDataForStartAndEndDate() }() var lastMonthSize: [AnyHashable:CGFloat] = [:] var monthMap: [Int: Int] { get { return theData.sectionToMonthMap } set { theData.sectionToMonthMap = monthMap } } /// Configure the scrolling behavior open var scrollingMode: ScrollingMode = .stopAtEachCalendarFrame { didSet { switch scrollingMode { case .stopAtEachCalendarFrame: decelerationRate = UIScrollViewDecelerationRateFast case .stopAtEach, .stopAtEachSection: decelerationRate = UIScrollViewDecelerationRateFast case .nonStopToSection, .nonStopToCell, .nonStopTo, .none: decelerationRate = UIScrollViewDecelerationRateNormal } #if os(iOS) switch scrollingMode { case .stopAtEachCalendarFrame: isPagingEnabled = true default: isPagingEnabled = false } #endif } } } @available(iOS 9.0, *) extension JTAppleCalendarView { /// A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts. open override var semanticContentAttribute: UISemanticContentAttribute { didSet { transform.a = semanticContentAttribute == .forceRightToLeft ? -1 : 1 } } }
apache-2.0
b9877bb26fbcf1cff946b4cee87178ed
44.631841
174
0.68044
5.220262
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Read/Controller/RecommendedViewController.swift
1
11158
// // RecommendedViewController.swift // WePeiYang // // Created by JinHongxu on 2016/10/25. // Copyright © 2016年 Qin Yubo. All rights reserved. // import UIKit import SafariServices class RecommendedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, RecommendBookViewDelegate { let tableView = UITableView(frame: CGRect(x: 0, y: 108, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height-108) , style: .Grouped) let sectionList = ["热门推荐", "热门书评", "阅读之星"] var headerScrollView = UIScrollView() let pageControl = UIPageControl() var loadingView = UIView() // let bannerList = ["http://www.twt.edu.cn/upload/banners/hheZnqd196Te76SDF9Ww.png", "http://www.twt.edu.cn/upload/banners/ZPQqmajzKOI3A6qE7gIR.png", "http://www.twt.edu.cn/upload/banners/gJjWSlAvkGjZmdbuFtXT.jpeg"] //var reviewList = [MyReview]() override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) self.navigationController?.navigationBarHidden = false } override func viewDidLoad() { super.viewDidLoad() initUI() if !Recommender.sharedInstance.dataDidRefresh { initLoadingView() } Recommender.sharedInstance.getBannerList(refreshUI) Recommender.sharedInstance.getRecommendedList(refreshUI) Recommender.sharedInstance.getHotReviewList(refreshUI) Recommender.sharedInstance.getStarUserList(refreshUI) //initReviews(tableView.reloadData) } func initLoadingView() { loadingView = UIView(frame: CGRect(x: 0, y: 108, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height-108)) loadingView.backgroundColor = UIColor.whiteColor() view.addSubview(loadingView) MsgDisplay.showLoading() } func refreshUI() { if Recommender.sharedInstance.finishFlag.isFinished() { Recommender.sharedInstance.dataDidRefresh = true Recommender.sharedInstance.finishFlag.reset() loadingView.removeFromSuperview() MsgDisplay.dismiss() } tableView.reloadData() } func initReviews(success: () -> ()) { // for i in 0...3 { // let foo = MyReview() // foo.initWithDict( // [ // "content": "James while John had had had had had had had had had had had a better effect on the teacher", // "rate": i, // "like": i, // "timestamp": 143315151, // "book": [ // "title": "活着", // "isbn": "ABS-131" // ] // ]) // reviewList.append(foo) // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func initUI() { view.addSubview(tableView) tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorStyle = .None } //Table DataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sectionList.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return Recommender.sharedInstance.reviewList.count case 2: return 1 default: return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell = RecommendCell(model: Recommender.sharedInstance.recommendedList) for fooView in cell.fooView { fooView.delegate = self } return cell case 1: let cell = ReviewCell(model: Recommender.sharedInstance.reviewList[indexPath.row]) return cell case 2: let cell = ReadStarCell(model: Recommender.sharedInstance.starList) return cell default: let cell = UITableViewCell() return cell } } // func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // switch indexPath.section { // case 0: // return 200 // case 2: // return 160 // default: // return 0 // } // } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return UIScreen.mainScreen().bounds.width*0.375+32 } return 16 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionList[section] } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.width*0.375+32)) headerScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.width*0.375)) headerView.addSubview(headerScrollView) headerView.addSubview(pageControl) // headerScrollView.snp_makeConstraints { // make in // make.top.equalTo(headerView) // make.left.equalTo(headerView) // make.right.equalTo(headerView) // make.bottom.equalTo(headerView).offset(-32) // } pageControl.snp_makeConstraints { make in make.centerX.equalTo(headerScrollView) make.bottom.equalTo(headerScrollView) } //设置scrollView的内容总尺寸 headerScrollView.contentSize = CGSize(width: CGFloat(UIScreen.mainScreen().bounds.width)*CGFloat(Recommender.sharedInstance.bannerList.count), height: UIScreen.mainScreen().bounds.width*0.375) //关闭滚动条显示 headerScrollView.showsHorizontalScrollIndicator = false headerScrollView.showsVerticalScrollIndicator = false headerScrollView.scrollsToTop = false //无弹性 headerScrollView.bounces = false //协议代理,在本类中处理滚动事件 headerScrollView.delegate = self //滚动时只能停留到某一页 headerScrollView.pagingEnabled = true //添加页面到滚动面板里 for (seq, banner) in Recommender.sharedInstance.bannerList.enumerate() { let imageView = UIImageView() imageView.setImageWithURL(NSURL(string: banner.image)!); imageView.frame = CGRect(x: CGFloat(seq)*UIScreen.mainScreen().bounds.width, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.width*0.375) imageView.userInteractionEnabled = true imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(RecommendedViewController.pushWebPage))) headerScrollView.addSubview(imageView) } //页控件属性 pageControl.backgroundColor = UIColor.clearColor() pageControl.numberOfPages = Recommender.sharedInstance.bannerList.count pageControl.currentPage = 0 //设置页控件点击事件 pageControl.addTarget(self, action: #selector(pageChanged(_:)), forControlEvents: UIControlEvents.ValueChanged) let fooLabel = UILabel(text: "热门推荐") fooLabel.textColor = UIColor.grayColor() fooLabel.font = UIFont(name: "Arial", size: 13) headerView.addSubview(fooLabel) fooLabel.snp_makeConstraints { make in make.top.equalTo(headerScrollView.snp_bottom).offset(10) make.left.equalTo(headerView).offset(14) } return headerView } else { return nil } } //Table View Delegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 { let detailVC = BookDetailViewController(bookID: "\(Recommender.sharedInstance.reviewList[indexPath.row].bookID)") self.navigationController?.showViewController(detailVC, sender: nil) print("Push Detail View Controller, bookID: \(Recommender.sharedInstance.reviewList[indexPath.row].bookID)") } tableView.deselectRowAtIndexPath(indexPath, animated: true) } //UIScrollViewDelegate方法,每次滚动结束后调用 func scrollViewDidEndDecelerating(scrollView: UIScrollView) { //通过scrollView内容的偏移计算当前显示的是第几页 let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width) //设置pageController的当前页 pageControl.currentPage = page } //点击页控件时事件处理 func pageChanged(sender:UIPageControl) { //根据点击的页数,计算scrollView需要显示的偏移量 var frame = headerScrollView.frame frame.origin.x = frame.size.width * CGFloat(sender.currentPage) frame.origin.y = 0 //展现当前页面内容 headerScrollView.scrollRectToVisible(frame, animated:true) } func pushDetailViewController(bookID: String) { let detailVC = BookDetailViewController(bookID: bookID) self.navigationController?.showViewController(detailVC, sender: nil) // self.navigationController?.navigationBarHidden = true print("Push Detail View Controller, bookID: \(bookID)") } func pushWebPage() { if #available(iOS 9.0, *) { let safariController = SFSafariViewController(URL: NSURL(string: Recommender.sharedInstance.bannerList[pageControl.currentPage].url)!, entersReaderIfAvailable: true) presentViewController(safariController, animated: true, completion: nil) } else { let webController = WebAppViewController(address: Recommender.sharedInstance.bannerList[pageControl.currentPage].url) self.navigationController?.pushViewController(webController, animated: true) self.jz_navigationBarBackgroundAlpha = 0 } } }
mit
29efacbfc471776b031ac9d6431af19b
37.300353
219
0.608266
4.953839
false
false
false
false
chashmeetsingh/Youtube-iOS
YouTube Demo/VideoCell.swift
1
5862
// // VideoCell.swift // YouTube Demo // // Created by Chashmeet Singh on 06/01/17. // Copyright © 2017 Chashmeet Singh. All rights reserved. // import UIKit class VideoCell: BaseCell { var video: Video? { didSet { titleLabel.text = video?.title setupThumbnailImage() setupProfileImage() if let channelName = video?.channel?.name, let numberOfViews = video?.number_of_views { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal let subtitleText = "\(channelName) · \(numberFormatter.string(from: numberOfViews)!) views · 2 years ago" subtitleTextView.text = subtitleText } // Measure text if let title = video?.title { let size = CGSize(width: frame.width - 16 - 44 - 8 - 16, height: 1000) let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin) let estimatedRect = NSString(string: title).boundingRect(with: size, options: options, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 17)], context: nil) if round(estimatedRect.size.height) > 20 { titleLabelHeightConstraint?.constant = 44 } else { titleLabelHeightConstraint?.constant = 20 } } } } func setupProfileImage() { if let profileImageUrl = video?.channel?.profile_image_name { self.userProfileImagView.loadImageUsingUrlString(profileImageUrl) } } func setupThumbnailImage() { if let thumbnailImageUrl = video?.thumbnail_image_name { self.thumbnailImageView.loadImageUsingUrlString(thumbnailImageUrl) } } let thumbnailImageView: CustomImageView = { let imageView = CustomImageView() imageView.image = UIImage(named: "starboy_the_weeknd") imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true return imageView }() let separatorView: UIView = { let view = UIView() view.backgroundColor = UIColor(red: 230 / 255, green: 230 / 255, blue: 230 / 255, alpha: 1) return view }() let userProfileImagView: CustomImageView = { let imageView = CustomImageView() imageView.image = UIImage(named: "starboy") imageView.layer.cornerRadius = 22 imageView.layer.masksToBounds = true imageView.contentMode = .scaleAspectFill return imageView }() let titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "The Weeknd - Starboy (official) ft. Daft Punk" label.numberOfLines = 2 return label }() let subtitleTextView: UITextView = { let textView = UITextView() textView.translatesAutoresizingMaskIntoConstraints = false textView.text = "TheWeekndVEVO · 471M views · 1 month ago" textView.textContainerInset = UIEdgeInsets(top: 0, left: -4, bottom: 0, right: 0) textView.textColor = .lightGray return textView }() var titleLabelHeightConstraint: NSLayoutConstraint? override func setupViews() { super.setupViews() addSubview(thumbnailImageView) addSubview(separatorView) addSubview(userProfileImagView) addSubview(titleLabel) addSubview(subtitleTextView) addConstraintsWithFormat(format: "H:|-16-[v0]-16-|", view: thumbnailImageView) addConstraintsWithFormat(format: "V:|-16-[v0]-8-[v1(44)]-36-[v2(1)]|", view: thumbnailImageView, userProfileImagView, separatorView) addConstraintsWithFormat(format: "H:|[v0]|", view: separatorView) addConstraintsWithFormat(format: "H:|-16-[v0(44)]", view: userProfileImagView) // Top Constraint addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: thumbnailImageView, attribute: .bottom, multiplier: 1, constant: 8)) // Left Constraint addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: userProfileImagView, attribute: .right, multiplier: 1, constant: 8)) // Right Constraint addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: thumbnailImageView, attribute: .right, multiplier: 1, constant: 0)) // Height Constraint titleLabelHeightConstraint = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 44) addConstraint(titleLabelHeightConstraint!) // Top Constraint addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1, constant: 4)) // Left Constraint addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .left, relatedBy: .equal, toItem: userProfileImagView, attribute: .right, multiplier: 1, constant: 8)) // Right Constraint addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .right, relatedBy: .equal, toItem: thumbnailImageView, attribute: .right, multiplier: 1, constant: 0)) // Height Constraint addConstraint(NSLayoutConstraint(item: subtitleTextView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 30)) } }
mit
02ee433031ecd02571e5f1c011445e18
40.539007
183
0.630015
5.243509
false
false
false
false
asynchrony/Re-Lax
ReLax/ReLax/LCRLayer.swift
1
3595
import Accelerate import Compression import UIKit struct LCRLayer { let imageName: String let image: CGImage let imageWidth: Int let imageHeight: Int let imageRect: CGRect private let alpha: Data private let csiHeader: CoreStructuredImage init(layer: LCRLayerSource, name: String = "Image-" + uuidHexString()) { imageName = name imageWidth = layer.image.width imageHeight = layer.image.height imageRect = CGRect(origin: layer.origin, size: CGSize(width: imageWidth, height: imageHeight)) csiHeader = CoreStructuredImage.layer(imageName: imageName, imageSize: CGSize(width: imageWidth, height: imageHeight)) let context = CGContext(data: nil, width: imageWidth, height: imageHeight, bitsPerComponent: 8, bytesPerRow: imageWidth * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! context.draw(layer.image, in: CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight)) image = context.makeImage()! let imageData = context.data var imageBuffer = vImage_Buffer(data: imageData, height: UInt(imageHeight), width: UInt(imageWidth), rowBytes: imageWidth * 4) var alphaChannel = vImage_Buffer(data: UnsafeMutableRawPointer(malloc(imageWidth * imageHeight)), height: UInt(imageHeight), width: UInt(imageWidth), rowBytes: imageWidth) let vImageError = vImageExtractChannel_ARGB8888(&imageBuffer, &alphaChannel, 3, UInt32(kvImageNoFlags)) guard vImageError == 0 else { fatalError("Unable to populate Alpha Channel Buffer") } let alphaChannelBufferAsUInt8 = unsafeBitCast(alphaChannel.data, to: UnsafeMutablePointer<UInt8>.self) let encodedAlphaChannel = unsafeBitCast(malloc(imageWidth * imageHeight), to: UnsafeMutablePointer<UInt8>.self) let sizeOfEncodedAlphaChannel = compression_encode_buffer(encodedAlphaChannel, imageWidth * imageHeight, alphaChannelBufferAsUInt8, imageWidth * imageHeight, nil, COMPRESSION_LZFSE) guard sizeOfEncodedAlphaChannel > 0 else { fatalError("Alpha Channel Buffer is 0 length") } alpha = Data(bytes: encodedAlphaChannel, count: sizeOfEncodedAlphaChannel) free(alphaChannel.data) free(encodedAlphaChannel) } func data() -> Data { let infoListData = structuredImageData() let coreElemData = coreElementData() return concatData([csiHeader.data(structuredInfoDataLength: infoListData.count, payloadDataLength: coreElemData.count), infoListData, coreElementData()]) } private func coreElementData() -> Data { let celm = "MLEC".data(using: .ascii)! let lzsfeCompressionId = 5 let compressionType = int32Data(lzsfeCompressionId) let image = imageData() let imageByteCount = int32Data(image.count) return concatData([celm, zeroPadding(4), compressionType, imageByteCount, image]) } private func structuredImageData() -> Data { return concatData([ StructuredInfo.slices(width: imageWidth, height: imageHeight).data(), StructuredInfo.metrics(width: imageWidth, height: imageHeight).data(), StructuredInfo.composition.data(), StructuredInfo.exifOrientation.data(), StructuredInfo.bytesPerRow(width: imageWidth).data() ]) } private func imageData() -> Data { let jpeg = JPEGData(from: image) return concatData([zeroPadding(8), int32Data(alpha.count), int32Data(imageWidth), int32Data(jpeg.count), alpha, jpeg]) } }
mit
c2185069ac460e64d4298998088441ed
48.930556
228
0.705702
4.585459
false
false
false
false
kumabook/MusicFav
MusicFav/HUDExtension.swift
1
1833
// // HUDExtension.swift // MusicFav // // Created by Hiroki Kumamoto on 2/19/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import Foundation import MBProgressHUD extension MBProgressHUD { fileprivate class func createCompletedHUD(_ view: UIView) -> MBProgressHUD { let hud = MBProgressHUD(view: view) hud.customView = UIImageView(image:UIImage(named:"checkmark")) hud.mode = MBProgressHUDMode.customView hud.label.text = "Completed".localize() return hud } class func showHUDForView(_ view: UIView, message: String, animated: Bool, duration: TimeInterval, after: @escaping () -> Void) -> MBProgressHUD { let hud = MBProgressHUD(view: view) hud.label.text = message return hud.show(view, animated: animated, duration: duration, after: after) } class func showCompletedHUDForView(_ view: UIView, animated: Bool, duration: TimeInterval, after: @escaping () -> Void) -> MBProgressHUD { let hud = MBProgressHUD.createCompletedHUD(view) return hud.show(view, animated: animated, duration: duration, after: after) } fileprivate func show(_ view: UIView, animated: Bool, duration: TimeInterval, after: @escaping () -> Void) -> MBProgressHUD { view.addSubview(self) self.show(true, duration: duration, after: { self.removeFromSuperview() after() }) return self } func show(_ animated:Bool, duration:TimeInterval, after:@escaping () -> Void) { show(animated: true) let startTime = DispatchTime.now() + Double(Int64(duration * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: startTime) { () -> Void in self.hide(animated: true) after() } } }
mit
339f7e2906136ab2ce578411554dd20c
36.408163
150
0.649209
4.374702
false
false
false
false
kumabook/MusicFav
MusicFav/SoundCloudPlaylistLoader.swift
1
4631
// // SoundCloudPlaylistLoader.swift // MusicFav // // Created by Hiroki Kumamoto on 8/22/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import Foundation import SoundCloudKit import ReactiveSwift import MusicFeeder import Breit extension SoundCloudKit.Track { var thumbnailURLString: String { if let url = artworkUrl { return url } else { return user.avatarUrl } } func toTrack() -> MusicFeeder.Track { let track = MusicFeeder.Track( id: "\(Provider.soundCloud.rawValue)/\(id)", provider: Provider.soundCloud, url: uri, identifier: "\(id)", title: title) track.updateProperties(self) return track } func toPlaylist() -> MusicFeeder.Playlist { return MusicFeeder.Playlist(id: "soundcloud-track-\(id)", title: title, tracks: [toTrack()]) } } extension SoundCloudKit.Playlist { func toPlaylist() -> MusicFeeder.Playlist { return MusicFeeder.Playlist(id: "soundcloud-playlist-\(id)", title: title, tracks: tracks.map { $0.toTrack() }) } } class SoundCloudPlaylistLoader { enum State { case `init` case fetching case normal case error } enum Event { case startLoading case completeLoading case failToLoad } let user: User var playlists: [SoundCloudKit.Playlist] var favorites: [SoundCloudKit.Track] var state: State var signal: Signal<Event, NSError> var observer: Signal<Event, NSError>.Observer var playlistsDisposable: Disposable? var hasNextPlaylists: Bool var favoritesDisposable: Disposable? var hasNextFavorites: Bool init(user: User) { self.user = user playlists = [] favorites = [] self.state = State.init let pipe = Signal<Event, NSError>.pipe() signal = pipe.0 observer = pipe.1 playlistsDisposable = nil hasNextPlaylists = true favoritesDisposable = nil hasNextFavorites = true } fileprivate func fetchNextPlaylists() -> SignalProducer<Void, NSError> { state = State.fetching observer.send(value: .startLoading) return APIClient.shared.fetchPlaylistsOf(user).map { self.hasNextPlaylists = false self.playlists.append(contentsOf: $0) self.observer.send(value: .completeLoading) self.state = State.normal }.mapError { self.hasNextPlaylists = true self.observer.send(error: $0) self.state = State.error return $0 } } func needFetchPlaylists() -> Bool { return hasNextPlaylists } func fetchPlaylists() { if !needFetchPlaylists() { return } switch state { case .init: playlistsDisposable = fetchNextPlaylists().start() case .fetching: break case .normal: playlistsDisposable = fetchNextPlaylists().start() case .error: playlistsDisposable = fetchNextPlaylists().start() } } fileprivate func fetchNextFavorites() -> SignalProducer<Void, NSError> { state = State.fetching observer.send(value: .startLoading) return APIClient.shared.fetchFavoritesOf(user) .map { self.hasNextFavorites = false self.favorites.append(contentsOf: $0) self.observer.send(value: .completeLoading) self.state = State.normal self.fetchPlaylists() }.mapError { self.hasNextFavorites = true self.observer.send(error: $0) self.state = State.error return $0 } } func needFetchFavorites() -> Bool { return hasNextFavorites } func fetchFavorites() { switch state { case .init: playlistsDisposable = fetchNextFavorites().start() case .fetching: break case .normal: playlistsDisposable = fetchNextFavorites().start() case .error: playlistsDisposable = fetchNextFavorites().start() } } }
mit
c3b03c6e456371dc6ea6d1e25a5e0f07
30.290541
88
0.544807
5.06674
false
false
false
false
rnapier/SwiftCheck
SwiftCheck/Gen.swift
1
5974
// // Gen.swift // SwiftCheck // // Created by Robert Widmann on 7/31/14. // Copyright (c) 2015 TypeLift. All rights reserved. // /// A generator for values of type A. public struct Gen<A> { let unGen : StdGen -> Int -> A /// Generates a value. /// /// This method exists as a convenience mostly to test generators. It will always generate with /// size 30. public var generate : A { let r = newStdGen() return unGen(r)(30) } /// These must be in here or we get linker errors; rdar://21172325 /// Shakes up the internal Random Number generator for a given Generator with a seed. public func variant<S : IntegerType>(seed : S) -> Gen<A> { return Gen(unGen: { r in return { n in return self.unGen(vary(seed)(r: r))(n) } }) } /// Constructs a generator that always uses a given size. public func resize(n : Int) -> Gen<A> { return Gen(unGen: { r in return { (_) in return self.unGen(r)(n) } }) } /// Constructs a Generator that only returns values that satisfy a predicate. public func suchThat(p : (A -> Bool)) -> Gen<A> { return self.suchThatOptional(p).bind { mx in switch mx { case .Some(let x): return Gen.pure(x) case .None: return Gen.sized { n in return self.suchThat(p).resize(n + 1) } } } } /// Constructs a Generator that attempts to generate a values that satisfy a predicate. /// /// Passing values are wrapped in `.Some`. Failing values are `.None`. public func suchThatOptional(p : A -> Bool) -> Gen<Optional<A>> { return Gen<Optional<A>>.sized({ n in return try(self, 0, max(n, 1), p) }) } /// Generates a list of random length. public func listOf() -> Gen<[A]> { return Gen<[A]>.sized({ n in return Gen.choose((0, n)).bind { k in return self.vectorOf(k) } }) } /// Generates a non-empty list of random length. public func listOf1() -> Gen<[A]> { return Gen<[A]>.sized({ n in return Gen.choose((1, max(1, n))).bind { k in return self.vectorOf(k) } }) } /// Generates a list of a given length. public func vectorOf(k : Int) -> Gen<[A]> { return sequence(Array<Gen<A>>(count: k, repeatedValue: self)) } /// Selects a random value from a list and constructs a Generator that returns only that value. public static func elements(xs : [A]) -> Gen<A> { assert(xs.count != 0, "elements used with empty list") return choose((0, xs.count - 1)).fmap { i in return xs[i] } } /// Takes a list of elements of increasing size, and chooses among an initial segment of the list. /// The size of this initial segment increases with the size parameter. public static func growingElements(xs : [A]) -> Gen<A> { assert(xs.count != 0, "growingElements used with empty list") let k = Double(xs.count) return sized({ n in let m = max(1, size(k)(m: n)) return Gen.elements(Array(xs[0 ..< m])) }) } } extension Gen /*: Functor*/ { typealias B = Swift.Any /// Returns a new generator that applies a given function to any outputs the receiver creates. public func fmap<B>(f : (A -> B)) -> Gen<B> { return Gen<B>(unGen: { r in return { n in return f(self.unGen(r)(n)) } }) } } extension Gen /*: Applicative*/ { typealias FAB = Gen<A -> B> /// Lifts a value into a generator that will only generate that value. public static func pure(a : A) -> Gen<A> { return Gen(unGen: { (_) in return { (_) in return a } }) } /// Given a generator of functions, applies any generated function to any outputs the receiver /// creates. public func ap<B>(fn : Gen<A -> B>) -> Gen<B> { return Gen<B>(unGen: { r in return { n in return fn.unGen(r)(n)(self.unGen(r)(n)) } }) } } extension Gen /*: Monad*/ { /// Applies the function to any generated values to yield a new generator. This generator is /// then given a new random seed and returned. public func bind<B>(fn : A -> Gen<B>) -> Gen<B> { return Gen<B>(unGen: { r in return { n in let (r1, r2) = r.split() let m = fn(self.unGen(r1)(n)) return m.unGen(r2)(n) } }) } } /// Reduces an array of generators to a generator that returns arrays of the original generators /// values in the order given. public func sequence<A>(ms : [Gen<A>]) -> Gen<[A]> { return ms.reduce(Gen<[A]>.pure([]), combine: { y, x in return x.bind { x1 in return y.bind { xs in return Gen<[A]>.pure([x1] + xs) } } }) } /// Flattens a generator of generators by one level. public func join<A>(rs : Gen<Gen<A>>) -> Gen<A> { return rs.bind { x in return x } } /// Lifts a function from some A to some R to a function from generators of A to generators of R. public func liftM<A, R>(f : A -> R)(m1 : Gen<A>) -> Gen<R> { return m1.bind{ x1 in return Gen.pure(f(x1)) } } /// Promotes a rose of generators to a generator of rose values. public func promote<A>(x : Rose<Gen<A>>) -> Gen<Rose<A>> { return delay().bind { (let eval : Gen<A> -> A) in return Gen<Rose<A>>.pure(liftM(eval)(m1: x)) } } /// Promotes a function returning generators to a generator of functions. public func promote<A, B>(m : A -> Gen<B>) -> Gen<A -> B> { return delay().bind { (let eval : Gen<B> -> B) in return Gen<A -> B>.pure({ x in eval(m(x)) }) } } internal func delay<A>() -> Gen<Gen<A> -> A> { return Gen(unGen: { r in return { n in return { g in return g.unGen(r)(n) } } }) } /// Implementation Details Follow private func vary<S : IntegerType>(k : S)(r: StdGen) -> StdGen { let s = r.split() var gen = ((k % 2) == 0) ? s.0 : s.1 return (k == (k / 2)) ? gen : vary(k / 2)(r: r) } private func try<A>(gen: Gen<A>, k: Int, n : Int, p: A -> Bool) -> Gen<Optional<A>> { if n == 0 { return Gen.pure(.None) } return gen.resize(2 * k + n).bind { (let x : A) -> Gen<Optional<A>> in if p(x) { return Gen.pure(.Some(x)) } return try(gen, k + 1, n - 1, p) } } private func size(k : Double)(m : Int) -> Int { let n = Double(m) return Int((log(n + 1)) * k / log(100)) }
mit
7022cd1649d210abcf45da70fcee7fd3
24.529915
99
0.611483
2.892978
false
false
false
false
herrkaefer/AccelerateWatch
AccelerateWatch/Classes/Vector.swift
1
6224
/// Vector // // Created by Yang Liu (gloolar [at] gmail [dot] com) on 16/7/9. // Copyright © 2016年 Yang Liu. All rights reserved. // import Foundation private func scalarEqual(_ scalar1: Float, scalar2: Float) -> Bool { return fabs(scalar1 - scalar2) < 1e-6 } private func scalarEqual(_ scalar1: Double, scalar2: Double) -> Bool { return fabs(scalar1 - scalar2) < 1e-6 } /// Mean value. Float type version. public func vMean(_ v: [Float]) -> Float { return vectorf_mean(v, v.count) } /// Mean value. Double type version. public func vMean(_ v: [Double]) -> Double { return vectord_mean(v, v.count) } /// Summation. Float type version. public func vSum(_ v: [Float]) -> Float { return vectorf_sum(v, v.count) } /// Summation. Double type version. public func vSum(_ v: [Double]) -> Double { return vectord_sum(v, v.count) } /// Vector length. Float type version. public func vLength(_ v: [Float]) -> Float { return vectorf_length(v, v.count) } /// Vector length. Double type version. public func vLength(_ v: [Double]) -> Double { return vectord_length(v, v.count) } /// Square of length. Float type version. public func vPower(_ v: [Float]) -> Float { return vectorf_power(v, v.count) } /// Square of length. Double type version. public func vPower(_ v: [Double]) -> Double { return vectord_power(v, v.count) } /// Add scalar to vector. Float type version. public func vAdd(_ v: [Float], valueToAdd: Float) -> [Float] { var result = [Float](repeating: 0.0, count: v.count) vectorf_add(v, v.count, valueToAdd, &result) return result } /// Add scalar to vector. Double type version. public func vAdd(_ v: [Double], valueToAdd: Double) -> [Double] { var result = [Double](repeating: 0.0, count: v.count) vectord_add(v, v.count, valueToAdd, &result) return result } /// Multiply vector with scalar. Float type version. public func vMultiply(_ v: [Float], valueToMultiply: Float) -> [Float] { var result = [Float](repeating: 0.0, count: v.count) vectorf_multiply(v, v.count, valueToMultiply, &result) return result } /// Multiply vector with scalar. Double type version. public func vMultiply(_ v: [Double], valueToMultiply: Double) -> [Double] { var result = [Double](repeating: 0.0, count: v.count) vectord_multiply(v, v.count, valueToMultiply, &result) return result } /// Remove mean value. Float type version. public func vRemoveMean(_ v: [Float]) -> [Float] { var result = [Float](repeating: 0.0, count: v.count) vectorf_remove_mean(v, v.count, &result) return result } /// Remove mean value. Double type version. public func vRemoveMean(_ v: [Double]) -> [Double] { var result = [Double](repeating: 0.0, count: v.count) vectord_remove_mean(v, v.count, &result) return result } /// Normalize vector to have unit length. Float type version. public func vNormalizeToUnitLength(_ v: [Float], centralized: Bool) -> [Float] { var result = [Float](repeating: 0.0, count: v.count) vectorf_normalize_to_unit_length(v, v.count, centralized, &result) return result } /// Normalize vector to have unit length. Double type version. public func vNormalizeToUnitLength(_ v: [Double], centralized: Bool) -> [Double] { var result = [Double](repeating: 0.0, count: v.count) vectord_normalize_to_unit_length(v, v.count, centralized, &result) return result } /// Sqrt. Float type version. public func vSqrt(_ v: [Float]) -> [Float] { var result = [Float](repeating: 0.0, count: v.count) vectorf_sqrt(v, v.count, &result) return result } /// Sqrt. Double type version. public func vSqrt(_ v: [Double]) -> [Double] { var result = [Double](repeating: 0.0, count: v.count) vectord_sqrt(v, v.count, &result) return result } /// Dot production between two vectors. Float type version. public func vDotProduct(_ v1: [Float], v2: [Float]) -> Float { assert (v1.count == v2.count) return vectorf_dot_product(v1, v2, v1.count) } /// Dot production between two vectors. Double type version. public func vDotProduct(_ v1: [Double], v2: [Double]) -> Double { assert (v1.count == v2.count) return vectord_dot_product(v1, v2, v1.count) } /// Correlation Coefficient between two vectors. Float type version. public func vCorrelationCoefficient(_ v1: [Float], v2: [Float]) -> Float { assert (v1.count == v2.count) return vDotProduct(vNormalizeToUnitLength(v1, centralized: true), v2: vNormalizeToUnitLength(v2, centralized: true)) } /// Correlation Coefficient between two vectors. Double type version. public func vCorrelationCoefficient(_ v1: [Double], v2: [Double]) -> Double { assert (v1.count == v2.count) return vDotProduct(vNormalizeToUnitLength(v1, centralized: true), v2: vNormalizeToUnitLength(v2, centralized: true)) } /// :nodoc: /// Self test of Vector functions public func vTest() { print("Vector test: \n") let v1 = Array(0..<10).map{Float($0)} var v2 = Array(0..<10).map{Float($0)} print(v1) print(v2) var cc = vCorrelationCoefficient(v1, v2: v2) print("cc: \(cc)") assert(scalarEqual(cc, scalar2: 1.0)) v2 = vAdd(v2, valueToAdd: 3.0) cc = vCorrelationCoefficient(v1, v2: v2) print("cc: \(cc)") assert(scalarEqual(cc, scalar2: 1.0)) // time it let iterations = 10000 let v3 = Array(1...100).map{Double($0)} // Naïve Swift Implementation var startTime = CFAbsoluteTimeGetCurrent() for _ in 0..<iterations { let avg = v3.reduce(0.0, +) / Double(v3.count) let centralized = v3.map{$0-avg} let length = centralized.reduce(0.0, {$0+$1*$1}) _ = centralized.map{$0/length} } let deltaTime1 = CFAbsoluteTimeGetCurrent() - startTime print(String(format: "deltaTime 1: %f\n", deltaTime1)) startTime = CFAbsoluteTimeGetCurrent() for _ in 0..<iterations { _ = vNormalizeToUnitLength(v3, centralized: true) } let deltaTime2 = CFAbsoluteTimeGetCurrent() - startTime print(String(format: "deltaTime 2: %f\n", deltaTime2)) print(String(format: "improve: %f\n", deltaTime1/deltaTime2)) print("Vector test: OK.\n") }
mit
d24639123996097c747988167e2063d7
27.272727
120
0.655627
3.241271
false
false
false
false
larrabetzu/iBasque-Radio
SwiftRadio/StationsViewController.swift
1
9751
// // StationsViewController.swift // Swift Radio // // Created by Matthew Fecher on 7/19/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import UIKit import MediaPlayer import AVFoundation class StationsViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var stationNowPlayingButton: UIButton! @IBOutlet weak var nowPlayingAnimationImageView: UIImageView! var stations = [RadioStation]() var currentStation: RadioStation? var currentTrack: Track? var firstTime = true //***************************************************************** // MARK: - ViewDidLoad //***************************************************************** override func viewDidLoad() { super.viewDidLoad() // Register 'Nothing Found' cell xib let cellNib = UINib(nibName: "NothingFoundCell", bundle: nil) tableView.register(cellNib, forCellReuseIdentifier: "NothingFound") // Load Data loadStationsFromJSON() // Setup TableView tableView.backgroundColor = UIColor.clear tableView.backgroundView = nil tableView.separatorStyle = UITableViewCellSeparatorStyle.none // Create NowPlaying Animation createNowPlayingAnimation() // Set AVFoundation category, required for background audio var error: NSError? var success: Bool do { try AVAudioSession.sharedInstance().setCategory( AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker) success = true } catch let error1 as NSError { error = error1 success = false } if !success { if DEBUG_LOG { print("Failed to set audio session category. Error: \(error.debugDescription)") } } } override func viewWillAppear(_ animated: Bool) { self.title = String.StationScreen.Title.localized // If a track is playing, display title & artist information and animation if currentTrack != nil && currentTrack!.isPlaying { let title = String.StationScreen.LiveMetaData.localized(with: currentStation!.name, currentTrack!.title, currentTrack!.artist) stationNowPlayingButton.setTitle(title, for: .normal) nowPlayingAnimationImageView.startAnimating() } else { nowPlayingAnimationImageView.stopAnimating() nowPlayingAnimationImageView.image = UIImage(named: "NowPlayingBars") } } //***************************************************************** // MARK: - Setup UI Elements //***************************************************************** func createNowPlayingAnimation() { nowPlayingAnimationImageView.animationImages = AnimationFrames.createFrames() nowPlayingAnimationImageView.animationDuration = 0.7 } //***************************************************************** // MARK: - Actions //***************************************************************** func nowPlayingBarButtonPressed() { performSegue(withIdentifier: "NowPlaying", sender: self) } @IBAction func nowPlayingPressed(sender: UIButton) { performSegue(withIdentifier: "NowPlaying", sender: self) } //***************************************************************** // MARK: - Load Station Data //***************************************************************** func loadStationsFromJSON() { // Turn on network indicator in status bar UIApplication.shared.isNetworkActivityIndicatorVisible = true // Get the Radio Stations DataManager.getStationDataWithSuccess() { (data) in // Turn off network indicator in status bar defer { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false } } if DEBUG_LOG { print("Stations JSON Found") } if let jsonString = String(data: data as Data!, encoding: String.Encoding.utf8){ self.stations = RadioStation.parseStations(jsonString: jsonString) // stations array populated, update table on main queue DispatchQueue.main.async(execute: { self.tableView.reloadData() self.view.setNeedsDisplay() }) } else { if DEBUG_LOG { print("JSON Station Loading Error") } } } } //***************************************************************** // MARK: - Segue //***************************************************************** override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "NowPlaying" { self.title = "" firstTime = false let nowPlayingVC = segue.destination as! NowPlayingViewController nowPlayingVC.delegate = self if let indexPath = (sender as? NSIndexPath) { // User clicked on row, load/reset station currentStation = stations[indexPath.row] nowPlayingVC.currentStation = currentStation nowPlayingVC.newStation = true } else { // User clicked on a now playing button if let currentTrack = currentTrack { // Return to NowPlaying controller without reloading station nowPlayingVC.track = currentTrack nowPlayingVC.currentStation = currentStation nowPlayingVC.newStation = false } else { // Issue with track, reload station nowPlayingVC.currentStation = currentStation nowPlayingVC.newStation = true } } } } } //***************************************************************** // MARK: - TableViewDataSource //***************************************************************** extension StationsViewController: UITableViewDataSource { // MARK: - Table view data source @objc(tableView:heightForRowAtIndexPath:) func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 88.0 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if stations.count == 0 { return 1 } else { return stations.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if stations.isEmpty { let cell = tableView.dequeueReusableCell(withIdentifier: "NothingFound", for: indexPath as IndexPath) cell.backgroundColor = UIColor.clear cell.selectionStyle = UITableViewCellSelectionStyle.none return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "StationCell", for: indexPath as IndexPath) as! StationTableViewCell // alternate background color if indexPath.row % 2 == 0 { cell.backgroundColor = UIColor.clear } else { cell.backgroundColor = UIColor.black.withAlphaComponent(0.2) } // Configure the cell... let station = stations[indexPath.row] cell.configureStationCell(station: station) return cell } } } //***************************************************************** // MARK: - TableViewDelegate //***************************************************************** extension StationsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: true) if !stations.isEmpty { // Set Now Playing Buttons let title = String.StationScreen.Live.localized(with: stations[indexPath.row].name) stationNowPlayingButton.setTitle(title, for: .normal) stationNowPlayingButton.isEnabled = true performSegue(withIdentifier: "NowPlaying", sender: indexPath) } } } //***************************************************************** // MARK: - NowPlayingViewControllerDelegate //***************************************************************** extension StationsViewController: NowPlayingViewControllerDelegate { func artworkDidUpdate(track: Track) { currentTrack?.artworkURL = track.artworkURL currentTrack?.artworkImage = track.artworkImage } func songMetaDataDidUpdate(track: Track) { currentTrack = track let title = String.StationScreen.LiveMetaData.localized(with: currentStation!.name, currentTrack!.title, currentTrack!.artist) stationNowPlayingButton.setTitle(title, for: .normal) } }
mit
5f6fcfc3db9fc63a510d81ba9f54fdbd
35.384328
137
0.518101
6.584065
false
false
false
false
dreamsxin/swift
test/SILGen/coverage_while.swift
8
4194
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -suppress-warnings -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_while %s | FileCheck %s // CHECK-LABEL: // coverage_while.eoo () -> () func eoo() { // CHECK: int_instrprof_increment var x : Int32 = 0 repeat { // CHECK: int_instrprof_increment // CHECK: sadd_with_overflow_Int32 x += 1 // CHECK: cmp_slt_Int32 } while x < 10 } // CHECK-LABEL: sil_coverage_map {{.*}}// coverage_while.foo func foo() -> Int32 { var x : Int32 = 0 // CHECK: [[@LINE+1]]:9 -> [[@LINE+1]]:17 : (0 + 1) while (x < 10) { x += 1 } // CHECK: [[@LINE+1]]:9 -> [[@LINE+1]]:22 : (0 + 2) while ((x - 1) > 0) { x -= 1 if (x % 2 == 0) { continue } } // CHECK: [[@LINE+1]]:9 -> [[@LINE+1]]:18 : ((0 + 4) - 5) while (x < 100) { x += 1 if (x == 10) { break } } // CHECK: [[@LINE+1]]:9 -> [[@LINE+1]]:18 : ((0 + 6) - 9) while (x < 100) { x += 1 while (true) { break } if (x % 2 == 0) { continue } // CHECK: [[@LINE-1]]:33 -> [[@LINE+2]]:4 : (6 - 8) if (x > 30) { break } } // CHECK: [[@LINE+1]]:10 -> [[@LINE+4]]:4 : 10 repeat { x -= 1 // CHECK: [[@LINE+1]]:11 -> [[@LINE+1]]:16 : 10 } while x > 0 // CHECK: [[@LINE+1]]:9 -> [[@LINE+1]]:18 : ((0 + 11) - 12) while (x < 100) { if (x == 40) { // CHECK: [[@LINE]]:18 -> [[@LINE+2]]:6 : 12 return x } x += 1 } var y : Int32? = 2 // CHECK: [[@LINE+1]]:9 -> [[@LINE+1]]:15 : ((0 + 13) - 12) while x > 30, let _ = y { y = nil } // TODO: [[@LINE+1]]:9 -> [[@LINE+1]]:18 : ((0 + 14) - 12) while let _ = y { } // CHECK: [[@LINE-1]]:4 -> [[@LINE+1]]:11 : (0 - 12) return x } // rdar://problem/24572268 // CHECK-LABEL: sil_coverage_map {{.*}}// coverage_while.goo func goo() { var x : Int32 = 0 repeat { // CHECK-DAG: [[@LINE]]:10 -> [[@LINE+2]]:4 : [[RWS1:[0-9]+]] x += 1 } while x < 10 // CHECK-DAG: [[@LINE]]:11 -> [[@LINE]]:17 : [[RWS1]] repeat { // CHECK-DAG: [[@LINE]]:10 -> [[@LINE+5]]:4 : [[RWS2:[0-9]+]] x += 1 if (x % 2 == 0) { // CHECK-DAG: [[@LINE]]:21 -> [[@LINE+2]]:6 : [[CONT1:[0-9]+]] continue } // CHECK-DAG: [[@LINE]]:6 -> [[@LINE+1]]:4 : ([[RWS2]] - [[CONT1]]) } while x < 20 // CHECK-DAG: [[@LINE]]:11 -> [[@LINE]]:17 : [[RWS2]] repeat { // CHECK-DAG: [[@LINE]]:10 -> [[@LINE+5]]:4 : [[RWS3:[0-9]+]] x += 1 if (x % 2 == 0) { // CHECK-DAG: [[@LINE]]:21 -> [[@LINE+2]]:6 : [[BRK1:[0-9]+]] break } // CHECK-DAG: [[@LINE]]:6 -> [[@LINE+1]]:4 : ([[RWS3]] - [[BRK1]]) } while x < 30 // CHECK-DAG: [[@LINE]]:11 -> [[@LINE]]:17 : ([[RWS3]] - [[BRK1]]) repeat { // CHECK-DAG: [[@LINE]]:10 -> [[@LINE+10]]:4 : [[RWS4:[0-9]+]] x += 1 if (x % 2 == 0) { // CHECK-DAG: [[@LINE]]:21 -> [[@LINE+2]]:6 : [[CONT2:[0-9]+]] continue } // CHECK-DAG: [[@LINE]]:6 -> [[@LINE+6]]:4 : ([[RWS4]] - [[CONT2]]) x += 1 if (x % 7 == 0) { // CHECK-DAG: [[@LINE]]:21 -> [[@LINE+2]]:6 : [[BRK2:[0-9]+]] break } // CHECK-DAG: [[@LINE]]:6 -> [[@LINE+2]]:4 : (([[RWS4]] - [[CONT2]]) - [[BRK2]]) x += 1 } while x < 40 // CHECK-DAG: [[@LINE]]:11 -> [[@LINE]]:17 : ([[RWS4]] - [[BRK2]]) repeat { // CHECK-DAG: [[@LINE]]:10 -> [[@LINE+1]]:4 : [[RWS5:[0-9]+]] } while false // CHECK-DAG: [[@LINE]]:11 -> [[@LINE]]:16 : [[RWS5]] repeat { // CHECK-DAG: [[@LINE]]:10 -> [[@LINE+4]]:4 : [[RWS6:[0-9]+]] repeat { // CHECK-DAG: [[@LINE]]:12 -> [[@LINE+2]]:6 : [[RWS7:[0-9]+]] return } while false // CHECK-DAG: [[@LINE]]:13 -> [[@LINE]]:18 : zero } while false // CHECK-DAG: [[@LINE]]:11 -> [[@LINE]]:16 : ([[RWS6]] - [[RWS7]]) repeat { // CHECK-DAG: [[@LINE]]:10 -> [[@LINE+6]]:4 : [[RWS8:[0-9]+]] repeat { // CHECK-DAG: [[@LINE]]:12 -> [[@LINE+4]]:6 : [[RWS9:[0-9]+]] if (true) { // CHECK-DAG: [[@LINE]]:17 -> [[@LINE+2]]:8 : [[RET1:[0-9]+]] return } } while false // CHECK-DAG: [[@LINE]]:13 -> [[@LINE]]:18 : ([[RWS9]] - [[RET1]]) } while false // CHECK-DAG: [[@LINE]]:11 -> [[@LINE]]:16 : ([[RWS8]] - [[RET1]]) // TODO(vsk): need tests for fail and throw statements. } eoo() foo() goo()
apache-2.0
4072d477bb93834275dea558999924bb
31.511628
192
0.441822
2.691913
false
false
false
false
mrdepth/Neocom
database/NCDatabase/SDE/main.swift
2
51364
// // main.swift // SDE // // Created by Artem Shimanski on 16.12.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import Cocoa import CoreText public typealias UIImage = Data class ImageValueTransformer: ValueTransformer { override func reverseTransformedValue(_ value: Any?) -> Any? { return value } } ValueTransformer.setValueTransformer(ImageValueTransformer(), forName: NSValueTransformerName("ImageValueTransformer")) enum SDEDgmppItemCategoryID: Int32 { case none = 0 case hi case med case low case rig case subsystem case mode case charge case drone case fighter case implant case booster case ship case structure case service case structureFighter case structureRig } enum NCDBRegionID: Int { case whSpace = 11000000 } extension NSColor { public convenience init(number: UInt) { var n = number var abgr = [CGFloat]() for _ in 0...3 { let byte = n & 0xFF abgr.append(CGFloat(byte) / 255.0) n >>= 8 } self.init(red: abgr[3], green: abgr[2], blue: abgr[1], alpha: abgr[0]) } public convenience init?(string: String) { let scanner = Scanner(string: string) var rgba: UInt32 = 0 if scanner.scanHexInt32(&rgba) { self.init(number:UInt(rgba)) } else { let key = string.capitalized for colorList in NSColorList.availableColorLists() { guard let color = colorList.color(withKey: key) else {continue} self.init(cgColor: color.cgColor) return } } return nil } } extension NSAttributedString { convenience init(html: String?) { var html = html ?? "" html = html.replacingOccurrences(of: "<br>", with: "\n", options: [.caseInsensitive], range: nil) html = html.replacingOccurrences(of: "<p>", with: "\n", options: [.caseInsensitive], range: nil) let s = NSMutableAttributedString(string: html) let options: NSRegularExpression.Options = [.caseInsensitive, .dotMatchesLineSeparators] var expression = try! NSRegularExpression(pattern: "<(a[^>]*href|url)=[\"']?(.*?)[\"']?>(.*?)<\\/(a|url)>", options: options) for result in expression.matches(in: s.string, options: [], range: NSMakeRange(0, s.length)).reversed() { let replace = s.attributedSubstring(from: result.rangeAt(3)).mutableCopy() as! NSMutableAttributedString let url = URL(string: s.attributedSubstring(from: result.rangeAt(2)).string.replacingOccurrences(of: " ", with: "")) replace.addAttribute(NSLinkAttributeName, value: url!, range: NSMakeRange(0, replace.length)) s.replaceCharacters(in: result.rangeAt(0), with: replace) } expression = try! NSRegularExpression(pattern: "<b[^>]*>(.*?)</b>", options: options) for result in expression.matches(in: s.string, options: [], range: NSMakeRange(0, s.length)).reversed() { let replace = s.attributedSubstring(from: result.rangeAt(1)).mutableCopy() as! NSMutableAttributedString replace.addAttribute("UIFontDescriptorSymbolicTraits", value: CTFontSymbolicTraits.boldTrait.rawValue, range: NSMakeRange(0, replace.length)) s.replaceCharacters(in: result.rangeAt(0), with: replace) } expression = try! NSRegularExpression(pattern: "<i[^>]*>(.*?)</i>", options: options) for result in expression.matches(in: s.string, options: [], range: NSMakeRange(0, s.length)).reversed() { let replace = s.attributedSubstring(from: result.rangeAt(1)).mutableCopy() as! NSMutableAttributedString replace.addAttribute("UIFontDescriptorSymbolicTraits", value: CTFontSymbolicTraits.italicTrait.rawValue, range: NSMakeRange(0, replace.length)) s.replaceCharacters(in: result.rangeAt(0), with: replace) } expression = try! NSRegularExpression(pattern: "<u[^>]*>(.*?)</u>", options: options) for result in expression.matches(in: s.string, options: [], range: NSMakeRange(0, s.length)).reversed() { let replace = s.attributedSubstring(from: result.rangeAt(1)).mutableCopy() as! NSMutableAttributedString replace.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, replace.length)) s.replaceCharacters(in: result.rangeAt(0), with: replace) } expression = try! NSRegularExpression(pattern: "<(color|font)[^>]*=[\"']?(.*?)[\"']?\\s*?>(.*?)</(color|font)>", options: [.caseInsensitive]) for result in expression.matches(in: s.string, options: [], range: NSMakeRange(0, s.length)).reversed() { let key = s.attributedSubstring(from: result.rangeAt(2)).string let replace = s.attributedSubstring(from: result.rangeAt(3)).mutableCopy() as! NSMutableAttributedString if let color = NSColor(string: key) { replace.addAttribute(NSForegroundColorAttributeName, value: color, range: NSMakeRange(0, replace.length)) } s.replaceCharacters(in: result.rangeAt(0), with: replace) } expression = try! NSRegularExpression(pattern: "</?.*?>", options: options) for result in expression.matches(in: s.string, options: [], range: NSMakeRange(0, s.length)).reversed() { s.replaceCharacters(in: result.rangeAt(0), with: NSAttributedString(string: "")) } self.init(attributedString: s) } } extension String { static let regex = try! NSRegularExpression(pattern: "\\\\u(.{4})", options: [.caseInsensitive]) func replacingEscapes() -> String { let s = NSMutableString(string: self) for result in String.regex.matches(in: self, options: [], range: NSMakeRange(0, s.length)).reversed() { let hexString = s.substring(with: result.rangeAt(1)) let scanner = Scanner(string: hexString) var i: UInt32 = 0 if !scanner.scanHexInt32(&i) { exit(EXIT_FAILURE) } s.replaceCharacters(in: result.rangeAt(0), with: String(unichar(i))) } s.replaceOccurrences(of: "\\r", with: "", options: [], range: NSMakeRange(0, s.length)) s.replaceOccurrences(of: "\\n", with: "\n", options: [], range: NSMakeRange(0, s.length)) return String(s) } } class SQLiteDB { var db: OpaquePointer? init(filePath: String) throws { if sqlite3_open_v2(filePath, &db, SQLITE_OPEN_READONLY, nil) != SQLITE_OK { exit(EXIT_FAILURE) } } func exec(_ sql: String, block: ([String: Any]) -> Void) throws { var stmt: OpaquePointer? if sqlite3_prepare(db, sql, Int32(sql.lengthOfBytes(using: .utf8)), &stmt, nil) != SQLITE_OK { exit(EXIT_FAILURE) } while sqlite3_step(stmt) == SQLITE_ROW { let n = sqlite3_column_count(stmt) var dic = [String: Any]() for i in 0..<n { let name = String(cString: sqlite3_column_name(stmt, i)) switch sqlite3_column_type(stmt, i) { case SQLITE_INTEGER: let int = sqlite3_column_int64(stmt, i) dic[name] = int case SQLITE_FLOAT: let double = sqlite3_column_double(stmt, i) dic[name] = double case SQLITE_BLOB: let size = sqlite3_column_bytes(stmt, i) if let blob = sqlite3_column_blob(stmt, i) { let data = Data(bytes: blob, count: Int(size)) if data.count > 0 { dic[name] = data } } case SQLITE_NULL: break case SQLITE_TEXT: let text = String(cString: sqlite3_column_text(stmt, i)) if !text.isEmpty { dic[name] = text } default: print ("Invalid SQLite type \(sqlite3_column_type(stmt, i))") exit(EXIT_FAILURE) break } } block(dic) } sqlite3_finalize(stmt) } } var args = [String: String]() var key: String? for arg in CommandLine.arguments[1..<CommandLine.arguments.count] { if arg.hasPrefix("-") { key = arg } else if let k = key { args[k] = arg key = nil } else { exit(EXIT_FAILURE) } } let sde = args["-sde"]! let database = try! SQLiteDB(filePath: sde) let out = URL(fileURLWithPath: args["-out"]!) let iconsURL = URL(fileURLWithPath: args["-icons"]!) let typesURL = URL(fileURLWithPath: args["-types"]!) let factionsURL = URL(fileURLWithPath: args["-factions"]!) let expansion = args["-expansion"]! try? FileManager.default.removeItem(at: out) let managedObjectModel = NSManagedObjectModel.mergedModel(from: nil)! let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) try! persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: out, options: [NSSQLitePragmasOption:["journal_mode": "OFF"]]) let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = persistentStoreCoordinator // MARK: eveIcons print ("eveIcons") var eveIcons = [AnyHashable: SDEEveIcon]() extension SDEEveIcon { convenience init?(iconFile: String) { let url = iconsURL.appendingPathComponent(iconFile).appendingPathExtension("png") guard FileManager.default.fileExists(atPath: url.path) else {return nil} self.init(context: context) self.iconFile = iconFile image = SDEEveIconImage(context: context) image?.image = try! UIImage(contentsOf: url) eveIcons[iconFile] = self } convenience init?(factionFile: String) { let url = factionsURL.appendingPathComponent(factionFile) guard FileManager.default.fileExists(atPath: url.path) else {return nil} self.init(context: context) self.iconFile = url.deletingPathExtension().lastPathComponent image = SDEEveIconImage(context: context) image?.image = try! UIImage(contentsOf: url) eveIcons[factionFile] = self } convenience init?(typeFile: String) { let url = typesURL.appendingPathComponent(typeFile).appendingPathExtension("png") guard FileManager.default.fileExists(atPath: url.path) else {return nil} self.init(context: context) self.iconFile = url.deletingPathExtension().lastPathComponent image = SDEEveIconImage(context: context) image?.image = try! UIImage(contentsOf: url) eveIcons[typeFile] = self } } try! database.exec("select * from eveIcons") { row in let iconFile = row["iconFile"] as! String guard let icon = SDEEveIcon(iconFile: iconFile) else {return} eveIcons[row["iconID"] as! NSNumber] = icon } for iconFile in ["09_07", "105_32", "50_13", "38_193", "38_194", "38_195", "38_174", "17_04", "74_14", "23_03", "18_02", "33_02", "79_01", "79_02", "79_03", "79_04", "79_05", "79_06"] { var eveIcon: [String: Any]? try! database.exec("SELECT * FROM eveIcons WHERE iconFile == \"\(iconFile)\"") { row in eveIcon = row } if eveIcon != nil { continue } guard let _ = SDEEveIcon(iconFile: iconFile) else { print ("Warning: icon not found \"\(iconFile)\"") continue } } try! database.exec("SELECT * FROM ramActivities") { row in guard let iconNo = row["iconNo"] as? String else {return} if eveIcons[iconNo] == nil { guard let _ = SDEEveIcon(iconFile: iconNo) else { print ("Warning: icon not found \"\(iconNo)\"") return } } } try! database.exec("SELECT * FROM npcGroup WHERE iconName IS NOT NULL GROUP BY iconName") { row in guard let iconName = row["iconName"] as? String else {return} if eveIcons[iconName] == nil { guard let _ = SDEEveIcon(factionFile: iconName) else { print ("Warning: icon not found \"\(iconName)\"") return } } } try! database.exec("SELECT * FROM invTypes WHERE imageName IS NOT NULL GROUP BY imageName") { row in guard let imageName = row["imageName"] as? String else {return} if eveIcons[imageName] == nil { guard let _ = SDEEveIcon(typeFile: imageName) else { print ("Warning: icon not found \"\(imageName)\"") return } } } // MARK: eveUnits print ("eveUnits") var eveUnits = [NSNumber: SDEEveUnit]() try! database.exec("SELECT * FROM eveUnits") { row in let unit = SDEEveUnit(context: context) unit.unitID = Int32(row["unitID"] as! NSNumber) unit.displayName = row["displayName"] as? String eveUnits[row["unitID"] as! NSNumber] = unit } // MARK: chrRaces print ("chrRaces") var chrRaces = [NSNumber: SDEChrRace]() try! database.exec("SELECT * FROM chrRaces") { row in let race = SDEChrRace(context: context) race.raceID = Int32(row["raceID"] as! NSNumber) race.raceName = row["raceName"] as? String race.icon = row["iconID"] != nil ? eveIcons[row["iconID"] as! NSNumber] : nil chrRaces[race.raceID as NSNumber] = race } // MARK: chrFactions print ("chrFactions") var chrFactions = [NSNumber: SDEChrFaction]() try! database.exec("SELECT * FROM chrFactions") { row in let faction = SDEChrFaction(context: context) faction.factionID = Int32(row["factionID"] as! NSNumber) faction.factionName = row["factionName"] as? String faction.icon = row["iconID"] != nil ? eveIcons[row["iconID"] as! NSNumber] : nil faction.race = chrRaces[row["raceIDs"] as! NSNumber] chrFactions[faction.factionID as NSNumber] = faction } // MARK: chrBloodlines print ("chrBloodlines") var chrBloodlines = [NSNumber: SDEChrBloodline]() try! database.exec("SELECT * FROM chrBloodlines") { row in let bloodline = SDEChrBloodline(context: context) bloodline.bloodlineID = Int32(row["bloodlineID"] as! NSNumber) bloodline.bloodlineName = row["bloodlineName"] as? String bloodline.icon = row["iconID"] != nil ? eveIcons[row["iconID"] as! NSNumber] : nil bloodline.race = chrRaces[row["raceID"] as! NSNumber] chrBloodlines[bloodline.bloodlineID as NSNumber] = bloodline } // MARK: chrAncestries print ("chrAncestries") var chrAncestries = [NSNumber: SDEChrAncestry]() try! database.exec("SELECT * FROM chrAncestries") { row in let ancestry = SDEChrAncestry(context: context) ancestry.ancestryID = Int32(row["ancestryID"] as! NSNumber) ancestry.ancestryName = row["ancestryName"] as? String ancestry.icon = row["iconID"] != nil ? eveIcons[row["iconID"] as! NSNumber] : nil ancestry.bloodline = chrBloodlines[row["bloodlineID"] as! NSNumber] chrAncestries[ancestry.ancestryID as NSNumber] = ancestry } // MARK: invCategories print ("invCategories") var invCategories = [NSNumber: SDEInvCategory]() try! database.exec("SELECT * FROM invCategories") { row in let category = SDEInvCategory(context: context) category.categoryID = Int32(row["categoryID"] as! NSNumber) category.categoryName = row["categoryName"] as? String category.published = (row["published"] as! NSNumber) == 1 category.icon = row["iconID"] != nil ? eveIcons[row["iconID"] as! NSNumber] : nil invCategories[category.categoryID as NSNumber] = category } // MARK: invGroups print ("invGroups") var invGroups = [NSNumber: SDEInvGroup]() try! database.exec("SELECT * FROM invGroups") { row in let group = SDEInvGroup(context: context) group.groupID = Int32(row["groupID"] as! NSNumber) group.groupName = row["groupName"] as? String group.published = (row["published"] as! NSNumber) == 1 group.category = invCategories[row["categoryID"] as! NSNumber] group.icon = row["iconID"] != nil ? eveIcons[row["iconID"] as! NSNumber] : nil invGroups[group.groupID as NSNumber] = group } // MARK: invMarketGroups print ("invMarketGroups") var invMarketGroups = [NSNumber: SDEInvMarketGroup]() var marketGroupsParent = [NSNumber: NSNumber]() try! database.exec("SELECT * FROM invMarketGroups") { row in let marketGroup = SDEInvMarketGroup(context: context) marketGroup.marketGroupID = Int32(row["marketGroupID"] as! NSNumber) marketGroup.marketGroupName = row["marketGroupName"] as? String marketGroup.icon = row["iconID"] != nil ? eveIcons[row["iconID"] as! NSNumber] : nil if let parentGroupID = row["parentGroupID"] as? NSNumber { marketGroupsParent[marketGroup.marketGroupID as NSNumber] = parentGroupID } invMarketGroups[marketGroup.marketGroupID as NSNumber] = marketGroup } for (groupID, parentID) in marketGroupsParent { invMarketGroups[groupID]?.parentGroup = invMarketGroups[parentID] } // MARK: invMetaGroups print ("invMetaGroups") var invMetaGroups = [NSNumber: SDEInvMetaGroup]() try! database.exec("SELECT * FROM invMetaGroups") { row in let metaGroup = SDEInvMetaGroup(context: context) metaGroup.metaGroupID = Int32(row["metaGroupID"] as! NSNumber) metaGroup.metaGroupName = row["metaGroupName"] as? String metaGroup.icon = row["iconID"] != nil ? eveIcons[row["iconID"] as! NSNumber] : nil invMetaGroups[metaGroup.metaGroupID as NSNumber] = metaGroup } //let defaultMetaGroup = SDEInvMetaGroup(context: context) //defaultMetaGroup.metaGroupID = 1000 //defaultMetaGroup.metaGroupName = "" let defaultMetaGroup = invMetaGroups[1] let unpublishedMetaGroup = SDEInvMetaGroup(context: context) unpublishedMetaGroup.metaGroupID = 1001 unpublishedMetaGroup.metaGroupName = "Unpublished" // MARK: invMetaTypes print ("invMetaTypes") var invMetaTypes = [NSNumber: SDEInvMetaGroup]() var invParentTypes = [NSNumber: NSNumber]() try! database.exec("SELECT * FROM invMetaTypes") { row in let typeID = row["typeID"] as! NSNumber invMetaTypes[typeID] = invMetaGroups[row["metaGroupID"] as! NSNumber] if let parentType = row["parentTypeID"] as? NSNumber { invParentTypes[typeID] = parentType } } // MARK: invTypes print ("invTypes") var invTypes = [NSNumber: SDEInvType]() try! database.exec("SELECT * FROM invTypes") { row in let type = SDEInvType(context: context) type.typeID = Int32(row["typeID"] as! NSNumber) type.basePrice = Double(row["basePrice"] as! NSNumber) type.capacity = Double(row["capacity"] as! NSNumber) type.mass = Double(row["mass"] as! NSNumber) type.portionSize = Int32(row["portionSize"] as! NSNumber) type.group = invGroups[row["groupID"] as! NSNumber] type.published = (row["published"] as! Int64) == 1 && type.group!.published type.radius = row["radius"] != nil ? Double(row["radius"] as! NSNumber) : 0 type.volume = row["volume"] != nil ? Double(row["volume"] as! NSNumber) : 0 type.marketGroup = row["marketGroupID"] != nil ? invMarketGroups[row["marketGroupID"] as! NSNumber] : nil type.race = row["raceID"] != nil ? chrRaces[row["raceID"] as! NSNumber] : nil type.typeName = (row["typeName"] as! String).replacingEscapes() if let imageName = row["imageName"] as? String, let image = eveIcons[imageName] { type.icon = image } else if let iconID = row["iconID"] as? NSNumber, let icon = eveIcons[iconID] { type.icon = icon } if type.published { type.metaGroup = invMetaTypes[type.typeID as NSNumber] ?? defaultMetaGroup } else { type.metaGroup = unpublishedMetaGroup } var sections = [String:[String]]() try! database.exec("SELECT a.*, b.typeName FROM invTraits AS a LEFT JOIN invTypes as b ON a.skillID=b.typeID WHERE a.typeID = \(type.typeID) ORDER BY traitID") { row in let skillID = row["skillID"] as? NSNumber let skillName = row["typeName"] as? String // let typeID = row["typeID"] as! NSNumber let bonus = row["bonus"] as? NSNumber let bonusText = row["bonusText"] as! String let unitID = row["unitID"] as? NSNumber let trait: String if let bonus = bonus?.doubleValue, let unitID = unitID, let unit = eveUnits[unitID] { var int: Double = 0 if modf(bonus, &int) != 0 { trait = "<color=white><b>\(bonus)\(unit.displayName!)</b></color> \(bonusText)" } else { trait = "<color=white><b>\(Int(int))\(unit.displayName!)</b></color> \(bonusText)" } } else { trait = "<color=white><b>-</b></color> \(bonusText)" } let section: String if let skillName = skillName, let skillID = skillID?.intValue { section = "<a href=showinfo:\(skillID)>\(skillName)</a> bonuses (per skill level):" } else { section = "<b>Role Bonus</b>:" } var array = sections[section] ?? [] array.append(trait) sections[section] = array } let trait = sections.sorted{return $0.key < $1.key}.map { return "\($0.key)\n\($0.value.joined(separator: "\n"))" }.joined(separator: "\n\n") var description = (row["description"] as? String)?.replacingEscapes() ?? "" if !trait.isEmpty { description += "\n\n" + trait } type.typeDescription = SDETxtDescription(context: context) type.typeDescription?.text = NSAttributedString(html: description) invTypes[type.typeID as NSNumber] = type } for (typeID, type) in invTypes { if let parentTypeID = invParentTypes[typeID as NSNumber] { type.parentType = invTypes[parentTypeID] } } // MARK: dgmAttributeCategories print ("dgmAttributeCategories") var dgmAttributeCategories = [NSNumber: SDEDgmAttributeCategory]() try! database.exec("SELECT * FROM dgmAttributeCategories") { row in let attributeCategory = SDEDgmAttributeCategory(context: context) attributeCategory.categoryID = Int32(row["categoryID"] as! NSNumber) attributeCategory.categoryName = row["categoryName"] as? String dgmAttributeCategories[attributeCategory.categoryID as NSNumber] = attributeCategory } // MARK: dgmAttributeTypes print ("dgmAttributeTypes") var dgmAttributeTypes = [NSNumber: SDEDgmAttributeType]() try! database.exec("SELECT * FROM dgmAttributeTypes") { row in let attributeType = SDEDgmAttributeType(context: context) attributeType.attributeID = Int32(row["attributeID"] as! NSNumber) attributeType.attributeName = row["attributeName"] as? String attributeType.displayName = row["displayName"] as? String attributeType.published = (row["published"] as! Int64) == 1 attributeType.attributeCategory = row["categoryID"] != nil ? dgmAttributeCategories[row["categoryID"] as! NSNumber] : nil attributeType.icon = row["iconID"] != nil ? eveIcons[row["iconID"] as! NSNumber] : nil attributeType.unit = row["unitID"] != nil ? eveUnits[row["unitID"] as! NSNumber] : nil dgmAttributeTypes[attributeType.attributeID as NSNumber] = attributeType } // MARK: dgmTypeAttributes print ("dgmTypeAttributes") let NCDBMetaGroupAttributeID = 1692 as Int32 let NCDBMetaLevelAttributeID = 633 as Int32 try! database.exec("SELECT * FROM dgmTypeAttributes") { row in guard let type = invTypes[row["typeID"] as! NSNumber] else {return} let attributeType = dgmAttributeTypes[row["attributeID"] as! NSNumber]! let attribute = SDEDgmTypeAttribute(context: context) attribute.type = type attribute.attributeType = attributeType attribute.value = (row["value"] as! NSNumber).doubleValue if attributeType.attributeID == NCDBMetaGroupAttributeID { if let metaGroup = invMetaGroups[Int(attribute.value) as NSNumber], type.published { type.metaGroup = metaGroup } } if attributeType.attributeID == NCDBMetaLevelAttributeID { type.metaLevel = Int16(attribute.value) } } // MARK: dgmEffects print ("dgmEffects") var dgmEffects = [NSNumber: SDEDgmEffect]() try! database.exec("SELECT * FROM dgmEffects") { row in let effect = SDEDgmEffect(context: context) effect.effectID = Int32(row["effectID"] as! NSNumber) dgmEffects[effect.effectID as NSNumber] = effect } // MARK: dgmTypeEffects print ("dgmTypeEffects") try! database.exec("SELECT * FROM dgmTypeEffects") { row in guard let type = invTypes[row["typeID"] as! NSNumber] else {return} guard let effect = dgmEffects[row["effectID"] as! NSNumber] else {return} effect.addToTypes(type) } // MARK: certMasteryLevels print ("certMasteryLevels") var certMasteryLevels = [NSNumber: SDECertMasteryLevel]() try! database.exec("SELECT * FROM certSkills GROUP BY certLevelInt") { row in let level = SDECertMasteryLevel(context: context) level.level = Int16(row["certLevelInt"] as! NSNumber) level.displayName = row["certLevelText"] as? String level.icon = eveIcons["79_0\(level.level + 2)"]! certMasteryLevels[level.level as NSNumber] = level } // MARK: certCerts print ("certCerts") var certCerts = [NSNumber: SDECertCertificate]() var certMasteries = [IndexPath: SDECertMastery]() try! database.exec("SELECT * FROM certCerts") { row in let certificate = SDECertCertificate(context: context) certificate.certificateID = Int32(row["certID"] as! NSNumber) certificate.certificateName = row["name"] as? String certificate.group = invGroups[row["groupID"] as! NSNumber] certificate.certificateDescription = SDETxtDescription(context: context) certificate.certificateDescription?.text = NSAttributedString(html: (row["description"] as? String)?.replacingEscapes()) for (_, level) in certMasteryLevels { let mastery = SDECertMastery(context: context) mastery.certificate = certificate mastery.level = level certMasteries[IndexPath(item: Int(mastery.level!.level), section: Int(certificate.certificateID))] = mastery } certCerts[certificate.certificateID as NSNumber] = certificate } // MARK: certMasteries print ("certMasteries") try! database.exec("SELECT * FROM certMasteries") { row in let certificate = certCerts[row["certID"] as! NSNumber]! let mastery = certMasteries[IndexPath(item: Int(row["masteryLevel"] as! NSNumber), section: Int(row["certID"] as! NSNumber))]! mastery.certificate?.addToTypes(invTypes[row["typeID"] as! NSNumber]!) } // MARK: certSkills print ("certSkills") try! database.exec("SELECT * FROM certSkills") { row in let certID = row["certID"] as! NSNumber let certLevel = row["certLevelInt"] as! NSNumber let skill = SDECertSkill(context: context) skill.mastery = certMasteries[IndexPath(item: certLevel.intValue, section: certID.intValue)]! skill.skillLevel = (row["skillLevel"] as! NSNumber).int16Value skill.type = invTypes[row["skillID"] as! NSNumber]! } // MARK: mapRegions print ("mapRegions") var mapRegions = [NSNumber: SDEMapRegion]() try! database.exec("SELECT * FROM mapRegions") { row in let region = SDEMapRegion(context: context) region.regionID = Int32(row["regionID"] as! NSNumber) region.regionName = row["regionName"] as? String region.faction = row["factionID"] != nil ? chrFactions[row["factionID"] as! NSNumber] : nil mapRegions[region.regionID as NSNumber] = region } // MARK: mapConstellations print ("mapConstellations") var mapConstellations = [NSNumber: SDEMapConstellation]() try! database.exec("SELECT * FROM mapConstellations") { row in let constellation = SDEMapConstellation(context: context) constellation.constellationID = Int32(row["constellationID"] as! NSNumber) constellation.constellationName = row["constellationName"] as? String constellation.region = mapRegions[row["regionID"] as! NSNumber] constellation.faction = row["factionID"] != nil ? chrFactions[row["factionID"] as! NSNumber] : nil mapConstellations[constellation.constellationID as NSNumber] = constellation } // MARK: mapSolarSystems print ("mapSolarSystems") var mapSolarSystems = [NSNumber: SDEMapSolarSystem]() try! database.exec("SELECT * FROM mapSolarSystems") { row in let solarSystem = SDEMapSolarSystem(context: context) solarSystem.solarSystemID = Int32(row["solarSystemID"] as! NSNumber) solarSystem.solarSystemName = row["solarSystemName"] as? String solarSystem.security = Float(row["security"] as! NSNumber) solarSystem.constellation = mapConstellations[row["constellationID"] as! NSNumber] solarSystem.faction = row["factionID"] != nil ? chrFactions[row["factionID"] as! NSNumber] : nil mapSolarSystems[solarSystem.solarSystemID as NSNumber] = solarSystem } mapConstellations.values.forEach { guard let array = ($0.solarSystems?.allObjects as? [SDEMapSolarSystem]), !array.isEmpty else { $0.security = 0 return } $0.security = array.map {$0.security}.reduce(0, +) / Float(array.count) } mapRegions.values.forEach { if let array = ($0.constellations?.allObjects as? [SDEMapConstellation])?.map ({return $0.solarSystems?.allObjects as? [SDEMapSolarSystem] ?? []}).joined(), !array.isEmpty { $0.security = array.map {$0.security}.reduce(0, +) / Float(array.count) } else { $0.security = 0 } if $0.regionID >= Int32(NCDBRegionID.whSpace.rawValue) { $0.securityClass = -1 } else { switch $0.security { case 0.5...1: $0.securityClass = 1 case -1...0: $0.securityClass = 0 default: $0.securityClass = 0.5 } } } // MARK: mapDenormalize print ("mapDenormalize") var mapDenormalize = [NSNumber: SDEMapDenormalize]() try! database.exec("SELECT * FROM mapDenormalize WHERE groupID IN (7, 8, 15) AND itemID NOT IN (SELECT stationID FROM staStations)") { row in let denormalize = SDEMapDenormalize(context: context) denormalize.itemID = Int32(row["itemID"] as! NSNumber) denormalize.itemName = row["itemName"] as? String denormalize.security = Float(row["security"] as! NSNumber) denormalize.region = row["regionID"] != nil ? mapRegions[row["regionID"] as! NSNumber] : nil denormalize.constellation = row["constellationID"] != nil ? mapConstellations[row["constellationID"] as! NSNumber] : nil denormalize.solarSystem = row["solarSystemID"] != nil ? mapSolarSystems[row["solarSystemID"] as! NSNumber] : nil denormalize.type = invTypes[row["typeID"] as! NSNumber] mapDenormalize[denormalize.itemID as NSNumber] = denormalize } // MARK: staStations print ("staStations") var staStations = [NSNumber: SDEStaStation]() try! database.exec("SELECT * FROM staStations") { row in let station = SDEStaStation(context: context) station.stationID = Int32(row["stationID"] as! NSNumber) station.stationName = row["stationName"] as? String station.security = Float(row["security"] as! NSNumber) station.stationType = invTypes[row["stationTypeID"] as! NSNumber]! station.solarSystem = row["solarSystemID"] != nil ? mapSolarSystems[row["solarSystemID"] as! NSNumber] : nil staStations[station.stationID as NSNumber] = station } // MARK: npcGroups print ("npcGroups") var npcGroups = [NSNumber: SDENpcGroup]() var npcParentGroup = [NSNumber: NSNumber]() try! database.exec("SELECT * FROM npcGroup") { row in let group = SDENpcGroup(context: context) group.npcGroupName = row["npcGroupName"] as? String group.group = row["groupID"] != nil ? invGroups[row["groupID"] as! NSNumber] : nil group.icon = row["iconName"] != nil ? eveIcons[row["iconName"] as! String] : nil if let parent = row["parentNpcGroupID"] as? NSNumber { npcParentGroup[row["npcGroupID"] as! NSNumber] = parent } npcGroups[row["npcGroupID"] as! NSNumber] = group } for (groupID, parentGroupID) in npcParentGroup { npcGroups[groupID]?.parentNpcGroup = npcGroups[parentGroupID] } // MARK: ramActivities print ("ramActivities") var ramActivities = [NSNumber: SDERamActivity]() try! database.exec("SELECT * FROM ramActivities") { row in let activity = SDERamActivity(context: context) activity.activityID = Int32(row["activityID"] as! NSNumber) activity.activityName = row["activityName"] as? String activity.published = (row["published"] as! Int64) == 1 activity.icon = row["iconNo"] != nil ? eveIcons[row["iconNo"] as! String] : nil ramActivities[activity.activityID as NSNumber] = activity } // MARK: ramAssemblyLineTypes print ("ramAssemblyLineTypes") var ramAssemblyLineTypes = [NSNumber: SDERamAssemblyLineType]() try! database.exec("SELECT * FROM ramAssemblyLineTypes") { row in let assemblyLineType = SDERamAssemblyLineType(context: context) assemblyLineType.assemblyLineTypeID = Int32(row["assemblyLineTypeID"] as! NSNumber) assemblyLineType.assemblyLineTypeName = row["assemblyLineTypeName"] as? String assemblyLineType.baseTimeMultiplier = Float(row["baseTimeMultiplier"] as! NSNumber) assemblyLineType.baseMaterialMultiplier = Float(row["baseMaterialMultiplier"] as! NSNumber) assemblyLineType.baseCostMultiplier = Float(row["baseCostMultiplier"] as! NSNumber) assemblyLineType.minCostPerHour = row["minCostPerHour"] != nil ? Float(row["minCostPerHour"] as! NSNumber) : 0 assemblyLineType.volume = Float(row["volume"] as! NSNumber) assemblyLineType.activity = ramActivities[row["activityID"] as! NSNumber] ramAssemblyLineTypes[assemblyLineType.assemblyLineTypeID as NSNumber] = assemblyLineType } // MARK: ramInstallationTypeContents print ("ramInstallationTypeContents") try! database.exec("SELECT * FROM ramInstallationTypeContents") { row in let installationTypeContent = SDERamInstallationTypeContent(context: context) installationTypeContent.quantity = Int32(row["quantity"] as! NSNumber) installationTypeContent.assemblyLineType = ramAssemblyLineTypes[row["assemblyLineTypeID"] as! NSNumber] installationTypeContent.installationType = invTypes[row["installationTypeID"] as! NSNumber] } // MARK: invTypeRequiredSkills print ("invTypeRequiredSkills") extension SDEInvType { func getAttribute(_ attributeID: Int) -> SDEDgmTypeAttribute? { return (self.attributes as? Set<SDEDgmTypeAttribute>)?.filter { return $0.attributeType!.attributeID == Int32(attributeID) }.first } } for (_, type) in invTypes { for (skillID, level) in [(182, 277), (183, 278), (184, 279), (1285, 1286), (1289, 1287), (1290, 1288)] { guard let skillID = type.getAttribute(skillID), let level = type.getAttribute(level), let skill = invTypes[Int(skillID.value) as NSNumber], skill !== type else {continue} let requiredSkill = SDEInvTypeRequiredSkill(context: context) requiredSkill.type = type requiredSkill.skillType = skill requiredSkill.skillLevel = Int16(level.value) } } // MARK: industryBlueprints print ("industryBlueprints") var industryBlueprints = [NSNumber: SDEIndBlueprintType]() try! database.exec("SELECT * FROM industryBlueprints") { row in guard let type = invTypes[row["typeID"] as! NSNumber] else {return} let blueprintType = SDEIndBlueprintType(context: context) blueprintType.maxProductionLimit = Int32(row["maxProductionLimit"] as! NSNumber) blueprintType.type = type industryBlueprints[blueprintType.type!.typeID as NSNumber] = blueprintType } // MARK: industryActivity print ("industryActivity") var industryActivity = [IndexPath: SDEIndActivity]() try! database.exec("SELECT * FROM industryActivity") { row in let activity = SDEIndActivity(context: context) activity.time = Int32(row["time"] as! NSNumber) activity.blueprintType = industryBlueprints[row["typeID"] as! NSNumber] activity.activity = ramActivities[row["activityID"] as! NSNumber] industryActivity[IndexPath(item: (row["activityID"] as! NSNumber).intValue, section: (row["typeID"] as! NSNumber).intValue)] = activity } // MARK: industryActivityMaterials print ("industryActivityMaterials") try! database.exec("SELECT * FROM industryActivityMaterials") { row in let requiredMaterial = SDEIndRequiredMaterial(context: context) requiredMaterial.quantity = Int32(row["quantity"] as! NSNumber) requiredMaterial.materialType = invTypes[row["materialTypeID"] as! NSNumber] requiredMaterial.activity = industryActivity[IndexPath(item: (row["activityID"] as! NSNumber).intValue, section: (row["typeID"] as! NSNumber).intValue)] } // MARK: industryActivityProducts print ("industryActivityProducts") var industryActivityProducts = [IndexPath: SDEIndProduct]() try! database.exec("SELECT * FROM industryActivityProducts") { row in let product = SDEIndProduct(context: context) product.quantity = Int32(row["quantity"] as! NSNumber) product.productType = invTypes[row["productTypeID"] as! NSNumber] product.activity = industryActivity[IndexPath(item: (row["activityID"] as! NSNumber).intValue, section: (row["typeID"] as! NSNumber).intValue)] let key = IndexPath(indexes: [(row["activityID"] as! NSNumber).intValue, (row["typeID"] as! NSNumber).intValue, (row["productTypeID"] as! NSNumber).intValue]) industryActivityProducts[key] = product } // MARK: industryActivityProbabilities print ("industryActivityProbabilities") try! database.exec("SELECT * FROM industryActivityProbabilities") { row in let key = IndexPath(indexes: [(row["activityID"] as! NSNumber).intValue, (row["typeID"] as! NSNumber).intValue, (row["productTypeID"] as! NSNumber).intValue]) let product = industryActivityProducts[key]! product.probability = Float(row["probability"] as! NSNumber) } // MARK: industryActivitySkills print ("industryActivitySkills") try! database.exec("SELECT * FROM industryActivitySkills") { row in let requiredSkill = SDEIndRequiredSkill(context: context) requiredSkill.skillLevel = Int16(row["level"] as! NSNumber) requiredSkill.skillType = invTypes[row["skillID"] as! NSNumber] requiredSkill.activity = industryActivity[IndexPath(item: (row["activityID"] as! NSNumber).intValue, section: (row["typeID"] as! NSNumber).intValue)] } // MARK: whTypes print ("whTypes") try! database.exec("SELECT * FROM invTypes WHERE groupID = 988") { row in let whType = SDEWhType(context: context) whType.type = invTypes[row["typeID"] as! NSNumber]! whType.targetSystemClass = Int32(whType.type!.getAttribute(1381)?.value ?? 0) whType.maxStableTime = Float(whType.type!.getAttribute(1382)?.value ?? 0) whType.maxStableMass = Float(whType.type!.getAttribute(1383)?.value ?? 0) whType.maxRegeneration = Float(whType.type!.getAttribute(1384)?.value ?? 0) whType.maxJumpMass = Float(whType.type!.getAttribute(1385)?.value ?? 0) } // MARK: dgmppItems print ("dgmppItems") var dgmppItemGroups = [IndexPath: SDEDgmppItemGroup]() extension SDEDgmppItemGroup { class func itemGroup(marketGroup: SDEInvMarketGroup, category: SDEDgmppItemCategory) -> SDEDgmppItemGroup? { guard marketGroup.marketGroupID != 1659 else {return nil} let key = IndexPath(indexes: [Int(marketGroup.marketGroupID), Int(category.category), Int(category.subcategory), Int(category.race?.raceID ?? 0)]) if let group = dgmppItemGroups[key] { return group } else { guard let group = SDEDgmppItemGroup(marketGroup: marketGroup, category: category) else {return nil} dgmppItemGroups[key] = group return group } } convenience init?(marketGroup: SDEInvMarketGroup, category: SDEDgmppItemCategory) { var parentGroup: SDEDgmppItemGroup? if let parentMarketGroup = marketGroup.parentGroup { parentGroup = SDEDgmppItemGroup.itemGroup(marketGroup: parentMarketGroup, category: category) if parentGroup == nil { return nil } } self.init(context: context) groupName = marketGroup.marketGroupName icon = marketGroup.icon self.parentGroup = parentGroup self.category = category } } extension SDEDgmppItemCategory { convenience init(categoryID: SDEDgmppItemCategoryID, subcategory: Int32 = 0, race: SDEChrRace? = nil) { self.init(context: context) self.category = categoryID.rawValue self.subcategory = subcategory self.race = race } } func compress(itemGroup: SDEDgmppItemGroup) -> SDEDgmppItemGroup { if itemGroup.subGroups?.count == 1 { let child = itemGroup.subGroups?.anyObject() as? SDEDgmppItemGroup itemGroup.addToItems(child!.items!) itemGroup.addToSubGroups(child!.subGroups!) child!.removeFromItems(child!.items!) child!.removeFromSubGroups(child!.subGroups!) child?.category = nil child?.parentGroup = nil itemGroup.managedObjectContext?.delete(child!) } guard let parent = itemGroup.parentGroup else {return itemGroup} return compress(itemGroup: parent) } func trim(_ itemGroups: Set<SDEDgmppItemGroup>) -> [SDEDgmppItemGroup] { func leaf(_ itemGroup: SDEDgmppItemGroup) -> SDEDgmppItemGroup? { guard let parent = itemGroup.parentGroup else {return itemGroup} return leaf(parent) } var leaves: Set<SDEDgmppItemGroup>? = itemGroups while leaves?.count == 1 { let leaf = leaves?.first if let subGroups = leaf?.subGroups as? Set<SDEDgmppItemGroup> { leaves = leaf?.subGroups as? Set<SDEDgmppItemGroup> leaf?.removeFromSubGroups(subGroups as NSSet) leaf?.category = nil leaf?.parentGroup = nil leaf?.removeFromItems(leaf!.items!) leaf?.managedObjectContext?.delete(leaf!) } } //print ("\(Array(leaves!).flatMap {$0.groupName} )") return Array(leaves ?? Set()) } func importItems(types: [SDEInvType], category: SDEDgmppItemCategory, categoryName: String) { let groups = Set(types.compactMap { type -> SDEDgmppItemGroup? in guard let marketGroup = type.marketGroup else {return nil} guard let group = SDEDgmppItemGroup.itemGroup(marketGroup: marketGroup, category: category) else {return nil} type.dgmppItem = SDEDgmppItem(context: context) group.addToItems(type.dgmppItem!) return group }) let leaves = Set(groups.map { compress(itemGroup: $0) }) let root = SDEDgmppItemGroup(context: context) root.groupName = categoryName root.category = category let trimmed = trim(leaves) if trimmed.count == 0 { for type in types { type.dgmppItem?.addToGroups(root) } } for group in trimmed { group.parentGroup = root } } func importItems(category: SDEDgmppItemCategory, categoryName: String, predicate: NSPredicate) { let request = NSFetchRequest<SDEInvType>(entityName: "InvType") request.predicate = predicate let types = try! context.fetch(request) importItems(types: types, category: category, categoryName: categoryName) } func tablesFrom(conditions: [String]) -> Set<String> { var tables = Set<String>() let expression = try! NSRegularExpression(pattern: "\\b([a-zA-Z]{1,}?)\\.[a-zA-Z]{1,}?\\b", options: [.caseInsensitive]) for condition in conditions { let s = condition as NSString for result in expression.matches(in: condition, options: [], range: NSMakeRange(0, s.length)) { tables.insert(s.substring(with: result.rangeAt(1))) } } return tables } importItems(category: SDEDgmppItemCategory(categoryID: .ship), categoryName: "Ships", predicate: NSPredicate(format: "group.category.categoryID == 6")) importItems(category: SDEDgmppItemCategory(categoryID: .drone), categoryName: "Drones", predicate: NSPredicate(format: "group.category.categoryID == 18")) importItems(category: SDEDgmppItemCategory(categoryID: .fighter), categoryName: "Fighters", predicate: NSPredicate(format: "group.category.categoryID == 87 AND ANY attributes.attributeType.attributeID IN (%@)", [2212, 2213, 2214])) importItems(category: SDEDgmppItemCategory(categoryID: .structureFighter), categoryName: "Fighters", predicate: NSPredicate(format: "group.category.categoryID == 87 AND ANY attributes.attributeType.attributeID IN (%@)", [2740, 2741, 2742])) importItems(category: SDEDgmppItemCategory(categoryID: .structure), categoryName: "Structures", predicate: NSPredicate(format: "marketGroup.parentGroup.marketGroupID == 2199 OR marketGroup.marketGroupID == 2324 OR marketGroup.marketGroupID == 2327")) for subcategory in [7, 66] as [Int32] { importItems(category: SDEDgmppItemCategory(categoryID: .hi, subcategory: subcategory), categoryName: "Hi Slot", predicate: NSPredicate(format: "group.category.categoryID == %d AND ANY effects.effectID == 12", subcategory)) importItems(category: SDEDgmppItemCategory(categoryID: .med, subcategory: subcategory), categoryName: "Med Slot", predicate: NSPredicate(format: "group.category.categoryID == %d AND ANY effects.effectID == 13", subcategory)) importItems(category: SDEDgmppItemCategory(categoryID: .low, subcategory: subcategory), categoryName: "Low Slot", predicate: NSPredicate(format: "group.category.categoryID == %d AND ANY effects.effectID == 11", subcategory)) try! database.exec("select value from dgmTypeAttributes as a, dgmTypeEffects as b, invTypes as c, invGroups as d where b.effectID = 2663 AND attributeID=1547 AND a.typeID=b.typeID AND b.typeID=c.typeID AND c.groupID = d.groupID AND d.categoryID = \(subcategory) group by value;") { row in let value = row["value"] as! NSNumber importItems(category: SDEDgmppItemCategory(categoryID: subcategory == 7 ? .rig : .structureRig, subcategory: value.int32Value), categoryName: "Rig Slot", predicate: NSPredicate(format: "group.category.categoryID == %d AND ANY effects.effectID == 2663 AND SUBQUERY(attributes, $attribute, $attribute.attributeType.attributeID == 1547 AND $attribute.value == %@).@count > 0", subcategory, value)) } } try! database.exec("select raceID from invTypes as a, dgmTypeEffects as b where b.effectID = 3772 AND a.typeID=b.typeID group by raceID;") { row in let raceID = row["raceID"] as! NSNumber let race = chrRaces[raceID] importItems(category: SDEDgmppItemCategory(categoryID: .subsystem, subcategory: 7, race: race), categoryName: "Subsystems", predicate: NSPredicate(format: "ANY effects.effectID == 3772 AND race.raceID == %@", raceID)) } importItems(category: SDEDgmppItemCategory(categoryID: .service, subcategory: 66), categoryName: "Service Slot", predicate: NSPredicate(format: "group.category.categoryID == 66 AND ANY effects.effectID == 6306")) try! database.exec("select value from dgmTypeAttributes as a, invTypes as b where attributeID=331 and a.typeID=b.typeID and b.marketGroupID > 0 group by value;") { row in let value = row["value"] as! NSNumber let request = NSFetchRequest<SDEDgmTypeAttribute>(entityName: "DgmTypeAttribute") request.predicate = NSPredicate(format: "attributeType.attributeID == 331 AND value == %@", value) let attributes = (try! context.fetch(request)) importItems(types: attributes.map{$0.type!}, category: SDEDgmppItemCategory(categoryID: .implant, subcategory: value.int32Value), categoryName: "Implants") } try! database.exec("select value from dgmTypeAttributes as a, invTypes as b where attributeID=1087 and a.typeID=b.typeID and b.marketGroupID > 0 group by value;") { row in let value = row["value"] as! NSNumber let request = NSFetchRequest<SDEDgmTypeAttribute>(entityName: "DgmTypeAttribute") request.predicate = NSPredicate(format: "attributeType.attributeID == 1087 AND value == %@", value) let attributes = (try! context.fetch(request)) importItems(types: attributes.map{$0.type!}, category: SDEDgmppItemCategory(categoryID: .booster, subcategory: value.int32Value), categoryName: "Boosters") } try! database.exec("SELECT typeID FROM dgmTypeAttributes WHERE attributeID=10000") { row in let typeID = row["typeID"] as! NSNumber let request = NSFetchRequest<SDEInvType>(entityName: "InvType") request.predicate = NSPredicate(format: "ANY effects.effectID == 10002 AND SUBQUERY(attributes, $attribute, $attribute.attributeType.attributeID == 1302 AND $attribute.value == %@).@count > 0", typeID) let root = SDEDgmppItemGroup(context: context) root.category = SDEDgmppItemCategory(categoryID: .mode, subcategory: typeID.int32Value) root.groupName = "Tactical Mode" for type in try! context.fetch(request) { type.dgmppItem = SDEDgmppItem(context: context) root.addToItems(type.dgmppItem!) } } var chargeCategories = [IndexPath: SDEDgmppItemCategory]() let request = NSFetchRequest<SDEInvType>(entityName: "InvType") let attributeIDs = Set<Int32>([604, 605, 606, 609, 610]) request.predicate = NSPredicate(format: "ANY attributes.attributeType.attributeID IN (%@)", attributeIDs) for type in try! context.fetch(request) { let attributes = type.attributes?.allObjects as? [SDEDgmTypeAttribute] let chargeSize = attributes?.first(where: {$0.attributeType?.attributeID == 128})?.value var chargeGroups: Set<Int> = Set() for attribute in attributes?.filter({attributeIDs.contains($0.attributeType!.attributeID)}) ?? [] { chargeGroups.insert(Int(attribute.value)) } if !chargeGroups.isEmpty { var array = chargeGroups.sorted() if let chargeSize = chargeSize { array.append(Int(chargeSize)) } else { array.append(Int(type.capacity * 100)) } let key = IndexPath(indexes: array) if let category = chargeCategories[key] { type.dgmppItem?.charge = category } else { let root = SDEDgmppItemGroup(context: context) root.groupName = "Ammo" root.category = SDEDgmppItemCategory(categoryID: .charge, subcategory: Int32(chargeSize ?? 0), race: nil) type.dgmppItem?.charge = root.category chargeCategories[key] = root.category! let request = NSFetchRequest<SDEInvType>(entityName: "InvType") if let chargeSize = chargeSize { request.predicate = NSPredicate(format: "group.groupID IN %@ AND published = 1 AND SUBQUERY(attributes, $attribute, $attribute.attributeType.attributeID == 128 AND $attribute.value == %d).@count > 0", chargeGroups, Int(chargeSize)) } else { request.predicate = NSPredicate(format: "group.groupID IN %@ AND published = 1 AND volume <= %f", chargeGroups, type.capacity) } for charge in try! context.fetch(request) { if charge.dgmppItem == nil { charge.dgmppItem = SDEDgmppItem(context: context) } root.addToItems(charge.dgmppItem!) //charge.dgmppItem?.addToGroups(root) } } } } print ("dgmppItems info") request.predicate = NSPredicate(format: "dgmppItem <> NULL") for type in try! context.fetch(request) { switch SDEDgmppItemCategoryID(rawValue: (type.dgmppItem!.groups!.anyObject() as! SDEDgmppItemGroup).category!.category)! { case .hi, .med, .low, .rig, .structureRig: type.dgmppItem?.requirements = SDEDgmppItemRequirements(context: context) type.dgmppItem?.requirements?.powerGrid = type.getAttribute(30)?.value ?? 0 type.dgmppItem?.requirements?.cpu = type.getAttribute(50)?.value ?? 0 type.dgmppItem?.requirements?.calibration = type.getAttribute(1153)?.value ?? 0 case .charge, .drone, .fighter, .structureFighter: var multiplier = max(type.getAttribute(64)?.value ?? 0, type.getAttribute(212)?.value ?? 0) if multiplier == 0 { multiplier = 1 } let em = (type.getAttribute(114)?.value ?? 0) * multiplier let kinetic = (type.getAttribute(117)?.value ?? 0) * multiplier let thermal = (type.getAttribute(118)?.value ?? 0) * multiplier let explosive = (type.getAttribute(116)?.value ?? 0) * multiplier if em + kinetic + thermal + explosive > 0 { type.dgmppItem?.damage = SDEDgmppItemDamage(context: context) type.dgmppItem?.damage?.emAmount = em type.dgmppItem?.damage?.kineticAmount = kinetic type.dgmppItem?.damage?.thermalAmount = thermal type.dgmppItem?.damage?.explosiveAmount = explosive } case .ship: type.dgmppItem?.shipResources = SDEDgmppItemShipResources(context: context) type.dgmppItem?.shipResources?.hiSlots = Int16(type.getAttribute(14)?.value ?? 0) type.dgmppItem?.shipResources?.medSlots = Int16(type.getAttribute(13)?.value ?? 0) type.dgmppItem?.shipResources?.lowSlots = Int16(type.getAttribute(12)?.value ?? 0) type.dgmppItem?.shipResources?.rigSlots = Int16(type.getAttribute(1137)?.value ?? 0) type.dgmppItem?.shipResources?.turrets = Int16(type.getAttribute(102)?.value ?? 0) type.dgmppItem?.shipResources?.launchers = Int16(type.getAttribute(101)?.value ?? 0) case .structure: type.dgmppItem?.structureResources = SDEDgmppItemStructureResources(context: context) type.dgmppItem?.structureResources?.hiSlots = Int16(type.getAttribute(14)?.value ?? 0) type.dgmppItem?.structureResources?.medSlots = Int16(type.getAttribute(13)?.value ?? 0) type.dgmppItem?.structureResources?.lowSlots = Int16(type.getAttribute(12)?.value ?? 0) type.dgmppItem?.structureResources?.rigSlots = Int16(type.getAttribute(1137)?.value ?? 0) type.dgmppItem?.structureResources?.serviceSlots = Int16(type.getAttribute(2056)?.value ?? 0) type.dgmppItem?.structureResources?.turrets = Int16(type.getAttribute(102)?.value ?? 0) type.dgmppItem?.structureResources?.launchers = Int16(type.getAttribute(101)?.value ?? 0) default: break } } print ("dgmppHullTypes") do { func types(_ marketGroup: SDEInvMarketGroup) -> [SDEInvType] { var array = (marketGroup.types?.allObjects as? [SDEInvType]) ?? [] for group in marketGroup.subGroups?.allObjects ?? [] { array.append(contentsOf: types(group as! SDEInvMarketGroup)) } return array } for marketGroup in invMarketGroups[4]?.subGroups ?? [] { let marketGroup = marketGroup as! SDEInvMarketGroup let hullType = SDEDgmppHullType(context: context) hullType.hullTypeName = marketGroup.marketGroupName let ships = Set(types(marketGroup)) hullType.addToTypes(ships as NSSet) let array = ships.compactMap {$0.getAttribute(552)?.value}.map{ Double($0) } var signature = array.reduce(0, +) signature /= Double(array.count) signature = ceil(signature / 5) * 5 hullType.signature = Float(signature) } } try! database.exec("SELECT * FROM version") { row in let version = NCDBVersion(context: context) version.expansion = expansion version.build = Int32(row["build"] as! NSNumber) version.version = row["version"] as? String } print ("Save...") try! context.save()
lgpl-2.1
357718093106c250f82967c233afb168
37.911364
396
0.731285
3.456693
false
false
false
false
khizkhiz/swift
benchmark/single-source/ArrayAppend.swift
2
1030
//===--- ArrayAppend.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks the performance of appending to an array. import TestsUtils @inline(never) public func run_ArrayAppend(N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<40000 { nums.append(1) } } } } @inline(never) public func run_ArrayAppendReserved(N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() nums.reserveCapacity(40000) for _ in 0..<40000 { nums.append(1) } } } }
apache-2.0
475d74f17185f9fa9e7d6bdb054f4a96
24.75
80
0.532039
4.071146
false
false
false
false
lucaangeletti/FireworksKit
FireworksKit/FireworksView.swift
1
1693
// // FireworksView.swift // FireworksKit // // Created by Luca Angeletti on 28/07/2017. // Copyright © 2017 Luca Angeletti. All rights reserved. // import SpriteKit public class FireworksView: SKView { private let effectScene: Scene @IBInspectable var particleName: String? @IBInspectable var particleColor: UIColor? public override func awakeFromNib() { super.awakeFromNib() if let particleEffectName = particleName { guard let particleEffectType = ParticleEffectType(rawValue: particleEffectName) else { print("Invalid effect name: \(particleEffectName)") return } self.particleEffect = ParticleEffect(type: particleEffectType) } if let particleColor = particleColor { particleEffect?.particleColor = particleColor } } public override init(frame: CGRect) { effectScene = Scene(size: frame.size) super.init(frame: frame) prepare() } required public init?(coder aDecoder: NSCoder) { self.effectScene = Scene(size: .zero) super.init(coder: aDecoder) self.effectScene.size = frame.size prepare() } private func prepare() { presentScene(effectScene) allowsTransparency = true isUserInteractionEnabled = false } public var particleEffect: ParticleEffect? { didSet { guard let particleEffect = particleEffect else { effectScene.removeEmitterNodes() return } effectScene.add(emitterNode: particleEffect.emitter, ofType: particleEffect.type) } } }
mit
f5b354609a011e62e2b1ce7c8cf3064b
26.737705
98
0.626478
4.820513
false
false
false
false
Frainbow/ShaRead.frb-swift
ShaRead/ShaRead/BookCommentFormTableViewCell.swift
1
1650
// // BookCommentFormTableViewCell.swift // ShaRead // // Created by martin on 2016/5/8. // Copyright © 2016年 Frainbow. All rights reserved. // import UIKit class BookCommentFormTableViewCell: UITableViewCell { @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var inputTextView: UITextView! @IBOutlet weak var placeholderLabel: UILabel! @IBOutlet weak var submitButton: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code avatarImageView.layer.cornerRadius = 32 avatarImageView.clipsToBounds = true inputTextView.delegate = self inputTextView.layer.borderColor = UIColor.lightGrayColor().CGColor inputTextView.layer.borderWidth = 1 submitButton.layer.cornerRadius = 5 } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } extension BookCommentFormTableViewCell: UITextViewDelegate { func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if (text == "\n") { textView.resignFirstResponder() return false } return true } func textViewDidBeginEditing(textView: UITextView) { placeholderLabel.hidden = true } func textViewDidEndEditing(textView: UITextView) { textView.resignFirstResponder() if textView.text.characters.count == 0 { placeholderLabel.hidden = false } } }
mit
9905d5a42f000af1731ff047699c3fd8
26.45
119
0.671524
5.261981
false
false
false
false
themonki/onebusaway-iphone
OneBusAway/externals/AwesomeSpotlightView/Classes/AwesomeTabButton.swift
3
575
// // AwesomeTabButton.swift // AwesomeSpotlightViewDemo // // Created by Alexander Shoshiashvili on 11/02/2018. // Copyright © 2018 Alex Shoshiashvili. All rights reserved. // import UIKit public struct AwesomeTabButton { public var title: String public var font: UIFont public var isEnable: Bool public var backgroundColor: UIColor? public init(title: String, font: UIFont, isEnable: Bool = true, backgroundColor: UIColor? = nil) { self.title = title self.font = font self.isEnable = isEnable self.backgroundColor = backgroundColor } }
apache-2.0
35dc5f8b511548448a08389a8238a217
22.916667
100
0.722997
3.826667
false
false
false
false
jwelton/BreweryDB
BreweryDB/SearchRequest.swift
1
1326
// // SearchRequest.swift // BreweryDB // // Created by Jake Welton on 2016-07-22. // Copyright © 2016 Jake Welton. All rights reserved. // import Foundation public enum SearchRequestParam: String { case searchTerm = "q" case resultType = "type" case pageNumber = "p" case withBreweries = "withBreweries" case withIngredients = "withIngredients" case withLocations = "withLocations" } public struct SearchRequest { public var params: [SearchRequestParam: String]? public var endpoint: RequestEndPoint{ return .search } public init(params: [SearchRequestParam: String]? = nil) { self.params = params } } extension SearchRequest: BreweryDBRequest { public var rawParams: [String: String]? { return params?.reduce([String: String]()) { previous, item in var temp = previous temp[item.0.rawValue] = item.1 return temp } } public var rawOrderBy: String? { return nil } public var pageNumber: Int { get { guard let rawPageNumber = params?[.pageNumber] else { return 1 } return Int(rawPageNumber) ?? 1 } set { params?[.pageNumber] = String(newValue) } } }
mit
6475b169c30263154866d4a5ed9bdbff
22.660714
69
0.586415
4.416667
false
false
false
false
jrmgx/swift
jrmgx/Classes/Helper/JrmgxDebug.swift
1
486
import UIKit /** * NAME * * - parameters * - name: String * - returns: nothing */ public var debugMode = false /** * NAME * * - parameters * - name: String * - returns: nothing */ public func printd(_ message: String, function: String = #function, file: String = #file, line: Int = #line) { if debugMode { let url = URL(fileURLWithPath: file) print("[\(url.lastPathComponent):\(line)] \(function): \(message)") } } open class JrmgxDebug { }
mit
eece12c0fd5fd13c12d69301a9d37d53
15.758621
110
0.592593
3.471429
false
false
false
false
saoudrizwan/Disk
Sources/Disk+InternalHelpers.swift
1
9236
// The MIT License (MIT) // // Copyright (c) 2017 Saoud Rizwan <[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 Foundation extension Disk { /// Create and returns a URL constructed from specified directory/path static func createURL(for path: String?, in directory: Directory) throws -> URL { let filePrefix = "file://" var validPath: String? = nil if let path = path { do { validPath = try getValidFilePath(from: path) } catch { throw error } } var searchPathDirectory: FileManager.SearchPathDirectory switch directory { case .documents: searchPathDirectory = .documentDirectory case .caches: searchPathDirectory = .cachesDirectory case .applicationSupport: searchPathDirectory = .applicationSupportDirectory case .temporary: if var url = URL(string: NSTemporaryDirectory()) { if let validPath = validPath { url = url.appendingPathComponent(validPath, isDirectory: false) } if url.absoluteString.lowercased().prefix(filePrefix.count) != filePrefix { let fixedUrlString = filePrefix + url.absoluteString url = URL(string: fixedUrlString)! } return url } else { throw createError( .couldNotAccessTemporaryDirectory, description: "Could not create URL for \(directory.pathDescription)/\(validPath ?? "")", failureReason: "Could not get access to the application's temporary directory.", recoverySuggestion: "Use a different directory." ) } case .sharedContainer(let appGroupName): if var url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupName) { if let validPath = validPath { url = url.appendingPathComponent(validPath, isDirectory: false) } if url.absoluteString.lowercased().prefix(filePrefix.count) != filePrefix { let fixedUrl = filePrefix + url.absoluteString url = URL(string: fixedUrl)! } return url } else { throw createError( .couldNotAccessSharedContainer, description: "Could not create URL for \(directory.pathDescription)/\(validPath ?? "")", failureReason: "Could not get access to shared container with app group named \(appGroupName).", recoverySuggestion: "Check that the app-group name in the entitlement matches the string provided." ) } } if var url = FileManager.default.urls(for: searchPathDirectory, in: .userDomainMask).first { if let validPath = validPath { url = url.appendingPathComponent(validPath, isDirectory: false) } if url.absoluteString.lowercased().prefix(filePrefix.count) != filePrefix { let fixedUrlString = filePrefix + url.absoluteString url = URL(string: fixedUrlString)! } return url } else { throw createError( .couldNotAccessUserDomainMask, description: "Could not create URL for \(directory.pathDescription)/\(validPath ?? "")", failureReason: "Could not get access to the file system's user domain mask.", recoverySuggestion: "Use a different directory." ) } } /// Find an existing file's URL or throw an error if it doesn't exist static func getExistingFileURL(for path: String?, in directory: Directory) throws -> URL { do { let url = try createURL(for: path, in: directory) if FileManager.default.fileExists(atPath: url.path) { return url } throw createError( .noFileFound, description: "Could not find an existing file or folder at \(url.path).", failureReason: "There is no existing file or folder at \(url.path)", recoverySuggestion: "Check if a file or folder exists before trying to commit an operation on it." ) } catch { throw error } } /// Convert a user generated name to a valid file name static func getValidFilePath(from originalString: String) throws -> String { var invalidCharacters = CharacterSet(charactersIn: ":") invalidCharacters.formUnion(.newlines) invalidCharacters.formUnion(.illegalCharacters) invalidCharacters.formUnion(.controlCharacters) let pathWithoutIllegalCharacters = originalString .components(separatedBy: invalidCharacters) .joined(separator: "") let validFileName = removeSlashesAtBeginning(of: pathWithoutIllegalCharacters) guard validFileName.count > 0 && validFileName != "." else { throw createError( .invalidFileName, description: "\(originalString) is an invalid file name.", failureReason: "Cannot write/read a file with the name \(originalString) on disk.", recoverySuggestion: "Use another file name with alphanumeric characters." ) } return validFileName } /// Helper method for getValidFilePath(from:) to remove all "/" at the beginning of a String static func removeSlashesAtBeginning(of string: String) -> String { var string = string if string.prefix(1) == "/" { string.remove(at: string.startIndex) } if string.prefix(1) == "/" { string = removeSlashesAtBeginning(of: string) } return string } /// Set 'isExcludedFromBackup' BOOL property of a file or directory in the file system static func setIsExcludedFromBackup(to isExcludedFromBackup: Bool, for path: String?, in directory: Directory) throws { do { let url = try getExistingFileURL(for: path, in: directory) var resourceUrl = url var resourceValues = URLResourceValues() resourceValues.isExcludedFromBackup = isExcludedFromBackup try resourceUrl.setResourceValues(resourceValues) } catch { throw error } } /// Set 'isExcludedFromBackup' BOOL property of a file or directory in the file system static func setIsExcludedFromBackup(to isExcludedFromBackup: Bool, for url: URL) throws { do { var resourceUrl = url var resourceValues = URLResourceValues() resourceValues.isExcludedFromBackup = isExcludedFromBackup try resourceUrl.setResourceValues(resourceValues) } catch { throw error } } /// Create necessary sub folders before creating a file static func createSubfoldersBeforeCreatingFile(at url: URL) throws { do { let subfolderUrl = url.deletingLastPathComponent() var subfolderExists = false var isDirectory: ObjCBool = false if FileManager.default.fileExists(atPath: subfolderUrl.path, isDirectory: &isDirectory) { if isDirectory.boolValue { subfolderExists = true } } if !subfolderExists { try FileManager.default.createDirectory(at: subfolderUrl, withIntermediateDirectories: true, attributes: nil) } } catch { throw error } } /// Get Int from a file name static func fileNameInt(_ url: URL) -> Int? { let fileExtension = url.pathExtension let filePath = url.lastPathComponent let fileName = filePath.replacingOccurrences(of: fileExtension, with: "") return Int(String(fileName.filter { "0123456789".contains($0) })) } }
mit
ca392aba4a98e1f74b2cb518c6896e14
44.497537
125
0.613469
5.540492
false
false
false
false
s-aska/Justaway-for-iOS
Justaway/TwitterMessageAdapter.swift
1
8317
// // TwitterMessageAdapter.swift // Justaway // // Created by Shinichiro Aska on 3/18/16. // Copyright © 2016 Shinichiro Aska. All rights reserved. // import UIKit import EventBox import Async class TwitterMessageAdapter: TwitterAdapter { // MARK: Properties let threadMode: Bool var messages: [TwitterMessage] { return rows.filter({ $0.message != nil }).map({ $0.message! }) } // MARK: Configuration override func configureView(_ tableView: UITableView) { super.configureView(tableView) setupLayout(tableView) } func setupLayout(_ tableView: UITableView) { let nib = UINib(nibName: "TwitterStatusCell", bundle: nil) for layout in TwitterStatusCellLayout.allValuesForMessage { tableView.register(nib, forCellReuseIdentifier: layout.rawValue) self.layoutHeightCell[layout] = tableView.dequeueReusableCell(withIdentifier: layout.rawValue) as? TwitterStatusCell } } // MARK: Initializers init(threadMode: Bool) { self.threadMode = threadMode } // MARK: Private Methods func createRow(_ message: TwitterMessage, fontSize: CGFloat, tableView: UITableView) -> Row { let layout = TwitterStatusCellLayout.fromMessage(message) if let height = layoutHeight[layout] { let textHeight = measure(message.text as NSString, fontSize: fontSize) let totalHeight = ceil(height + textHeight) return Row(message: message, fontSize: fontSize, height: totalHeight, textHeight: textHeight) } else if let cell = self.layoutHeightCell[layout] { cell.frame = tableView.bounds cell.setLayout(layout) let textHeight = measure(message.text as NSString, fontSize: fontSize) cell.textHeightConstraint.constant = 0 cell.quotedStatusLabelHeightConstraint.constant = 0 let height = cell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height layoutHeight[layout] = height let totalHeight = ceil(height + textHeight) return Row(message: message, fontSize: fontSize, height: totalHeight, textHeight: textHeight) } fatalError("cellForHeight is missing.") } fileprivate func measure(_ text: NSString, fontSize: CGFloat) -> CGFloat { return ceil(text.boundingRect( with: CGSize.init(width: (self.layoutHeightCell[.Message]?.statusLabel.frame.size.width)!, height: 0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: fontSize)], context: nil).size.height) } func fontSizeApplied(_ tableView: UITableView, fontSize: CGFloat) { let newRows = self.rows.map({ (row) -> TwitterStatusAdapter.Row in if let message = row.message { return self.createRow(message, fontSize: fontSize, tableView: tableView) } else { return row } }) fontSizeApplied(tableView, fontSize: fontSize, rows: newRows) } // MARK: Public Methods func thread(_ messages: [TwitterMessage]) -> [TwitterMessage] { var thread = [TwitterMessage]() if let account = AccountSettingsStore.get()?.account() { var userMap = [String: Bool]() for message in messages { let userID = account.userID != message.sender.userID ? message.sender.userID : message.recipient.userID if userMap[userID] == nil { userMap[userID] = true thread.append(message) } } } return thread } func renderData(_ tableView: UITableView, messages: [TwitterMessage], mode: RenderMode, handler: (() -> Void)?) { var messages = messages let fontSize = CGFloat(GenericSettings.get().fontSize) let limit = mode == .over ? 0 : timelineRowsLimit let deleteCount = mode == .over ? self.rows.count : max((self.rows.count + messages.count) - limit, 0) let deleteStart = mode == .top || mode == .header ? self.rows.count - deleteCount : 0 let deleteRange = deleteStart ..< (deleteStart + deleteCount) let deleteIndexPaths = deleteRange.map { row in IndexPath(row: row, section: 0) } let insertStart = mode == .bottom ? self.rows.count - deleteCount : 0 let insertIndexPaths = (insertStart ..< (insertStart + messages.count)).map { row in IndexPath(row: row, section: 0) } if deleteIndexPaths.count == 0 && messages.count == 0 { handler?() return } // println("renderData lastID: \(self.lastID ?? 0) insertIndexPaths: \(insertIndexPaths.count) deleteIndexPaths: \(deleteIndexPaths.count) oldRows:\(self.rows.count)") if let lastCell = tableView.visibleCells.last { // NSLog("y:\(tableView.contentOffset.y) top:\(tableView.contentInset.top)") let isTop = tableView.contentOffset.y + tableView.contentInset.top <= 0 && mode == .top let offset = lastCell.frame.origin.y - tableView.contentOffset.y UIView.setAnimationsEnabled(false) tableView.beginUpdates() if deleteIndexPaths.count > 0 { tableView.deleteRows(at: deleteIndexPaths, with: .none) self.rows.removeSubrange(deleteRange) } if insertIndexPaths.count > 0 { var i = 0 for insertIndexPath in insertIndexPaths { let row = self.createRow(messages[i], fontSize: fontSize, tableView: tableView) self.rows.insert(row, at: insertIndexPath.row) i += 1 } tableView.insertRows(at: insertIndexPaths, with: .none) } tableView.endUpdates() tableView.setContentOffset(CGPoint.init(x: 0, y: lastCell.frame.origin.y - offset), animated: false) UIView.setAnimationsEnabled(true) if isTop { UIView.animate(withDuration: 0.3, animations: { _ in tableView.contentOffset = CGPoint.init(x: 0, y: -tableView.contentInset.top) }, completion: { _ in self.scrollEnd(tableView) handler?() }) } else { if mode == .over { tableView.contentOffset = CGPoint.init(x: 0, y: -tableView.contentInset.top) } handler?() } } else { if deleteIndexPaths.count > 0 { self.rows.removeSubrange(deleteRange) } for message in messages { self.rows.append(self.createRow(message, fontSize: fontSize, tableView: tableView)) } tableView.setContentOffset(CGPoint.init(x: 0, y: -tableView.contentInset.top), animated: false) tableView.reloadData() self.renderImages(tableView) handler?() } } func eraseData(_ tableView: UITableView, messageID: String, handler: (() -> Void)?) { let target = { (row: Row) -> Bool in return row.message?.id ?? "" == messageID } eraseData(tableView, target: target, handler: handler) } } // MARK: - UITableViewDelegate extension TwitterMessageAdapter { func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) { NSLog("TwitterMessageAdapter didSelectRowAtIndexPath") let row = rows[indexPath.row] if let message = row.message { if let account = AccountSettingsStore.get()?.account(), let messages = Twitter.messages[account.userID], threadMode { let collocutorID = message.collocutor.userID let threadMessages = messages.filter({ $0.collocutor.userID == collocutorID }) Async.main { MessagesViewController.show(message.collocutor, messages: threadMessages) } } else if let account = AccountSettingsStore.get()?.account() { DirectMessageAlert.show(account, message: message) } } } }
mit
53a6a8e0c349530191faeaf961de61a0
41.213198
175
0.606542
4.843331
false
false
false
false
zetasq/Aztec
Source/HTTP/HTTPRequest/Encoding/CharacterSet+QueryEscape.swift
1
620
// // CharacterSet+QueryEscape.swift // Aztec // // Created by Zhu Shengqi on 23/04/2017. // Copyright © 2017 Zhu Shengqi. All rights reserved. // import Foundation extension CharacterSet { /// RFC 3986 static let queryStringAllowed: CharacterSet = { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode) return allowedCharacterSet }() }
mit
b4df5e5f0d1884735a396cb464916ccd
25.913043
104
0.696284
4.991935
false
false
false
false
natecook1000/swift
test/Generics/function_decls.swift
1
3745
// RUN: %target-typecheck-verify-swift //===----------------------------------------------------------------------===// // Generic function declarations //===----------------------------------------------------------------------===// func f0<T>(x: Int, y: Int, t: T) { } func f1<T : Any>(x: Int, y: Int, t: T) { } func f2<T : IteratorProtocol>(x: Int, y: Int, t: T) { } func f3<T : () -> ()>(x: Int, y: Int, t: T) { } // expected-error{{expected a class type or protocol-constrained type restricting 'T'}} func f4<T>(x: T, y: T) { } // Non-protocol type constraints. func f6<T : Wonka>(x: T) {} // expected-error{{use of undeclared type 'Wonka'}} func f7<T : Int>(x: T) {} // expected-error{{type 'T' constrained to non-protocol, non-class type 'Int'}} func f8<T> (x: Int) {} //expected-error{{generic parameter 'T' is not used in function signature}} public class A<X> { init<T>(){} //expected-error{{generic parameter 'T' is not used in function signature}} public func f9<T, U>(x: T, y: X) {} //expected-error{{generic parameter 'U' is not used in function signature}} public func f10(x: Int) {} public func f11<T, U>(x: X, y: T) {} //expected-error{{generic parameter 'U' is not used in function signature}} } struct G<T> {} // expected-note {{generic type 'G' declared here}} struct GG<T, U> {} protocol P { associatedtype A typealias B = Int typealias C<T> = T typealias D = G typealias E<T> = GG<T, T> } func f12<T : P>(x: T) -> T.A<Int> {} // expected-error {{cannot specialize non-generic type 'T.A'}}{{29-34=}} func f13<T : P>(x: T) -> T.B<Int> {} // expected-error {{cannot specialize non-generic type 'Int'}}{{29-34=}} func f14<T : P>(x: T) -> T.C<Int> {} func f15<T : P>(x: T) -> T.D<Int> {} func f16<T : P>(x: T) -> T.D {} // expected-error {{reference to generic type 'G' requires arguments in <...>}} func f17<T : P>(x: T) -> T.E<Int> {} public protocol Q { associatedtype AT1 associatedtype AT2 } public protocol R { associatedtype I } public class C { } // Check that all generic params except for V can be inferred, because // they are directly or indirectly used to declare function's arguments. // In particular, T and U are considered to be used, because E is explicitly // used and there is a requirement E.I == (T, U) //expected-error@+1{{generic parameter 'V' is not used in function signature}} public func expectEqualSequence<E : R, A : R, T : Q, U : Q, V : Q>( _ expected: E, _ actual: A ) where E.I == A.I, E.I == (T, U) { } // Check that all generic params can be inferred, because // they are directly or indirectly used to declare function's arguments. // The only generic param that is used explicitly is T6. // All others are inferred from it step-by-step through the chain of // requirements. func foo<T1:Q, T2:Q, T3:Q, T4:Q, T5:Q, T6:Q> (x: T6) where T1.AT1 == T2.AT1, T1 == T6.AT2, T2 == T3.AT1, T3 == T4.AT1, T4 == T5.AT2, T5 == T6.AT1 { } // Check that all generic params except for T1 and T2 can be inferred, because // they are directly or indirectly used to declare function's arguments. //expected-error@+2{{generic parameter 'T1' is not used in function signature}} //expected-error@+1{{generic parameter 'T2' is not used in function signature}} func boo<T1, T2:Q, T3:Q, T4:Q, T5:Q, T6:Q> (x: T6) where T1:Q, T2:C, T3 == T4.AT1, T4 == T5.AT2, T5 == T6.AT1 { } // At the first glance U seems to be explicitly used for declaring a parameter d. // But in fact, the declaration of d uses the associated type U.A. This is not // enough to infer the type of U at any of the baz's call-sites. // Therefore we should reject this declaration. //expected-error@+1{{generic parameter 'U' is not used in function signature}} func baz<U:P>(_ d: U.A) { }
apache-2.0
e8e9de85d300f1f5889537942be15a65
37.214286
135
0.6251
3.039773
false
false
false
false
NitWitStudios/NWSExtensions
NWSExtensions/Classes/UIDevice+Extensions.swift
1
5021
// // UIDevice+Extensions.swift // Bobblehead-TV // // Created by James Hickman on 8/5/16. // Copyright © 2016 NitWit Studios. All rights reserved. // import UIKit import Foundation public extension UIDevice { /// iPhone 4 class func isScreenSizeThreePointFiveInch() -> Bool { return max(UIScreen.main.bounds.width, UIScreen.main.bounds.height) == 320.0 } /// iPhone 5 class func isScreenSizeFourInch() -> Bool { return max(UIScreen.main.bounds.width, UIScreen.main.bounds.height) == 568.0 } /// iPhone 6/6s/7 class func isScreenSizeFourPointSevenInch() -> Bool { return max(UIScreen.main.bounds.width, UIScreen.main.bounds.height) == 667.0 } /// iPhone 6+/6s+/7+ class func isScreenSizeFivePointFiveInch() -> Bool { return max(UIScreen.main.bounds.width, UIScreen.main.bounds.height) == 736.0 } var modelName: String { let currentSimulatorDevice = "iPhone 7 Plus" // Set simulator device here when testing. var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8 , value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone8,4": return "iPhone SE" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return "iPad Pro" case "AppleTV5,3": return "Apple TV" case "i386", "x86_64": return currentSimulatorDevice default: return identifier } } class func iPhone7Plus() -> Bool { return UIDevice.current.modelName == "iPhone 7 Plus" || UIDevice.current.modelName == "iPhone 7s Plus" } class func iPhone7() -> Bool { return UIDevice.current.modelName == "iPhone 7" || UIDevice.current.modelName == "iPod Touch 7" } class func iPhone6Plus() -> Bool { return UIDevice.current.modelName == "iPhone 6 Plus" || UIDevice.current.modelName == "iPhone 6s Plus" } class func iPhone6() -> Bool { return UIDevice.current.modelName == "iPhone 6" || UIDevice.current.modelName == "iPhone 6s" || UIDevice.current.modelName == "iPod Touch 6" } class func iPhone5() -> Bool { return UIDevice.current.modelName == "iPhone 5" || UIDevice.current.modelName == "iPhone 5s" || UIDevice.current.modelName == "iPhone 5c" || UIDevice.current.modelName == "iPhone SE" || UIDevice.current.modelName == "iPod Touch 5" } class func iPhone4() -> Bool { return UIDevice.current.modelName == "iPhone 4" || UIDevice.current.modelName == "iPhone 4s" } class func iPad() -> Bool { return UIDevice.current.modelName == "iPad 2" || UIDevice.current.modelName == "iPad 3" || UIDevice.current.modelName == "iPad 4" || UIDevice.current.modelName == "iPad Air" || UIDevice.current.modelName == "iPad Air 2" || UIDevice.current.modelName == "iPad Mini" || UIDevice.current.modelName == "iPad Mini 2" || UIDevice.current.modelName == "iPad Mini 3" || UIDevice.current.modelName == "iPad Mini 4" } class func iPadPro() -> Bool { return UIDevice.current.modelName == "iPad Pro" } }
mit
41042e35bcbc68985f655bac0e903c19
47.269231
413
0.555578
3.977813
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/BasicMoveStrategy.swift
1
2744
// // BasicMoveStrategy.swift // MrGreen // // Created by Benzi on 15/08/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation class EnemyMove : CustomStringConvertible { var direction:UInt = Direction.None var row:Int = -1 var column:Int = -1 var description: String { return "move \(Direction.Name[direction]!) to (\(column),\(row))" } } protocol EnemyMoveStrategy { func getMove() -> EnemyMove } class BasicMoveStrategy : EnemyMoveStrategy { var enemy:Entity! var world:WorldMapper! init(enemy:Entity, world:WorldMapper) { self.enemy = enemy self.world = world } func getMove() -> EnemyMove { return EnemyMove() } // returns true if the destination cell // is a valid move target for an enemy // entity func willNotCollideWithEnemyOrPortal(atLocation:LocationComponent) -> Bool { // find out where all enemies are currently // and check if we will cross over the bounds // of the other enemy // if we move to this location, compute our new bounds // and check if that space is already occupied let selfBounds = getEnemyBounds(world, enemy: enemy, fromLocation: atLocation) for l in selfBounds { // if cell is occupied, return false let cell = world.level.cells.get(l)! if cell.occupiedByEnemy && cell.occupiedBy != self.enemy { return false } } for location in selfBounds { if let portal = world.portalCache.get(location) { let p = self.world.portal.get(portal) if p.enabled { return false } } } return true } /// determines if a valid enemy move can be made from the speicified /// location and target direction func isValidMoveFromLocation(location:LocationComponent, moveDirection:UInt) -> Bool { if world.level.movePossible(location, direction: moveDirection) { let cell = world.level.cells.get(location)! if let neighbour = world.level.getNeighbour(cell, direction: moveDirection) { if willNotCollideWithEnemyOrPortal(neighbour.location) { return true } } } return false } func getLocationRelativeToMove(current:LocationComponent, direction:UInt) -> LocationComponent { let (c,r) = world.level.getCellRelativeTo(column: current.column, row: current.row, direction: direction)! return LocationComponent(row: r, column: c) } }
isc
b4db04d26fa9b2972e1c359f9c6c19bf
28.836957
114
0.598397
4.588629
false
false
false
false
PPacie/Swiping-Carousel
ExampleProject/ExampleProject/CardViewController.swift
2
4713
// // CardViewController.swift // ExampleProject // // Created by Pablo Paciello on 10/27/16. // Copyright © 2016 PPacie. All rights reserved. // import UIKit import SwipingCarousel class CardViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! { didSet { collectionView.register(CardCollectionViewCell.nib, forCellWithReuseIdentifier: CardCollectionViewCell.reuseIdentifier) } } // Load allTheCards from SavedCards Class. private var allTheCards = Card.loadCards() private let segueIdentifier = "OpenChat" } // MARK: UICollectionView DataSource extension CardViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //Return the number of items in the section return allTheCards.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CardCollectionViewCell.reuseIdentifier, for: indexPath) as! CardCollectionViewCell // Configure the cell cell.populateWith(card: allTheCards[(indexPath as NSIndexPath).row]) cell.delegate = self cell.deleteOnSwipeDown = true return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let cell = collectionView.cellForItem(at: indexPath) { //We check if the selected Card is the one in the middle to open the chat. If it's not, we scroll to the selected side card. if cell.frame.size.height > cell.bounds.size.height { performSegue(withIdentifier: segueIdentifier, sender: Any?.self) } else { collectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true) } } } } // MARK: Conform to the SwipingCarousel Delegate extension CardViewController: SwipingCarouselDelegate { func cellSwipedUp(_ cell: UICollectionViewCell) { guard let cell = cell as? CardCollectionViewCell else { return } print("Swiped Up - Card to Like/Dislike: \(cell.nameLabel.text!)") //Get the IndexPath from Cell being passed (swiped up). if let indexPath = collectionView?.indexPath(for: cell) { //Change the Like status to Like/Dislike. allTheCards[(indexPath as NSIndexPath).row].likedCard = !allTheCards[(indexPath as NSIndexPath).row].likedCard // Update the Like Image cell.likeImage.image = allTheCards[(indexPath as NSIndexPath).row].likedCard ? UIImage(named: "Liked") : UIImage(named:"Disliked") //We are going to Scroll to the next item or to the previous one after Liking/Disliking a card. //So, we check if we ara at the end of the Array to know if we can scroll to the next item. if (indexPath as NSIndexPath).row+1 < allTheCards.count { let nextIndexPath = IndexPath(row: (indexPath as NSIndexPath).row + 1, section: 0) collectionView?.scrollToItem(at: nextIndexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true) } else { //Otherwise, we scroll back to the previous one. let previousIndexPath = IndexPath(row: (indexPath as NSIndexPath).row - 1, section: 0) collectionView?.scrollToItem(at: previousIndexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true) } } } func cellSwipedDown(_ cell: UICollectionViewCell) { guard let cell = cell as? CardCollectionViewCell else { return } print("Swiped Down - Card to Delete: \(cell.nameLabel.text!)") //Get the IndexPath from Cell being passed (swiped down). if let indexPath = collectionView?.indexPath(for: cell) { //Delete the swiped card from the Model. allTheCards.remove(at: (indexPath as NSIndexPath).row) //Delete the swiped card from CollectionView. collectionView?.deleteItems(at: [indexPath]) //Delete cell from View. cell.removeFromSuperview() } } } // MARK: Set the size of the cards extension CardViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 230.0, height: 300.0) } }
mit
6aa199cc232722adda0855a8fdac267c
49.666667
160
0.686757
5.138495
false
false
false
false
aktowns/swen
Sources/Swen/Window.swift
1
4091
// // AudioDeviceEvent.swift created on 28/12/15 // Swen project // // Copyright 2015 Ashley Towns <[email protected]> // // 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 CSDL public struct WindowFlags: OptionSetType { public let rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } static let Fullscreen = WindowFlags(rawValue: SDL_WINDOW_FULLSCREEN.rawValue) static let OpenGL = WindowFlags(rawValue: SDL_WINDOW_OPENGL.rawValue) static let Shown = WindowFlags(rawValue: SDL_WINDOW_SHOWN.rawValue) static let Hidden = WindowFlags(rawValue: SDL_WINDOW_HIDDEN.rawValue) static let Borderless = WindowFlags(rawValue: SDL_WINDOW_BORDERLESS.rawValue) static let Resizable = WindowFlags(rawValue: SDL_WINDOW_RESIZABLE.rawValue) static let Minimised = WindowFlags(rawValue: SDL_WINDOW_MINIMIZED.rawValue) static let Maximised = WindowFlags(rawValue: SDL_WINDOW_MAXIMIZED.rawValue) static let InputGrabbed = WindowFlags(rawValue: SDL_WINDOW_INPUT_GRABBED.rawValue) static let InputFocus = WindowFlags(rawValue: SDL_WINDOW_INPUT_FOCUS.rawValue) static let MouseFocus = WindowFlags(rawValue: SDL_WINDOW_MOUSE_FOCUS.rawValue) static let FullscreenDesktop = WindowFlags(rawValue: SDL_WINDOW_FULLSCREEN_DESKTOP.rawValue) static let Foreign = WindowFlags(rawValue: SDL_WINDOW_FOREIGN.rawValue) static let AllowHighDPI = WindowFlags(rawValue: SDL_WINDOW_ALLOW_HIGHDPI.rawValue) static let MouseCapture = WindowFlags(rawValue: SDL_WINDOW_MOUSE_CAPTURE.rawValue) } let WindowPosUndefined = SDL_WINDOWPOS_UNDEFINED_MASK | 0 let WindowPosCentered = SDL_WINDOWPOS_CENTERED_MASK | 0 public class Window { public typealias RawWindow = COpaquePointer let handle: RawWindow public let renderer: Renderer public init(fromHandle handle: RawWindow) throws { assert(handle != nil, "Window.init handed a null pointer.") self.handle = handle self.renderer = try Renderer(forWindowHandle: handle) } public convenience init(withTitle title: String, position: Vector, size: Size, andFlags flags: WindowFlags) throws { // Hmm could possibly just use SDL_CreateWindowAndRenderer let window = SDL_CreateWindow(title, Int32(position.x), Int32(position.y), Int32(size.sizeX), Int32(size.sizeY), flags.rawValue) assert(window != nil, "SDL_CreateWindow failed: \(SDL.getErrorMessage())") try self.init(fromHandle: window) } public convenience init(withTitle title: String, position: Vector, andSize size: Size) throws { try self.init(withTitle: title, position: position, size: size, andFlags: [WindowFlags.Shown, WindowFlags.AllowHighDPI]) } public convenience init(withTitle title: String, andSize size: Size) throws { try self.init(withTitle: title, position: Vector.fromInt32(x: WindowPosUndefined, y: WindowPosUndefined), andSize: size) } public var surface: Surface { let windowSurface = SDL_GetWindowSurface(handle) return Surface(fromHandle: windowSurface) } public func updateSurface() { let res = SDL_UpdateWindowSurface(handle) assert(res == 0, "SDL_UpdateWindowSurface failed") } public var size: Size { get { var w: Int32 = 0 var h: Int32 = 0 SDL_GetWindowSize(self.handle, &w, &h) return Size(sizeX: w, sizeY: h) } set { SDL_SetWindowSize(self.handle, Int32(newValue.sizeX), Int32(newValue.sizeY)) } } }
apache-2.0
fd0500069a43f938822319fe4a431e7d
35.20354
97
0.713273
3.844925
false
false
false
false
ryanbaldwin/Restivus
Tests/Person.swift
1
512
// // Person.swift // RestivusTests // // Created by Ryan Baldwin on 2017-08-23. // Copyright © 2017 bunnyhug.me. All rights governed under the Apache 2 License Agreement // import Foundation struct Person: Codable { let firstName: String let lastName: String let age: Int } extension Person: Equatable { static func ==(lhs: Person, rhs: Person) -> Bool { return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName && lhs.age == rhs.age } }
apache-2.0
bf54c4c079ae3fd4c44011496c865a00
21.217391
90
0.634051
3.842105
false
false
false
false
steelwheels/Coconut
CoconutData/Source/Data/CNRange.swift
1
1063
/** * @file CNRange.swift * @brief Define CNRange class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ import Foundation public extension NSRange { static let ClassName = "range" static func fromValue(value val: CNValue) -> NSRange? { if let dict = val.toDictionary() { return fromValue(value: dict) } else { return nil } } static func fromValue(value val: Dictionary<String, CNValue>) -> NSRange? { if let locval = val["location"], let lenval = val["length"] { if let locnum = locval.toNumber(), let lennum = lenval.toNumber() { let loc = locnum.intValue let len = lennum.intValue return NSRange(location: loc, length: len) } } return nil } func toValue() -> Dictionary<String, CNValue> { let locnum = NSNumber(integerLiteral: self.location) let lennum = NSNumber(integerLiteral: self.length) let result: Dictionary<String, CNValue> = [ "class" : .stringValue(NSRange.ClassName), "location" : .numberValue(locnum), "length" : .numberValue(lennum) ] return result } }
lgpl-2.1
0ec9912192ae572990958c0f8cb64c4c
23.159091
76
0.672625
3.291022
false
false
false
false
omiz/In-Air
In Air/Source/ViewController/SettingsViewController.swift
1
2000
// // SettingsViewController.swift // In Air // // Created by Omar Allaham on 4/5/17. // Copyright © 2017 Bemaxnet. All rights reserved. // import UIKit class SettingsViewController: UITableViewController { @IBOutlet weak var cellularData: UISwitch! @IBOutlet weak var airportVolume: ZSlider! @IBOutlet weak var stopIfOffline: UISwitch! @IBOutlet weak var showNearest: UISwitch! @IBOutlet weak var musicVolume: ZSlider! @IBOutlet weak var automaticalyDownload: UISwitch! @IBOutlet weak var playMusic: UISwitch! override func viewDidLoad() { super.viewDidLoad() title = "Settings" prepare() } func prepare() { cellularData.isOn = Settings.shared.cellularData airportVolume.value = Settings.shared.airportVolume stopIfOffline.isOn = Settings.shared.stopIfOffline showNearest.isOn = Settings.shared.showNearest musicVolume.value = Settings.shared.musicVolume automaticalyDownload.isOn = Settings.shared.automaticalyDownload } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cellularDataChanged(_ sender: UISwitch) { Settings.shared.cellularData = sender.isOn } @IBAction func airportVolumeChanged(_ sender: ZSlider) { Settings.shared.airportVolume = sender.value } @IBAction func stopIfOfflineChanged(_ sender: UISwitch) { Settings.shared.stopIfOffline = sender.isOn } @IBAction func showNearestChanged(_ sender: UISwitch) { Settings.shared.showNearest = sender.isOn } @IBAction func musicVolumeChanged(_ sender: ZSlider) { Settings.shared.musicVolume = sender.value } @IBAction func playMusicChanged(_ sender: UISwitch) { Settings.shared.playMusic = sender.isOn } @IBAction func automaticallyDownloadChanged(_ sender: UISwitch) { Settings.shared.automaticalyDownload = sender.isOn } }
apache-2.0
e6e77a3edb483c2abb55ad471756b5f6
26.013514
70
0.711856
4.472036
false
false
false
false
brentdax/swift
benchmark/single-source/ChainedFilterMap.swift
6
1029
import TestsUtils public var ChainedFilterMap = [ BenchmarkInfo(name: "ChainedFilterMap", runFunction: run_ChainedFilterMap, tags: [.algorithm]), BenchmarkInfo(name: "FatCompactMap", runFunction: run_FatCompactMap, tags: [.algorithm]) ] public let first100k = Array(0...100_000-1) @inline(never) public func run_ChainedFilterMap(_ N: Int) { var result = 0 for _ in 1...10*N { let numbers = first100k.lazy .filter { $0 % 3 == 0 } .map { $0 * 2 } .filter { $0 % 8 == 0 } .map { $0 / 2 + 1} result = numbers.reduce(into: 0) { $0 += $1 } } CheckResults(result == 416691666) } @inline(never) public func run_FatCompactMap(_ N: Int) { var result = 0 for _ in 1...10*N { let numbers = first100k.lazy .compactMap { (x: Int) -> Int? in if x % 3 != 0 { return nil } let y = x * 2 if y % 8 != 0 { return nil } let z = y / 2 + 1 return z } result = numbers.reduce(into: 0) { $0 += $1 } } CheckResults(result == 416691666) }
apache-2.0
7c2eb72a12f3e799b85c193799c19569
24.725
97
0.5724
3.137195
false
false
false
false
brentdax/swift
test/Serialization/search-paths-relative.swift
6
1713
// RUN: %empty-directory(%t) // RUN: %empty-directory(%t/secret) // RUN: %target-swift-frontend -emit-module -o %t/secret %S/Inputs/struct_with_operators.swift // RUN: %empty-directory(%t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule) // RUN: %target-swift-frontend -emit-module -o %t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule/%target-swiftmodule-name %S/Inputs/alias.swift -module-name has_alias // RUN: cd %t/secret && %target-swiftc_driver -emit-module -o %t/has_xref.swiftmodule -I . -F ../Frameworks -parse-as-library %S/Inputs/has_xref.swift %S/../Inputs/empty.swift -Xfrontend -serialize-debugging-options -Xcc -ivfsoverlay -Xcc %S/../Inputs/unextended-module-overlay.yaml -Xcc -DDUMMY // RUN: %target-swift-frontend %s -typecheck -I %t // Check the actual serialized search paths. // RUN: llvm-bcanalyzer -dump %t/has_xref.swiftmodule > %t/has_xref.swiftmodule.txt // RUN: %FileCheck %s < %t/has_xref.swiftmodule.txt // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/has_xref.swiftmodule.txt import has_xref numeric(42) // CHECK-LABEL: <OPTIONS_BLOCK // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-working-directory' // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '{{.+}}/secret' // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-DDUMMY' // CHECK: </OPTIONS_BLOCK> // CHECK-LABEL: <INPUT_BLOCK // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=1 op1=0/> blob data = '{{.+}}/secret/../Frameworks' // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=0 op1=0/> blob data = '{{.+}}/secret/.' // CHECK: </INPUT_BLOCK> // NEGATIVE-NOT: '.' // NEGATIVE-NOT: '../Frameworks' // This should be filtered out. // NEGATIVE-NOT: -ivfsoverlay{{.*}}unextended-module-overlay.yaml
apache-2.0
a80bd3a4f47a28a09c11e16cda09524f
50.909091
295
0.684764
2.97913
false
false
false
false
alblue/swift-corelibs-foundation
Foundation/NumberFormatter.swift
1
29257
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(macOS) || os(iOS) internal let kCFNumberFormatterNoStyle = CFNumberFormatterStyle.noStyle internal let kCFNumberFormatterDecimalStyle = CFNumberFormatterStyle.decimalStyle internal let kCFNumberFormatterCurrencyStyle = CFNumberFormatterStyle.currencyStyle internal let kCFNumberFormatterPercentStyle = CFNumberFormatterStyle.percentStyle internal let kCFNumberFormatterScientificStyle = CFNumberFormatterStyle.scientificStyle internal let kCFNumberFormatterSpellOutStyle = CFNumberFormatterStyle.spellOutStyle internal let kCFNumberFormatterOrdinalStyle = CFNumberFormatterStyle.ordinalStyle internal let kCFNumberFormatterCurrencyISOCodeStyle = CFNumberFormatterStyle.currencyISOCodeStyle internal let kCFNumberFormatterCurrencyPluralStyle = CFNumberFormatterStyle.currencyPluralStyle internal let kCFNumberFormatterCurrencyAccountingStyle = CFNumberFormatterStyle.currencyAccountingStyle #endif extension NumberFormatter { public enum Style : UInt { case none = 0 case decimal = 1 case currency = 2 case percent = 3 case scientific = 4 case spellOut = 5 case ordinal = 6 case currencyISOCode = 8 // 7 is not used case currencyPlural = 9 case currencyAccounting = 10 } public enum PadPosition : UInt { case beforePrefix case afterPrefix case beforeSuffix case afterSuffix } public enum RoundingMode : UInt { case ceiling case floor case down case up case halfEven case halfDown case halfUp } } open class NumberFormatter : Formatter { typealias CFType = CFNumberFormatter private var _currentCfFormatter: CFType? private var _cfFormatter: CFType { if let obj = _currentCfFormatter { return obj } else { #if os(macOS) || os(iOS) let numberStyle = CFNumberFormatterStyle(rawValue: CFIndex(self.numberStyle.rawValue))! #else let numberStyle = CFNumberFormatterStyle(self.numberStyle.rawValue) #endif let obj = CFNumberFormatterCreate(kCFAllocatorSystemDefault, locale._cfObject, numberStyle)! _setFormatterAttributes(obj) if let format = _format { CFNumberFormatterSetFormat(obj, format._cfObject) } _currentCfFormatter = obj return obj } } // this is for NSUnitFormatter open var formattingContext: Context = .unknown // default is NSFormattingContextUnknown // Report the used range of the string and an NSError, in addition to the usual stuff from Formatter /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func objectValue(_ string: String, range: inout NSRange) throws -> Any? { NSUnimplemented() } open override func string(for obj: Any) -> String? { //we need to allow Swift's numeric types here - Int, Double et al. guard let number = _SwiftValue.store(obj) as? NSNumber else { return nil } return string(from: number) } // Even though NumberFormatter responds to the usual Formatter methods, // here are some convenience methods which are a little more obvious. open func string(from number: NSNumber) -> String? { return CFNumberFormatterCreateStringWithNumber(kCFAllocatorSystemDefault, _cfFormatter, number._cfObject)._swiftObject } open func number(from string: String) -> NSNumber? { var range = CFRange(location: 0, length: string.length) let number = withUnsafeMutablePointer(to: &range) { (rangePointer: UnsafeMutablePointer<CFRange>) -> NSNumber? in #if os(macOS) || os(iOS) let parseOption = allowsFloats ? 0 : CFNumberFormatterOptionFlags.parseIntegersOnly.rawValue #else let parseOption = allowsFloats ? 0 : CFOptionFlags(kCFNumberFormatterParseIntegersOnly) #endif let result = CFNumberFormatterCreateNumberFromString(kCFAllocatorSystemDefault, _cfFormatter, string._cfObject, rangePointer, parseOption) return result?._nsObject } return number } open class func localizedString(from num: NSNumber, number nstyle: Style) -> String { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = nstyle return numberFormatter.string(for: num)! } internal func _reset() { _currentCfFormatter = nil } internal func _setFormatterAttributes(_ formatter: CFNumberFormatter) { _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyCode, value: _currencyCode?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterDecimalSeparator, value: _decimalSeparator?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyDecimalSeparator, value: _currencyDecimalSeparator?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterAlwaysShowDecimalSeparator, value: _alwaysShowsDecimalSeparator._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterGroupingSeparator, value: _groupingSeparator?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseGroupingSeparator, value: _usesGroupingSeparator._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPercentSymbol, value: _percentSymbol?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterZeroSymbol, value: _zeroSymbol?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNaNSymbol, value: _notANumberSymbol?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInfinitySymbol, value: _positiveInfinitySymbol._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinusSign, value: _minusSign?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPlusSign, value: _plusSign?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencySymbol, value: _currencySymbol?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterExponentSymbol, value: _exponentSymbol?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinIntegerDigits, value: minimumIntegerDigits._bridgeToObjectiveC()._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxIntegerDigits, value: _maximumIntegerDigits._bridgeToObjectiveC()._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinFractionDigits, value: _minimumFractionDigits._bridgeToObjectiveC()._cfObject) if _minimumFractionDigits <= 0 { _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxFractionDigits, value: _maximumFractionDigits._bridgeToObjectiveC()._cfObject) } _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterGroupingSize, value: _groupingSize._bridgeToObjectiveC()._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterSecondaryGroupingSize, value: _secondaryGroupingSize._bridgeToObjectiveC()._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterRoundingMode, value: _roundingMode.rawValue._bridgeToObjectiveC()._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterRoundingIncrement, value: _roundingIncrement?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterFormatWidth, value: _formatWidth._bridgeToObjectiveC()._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPaddingCharacter, value: _paddingCharacter?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPaddingPosition, value: _paddingPosition.rawValue._bridgeToObjectiveC()._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMultiplier, value: _multiplier?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPositivePrefix, value: _positivePrefix?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPositiveSuffix, value: _positiveSuffix?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNegativePrefix, value: _negativePrefix?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNegativeSuffix, value: _negativeSuffix?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPerMillSymbol, value: _percentSymbol?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInternationalCurrencySymbol, value: _internationalCurrencySymbol?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyGroupingSeparator, value: _currencyGroupingSeparator?._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterIsLenient, value: _lenient._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseSignificantDigits, value: _usesSignificantDigits._cfObject) if _usesSignificantDigits { _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinSignificantDigits, value: _minimumSignificantDigits._bridgeToObjectiveC()._cfObject) _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxSignificantDigits, value: _maximumSignificantDigits._bridgeToObjectiveC()._cfObject) } } internal func _setFormatterAttribute(_ formatter: CFNumberFormatter, attributeName: CFString, value: AnyObject?) { if let value = value { CFNumberFormatterSetProperty(formatter, attributeName, value) } } // Attributes of a NumberFormatter internal var _numberStyle: Style = .none open var numberStyle: Style { get { return _numberStyle } set { switch newValue { case .none, .ordinal, .spellOut: _usesSignificantDigits = false case .currency, .currencyISOCode, .currencyAccounting: _usesSignificantDigits = false _usesGroupingSeparator = true if _minimumIntegerDigits == nil { _minimumIntegerDigits = 1 } if _groupingSize == 0 { _groupingSize = 3 } _minimumFractionDigits = 2 case .currencyPlural: _usesSignificantDigits = false _usesGroupingSeparator = true if _minimumIntegerDigits == nil { _minimumIntegerDigits = 0 } _minimumFractionDigits = 2 case .decimal: _usesGroupingSeparator = true _maximumFractionDigits = 3 if _minimumIntegerDigits == nil { _minimumIntegerDigits = 1 } if _groupingSize == 0 { _groupingSize = 3 } case .percent: _usesSignificantDigits = false _usesGroupingSeparator = true if _minimumIntegerDigits == nil { _minimumIntegerDigits = 1 } if _groupingSize == 0 { _groupingSize = 3 } _minimumFractionDigits = 0 _maximumFractionDigits = 0 case .scientific: _usesSignificantDigits = false _usesGroupingSeparator = false if _minimumIntegerDigits == nil { _minimumIntegerDigits = 0 } } _reset() _numberStyle = newValue } } internal var _locale: Locale = Locale.current /*@NSCopying*/ open var locale: Locale! { get { return _locale } set { _reset() _locale = newValue } } internal var _generatesDecimalNumbers: Bool = false open var generatesDecimalNumbers: Bool { get { return _generatesDecimalNumbers } set { _reset() _generatesDecimalNumbers = newValue } } internal var _negativeFormat: String! open var negativeFormat: String! { get { return _negativeFormat } set { _reset() _negativeFormat = newValue } } internal var _textAttributesForNegativeValues: [String : Any]? open var textAttributesForNegativeValues: [String : Any]? { get { return _textAttributesForNegativeValues } set { _reset() _textAttributesForNegativeValues = newValue } } internal var _positiveFormat: String! open var positiveFormat: String! { get { return _positiveFormat } set { _reset() _positiveFormat = newValue } } internal var _textAttributesForPositiveValues: [String : Any]? open var textAttributesForPositiveValues: [String : Any]? { get { return _textAttributesForPositiveValues } set { _reset() _textAttributesForPositiveValues = newValue } } internal var _allowsFloats: Bool = true open var allowsFloats: Bool { get { return _allowsFloats } set { _reset() _allowsFloats = newValue } } internal var _decimalSeparator: String! open var decimalSeparator: String! { get { return _decimalSeparator } set { _reset() _decimalSeparator = newValue } } internal var _alwaysShowsDecimalSeparator: Bool = false open var alwaysShowsDecimalSeparator: Bool { get { return _alwaysShowsDecimalSeparator } set { _reset() _alwaysShowsDecimalSeparator = newValue } } internal var _currencyDecimalSeparator: String! open var currencyDecimalSeparator: String! { get { return _currencyDecimalSeparator } set { _reset() _currencyDecimalSeparator = newValue } } internal var _usesGroupingSeparator: Bool = false open var usesGroupingSeparator: Bool { get { return _usesGroupingSeparator } set { _reset() _usesGroupingSeparator = newValue } } internal var _groupingSeparator: String! open var groupingSeparator: String! { get { return _groupingSeparator } set { _reset() _groupingSeparator = newValue } } // internal var _zeroSymbol: String? open var zeroSymbol: String? { get { return _zeroSymbol } set { _reset() _zeroSymbol = newValue } } internal var _textAttributesForZero: [String : Any]? open var textAttributesForZero: [String : Any]? { get { return _textAttributesForZero } set { _reset() _textAttributesForZero = newValue } } internal var _nilSymbol: String = "" open var nilSymbol: String { get { return _nilSymbol } set { _reset() _nilSymbol = newValue } } internal var _textAttributesForNil: [String : Any]? open var textAttributesForNil: [String : Any]? { get { return _textAttributesForNil } set { _reset() _textAttributesForNil = newValue } } internal var _notANumberSymbol: String! open var notANumberSymbol: String! { get { return _notANumberSymbol } set { _reset() _notANumberSymbol = newValue } } internal var _textAttributesForNotANumber: [String : Any]? open var textAttributesForNotANumber: [String : Any]? { get { return _textAttributesForNotANumber } set { _reset() _textAttributesForNotANumber = newValue } } internal var _positiveInfinitySymbol: String = "+∞" open var positiveInfinitySymbol: String { get { return _positiveInfinitySymbol } set { _reset() _positiveInfinitySymbol = newValue } } internal var _textAttributesForPositiveInfinity: [String : Any]? open var textAttributesForPositiveInfinity: [String : Any]? { get { return _textAttributesForPositiveInfinity } set { _reset() _textAttributesForPositiveInfinity = newValue } } internal var _negativeInfinitySymbol: String = "-∞" open var negativeInfinitySymbol: String { get { return _negativeInfinitySymbol } set { _reset() _negativeInfinitySymbol = newValue } } internal var _textAttributesForNegativeInfinity: [String : Any]? open var textAttributesForNegativeInfinity: [String : Any]? { get { return _textAttributesForNegativeInfinity } set { _reset() _textAttributesForNegativeInfinity = newValue } } // internal var _positivePrefix: String! open var positivePrefix: String! { get { return _positivePrefix } set { _reset() _positivePrefix = newValue } } internal var _positiveSuffix: String! open var positiveSuffix: String! { get { return _positiveSuffix } set { _reset() _positiveSuffix = newValue } } internal var _negativePrefix: String! open var negativePrefix: String! { get { return _negativePrefix } set { _reset() _negativePrefix = newValue } } internal var _negativeSuffix: String! open var negativeSuffix: String! { get { return _negativeSuffix } set { _reset() _negativeSuffix = newValue } } internal var _currencyCode: String! open var currencyCode: String! { get { return _currencyCode } set { _reset() _currencyCode = newValue } } internal var _currencySymbol: String! open var currencySymbol: String! { get { return _currencySymbol } set { _reset() _currencySymbol = newValue } } internal var _internationalCurrencySymbol: String! open var internationalCurrencySymbol: String! { get { return _internationalCurrencySymbol } set { _reset() _internationalCurrencySymbol = newValue } } internal var _percentSymbol: String! open var percentSymbol: String! { get { return _percentSymbol } set { _reset() _percentSymbol = newValue } } internal var _perMillSymbol: String! open var perMillSymbol: String! { get { return _perMillSymbol } set { _reset() _perMillSymbol = newValue } } internal var _minusSign: String! open var minusSign: String! { get { return _minusSign } set { _reset() _minusSign = newValue } } internal var _plusSign: String! open var plusSign: String! { get { return _plusSign } set { _reset() _plusSign = newValue } } internal var _exponentSymbol: String! open var exponentSymbol: String! { get { return _exponentSymbol } set { _reset() _exponentSymbol = newValue } } // internal var _groupingSize: Int = 0 open var groupingSize: Int { get { return _groupingSize } set { _reset() _groupingSize = newValue } } internal var _secondaryGroupingSize: Int = 0 open var secondaryGroupingSize: Int { get { return _secondaryGroupingSize } set { _reset() _secondaryGroupingSize = newValue } } internal var _multiplier: NSNumber? /*@NSCopying*/ open var multiplier: NSNumber? { get { return _multiplier } set { _reset() _multiplier = newValue } } internal var _formatWidth: Int = 0 open var formatWidth: Int { get { return _formatWidth } set { _reset() _formatWidth = newValue } } internal var _paddingCharacter: String! open var paddingCharacter: String! { get { return _paddingCharacter } set { _reset() _paddingCharacter = newValue } } // internal var _paddingPosition: PadPosition = .beforePrefix open var paddingPosition: PadPosition { get { return _paddingPosition } set { _reset() _paddingPosition = newValue } } internal var _roundingMode: RoundingMode = .halfEven open var roundingMode: RoundingMode { get { return _roundingMode } set { _reset() _roundingMode = newValue } } internal var _roundingIncrement: NSNumber! = 0 /*@NSCopying*/ open var roundingIncrement: NSNumber! { get { return _roundingIncrement } set { _reset() _roundingIncrement = newValue } } // Use an optional for _minimumIntegerDigits to track if the value is // set BEFORE the .numberStyle is changed. This allows preserving a setting // of 0. internal var _minimumIntegerDigits: Int? open var minimumIntegerDigits: Int { get { return _minimumIntegerDigits ?? 0 } set { _reset() _minimumIntegerDigits = newValue } } internal var _maximumIntegerDigits: Int = 42 open var maximumIntegerDigits: Int { get { return _maximumIntegerDigits } set { _reset() _maximumIntegerDigits = newValue } } internal var _minimumFractionDigits: Int = 0 open var minimumFractionDigits: Int { get { return _minimumFractionDigits } set { _reset() _minimumFractionDigits = newValue } } internal var _maximumFractionDigits: Int = 0 open var maximumFractionDigits: Int { get { return _maximumFractionDigits } set { _reset() _maximumFractionDigits = newValue } } internal var _minimum: NSNumber? /*@NSCopying*/ open var minimum: NSNumber? { get { return _minimum } set { _reset() _minimum = newValue } } internal var _maximum: NSNumber? /*@NSCopying*/ open var maximum: NSNumber? { get { return _maximum } set { _reset() _maximum = newValue } } internal var _currencyGroupingSeparator: String! open var currencyGroupingSeparator: String! { get { return _currencyGroupingSeparator } set { _reset() _currencyGroupingSeparator = newValue } } internal var _lenient: Bool = false open var isLenient: Bool { get { return _lenient } set { _reset() _lenient = newValue } } internal var _usesSignificantDigits: Bool = false open var usesSignificantDigits: Bool { get { return _usesSignificantDigits } set { _reset() _usesSignificantDigits = newValue } } internal var _minimumSignificantDigits: Int = 1 open var minimumSignificantDigits: Int { get { return _minimumSignificantDigits } set { _reset() _usesSignificantDigits = true _minimumSignificantDigits = newValue } } internal var _maximumSignificantDigits: Int = 6 open var maximumSignificantDigits: Int { get { return _maximumSignificantDigits } set { _reset() _usesSignificantDigits = true _maximumSignificantDigits = newValue } } internal var _partialStringValidationEnabled: Bool = false open var isPartialStringValidationEnabled: Bool { get { return _partialStringValidationEnabled } set { _reset() _partialStringValidationEnabled = newValue } } // internal var _hasThousandSeparators: Bool = false open var hasThousandSeparators: Bool { get { return _hasThousandSeparators } set { _reset() _hasThousandSeparators = newValue } } internal var _thousandSeparator: String! open var thousandSeparator: String! { get { return _thousandSeparator } set { _reset() _thousandSeparator = newValue } } // internal var _localizesFormat: Bool = true open var localizesFormat: Bool { get { return _localizesFormat } set { _reset() _localizesFormat = newValue } } // internal var _format: String? open var format: String { get { return _format ?? "#;0;#" } set { _reset() _format = newValue } } // internal var _attributedStringForZero: NSAttributedString = NSAttributedString(string: "0") /*@NSCopying*/ open var attributedStringForZero: NSAttributedString { get { return _attributedStringForZero } set { _reset() _attributedStringForZero = newValue } } internal var _attributedStringForNil: NSAttributedString = NSAttributedString(string: "") /*@NSCopying*/ open var attributedStringForNil: NSAttributedString { get { return _attributedStringForNil } set { _reset() _attributedStringForNil = newValue } } internal var _attributedStringForNotANumber: NSAttributedString = NSAttributedString(string: "NaN") /*@NSCopying*/ open var attributedStringForNotANumber: NSAttributedString { get { return _attributedStringForNotANumber } set { _reset() _attributedStringForNotANumber = newValue } } internal var _roundingBehavior: NSDecimalNumberHandler = NSDecimalNumberHandler.default /*@NSCopying*/ open var roundingBehavior: NSDecimalNumberHandler { get { return _roundingBehavior } set { _reset() _roundingBehavior = newValue } } }
apache-2.0
8a714c66b7819015023a529cdbd2b063
29.955556
166
0.590982
5.977319
false
false
false
false
tjw/swift
test/IRGen/big_types_corner_cases_as_library.swift
1
765
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -enable-large-loadable-types %s -emit-ir -parse-as-library | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize public struct BigStruct { var i0 : Int32 = 0 var i1 : Int32 = 1 var i2 : Int32 = 2 var i3 : Int32 = 3 var i4 : Int32 = 4 var i5 : Int32 = 5 var i6 : Int32 = 6 var i7 : Int32 = 7 var i8 : Int32 = 8 } // CHECK-LABEL: define{{( protected)?}} linkonce_odr hidden %swift.opaque* @"$S33big_types_corner_cases_as_library9BigStructVwCP" // CHECK: [[RETVAL:%.*]] = bitcast %T33big_types_corner_cases_as_library9BigStructV* {{.*}} to %swift.opaque* // CHECK: ret %swift.opaque* [[RETVAL]] let bigStructGlobalArray : [BigStruct] = [ BigStruct() ]
apache-2.0
675917d68e81383693233981f428b28c
37.25
206
0.673203
3.023715
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Managers/Animators/TabBarAnimator.swift
1
4784
// // TabBarAnimator.swift // Inbbbox // // Created by Patryk Kaczmarek on 21/01/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit import PromiseKit class TabBarAnimator { fileprivate let centerButton = RoundedButton() fileprivate let tabBarView = CenterButtonTabBarView() fileprivate var tabBarHeight: CGFloat { return tabBarView.intrinsicContentSize.height } init(view: LoginView) { let tabBarHeight = tabBarView.intrinsicContentSize.height tabBarView.layer.shadowColor = UIColor(white: 0, alpha: 0.03).cgColor tabBarView.layer.shadowRadius = 1 tabBarView.layer.shadowOpacity = 0.6 view.addSubview(tabBarView) tabBarView.frame = CGRect( x: 0, y: view.frame.maxY, width: view.frame.width, height: tabBarHeight ) tabBarView.layoutIfNeeded() centerButton.setImage(UIImage(named: "ic-ball-active"), for: .normal) centerButton.backgroundColor = .white tabBarView.addSubview(centerButton) centerButton.frame = CGRect( x: tabBarView.frame.width / 2 - centerButton.intrinsicContentSize.width / 2, y: -centerButton.intrinsicContentSize.height - 8, width: centerButton.intrinsicContentSize.width, height: centerButton.intrinsicContentSize.height ) } func animateTabBar() -> Promise<Void> { return Promise<Void> { fulfill, _ in firstly { prepare() }.then { self.fadeCenterButtonIn() }.then { when(fulfilled: [self.slideTabBar(), self.slideTabBarItemsSubsequently(), self.positionCenterButton()]) }.then { fulfill() }.catch { _ in } } } } private extension TabBarAnimator { func slideTabBarItemsSubsequently() -> Promise<Void> { return Promise<Void> { fulfill, _ in UIView.animateKeyframes(withDuration: 1, delay: 0, options: .layoutSubviews, animations: { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.25, animations: { self.tabBarView.likesItemViewVerticalConstraint?.constant -= self.tabBarHeight self.tabBarView.layoutIfNeeded() }) UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25, animations: { self.tabBarView.bucketsItemViewVerticalConstraint?.constant -= self.tabBarHeight self.tabBarView.layoutIfNeeded() }) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: { self.tabBarView.followingItemViewVerticalConstraint?.constant -= self.tabBarHeight self.tabBarView.layoutIfNeeded() }) UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: { self.tabBarView.accountItemViewVerticalConstraint?.constant -= self.tabBarHeight self.tabBarView.layoutIfNeeded() }) }, completion: { _ in fulfill() }) } } func slideTabBar() -> Promise<Void> { var frame = tabBarView.frame frame.origin.y -= tabBarHeight return Promise<Void> { fulfill, _ in UIView.animate(withDuration: 0.5, animations: { self.tabBarView.frame = frame }, completion: { _ in fulfill() }) } } func positionCenterButton() -> Promise<Void> { var frame = centerButton.frame frame.origin.y += tabBarHeight return Promise<Void> { fulfill, _ in UIView.animate(withDuration: 0.5, animations: { self.centerButton.frame = frame }, completion: { _ in fulfill() }) } } func fadeCenterButtonIn() -> Promise<Void> { return Promise<Void> { fulfill, _ in UIView.animate(withDuration: 0.5, delay: 0.1, options: [], animations: { self.centerButton.alpha = 1 }, completion: { _ in fulfill() }) } } func prepare() -> Promise<Void> { tabBarView.likesItemViewVerticalConstraint?.constant += tabBarHeight tabBarView.bucketsItemViewVerticalConstraint?.constant += tabBarHeight tabBarView.followingItemViewVerticalConstraint?.constant += tabBarHeight tabBarView.accountItemViewVerticalConstraint?.constant += tabBarHeight centerButton.alpha = 0.0 return Promise<Void>(value:Void()) } }
gpl-3.0
6b844e1c5cd16cb745ce4f3943c41c1f
32.921986
119
0.593561
5.143011
false
false
false
false
raulriera/AuthenticationViewController
AuthenticationViewController/Example/OAuthInstagram.swift
1
1177
// // OAuthInstagram.swift // AuthenticationViewController // // Created by Raul Riera on 04/11/2015. // Copyright © 2015 Raul Riera. All rights reserved. // import Foundation import AuthenticationViewController struct OAuthInstagram: AuthenticationProvider { let title: String? let clientId: String let clientSecret: String let scopes: [String] let redirectURI = "your-redirect-uri" // this is required for Instagram var authorizationURL: URL { return URL(string: "https://api.instagram.com/oauth/authorize/?client_id=\(clientId)&scope=\(scopes.joined(separator: "+"))&redirect_uri=\(redirectURI)&response_type=code")! } var accessTokenURL: URL { return URL(string: "https://api.instagram.com/oauth/access_token")! } var parameters: [String: String] { return ["grant_type": "authorization_code", "redirect_uri": redirectURI] } // MARK: Initialisers init(clientId: String, clientSecret: String, scopes: [String]) { self.clientId = clientId self.clientSecret = clientSecret self.scopes = scopes self.title = "Instagram" } }
mit
556a5dab0b92acd8248eb6e6eec0bc37
27.682927
181
0.659014
4.371747
false
false
false
false
smileyborg/PureLayout
PureLayout/Example-iOS/Demos/iOSDemo1ViewController.swift
4
3415
// // iOSDemo1ViewController.swift // PureLayout Example-iOS // // Copyright (c) 2015 Tyler Fox // https://github.com/PureLayout/PureLayout // import UIKit import PureLayout @objc(iOSDemo1ViewController) class iOSDemo1ViewController: UIViewController { let blueView: UIView = { let view = UIView.newAutoLayout() view.backgroundColor = .blue return view }() let redView: UIView = { let view = UIView.newAutoLayout() view.backgroundColor = .red return view }() let yellowView: UIView = { let view = UIView.newAutoLayout() view.backgroundColor = .yellow return view }() let greenView: UIView = { let view = UIView.newAutoLayout() view.backgroundColor = .green return view }() var didSetupConstraints = false override func loadView() { view = UIView() view.backgroundColor = UIColor(white: 0.1, alpha: 1.0) view.addSubview(blueView) view.addSubview(redView) view.addSubview(yellowView) view.addSubview(greenView) view.setNeedsUpdateConstraints() // bootstrap Auto Layout } override func updateViewConstraints() { // Check a flag didSetupConstraints before creating constraints, because this method may be called multiple times, and we // only want to create these constraints once. Without this check, the same constraints could be added multiple times, // which can hurt performance and cause other issues. See Demo 7 (Animation) for an example of code that runs every time. if (!didSetupConstraints) { // Blue view is centered on screen, with size {50 pt, 50 pt} blueView.autoCenterInSuperview() blueView.autoSetDimensions(to: CGSize(width: 50.0, height: 50.0)) // Red view is positioned at the bottom right corner of the blue view, with the same width, and a height of 40 pt redView.autoPinEdge(.top, to: .bottom, of: blueView) redView.autoPinEdge(.left, to: .right, of: blueView) redView.autoMatch(.width, to: .width, of: blueView) redView.autoSetDimension(.height, toSize: 40.0) // Yellow view is positioned 10 pt below the red view, extending across the screen with 20 pt insets from the edges, // and with a fixed height of 25 pt yellowView.autoPinEdge(.top, to: .bottom, of: redView, withOffset: 10.0) yellowView.autoSetDimension(.height, toSize: 25.0) yellowView.autoPinEdge(toSuperviewEdge: .left, withInset: 20.0) yellowView.autoPinEdge(toSuperviewEdge: .right, withInset: 20.0) // Green view is positioned 10 pt below the yellow view, aligned to the vertical axis of its superview, // with its height twice the height of the yellow view and its width fixed to 150 pt greenView.autoPinEdge(.top, to: .bottom, of: yellowView, withOffset: 10.0) greenView.autoAlignAxis(toSuperviewAxis: .vertical) greenView.autoMatch(.height, to: .height, of: yellowView, withMultiplier: 2.0) greenView.autoSetDimension(.width, toSize: 150.0) didSetupConstraints = true } super.updateViewConstraints() } }
mit
a5ffb2b8ca1bb6c30ada0bddd24862fc
39.654762
129
0.631918
4.934971
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/SQS/SQS_Error.swift
1
5359
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for SQS public struct SQSErrorType: AWSErrorType { enum Code: String { case batchEntryIdsNotDistinct = "AWS.SimpleQueueService.BatchEntryIdsNotDistinct" case batchRequestTooLong = "AWS.SimpleQueueService.BatchRequestTooLong" case emptyBatchRequest = "AWS.SimpleQueueService.EmptyBatchRequest" case invalidAttributeName = "InvalidAttributeName" case invalidBatchEntryId = "AWS.SimpleQueueService.InvalidBatchEntryId" case invalidIdFormat = "InvalidIdFormat" case invalidMessageContents = "InvalidMessageContents" case messageNotInflight = "AWS.SimpleQueueService.MessageNotInflight" case overLimit = "OverLimit" case purgeQueueInProgress = "AWS.SimpleQueueService.PurgeQueueInProgress" case queueDeletedRecently = "AWS.SimpleQueueService.QueueDeletedRecently" case queueDoesNotExist = "AWS.SimpleQueueService.NonExistentQueue" case queueNameExists = "QueueAlreadyExists" case receiptHandleIsInvalid = "ReceiptHandleIsInvalid" case tooManyEntriesInBatchRequest = "AWS.SimpleQueueService.TooManyEntriesInBatchRequest" case unsupportedOperation = "AWS.SimpleQueueService.UnsupportedOperation" } private let error: Code public let context: AWSErrorContext? /// initialize SQS public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// Two or more batch entries in the request have the same Id. public static var batchEntryIdsNotDistinct: Self { .init(.batchEntryIdsNotDistinct) } /// The length of all the messages put together is more than the limit. public static var batchRequestTooLong: Self { .init(.batchRequestTooLong) } /// The batch request doesn't contain any entries. public static var emptyBatchRequest: Self { .init(.emptyBatchRequest) } /// The specified attribute doesn't exist. public static var invalidAttributeName: Self { .init(.invalidAttributeName) } /// The Id of a batch entry in a batch request doesn't abide by the specification. public static var invalidBatchEntryId: Self { .init(.invalidBatchEntryId) } /// The specified receipt handle isn't valid for the current version. public static var invalidIdFormat: Self { .init(.invalidIdFormat) } /// The message contains characters outside the allowed set. public static var invalidMessageContents: Self { .init(.invalidMessageContents) } /// The specified message isn't in flight. public static var messageNotInflight: Self { .init(.messageNotInflight) } /// The specified action violates a limit. For example, ReceiveMessage returns this error if the maximum number of inflight messages is reached and AddPermission returns this error if the maximum number of permissions for the queue is reached. public static var overLimit: Self { .init(.overLimit) } /// Indicates that the specified queue previously received a PurgeQueue request within the last 60 seconds (the time it can take to delete the messages in the queue). public static var purgeQueueInProgress: Self { .init(.purgeQueueInProgress) } /// You must wait 60 seconds after deleting a queue before you can create another queue with the same name. public static var queueDeletedRecently: Self { .init(.queueDeletedRecently) } /// The specified queue doesn't exist. public static var queueDoesNotExist: Self { .init(.queueDoesNotExist) } /// A queue with this name already exists. Amazon SQS returns this error only if the request includes attributes whose values differ from those of the existing queue. public static var queueNameExists: Self { .init(.queueNameExists) } /// The specified receipt handle isn't valid. public static var receiptHandleIsInvalid: Self { .init(.receiptHandleIsInvalid) } /// The batch request contains more entries than permissible. public static var tooManyEntriesInBatchRequest: Self { .init(.tooManyEntriesInBatchRequest) } /// Error code 400. Unsupported operation. public static var unsupportedOperation: Self { .init(.unsupportedOperation) } } extension SQSErrorType: Equatable { public static func == (lhs: SQSErrorType, rhs: SQSErrorType) -> Bool { lhs.error == rhs.error } } extension SQSErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
6fda3bd3078d43d15844a1cb34ba5f72
51.539216
247
0.713939
4.806278
false
false
false
false
graycampbell/GCCountryPicker
Tests/GCCountryPickerTests/GCCountryTests.swift
1
1905
// // GCCountryTests.swift // GCCountryPickerTests // // Created by Gray Campbell on 11/3/17. // import XCTest @testable import GCCountryPicker class GCCountryTests: XCTestCase { func testFailableInitializer() { let country1 = GCCountry(countryCode: "LOL") let country2 = GCCountry(countryCode: "DE") XCTAssertNil(country1) XCTAssertNotNil(country2) } func testCountryCode() { let country1 = GCCountry(countryCode: "us") let country2 = GCCountry(countryCode: "uS") let country3 = GCCountry(countryCode: "Us") let country4 = GCCountry(countryCode: "US") XCTAssertNotNil(country1) XCTAssertNotNil(country2) XCTAssertNotNil(country3) XCTAssertNotNil(country4) XCTAssert(country1?.countryCode == "US", String(describing: country1?.countryCode)) XCTAssert(country2?.countryCode == "US", String(describing: country2?.countryCode)) XCTAssert(country3?.countryCode == "US", String(describing: country3?.countryCode)) XCTAssert(country4?.countryCode == "US", String(describing: country4?.countryCode)) } func testCallingCode() { let country1 = GCCountry(countryCode: "HM") let country2 = GCCountry(countryCode: "US") XCTAssertNotNil(country1) XCTAssertNotNil(country2) XCTAssertNil(country1?.callingCode) XCTAssertNotNil(country2?.callingCode) XCTAssert(country2?.callingCode == "+1", String(describing: country2?.callingCode)) } func testPossibleCountries() { for countryCode in Locale.isoRegionCodes { let country = GCCountry(countryCode: countryCode) XCTAssertNotNil(country, "Country Code: \(countryCode)") } } }
mit
8a81ae132f261959a187a2a8746177e6
29.238095
91
0.620997
4.922481
false
true
false
false
Tantalum73/XJodel
XJodel/BlurTopView.swift
1
1596
// // BlurTopView.swift // XJodel // // Created by Andreas Neusüß on 25.03.16. // Copyright © 2016 Cocoawah. All rights reserved. // import Cocoa class BlurTopView: NSVisualEffectView { fileprivate var initialLocation : CGPoint = .zero override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. } override var mouseDownCanMoveWindow : Bool { get { return true } } override var acceptsFirstResponder : Bool { get { return true } } override func awakeFromNib() { wantsLayer = true super.awakeFromNib() } override func mouseDown(with theEvent: NSEvent) { let windowFrame = window!.frame initialLocation = NSEvent.mouseLocation() initialLocation.x -= windowFrame.origin.x initialLocation.y -= windowFrame.origin.y } override func mouseDragged(with theEvent: NSEvent) { let screenFrame = NSScreen.main()!.frame let windowFrame = window!.frame var newOrigin = CGPoint.zero let currentLocation = NSEvent.mouseLocation() newOrigin.x = currentLocation.x - initialLocation.x newOrigin.y = currentLocation.y - initialLocation.y if (newOrigin.y+windowFrame.size.height) > (screenFrame.origin.y+screenFrame.size.height) { newOrigin.y = screenFrame.origin.y + (screenFrame.size.height-windowFrame.size.height) } window!.setFrameOrigin(newOrigin) } }
mit
1969f1591f0cecbea4967847bd881dd3
25.114754
99
0.61268
4.841945
false
false
false
false
lanjing99/RxSwiftDemo
23-mvvm-with-rxswift/starter/Tweetie/iOS Tweetie/View Controllers/List People/ListPeopleViewController.swift
2
2998
/* * Copyright (c) 2016-2017 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import RxSwift import Then class ListPeopleViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var messageView: UIView! private let bag = DisposeBag() fileprivate var viewModel: ListPeopleViewModel! fileprivate var navigator: Navigator! static func createWith(navigator: Navigator, storyboard: UIStoryboard, viewModel: ListPeopleViewModel) -> ListPeopleViewController { return storyboard.instantiateViewController(ofType: ListPeopleViewController.self).then { vc in vc.navigator = navigator vc.viewModel = viewModel } } override func viewDidLoad() { super.viewDidLoad() title = "List Members" tableView.estimatedRowHeight = 90 tableView.rowHeight = UITableViewAutomaticDimension bindUI() } func bindUI() { //show tweets in table view viewModel.people.asDriver() .drive(onNext: { [weak self] _ in self?.tableView.reloadData() }) .addDisposableTo(bag) //show message when no account available } } extension ListPeopleViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.people.value?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueCell(ofType: UserCellView.self).then { cell in cell.update(with: viewModel.people.value![indexPath.row]) } } } extension ListPeopleViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let tweet = viewModel.people.value?[indexPath.row] else { return } navigator.show(segue: .personTimeline(viewModel.account, username: tweet.username), sender: self) } }
mit
afcf8b71c177a6e1d91a4a8b2c71fa09
36.949367
134
0.749833
4.736177
false
false
false
false
wangyuanou/Coastline
Coastline/Paint/AttributeString+Attribute.swift
1
9432
// // AttributeString+Attribute.swift // Coastline // // Created by 王渊鸥 on 2016/10/22. // Copyright © 2016年 王渊鸥. All rights reserved. // import Foundation public extension NSAttributedString { public convenience init(str:String, attr:CLAttributes) { self.init(string: str, attributes: attr.dict) } public func calcSize(size:CGSize) -> CGSize { let textContainer = NSTextContainer(size: size) let textStorage = NSTextStorage(attributedString: self) let layoutManager = NSLayoutManager() layoutManager.addTextContainer(textContainer) textStorage.addLayoutManager(layoutManager) let rect = layoutManager.usedRect(for: textContainer) return CGSize(width:ceil(rect.size.width ), height:ceil(rect.size.height)) } } // 文本属性 public class CLAttributes { public enum LineWidth:Int { case none = 0x00 case single = 0x01 case thick = 0x02 case double = 0x09 } public enum LineStyle:Int { case solid = 0x000 case dot = 0x0100 case dash = 0x0200 case dashDot = 0x0300 case dashDotDot = 0x0400 } public var font:UIFont? public var textColor:UIColor? public var backColor:UIColor? public var ligature:Bool? //连体符 public var kern:CGFloat? //字间距 public var strikethrough:(LineWidth, LineStyle, UIColor)? //删除线 public var underline:(LineWidth, LineStyle, UIColor)? //下划线 public var textStroke:(CGFloat, UIColor)? //文字描边 public var shadow:NSShadow? public var attachment:NSTextAttachment? //附件 public var baseline:CGFloat? //基线 public var expansion:CGFloat? //横向拉伸 public var link:URL? //外链 public var obliqueness:CGFloat? //倾斜度,+右,-左 public var vertical:Bool? //竖排文本 public var alignment:NSTextAlignment? public var firstLineHeadIndent:CGFloat? public var headIndent:CGFloat? public var tailIndent:CGFloat? public var lineBreakMode:NSLineBreakMode? public var maximumLineHeight:CGFloat? public var minimumLineHeight:CGFloat? public var lineSpacing:CGFloat? public var paragraphSpacing:CGFloat? public var paragraphSpacingBefore:CGFloat? public var baseWritingDirection:NSWritingDirection? public var lineHeightMultiple:CGFloat? public var defaultTabInterval:CGFloat? public init() { } public init(image:UIImage, size:CGSize?) { attachment = NSTextAttachment() attachment?.image = image if let size = size { attachment?.bounds = CGRect(origin: .zero, size: size) } else { let imageSize = image.size let drawSize = CGSize(width:imageSize.width/UIScreen.main.scale, height:imageSize.height/UIScreen.main.scale) attachment?.bounds = CGRect(origin: .zero, size: drawSize) } } // 将文本属性生成系统所属的字典 public var dict:[String:AnyObject] { get{ var result:[String:AnyObject] = [:] if let font = self.font { result[NSFontAttributeName] = font } if let textColor = self.textColor { result[NSForegroundColorAttributeName] = textColor } if let backColor = self.backColor { result[NSBackgroundColorAttributeName] = backColor } if let ligature = self.ligature { result[NSLigatureAttributeName] = NSNumber(value: ligature ? 1:0 as Int) } if let kern = self.kern { result[NSKernAttributeName] = NSNumber(value: Float(kern) as Float) } if let strikethrough = self.strikethrough { result[NSUnderlineColorAttributeName] = strikethrough.2 result[NSUnderlineStyleAttributeName] = NSNumber(value: strikethrough.0.rawValue + strikethrough.1.rawValue as Int) } if let underline = self.underline { result[NSUnderlineColorAttributeName] = underline.2 result[NSUnderlineStyleAttributeName] = NSNumber(value: underline.0.rawValue + underline.1.rawValue as Int) } if let textStroke = self.textStroke { result[NSStrokeWidthAttributeName] = NSNumber(value: Float(textStroke.0) as Float) result[NSStrokeColorAttributeName] = textStroke.1 } if let shadow = self.shadow { result[NSShadowAttributeName] = shadow } if let attachment = self.attachment { result[NSAttachmentAttributeName] = attachment } if let baseline = self.baseline { result[NSBaselineOffsetAttributeName] = NSNumber(value: Float(baseline) as Float) } if let expansion = self.expansion { result[NSExpansionAttributeName] = NSNumber(value: Float(expansion) as Float) } if let link = self.link { result[NSLinkAttributeName] = link as AnyObject? } if let obliqueness = self.obliqueness { result[NSObliquenessAttributeName] = obliqueness as AnyObject? } if let vertical = self.vertical { result[NSVerticalGlyphFormAttributeName] = NSNumber(value: vertical ? 1:0 as Int) } var style:NSMutableParagraphStyle? = nil if let alignment = self.alignment { if nil == style { style = NSMutableParagraphStyle() } style?.alignment = alignment } if let firstLineHeadIndent = self.firstLineHeadIndent { if nil == style { style = NSMutableParagraphStyle() } style?.firstLineHeadIndent = firstLineHeadIndent } if let headIndent = self.headIndent { if nil == style { style = NSMutableParagraphStyle() } style?.headIndent = headIndent } if let tailIndent = self.tailIndent { if nil == style { style = NSMutableParagraphStyle() } style?.tailIndent = tailIndent } if let lineBreakMode = self.lineBreakMode { if nil == style { style = NSMutableParagraphStyle() } style?.lineBreakMode = lineBreakMode } if let maximumLineHeight = self.maximumLineHeight { if nil == style { style = NSMutableParagraphStyle() } style?.maximumLineHeight = maximumLineHeight } if let minimumLineHeight = self.minimumLineHeight { if nil == style { style = NSMutableParagraphStyle() } style?.minimumLineHeight = minimumLineHeight } if let lineSpacing = self.lineSpacing { if nil == style { style = NSMutableParagraphStyle() } style?.lineSpacing = lineSpacing } if let paragraphSpacing = self.paragraphSpacing { if nil == style { style = NSMutableParagraphStyle() } style?.paragraphSpacing = paragraphSpacing } if let paragraphSpacingBefore = self.paragraphSpacingBefore { if nil == style { style = NSMutableParagraphStyle() } style?.paragraphSpacingBefore = paragraphSpacingBefore } if let baseWritingDirection = self.baseWritingDirection { if nil == style { style = NSMutableParagraphStyle() } style?.baseWritingDirection = baseWritingDirection } if let lineHeightMultiple = self.lineHeightMultiple { if nil == style { style = NSMutableParagraphStyle() } style?.lineHeightMultiple = lineHeightMultiple } if let defaultTabInterval = self.defaultTabInterval { if nil == style { style = NSMutableParagraphStyle() } style?.defaultTabInterval = defaultTabInterval } if let style = style { result[NSParagraphStyleAttributeName] = style } return result } } // 合成新的属性 func combine(_ attr:CLAttributes) -> CLAttributes { if let font = attr.font { self.font = font } if let textColor = attr.textColor { self.textColor = textColor } if let backColor = attr.backColor { self.backColor = backColor } if let ligature = attr.ligature { self.ligature = ligature } if let kern = attr.kern { self.kern = kern } if let strikethrough = attr.strikethrough { self.strikethrough = strikethrough } if let underline = attr.underline { self.underline = underline } if let textStroke = attr.textStroke { self.textStroke = textStroke } if let shadow = attr.shadow { self.shadow = shadow } if let attachment = attr.attachment { self.attachment = attachment } if let baseline = attr.baseline { self.baseline = baseline } if let expansion = attr.expansion { self.expansion = expansion } if let link = attr.link { self.link = link } if let obliqueness = attr.obliqueness { self.obliqueness = obliqueness } if let vertical = attr.vertical { self.vertical = vertical } if let alignment = attr.alignment { self.alignment = alignment } if let firstLineHeadIndent = attr.firstLineHeadIndent { self.firstLineHeadIndent = firstLineHeadIndent } if let headIndent = attr.headIndent { self.headIndent = headIndent } if let tailIndent = attr.tailIndent { self.tailIndent = tailIndent } if let lineBreakMode = attr.lineBreakMode { self.lineBreakMode = lineBreakMode } if let maximumLineHeight = attr.maximumLineHeight { self.maximumLineHeight = maximumLineHeight } if let minimumLineHeight = attr.minimumLineHeight { self.minimumLineHeight = minimumLineHeight } if let lineSpacing = attr.lineSpacing { self.lineSpacing = lineSpacing } if let paragraphSpacing = attr.paragraphSpacing { self.paragraphSpacing = paragraphSpacing } if let paragraphSpacingBefore = attr.paragraphSpacingBefore { self.paragraphSpacingBefore = paragraphSpacingBefore } if let baseWritingDirection = attr.baseWritingDirection { self.baseWritingDirection = baseWritingDirection } if let lineHeightMultiple = attr.lineHeightMultiple { self.lineHeightMultiple = lineHeightMultiple } if let defaultTabInterval = attr.defaultTabInterval { self.defaultTabInterval = defaultTabInterval } return self } static public func + (attr0:CLAttributes, attr1:CLAttributes) -> CLAttributes { return attr0.combine(attr1) } public var imageString : NSAttributedString? { if let attach = attachment { return NSAttributedString(attachment: attach) } return nil } }
mit
de7d92de6cab26dc091aec7f8cec451d
40.699552
120
0.736423
4.155049
false
false
false
false
roambotics/swift
test/Interop/C/struct/foreign-reference.swift
1
1046
// RUN: %target-run-simple-swift(-I %S/Inputs/ -Xfrontend -validate-tbd-against-ir=none) // // REQUIRES: executable_test // TODO: This should work without ObjC interop in the future rdar://97497120 // REQUIRES: objc_interop import StdlibUnittest import ForeignReference var ReferenceCountedTestSuite = TestSuite("Foreign reference types that have reference counts") @inline(never) public func blackHole<T>(_ _: T) { } ReferenceCountedTestSuite.test("Local") { var x = createLocalCount() expectEqual(x.value, 6) // This is 6 because of "var x" "x.value" * 2 and "(x, x, x)". let t = (x, x, x) expectEqual(x.value, 5) } @inline(never) func globalTest1() { var x = createGlobalCount() let t = (x, x, x) expectEqual(globalCount, 4) blackHole(t) } @inline(never) func globalTest2() { var x = createGlobalCount() expectEqual(globalCount, 1) } ReferenceCountedTestSuite.test("Global") { expectEqual(globalCount, 0) globalTest1() globalTest2() expectEqual(globalCount, 0) } runAllTests()
apache-2.0
bba4a3a5060240e100237905ea7d549f
22.772727
95
0.688337
3.352564
false
true
false
false
nathawes/swift
test/AutoDiff/SILGen/vtable.swift
7
9864
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s // Test derivative function vtable entries for `@differentiable` class members: // - Methods. // - Accessors (from properties and subscripts). // - Initializers. import _Differentiation // Dummy `Differentiable`-conforming type. struct DummyTangentVector: Differentiable & AdditiveArithmetic { // FIXME(TF-648): Dummy to make `Super.TangentVector` be nontrivial. var _nontrivial: [Float] = [] static var zero: Self { Self() } static func + (_: Self, _: Self) -> Self { Self() } static func - (_: Self, _: Self) -> Self { Self() } typealias TangentVector = Self } class Super: Differentiable { typealias TangentVector = DummyTangentVector func move(along _: TangentVector) {} var base: Float // FIXME(TF-648): Dummy to make `Super.TangentVector` be nontrivial. var _nontrivial: [Float] = [] init(base: Float) { self.base = base } @differentiable(wrt: x) func method(_ x: Float, _ y: Float) -> Float { return x } @differentiable(wrt: x where T: Differentiable) func genericMethod<T>(_ x: T, _ y: T) -> T { return x } @differentiable var property: Float { base } @differentiable(wrt: x) subscript(_ x: Float, _ y: Float) -> Float { return x } } class Sub: Super { override init(base: Float) { super.init(base: base) } // Override JVP for `method` wrt `x`. @derivative(of: method, wrt: x) @derivative(of: subscript, wrt: x) final func jvpMethod(_ x: Float, _ y: Float) -> (value: Float, differential: (Float) -> Float) { fatalError() } // Override VJP for `method` wrt `x`. @derivative(of: method, wrt: x) @derivative(of: subscript, wrt: x) final func vjpMethod(_ x: Float, _ y: Float) -> (value: Float, pullback: (Float) -> (Float)) { fatalError() } // Override derivatives for `method` wrt `x`. // FIXME(TF-1203): This `@differentiable` attribute should not be necessary to // override derivatives. Fix `derivativeFunctionRequiresNewVTableEntry` to // account for derived declaration `@derivative` attributes. @differentiable(wrt: x) // Add new derivatives for `method` wrt `(x, y)`. @differentiable(wrt: (x, y)) override func method(_ x: Float, _ y: Float) -> Float { return x } // Override derivatives for `property` wrt `self`. @differentiable override var property: Float { base } @derivative(of: property) final func vjpProperty() -> (value: Float, pullback: (Float) -> TangentVector) { fatalError() } // Override derivatives for `subscript` wrt `x`. @differentiable(wrt: x) override subscript(_ x: Float, _ y: Float) -> Float { return x } } class SubSub: Sub {} // Check vtable entry thunks. // CHECK-LABEL: sil hidden [transparent] [thunk] [ossa] @AD__${{.*}}5SuperC6methody{{.*}}jvp_src_0_wrt_0_vtable_entry_thunk : $@convention(method) (Float, Float, @guaranteed Super) -> (Float, @owned @callee_guaranteed (Float) -> Float) { // CHECK: bb0(%0 : $Float, %1 : $Float, %2 : @guaranteed $Super): // CHECK: %3 = function_ref @$s6vtable5SuperC6methodyS2f_SftF : $@convention(method) (Float, Float, @guaranteed Super) -> Float // CHECK: %4 = differentiable_function [parameters 0] [results 0] %3 : $@convention(method) (Float, Float, @guaranteed Super) -> Float // CHECK: %5 = differentiable_function_extract [jvp] %4 : $@differentiable @convention(method) (Float, @noDerivative Float, @noDerivative @guaranteed Super) -> Float // CHECK: %6 = apply %5(%0, %1, %2) : $@convention(method) (Float, Float, @guaranteed Super) -> (Float, @owned @callee_guaranteed (Float) -> Float) // CHECK: return %6 : $(Float, @callee_guaranteed (Float) -> Float) // CHECK: } // Check vtable entries: new vs `[override]` vs `[inherited]` entries. // CHECK-LABEL: sil_vtable Super { // CHECK: #Super.method: (Super) -> (Float, Float) -> Float : @$s6vtable5SuperC6methodyS2f_SftF // CHECK: #Super.method!jvp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable5SuperC6methodyS2f_SftF__jvp_src_0_wrt_0_vtable_entry_thunk // CHECK: #Super.method!vjp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable5SuperC6methodyS2f_SftF__vjp_src_0_wrt_0_vtable_entry_thunk // CHECK: #Super.genericMethod: <T> (Super) -> (T, T) -> T : @$s6vtable5SuperC13genericMethodyxx_xtlF // CHECK: #Super.genericMethod!jvp.SUU.<T where T : Differentiable>: <T> (Super) -> (T, T) -> T : @AD__$s6vtable5SuperC13genericMethodyxx_xtlF__jvp_src_0_wrt_0_16_Differentiation14DifferentiableRzl_vtable_entry_thunk // CHECK: #Super.genericMethod!vjp.SUU.<T where T : Differentiable>: <T> (Super) -> (T, T) -> T : @AD__$s6vtable5SuperC13genericMethodyxx_xtlF__vjp_src_0_wrt_0_16_Differentiation14DifferentiableRzl_vtable_entry_thunk // CHECK: #Super.property!getter: (Super) -> () -> Float : @$s6vtable5SuperC8propertySfvg // CHECK: #Super.property!getter.jvp.S: (Super) -> () -> Float : @AD__$s6vtable5SuperC8propertySfvg__jvp_src_0_wrt_0_vtable_entry_thunk // CHECK: #Super.property!getter.vjp.S: (Super) -> () -> Float : @AD__$s6vtable5SuperC8propertySfvg__vjp_src_0_wrt_0_vtable_entry_thunk // CHECK: #Super.subscript!getter: (Super) -> (Float, Float) -> Float : @$s6vtable5SuperCyS2f_Sftcig // CHECK: #Super.subscript!getter.jvp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable5SuperCyS2f_Sftcig__jvp_src_0_wrt_0_vtable_entry_thunk // CHECK: #Super.subscript!getter.vjp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable5SuperCyS2f_Sftcig__vjp_src_0_wrt_0_vtable_entry_thunk // CHECK: } // CHECK-LABEL: sil_vtable Sub { // CHECK: #Super.method: (Super) -> (Float, Float) -> Float : @$s6vtable3SubC6methodyS2f_SftF [override] // CHECK: #Super.method!jvp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable3SubC6methodyS2f_SftF__jvp_src_0_wrt_0_vtable_entry_thunk [override] // CHECK: #Super.method!vjp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable3SubC6methodyS2f_SftF__vjp_src_0_wrt_0_vtable_entry_thunk [override] // CHECK: #Super.genericMethod: <T> (Super) -> (T, T) -> T : @$s6vtable5SuperC13genericMethodyxx_xtlF [inherited] // CHECK: #Super.genericMethod!jvp.SUU.<T where T : Differentiable>: <T> (Super) -> (T, T) -> T : @AD__$s6vtable5SuperC13genericMethodyxx_xtlF__jvp_src_0_wrt_0_16_Differentiation14DifferentiableRzl_vtable_entry_thunk [inherited] // CHECK: #Super.genericMethod!vjp.SUU.<T where T : Differentiable>: <T> (Super) -> (T, T) -> T : @AD__$s6vtable5SuperC13genericMethodyxx_xtlF__vjp_src_0_wrt_0_16_Differentiation14DifferentiableRzl_vtable_entry_thunk [inherited] // CHECK: #Super.property!getter: (Super) -> () -> Float : @$s6vtable3SubC8propertySfvg [override] // CHECK: #Super.property!getter.jvp.S: (Super) -> () -> Float : @AD__$s6vtable3SubC8propertySfvg__jvp_src_0_wrt_0_vtable_entry_thunk [override] // CHECK: #Super.property!getter.vjp.S: (Super) -> () -> Float : @AD__$s6vtable3SubC8propertySfvg__vjp_src_0_wrt_0_vtable_entry_thunk [override] // CHECK: #Super.subscript!getter: (Super) -> (Float, Float) -> Float : @$s6vtable3SubCyS2f_Sftcig [override] // CHECK: #Super.subscript!getter.jvp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable3SubCyS2f_Sftcig__jvp_src_0_wrt_0_vtable_entry_thunk [override] // CHECK: #Super.subscript!getter.vjp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable3SubCyS2f_Sftcig__vjp_src_0_wrt_0_vtable_entry_thunk [override] // CHECK: #Sub.method!jvp.SSU: (Sub) -> (Float, Float) -> Float : @AD__$s6vtable3SubC6methodyS2f_SftF__jvp_src_0_wrt_0_1_vtable_entry_thunk // CHECK: #Sub.method!vjp.SSU: (Sub) -> (Float, Float) -> Float : @AD__$s6vtable3SubC6methodyS2f_SftF__vjp_src_0_wrt_0_1_vtable_entry_thunk // CHECK: } // CHECK-LABEL: sil_vtable SubSub { // CHECK: #Super.method: (Super) -> (Float, Float) -> Float : @$s6vtable3SubC6methodyS2f_SftF [inherited] // CHECK: #Super.method!jvp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable3SubC6methodyS2f_SftF__jvp_src_0_wrt_0_vtable_entry_thunk [inherited] // CHECK: #Super.method!vjp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable3SubC6methodyS2f_SftF__vjp_src_0_wrt_0_vtable_entry_thunk [inherited] // CHECK: #Super.genericMethod: <T> (Super) -> (T, T) -> T : @$s6vtable5SuperC13genericMethodyxx_xtlF [inherited] // CHECK: #Super.genericMethod!jvp.SUU.<T where T : Differentiable>: <T> (Super) -> (T, T) -> T : @AD__$s6vtable5SuperC13genericMethodyxx_xtlF__jvp_src_0_wrt_0_16_Differentiation14DifferentiableRzl_vtable_entry_thunk [inherited] // CHECK: #Super.genericMethod!vjp.SUU.<T where T : Differentiable>: <T> (Super) -> (T, T) -> T : @AD__$s6vtable5SuperC13genericMethodyxx_xtlF__vjp_src_0_wrt_0_16_Differentiation14DifferentiableRzl_vtable_entry_thunk [inherited] // CHECK: #Super.property!getter: (Super) -> () -> Float : @$s6vtable3SubC8propertySfvg [inherited] // CHECK: #Super.property!getter.jvp.S: (Super) -> () -> Float : @AD__$s6vtable3SubC8propertySfvg__jvp_src_0_wrt_0_vtable_entry_thunk [inherited] // CHECK: #Super.property!getter.vjp.S: (Super) -> () -> Float : @AD__$s6vtable3SubC8propertySfvg__vjp_src_0_wrt_0_vtable_entry_thunk [inherited] // CHECK: #Super.subscript!getter: (Super) -> (Float, Float) -> Float : @$s6vtable3SubCyS2f_Sftcig [inherited] // CHECK: #Super.subscript!getter.jvp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable3SubCyS2f_Sftcig__jvp_src_0_wrt_0_vtable_entry_thunk [inherited] // CHECK: #Super.subscript!getter.vjp.SUU: (Super) -> (Float, Float) -> Float : @AD__$s6vtable3SubCyS2f_Sftcig__vjp_src_0_wrt_0_vtable_entry_thunk [inherited] // CHECK: #Sub.method!jvp.SSU: (Sub) -> (Float, Float) -> Float : @AD__$s6vtable3SubC6methodyS2f_SftF__jvp_src_0_wrt_0_1_vtable_entry_thunk [inherited] // CHECK: #Sub.method!vjp.SSU: (Sub) -> (Float, Float) -> Float : @AD__$s6vtable3SubC6methodyS2f_SftF__vjp_src_0_wrt_0_1_vtable_entry_thunk [inherited] // CHECK: }
apache-2.0
61c5df1c2241bbbc03c2442c4001e5cc
61.43038
237
0.680251
2.940089
false
false
false
false
xuzhuoxi/SearchKit
Source/ExSwift/Float.swift
2
1626
// // Float.swift // ExSwift // // Created by pNre on 04/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation public extension Float { /** Absolute value. - returns: fabs(self) */ func abs () -> Float { return fabsf(self) } /** Squared root. - returns: sqrtf(self) */ func sqrt () -> Float { return sqrtf(self) } /** Rounds self to the largest integer <= self. - returns: floorf(self) */ func floor () -> Float { return floorf(self) } /** Rounds self to the smallest integer >= self. - returns: ceilf(self) */ func ceil () -> Float { return ceilf(self) } /** Rounds self to the nearest integer. - returns: roundf(self) */ func round () -> Float { return roundf(self) } /** Clamps self to a specified range. - parameter min: Lower bound - parameter max: Upper bound - returns: Clamped value */ func clamp (_ min: Float, _ max: Float) -> Float { return Swift.max(min, Swift.min(max, self)) } /** Random float between min and max (inclusive). - parameter min: - parameter max: - returns: Random number */ static func random(_ min: Float = 0, max: Float) -> Float { let diff = max - min; let rand = Float(arc4random() % (UInt32(RAND_MAX) + 1)) return ((rand / Float(RAND_MAX)) * diff) + min; } }
mit
3e1846a97cb1ab133be6455551d87a6f
18.590361
63
0.492005
4.085427
false
false
false
false
inspace-io/INSPhotoGallery
INSPhotoGallery/INSPhotosInteractionAnimator.swift
1
6991
// // INSInteractionAnimator.swift // INSPhotoViewer // // Created by Michal Zaborowski on 28.02.2016. // Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this library 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 public class INSPhotosInteractionAnimator: NSObject, UIViewControllerInteractiveTransitioning { var animator: UIViewControllerAnimatedTransitioning? var viewToHideWhenBeginningTransition: UIView? var shouldAnimateUsingAnimator: Bool = false private var transitionContext: UIViewControllerContextTransitioning? public func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { viewToHideWhenBeginningTransition?.alpha = 0.0 self.transitionContext = transitionContext } func handlePanWithPanGestureRecognizer(_ gestureRecognizer: UIPanGestureRecognizer, viewToPan: UIView, anchorPoint: CGPoint) { guard let fromView = transitionContext?.view(forKey: UITransitionContextViewKey.from) else { return } let translatedPanGesturePoint = gestureRecognizer.translation(in: fromView) let newCenterPoint = CGPoint(x: anchorPoint.x + translatedPanGesturePoint.x, y: anchorPoint.y + translatedPanGesturePoint.y) viewToPan.center = newCenterPoint let verticalDelta = newCenterPoint.y - anchorPoint.y let backgroundAlpha = backgroundAlphaForPanningWithVerticalDelta(verticalDelta) fromView.backgroundColor = fromView.backgroundColor?.withAlphaComponent(backgroundAlpha) if gestureRecognizer.state == .ended { finishPanWithPanGestureRecognizer(gestureRecognizer, verticalDelta: verticalDelta,viewToPan: viewToPan, anchorPoint: anchorPoint) } } func finishPanWithPanGestureRecognizer(_ gestureRecognizer: UIPanGestureRecognizer, verticalDelta: CGFloat, viewToPan: UIView, anchorPoint: CGPoint) { guard let fromView = transitionContext?.view(forKey: UITransitionContextViewKey.from) else { return } let returnToCenterVelocityAnimationRatio = 0.00007 let panDismissDistanceRatio = 50.0 / 667.0 // distance over iPhone 6 height let panDismissMaximumDuration = 0.45 let velocityY = gestureRecognizer.velocity(in: gestureRecognizer.view).y var animationDuration = (Double(abs(velocityY)) * returnToCenterVelocityAnimationRatio) + 0.2 var animationCurve: UIView.AnimationOptions = .curveEaseOut var finalPageViewCenterPoint = anchorPoint var finalBackgroundAlpha = 1.0 let dismissDistance = panDismissDistanceRatio * Double(fromView.bounds.height) let isDismissing = Double(abs(verticalDelta)) > dismissDistance var didAnimateUsingAnimator = false if isDismissing { if let animator = self.animator, let transitionContext = transitionContext , shouldAnimateUsingAnimator { animator.animateTransition(using: transitionContext) didAnimateUsingAnimator = true } else { let isPositiveDelta = verticalDelta >= 0 let modifier: CGFloat = isPositiveDelta ? 1 : -1 let finalCenterY = fromView.bounds.midY + modifier * fromView.bounds.height finalPageViewCenterPoint = CGPoint(x: fromView.center.x, y: finalCenterY) animationDuration = Double(abs(finalPageViewCenterPoint.y - viewToPan.center.y) / abs(velocityY)) animationDuration = min(animationDuration, panDismissMaximumDuration) animationCurve = .curveEaseOut finalBackgroundAlpha = 0.0 } } if didAnimateUsingAnimator { self.transitionContext = nil } else { UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in viewToPan.center = finalPageViewCenterPoint fromView.backgroundColor = fromView.backgroundColor?.withAlphaComponent(CGFloat(finalBackgroundAlpha)) }, completion: { finished in if isDismissing { self.transitionContext?.finishInteractiveTransition() } else { self.transitionContext?.cancelInteractiveTransition() if !self.isRadar20070670Fixed() { self.fixCancellationStatusBarAppearanceBug() } } self.viewToHideWhenBeginningTransition?.alpha = 1.0 self.transitionContext?.completeTransition(isDismissing && !(self.transitionContext?.transitionWasCancelled ?? false)) self.transitionContext = nil }) } } private func fixCancellationStatusBarAppearanceBug() { guard let toViewController = self.transitionContext?.viewController(forKey: UITransitionContextViewControllerKey.to), let fromViewController = self.transitionContext?.viewController(forKey: UITransitionContextViewControllerKey.from) else { return } let statusBarViewControllerSelector = Selector("_setPresentedSta" + "tusBarViewController:") if toViewController.responds(to: statusBarViewControllerSelector) && fromViewController.modalPresentationCapturesStatusBarAppearance { toViewController.perform(statusBarViewControllerSelector, with: fromViewController) } } private func isRadar20070670Fixed() -> Bool { return ProcessInfo.processInfo.isOperatingSystemAtLeast(OperatingSystemVersion.init(majorVersion: 8, minorVersion: 3, patchVersion: 0)) } private func backgroundAlphaForPanningWithVerticalDelta(_ delta: CGFloat) -> CGFloat { guard let fromView = transitionContext?.view(forKey: UITransitionContextViewKey.from) else { return 0.0 } let startingAlpha: CGFloat = 1.0 let finalAlpha: CGFloat = 0.1 let totalAvailableAlpha = startingAlpha - finalAlpha let maximumDelta = CGFloat(fromView.bounds.height / 2.0) let deltaAsPercentageOfMaximum = min(abs(delta) / maximumDelta, 1.0) return startingAlpha - (deltaAsPercentageOfMaximum * totalAvailableAlpha) } }
apache-2.0
16a738938232654789b8a8b0c0b8d28f
48.211268
154
0.684459
5.6583
false
false
false
false
edragoev1/pdfjet
Sources/PDFjet/Courier_Bold.swift
1
4664
class Courier_Bold { static let name = "Courier-Bold" static let bBoxLLx: Int16 = -113 static let bBoxLLy: Int16 = -250 static let bBoxURx: Int16 = 749 static let bBoxURy: Int16 = 801 static let underlinePosition: Int16 = -100 static let underlineThickness: Int16 = 50 static let notice = "Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved." static let metrics = Array<[Int16]>(arrayLiteral: [32,600], [33,600], [34,600], [35,600], [36,600], [37,600], [38,600], [39,600], [40,600], [41,600], [42,600], [43,600], [44,600], [45,600], [46,600], [47,600], [48,600], [49,600], [50,600], [51,600], [52,600], [53,600], [54,600], [55,600], [56,600], [57,600], [58,600], [59,600], [60,600], [61,600], [62,600], [63,600], [64,600], [65,600], [66,600], [67,600], [68,600], [69,600], [70,600], [71,600], [72,600], [73,600], [74,600], [75,600], [76,600], [77,600], [78,600], [79,600], [80,600], [81,600], [82,600], [83,600], [84,600], [85,600], [86,600], [87,600], [88,600], [89,600], [90,600], [91,600], [92,600], [93,600], [94,600], [95,600], [96,600], [97,600], [98,600], [99,600], [100,600], [101,600], [102,600], [103,600], [104,600], [105,600], [106,600], [107,600], [108,600], [109,600], [110,600], [111,600], [112,600], [113,600], [114,600], [115,600], [116,600], [117,600], [118,600], [119,600], [120,600], [121,600], [122,600], [123,600], [124,600], [125,600], [126,600], [127,600], [128,600], [129,600], [130,600], [131,600], [132,600], [133,600], [134,600], [135,600], [136,600], [137,600], [138,600], [139,600], [140,600], [141,600], [142,600], [143,600], [144,600], [145,600], [146,600], [147,600], [148,600], [149,600], [150,600], [151,600], [152,600], [153,600], [154,600], [155,600], [156,600], [157,600], [158,600], [159,600], [160,600], [161,600], [162,600], [163,600], [164,600], [165,600], [166,600], [167,600], [168,600], [169,600], [170,600], [171,600], [172,600], [173,600], [174,600], [175,600], [176,600], [177,600], [178,600], [179,600], [180,600], [181,600], [182,600], [183,600], [184,600], [185,600], [186,600], [187,600], [188,600], [189,600], [190,600], [191,600], [192,600], [193,600], [194,600], [195,600], [196,600], [197,600], [198,600], [199,600], [200,600], [201,600], [202,600], [203,600], [204,600], [205,600], [206,600], [207,600], [208,600], [209,600], [210,600], [211,600], [212,600], [213,600], [214,600], [215,600], [216,600], [217,600], [218,600], [219,600], [220,600], [221,600], [222,600], [223,600], [224,600], [225,600], [226,600], [227,600], [228,600], [229,600], [230,600], [231,600], [232,600], [233,600], [234,600], [235,600], [236,600], [237,600], [238,600], [239,600], [240,600], [241,600], [242,600], [243,600], [244,600], [245,600], [246,600], [247,600], [248,600], [249,600], [250,600], [251,600], [252,600], [253,600], [254,600], [255,600] ) }
mit
da32d15249c009bb29a8e30b76348480
18.762712
117
0.343911
3.162034
false
false
false
false
LeeMZC/MZCWB
MZCWB/MZCWB/Classes/Home-首页/Controller/MZCHomeTableViewController.swift
1
11719
// // MZCHomeTableViewController.swift // MZCWB // // Created by 马纵驰 on 16/7/20. // Copyright © 2016年 马纵驰. All rights reserved. // import UIKit import QorumLogs import SwiftyJSON import YYKit import MJRefresh private let Identifier = "HomeCell" public enum MZCRequestDataState : Int { /// 普通状态 case normal /// 请求新数据状态 case newData /// 请求老数据状态 case oldData } class MZCHomeTableViewController: UITableViewController { //MARK:- 属性 var requestDataState = MZCRequestDataState.normal var homeDataArr : [MZCHomeViewMode] = [] { didSet{ dispatch_async(dispatch_get_main_queue(), { [weak self] () in guard let weakSelf = self else {return } let oldCount = oldValue.count ?? 0 let newIdCount = weakSelf.homeDataArr.count ?? 0 weakSelf.noMoreDataTipsView.ani(newIdCount - oldCount) weakSelf.endRefreshing() weakSelf.tableView.reloadData() }) } } //MARK:- viewDidLoad override func viewDidLoad() { super.viewDidLoad() QL1("") setupUI() } //MARK: did deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } //MARK:- didReceiveMemoryWarning override func didReceiveMemoryWarning() { homeDataArr.removeAll() } //MARK:- setup func setupUI(){ setupNotification() registerCell() setupNavUI() setupTabViewUI() setupLoadData() } private func setupNotification(){ NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MZCHomeTableViewController.pictureWillShow(notice:)), name: MZCPictureWillShow, object: nil) } private func setupLoadData(){ self.tableView.mj_header = MZCRefreshStateHeader {[weak self] () in guard let weakSelf = self else {return } if weakSelf.requestDataState != MZCRequestDataState.normal {return } weakSelf.loadNewData() } self.tableView.mj_header.beginRefreshing() self.tableView.mj_footer = MZCRefreshAutoFooter(refreshingBlock: {[weak self] () in guard let weakSelf = self else {return } if weakSelf.requestDataState != MZCRequestDataState.normal {return } weakSelf.loadOldData() }) } private func setupTabViewUI(){ let view = UIView() view.bounds = tableView.bounds view.backgroundColor = UIColor.grayColor() tableView.backgroundView = view tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.backgroundColor = UIColor.clearColor() } //MARK:- private 注册cell private func registerCell(){ let cellNib = UINib(nibName: "MZCHomeTableViewCell", bundle: nil) tableView.registerNib(cellNib, forCellReuseIdentifier: Identifier) } //MARK:- 加载更多数据 private var since_id : String { return homeDataArr.first?.modeSource?.idstr ?? "0" } private var max_id : String { let t_idstr = homeDataArr.last?.modeSource?.idstr ?? "0" var idstr = "" if t_idstr != "0" { idstr = "\(Int(t_idstr)! - 1)" }else{ idstr = "0" } return idstr } private func loadNewData(){ requestDataState = MZCRequestDataState.newData let access_token = accountTokenMode!.access_token! let parameters = ["access_token": access_token, "since_id" : since_id] loadData(parameters: parameters) } private func loadOldData(){ requestDataState = MZCRequestDataState.oldData let access_token = accountTokenMode!.access_token! let parameters = ["access_token": access_token, "max_id" : max_id] loadData(parameters: parameters) } private func loadData(parameters aParameters : [String : String]){ MZCAlamofire.shareInstance.homeLoadData(parameters: aParameters) {[weak self] (datas, error) in guard let weakSelf = self else {return } if error != nil { weakSelf.endRefreshing() return } guard let t_datas = datas else { weakSelf.endRefreshing() return } var t_homeModeArr = [MZCHomeViewMode]() for dict in t_datas { let homeMode = MZCHomeMode(dict: dict) t_homeModeArr.append(MZCHomeViewMode(mode: homeMode)) } weakSelf.cachesImages(t_homeModeArr) } } //MARK:- 结束刷新 private func endRefreshing(){ switch self.requestDataState { case .newData: tableView.mj_header.endRefreshing() case .oldData: tableView.mj_footer.endRefreshing() default: break } requestDataState = MZCRequestDataState.normal } //MARK:- 缓存贴图img private func cachesImages(modes : [MZCHomeViewMode]) { let group = dispatch_group_create() for mode in modes { guard let urls = mode.pic_urls_ViewMode where urls.count > 0 else { continue } for url in urls { dispatch_group_enter(group) YYWebImageManager.sharedManager().requestImageWithURL(url, options: YYWebImageOptions.RefreshImageCache, progress: { (currentCount : Int, toteCount : Int) in }, transform: { (img : UIImage, url:NSURL) -> UIImage? in return img }) { (img:UIImage?, url:NSURL, type:YYWebImageFromType, stage:YYWebImageStage,error: NSError?) in //导致显示延迟问题 // dispatch_group_leave(group) } //解决显示延迟问题 dispatch_group_leave(group) } } dispatch_group_notify(group, dispatch_get_main_queue()) { switch self.requestDataState { case .newData: self.homeDataArr = modes + self.homeDataArr case .oldData: self.homeDataArr = self.homeDataArr + modes default: break } } } //MARK:- 弹出加载完成提示 private lazy var noMoreDataTipsView : MZCNoMoreDataTipsView = { let navBarView = self.navigationController?.navigationBar let frame = navBarView?.bounds let view = MZCNoMoreDataTipsView(frame: frame!) navBarView?.insertSubview(view, atIndex: 0) return view }() //MARK:- 设置navigationUI private func setupNavUI(){ QL1("") navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendattention", target: self, action: #selector(MZCHomeTableViewController.leftDidOnClick)); navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", target: self, action: #selector(MZCHomeTableViewController.rightDidOnClick)); let titleView = MZCHomeTitleButton() navigationItem.titleView = titleView titleView.addTarget(self, action: #selector(MZCHomeTableViewController.titleDidOnClick(titleBtn:)), forControlEvents: UIControlEvents.TouchUpInside) } //MARK:- 用户信息动画代理对象 private lazy var userInfoPopManager : MZCHomeUserInfoPresentationController = { //1. 创建转场对象 let popManager = MZCHomeUserInfoPresentationController() popManager.dataSource = self return popManager }() //MARK:- 点击微博图片转场动画 private lazy var imageBrowserPopManager : MZCHomePopImageBrowserPresentationController = { //1. 创建转场对象 let popManager = MZCHomePopImageBrowserPresentationController() return popManager }() } // MARK:- delegate extension MZCHomeTableViewController : MZCHomeUserInfoDataSource{ override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return homeDataArr.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> MZCHomeTableViewCell { let homeCell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as! MZCHomeTableViewCell let homeViewMode = homeDataArr[indexPath.row] homeCell.mode = homeViewMode // homeCell.backgroundColor = MZCRandomColor return homeCell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let homeViewMode = homeDataArr[indexPath.row] return homeViewMode.height } func userInfoPresentationControllerRect() -> CGRect { let mainScreenframe = UIScreen.mainScreen().bounds let width = mainScreenframe.size.width / 2 let height = mainScreenframe.size.height / 3 let x = (mainScreenframe.size.width - width) / 2 return CGRectMake(x, 64,width , height) } } // MARK:- 事件 extension MZCHomeTableViewController{ @objc private func leftDidOnClick(){ } @objc private func rightDidOnClick(){ QL1("") let scanViewController = UINavigationController(rootViewController: MZCScanViewController()) presentViewController(scanViewController, animated: true, completion: nil) } @objc private func titleDidOnClick(titleBtn aDeTitleBtn : MZCHomeTitleButton){ QL1("") //1. 创建视图 let presentationView = MZCHomePopViewController() //2. 设置视图转场代理 presentationView.transitioningDelegate = userInfoPopManager //3. 设置视图转场样式 presentationView.modalPresentationStyle = UIModalPresentationStyle.Custom //4. modal窗口 presentViewController(presentationView, animated: true, completion: nil) } @objc private func pictureWillShow(notice aNotice: NSNotification){ QL1("") guard let urls = aNotice.userInfo!["bmiddle_pic"] where (urls as! [NSURL]).count > 0 else { return } guard let indexPath = aNotice.userInfo!["indexPath"] else { return } imageBrowserPopManager.dataSource = aNotice.object as! MZCHomeChartletCollectionView let viewController = MZCHomeImageBrowserViewController(bmiddle_pic: urls as! [NSURL], indexPath: indexPath as! NSIndexPath) viewController.transitioningDelegate = imageBrowserPopManager //3. 设置视图转场样式 viewController.modalPresentationStyle = UIModalPresentationStyle.Custom /** * 弹出图片浏览器 */ dispatch_async(dispatch_get_main_queue()) { self.presentViewController(viewController, animated: true, completion: nil) } } }
artistic-2.0
eb7813ad0c916e7528ab040ed8d1b1a7
30.512397
177
0.594072
5.208561
false
false
false
false
crazypoo/PTools
Pods/SwifterSwift/Sources/SwifterSwift/UIKit/UITableViewExtensions.swift
1
7868
// // UITableViewExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/22/16. // Copyright © 2016 SwifterSwift // #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Properties public extension UITableView { /// SwifterSwift: Index path of last row in tableView. var indexPathForLastRow: IndexPath? { guard let lastSection = lastSection else { return nil } return indexPathForLastRow(inSection: lastSection) } /// SwifterSwift: Index of last section in tableView. var lastSection: Int? { return numberOfSections > 0 ? numberOfSections - 1 : nil } } // MARK: - Methods public extension UITableView { /// SwifterSwift: Number of all rows in all sections of tableView. /// /// - Returns: The count of all rows in the tableView. func numberOfRows() -> Int { var section = 0 var rowCount = 0 while section < numberOfSections { rowCount += numberOfRows(inSection: section) section += 1 } return rowCount } /// SwifterSwift: IndexPath for last row in section. /// /// - Parameter section: section to get last row in. /// - Returns: optional last indexPath for last row in section (if applicable). func indexPathForLastRow(inSection section: Int) -> IndexPath? { guard numberOfSections > 0, section >= 0 else { return nil } guard numberOfRows(inSection: section) > 0 else { return IndexPath(row: 0, section: section) } return IndexPath(row: numberOfRows(inSection: section) - 1, section: section) } /// SwifterSwift: Reload data with a completion handler. /// /// - Parameter completion: completion handler to run after reloadData finishes. func reloadData(_ completion: @escaping () -> Void) { UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() }) } /// SwifterSwift: Remove TableFooterView. func removeTableFooterView() { tableFooterView = nil } /// SwifterSwift: Remove TableHeaderView. func removeTableHeaderView() { tableHeaderView = nil } /// SwifterSwift: Scroll to bottom of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). func scrollToBottom(animated: Bool = true) { let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height) setContentOffset(bottomOffset, animated: animated) } /// SwifterSwift: Scroll to top of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). func scrollToTop(animated: Bool = true) { setContentOffset(CGPoint.zero, animated: animated) } /// SwifterSwift: Dequeue reusable UITableViewCell using class name /// /// - Parameter name: UITableViewCell type /// - Returns: UITableViewCell object with associated class name. func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: name)) as? T else { fatalError("Couldn't find UITableViewCell for \(String(describing: name)), make sure the cell is registered with table view") } return cell } /// SwifterSwift: Dequeue reusable UITableViewCell using class name for indexPath /// /// - Parameters: /// - name: UITableViewCell type. /// - indexPath: location of cell in tableView. /// - Returns: UITableViewCell object with associated class name. func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: name), for: indexPath) as? T else { fatalError("Couldn't find UITableViewCell for \(String(describing: name)), make sure the cell is registered with table view") } return cell } /// SwifterSwift: Dequeue reusable UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type /// - Returns: UITableViewHeaderFooterView object with associated class name. func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withClass name: T.Type) -> T { guard let headerFooterView = dequeueReusableHeaderFooterView(withIdentifier: String(describing: name)) as? T else { fatalError("Couldn't find UITableViewHeaderFooterView for \(String(describing: name)), make sure the view is registered with table view") } return headerFooterView } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameters: /// - nib: Nib file used to create the header or footer view. /// - name: UITableViewHeaderFooterView type. func register<T: UITableViewHeaderFooterView>(nib: UINib?, withHeaderFooterViewClass name: T.Type) { register(nib, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type func register<T: UITableViewHeaderFooterView>(headerFooterViewClassWith name: T.Type) { register(T.self, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameter name: UITableViewCell type func register<T: UITableViewCell>(cellWithClass name: T.Type) { register(T.self, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameters: /// - nib: Nib file used to create the tableView cell. /// - name: UITableViewCell type. func register<T: UITableViewCell>(nib: UINib?, withCellClass name: T.Type) { register(nib, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell with .xib file using only its corresponding class. /// Assumes that the .xib filename and cell class has the same name. /// /// - Parameters: /// - name: UITableViewCell type. /// - bundleClass: Class in which the Bundle instance will be based on. func register<T: UITableViewCell>(nibWithCellClass name: T.Type, at bundleClass: AnyClass? = nil) { let identifier = String(describing: name) var bundle: Bundle? if let bundleName = bundleClass { bundle = Bundle(for: bundleName) } register(UINib(nibName: identifier, bundle: bundle), forCellReuseIdentifier: identifier) } /// SwifterSwift: Check whether IndexPath is valid within the tableView /// /// - Parameter indexPath: An IndexPath to check /// - Returns: Boolean value for valid or invalid IndexPath func isValidIndexPath(_ indexPath: IndexPath) -> Bool { return indexPath.section >= 0 && indexPath.row >= 0 && indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section) } /// SwifterSwift: Safely scroll to possibly invalid IndexPath /// /// - Parameters: /// - indexPath: Target IndexPath to scroll to /// - scrollPosition: Scroll position /// - animated: Whether to animate or not func safeScrollToRow(at indexPath: IndexPath, at scrollPosition: UITableView.ScrollPosition, animated: Bool) { guard indexPath.section < numberOfSections else { return } guard indexPath.row < numberOfRows(inSection: indexPath.section) else { return } scrollToRow(at: indexPath, at: scrollPosition, animated: animated) } } #endif
mit
54896ce7bd909037eb3f566dd2e4ea14
38.139303
149
0.667345
5.138472
false
false
false
false
kingslay/KSSwiftExtension
CityPicker/Extendsion/CFCityPickerVC+TableView.swift
1
14660
// // CFCityPickerVC+TableView.swift // CFCityPickerVC // // Created by 冯成林 on 15/7/30. // Copyright (c) 2015年 冯成林. All rights reserved. // import Foundation import UIKit extension CFCityPickerVC: UITableViewDataSource,UITableViewDelegate{ var searchH: CGFloat{return 60} private var currentCityModel: CityModel? {if self.currentCity==nil{return nil};return CityModel.findCityModelWithCityName([self.currentCity], cityModels: self.cityModels, isFuzzy: false)?.first} private var hotCityModels: [CityModel]? {if self.hotCities==nil{return nil};return CityModel.findCityModelWithCityName(self.hotCities, cityModels: self.cityModels, isFuzzy: false)} private var historyModels: [CityModel]? {if self.selectedCityArray.count == 0 {return nil};return CityModel.findCityModelWithCityName(self.selectedCityArray, cityModels: self.cityModels, isFuzzy: false)} private var headViewWith: CGFloat{return UIScreen.mainScreen().bounds.width - 10} private var headerViewH: CGFloat{ let h0: CGFloat = searchH let h1: CGFloat = 100 var h2: CGFloat = 100; if self.historyModels?.count > 4{h2+=40} var h3: CGFloat = 100; if self.hotCities?.count > 4 {h3+=40} return h0+h1+h2+h3 } private var sortedCityModles: [CityModel] { return cityModels.sort({ (m1, m2) -> Bool in m1.getFirstUpperLetter < m2.getFirstUpperLetter }) } /** 计算高度 */ private func headItemViewH(count: Int) -> CGRect{ let height: CGFloat = count <= 4 ? 96 : 140 return CGRectMake(0, 0, headViewWith, height) } /** 为tableView准备 */ func tableViewPrepare(){ self.title = "城市选择" self.tableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Plain) self.tableView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(tableView) tableView.dataSource = self tableView.delegate = self //vfl let viewDict = ["tableView": tableView] let vfl_arr_H = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tableView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict) let vfl_arr_V = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[tableView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict) self.view.addConstraints(vfl_arr_H) self.view.addConstraints(vfl_arr_V) } func notiAction(noti: NSNotification){ let userInfo = noti.userInfo as! [String: CityModel] let cityModel = userInfo["citiModel"]! citySelected(cityModel) } /** 定位处理 */ func locationPrepare(){ if self.currentCity != nil {return} //定位开始 let location = LocationManager.sharedInstance location.autoUpdate = true location.startUpdatingLocationWithCompletionHandler { (latitude, longitude, status, verboseMessage, error) -> () in location.stopUpdatingLocation() location.reverseGeocodeLocationWithLatLon(latitude: latitude, longitude: longitude, onReverseGeocodingCompletionHandler: { (reverseGecodeInfo, placemark, error) -> Void in guard error == nil else{return} guard let placemark = placemark,let locality = placemark.locality else {return} self.currentCity = (locality as NSString).stringByReplacingOccurrencesOfString("市", withString: "") }) } } /** headerView */ func headerviewPrepare(){ let headerView = UIView() //搜索框 searchBar = CitySearchBar() headerView.addSubview(searchBar) //vfl let searchBarViewDict = ["searchBar": searchBar] let searchBar_vfl_arr_H = NSLayoutConstraint.constraintsWithVisualFormat("H:|-18-[searchBar]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: searchBarViewDict) let searchBar_vfl_arr_V = NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[searchBar(==36)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: searchBarViewDict) headerView.addConstraints(searchBar_vfl_arr_H) headerView.addConstraints(searchBar_vfl_arr_V) searchBar.searchAction = { (searchText: String) -> Void in print(searchText) } searchBar.searchBarShouldBeginEditing = {[unowned self] in self.navigationController?.setNavigationBarHidden(true, animated: true) self.searchRVC.cityModels = nil UIView.animateWithDuration(0.15, animations: {[unowned self] () -> Void in self.searchRVC.view.alpha = 1 }) } searchBar.searchBarDidEndditing = {[unowned self] in if self.searchRVC.cityModels != nil {return} self.searchBar.setShowsCancelButton(false, animated: true) self.searchBar.text = "" self.navigationController?.setNavigationBarHidden(false, animated: true) UIView.animateWithDuration(0.14, animations: {[unowned self] () -> Void in self.searchRVC.view.alpha = 0 }) } searchBar.searchTextDidChangedAction = {[unowned self] (text: String) in if text.characters.count == 0 {self.searchRVC.cityModels = nil;return} let searchCityModols = CityModel.searchCityModelsWithCondition(text, cities: self.cityModels) self.searchRVC.cityModels = searchCityModols } searchBar.searchBarCancelAction = {[unowned self] in self.searchRVC.cityModels = nil self.searchBar.searchBarDidEndditing?() } //SeatchResultVC self.searchRVC = CitySearchResultVC(nibName: "CitySearchResultVC", bundle: nil) self.addChildViewController(searchRVC) self.view.addSubview(searchRVC.view) self.view.bringSubviewToFront(searchRVC.view) searchRVC.view.translatesAutoresizingMaskIntoConstraints = false //vfl let maskViewDict = ["maskView": searchRVC.view] let maskView_vfl_arr_H = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[maskView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: maskViewDict) let maskView_vfl_arr_V = NSLayoutConstraint.constraintsWithVisualFormat("V:|-80-[maskView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: maskViewDict) self.view.addConstraints(maskView_vfl_arr_H) self.view.addConstraints(maskView_vfl_arr_V) searchRVC.view.alpha = 0 searchRVC.touchBeganAction = {[unowned self] in self.searchBar.endEditing(true) } searchRVC.tableViewScrollAction = { [unowned self] in self.searchBar.endEditing(true) } searchRVC.tableViewDidSelectedRowAction = {[unowned self] (cityModel: CityModel) in self.citySelected(cityModel) } headerView.frame = CGRectMake(0, 0, headViewWith, headerViewH) let itemView = HeaderItemView.getHeaderItemView("当前城市") currentCityItemView = itemView var currentCities: [CityModel] = [] if self.currentCityModel != nil {currentCities.append(self.currentCityModel!)} itemView.cityModles = currentCities var frame1 = headItemViewH(itemView.cityModles.count) frame1.origin.y = searchH itemView.frame = frame1 headerView.addSubview(itemView) let itemView2 = HeaderItemView.getHeaderItemView("历史选择") var historyCityModels: [CityModel] = [] if self.historyModels != nil {historyCityModels += self.historyModels!} itemView2.cityModles = historyCityModels var frame2 = headItemViewH(itemView2.cityModles.count) frame2.origin.y = CGRectGetMaxY(frame1) itemView2.frame = frame2 headerView.addSubview(itemView2) let itemView3 = HeaderItemView.getHeaderItemView("热门城市") var hotCityModels: [CityModel] = [] if self.hotCityModels != nil {hotCityModels += self.hotCityModels!} itemView3.cityModles = hotCityModels var frame3 = headItemViewH(itemView3.cityModles.count) frame3.origin.y = CGRectGetMaxY(frame2) itemView3.frame = frame3 headerView.addSubview(itemView3) self.tableView?.tableHeaderView = headerView } /** 定位到具体的城市了 */ func getedCurrentCityWithName(currentCityName: String){ if self.currentCityModel == nil {return} if currentCityItemView?.cityModles.count != 0 {return} currentCityItemView?.cityModles = [self.currentCityModel!] } /** 处理label */ func labelPrepare(){ indexTitleLabel.backgroundColor = CFCityPickerVC.rgba(0, g: 0, b: 0, a: 0.4) indexTitleLabel.center = self.view.center indexTitleLabel.bounds = CGRectMake(0, 0, 120, 100) indexTitleLabel.font = UIFont.boldSystemFontOfSize(80) indexTitleLabel.textAlignment = NSTextAlignment.Center indexTitleLabel.textColor = UIColor.whiteColor() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sortedCityModles.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let children = sortedCityModles[section].children return children==nil ? 0 : children!.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sortedCityModles[section].name } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = CFCityCell.cityCellInTableView(tableView) cell.cityModel = sortedCityModles[indexPath.section].children?[indexPath.item] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let cityModel = sortedCityModles[indexPath.section].children![indexPath.row] citySelected(cityModel) } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { return indexHandle() } func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { showIndexTitle(title) self.showTime = 1 dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(0.2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {[unowned self] () -> Void in self.showTime = 0.8 }) dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {[unowned self] () -> Void in if self.showTime == 0.8 { self.showTime = 0.6 } }) dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(0.6 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {[unowned self] () -> Void in if self.showTime == 0.6 { self.showTime = 0.4 } }) dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(0.8 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {[unowned self] () -> Void in if self.showTime == 0.4 { self.showTime = 0.2 } }) dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {[unowned self] () -> Void in if self.showTime == 0.2 { self.dismissIndexTitle() } }) return indexTitleIndexArray[index] } func scrollViewDidScroll(scrollView: UIScrollView) { searchBar.endEditing(true) } func showIndexTitle(indexTitle: String){ self.dismissBtn.enabled = false self.view.userInteractionEnabled = false indexTitleLabel.text = indexTitle self.view.addSubview(indexTitleLabel) } func dismissIndexTitle(){ self.dismissBtn.enabled = true self.view.userInteractionEnabled = true indexTitleLabel.removeFromSuperview() } /** 选中城市处理 */ func citySelected(cityModel: CityModel){ if let cityIndex = self.selectedCityArray.indexOf(cityModel.name) { self.selectedCityArray.removeAtIndex(cityIndex) }else{ if self.selectedCityArray.count >= 8 {self.selectedCityArray.removeLast()} } self.selectedCityArray.insert(cityModel.name, atIndex: 0) NSUserDefaults.standardUserDefaults().setObject(self.selectedCityArray, forKey: SelectedCityKey) selectedCityModel?(cityModel: cityModel) delegate?.selectedCityModel(self, cityModel: cityModel) self.dismiss() } } extension CFCityPickerVC{ /** 处理索引 */ func indexHandle() -> [String] { var indexArr: [String] = [] for (index,cityModel) in sortedCityModles.enumerate() { let indexString = cityModel.getFirstUpperLetter if indexArr.contains(indexString) {continue} indexArr.append(indexString) indexTitleIndexArray.append(index) } return indexArr } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { indexTitleLabel.center = self.view.center } }
mit
9851092e865bbea3769be0961978693b
33.770335
207
0.616967
4.760563
false
false
false
false
naturaln0va/Doodler_iOS
Doodler/CanvasViewController.swift
1
20445
import UIKit protocol CanvasViewControllerDelegate: class { func canvasViewControllerShouldDismiss(_ vc: CanvasViewController, didSave: Bool) } class CanvasViewController: UIViewController, UIGestureRecognizerDelegate { var doodleToEdit: Doodle? var isPresentingWithinMessages = false weak var delegate: CanvasViewControllerDelegate? private var lastCanvasZoomScale = 0 private var pendingPickedColor: UIColor? private var toolBarBottomConstraint: NSLayoutConstraint! private var canvasNeedsLayout = true private lazy var gridView: GridView = { let view = GridView() view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var strokeSlider: UISlider = { let view = UISlider() view.minimumValue = 1 view.maximumValue = 100 view.translatesAutoresizingMaskIntoConstraints = false view.setThumbImage(UIImage(named: "knob"), for: .normal) view.addTarget(self, action: #selector(sliderUpdated(_:)), for: .valueChanged) view.setMinimumTrackImage(UIImage(named: "slider"), for: .normal) view.setMaximumTrackImage(UIImage(named: "slider"), for: .normal) view.setValue(SettingsController.shared.strokeWidth, animated: false) return view }() private lazy var strokeSizeView: StrokeSizeView = { let view = StrokeSizeView() view.alpha = 0 view.clipsToBounds = true view.layer.cornerRadius = 8 view.translatesAutoresizingMaskIntoConstraints = false return view }() private lazy var blurStatusView: UIVisualEffectView = { let style: UIBlurEffect.Style if #available(iOS 13.0, *) { style = .systemChromeMaterialDark } else { style = .dark } let view = UIVisualEffectView(effect: UIBlurEffect(style: style)) view.translatesAutoresizingMaskIntoConstraints = false return view }() private(set) lazy var toolbar: UIToolbar = { let view = UIToolbar() view.isTranslucent = true view.translatesAutoresizingMaskIntoConstraints = false view.barTintColor = self.isPresentingWithinMessages ? UIColor(white: 0.98899, alpha: 1.0) : UIColor.black view.tintColor = self.isPresentingWithinMessages ? UIColor(red: 0.52, green: 0.56, blue: 0.6, alpha: 1.0) : UIColor.white return view }() private lazy var segmentedControl: UISegmentedControl = { let view = UISegmentedControl(items: [ NSLocalizedString("DRAW", comment: "Draw"), NSLocalizedString("ERASE", comment: "Erase") ] ) view.frame.size.width = 175 view.selectedSegmentIndex = 0 if !self.isPresentingWithinMessages { view.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal) view.setTitleTextAttributes([.foregroundColor: UIColor.black], for: .selected) } view.selectedSegmentTintColor = .white view.addTarget(self, action: #selector(segmentWasChanged(_:)), for: .valueChanged) return view }() private lazy var scrollView: UIScrollView = { let view = UIScrollView() view.delegate = self view.maximumZoomScale = 12.5 view.panGestureRecognizer.minimumNumberOfTouches = 2 view.translatesAutoresizingMaskIntoConstraints = false return view }() private let colorButton = ColorPreviewButton( frame: CGRect(origin: .zero, size: CGSize(width: 27, height: 27)) ) private var segmentBarButton: UIBarButtonItem! private var colorPickerBarButton: UIBarButtonItem! private lazy var backButton = UIBarButtonItem( image: UIImage(named: "back-arrow-icon"), style: .plain, target: self, action: #selector(backButtonPressed) ) private lazy var actionButton = UIBarButtonItem( image: UIImage(named: "toolbox-icon"), style: .plain, target: self, action: #selector(actionButtonPressed) ) private lazy var undoButton = UIBarButtonItem( title: NSLocalizedString("UNDO", comment: "Undo"), style: .plain, target: self, action: #selector(undoButtonPressed) ) private lazy var redoButton = UIBarButtonItem( title: NSLocalizedString("REDO", comment: "Redo"), style: .plain, target: self, action: #selector(redoButtonPressed) ) private lazy var shareButton = UIBarButtonItem( image: UIImage(named: "share-button"), style: .plain, target: self, action: #selector(shareButtonPressed) ) let canvas: DrawableView init(size: CGSize) { canvas = DrawableView(frame: CGRect(origin: .zero, size: size)) canvas.backgroundColor = .white canvas.isUserInteractionEnabled = true canvas.layer.magnificationFilter = .linear super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - ViewController Delegate - override var canBecomeFirstResponder: Bool { return true } override var prefersStatusBarHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.backgroundColor SettingsController.shared.disableEraser() view.addSubview(gridView) view.addConstraints(NSLayoutConstraint.constraints(forPinningViewToSuperview: gridView)) view.addSubview(scrollView) view.addConstraints(NSLayoutConstraint.constraints(forPinningViewToSuperview: scrollView)) view.addSubview(toolbar) NSLayoutConstraint.activate([ toolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor), toolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) toolBarBottomConstraint = toolbar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) toolBarBottomConstraint.isActive = true view.addSubview(blurStatusView) NSLayoutConstraint.activate([ blurStatusView.topAnchor.constraint(equalTo: view.topAnchor), blurStatusView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), blurStatusView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), blurStatusView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor) ]) view.addSubview(strokeSizeView) view.addConstraints( NSLayoutConstraint.constraints( forConstrainingView: strokeSizeView, toSize: CGSize(width: 125, height: 125) ) ) view.addConstraints( NSLayoutConstraint.constraints(forCenteringView: strokeSizeView) ) view.addSubview(strokeSlider) NSLayoutConstraint.activate([ strokeSlider.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8), strokeSlider.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8), strokeSlider.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8) ]) segmentBarButton = UIBarButtonItem(customView: segmentedControl) colorPickerBarButton = UIBarButtonItem(customView: colorButton) colorButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(colorButtonPressed))) colorButton.color = SettingsController.shared.strokeColor hideToolbar() refreshToolbarItems() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) showToolbar() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) hideToolbar() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil) { context in self.centerScrollViewContents() } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard canvasNeedsLayout && view.bounds.width > 0 else { return } canvasNeedsLayout = false scrollView.addSubview(canvas) let canvasTransformValue = view.frame.width / canvas.frame.width scrollView.minimumZoomScale = canvasTransformValue / 2.5 scrollView.contentSize = canvas.bounds.size canvas.transform = CGAffineTransform(scaleX: canvasTransformValue, y: canvasTransformValue) canvas.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(handle(longPress:)))) canvas.doodleToEdit = doodleToEdit centerScrollViewContents() } //MARK: - Actions - @objc private func handle(longPress gesture: UILongPressGestureRecognizer) { guard let gestureView = gesture.view else { return } guard gesture.state == .began else { return } let position = gesture.location(in: gestureView) pendingPickedColor = canvas.imageByCapturing.color(at: position) guard pendingPickedColor != nil else { return } UIMenuController.shared.showMenu(from: gestureView, rect: CGRect(origin: position, size: .zero)) UIMenuController.shared.menuItems = [UIMenuItem(title: NSLocalizedString("PICKCOLOR", comment: "Pick Color"), action: #selector(selectColor))] gestureView.becomeFirstResponder() } @objc private func undoButtonPressed() { canvas.undo() } @objc private func redoButtonPressed() { canvas.redo() } @objc private func shareButtonPressed() { let ac = UIActivityViewController(activityItems: [NSLocalizedString("DOODLERSHARE", comment: "Made with Doodler"), URL(string: "https://itunes.apple.com/us/app/doodler-simple-drawing/id948139703?mt=8")!, self.canvas.imageByCapturing], applicationActivities: nil) ac.excludedActivityTypes = [ .assignToContact, .addToReadingList, .print ] ac.setupPopoverInView(sourceView: view, barButtonItem: shareButton) present(ac, animated: true, completion: nil) } @objc private func actionButtonPressed() { let vc = ActionMenuViewController(isPresentingWithinMessages: isPresentingWithinMessages) vc.loadViewIfNeeded() vc.delegate = self vc.drawableView = canvas vc.preferredContentSize = vc.contentSize vc.setupPopoverInView(sourceView: view, barButtonItem: actionButton) present(vc, animated: true, completion: nil) } @objc private func colorButtonPressed() { let picker = ColorPickerViewController() picker.delegate = self picker.preferredContentSize = CGSize(width: 300, height: 366) picker.setupPopoverInView(sourceView: view, barButtonItem: toolbar.items?.last) present(picker, animated: true, completion: nil) } @objc private func backButtonPressed() { guard canvas.history.canReset && canvas.isDirty else { delegate?.canvasViewControllerShouldDismiss(self, didSave: false) return } let activityIndicator = UIActivityIndicatorView(style: .medium) activityIndicator.tintColor = isPresentingWithinMessages ? UIColor(red: 0.52, green: 0.56, blue: 0.6, alpha: 1.0) : .white activityIndicator.startAnimating() let previousItems = toolbar.items toolbar.items?.removeFirst() toolbar.items?.insert(UIBarButtonItem(customView: activityIndicator), at: 0) let preview = canvas.imageByCapturing DispatchQueue(label: "io.ackermann.imageCreate").async { let stickerImage = self.canvas.bufferImage?.autoCroppedImage?.verticallyFlipped ?? UIImage() let stickerData = stickerImage.pngData() ?? Data() let doodle = Doodle( createdDate: self.doodleToEdit?.createdDate ?? Date(), updatedDate: Date(), history: self.canvas.history, stickerImageData: stickerData, previewImage: preview ) DocumentsController.sharedController.save(doodle: doodle) { success in if success { self.delegate?.canvasViewControllerShouldDismiss(self, didSave: success) } else { self.toolbar.items = previousItems let alert = UIAlertController(title: nil, message: NSLocalizedString("ERRORSAVING", comment: "Error saving doodle."), preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("CANCEL", comment: "Cancel"), style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } } } @objc private func selectColor() { if let color = pendingPickedColor { update(to: color) pendingPickedColor = nil } } @objc private func clearScreen() { let alert = UIAlertController(title: NSLocalizedString("CLEAR", comment: "Clear"), message: NSLocalizedString("CLEARPROMPT", comment: "Would you like to clear the screen?"), preferredStyle: .alert) alert.addAction( UIAlertAction(title: NSLocalizedString("CLEAR", comment: "Clear"), style: .destructive) { action in self.canvas.clear() } ) alert.addAction(UIAlertAction(title: NSLocalizedString("CANCEL", comment: "Cancel"), style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } @objc private func segmentWasChanged(_ sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { SettingsController.shared.disableEraser() } else if sender.selectedSegmentIndex == 1 { SettingsController.shared.enableEraser() } } @objc private func sliderUpdated(_ sender: UISlider) { SettingsController.shared.strokeWidth = sender.value strokeSizeView.strokeSize = CGFloat(sender.value) } // MARK: - Helpers - func refreshToolbarItems() { if UIDevice.current.userInterfaceIdiom == .pad { toolbar.items = [ backButton, UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), segmentBarButton, UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), undoButton, redoButton, UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), shareButton, colorPickerBarButton ] } else { toolbar.items = [ backButton, UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), segmentBarButton, UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), actionButton, UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), colorPickerBarButton ] } } func update(to color: UIColor) { segmentedControl.selectedSegmentIndex = 0 SettingsController.shared.disableEraser() SettingsController.shared.setStrokeColor(color) colorButton.color = color } func showToolbar() { toolBarBottomConstraint.constant = 0 UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.05, initialSpringVelocity: 0.125, options: [], animations: { self.view.layoutIfNeeded() }, completion: nil) } func hideToolbar() { toolBarBottomConstraint.constant = toolbar.bounds.height + view.safeAreaInsets.bottom UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.05, initialSpringVelocity: 0.125, options: [], animations: { self.view.layoutIfNeeded() }, completion: nil) } func centerScrollViewContents() { let boundsSize = scrollView.bounds.size var contentsFrame = canvas.frame if contentsFrame.size.width < boundsSize.width { contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0 } else { contentsFrame.origin.y = 0.0 } let centeredFrame = CGRect(origin: contentsFrame.origin, size: contentsFrame.size) canvas.frame = centeredFrame } //MARK: - Motion Event Delegate - override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { guard motion == .motionShake else { return } clearScreen() } } extension CanvasViewController: UIScrollViewDelegate { //MARK: - UIScrollViewDelegate - func viewForZooming(in scrollView: UIScrollView) -> UIView? { return canvas } func scrollViewDidZoom(_ scrollView: UIScrollView) { let scale = Int(scrollView.zoomScale * 100) if lastCanvasZoomScale < scale && (scrollView.pinchGestureRecognizer?.velocity ?? 0) > CGFloat(2) { hideToolbar() } else if lastCanvasZoomScale > scale && (scrollView.pinchGestureRecognizer?.velocity ?? 0) < CGFloat(-1) { showToolbar() } if scale > 675 { canvas.layer.magnificationFilter = .nearest } else { canvas.layer.magnificationFilter = .linear } lastCanvasZoomScale = scale centerScrollViewContents() } } extension CanvasViewController: ColorPickerViewControllerDelegate { //MARK: - ColorPickerViewControllerDelegate Methods - func colorPickerViewControllerDidPickColor(_ color: UIColor) { update(to: color) } } extension CanvasViewController: ActionMenuViewControllerDelegate { func actionMenuViewControllerDidSelectShare(vc: ActionMenuViewController) { vc.dismiss(animated: true, completion: nil) let ac = UIActivityViewController(activityItems: [NSLocalizedString("DOODLERSHARE", comment: "Made with Doodler"), URL(string: "https://itunes.apple.com/us/app/doodler-simple-drawing/id948139703?mt=8")!, self.canvas.imageByCapturing], applicationActivities: nil) ac.excludedActivityTypes = [ .assignToContact, .addToReadingList, .print ] ac.setupPopoverInView(sourceView: view, barButtonItem: actionButton) present(ac, animated: true, completion: nil) } func actionMenuViewControllerDidSelectClear(vc: ActionMenuViewController) { vc.dismiss(animated: true, completion: nil) clearScreen() } func actionMenuViewControllerDidSelectUndo(vc: ActionMenuViewController) { canvas.undo() vc.drawableView = canvas } func actionMenuViewControllerDidSelectRedo(vc: ActionMenuViewController) { canvas.redo() vc.drawableView = canvas } }
mit
571bfc35f4c02ea9152078d977066d09
35.121908
270
0.630423
5.420201
false
false
false
false
kak-ios-codepath/everest
Everest/Everest/Views/MomentDetailCell.swift
1
5712
// // MomentDetailCell.swift // Everest // // Created by Kaushik on 10/20/17. // Copyright © 2017 Kavita Gaitonde. All rights reserved. // import UIKit import Announce class MomentDetailCell: UITableViewCell { static let formatter = DateFormatter() static let friendlyDateformatter = DateFormatter() static let dateFormat = "yyyy-MM-dd HH:mm:ssZ" static let friendlyDateFormat = "d MMM YY h:mm a" @IBOutlet weak var momentLikeLabel: UILabel! @IBOutlet weak var momentLocationLabel: UILabel! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var userProfileImaeView: UIImageView! @IBOutlet weak var momentCreatedDateLabel: UILabel! @IBOutlet weak var likesCountLabel: UILabel! @IBOutlet weak var momentDescriptionLabel: UILabel! @IBOutlet weak var momentImageView: UIImageView! @IBOutlet weak var momentTitleLabel: UILabel! @IBOutlet weak var cloneButton: UIButton! @IBOutlet weak var actTitle: UILabel! @IBOutlet weak var momentLikeButton: UIButton! private var isLiked : Bool? var moment : Moment? { didSet { if moment == nil { return } self.momentTitleLabel.text = moment?.title self.momentDescriptionLabel.text = moment?.details if moment?.actId != nil { self.actTitle.text = MainManager.shared.availableActs[(moment?.actId)!]?.title } if moment?.timestamp != nil { let date = MomentDetailCell.formatter.date(from: (moment?.timestamp)!) self.momentCreatedDateLabel.text = MomentDetailCell.friendlyDateformatter.string(from: date!) } else { self.momentCreatedDateLabel.text = moment?.timestamp } if let picUrls = moment?.picUrls { if let url = URL(string: picUrls[0]) { self.momentImageView.setImageWith(url) } else { self.momentImageView.image = UIImage(named: "Moment") } } else { self.momentImageView.image = UIImage(named: "Moment") } if moment?.userId != nil { FireBaseManager.shared.getUser(userID: (moment?.userId)!) { (user:User?, error:Error?) in if user != nil { self.userNameLabel.text = user?.name if (user?.profilePhotoUrl != nil) { self.userProfileImaeView.setImageWith(URL(string: (user?.profilePhotoUrl!)!)!) } else { self.userProfileImaeView.image = UIImage(named: "Profile") } } } } self.cloneButton.isHidden = true self.categoryLabel.text = ((MainManager.shared.availableActs[(moment?.actId)!]?.category)?.capitalized)! + " action" self.momentLocationLabel.text = self.moment?.location if let likes = self.moment?.likes { if likes > 0 { self.momentLikeLabel.text = "\(likes)" } } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code MomentDetailCell.formatter.dateFormat = MomentDetailCell.dateFormat MomentDetailCell.friendlyDateformatter.dateFormat = MomentDetailCell.friendlyDateFormat self.isLiked = false } override func draw(_ rect: CGRect) { self.userProfileImaeView.setRounded() self.momentImageView.setRoundedCorner(radius: 5) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func momentLikeAction(_ sender: Any) { // var likeImage = UIImage.init(named: "Like") if isLiked == false { isLiked = true FireBaseManager.shared.updateMomentLikes(momentId: (self.moment?.id)!, incrementBy: 1) if let likesCount = self.moment?.likes { self.moment?.likes = likesCount+1 } }else{ isLiked = false // likeImage = UIImage.init(named: "like_bw") if let likesCount = self.moment?.likes { if likesCount>1 { self.moment?.likes = likesCount-1 FireBaseManager.shared.updateMomentLikes(momentId: (self.moment?.id)!, incrementBy: -1) } } } UIView.animate(withDuration: 0.6, animations: { self.momentLikeButton.transform = CGAffineTransform.identity.scaledBy(x: 0.6, y: 0.6) }, completion: { (finish) in UIView.animate(withDuration: 0.6, animations: { self.momentLikeButton.transform = CGAffineTransform.identity // self.momentLikeButton.setImage(likeImage, for: .normal) if let likes = self.moment?.likes { self.momentLikeLabel.text = "\(likes)" } }) }) } @IBAction func cloneAction(_ sender: AnyObject) { MainManager.shared.createNewAction(id: (moment?.actId)!, completion:{(error) in let message = Message(message: "You are now successfully subscribed to this act", theme: .warning) announce(message, on: .view(self.contentView), withMode: .timed(3.0)) }) } }
apache-2.0
ed6d61e7f5366719038ff8d09f064335
36.326797
128
0.571354
4.839831
false
false
false
false
iossocket/DBDemo
DBDemo/RealmBookNotificaitonCenter.swift
1
1409
// // RealmBookNotificaitonCenter.swift // DBDemo // // Created by Jian Zhang on 1/1/17. // Copyright © 2017 ThoughtWorks. All rights reserved. // import Foundation import RealmSwift class RealmBookNotificaitonCenter: BookNotificationCenter { private let transform: RealmBookToBookTransform private var notificationTokens = [NotificationToken]() init(transform: RealmBookToBookTransform) { self.transform = transform } func register(deletionHandler: (([Book], [Int]) -> ())?, insertionHandler: (([Book], [Int]) -> ())?, modificationHandler: (([Book], [Int]) -> ())?) { let realm = try! Realm() let results = realm.objects(RealmBook.self) let notificationToken = results.addNotificationBlock { [weak self] changes in guard let strongSelf = self else { // TODO: thorw a error return } switch changes { case .update(let value, let deletions, let insertions, let modifications): let books = strongSelf.transform.mapResults(value) deletionHandler?(books, deletions) insertionHandler?(books, insertions) modificationHandler?(books, modifications) break default: break } } notificationTokens.append(notificationToken) } }
mit
29c56b831097f49e759fc0ac3c92bf18
32.52381
153
0.604403
5.010676
false
false
false
false
allen-zeng/PromiseKit
Tests/Categories/TestStoreKit.swift
2
1581
import PromiseKit import StoreKit import XCTest class Test_SKProductsRequest_Swift: XCTestCase { func test() { class MockProductsRequest: SKProductsRequest { override func start() { after(0.1).then { self.delegate?.productsRequest(self, didReceiveResponse: SKProductsResponse()) } } } let ex = expectationWithDescription("") MockProductsRequest().promise().then { _ in ex.fulfill() } waitForExpectationsWithTimeout(1, handler: nil) } func testCancellation() { class MockProductsRequest: SKProductsRequest { override func start() { after(0.1).then { _ -> Void in #if os(iOS) || swift(>=2.3) let err = NSError(domain: SKErrorDomain, code: SKErrorCode.PaymentCancelled.rawValue, userInfo: nil) #else let err = NSError(domain: SKErrorDomain, code: SKErrorPaymentCancelled, userInfo: nil) NSError.registerCancelledErrorDomain(SKErrorDomain, code: SKErrorPaymentCancelled) #endif self.delegate?.request?(self, didFailWithError: err) } } } let ex = expectationWithDescription("") MockProductsRequest().promise().error(policy: .AllErrors) { err in XCTAssert((err as NSError).cancelled) ex.fulfill() } waitForExpectationsWithTimeout(1, handler: nil) } }
mit
099a17bb13de6433d328ef99d4362381
34.931818
124
0.562302
5.451724
false
true
false
false
J3D1-WARR10R/WikiRaces
WKRKit/WKRKit/Game/WKRRaceSettings.swift
2
4908
// // WKRGameSettings.swift // WikiRaces // // Created by Andrew Finke on 5/3/20. // Copyright © 2020 Andrew Finke. All rights reserved. // import Foundation public class WKRGameSettings: Codable { // MARK: - Types - public enum StartPage { case random case custom(WKRPage) public var isStandard: Bool { switch self { case .random: return true default: return false } } } public enum EndPage { case curatedVoting case randomVoting case custom(WKRPage) public var isStandard: Bool { switch self { case .curatedVoting: return true default: return false } } } public enum BannedPage { case portal case custom(WKRPage) } public struct Notifications: Codable { public let neededHelp: Bool public let linkOnPage: Bool public let missedLink: Bool public let isOnUSA: Bool public let isOnSamePage: Bool public var isStandard: Bool { return neededHelp && linkOnPage && missedLink && isOnUSA && isOnSamePage } public init(neededHelp: Bool, linkOnPage: Bool, missedTheLink: Bool, isOnUSA: Bool, isOnSamePage: Bool) { self.neededHelp = neededHelp self.linkOnPage = linkOnPage self.missedLink = missedTheLink self.isOnUSA = isOnUSA self.isOnSamePage = isOnSamePage } } public struct Points: Codable { public let bonusPointReward: Int public let bonusPointsInterval: Double public var isStandard: Bool { return bonusPointsInterval == WKRKitConstants.current.bonusPointsInterval && bonusPointReward == WKRKitConstants.current.bonusPointReward } public init(bonusPointReward: Int, bonusPointsInterval: Double) { self.bonusPointReward = bonusPointReward self.bonusPointsInterval = bonusPointsInterval } } public struct Timing: Codable { public let votingTime: Int public let resultsTime: Int public var isStandard: Bool { return votingTime == WKRRaceDurationConstants.votingState && resultsTime == WKRRaceDurationConstants.resultsState } public init(votingTime: Int, resultsTime: Int) { self.votingTime = votingTime self.resultsTime = resultsTime } } public struct Other: Codable { public let isHelpEnabled: Bool public var isStandard: Bool { return isHelpEnabled } public init(isHelpEnabled: Bool) { self.isHelpEnabled = isHelpEnabled } } public struct Language: Codable { public let code: String public var isStandard: Bool { return code == "en" } public init(code: String) { self.code = code } } // MARK: - Properties - public var isCustom: Bool { if notifications.isStandard && points.isStandard && timing.isStandard && other.isStandard && startPage.isStandard && endPage.isStandard && language.isStandard, bannedPages.count == 1, case .portal = bannedPages[0] { return false } else { return true } } public var startPage: StartPage = .random public var endPage: EndPage = .curatedVoting public var bannedPages: [BannedPage] = [.portal] public var notifications = Notifications( neededHelp: true, linkOnPage: true, missedTheLink: true, isOnUSA: true, isOnSamePage: true) public var points = Points(bonusPointReward: WKRKitConstants.current.bonusPointReward, bonusPointsInterval: WKRKitConstants.current.bonusPointsInterval) public var timing = Timing(votingTime: WKRRaceDurationConstants.votingState, resultsTime: WKRRaceDurationConstants.resultsState) public var other = Other(isHelpEnabled: true) public var language = Language(code: "en") public func reset() { startPage = .random endPage = .curatedVoting bannedPages = [.portal] notifications = Notifications( neededHelp: true, linkOnPage: true, missedTheLink: true, isOnUSA: true, isOnSamePage: true) points = Points(bonusPointReward: WKRKitConstants.current.bonusPointReward, bonusPointsInterval: WKRKitConstants.current.bonusPointsInterval) timing = Timing(votingTime: WKRRaceDurationConstants.votingState, resultsTime: WKRRaceDurationConstants.resultsState) other = Other(isHelpEnabled: true) } public init() {} }
mit
7ef292a78ccf56286a9b0475d8e373d8
27.364162
156
0.606481
4.713737
false
false
false
false
mdiep/Tentacle
Sources/Tentacle/Content.swift
1
5764
// // Content.swift // Tentacle // // Created by Romain Pouclet on 2016-11-28. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Foundation extension Repository { /// A request for the content at a given path in the repository. /// /// https://developer.github.com/v3/repos/contents/#get-contents public func content(atPath path: String, atRef ref: String? = nil) -> Request<Content> { let queryItems: [URLQueryItem] if let ref = ref { queryItems = [ URLQueryItem(name: "ref", value: ref) ] } else { queryItems = [] } return Request(method: .get, path: "/repos/\(owner)/\(name)/contents/\(path)", queryItems: queryItems) } } /// Content /// https://developer.github.com/v3/repos/contents/ /// /// - file: a file when queried directly in a repository /// - directory: a directory when queried directly in a repository (may contain multiple files) public enum Content: ResourceType, Hashable { /// A file in a repository public struct File: CustomStringConvertible, ResourceType { public enum ContentTypeName: String, Decodable { case file case directory = "dir" case symlink case submodule } /// Type of content in a repository /// /// - file: a file in a repository /// - directory: a directory in a repository /// - symlink: a symlink in a repository not targeting a file inside the same repository /// - submodule: a submodule in a repository public enum ContentType: Decodable, Equatable { /// A file a in a repository case file(size: Int, downloadURL: URL?) /// A directory in a repository case directory /// A symlink in a repository. Target and URL are optional because they are treated as regular files /// when they are the result of a query for a directory /// See https://developer.github.com/v3/repos/contents/ case symlink(target: String?, downloadURL: URL?) /// A submodule in a repository. URL is optional because they are treated as regular files /// when they are the result of a query for a directory /// See https://developer.github.com/v3/repos/contents/ case submodule(url: String?) public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let type = try container.decode(ContentTypeName.self, forKey: .type) switch type { case .file: let size = try container.decode(Int.self, forKey: .size) if let url = try container.decodeIfPresent(URL.self, forKey: .downloadURL) { self = .file(size: size, downloadURL: url) } else { self = .submodule(url: nil) } case .directory: self = .directory case .submodule: let url = try container.decodeIfPresent(String.self, forKey: .submoduleURL) self = .submodule(url: url) case .symlink: let target = try container.decodeIfPresent(String.self, forKey: .target) let url = try container.decodeIfPresent(URL.self, forKey: .downloadURL) self = .symlink(target: target, downloadURL: url) } } private enum CodingKeys: String, CodingKey { case type case size case target case downloadURL = "download_url" case submoduleURL = "submodule_git_url" } } /// The type of content public let content: ContentType /// Name of the file public let name: String /// Path to the file in repository public let path: String /// Sha of the file public let sha: String /// URL to preview the content public let url: URL public var description: String { return name } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.name = try container.decode(String.self, forKey: .name) self.path = try container.decode(String.self, forKey: .path) self.sha = try container.decode(String.self, forKey: .sha) self.url = try container.decode(URL.self, forKey: .url) self.content = try ContentType(from: decoder) } public init(content: ContentType, name: String, path: String, sha: String, url: URL) { self.name = name self.path = path self.sha = sha self.url = url self.content = content } private enum CodingKeys: String, CodingKey { case name case path case sha case url = "html_url" case content } public func hash(into hasher: inout Hasher) { name.hash(into: &hasher) } } case file(File) case directory([File]) public init(from decoder: Decoder) throws { do { let file = try File(from: decoder) self = .file(file) } catch { var container = try decoder.unkeyedContainer() var files = [File]() while !container.isAtEnd { files.append(try container.decode(File.self)) } self = .directory(files) } } }
mit
6ad3968fe6a6d85bbb2132bf41999f51
33.927273
112
0.556828
4.85101
false
false
false
false
HTWDD/HTWDresden-iOS-Temp
HTWDresden_old/HTWDresden/MPMainModel.swift
1
2662
// // MPMainModel.swift // HTWDresden // // Created by Benjamin Herzog on 27.08.14. // Copyright (c) 2014 Benjamin Herzog. All rights reserved. // import UIKit class MPMainModel: NSObject, NSXMLParserDelegate { var mensenTitel = [String]() var mensen = [String:[Speise]]() var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext! override init() { super.init() } init(test: Bool) { super.init() let request = NSFetchRequest(entityName: "Speise") let array = context.executeFetchRequest(request, error: nil) as [Speise] } func start(completion: () -> Void) { if MENSA_LAST_REFRESH != nil && MENSA_LAST_REFRESH.timeIntervalSinceNow >= -60*60 { // Wurde vor einer Stunde das letzte Mal aktualisiert self.getData() completion() return } let parser = MPMainXMLParser() parser.parseWithCompletion { success, error in if error != nil || !success { println("Parsen fehlgeschlagen") return } self.getData() completion() } } func refresh(start: () -> Void, end: () -> Void) { mensen = [String:[Speise]]() start() let parser = MPMainXMLParser() parser.parseWithCompletion { success, error in if error != nil || !success { println("Parsen fehlgeschlagen") return } self.getData() end() } } func getData() { mensen = [String:[Speise]]() let request = NSFetchRequest(entityName: "Speise") let array = context.executeFetchRequest(request, error: nil) as [Speise] for speise in array { if mensen[speise.mensa] == nil { mensen[speise.mensa] = [Speise]() if !contains(mensenTitel, speise.mensa) { mensenTitel.append(speise.mensa) } } mensen[speise.mensa]?.append(speise) } } func numberOfSections() -> Int { return 1 } func numberOfRowsInSection(section: Int) -> Int { if CURR_MENSA != nil { return mensen[CURR_MENSA]?.count ?? 0 } else { return 0 } } func speiseForIndexPath(indexPath: NSIndexPath) -> Speise? { if let thisMensa = mensen[CURR_MENSA] { return thisMensa[indexPath.row] } return nil } }
gpl-2.0
ff9efc9bb52bcf8c1e1a4c4f460c3ed9
25.888889
100
0.522539
4.542662
false
false
false
false
poetmountain/PapersPlease
Classes/ValidationUnit.swift
1
5546
// // ValidationUnit.swift // PapersPlease // // Created by Brett Walker on 7/3/14. // Copyright (c) 2014-2016 Poet & Mountain, LLC. All rights reserved. // import Foundation import UIKit public let ValidationUnitUpdateNotification:String = "ValidationUnitUpdateNotification" public class ValidationUnit { internal(set) public var registeredValidationTypes:[ValidatorType] = [] internal(set) public var errors = [String:[String]]() public var identifier = "" internal(set) public var valid:Bool = false public var enabled:Bool = true let validationQueue:dispatch_queue_t internal(set) public var lastTextValue:String = "" public init(validatorTypes:[ValidatorType]=[], identifier:String, initialText:String="") { self.validationQueue = dispatch_queue_create("com.poetmountain.ValidationUnitQueue", DISPATCH_QUEUE_SERIAL) self.registeredValidationTypes = validatorTypes self.identifier = identifier self.lastTextValue = initialText for type:ValidatorType in self.registeredValidationTypes { if (type.sendsUpdates) { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ValidationUnit.validationUnitStatusUpdatedNotification(_:)), name: ValidatorUpdateNotification, object: type) type.isTextValid(self.lastTextValue) } } } func dealloc() { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Validation methods public func registerValidatorType(validatorType:ValidatorType) { self.registeredValidationTypes.append(validatorType) } public func clearValidatorTypes() { self.registeredValidationTypes.removeAll() } func validationComplete() { // first remove any old errors self.errors.removeAll() var total_errors = [String:[String:[String]]]() if (!self.valid) { for validator_type:ValidatorType in self.registeredValidationTypes { if (!validator_type.valid) { self.errors[validator_type.dynamicType.type()] = validator_type.validationStates } } total_errors = ["errors" : self.errors] } NSNotificationCenter.defaultCenter().postNotificationName(ValidationUnitUpdateNotification, object: self, userInfo: total_errors) } public func validateText(text:String) { if (self.enabled) { dispatch_async(self.validationQueue, { [weak self] in if let strong_self = self { // add up the number of valid validation tests (coercing each Bool result to an Int) let num_valid = strong_self.registeredValidationTypes.reduce(0) { (lastValue, type:ValidatorType) in lastValue + Int(type.isTextValid(text)) } // use the number of total validations to set a global validation status let type_count = strong_self.registeredValidationTypes.count (num_valid == type_count) ? (strong_self.valid = true) : (strong_self.valid = false) // set the current text value to be the last value to prepare for the next validation request strong_self.lastTextValue = text // send notification (on main queue, there be UI work) dispatch_async(dispatch_get_main_queue(), { strong_self.validationComplete() }) } }) } } // MARK: Utility methods public func validatorTypeForIdentifier(identifier:String) -> ValidatorType? { var validator_type: ValidatorType? for type:ValidatorType in self.registeredValidationTypes { if (type.identifier == identifier) { validator_type = type break } } return validator_type } // MARK: Notifications @objc public func textDidChangeNotification(notification:NSNotification) { if (notification.name == UITextFieldTextDidChangeNotification) { guard let text_field:UITextField = notification.object as? UITextField else { return } guard let text = text_field.text else { return } self.validateText(text) } else if (notification.name == UITextViewTextDidChangeNotification) { guard let text_view:UITextView = notification.object as? UITextView else { return } guard let text = text_view.text else { return } self.validateText(text) } } @objc public func validationUnitStatusUpdatedNotification(notification:NSNotification) { if (!self.enabled) { return } guard let user_info = notification.userInfo else { return } guard let status_num:NSNumber = user_info["status"] as? NSNumber else { return } let is_valid: Bool = status_num.boolValue ?? false if (is_valid) { self.validateText(self.lastTextValue) } else { self.valid = false self.validationComplete() } } }
mit
22ccbc9bafe25ce7ba7338b1a43b2c0e
33.240741
200
0.592679
5.241966
false
false
false
false
hayashi311/iosdcjp2016app
iOSApp/Pods/APIKit/Sources/DataParserType/FormURLEncodedDataParser.swift
2
1379
import Foundation /// `FormURLEncodedDataParser` parses form URL encoded response data. public class FormURLEncodedDataParser: DataParserType { public enum Error: ErrorType { case CannotGetStringFromData(NSData) } /// The string encoding of the data. public let encoding: NSStringEncoding /// Returns `FormURLEncodedDataParser` with the string encoding. public init(encoding: NSStringEncoding) { self.encoding = encoding } // MARK: - DataParserType /// Value for `Accept` header field of HTTP request. public var contentType: String? { return "application/x-www-form-urlencoded" } /// Return `AnyObject` that expresses structure of response. /// - Throws: `FormURLEncodedDataParser.Error` when the parser fails to initialize `NSString` from `NSData`. public func parseData(data: NSData) throws -> AnyObject { guard let string = NSString(data: data, encoding: encoding) as? String else { throw Error.CannotGetStringFromData(data) } let components = NSURLComponents() components.percentEncodedQuery = string let queryItems = components.queryItems ?? [] var dictionary = [String: AnyObject]() for queryItem in queryItems { dictionary[queryItem.name] = queryItem.value } return dictionary } }
mit
4700c8fec54f63c82c119d559567e49d
31.069767
112
0.674402
5.014545
false
false
false
false
Incipia/Elemental
Elemental/Classes/Geometry/IncFormGeometry.swift
1
1301
// // IncFormGeometry.swift // Elemental // // Created by Leif Meyer on 5/3/17. // // import Foundation extension CGRect { func distance(to point: CGPoint) -> CGFloat { var closestPoint: CGPoint = .zero switch point.x { case let x where x < minX: closestPoint.x = minX case let x where x > maxX: closestPoint.x = maxX default: closestPoint.x = point.x } switch point.y { case let y where y < minY: closestPoint.y = minY case let y where y > maxY: closestPoint.y = maxY default: closestPoint.y = point.y } return closestPoint.distance(to: point) } } extension CGPoint { func distance(to point: CGPoint) -> CGFloat { let difference = self - point return sqrt(difference.x * difference.x + difference.y * difference.y) } static func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } } extension CGSize { func inset(by insets: UIEdgeInsets) -> CGSize { return CGSize(width: width - insets.left - insets.right, height: height - insets.top - insets.bottom) } func outset(by insets: UIEdgeInsets) -> CGSize { return CGSize(width: width + insets.left + insets.right, height: height + insets.top + insets.bottom) } }
mit
73093ca986e63133cdba623549b48359
26.680851
107
0.63259
3.685552
false
false
false
false
duliodenis/slappylock
Slappy Lock/Slappy Lock/MenuVC.swift
1
2685
// // MenuVC.swift // Slappy Lock // // Created by Dulio Denis on 11/18/15. // Copyright © 2015 Dulio Denis. All rights reserved. // import UIKit import iAd import AVFoundation import GameKit class MenuVC: UIViewController, GKGameCenterControllerDelegate { var click: AVAudioPlayer! // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() authenticateLocalPlayer() addSound() canDisplayBannerAds = true } // MARK: Button Actions @IBAction func playButton(sender: AnyObject) { click.play() let gameVC = storyboard?.instantiateViewControllerWithIdentifier("GameViewController") as! GameViewController gameVC.continueMode = false presentViewController(gameVC, animated: true, completion: nil) } @IBAction func continueButton(sender: AnyObject) { click.play() let gameVC = storyboard?.instantiateViewControllerWithIdentifier("GameViewController") as! GameViewController gameVC.continueMode = true presentViewController(gameVC, animated: true, completion: nil) } @IBAction func leaderboardButton(sender: AnyObject) { click.play() showLeaderboard() } // MARK: AVAudioPlayer Utility Function func addSound() { // AudioPlayer for Button Click do { try click = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("click", ofType: "wav")!)) click.prepareToPlay() } catch let error as NSError { print(error.debugDescription) } } // MARK: Game Center Functions func authenticateLocalPlayer() { let localPlayer = GKLocalPlayer.localPlayer() localPlayer.authenticateHandler = {(viewController, error) -> Void in if (viewController != nil) { self.presentViewController(viewController!, animated: true, completion: nil) } else { print((GKLocalPlayer.localPlayer().authenticated)) } } } func showLeaderboard() { let vc = self.view?.window?.rootViewController let gc = GKGameCenterViewController() gc.gameCenterDelegate = self vc?.presentViewController(gc, animated: true, completion: nil) } func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) { gameCenterViewController.dismissViewControllerAnimated(true, completion: nil) } }
mit
0b6ffcd5dc015fce00cf864e7e8f72d6
26.387755
140
0.624814
5.591667
false
false
false
false
GraphQLSwift/GraphQL
Tests/GraphQLTests/StarWarsTests/StarWarsSchema.swift
1
8939
import GraphQL /** * This is designed to be an end-to-end test, demonstrating * the full GraphQL stack. * * We will create a GraphQL schema that describes the major * characters in the original Star Wars trilogy. * * NOTE: This may contain spoilers for the original Star * Wars trilogy. */ /** * Using our shorthand to describe type systems, the type system for our * Star Wars example is: * * enum Episode { NEWHOPE, EMPIRE, JEDI } * * interface Character { * id: String! * name: String * friends: [Character] * appearsIn: [Episode] * } * * type Human : Character { * id: String! * name: String * friends: [Character] * appearsIn: [Episode] * homePlanet: String * } * * type Droid : Character { * id: String! * name: String * friends: [Character] * appearsIn: [Episode] * primaryFunction: String * } * * type Query { * hero(episode: Episode): Character * human(id: String!): Human * droid(id: String!): Droid * } * * We begin by setting up our schema. */ /** * The original trilogy consists of three movies. * * This implements the following type system shorthand: * enum Episode { NEWHOPE, EMPIRE, JEDI } */ let EpisodeEnum = try! GraphQLEnumType( name: "Episode", description: "One of the films in the Star Wars Trilogy", values: [ "NEWHOPE": GraphQLEnumValue( value: Map(Episode.newHope.rawValue), description: "Released in 1977." ), "EMPIRE": GraphQLEnumValue( value: Map(Episode.empire.rawValue), description: "Released in 1980." ), "JEDI": GraphQLEnumValue( value: Map(Episode.jedi.rawValue), description: "Released in 1983." ), ] ) /** * Characters in the Star Wars trilogy are either humans or droids. * * This implements the following type system shorthand: * interface Character { * id: String! * name: String * friends: [Character] * appearsIn: [Episode] * secretBackstory: String * } */ let CharacterInterface = try! GraphQLInterfaceType( name: "Character", description: "A character in the Star Wars Trilogy", fields: [ "id": GraphQLField( type: GraphQLNonNull(GraphQLString), description: "The id of the character." ), "name": GraphQLField( type: GraphQLString, description: "The name of the character." ), "friends": GraphQLField( type: GraphQLList(GraphQLTypeReference("Character")), description: "The friends of the character, or an empty list if they have none." ), "appearsIn": GraphQLField( type: GraphQLList(EpisodeEnum), description: "Which movies they appear in." ), "secretBackstory": GraphQLField( type: GraphQLString, description: "All secrets about their past." ), ], resolveType: { character, _, _ in switch character { case is Human: return "Human" default: return "Droid" } } ) /** * We define our human type, which implements the character interface. * * This implements the following type system shorthand: * type Human : Character { * id: String! * name: String * friends: [Character] * appearsIn: [Episode] * secretBackstory: String * } */ let HumanType = try! GraphQLObjectType( name: "Human", description: "A humanoid creature in the Star Wars universe.", fields: [ "id": GraphQLField( type: GraphQLNonNull(GraphQLString), description: "The id of the human." ), "name": GraphQLField( type: GraphQLString, description: "The name of the human." ), "friends": GraphQLField( type: GraphQLList(CharacterInterface), description: "The friends of the human, or an empty list if they " + "have none.", resolve: { human, _, _, _ in getFriends(character: human as! Human) } ), "appearsIn": GraphQLField( type: GraphQLList(EpisodeEnum), description: "Which movies they appear in." ), "homePlanet": GraphQLField( type: GraphQLString, description: "The home planet of the human, or null if unknown." ), "secretBackstory": GraphQLField( type: GraphQLString, description: "Where are they from and how they came to be who they are.", resolve: { _, _, _, _ in struct Secret: Error, CustomStringConvertible { let description: String } throw Secret(description: "secretBackstory is secret.") } ), ], interfaces: [CharacterInterface], isTypeOf: { source, _, _ in source is Human } ) /** * The other type of character in Star Wars is a droid. * * This implements the following type system shorthand: * type Droid : Character { * id: String! * name: String * friends: [Character] * appearsIn: [Episode] * secretBackstory: String * primaryFunction: String * } */ let DroidType = try! GraphQLObjectType( name: "Droid", description: "A mechanical creature in the Star Wars universe.", fields: [ "id": GraphQLField( type: GraphQLNonNull(GraphQLString), description: "The id of the droid." ), "name": GraphQLField( type: GraphQLString, description: "The name of the droid." ), "friends": GraphQLField( type: GraphQLList(CharacterInterface), description: "The friends of the droid, or an empty list if they have none.", resolve: { droid, _, _, _ in getFriends(character: droid as! Droid) } ), "appearsIn": GraphQLField( type: GraphQLList(EpisodeEnum), description: "Which movies they appear in." ), "secretBackstory": GraphQLField( type: GraphQLString, description: "Construction date and the name of the designer.", resolve: { _, _, _, _ in struct SecretError: Error, CustomStringConvertible { let description: String } throw SecretError(description: "secretBackstory is secret.") } ), "primaryFunction": GraphQLField( type: GraphQLString, description: "The primary function of the droid." ), ], interfaces: [CharacterInterface], isTypeOf: { source, _, _ in source is Droid } ) /** * This is the type that will be the root of our query, and the * entry point into our schema. It gives us the ability to fetch * objects by their IDs, as well as to fetch the undisputed hero * of the Star Wars trilogy, R2-D2, directly. * * This implements the following type system shorthand: * type Query { * hero(episode: Episode): Character * human(id: String!): Human * droid(id: String!): Droid * } * */ let QueryType = try! GraphQLObjectType( name: "Query", fields: [ "hero": GraphQLField( type: CharacterInterface, args: [ "episode": GraphQLArgument( type: EpisodeEnum, description: "If omitted, returns the hero of the whole saga. If " + "provided, returns the hero of that particular episode." ), ], resolve: { _, arguments, _, _ in let episode = Episode(arguments["episode"].string) return getHero(episode: episode) } ), "human": GraphQLField( type: HumanType, args: [ "id": GraphQLArgument( type: GraphQLNonNull(GraphQLString), description: "id of the human" ), ], resolve: { _, arguments, _, _ in getHuman(id: arguments["id"].string!) } ), "droid": GraphQLField( type: DroidType, args: [ "id": GraphQLArgument( type: GraphQLNonNull(GraphQLString), description: "id of the droid" ), ], resolve: { _, arguments, _, _ in getDroid(id: arguments["id"].string!) } ), ] ) /** * Finally, we construct our schema (whose starting query type is the query * type we defined above) and export it. */ let starWarsSchema = try! GraphQLSchema( query: QueryType, types: [HumanType, DroidType] )
mit
e98e6b561d24330e395d767d9e9ec87e
28.212418
92
0.556102
4.366878
false
false
false
false
Constructor-io/constructorio-client-swift
AutocompleteClientTests/FW/Logic/Worker/ConstructorIOTrackBrowseResultClickTests.swift
1
7856
// // ConstructorIOTrackBrowseResultClickTests.swift // Constructor.io // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import XCTest import OHHTTPStubs import ConstructorAutocomplete class ConstructorIOTrackBrowseResultClickTests: XCTestCase { var constructor: ConstructorIO! override func setUp() { super.setUp() self.constructor = TestConstants.testConstructor() } override func tearDown() { super.tearDown() OHHTTPStubs.removeAllStubs() } func testTrackBrowseResultClick() { let filterName = "potato" let filterValue = "russet" let customerID = "customerID123" let builder = CIOBuilder(expectation: "Calling trackBrowseResultClick should send a valid request with a default section name.", builder: http(200)) stub(regex("https://ac.cnstrc.com/v2/behavioral_action/browse_result_click?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&s=\(kRegexSession)"), builder.create()) self.constructor.trackBrowseResultClick(customerID: customerID, filterName: filterName, filterValue: filterValue, resultPositionOnPage: nil, sectionName: nil) self.wait(for: builder.expectation) } func testTrackBrowseResultClick_WithSection() { let filterName = "potato" let filterValue = "russet" let customerID = "customerID123" let sectionName = "Search Suggestions" let builder = CIOBuilder(expectation: "Calling trackBrowseResultClick should send a valid request with a section name.", builder: http(200)) stub(regex("https://ac.cnstrc.com/v2/behavioral_action/browse_result_click?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&s=\(kRegexSession)"), builder.create()) self.constructor.trackBrowseResultClick(customerID: customerID, filterName: filterName, filterValue: filterValue, resultPositionOnPage: nil, sectionName: sectionName) self.wait(for: builder.expectation) } func testTrackBrowseResultClick_WithVariationID() { let filterName = "potato" let filterValue = "russet" let customerID = "customerID123" let variationID = "variationID456" let sectionName = "Search Suggestions" let builder = CIOBuilder(expectation: "Calling trackBrowseResultClick should send a valid request with a section name.", builder: http(200)) stub(regex("https://ac.cnstrc.com/v2/behavioral_action/browse_result_click?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&s=\(kRegexSession)"), builder.create()) self.constructor.trackBrowseResultClick(customerID: customerID, variationID: variationID, filterName: filterName, filterValue: filterValue, resultPositionOnPage: nil, sectionName: sectionName) self.wait(for: builder.expectation) } func testTrackBrowseResultClick_WithResultID() { let filterName = "potato" let filterValue = "russet" let customerID = "customerID123" let resultID = "0123456789" let builder = CIOBuilder(expectation: "Calling trackBrowseResultClick should send a valid request with a section name.", builder: http(200)) stub(regex("https://ac.cnstrc.com/v2/behavioral_action/browse_result_click?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&s=\(kRegexSession)"), builder.create()) self.constructor.trackBrowseResultClick(customerID: customerID, filterName: filterName, filterValue: filterValue, resultPositionOnPage: nil, sectionName: nil, resultID: resultID) self.wait(for: builder.expectation) } func testTrackBrowseResultClick_WithSectionFromConfig() { let filterName = "potato" let filterValue = "russet" let customerID = "customerID123" let sectionName = "section321" let builder = CIOBuilder(expectation: "Calling trackBrowseResultClick should send a valid request with a section name.", builder: http(200)) stub(regex("https://ac.cnstrc.com/v2/behavioral_action/browse_result_click?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&s=\(kRegexSession)"), builder.create()) let config = ConstructorIOConfig(apiKey: TestConstants.testApiKey, defaultItemSectionName: sectionName) let constructor = TestConstants.testConstructor(config) constructor.trackBrowseResultClick(customerID: customerID, filterName: filterName, filterValue: filterValue, resultPositionOnPage: nil, sectionName: nil) self.wait(for: builder.expectation) } func testTrackBrowseResultClick_With400() { let expectation = self.expectation(description: "Calling trackBrowseResultClick with 400 should return badRequest CIOError.") let filterName = "potato" let filterValue = "russet" let customerID = "customerID123" stub(regex("https://ac.cnstrc.com/v2/behavioral_action/browse_result_click?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&s=\(kRegexSession)"), http(400)) self.constructor.trackBrowseResultClick(customerID: customerID, filterName: filterName, filterValue: filterValue, resultPositionOnPage: nil, sectionName: nil, completionHandler: { response in if let cioError = response.error as? CIOError { XCTAssertEqual(cioError.errorType, .badRequest, "If tracking call returns status code 400, the error should be delegated to the completion handler") expectation.fulfill() } }) self.wait(for: expectation) } func testTrackBrowseResultClick_With500() { let expectation = self.expectation(description: "Calling trackBrowseResultClick with 500 should return internalServerError CIOError.") let filterName = "potato" let filterValue = "russet" let customerID = "customerID123" stub(regex("https://ac.cnstrc.com/v2/behavioral_action/browse_result_click?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&s=\(kRegexSession)"), http(500)) self.constructor.trackBrowseResultClick(customerID: customerID, filterName: filterName, filterValue: filterValue, resultPositionOnPage: nil, sectionName: nil, completionHandler: { response in if let cioError = response.error as? CIOError { XCTAssertEqual(cioError.errorType, .internalServerError, "If tracking call returns status code 500, the error should be delegated to the completion handler") expectation.fulfill() } }) self.wait(for: expectation) } func testTrackBrowseResultClick_WithNoConnectivity() { let expectation = self.expectation(description: "Calling trackBrowseResultClick with no connectvity should return noConnectivity CIOError.") let filterName = "potato" let filterValue = "russet" let customerID = "customerID123" stub(regex("https://ac.cnstrc.com/v2/behavioral_action/browse_result_click?_dt=\(kRegexTimestamp)&c=\(kRegexVersion)&i=\(kRegexClientID)&key=\(kRegexAutocompleteKey)&s=\(kRegexSession)"), noConnectivity()) self.constructor.trackBrowseResultClick(customerID: customerID, filterName: filterName, filterValue: filterValue, resultPositionOnPage: nil, sectionName: nil, completionHandler: { response in if let cioError = response.error as? CIOError { XCTAssertEqual(cioError.errorType, .noConnection, "If tracking call returns no connectivity, the error should be delegated to the completion handler") expectation.fulfill() } }) self.wait(for: expectation) } }
mit
330877c8940bc3e5756bcb9088b2d5a7
60.367188
213
0.71725
4.349391
false
true
false
false
gregomni/swift
test/Generics/concrete_conformance_rule_simplified.swift
3
790
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on -disable-requirement-machine-concrete-contraction 2>&1 | %FileCheck %s protocol P1 {} protocol P2 { associatedtype T: P1 } protocol P3: P1 {} protocol P4: P3 {} protocol P5: P2 { associatedtype U: P5 where U.T: P4 } protocol P6: P1 { associatedtype V: P6 & P4 } struct C: P6 & P4 { typealias V = C } struct G1<T: P6>: P5 { typealias U = G1<T.V> } struct G2<T: P5> where T.T: P4 {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=G2 // CHECK-NEXT: Generic signature: <T where T == G1<C>> extension G2 where T == G1<C> {}
apache-2.0
0be1d8bf526fdd32597b6765983812b6
22.235294
185
0.682278
2.831541
false
false
false
false
oguntli/swift-grant-o-meter
Sources/libgrumpy/Models/QueriedUsers.swift
2
1912
// // Copyright 2016-2017 Oliver Guntli // // 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 Vapor import Fluent import Foundation import HTTP /// This is a model struct, to contain and manage different queries to find users public struct QueriedUsers: ResponseRepresentable { let allFoundUsers: [User] /// Find users by searching for names or parts of names /// - parameter name: the name or part of the name to look for init?(by name: String) throws { self.allFoundUsers = try User.query().filter("user_name", contains: name).all() } /// Make a response for the queried user object. /// Instead of convert the members as usually, this method is also responsible to sort /// the query results. public func makeResponse() throws -> Response { //allFoundUsers.count var allusers: [(user: String, level: Double, other: Double, ldate: Double)] = [] for user in allFoundUsers { let selfMeas = try user.latestSelfRating() let otherMeas = try user.latestOtherRating() let date: Double if (selfMeas.grumpydate > otherMeas.grumpydate) { date = selfMeas.grumpydate } else { date = otherMeas.grumpydate } allusers.append((user.userName.value, selfMeas.currentLevel, otherMeas.currentLevel, date )) } allusers.sort(by: { return $0.ldate > $1.ldate } ) let returnValue = try allusers.map { try JSON(node: ["user_name": $0.user, "level": $0.level, "rating": $0.other, "grumpydate": $0.ldate] )} return try JSON(returnValue).makeResponse() } }
mpl-2.0
e51bb0f33caeba89ed1d1e78f6957fab
35.075472
107
0.612971
4.025263
false
false
false
false
aboutsajjad/Bridge
Bridge/API/URLSession.swift
1
742
// // URLSession.swift // Bridge // // Created by Sajjad Aboutalebi on 3/9/18. // Copyright © 2018 Sajjad Aboutalebi. All rights reserved. // import Foundation extension URLSession { func synchronousDataTask(with url: URL) -> (Data?, URLResponse?, Error?) { var data: Data? var response: URLResponse? var error: Error? let semaphore = DispatchSemaphore(value: 0) let dataTask = self.dataTask(with: url) { data = $0 response = $1 error = $2 semaphore.signal() } dataTask.resume() _ = semaphore.wait(timeout: .distantFuture) return (data, response, error) } }
mit
6d3a880af7073f30d461c2f88a0412f5
22.15625
78
0.54251
4.30814
false
false
false
false
leytzher/LemonadeStand_v2
LemonadeStandv2/Balance.swift
1
344
// // Balance.swift // LemonadeStandv2 // // Created by Leytzher on 1/24/15. // Copyright (c) 2015 Leytzher. All rights reserved. // import Foundation import UIKit class Balance{ var money = 0.0 var lemons = 0 var iceCubes = 0 var lemonsUsed = 0 var iceCubesUsed = 0 var lemonsInCart = 0 var iceCubesInCart = 0 var inStock = 0 }
gpl-2.0
532bae38886e9ee503672053ca123003
14.636364
53
0.686047
2.606061
false
false
false
false
ztyjr888/WeChat
WeChat/Plugins/KeyBoard/WeChatCustomKeyBordView.swift
1
27919
// // WeChatCustomKeyBord.swift // WeChat // // Created by Smile on 16/1/27. // Copyright © 2016年 [email protected]. All rights reserved. // import UIKit //自定义聊天键盘 class WeChatCustomKeyBordView: UIView,UITextViewDelegate{ var bgColor:UIColor! var isLayedOut:Bool = false var topView:UIView! var textView:PlaceholderTextView!//多行输入 let topOrBottomPadding:CGFloat = 7//上边空白 let leftPadding:CGFloat = 10//左边空白 let kAnimationDuration:NSTimeInterval = 0.2//动画时间 var biaoQing:UIImageView! let biaoQingPadding:CGFloat = 15 var isBiaoQingDialogShow:Bool = false//是否显示表情对话框 var biaoQingDialog:WeChatEmojiDialogView? var defaultHeight:CGFloat = 47//默认高度 let biaoQingHeight:CGFloat = 220//表情对话框高度 var delegate:WeChatEmojiDialogBottomDelegate? var height:CGFloat = 0//总高度 var textViewHeight:CGFloat = 0//textView高度 var textViewWidth:CGFloat = 0//textView宽度 let defaultLine:Int = 4 var placeholderText:String? init(placeholderText:String?){ self.height = UIScreen.mainScreen().bounds.height - defaultHeight let frame = CGRectMake(0, self.height, UIScreen.mainScreen().bounds.width, defaultHeight) super.init(frame: frame) if placeholderText != nil { if !placeholderText!.isEmpty { self.placeholderText = placeholderText } } //定义通知,获取键盘高度 NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillAppear:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillDisappear:", name: UIKeyboardWillHideNotification, object: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARKS: 键盘弹起事件的时候隐藏表情对话框 func keyboardWillAppear(notification: NSNotification) { let keyboardInfo = notification.userInfo![UIKeyboardFrameEndUserInfoKey] let keyboardHeight:CGFloat = (keyboardInfo?.CGRectValue.size.height)! /* //键盘偏移量 let userInfo = notification.userInfo! let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey]?.floatValue let beginKeyboardRect = userInfo[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue let endKeyboardRect = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue let yOffset = endKeyboardRect!.origin.y - beginKeyboardRect!.origin.y*/ //隐藏表情对话框 if self.biaoQingDialog != nil { if isBiaoQingDialogShow { self.biaoQingDialog?.removeFromSuperview() self.biaoQing.image = UIImage(named: "rightImg") isBiaoQingDialogShow = false } } animation(self.frame.origin.x, y: UIScreen.mainScreen().bounds.height - self.topOrBottomPadding * 2 - self.textView.frame.height - keyboardHeight) } //MARKS: 键盘落下事件 func keyboardWillDisappear(notification:NSNotification){ if self.textView != nil { animation(self.frame.origin.x, y: UIScreen.mainScreen().bounds.height - self.topOrBottomPadding * 2 - self.textView.frame.height) } } //MARKS: 导航条返回 func navigationBackClick(){ self.frame.origin = CGPointMake(self.frame.origin.x,UIScreen.mainScreen().bounds.height - self.frame.height) self.textView.resignFirstResponder() } //MARKS: TextView动画 func animation(x:CGFloat,y:CGFloat){ UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(kAnimationDuration) self.frame.origin = CGPointMake(x, y) UIView.commitAnimations() } func animation(rect:CGRect){ UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(kAnimationDuration) self.frame = rect UIView.commitAnimations() } override func layoutSubviews() { super.layoutSubviews() if !isLayedOut { self.backgroundColor = UIColor.whiteColor() create() self.textView.resignFirstResponder() self.isLayedOut = true } } func create(){ createLineOnTop() createTopView() } //MARKS: 创建顶部view func createTopView(){ //创建输入框 createTextView() //创建输入框边上的表情 createBiaoQing() self.topView = UIView() topView.frame = CGRectMake(0, 0, self.frame.width, defaultHeight) topView.addSubview(self.textView) topView.addSubview(self.biaoQing) self.addSubview(topView) } //MARKS: 创建TextView func createTextView(){ self.textViewHeight = defaultHeight - topOrBottomPadding * 2 self.textViewWidth = UIScreen.mainScreen().bounds.width - leftPadding - biaoQingPadding * 2 - self.textViewHeight let frame = CGRectMake(leftPadding, topOrBottomPadding,self.textViewWidth, textViewHeight) self.textView = PlaceholderTextView(frame: frame,placeholder: self.placeholderText,color: nil,font: nil) self.textView.layer.borderWidth = 0.5 //边框粗细 self.textView.layer.borderColor = UIColor(red: 204/255, green: 204/255, blue: 204/255, alpha: 1).CGColor //边框颜色 self.textView.editable = true//是否可编辑 self.textView.selectable = true//是否可选 self.textView.dataDetectorTypes = .None//给文字中的电话号码和网址自动加链接,这里不需要添加 self.textView.returnKeyType = .Done self.textView.font = UIFont(name: "AlNile", size: 16) //设置不可以滚动 self.textView.showsVerticalScrollIndicator = false self.textView.showsHorizontalScrollIndicator = false self.textView.autoresizingMask = .FlexibleHeight //不允许滚动,当textview的大小足以容纳它的text的时候,需要设置scrollEnabed为NO,否则会出现光标乱滚动的情况 self.textView.scrollEnabled = false self.textView.scrollsToTop = false //设置圆角 self.textView.layer.cornerRadius = 4 self.textView.layer.masksToBounds = true self.textView.delegate = self //self.textView.selectedRange = NSMakeRange(0,0) ; //起始位置 //设置行距 /*let style = NSMutableParagraphStyle() style.lineSpacing = 8//行距 let attributes:NSDictionary = NSDictionary(object: style, forKey: NSParagraphStyleAttributeName) self.textView.attributedText = NSAttributedString(string: self.textView.text, attributes: attributes as? [String : AnyObject])*/ } //MARKS: 创建输入框边上的表情 func createBiaoQing(){ self.biaoQing = UIImageView() self.biaoQing.frame = CGRectMake(self.textView.frame.origin.x + self.textView.frame.width + self.biaoQingPadding, self.textView.frame.origin.y, self.textView.frame.height, self.textView.frame.height) self.biaoQing.image = UIImage(named: "rightImg") self.biaoQing.userInteractionEnabled = true self.biaoQing.addGestureRecognizer(WeChatUITapGestureRecognizer(target: self, action: "createBiaoQing:")) } //MARKS: 表情点击事件 func createBiaoQing(gestrue: WeChatUITapGestureRecognizer){ let imageView = gestrue.view as! UIImageView if !isBiaoQingDialogShow { imageView.image = UIImage(named: "rightImgChange") isBiaoQingDialogShow = true self.textView.resignFirstResponder() let frameBeginY:CGFloat = UIScreen.mainScreen().bounds.height - self.biaoQingHeight - self.textView.frame.height - topOrBottomPadding * 2 animation(CGRectMake(self.frame.origin.x,frameBeginY , UIScreen.mainScreen().bounds.width, self.defaultHeight + biaoQingHeight)) if biaoQingDialog != nil { self.biaoQingDialog?.removeFromSuperview() } let labelHeight:CGFloat = getTextViewTextBoundingHeight(self.textView.text) let numLine:Int = Int(ceil(labelHeight / getOneCharHeight())) //添加表情对话框 var beginY:CGFloat = 0 if numLine == 1 { beginY = self.textView.frame.origin.y + self.textView.frame.height - self.topOrBottomPadding * 2 } else if numLine > 1 { beginY = self.frame.height - self.biaoQingHeight + topOrBottomPadding + 5 } biaoQingDialog = WeChatEmojiDialogView(frame: CGRectMake(0,beginY, UIScreen.mainScreen().bounds.width,biaoQingHeight),keyboardView:self) self.addSubview(biaoQingDialog!) self.bringSubviewToFront(biaoQingDialog!) self.biaoQingDialog?.delegate = self.delegate } else { imageView.image = UIImage(named: "rightImg") isBiaoQingDialogShow = false self.textView.resignFirstResponder() if self.biaoQingDialog != nil { self.biaoQingDialog?.removeFromSuperview() } animation(CGRectMake(self.frame.origin.x, UIScreen.mainScreen().bounds.height - self.topOrBottomPadding * 2 - self.textView.frame.height, UIScreen.mainScreen().bounds.width, self.textView.frame.height + self.topOrBottomPadding * 2)) } } //MARKS: 顶部画线 func createLineOnTop(){ let shape = WeChatDrawView().drawLine(beginPointX: 0, beginPointY: 0, endPointX: self.frame.width, endPointY: 0,color:UIColor(red: 153/255, green: 153/255, blue: 153/255, alpha: 1)) shape.lineWidth = 0.2 self.layer.addSublayer(shape) } //MARKS: 自定义选择内容后的菜单 func addSelectCustomMenu(){ } func getOneCharHeight() ->CGFloat{ return getTextViewTextBoundingHeight("我") } //MARSK: 去掉回车,限制UITextView的行数 func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if text == "\n" { self.textView.resignFirstResponder() return false } let labelHeight:CGFloat = getTextViewTextBoundingHeight(self.textView.text + text) let numLine:Int = Int(ceil(labelHeight / getOneCharHeight())) if numLine > defaultLine { self.textView.text = (self.textView.text as NSString).substringToIndex(self.textView.text.characters.count) return false } return true } //触摸空白处隐藏键盘 //MARKS: 当空字符的时候重绘placeholder func textViewDidChange(textView: UITextView) { if textView.text.isEmpty { //self.textView.resetCur(self.textView.caretRectForPosition(textView.selectedTextRange!.start)) self.textView.removeFromSuperview() //createTextView() self.topView.addSubview(self.textView) self.textView.becomeFirstResponder() } //自动增加textView高度 getTextViewHeight(textView.text) } //MARKS: 获取文字高度 func getTextViewTextBoundingHeight(text:String) -> CGFloat{ let contentSize = CGSizeMake(self.textView.frame.width,CGFloat(MAXFLOAT)) let options : NSStringDrawingOptions = [.UsesLineFragmentOrigin,.UsesFontLeading] let labelHeight = text.boundingRectWithSize(contentSize, options: options, attributes: [NSFontAttributeName:self.textView.font!], context: nil).size.height return labelHeight } var originHeight:CGFloat = 0 var beginY:CGFloat = 0 //MARKS: 自动增加textView高度 func getTextViewHeight(text:String){ if originHeight == 0 { originHeight = self.frame.height beginY = self.frame.origin.y } let contentSize = CGSizeMake(self.textView.frame.width,CGFloat(MAXFLOAT)) let labelHeight:CGFloat = getTextViewTextBoundingHeight(text) var numLine:Int = 1//显示行数 numLine = Int(ceil(labelHeight / self.textViewHeight)) var size = self.textView.sizeThatFits(contentSize) if numLine > 4 { size.height = labelHeight } if labelHeight != self.textView.frame.height && labelHeight > self.textViewHeight{ //重新设置textView textView.frame = CGRectMake(leftPadding, topOrBottomPadding, textViewWidth, size.height) //重新设置框架frame let _padding:CGFloat = size.height - self.textViewHeight self.frame = CGRectMake(self.frame.origin.x, beginY - _padding, self.frame.width, originHeight + _padding) //重新设置biaoQing //self.biaoQing.frame = CGRectMake(self.biaoQing.frame.origin.x, self.textView.frame.height - self.topOrBottomPadding - self.biaoQing.frame.height, self.biaoQing.frame.width, self.biaoQing.frame.height) /*let labelHeight:CGFloat = getTextViewTextBoundingHeight(self.textView.text) let numLine:Int = Int(ceil(labelHeight / getOneCharHeight())) //添加表情对话框 var _beginY:CGFloat = 0 if numLine == 1 { _beginY = self.textView.frame.origin.y + self.textView.frame.height - self.topOrBottomPadding * 2 } else if numLine > 1 { _beginY = self.frame.height - self.biaoQingHeight + topOrBottomPadding + 5 } //重新设置biaoQingDialog self.biaoQingDialog?.frame.origin = CGPoint(x: (self.biaoQingDialog?.frame.origin.x)!, y: _beginY)*/ } } } protocol WeChatEmojiDialogBottomDelegate { func addBottom() -> UIView } //表情对话框 class WeChatEmojiDialogView:UIView,UIScrollViewDelegate{ var isLayedOut:Bool = false var dialogLeftPadding:CGFloat = 25 var dialogTopPadding:CGFloat = 15 var emojiWidth:CGFloat = 32 var emojiHeight:CGFloat = 32 var emoji:Emoji! var scrollView:UIScrollView! var pageControl:UIPageControl! var pageCount:Int = 0 let pageControlHeight:CGFloat = 10 let onePageCount:Int = 23 let pageControlWidth:CGFloat = 100 let bottomHeight:CGFloat = 40 let bottomTopPadding:CGFloat = 10 var pageControlBeginY:CGFloat = 0 var delegate:WeChatEmojiDialogBottomDelegate! var bottomView:UIView! var keyboardView:WeChatCustomKeyBordView! init(frame:CGRect,keyboardView:WeChatCustomKeyBordView){ super.init(frame: frame) self.emoji = Emoji() //获取页数,向上取整数,如果直接用/会截断取整,需要转成Float self.pageCount = Int(ceilf(Float(self.emoji.emojiArray.count) / 23.0)) self.keyboardView = keyboardView } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() if !isLayedOut { createScrollView() self.bottomView = delegate.addBottom() self.addSubview(self.bottomView) isLayedOut = true } } func createScrollView(){ self.scrollView = UIScrollView() self.scrollView.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.width, self.frame.height - self.bottomHeight) self.scrollView.showsHorizontalScrollIndicator = false self.scrollView.showsVerticalScrollIndicator = false self.scrollView.scrollsToTop = false self.scrollView.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 244/255, alpha: 0.2) createDialog() self.addSubview(self.scrollView) createPageControl() } //MARKS: 创建PageControl func createPageControl(){ self.pageControl = UIPageControl() self.pageControl.frame = CGRectMake((self.frame.width - pageControlWidth) / 2, self.scrollView.frame.origin.y + self.scrollView.frame.height - bottomTopPadding - pageControlHeight, pageControlWidth, pageControlHeight) self.pageControl.currentPageIndicatorTintColor = UIColor.darkGrayColor() self.pageControl.pageIndicatorTintColor = UIColor(red: 221/255, green: 221/255, blue: 221/255, alpha: 1) self.pageControl.numberOfPages = self.pageCount self.addSubview(self.pageControl) self.bringSubviewToFront(self.pageControl) } func createDialog(){ //计算padding let leftPadding:CGFloat = (self.frame.width - emojiWidth * 8 - dialogLeftPadding * 2) / 7 let topPadding:CGFloat = (self.scrollView.frame.height - emojiHeight * 3 - dialogTopPadding * 2 - self.bottomTopPadding - self.pageControlHeight) / 2 var originX:CGFloat = self.dialogLeftPadding var originY:CGFloat = self.dialogTopPadding let totalCount:Int = emoji.emojiArray.count var x:CGFloat = 0 for(var i = 0;i < pageCount;i++){ let view = UIView() view.frame = CGRectMake(x, 0, self.frame.width, self.frame.height - pageControlHeight) for(var j = 0;j < totalCount - 1;j++){ if i * onePageCount + j > (totalCount - 1) { break } let weChatEmoji = emoji.emojiArray[i * onePageCount + j] let imageView = UIImageView() imageView.userInteractionEnabled = true if j % 8 == 0 && j != 0{ originY += (emojiHeight + topPadding) originX = self.dialogLeftPadding } if j != 0 && j % 8 != 0{ originX += (emojiWidth + leftPadding) } imageView.frame = CGRectMake(originX,originY,emojiWidth,emojiHeight) if (j % onePageCount == 0 && j != 0){ imageView.image = UIImage(named: "key-delete") addDeleteViewTap(imageView) if self.pageControlBeginY == 0 { self.pageControlBeginY = originY } originX = self.dialogLeftPadding originY = self.dialogTopPadding view.addSubview(imageView) break } else { if (i == pageCount - 1) && (i * onePageCount + j) == (totalCount - 1){ imageView.image = UIImage(named: "key-delete") }else{ imageView.image = weChatEmoji.image } } addImageViewTap(weChatEmoji, imageView: imageView) view.addSubview(imageView) } x += self.frame.width self.scrollView.addSubview(view) } //为了让内容横向滚动,设置横向内容宽度为N个页面的宽度总和 //不允许在垂直方向上进行滚动 self.scrollView.contentSize = CGSizeMake(CGFloat(UIScreen.mainScreen().bounds.width * CGFloat(self.pageCount)), 0) self.scrollView.pagingEnabled = true//滚动时只能停留到某一页 self.scrollView.delegate = self self.scrollView.userInteractionEnabled = true } //MARKS: 图片添加点击事件 func addImageViewTap(weChatEmoji:WeChatEmoji,imageView:UIImageView){ let tap = WeChatUITapGestureRecognizer(target:self,action: "imageViewTap:") tap.data = [] tap.data?.append(weChatEmoji.image) tap.data?.append(weChatEmoji.key) imageView.addGestureRecognizer(tap) } //MARKS:删除事件 func addDeleteViewTap(imageView:UIImageView){ let tap = WeChatUITapGestureRecognizer(target:self,action: "imageViewTap:") tap.data = [] tap.data?.append(imageView.image!) tap.data?.append("emoji_delete") imageView.addGestureRecognizer(tap) } func scrollViewDidScroll(scrollView: UIScrollView) { if (self.scrollView == scrollView){ let current:Int = Int(scrollView.contentOffset.x / UIScreen.mainScreen().bounds.size.width) //根据scrollView 的位置对page 的当前页赋值 self.pageControl.currentPage = current } } //MARKS: 图片点击事件 func imageViewTap(gestrue:WeChatUITapGestureRecognizer){ //let gestureView = gestrue.view as! UIImageView //查找数据 let weChatView = gestrue.data if weChatView != nil && weChatView?.count > 0{ //let image = weChatView![0] let key = weChatView![1] as! String let text = self.keyboardView.textView.text + key let labelHeight:CGFloat = self.keyboardView.getTextViewTextBoundingHeight(text) let numLine:Int = Int(ceil(labelHeight / self.keyboardView.getOneCharHeight())) if numLine > self.keyboardView.defaultLine { return } if key == "emoji_delete" {//删除键 deleteText() }else { self.keyboardView.textView.insertText(key) } } } //删除文本 func deleteText(){ let text = self.keyboardView.textView.text if text.isEmpty { return } let count:Int = text.characters.count if count > 2 { if text.hasSuffix("]"){ var index:Int = 3 var isDeleted:Bool = false for(var i = 0;i < 3;i++){ if i != 0 { index++ } let flag = getEmoji(text, count: count, index: index) if flag { isDeleted = true break } } //以上都不匹配,则删除最后一个字符 if !isDeleted { deleteLastOneChar(text, count: count) } }else{ deleteLastOneChar(text, count: count) } }else{ deleteLastOneChar(text, count: count) } if self.keyboardView.textView.text.isEmpty { self.keyboardView.textView.placeholderLabel!.hidden = false } } func deleteLastOneChar(text:String,count:Int){ let oneCharIndex:Int = count - 1 self.keyboardView.textView.text = (text as NSString).substringWithRange(NSMakeRange(0, oneCharIndex)) } func getEmoji(text:String,count:Int,index:Int) -> Bool{ let oneCharIndex:Int = count - index let oneChar = (text as NSString).substringFromIndex(oneCharIndex) if emoji.keys.indexOf(oneChar) != nil { self.keyboardView.textView.text = (text as NSString).substringWithRange(NSMakeRange(0, oneCharIndex)) return true } return false } } enum PlaceholderLocation { case Top,Center,Bottom } //自定义TextView Placeholder类 class PlaceholderTextView:UITextView,UITextViewDelegate { var placeholder:String? var color:UIColor? var fontSize:CGFloat = 18 var placeholderLabel:UILabel? var placeholderFont:UIFont? var isLayedOut:Bool = false var placeholderLabelHeight:CGFloat = 0 var defaultHeight:CGFloat = 0 var placeholderLocation:PlaceholderLocation = PlaceholderLocation.Center init(frame:CGRect,placeholder:String?,color:UIColor?,font:UIFont?){ super.init(frame: frame, textContainer: nil) self.defaultHeight = frame.height if placeholder != nil { self.placeholder = placeholder } if color != nil { self.color = color } else { self.color = UIColor.lightGrayColor() } if font != nil { self.font = font } else { self.font = UIFont.systemFontOfSize(fontSize) } if self.placeholder != nil && !self.placeholder!.isEmpty { initFrame() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func initFrame(){ self.backgroundColor = UIColor.clearColor() self.placeholderLabel = UILabel() placeholderLabel!.backgroundColor = UIColor.clearColor() placeholderLabel!.numberOfLines = 0//多行 if self.placeholder != nil { placeholderLabel?.text = self.placeholder } placeholderLabel?.font = self.font placeholderLabel?.textColor = self.color //根据字体的高度,计算上下空白 var labelHeight:CGFloat = 0 let labelWidth:CGFloat = self.frame.width - labelLeftPadding * 2 let maxSize = CGSizeMake(labelWidth,CGFloat(MAXFLOAT)) let options : NSStringDrawingOptions = [.UsesLineFragmentOrigin,.UsesFontLeading] labelHeight = self.placeholder!.boundingRectWithSize(maxSize, options: options, attributes: [NSFontAttributeName:self.font!], context: nil).size.height if placeholderLocation == PlaceholderLocation.Center { self.labelTopPadding = (self.frame.height - labelHeight) / 2 } else if placeholderLocation == PlaceholderLocation.Bottom { self.labelTopPadding = self.frame.height - labelHeight } else if placeholderLocation == PlaceholderLocation.Top { } self.placeholderLabel!.frame = CGRectMake(labelLeftPadding, self.labelTopPadding,labelWidth , labelHeight) placeholderLabelHeight = labelHeight self.addSubview(placeholderLabel!) //监听文字变化 NSNotificationCenter.defaultCenter().addObserver(self, selector:"textDidChange", name: UITextViewTextDidChangeNotification , object: self) } //MARKS: 文字变化 func textDidChange(){ self.placeholderLabel!.hidden = self.hasText()//如果UITextView输入了文字,hasText就是YES,反之就为NO } let labelLeftPadding:CGFloat = 7 var labelTopPadding:CGFloat = 5 var curTopPadding:CGFloat = 5 //MARKS: 设置光标 override func caretRectForPosition(position: UITextPosition) -> CGRect { let originalRect = super.caretRectForPosition(position) let curHeight:CGFloat = self.defaultHeight - curTopPadding * 3 + 0.5 return CGRectMake(originalRect.origin.x, originalRect.origin.y, originalRect.width,curHeight) } //MARKS: 重置光标 /*func resetCur(originalRect:CGRect) -> CGRect{ var curTopPadding:CGFloat = 5 let rect = originalRect let curHeight:CGFloat = self.defaultHeight - curTopPadding * 2 if self.frame.height != self.defaultHeight { curTopPadding = self.frame.height - curHeight - curTopPadding } return CGRectMake(rect.origin.x, curTopPadding, rect.width, curHeight) }*/ func textViewDidBeginEditing(textView: UITextView) { print("cur focus...") } }
apache-2.0
046dd3ab9875ad066b5b7913aae40a95
37.270655
244
0.618179
4.632868
false
false
false
false
VBVMI/VerseByVerse-iOS
Pods/XCGLogger/Sources/XCGLogger/XCGLogger.swift
1
61437
// // XCGLogger.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2014-06-06. // Copyright © 2014 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // #if os(macOS) import AppKit #elseif os(iOS) || os(tvOS) || os(watchOS) import UIKit #endif // MARK: - XCGLogger /// The main logging class open class XCGLogger: CustomDebugStringConvertible { // MARK: - Constants public struct Constants { /// Prefix identifier to use for all other identifiers public static let baseIdentifier = "com.cerebralgardens.xcglogger" /// Identifier for the default instance of XCGLogger public static let defaultInstanceIdentifier = "\(baseIdentifier).defaultInstance" /// Identifer for the Xcode console destination public static let baseConsoleDestinationIdentifier = "\(baseIdentifier).logdestination.console" /// Identifier for the Apple System Log destination public static let systemLogDestinationIdentifier = "\(baseIdentifier).logdestination.console.nslog" /// Identifier for the file logging destination public static let fileDestinationIdentifier = "\(baseIdentifier).logdestination.file" /// Identifier for the default dispatch queue public static let logQueueIdentifier = "\(baseIdentifier).queue" /// UserInfo Key - tags public static let userInfoKeyTags = "\(baseIdentifier).tags" /// UserInfo Key - devs public static let userInfoKeyDevs = "\(baseIdentifier).devs" /// UserInfo Key - internal public static let userInfoKeyInternal = "\(baseIdentifier).internal" /// Library version number public static let versionString = "6.0.1" /// Internal userInfo internal static let internalUserInfo: [String: Any] = [XCGLogger.Constants.userInfoKeyInternal: true] /// Extended file attributed key to use when storing the logger's identifier on an archived log file public static let extendedAttributeArchivedLogIdentifierKey = "\(baseIdentifier).archived.by" /// Extended file attributed key to use when storing the time a log file was archived public static let extendedAttributeArchivedLogTimestampKey = "\(baseIdentifier).archived.at" } // MARK: - Enums /// Enum defining our log levels public enum Level: Int, Comparable, CustomStringConvertible { case verbose case debug case info case warning case error case severe case none public var description: String { switch self { case .verbose: return "Verbose" case .debug: return "Debug" case .info: return "Info" case .warning: return "Warning" case .error: return "Error" case .severe: return "Severe" case .none: return "None" } } public static let all: [Level] = [.verbose, .debug, .info, .warning, .error, .severe] } // MARK: - Default instance /// The default XCGLogger object open static var `default`: XCGLogger = { struct Statics { static let instance: XCGLogger = XCGLogger(identifier: XCGLogger.Constants.defaultInstanceIdentifier) } return Statics.instance }() // MARK: - Properties /// Identifier for this logger object (should be unique) open var identifier: String = "" /// The log level of this logger, any logs received at this level or higher will be output to the destinations open var outputLevel: Level = .debug { didSet { for index in 0 ..< destinations.count { destinations[index].outputLevel = outputLevel } } } /// Option: a closure to execute whenever a logging method is called without a log message open var noMessageClosure: () -> Any? = { return "" } /// Option: override descriptions of log levels open var levelDescriptions: [XCGLogger.Level: String] = [:] /// Array of log formatters to apply to messages before they're output open var formatters: [LogFormatterProtocol]? = nil /// Array of log filters to apply to messages before they're output open var filters: [FilterProtocol]? = nil /// The default dispatch queue used for logging open class var logQueue: DispatchQueue { struct Statics { static var logQueue = DispatchQueue(label: XCGLogger.Constants.logQueueIdentifier, attributes: []) } return Statics.logQueue } /// A custom date formatter object to use when displaying the dates of log messages (internal storage) internal var _customDateFormatter: DateFormatter? = nil /// The date formatter object to use when displaying the dates of log messages open var dateFormatter: DateFormatter? { get { guard _customDateFormatter == nil else { return _customDateFormatter } struct Statics { static var dateFormatter: DateFormatter = { let defaultDateFormatter = DateFormatter() defaultDateFormatter.locale = NSLocale.current defaultDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" return defaultDateFormatter }() } return Statics.dateFormatter } set { _customDateFormatter = newValue } } /// Array containing all of the destinations for this logger open var destinations: [DestinationProtocol] = [] // MARK: - Life Cycle public init(identifier: String = "", includeDefaultDestinations: Bool = true) { self.identifier = identifier if includeDefaultDestinations { // Setup a standard console destination add(destination: ConsoleDestination(identifier: XCGLogger.Constants.baseConsoleDestinationIdentifier)) } } // MARK: - Setup methods /// A shortcut method to configure the default logger instance. /// /// - Note: The function exists to get you up and running quickly, but it's recommended that you use the advanced usage configuration for most projects. See https://github.com/DaveWoodCom/XCGLogger/blob/master/README.md#advanced-usage-recommended /// /// - Parameters: /// - level: The log level of this logger, any logs received at this level or higher will be output to the destinations. **Default:** Debug /// - showLogIdentifier: Whether or not to output the log identifier. **Default:** false /// - showFunctionName: Whether or not to output the function name that generated the log. **Default:** true /// - showThreadName: Whether or not to output the thread's name the log was created on. **Default:** false /// - showLevel: Whether or not to output the log level of the log. **Default:** true /// - showFileNames: Whether or not to output the fileName that generated the log. **Default:** true /// - showLineNumbers: Whether or not to output the line number where the log was generated. **Default:** true /// - showDate: Whether or not to output the date the log was created. **Default:** true /// - writeToFile: FileURL or path (as String) to a file to log all messages to (this file is overwritten each time the logger is created). **Default:** nil => no log file /// - fileLevel: An alternate log level for the file destination. **Default:** nil => use the same log level as the console destination /// /// - Returns: Nothing /// open class func setup(level: Level = .debug, showLogIdentifier: Bool = false, showFunctionName: Bool = true, showThreadName: Bool = false, showLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: Any? = nil, fileLevel: Level? = nil) { self.default.setup(level: level, showLogIdentifier: showLogIdentifier, showFunctionName: showFunctionName, showThreadName: showThreadName, showLevel: showLevel, showFileNames: showFileNames, showLineNumbers: showLineNumbers, showDate: showDate, writeToFile: writeToFile) } /// A shortcut method to configure the logger. /// /// - Note: The function exists to get you up and running quickly, but it's recommended that you use the advanced usage configuration for most projects. See https://github.com/DaveWoodCom/XCGLogger/blob/master/README.md#advanced-usage-recommended /// /// - Parameters: /// - level: The log level of this logger, any logs received at this level or higher will be output to the destinations. **Default:** Debug /// - showLogIdentifier: Whether or not to output the log identifier. **Default:** false /// - showFunctionName: Whether or not to output the function name that generated the log. **Default:** true /// - showThreadName: Whether or not to output the thread's name the log was created on. **Default:** false /// - showLevel: Whether or not to output the log level of the log. **Default:** true /// - showFileNames: Whether or not to output the fileName that generated the log. **Default:** true /// - showLineNumbers: Whether or not to output the line number where the log was generated. **Default:** true /// - showDate: Whether or not to output the date the log was created. **Default:** true /// - writeToFile: FileURL or path (as String) to a file to log all messages to (this file is overwritten each time the logger is created). **Default:** nil => no log file /// - fileLevel: An alternate log level for the file destination. **Default:** nil => use the same log level as the console destination /// /// - Returns: Nothing /// open func setup(level: Level = .debug, showLogIdentifier: Bool = false, showFunctionName: Bool = true, showThreadName: Bool = false, showLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: Any? = nil, fileLevel: Level? = nil) { outputLevel = level if let standardConsoleDestination = destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) as? ConsoleDestination { standardConsoleDestination.showLogIdentifier = showLogIdentifier standardConsoleDestination.showFunctionName = showFunctionName standardConsoleDestination.showThreadName = showThreadName standardConsoleDestination.showLevel = showLevel standardConsoleDestination.showFileName = showFileNames standardConsoleDestination.showLineNumber = showLineNumbers standardConsoleDestination.showDate = showDate standardConsoleDestination.outputLevel = level } if let writeToFile: Any = writeToFile { // We've been passed a file to use for logging, set up a file logger let standardFileDestination: FileDestination = FileDestination(writeToFile: writeToFile, identifier: XCGLogger.Constants.fileDestinationIdentifier) standardFileDestination.showLogIdentifier = showLogIdentifier standardFileDestination.showFunctionName = showFunctionName standardFileDestination.showThreadName = showThreadName standardFileDestination.showLevel = showLevel standardFileDestination.showFileName = showFileNames standardFileDestination.showLineNumber = showLineNumbers standardFileDestination.showDate = showDate standardFileDestination.outputLevel = fileLevel ?? level add(destination: standardFileDestination) } logAppDetails() } // MARK: - Logging methods /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing /// open class func logln(_ closure: @autoclosure () -> Any?, level: Level = .debug, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(level, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing /// open class func logln(_ level: Level = .debug, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(level, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing /// open class func logln(_ level: Level = .debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(level, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing /// open func logln(_ closure: @autoclosure () -> Any?, level: Level = .debug, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(level, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing /// open func logln(_ level: Level = .debug, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { logln(level, functionName: String(describing: functionName), fileName: String(describing: fileName), lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing /// open func logln(_ level: Level = .debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { let enabledDestinations = destinations.filter({$0.isEnabledFor(level: level)}) guard enabledDestinations.count > 0 else { return } guard let closureResult = closure() else { return } let logDetails: LogDetails = LogDetails(level: level, date: Date(), message: String(describing: closureResult), functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo) for destination in enabledDestinations { destination.process(logDetails: logDetails) } } /// Execute some code only when at the specified log level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func exec(_ level: Level = .debug, closure: () -> () = {}) { self.default.exec(level, closure: closure) } /// Execute some code only when at the specified log level. /// /// - Parameters: /// - level: Specified log level **Default:** *Debug*. /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func exec(_ level: Level = .debug, closure: () -> () = {}) { guard isEnabledFor(level:level) else { return } closure() } /// Generate logs to display your app's vitals (app name, version, etc) as well as XCGLogger's version and log level. /// /// - Parameters: /// - selectedDestination: A specific destination to log the vitals on, if omitted, will log to all destinations /// /// - Returns: Nothing. /// open func logAppDetails(selectedDestination: DestinationProtocol? = nil) { let date = Date() var buildString = "" if let infoDictionary = Bundle.main.infoDictionary { if let CFBundleShortVersionString = infoDictionary["CFBundleShortVersionString"] as? String { buildString = "Version: \(CFBundleShortVersionString) " } if let CFBundleVersion = infoDictionary["CFBundleVersion"] as? String { buildString += "Build: \(CFBundleVersion) " } } let processInfo: ProcessInfo = ProcessInfo.processInfo let XCGLoggerVersionNumber = XCGLogger.Constants.versionString var logDetails: [LogDetails] = [] logDetails.append(LogDetails(level: .info, date: date, message: "\(processInfo.processName) \(buildString)PID: \(processInfo.processIdentifier)", functionName: "", fileName: "", lineNumber: 0, userInfo: XCGLogger.Constants.internalUserInfo)) logDetails.append(LogDetails(level: .info, date: date, message: "XCGLogger Version: \(XCGLoggerVersionNumber) - Level: \(outputLevel)", functionName: "", fileName: "", lineNumber: 0, userInfo: XCGLogger.Constants.internalUserInfo)) for var destination in (selectedDestination != nil ? [selectedDestination!] : destinations) where !destination.haveLoggedAppDetails { for logDetail in logDetails { guard destination.isEnabledFor(level:.info) else { continue } destination.haveLoggedAppDetails = true destination.processInternal(logDetails: logDetail) } } } // MARK: - Convenience logging methods // MARK: * Verbose /// Log something at the Verbose log level. This format of verbose() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func verbose(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Verbose log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func verbose(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Verbose log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func verbose(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Verbose log level. This format of verbose() isn't provided the object to log, instead the property *`noMessageClosure`* is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func verbose(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Verbose log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func verbose(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Verbose log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func verbose(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: * Debug /// Log something at the Debug log level. This format of debug() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func debug(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Debug log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func debug(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Debug log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func debug(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Debug log level. This format of debug() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func debug(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Debug log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func debug(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Debug log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func debug(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: * Info /// Log something at the Info log level. This format of info() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func info(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Info log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func info(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Info log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func info(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Info log level. This format of info() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func info(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Info log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func info(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Info log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func info(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: * Warning /// Log something at the Warning log level. This format of warning() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func warning(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Warning log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func warning(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Warning log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func warning(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Warning log level. This format of warning() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func warning(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Warning log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func warning(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Warning log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func warning(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: * Error /// Log something at the Error log level. This format of error() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func error(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Error log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func error(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Error log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func error(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Error log level. This format of error() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func error(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Error log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func error(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Error log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func error(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: * Severe /// Log something at the Severe log level. This format of severe() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func severe(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.default.noMessageClosure) } /// Log something at the Severe log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open class func severe(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.default.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Severe log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open class func severe(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.default.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Severe log level. This format of severe() isn't provided the object to log, instead the property `noMessageClosure` is executed instead. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func severe(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: self.noMessageClosure) } /// Log something at the Severe log level. /// /// - Parameters: /// - closure: A closure that returns the object to be logged. /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// /// - Returns: Nothing. /// open func severe(_ closure: @autoclosure () -> Any?, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:]) { self.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } /// Log something at the Severe log level. /// /// - Parameters: /// - functionName: Normally omitted **Default:** *#function*. /// - fileName: Normally omitted **Default:** *#file*. /// - lineNumber: Normally omitted **Default:** *#line*. /// - userInfo: Dictionary for adding arbitrary data to the log message, can be used by filters/formatters etc /// - closure: A closure that returns the object to be logged. /// /// - Returns: Nothing. /// open func severe(_ functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line, userInfo: [String: Any] = [:], closure: () -> Any?) { self.logln(.severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, userInfo: userInfo, closure: closure) } // MARK: - Exec Methods // MARK: * Verbose /// Execute some code only when at the Verbose log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func verboseExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.verbose, closure: closure) } /// Execute some code only when at the Verbose log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func verboseExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.verbose, closure: closure) } // MARK: * Debug /// Execute some code only when at the Debug or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func debugExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.debug, closure: closure) } /// Execute some code only when at the Debug or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func debugExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.debug, closure: closure) } // MARK: * Info /// Execute some code only when at the Info or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func infoExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.info, closure: closure) } /// Execute some code only when at the Info or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func infoExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.info, closure: closure) } // MARK: * Warning /// Execute some code only when at the Warning or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func warningExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.warning, closure: closure) } /// Execute some code only when at the Warning or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func warningExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.warning, closure: closure) } // MARK: * Error /// Execute some code only when at the Error or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func errorExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.error, closure: closure) } /// Execute some code only when at the Error or lower log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func errorExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.error, closure: closure) } // MARK: * Severe /// Execute some code only when at the Severe log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open class func severeExec(_ closure: () -> () = {}) { self.default.exec(XCGLogger.Level.severe, closure: closure) } /// Execute some code only when at the Severe log level. /// /// - Parameters: /// - closure: The code closure to be executed. /// /// - Returns: Nothing. /// open func severeExec(_ closure: () -> () = {}) { self.exec(XCGLogger.Level.severe, closure: closure) } // MARK: - Log destination methods /// Get the destination with the specified identifier. /// /// - Parameters: /// - identifier: Identifier of the destination to return. /// /// - Returns: The destination with the specified identifier, if one exists, nil otherwise. /// open func destination(withIdentifier identifier: String) -> DestinationProtocol? { for destination in destinations { if destination.identifier == identifier { return destination } } return nil } /// Add a new destination to the logger. /// /// - Parameters: /// - destination: The destination to add. /// /// - Returns: /// - true: Log destination was added successfully. /// - false: Failed to add the destination. /// @discardableResult open func add(destination: DestinationProtocol) -> Bool { var destination = destination let existingDestination: DestinationProtocol? = self.destination(withIdentifier: destination.identifier) if existingDestination != nil { return false } if let previousOwner = destination.owner { previousOwner.remove(destination: destination) } destination.owner = self destinations.append(destination) return true } /// Remove the destination from the logger. /// /// - Parameters: /// - destination: The destination to remove. /// /// - Returns: /// - true: Log destination was removed successfully. /// - false: Failed to remove the destination. /// @discardableResult open func remove(destination: DestinationProtocol) -> Bool { guard destination.owner === self else { return false } let existingDestination: DestinationProtocol? = self.destination(withIdentifier: destination.identifier) guard existingDestination != nil else { return false } // Make our parameter mutable var destination = destination destination.owner = nil destinations = destinations.filter({$0.owner != nil}) return true } /// Remove the destination with the specified identifier from the logger. /// /// - Parameters: /// - identifier: The identifier of the destination to remove. /// /// - Returns: /// - true: Log destination was removed successfully. /// - false: Failed to remove the destination. /// @discardableResult open func remove(destinationWithIdentifier identifier: String) -> Bool { guard let destination = destination(withIdentifier: identifier) else { return false } return remove(destination: destination) } // MARK: - Misc methods /// Check if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - level: The log level to check. /// /// - Returns: /// - true: Logger is at the log level specified or lower. /// - false: Logger is at a higher log levelss. /// open func isEnabledFor(level: XCGLogger.Level) -> Bool { return level >= self.outputLevel } // MARK: - Private methods /// Log a message if the logger's log level is equal to or lower than the specified level. /// /// - Parameters: /// - message: Message to log. /// - level: Specified log level. /// - source: The destination calling this method /// /// - Returns: Nothing /// internal func _logln(_ message: String, level: Level = .debug, source sourceDestination: DestinationProtocol? = nil) { let logDetails: LogDetails = LogDetails(level: level, date: Date(), message: message, functionName: "", fileName: "", lineNumber: 0, userInfo: XCGLogger.Constants.internalUserInfo) for destination in self.destinations { if level >= .error && sourceDestination?.identifier == destination.identifier { continue } if (destination.isEnabledFor(level: level)) { destination.processInternal(logDetails: logDetails) } } } // MARK: - DebugPrintable open var debugDescription: String { get { var description: String = "\(extractTypeName(self)): \(identifier) - destinations: \r" for destination in destinations { description += "\t \(destination.debugDescription)\r" } return description } } } // Implement Comparable for XCGLogger.Level public func < (lhs: XCGLogger.Level, rhs: XCGLogger.Level) -> Bool { return lhs.rawValue < rhs.rawValue }
mit
9f11d532bdf65df94e573ac7c2a8e44b
49.398687
299
0.625594
4.642636
false
false
false
false