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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gaurav1981/eidolon | Kiosk/Sale Artwork Details/SaleArtworkDetailsViewController.swift | 1 | 17170 | import UIKit
import ORStackView
import Artsy_UILabels
import Artsy_UIFonts
import ReactiveCocoa
import Artsy_UIButtons
import Swift_RAC_Macros
import SDWebImage
class SaleArtworkDetailsViewController: UIViewController {
var allowAnimations = true
var auctionID = AppSetup.sharedState.auctionID
var saleArtwork: SaleArtwork!
var showBuyersPremiumCommand = { () -> RACCommand in
appDelegate().showBuyersPremiumCommand()
}
class func instantiateFromStoryboard(storyboard: UIStoryboard) -> SaleArtworkDetailsViewController {
return storyboard.viewControllerWithID(.SaleArtworkDetail) as! SaleArtworkDetailsViewController
}
lazy var artistInfoSignal: RACSignal = {
let signal = XAppRequest(.Artwork(id: self.saleArtwork.artwork.id)).filterSuccessfulStatusCodes().mapJSON()
return signal.replayLast()
}()
@IBOutlet weak var metadataStackView: ORTagBasedAutoStackView!
@IBOutlet weak var additionalDetailScrollView: ORStackScrollView!
var buyersPremium: () -> (BuyersPremium?) = { appDelegate().sale.buyersPremium }
override func viewDidLoad() {
super.viewDidLoad()
setupMetadataView()
setupAdditionalDetailStackView()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == .ZoomIntoArtwork {
let nextViewController = segue.destinationViewController as! SaleArtworkZoomViewController
nextViewController.saleArtwork = saleArtwork
}
}
enum MetadataStackViewTag: Int {
case LotNumberLabel = 1
case ArtistNameLabel
case ArtworkNameLabel
case ArtworkMediumLabel
case ArtworkDimensionsLabel
case ImageRightsLabel
case EstimateTopBorder
case EstimateLabel
case EstimateBottomBorder
case CurrentBidLabel
case CurrentBidValueLabel
case NumberOfBidsPlacedLabel
case BidButton
case BuyersPremium
}
@IBAction func backWasPressed(sender: AnyObject) {
navigationController?.popViewControllerAnimated(true)
}
private func setupMetadataView() {
enum LabelType {
case Serif
case SansSerif
case ItalicsSerif
case Bold
}
func label(type: LabelType, tag: MetadataStackViewTag, fontSize: CGFloat = 16.0) -> UILabel {
let label: UILabel = { () -> UILabel in
switch type {
case .Serif:
return ARSerifLabel()
case .SansSerif:
return ARSansSerifLabel()
case .ItalicsSerif:
return ARItalicsSerifLabel()
case .Bold:
let label = ARSerifLabel()
label.font = UIFont.sansSerifFontWithSize(label.font.pointSize)
return label
}
}()
label.lineBreakMode = .ByWordWrapping
label.font = label.font.fontWithSize(fontSize)
label.tag = tag.rawValue
label.preferredMaxLayoutWidth = 276
return label
}
let hasLotNumber = (saleArtwork.lotNumber != nil)
if let _ = saleArtwork.lotNumber {
let lotNumberLabel = label(.SansSerif, tag: .LotNumberLabel)
lotNumberLabel.font = lotNumberLabel.font.fontWithSize(12)
metadataStackView.addSubview(lotNumberLabel, withTopMargin: "0", sideMargin: "0")
RAC(lotNumberLabel, "text") <~ saleArtwork.lotNumberSignal
}
if let artist = artist() {
let artistNameLabel = label(.SansSerif, tag: .ArtistNameLabel)
artistNameLabel.text = artist.name
metadataStackView.addSubview(artistNameLabel, withTopMargin: hasLotNumber ? "10" : "0", sideMargin: "0")
}
let artworkNameLabel = label(.ItalicsSerif, tag: .ArtworkNameLabel)
artworkNameLabel.text = "\(saleArtwork.artwork.title), \(saleArtwork.artwork.date)"
metadataStackView.addSubview(artworkNameLabel, withTopMargin: "10", sideMargin: "0")
if let medium = saleArtwork.artwork.medium {
if medium.isNotEmpty {
let mediumLabel = label(.Serif, tag: .ArtworkMediumLabel)
mediumLabel.text = medium
metadataStackView.addSubview(mediumLabel, withTopMargin: "22", sideMargin: "0")
}
}
if saleArtwork.artwork.dimensions.count > 0 {
let dimensionsLabel = label(.Serif, tag: .ArtworkDimensionsLabel)
dimensionsLabel.text = (saleArtwork.artwork.dimensions as NSArray).componentsJoinedByString("\n")
metadataStackView.addSubview(dimensionsLabel, withTopMargin: "5", sideMargin: "0")
}
retrieveImageRights().filter { (imageRights) -> Bool in
return (imageRights as? String).isNotNilNotEmpty
}.subscribeNext { [weak self] (imageRights) -> Void in
if (imageRights as! String).isNotEmpty {
let rightsLabel = label(.Serif, tag: .ImageRightsLabel)
rightsLabel.text = imageRights as? String
self?.metadataStackView.addSubview(rightsLabel, withTopMargin: "22", sideMargin: "0")
}
}
let estimateTopBorder = UIView()
estimateTopBorder.constrainHeight("1")
estimateTopBorder.tag = MetadataStackViewTag.EstimateTopBorder.rawValue
metadataStackView.addSubview(estimateTopBorder, withTopMargin: "22", sideMargin: "0")
let estimateLabel = label(.Serif, tag: .EstimateLabel)
estimateLabel.text = saleArtwork.estimateString
metadataStackView.addSubview(estimateLabel, withTopMargin: "15", sideMargin: "0")
let estimateBottomBorder = UIView()
estimateBottomBorder.constrainHeight("1")
estimateBottomBorder.tag = MetadataStackViewTag.EstimateBottomBorder.rawValue
metadataStackView.addSubview(estimateBottomBorder, withTopMargin: "10", sideMargin: "0")
rac_signalForSelector("viewDidLayoutSubviews").subscribeNext { [weak estimateTopBorder, weak estimateBottomBorder] (_) -> Void in
estimateTopBorder?.drawDottedBorders()
estimateBottomBorder?.drawDottedBorders()
}
let hasBidsSignal = RACObserve(saleArtwork, "highestBidCents").map{ (cents) -> AnyObject! in
return (cents != nil) && ((cents as? NSNumber ?? 0) > 0)
}
let currentBidLabel = label(.Serif, tag: .CurrentBidLabel)
RAC(currentBidLabel, "text") <~ RACSignal.`if`(hasBidsSignal, then: RACSignal.`return`("Current Bid:"), `else`: RACSignal.`return`("Starting Bid:"))
metadataStackView.addSubview(currentBidLabel, withTopMargin: "22", sideMargin: "0")
let currentBidValueLabel = label(.Bold, tag: .CurrentBidValueLabel, fontSize: 27)
RAC(currentBidValueLabel, "text") <~ saleArtwork.currentBidSignal()
metadataStackView.addSubview(currentBidValueLabel, withTopMargin: "10", sideMargin: "0")
let numberOfBidsPlacedLabel = label(.Serif, tag: .NumberOfBidsPlacedLabel)
RAC(numberOfBidsPlacedLabel, "text") <~ saleArtwork.numberOfBidsWithReserveSignal
metadataStackView.addSubview(numberOfBidsPlacedLabel, withTopMargin: "10", sideMargin: "0")
let bidButton = ActionButton()
bidButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self] (_) -> Void in
if let strongSelf = self {
strongSelf.bid(strongSelf.auctionID, saleArtwork: strongSelf.saleArtwork, allowAnimations: strongSelf.allowAnimations)
}
}
saleArtwork.forSaleSignal.subscribeNext { [weak bidButton] (forSale) -> Void in
let forSale = forSale as! Bool
let title = forSale ? "BID" : "SOLD"
bidButton?.setTitle(title, forState: .Normal)
}
RAC(bidButton, "enabled") <~ saleArtwork.forSaleSignal
bidButton.tag = MetadataStackViewTag.BidButton.rawValue
metadataStackView.addSubview(bidButton, withTopMargin: "40", sideMargin: "0")
if let _ = buyersPremium() {
let buyersPremiumView = UIView()
buyersPremiumView.tag = MetadataStackViewTag.BuyersPremium.rawValue
let buyersPremiumLabel = ARSerifLabel()
buyersPremiumLabel.font = buyersPremiumLabel.font.fontWithSize(16)
buyersPremiumLabel.text = "This work has a "
buyersPremiumLabel.textColor = UIColor.artsyHeavyGrey()
let buyersPremiumButton = ARButton()
let title = "buyers premium"
let attributes: [String: AnyObject] = [ NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue, NSFontAttributeName: buyersPremiumLabel.font ];
let attributedTitle = NSAttributedString(string: title, attributes: attributes)
buyersPremiumButton.setTitle(title, forState: .Normal)
buyersPremiumButton.titleLabel?.attributedText = attributedTitle;
buyersPremiumButton.setTitleColor(UIColor.artsyHeavyGrey(), forState: .Normal)
buyersPremiumButton.rac_command = showBuyersPremiumCommand()
buyersPremiumView.addSubview(buyersPremiumLabel)
buyersPremiumView.addSubview(buyersPremiumButton)
buyersPremiumLabel.alignTop("0", leading: "0", bottom: "0", trailing: nil, toView: buyersPremiumView)
buyersPremiumLabel.alignBaselineWithView(buyersPremiumButton, predicate: nil)
buyersPremiumButton.alignAttribute(.Left, toAttribute: .Right, ofView: buyersPremiumLabel, predicate: "0")
metadataStackView.addSubview(buyersPremiumView, withTopMargin: "30", sideMargin: "0")
}
metadataStackView.bottomMarginHeight = CGFloat(NSNotFound)
}
private func setupImageView(imageView: UIImageView) {
if let image = saleArtwork.artwork.defaultImage {
// We'll try to retrieve the thumbnail image from the cache. If we don't have it, we'll set the background colour to grey to indicate that we're downloading it.
let key = SDWebImageManager.sharedManager().cacheKeyForURL(image.thumbnailURL())
let thumbnailImage = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key)
if thumbnailImage == nil {
imageView.backgroundColor = UIColor.artsyLightGrey()
}
imageView.sd_setImageWithURL(image.fullsizeURL(), placeholderImage: thumbnailImage, completed: { (image, _, _, _) -> Void in
// If the image was successfully downloaded, make sure we aren't still displaying grey.
if image != nil {
imageView.backgroundColor = UIColor.clearColor()
}
})
let heightConstraintNumber = { () -> CGFloat in
if let aspectRatio = image.aspectRatio {
if aspectRatio != 0 {
return min(400, CGFloat(538) / aspectRatio)
}
}
return 400
}()
imageView.constrainHeight( "\(heightConstraintNumber)" )
imageView.contentMode = .ScaleAspectFit
imageView.userInteractionEnabled = true
let recognizer = UITapGestureRecognizer()
imageView.addGestureRecognizer(recognizer)
recognizer.rac_gestureSignal().subscribeNext() { [weak self] (_) in
self?.performSegue(.ZoomIntoArtwork)
return
}
}
}
private func setupAdditionalDetailStackView() {
enum LabelType {
case Header
case Body
}
func label(type: LabelType, layoutSignal: RACSignal? = nil) -> UILabel {
let (label, fontSize) = { () -> (UILabel, CGFloat) in
switch type {
case .Header:
return (ARSansSerifLabel(), 14)
case .Body:
return (ARSerifLabel(), 16)
}
}()
label.font = label.font.fontWithSize(fontSize)
label.lineBreakMode = .ByWordWrapping
layoutSignal?.take(1).subscribeNext { [weak label] (_) -> Void in
if let label = label {
label.preferredMaxLayoutWidth = CGRectGetWidth(label.frame)
}
}
return label
}
additionalDetailScrollView.stackView.bottomMarginHeight = 40
let imageView = UIImageView()
additionalDetailScrollView.stackView.addSubview(imageView, withTopMargin: "0", sideMargin: "40")
setupImageView(imageView)
let additionalInfoHeaderLabel = label(.Header)
additionalInfoHeaderLabel.text = "Additional Information"
additionalDetailScrollView.stackView.addSubview(additionalInfoHeaderLabel, withTopMargin: "20", sideMargin: "40")
if let blurb = saleArtwork.artwork.blurb {
let blurbLabel = label(.Body, layoutSignal: additionalDetailScrollView.stackView.rac_signalForSelector("layoutSubviews"))
blurbLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( blurb )
additionalDetailScrollView.stackView.addSubview(blurbLabel, withTopMargin: "22", sideMargin: "40")
}
let additionalInfoLabel = label(.Body, layoutSignal: additionalDetailScrollView.stackView.rac_signalForSelector("layoutSubviews"))
additionalInfoLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( saleArtwork.artwork.additionalInfo )
additionalDetailScrollView.stackView.addSubview(additionalInfoLabel, withTopMargin: "22", sideMargin: "40")
retrieveAdditionalInfo().filter { (info) -> Bool in
return (info as? String).isNotNilNotEmpty
}.subscribeNext { (info) -> Void in
additionalInfoLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( info as! String )
}
if let artist = artist() {
retrieveArtistBlurb().filter { (blurb) -> Bool in
return (blurb as? String).isNotNilNotEmpty
}.subscribeNext { [weak self] (blurb) -> Void in
if self == nil {
return
}
let aboutArtistHeaderLabel = label(.Header)
aboutArtistHeaderLabel.text = "About \(artist.name)"
self?.additionalDetailScrollView.stackView.addSubview(aboutArtistHeaderLabel, withTopMargin: "22", sideMargin: "40")
let aboutAristLabel = label(.Body, layoutSignal: self?.additionalDetailScrollView.stackView.rac_signalForSelector("layoutSubviews"))
aboutAristLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( blurb as? String )
self?.additionalDetailScrollView.stackView.addSubview(aboutAristLabel, withTopMargin: "22", sideMargin: "40")
}
}
}
private func artist() -> Artist? {
return saleArtwork.artwork.artists?.first
}
private func retrieveImageRights() -> RACSignal {
let artwork = saleArtwork.artwork
if let imageRights = artwork.imageRights {
return RACSignal.`return`(imageRights)
} else {
return artistInfoSignal.map{ (json) -> AnyObject! in
return json["image_rights"]
}.filter({ (imageRights) -> Bool in
imageRights != nil
}).doNext{ (imageRights) -> Void in
artwork.imageRights = imageRights as? String
return
}
}
}
private func retrieveAdditionalInfo() -> RACSignal {
let artwork = saleArtwork.artwork
if let additionalInfo = artwork.additionalInfo {
return RACSignal.`return`(additionalInfo)
} else {
return artistInfoSignal.map{ (json) -> AnyObject! in
return json["additional_information"]
}.filter({ (info) -> Bool in
info != nil
}).doNext{ (info) -> Void in
artwork.additionalInfo = info as? String
return
}
}
}
private func retrieveArtistBlurb() -> RACSignal {
if let artist = artist() {
if let blurb = artist.blurb {
return RACSignal.`return`(blurb)
} else {
let artistSignal = XAppRequest(.Artist(id: artist.id)).filterSuccessfulStatusCodes().mapJSON()
return artistSignal.map{ (json) -> AnyObject! in
return json["blurb"]
}.filter({ (blurb) -> Bool in
blurb != nil
}).doNext{ (blurb) -> Void in
artist.blurb = blurb as? String
return
}
}
} else {
return RACSignal.empty()
}
}
}
| mit | 574de0b7417949ed8a9ffc230dd2792e | 42.032581 | 172 | 0.627897 | 5.870085 | false | false | false | false |
longitachi/ZLPhotoBrowser | Sources/Extensions/String+ZLPhotoBrowser.swift | 1 | 1917 | //
// String+ZLPhotoBrowser.swift
// ZLPhotoBrowser
//
// Created by long on 2020/8/18.
//
// Copyright (c) 2020 Long Zhang <[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
import UIKit
extension ZLPhotoBrowserWrapper where Base == String {
func boundingRect(font: UIFont, limitSize: CGSize) -> CGSize {
let style = NSMutableParagraphStyle()
style.lineBreakMode = .byCharWrapping
let att = [NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle: style]
let attContent = NSMutableAttributedString(string: base, attributes: att)
let size = attContent.boundingRect(with: limitSize, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).size
return CGSize(width: ceil(size.width), height: ceil(size.height))
}
}
| mit | 6c9c5cc35633cf05103afdca5da21891 | 43.581395 | 132 | 0.726135 | 4.478972 | false | false | false | false |
nickplee/Aestheticam | Aestheticam/Sources/Other Sources/AestheticApplication.swift | 1 | 1274 | //
// AestheticApplication.swift
// A E S T H E T I C A M
//
// Created by Nick Lee on 5/23/16.
// Copyright © 2016 Nick Lee. All rights reserved.
//
import Foundation
import UIKit
final class AestheticApplication: UIApplication {
private var experience: ShittyExperience!
override init() {
super.init()
experience = ShittyExperience(application: self)
}
override func sendEvent(_ event: UIEvent) {
super.sendEvent(event)
guard let w = keyWindow else {
return
}
if event.type == .touches, let touches = event.touches(for: w) {
if let _ = touches.filter({ $0.phase == .began }).first {
Synthesizer.shared.play(true)
if UInt8.random(within: 0...5) == 4 {
experience.messUpWindow()
}
if #available(iOS 10, *) {
FeedbackGenerator.shared.fire()
}
}
else if let _ = touches.filter({ $0.phase == .ended || $0.phase == .cancelled }).first {
Synthesizer.shared.stop(true)
experience.resetWindow()
}
}
}
}
| mit | 0c22972be8c0ee7a1283044d498cf108 | 25.520833 | 101 | 0.497251 | 4.404844 | false | false | false | false |
mpullman/ios-charts | Charts/Classes/Renderers/D3BarChartRenderer.swift | 1 | 24314 | //
// BarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
@objc
public protocol D3BarChartRendererDelegate
{
func barChartRendererData(renderer: D3BarChartRenderer) -> BarChartData!
func barChartRenderer(renderer: D3BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!
func barChartRendererMaxVisibleValueCount(renderer: D3BarChartRenderer) -> Int
func barChartDefaultRendererValueFormatter(renderer: D3BarChartRenderer) -> NSNumberFormatter!
func barChartRendererChartYMax(renderer: D3BarChartRenderer) -> Double
func barChartRendererChartYMin(renderer: D3BarChartRenderer) -> Double
func barChartRendererChartXMax(renderer: D3BarChartRenderer) -> Double
func barChartRendererChartXMin(renderer: D3BarChartRenderer) -> Double
func barChartIsDrawHighlightArrowEnabled(renderer: D3BarChartRenderer) -> Bool
func barChartIsDrawValueAboveBarEnabled(renderer: D3BarChartRenderer) -> Bool
func barChartIsDrawBarShadowEnabled(renderer: D3BarChartRenderer) -> Bool
func barChartIsInverted(renderer: D3BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool
}
public class D3BarChartRenderer: ChartDataRendererBase
{
public weak var delegate: D3BarChartRendererDelegate?
public init(delegate: D3BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.delegate = delegate
}
public override func drawData(#context: CGContext)
{
var barData = delegate!.barChartRendererData(self)
if (barData === nil)
{
return
}
for (var i = 0; i < barData.dataSetCount; i++)
{
var set = barData.getDataSetByIndex(i)
if set !== nil && set!.isVisible && set.entryCount > 0
{
drawDataSet(context: context, dataSet: set as! BarChartDataSet, index: i)
}
}
}
internal func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int)
{
CGContextSaveGState(context)
var barData = delegate!.barChartRendererData(self)
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self)
var dataSetOffset = (barData.dataSetCount - 1)
var groupSpace = barData.groupSpace
var groupSpaceHalf = groupSpace / 2.0
var barSpace = dataSet.barSpace
var barSpaceHalf = barSpace / 2.0
var containsStacks = dataSet.isStacked
var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency)
var entries = dataSet.yVals as! [BarChartDataEntry]
var barWidth: CGFloat = 0.5
var phaseY = _animator.phaseY
var barRect = CGRect()
var barShadow = CGRect()
var y: Double
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++)
{
var e = entries[j]
// calculate the x-position, depending on datasetcount
var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(j) + groupSpaceHalf
var vals = e.values
if (!containsStacks || vals == nil)
{
y = e.value
var left = x - barWidth + barSpaceHalf
var right = x + barWidth - barSpaceHalf
var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (top > 0)
{
top *= phaseY
}
else
{
bottom *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = barRect.origin.x
barShadow.origin.y = viewPortHandler.contentTop
barShadow.size.width = barRect.size.width
barShadow.size.height = viewPortHandler.contentHeight
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, UIColor.lightGrayColor().CGColor)
CGContextFillRect(context, barRect)
}
else
{
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value
var left = x - barWidth + barSpaceHalf
var right = x + barWidth - barSpaceHalf
var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (top > 0)
{
top *= phaseY
}
else
{
bottom *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
barShadow.origin.x = barRect.origin.x
barShadow.origin.y = viewPortHandler.contentTop
barShadow.size.width = barRect.size.width
barShadow.size.height = viewPortHandler.contentHeight
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// fill the stack
for (var k = 0; k < vals!.count; k++)
{
let value = vals![k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
var left = x - barWidth + barSpaceHalf
var right = x + barWidth - barSpaceHalf
var top: CGFloat, bottom: CGFloat
if isInverted
{
bottom = y >= yStart ? CGFloat(y) : CGFloat(yStart)
top = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
else
{
top = y >= yStart ? CGFloat(y) : CGFloat(yStart)
bottom = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
// multiply the height of the rect with the phase
top *= phaseY
bottom *= phaseY
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
// Skip to next bar
break
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, UIColor.lightGrayColor().CGColor)
CGContextFillRect(context, barRect)
}
}
}
CGContextRestoreGState(context)
}
/// Prepares a bar for being highlighted.
internal func prepareBarHighlight(#x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect)
{
let barWidth: CGFloat = 0.5
var left = x - barWidth + barspacehalf
var right = x + barWidth - barspacehalf
var top = CGFloat(y1)
var bottom = CGFloat(y2)
rect.origin.x = left
rect.origin.y = top
rect.size.width = right - left
rect.size.height = bottom - top
trans.rectValueToPixel(&rect, phaseY: _animator.phaseY)
}
public override func drawValues(#context: CGContext)
{
// if values are drawn
if (passesCheck())
{
var barData = delegate!.barChartRendererData(self)
var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self)
var dataSets = barData.dataSets
var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self)
var posOffset: CGFloat
var negOffset: CGFloat
for (var i = 0, count = barData.dataSetCount; i < count; i++)
{
var dataSet = dataSets[i] as! BarChartDataSet
if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0
{
continue
}
var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency)
// calculate the correct offset depending on the draw position of the value
let valueOffsetPlus: CGFloat = 4.5
var valueFont = dataSet.valueFont
var valueTextHeight = valueFont.lineHeight
posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus)
negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus))
if (isInverted)
{
posOffset = -posOffset - valueTextHeight
negOffset = -negOffset - valueTextHeight
}
var valueTextColor = dataSet.valueTextColor
var formatter = dataSet.valueFormatter
if (formatter === nil)
{
formatter = defaultValueFormatter
}
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var entries = dataSet.yVals as! [BarChartDataEntry]
var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i)
// if only single values are drawn (sum)
if (!dataSet.isStacked)
{
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
if (!viewPortHandler.isInBoundsRight(valuePoints[j].x))
{
break
}
if (!viewPortHandler.isInBoundsY(valuePoints[j].y)
|| !viewPortHandler.isInBoundsLeft(valuePoints[j].x))
{
continue
}
var val = entries[j].value
drawValue(context: context,
value: formatter!.stringFromNumber(val)!,
xPos: valuePoints[j].x,
yPos: valuePoints[j].y + (val >= 0.0 ? posOffset : negOffset),
font: valueFont,
align: .Center,
color: valueTextColor)
}
}
else
{
// if we have stacks
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
var e = entries[j]
let values = e.values
// we still draw stacked bars, but there is one non-stacked in between
if (values == nil)
{
if (!viewPortHandler.isInBoundsRight(valuePoints[j].x))
{
break
}
if (!viewPortHandler.isInBoundsY(valuePoints[j].y)
|| !viewPortHandler.isInBoundsLeft(valuePoints[j].x))
{
continue
}
drawValue(context: context,
value: formatter!.stringFromNumber(e.value)!,
xPos: valuePoints[j].x,
yPos: valuePoints[j].y + (e.value >= 0.0 ? posOffset : negOffset),
font: valueFont,
align: .Center,
color: valueTextColor)
}
else
{
// draw stack values
let vals = values!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for (var k = 0; k < vals.count; k++)
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: 0.0, y: CGFloat(y) * _animator.phaseY))
}
trans.pointValuesToPixel(&transformed)
for (var k = 0; k < transformed.count; k++)
{
var x = valuePoints[j].x
var y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset)
if (!viewPortHandler.isInBoundsRight(x))
{
break
}
if (!viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x))
{
continue
}
drawValue(context: context,
value: formatter!.stringFromNumber(vals[k])!,
xPos: x,
yPos: y,
font: valueFont,
align: .Center,
color: valueTextColor)
}
}
}
}
}
}
}
/// Draws a value at the specified x and y position.
internal func drawValue(#context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: UIFont, align: NSTextAlignment, color: UIColor)
{
ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
}
public override func drawExtras(#context: CGContext)
{
}
private var _highlightArrowPtsBuffer = [CGPoint](count: 3, repeatedValue: CGPoint())
public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight])
{
var barData = delegate!.barChartRendererData(self)
if (barData === nil)
{
return
}
CGContextSaveGState(context)
var setCount = barData.dataSetCount
var drawHighlightArrowEnabled = delegate!.barChartIsDrawHighlightArrowEnabled(self)
var barRect = CGRect()
for (var i = 0; i < indices.count; i++)
{
var h = indices[i]
var index = h.xIndex
var dataSetIndex = h.dataSetIndex
var set = barData.getDataSetByIndex(dataSetIndex) as! BarChartDataSet!
if (set === nil || !set.isHighlightEnabled)
{
continue
}
var barspaceHalf = set.barSpace / 2.0
var trans = delegate!.barChartRenderer(self, transformerForAxis: set.axisDependency)
CGContextSetFillColorWithColor(context, set.colorAt(index).CGColor)
CGContextSetAlpha(context, set.highLightAlpha)
// check outofbounds
if (CGFloat(index) < (CGFloat(delegate!.barChartRendererChartXMax(self)) * _animator.phaseX) / CGFloat(setCount))
{
var e = set.entryForXIndex(index) as! BarChartDataEntry!
if (e === nil || e.xIndex != index)
{
continue
}
var groupspace = barData.groupSpace
var isStack = h.stackIndex < 0 ? false : true
// calculate the correct x-position
var x = CGFloat(index * setCount + dataSetIndex) + groupspace / 2.0 + groupspace * CGFloat(index)
let y1: Double
let y2: Double
if (isStack)
{
y1 = h.range?.from ?? 0.0
y2 = (h.range?.to ?? 0.0) * Double(_animator.phaseY)
}
else
{
y1 = e.value
y2 = 0.0
}
prepareBarHighlight(x: x, y1: y1, y2: y2, barspacehalf: barspaceHalf, trans: trans, rect: &barRect)
CGContextFillRect(context, barRect)
if (drawHighlightArrowEnabled)
{
CGContextSetAlpha(context, 1.0)
// distance between highlight arrow and bar
var offsetY = _animator.phaseY * 0.07
CGContextSaveGState(context)
var pixelToValueMatrix = trans.pixelToValueMatrix
var xToYRel = abs(sqrt(pixelToValueMatrix.b * pixelToValueMatrix.b + pixelToValueMatrix.d * pixelToValueMatrix.d) / sqrt(pixelToValueMatrix.a * pixelToValueMatrix.a + pixelToValueMatrix.c * pixelToValueMatrix.c))
var arrowWidth = set.barSpace / 2.0
var arrowHeight = arrowWidth * xToYRel
let yArrow = y1 > -y2 ? y1 : y1;
_highlightArrowPtsBuffer[0].x = CGFloat(x) + 0.4
_highlightArrowPtsBuffer[0].y = CGFloat(yArrow) + offsetY
_highlightArrowPtsBuffer[1].x = CGFloat(x) + 0.4 + arrowWidth
_highlightArrowPtsBuffer[1].y = CGFloat(yArrow) + offsetY - arrowHeight
_highlightArrowPtsBuffer[2].x = CGFloat(x) + 0.4 + arrowWidth
_highlightArrowPtsBuffer[2].y = CGFloat(yArrow) + offsetY + arrowHeight
trans.pointValuesToPixel(&_highlightArrowPtsBuffer)
CGContextBeginPath(context)
CGContextMoveToPoint(context, _highlightArrowPtsBuffer[0].x, _highlightArrowPtsBuffer[0].y)
CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[1].x, _highlightArrowPtsBuffer[1].y)
CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[2].x, _highlightArrowPtsBuffer[2].y)
CGContextClosePath(context)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
}
}
CGContextRestoreGState(context)
}
public func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint]
{
return trans.generateTransformedValuesBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY)
}
internal func passesCheck() -> Bool
{
var barData = delegate!.barChartRendererData(self)
if (barData === nil)
{
return false
}
return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX
}
} | apache-2.0 | 20af6b013d49f9a788c2177cc824b734 | 40.281834 | 232 | 0.459571 | 6.410229 | false | false | false | false |
egnwd/ic-bill-hack | quick-split/Pods/MondoKit/MondoKit/MondoAPIOperation.swift | 2 | 3867 | //
// MondoAPIOperation.swift
// MondoKit
//
// Created by Mike Pollard on 06/02/2016.
// Copyright © 2016 Mike Pollard. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
/**
Packaging API calls as `NSOperation`s will allow MondoKit to more easily manage concurrency and potential dependencies between calls.
*/
class MondoAPIOperation: NSOperation {
typealias ResponseHandler = (json: JSON?, error: ErrorType?) -> Void
private var _executing : Bool = false {
willSet {
willChangeValueForKey("isExecuting")
}
didSet {
didChangeValueForKey("isExecuting")
}
}
private var _finished : Bool = false {
willSet {
willChangeValueForKey("isFinished")
}
didSet {
didChangeValueForKey("isFinished")
}
}
override var executing: Bool { return _executing }
override var finished: Bool { return _finished }
override var asynchronous: Bool { return true }
override func start() {
guard !self.cancelled else {
_executing = false
_finished = true
return
}
_executing = true
request = MondoAPI.instance.alamofireManager.request(method, urlString, parameters: parameters, headers: authHeader?())
request!.resume()
request!.response(queue: MondoAPIOperation.ResponseQueue, responseSerializer: Request.JSONResponseSerializer()) { [unowned self] response in
guard !self.cancelled else {
self._executing = false
self._finished = true
return
}
var json : JSON?
var anyError : ErrorType?
defer {
self.responseHandler(json: json, error: anyError)
self._executing = false
self._finished = true
}
guard let status = response.response?.statusCode where status == 200 else {
debugPrint(response)
anyError = self.errorFromResponse(response)
return
}
switch response.result {
case .Success(let value):
debugPrint(value)
json = JSON(value)
case .Failure(let error):
debugPrint(error)
anyError = error
}
}
}
private static let ResponseQueue : dispatch_queue_t = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
private var method : Alamofire.Method
private var urlString : URLStringConvertible
private var parameters : [String : AnyObject]?
private var authHeader: (()->[String:String]?)?
private var request : Alamofire.Request?
private var responseHandler : ResponseHandler
init(method: Alamofire.Method, urlString: URLStringConvertible,
parameters: [String : AnyObject]? = nil,
authHeader: ()->[String:String]? = { return nil },
responseHandler: ResponseHandler) {
self.method = method
self.urlString = urlString
self.parameters = parameters
self.authHeader = authHeader
self.responseHandler = responseHandler
}
private func errorFromResponse(response: Alamofire.Response<AnyObject, NSError>) -> ErrorType {
switch response.result {
case .Success(let value):
let json = JSON(value)
return MondoAPIError.apiErrorfromJson(json)
case .Failure(let error):
return error
}
}
}
| mit | 697906e98b4e53808b400b013b9d81df | 28.51145 | 148 | 0.552768 | 5.831071 | false | false | false | false |
IvanVorobei/Sparrow | sparrow/code-draw/SPCodeDrawSystemIconPack.swift | 1 | 5909 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
extension SPCodeDraw {
public class SystemIconPack : NSObject {
//// Cache
private struct Cache {
static let gradient: CGGradient = CGGradient(colorsSpace: nil, colors: [UIColor.red.cgColor, UIColor.red.cgColor] as CFArray, locations: [0, 1])!
}
//// Gradients
@objc dynamic public class var gradient: CGGradient { return Cache.gradient }
//// Drawing Methods
@objc dynamic public class func drawShare(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, color: UIColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Clip 2 Drawing
let clip2Path = UIBezierPath()
clip2Path.move(to: CGPoint(x: 38.59, y: 33.54))
clip2Path.addLine(to: CGPoint(x: 38.59, y: 38.16))
clip2Path.addLine(to: CGPoint(x: 24.9, y: 38.16))
clip2Path.addLine(to: CGPoint(x: 24.9, y: 90.08))
clip2Path.addLine(to: CGPoint(x: 75.1, y: 90.08))
clip2Path.addLine(to: CGPoint(x: 75.1, y: 38.16))
clip2Path.addLine(to: CGPoint(x: 61.41, y: 38.16))
clip2Path.addLine(to: CGPoint(x: 61.41, y: 33.54))
clip2Path.addLine(to: CGPoint(x: 80, y: 33.54))
clip2Path.addLine(to: CGPoint(x: 80, y: 95))
clip2Path.addLine(to: CGPoint(x: 20, y: 95))
clip2Path.addLine(to: CGPoint(x: 20, y: 33.54))
clip2Path.addLine(to: CGPoint(x: 38.59, y: 33.54))
clip2Path.close()
clip2Path.move(to: CGPoint(x: 52.27, y: 61.81))
clip2Path.addLine(to: CGPoint(x: 47.73, y: 61.81))
clip2Path.addLine(to: CGPoint(x: 47.73, y: 14.88))
clip2Path.addLine(to: CGPoint(x: 40.08, y: 22.75))
clip2Path.addLine(to: CGPoint(x: 37.14, y: 19.73))
clip2Path.addLine(to: CGPoint(x: 50, y: 6.5))
clip2Path.addLine(to: CGPoint(x: 62.86, y: 19.73))
clip2Path.addLine(to: CGPoint(x: 59.92, y: 22.75))
clip2Path.addLine(to: CGPoint(x: 52.27, y: 14.88))
clip2Path.addLine(to: CGPoint(x: 52.27, y: 61.81))
clip2Path.close()
color.setFill()
clip2Path.fill()
context.restoreGState()
}
@objc(StyleKitNameResizingBehavior)
public enum ResizingBehavior: Int {
case aspectFit /// The content is proportionally resized to fit into the target rectangle.
case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
case stretch /// The content is stretched to match the entire target rectangle.
case center /// The content is centered in the target rectangle, but it is NOT resized.
public func apply(rect: CGRect, target: CGRect) -> CGRect {
if rect == target || target == CGRect.zero {
return rect
}
var scales = CGSize.zero
scales.width = abs(target.width / rect.width)
scales.height = abs(target.height / rect.height)
switch self {
case .aspectFit:
scales.width = min(scales.width, scales.height)
scales.height = scales.width
case .aspectFill:
scales.width = max(scales.width, scales.height)
scales.height = scales.width
case .stretch:
break
case .center:
scales.width = 1
scales.height = 1
}
var result = rect.standardized
result.size.width *= scales.width
result.size.height *= scales.height
result.origin.x = target.minX + (target.width - result.width) / 2
result.origin.y = target.minY + (target.height - result.height) / 2
return result
}
}
}
}
| mit | 9fedb43ff43bf1b5bea5c71a259996d4 | 45.519685 | 244 | 0.57803 | 4.256484 | false | false | false | false |
1170197998/SinaWeibo | SFWeiBo/SFWeiBo/Classes/Home/Popover/PopoverViewController.swift | 1 | 1337 | //
// PopoverViewController.swift
// SFWeiBo
//
// Created by mac on 16/3/27.
// Copyright © 2016年 ShaoFeng. All rights reserved.
//
import UIKit
class PopoverViewController: UIViewController {
@IBOutlet var tableView: UITableView!
let arrayTitle = ["首页","好友圈","特别关注","媒体","同事","同学","名人明星","悄悄关注"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
}
extension PopoverViewController: UITableViewDelegate,UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayTitle.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("id")
if (cell == nil) {
cell = UITableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: "id")
}
cell?.textLabel?.text = arrayTitle[indexPath.row]
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("界面切换")
dismissViewControllerAnimated(true, completion: nil)
}
}
| apache-2.0 | 1bed96c752f1f6bb740fafb499f49e57 | 27.444444 | 109 | 0.666406 | 4.904215 | false | false | false | false |
hujewelz/modelSwift | ModelSwift/Classes/ModelSwift.swift | 1 | 5119 | //
// ModelSwift.swift
// ModelSwift
//
// Created by jewelz on 03/23/2017.
// Copyright (c) 2017 hujewelz. All rights reserved.
//
import Foundation
infix operator ~>
infix operator =>
/// convert json or Data into a model object.
///
/// - Parameter lhs: a json or Data to be converted.
/// - Parameter rhs: type of model.
/// - Returns: the converted model.
@discardableResult public func ~><T: NSObject>(lhs: Any, rhs: T.Type) -> T? {
if let data = lhs as? Data, let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String : Any] {
return convert(json, to: T.self) as? T
} else if let dict = lhs as? [String: Any] {
return convert(dict, to: T.self) as? T
}
print("Can't convert \(lhs) to [String: Any].")
return nil
}
/// convert json or Data into a model array.
///
/// - Parameter lhs: a json or Data to be converted.
/// - Parameter rhs: type of model.
/// - Returns: the converted model array.
@discardableResult public func =><T: NSObject>(lhs: Any, rhs: T.Type) -> [T]? {
if let data = lhs as? Data, let array = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [Any], !array.isEmpty {
return array.flatMap { $0 ~> rhs }
} else if let array = lhs as? [Any], !array.isEmpty {
return array.flatMap { $0 ~> rhs }
}
print("Can't convert \(lhs) to [Any].")
return nil
}
fileprivate func convert(_ any: Any, to classType: Any.Type) -> Any? {
if let dict = any as? [String: Any], !dict.isEmpty {
return convert(dict, to: classType)
} else if let array = any as? [Any] {
return array.flatMap{ convert($0, to: classType)}
}
return any
}
fileprivate func convert(_ dict: [String: Any], to classType: Any.Type) -> NSObject? {
if dict.isEmpty {
return nil
}
// 只有 NSObject 的子类才能动态创建一个对象
guard let type = classType as? NSObject.Type else {
return nil
}
let object = type.init()
let any = Image(reflecting: object)
for case let(label?, type) in any.children {
//debugPrint("\(label)`s type is \(type)")
if let obj = object as? Ignorable {
if obj.ignoredProperty.contains(label) {
continue
}
}
var jsonValue: Dictionary<String, Any>.Value? = nil
if let obj = object as? Replacable, let jsonKey = obj.replacedProperty[label] {
jsonValue = dict[jsonKey]
} else {
jsonValue = dict[label]
}
if let value = jsonValue {
if value is NSNull { continue }
// 如果 value 的值是字典
if let dictValue = value as? [String: Any],
let obj = object as? Reflectable,
let _classType = obj.reflectedObject[label] {
let _obj = convert(dictValue, to: _classType)
object.setValue(_obj, forKey: label)
} else if let dictValue = value as? [Any],
let obj = object as? ObjectingArray,
let _classType = obj.objectInArray[label] { // 如果 value 的值是数组
// 首先要将数组中的元素转换成模型中的类型,例如json中images=[1,2], model中images为[String], 则需要转换
let convertedValue = dictValue.flatMap{ convert(value: $0, to: type) }
//print("convertedValue: \(convertedValue)")
let _obj = convertedValue.flatMap{ convert($0, to: _classType) }
object.setValue(_obj, forKey: label)
} else {
// 将json中元素转换成模型中的类型,例如json中age="23", model中age为Int, 则需要转换
let convertedValue = convert(value: value, to: type)
object.setValue(convertedValue , forKeyPath: label)
}
}
}
return object
}
private func convert(value: Any, to realType: Type<Any>) -> Any? {
let stringVaule = String(describing: value)
switch realType {
case .int:
return Int(stringVaule) ?? 0
case .float:
return Float(stringVaule) ?? 0.0
case .double:
return Double(stringVaule) ?? 0.0
case .bool:
return Bool(stringVaule) ?? ((Int(stringVaule) ?? 0) > 0)
case .string:
return stringVaule
case .none:
return nil
case .array(let v):
if v is String.Type {
return stringVaule
} else if v is Int.Type {
return Int(stringVaule) ?? 0
} else if v is Float.Type {
return Float(stringVaule) ?? 0.0
} else if v is Double.Type {
return Double(stringVaule) ?? 0.0
} else if v is Bool.Type {
return Bool(stringVaule) ?? ((Int(stringVaule) ?? 0) > 0)
} else {
return value
}
default:
return value
}
}
| mit | 22ebd093a0d5cac2d14a822879ad332f | 29.20122 | 132 | 0.548153 | 4.049877 | false | false | false | false |
peterdruska/MVC-example | MVCExample/MVCExample/ViewController.swift | 1 | 2390 | //
// ViewController.swift
// MVCExample
//
// Created by Peter Druska on 14/03/16.
// Copyright © 2016 Bedots.eu. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
@IBOutlet weak var tableView: UITableView!
var userName: String!
var email: String!
var password: String!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func register(sender: AnyObject) {
/*
1) API request to create new user
2) Read response
3) If user is created on server, he is saved to persistent storage
*/
if userName != nil && email != nil && password != nil {
let user = User(userName: userName, email: email, password: password)
print(user.description)
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("formCell", forIndexPath: indexPath) as! FormViewCell
cell.formInput.delegate = self
if indexPath.row == 0 {
cell.formInput.tag = 0
cell.formInput.placeholder = "Username"
} else if indexPath.row == 1 {
cell.formInput.tag = 1
cell.formInput.placeholder = "Email"
cell.formInput.keyboardType = UIKeyboardType.EmailAddress
} else {
cell.formInput.tag = 2
cell.formInput.placeholder = "Password"
cell.formInput.secureTextEntry = true
}
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField.tag == 0 {
userName = textField.text
} else if textField.tag == 1 {
email = textField.text
} else {
password = textField.text
}
textField.resignFirstResponder()
return true
}
}
| mit | e632e6c3d81d31fb6cf5d0e6fc864305 | 28.8625 | 116 | 0.611972 | 5.137634 | false | false | false | false |
b-andris/Authenticate | Authenticate/ViewController.swift | 1 | 1149 | //
// ViewController.swift
// Authenticate
//
// Created by Benjamin Andris Suter-Dörig on 11/05/15.
// Copyright (c) 2015 Benjamin Andris Suter-Dörig. All rights reserved.
//
import UIKit
open class ViewController: UIViewController, LockViewControllerDelegate {
var code = "0000"
@IBAction func setup(_ sender: AnyObject) {
let lockVC = LockViewController()
lockVC.mode = .setup
lockVC.delegate = self
present(lockVC, animated: true, completion: nil)
}
@IBAction func authenticate(_ sender: UIButton) {
let lockVC = LockViewController()
lockVC.code = code
lockVC.remainingAttempts = -1
lockVC.maxWait = 3
lockVC.delegate = self
present(lockVC, animated: true, completion: nil)
}
open func lockViewControllerDidSetup(_ controller: LockViewController, code: String) {
self.code = code
dismiss(animated: true, completion: nil)
}
open func lockViewControllerAuthentication(_ controller: LockViewController, didSucced success: Bool) {
dismiss(animated: true, completion: nil)
DispatchQueue.main.async(execute: { () -> Void in
self.view.backgroundColor = success ? UIColor.green : UIColor.red
})
}
}
| mit | bd91519a1afb400a23aa5bf9088702b8 | 27.675 | 104 | 0.732345 | 3.664537 | false | false | false | false |
jokeyrhyme/webview-benchmarker-ios | WebViewBenchmarker/Benchmark.swift | 1 | 4002 | //
// Benchmark.swift
// WebViewBenchmarker
//
// Created by Ron Waldon on 23/02/2015.
// Copyright (c) 2015 Ron Waldon. All rights reserved.
//
import Foundation
import UIKit
import WebKit
class Benchmark: NSObject, UIWebViewDelegate {
var webView: UIWebView
var result: String = ""
var delegate: BenchmarkDelegate? = nil
var timeout: UInt64 = 10 * NSEC_PER_SEC
var delay: UInt64 = 1 * NSEC_PER_SEC
override init() {
self.webView = UIWebView()
}
func load() {
var url: String = "https://google.com/"
var request = NSURLRequest(URL: NSURL(string: url)!)
self.webView.loadRequest(request)
}
func isAutoStarted() -> Bool {
return true
}
func isPreparedToStart() -> Bool {
return true
}
func startTests() {}
func extractResult() -> String {
var script: String = "document.querySelector('body').textContent"
var result: String = self.webView.stringByEvaluatingJavaScriptFromString(script)!
return result
}
func isComplete() -> Bool {
var result: String = self.extractResult()
return ~result.isEmpty
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
return true
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
println("didFailLoadWithError")
}
func webViewDidFinishLoad(webView: UIWebView) {
println("webViewDidFinishLoad")
if (self.isAutoStarted()) {
self.pollUntil(self.isComplete, done: self.didComplete, timeout: self.timeout)
} else {
self.pollUntil(self.isPreparedToStart, done: self.didPrepareToStart, timeout: self.timeout)
}
}
func webViewDidStartLoad(webView: UIWebView) {
//println("webViewDidStartLoad")
}
func didPrepareToStart(err: NSError?) {
if (err != nil) {
if (self.delegate != nil) {
self.delegate!.benchmarkDidFail(self)
}
} else {
self.startTests()
self.pollUntil(self.isComplete, done: self.didComplete, timeout: self.timeout)
}
}
func didComplete(err: NSError?) {
if (err != nil) {
if (self.delegate != nil) {
self.delegate!.benchmarkDidFail(self)
}
} else {
self.result = self.extractResult()
if (self.delegate != nil) {
self.delegate!.benchmarkDidSucceed(self)
}
}
}
// http://stackoverflow.com/questions/25951980/swift-do-something-every-x-minutes
private func pollUntil(check: (() -> Bool), done: ((err: NSError?) -> Void), timeout: UInt64) {
let queue = dispatch_get_main_queue()
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
var elapsed: UInt64 = 0
// every 60 seconds, with leeway of 1 second
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, self.delay, 1 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer) {
// do whatever you want here
elapsed = elapsed + self.delay
if (elapsed >= timeout) {
dispatch_source_cancel(timer)
done(err: NSError(domain: "pollUntil", code: 1, userInfo: NSDictionary()))
}
var result: Bool = check()
if (result) {
dispatch_source_cancel(timer)
done(err: nil)
}
}
dispatch_resume(timer)
}
}
protocol BenchmarkProtocol {
func benchmarkDidSucceed()
func benchmarkDidFail()
func isComplete() -> Bool
func extractResult() -> String
}
protocol BenchmarkDelegate : NSObjectProtocol {
func benchmarkDidSucceed(benchmark: Benchmark)
func benchmarkDidFail(benchmark: Benchmark)
}
| bsd-3-clause | c1cc6a961598a300f541f51305463a65 | 29.090226 | 137 | 0.594953 | 4.542565 | false | false | false | false |
piwik/piwik-sdk-ios | MatomoTracker/OrderItem.swift | 1 | 1124 | import Foundation
/// Order item as described in: https://matomo.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required
public struct OrderItem: Codable {
/// The SKU of the order item
let sku: String
/// The name of the order item
let name: String
/// The category of the order item
let category: String
/// The price of the order item
let price: Float
/// The quantity of the order item
let quantity: Int
/// Creates a new OrderItem
///
/// - Parameters:
/// - sku: The SKU of the item
/// - name: The name of the item. Empty string per default.
/// - category: The category of the item. Empty string per default.
/// - price: The price of the item. 0 per default.
/// - quantity: The quantity of the item. 1 per default.
public init(sku: String, name: String = "", category: String = "", price: Float = 0.0, quantity: Int = 1) {
self.sku = sku
self.name = name
self.category = category
self.price = price
self.quantity = quantity
}
}
| mit | 5d606c071e01aba35085639629b40461 | 30.222222 | 127 | 0.606762 | 4.19403 | false | false | false | false |
PBBB/Life-Easy-iOS | showHTMLCode/ActionViewController.swift | 1 | 5422 | //
// ActionViewController.swift
// showHTMLCode
//
// Created by PennIssac on 16/3/11.
// Copyright © 2016年 PennIssac. All rights reserved.
//
import UIKit
import MobileCoreServices
class ActionViewController: UIViewController, UITextViewDelegate {
var htmlTextView: UITextView!
var textStorage: PBHighlightTextStorage!
override func viewDidLoad() {
super.viewDidLoad()
createTextView()
// self.automaticallyAdjustsScrollViewInsets = false
//initiate NSTextStorage, NSLayoutManager, NSTextContainer and UITextView
// let htmlHighlightTextStorage = PBHighlightTextStorage()
// let layoutManager = NSLayoutManager()
// htmlHighlightTextStorage.addLayoutManager(layoutManager)
//
// let textContainer = NSTextContainer()
// layoutManager.addTextContainer(textContainer)
//
// htmlTextView = UITextView(frame: CGRectZero, textContainer: textContainer)
//// htmlTextView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
// htmlTextView.translatesAutoresizingMaskIntoConstraints = false
//// htmlTextView.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(UIViewAutoresizing.FlexibleHeight)
//
// self.view.addSubview(htmlTextView)
//
//// 为htmlTextView添加约束
// let views = ["htmlTextView": htmlTextView]
// let hFormatString = "|[htmlTextView]|"
// let vFormatString = "V:|[htmlTextView]|"
// let hConstraints = NSLayoutConstraint.constraintsWithVisualFormat(hFormatString, options: .DirectionLeadingToTrailing, metrics: nil, views: views)
// let vConstraints = NSLayoutConstraint.constraintsWithVisualFormat(vFormatString, options: .DirectionLeadingToTrailing, metrics: nil, views: views)
// NSLayoutConstraint.activateConstraints(hConstraints + vConstraints)
//
for item: AnyObject in self.extensionContext!.inputItems {
let extItem = item as! NSExtensionItem
let itemProvider = extItem.attachments!.first! as! NSItemProvider
itemProvider.loadItemForTypeIdentifier(kUTTypePropertyList as String, options: nil) {
results, error in
guard results != nil else {
return
}
let dic = NSDictionary(object: results!, forKey: NSExtensionJavaScriptPreprocessingResultsKey)
var htmlText = ""
guard let extensionDic = dic[NSExtensionJavaScriptPreprocessingResultsKey] as? NSDictionary else {
return
}
guard let realExtensionDic = extensionDic[NSExtensionJavaScriptPreprocessingResultsKey] as? NSDictionary else {
return
}
if let headText = realExtensionDic.valueForKey("head") as? String, let bodyText = realExtensionDic.valueForKey("body") as? String {
htmlText = htmlText + "<head>\n" + headText + "</head>\n<body>\n" + bodyText + "\n</body>"
}
dispatch_async(dispatch_get_main_queue()){
// self.textView.text = "\(htmlText)"
// let htmlHighlightTextStorage = PBHighlightTextStorage(text: htmlText, hightRuleExpression: nil)
// htmlHighlightTextStorage.addLayoutManager(self.textView.layoutManager)
self.textStorage.beginEditing()
self.textStorage.appendAttributedString(NSMutableAttributedString(string: htmlText, attributes: [NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleBody)]))
self.textStorage.endEditing()
self.title = realExtensionDic.valueForKey("title") as? String
}
}
}
}
override func viewDidLayoutSubviews() {
htmlTextView.frame = view.bounds
}
func createTextView() {
let attrs = [NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleBody)]
let attrString = NSAttributedString(string: "", attributes: attrs)
textStorage = PBHighlightTextStorage()
textStorage.appendAttributedString(attrString)
let newTextViewRect = view.bounds
let layoutManager = NSLayoutManager()
let containerSize = CGSize(width: newTextViewRect.width, height: CGFloat.max)
let container = NSTextContainer(size: containerSize)
container.widthTracksTextView = true
layoutManager.addTextContainer(container)
textStorage.addLayoutManager(layoutManager)
htmlTextView = UITextView(frame: newTextViewRect, textContainer: container)
htmlTextView.delegate = self
htmlTextView.editable = false
view.addSubview(htmlTextView)
}
override func viewWillLayoutSubviews() {
htmlTextView.frame = view.bounds
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func done() {
// Return any edited content to the host app.
// This template doesn't do anything, so we just echo the passed in items.
self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
}
}
| mit | e8e005bfdb45307d647c3e4bb4031f45 | 42.272 | 195 | 0.65465 | 5.963616 | false | false | false | false |
ttlock/iOS_TTLock_Demo | Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/DFUServiceDelegate.swift | 2 | 10084 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
@objc public enum DFUError : Int {
// Legacy DFU errors
case remoteLegacyDFUSuccess = 1
case remoteLegacyDFUInvalidState = 2
case remoteLegacyDFUNotSupported = 3
case remoteLegacyDFUDataExceedsLimit = 4
case remoteLegacyDFUCrcError = 5
case remoteLegacyDFUOperationFailed = 6
// Secure DFU errors (received value + 10 as they overlap legacy errors)
case remoteSecureDFUSuccess = 11 // 10 + 1
case remoteSecureDFUOpCodeNotSupported = 12 // 10 + 2
case remoteSecureDFUInvalidParameter = 13 // 10 + 3
case remoteSecureDFUInsufficientResources = 14 // 10 + 4
case remoteSecureDFUInvalidObject = 15 // 10 + 5
case remoteSecureDFUSignatureMismatch = 16 // 10 + 6
case remoteSecureDFUUnsupportedType = 17 // 10 + 7
case remoteSecureDFUOperationNotPermitted = 18 // 10 + 8
case remoteSecureDFUOperationFailed = 20 // 10 + 10
// This error will no longer be reported
case remoteSecureDFUExtendedError = 21 // 10 + 11
// Instead, one of the extended errors below will used
case remoteExtendedErrorWrongCommandFormat = 22 // 20 + 0x02
case remoteExtendedErrorUnknownCommand = 23 // 20 + 0x03
case remoteExtendedErrorInitCommandInvalid = 24 // 20 + 0x04
case remoteExtendedErrorFwVersionFailure = 25 // 20 + 0x05
case remoteExtendedErrorHwVersionFailure = 26 // 20 + 0x06
case remoteExtendedErrorSdVersionFailure = 27 // 20 + 0x07
case remoteExtendedErrorSignatureMissing = 28 // 20 + 0x08
case remoteExtendedErrorWrongHashType = 29 // 20 + 0x09
case remoteExtendedErrorHashFailed = 30 // 20 + 0x0A
case remoteExtendedErrorWrongSignatureType = 31 // 20 + 0x0B
case remoteExtendedErrorVerificationFailed = 32 // 20 + 0x0C
case remoteExtendedErrorInsufficientSpace = 33 // 20 + 0x0D
// Experimental Buttonless DFU errors (received value + 9000 as they overlap legacy and secure DFU errors)
case remoteExperimentalButtonlessDFUSuccess = 9001 // 9000 + 1
case remoteExperimentalButtonlessDFUOpCodeNotSupported = 9002 // 9000 + 2
case remoteExperimentalButtonlessDFUOperationFailed = 9004 // 9000 + 4
// Buttonless DFU errors (received value + 90 as they overlap legacy and secure DFU errors)
case remoteButtonlessDFUSuccess = 91 // 90 + 1
case remoteButtonlessDFUOpCodeNotSupported = 92 // 90 + 2
case remoteButtonlessDFUOperationFailed = 94 // 90 + 4
/// Providing the DFUFirmware is required.
case fileNotSpecified = 101
/// Given firmware file is not supported.
case fileInvalid = 102
/// Since SDK 7.0.0 the DFU Bootloader requires the extended Init Packet. For more details, see:
/// http://infocenter.nordicsemi.com/topic/com.nordic.infocenter.sdk5.v11.0.0/bledfu_example_init.html?cp=4_0_0_4_2_1_1_3
case extendedInitPacketRequired = 103
/// Before SDK 7.0.0 the init packet could have contained only 2-byte CRC value, and was optional.
/// Providing an extended one instead would cause CRC error during validation (the bootloader assumes that the 2 first bytes
/// of the init packet are the firmware CRC).
case initPacketRequired = 104
case failedToConnect = 201
case deviceDisconnected = 202
case bluetoothDisabled = 203
case serviceDiscoveryFailed = 301
case deviceNotSupported = 302
case readingVersionFailed = 303
case enablingControlPointFailed = 304
case writingCharacteristicFailed = 305
case receivingNotificationFailed = 306
case unsupportedResponse = 307
/// Error raised during upload when the number of bytes sent is not equal to number of bytes confirmed in Packet Receipt Notification.
case bytesLost = 308
/// Error raised when the CRC reported by the remote device does not match. Service has done 3 attempts to send the data.
case crcError = 309
/// Returns whether the error has been returned by the remote device or occurred locally.
var isRemote: Bool {
return rawValue < 100 || rawValue > 9000
}
}
/**
The state of the DFU Service.
- connecting: Service is connecting to the DFU target.
- starting: DFU Service is initializing DFU operation.
- enablingDfuMode: Service is switching the device to DFU mode.
- uploading: Service is uploading the firmware.
- validating: The DFU target is validating the firmware.
- disconnecting: The iDevice is disconnecting or waiting for disconnection.
- completed: DFU operation is completed and successful.
- aborted: DFU Operation was aborted.
*/
@objc public enum DFUState : Int {
case connecting
case starting
case enablingDfuMode
case uploading
case validating
case disconnecting
case completed
case aborted
public func description() -> String {
switch self {
case .connecting: return "Connecting"
case .starting: return "Starting"
case .enablingDfuMode: return "Enabling DFU Mode"
case .uploading: return "Uploading"
case .validating: return "Validating" // this state occurs only in Legacy DFU
case .disconnecting: return "Disconnecting"
case .completed: return "Completed"
case .aborted: return "Aborted"
}
}
}
/**
* The progress delegates may be used to notify user about progress updates.
* The only method of the delegate is only called when the service is in the Uploading state.
*/
@objc public protocol DFUProgressDelegate {
/**
Callback called in the `State.Uploading` state. Gives detailed information about the progress
and speed of transmission. This method is always called at least two times (for 0% and 100%)
if upload has started and did not fail.
This method is called in the main thread and is safe to update any UI.
- parameter part: Number of part that is currently being transmitted. Parts start from 1
and may have value either 1 or 2. Part 2 is used only when there were Soft Device and/or
Bootloader AND an Application in the Distribution Packet and the DFU target does not
support sending all files in a single connection. First the SD and/or BL will be sent, then
the service will disconnect, reconnect again to the (new) bootloader and send the Application.
- parameter totalParts: Total number of parts that are to be send (this is always equal to 1 or 2).
- parameter progress: The current progress of uploading the current part in percentage (values 0-100).
Each value will be called at most once - in case of a large file a value e.g. 3% will be called only once,
despite that it will take more than one packet to reach 4%. In case of a small firmware file
some values may be ommited. For example, if firmware file would be only 20 bytes you would get
a callback 0% (called always) and then 100% when done.
- parameter currentSpeedBytesPerSecond: The current speed in bytes per second.
- parameter avgSpeedBytesPerSecond: The average speed in bytes per second.
*/
@objc func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int,
currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double)
}
/**
* The service delegate reports about state changes and errors.
*/
@objc public protocol DFUServiceDelegate {
/**
Callback called when state of the DFU Service has changed.
This method is called in the main thread and is safe to update any UI.
- parameter state: the new state fo the service
*/
@objc func dfuStateDidChange(to state: DFUState)
/**
Called after an error occurred.
The device will be disconnected and DFU operation has been aborted.
This method is called in the main thread and is safe to update any UI.
- parameter error: the error code
- parameter message: error description
*/
@objc func dfuError(_ error: DFUError, didOccurWithMessage message: String)
}
| mit | 56b2b0688e6734e6cba11d428e1a0efc | 49.929293 | 144 | 0.690401 | 4.984676 | false | false | false | false |
Liquidsoul/LocalizationConverter | Sources/LocalizationConverter/Formatters/StringsDictFormatter.swift | 1 | 2369 | //
// StringsDictFormatter.swift
//
// Created by Sébastien Duperron on 14/05/2016.
// Copyright © 2016 Sébastien Duperron
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
struct StringsDictFormatter {
func format(_ localization: LocalizationMap) throws -> Data {
let stringsDict = try self.stringsDict(from: localization)
return try PropertyListSerialization.data(fromPropertyList: stringsDict, format: .xml, options: 0)
}
func stringsDict(from localization: LocalizationMap) throws -> NSDictionary {
let localizations = localization.convertedLocalization(to: .ios).localizations
let pluralLocalizations = plurals(from: localizations)
if pluralLocalizations.count == 0 {
throw Error.noPlurals
}
let stringsDict = NSMutableDictionary()
try pluralLocalizations.forEach { (key, values) in
guard values[.other] != nil else {
throw Error.missingOtherKey
}
stringsDict[key] = stringsDictItem(with: values)
}
return stringsDict
}
fileprivate func plurals(from localizations: [String: LocalizationItem]) -> [String: [PluralType: String]] {
if localizations.count == 0 {
return [:]
}
var pluralLocalizations = [String: [PluralType: String]]()
localizations.forEach { (key, value) in
switch value {
case .string:
break
case .plurals(let values):
pluralLocalizations[key] = values
}
}
return pluralLocalizations
}
fileprivate func stringsDictItem(with values: [PluralType: String]) -> [String: Any] {
let initialValues: [String: Any] = [
"NSStringFormatSpecTypeKey": "NSStringPluralRuleType",
"NSStringFormatValueTypeKey": "d"
]
return [
"NSStringLocalizedFormatKey": "%#@elements@",
"elements": values.reduce(initialValues as [String: Any], { (elements, pair) -> [String: Any] in
var outputValues = elements
outputValues[pair.0.rawValue] = pair.1
return outputValues
})
]
}
enum Error: Swift.Error {
case noPlurals
case missingOtherKey
}
}
| mit | 36220bb0b8b835c60f271835721a391b | 31.861111 | 112 | 0.608199 | 4.981053 | false | false | false | false |
kdawgwilk/KarmaAPI | Sources/App/Models/Task.swift | 1 | 1819 | import Vapor
import Fluent
import Foundation
final class Task: BaseModel, Model {
var name: String
var groupID: Node?
var description: String?
var points: Int
init(name: String, description: String? = nil, points: Int = 5, group: Group) {
self.name = name
self.groupID = group.id
self.points = points
super.init()
}
override init(node: Node, in context: Context) throws {
name = try node.extract("name")
groupID = try node.extract("group_id")
description = try node.extract("description")
points = try node.extract("points") ?? 5
try super.init(node: node, in: context)
}
override func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"created_on": createdOn,
"name": name,
"group_id": groupID,
"description": description,
"points": points
])
}
}
extension Task: Preparation {
static func prepare(_ database: Database) throws {
try database.create("tasks") { task in
prepare(model: task)
task.string("name")
task.string("group_id")
task.string("description", optional: true)
task.int("points")
}
}
static func revert(_ database: Database) throws {
try database.delete("tasks")
}
}
// MARK: Merge
extension Task {
func merge(updates: Task) {
super.merge(updates: updates)
name = updates.name
groupID = updates.groupID ?? groupID
description = updates.description ?? description
points = updates.points
}
}
// MARK: Relationships
extension Task {
func group() throws -> Parent<Group> {
return try parent(groupID)
}
}
| mit | 9061ba4b2d3b3f31d9ade2f7043e1f1e | 23.917808 | 83 | 0.576141 | 4.28 | false | false | false | false |
fly19890211/WordPress-iOS | WordPress/Classes/Networking/PushAuthenticationServiceRemote.swift | 3 | 1731 | import Foundation
/**
* @class PushAuthenticationServiceRemote
* @brief The purpose of this class is to encapsulate all of the interaction with the REST endpoint,
* required to handle WordPress.com 2FA Code Veritication via Push Notifications
*/
@objc public class PushAuthenticationServiceRemote
{
/**
* @details Designated Initializer. Fails if the remoteApi is nil.
* @param remoteApi A Reference to the WordPressComApi that should be used to interact with WordPress.com
*/
init?(remoteApi: WordPressComApi!) {
self.remoteApi = remoteApi
if remoteApi == nil {
return nil
}
}
/**
* @details Verifies a WordPress.com Login.
* @param token The token passed on by WordPress.com's 2FA Push Notification.
* @param success Closure to be executed on success. Can be nil.
* @param failure Closure to be executed on failure. Can be nil.
*/
public func authorizeLogin(token: String, success: (() -> ())?, failure: (() -> ())?) {
let path = "me/two-step/push-authentication"
let parameters = [
"action" : "authorize_login",
"push_token" : token
]
remoteApi.POST(path,
parameters: parameters,
success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
success?()
},
failure:{ (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
failure?()
})
}
// MARK: - Private Internal Constants
private var remoteApi: WordPressComApi!
}
| gpl-2.0 | b83ec12e8f149d0777ffb3520efb77cc | 33.62 | 115 | 0.580012 | 4.931624 | false | false | false | false |
pepe/QRCode | QRCode/CIColorExtension.swift | 2 | 2159 | //
// CIColorExtension.swift
// Example
//
// Created by Alexander Schuch on 27/01/15.
// Copyright (c) 2015 Alexander Schuch. All rights reserved.
//
import UIKit
public extension CIColor {
/// Creates a CIColor from an rgba string
///
/// E.g.
/// `aaa`
/// `ff00`
/// `bb00ff`
/// `aabbccff`
///
/// :param: rgba The hex string to parse in rgba format
public convenience init(rgba: String) {
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 1.0
let scanner = NSScanner(string: rgba)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
let length = countElements(rgba)
switch (length) {
case 3:
r = CGFloat((hexValue & 0xF00) >> 8) / 15.0
g = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
b = CGFloat(hexValue & 0x00F) / 15.0
case 4:
r = CGFloat((hexValue & 0xF000) >> 12) / 15.0
g = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
b = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
a = CGFloat(hexValue & 0x000F) / 15.0
case 6:
r = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
g = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
b = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
r = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
g = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
b = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
a = CGFloat(hexValue & 0x000000FF) / 255.0
default:
println("Invalid number of values (\(length)) in HEX string. Make sure to enter 3, 4, 6 or 8 values. E.g. `aabbccff`")
}
} else {
println("Invalid HEX value: \(rgba)")
}
self.init(red: r, green: g, blue: b, alpha: a)
}
}
| mit | 14b629e3adb9b63d0383f76001e62f6d | 32.734375 | 134 | 0.464104 | 3.761324 | false | false | false | false |
qvik/HelsinkiOS-IBD-Demo | HelsinkiOS-Demo/Views/ExampleInspectables.swift | 1 | 4550 | //
// ExampleInspectables.swift
// HelsinkiOS-Demo
//
// Created by Jerry Jalava on 30/09/15.
// Copyright © 2015 Qvik. All rights reserved.
//
import UIKit
enum ExampleEnum {
case Value1
case Value2
}
@IBDesignable class ExampleInspectables: UIView {
@IBInspectable var stringInput:String = "A String"
@IBInspectable var nsStringInput:NSString = "NSString"
@IBInspectable var integerInput:Int!
@IBInspectable var cgFloatInput:CGFloat!
@IBInspectable var floatingPointInput:Double!
@IBInspectable var booleanInput:Bool = true
@IBInspectable var colorPicker:UIColor!
@IBInspectable var pointInput:CGPoint!
@IBInspectable var areaInput:CGRect = CGRect(x: 0, y: 0, width: 100, height: 100)
@IBInspectable var sizeInput:CGSize!
// This variable isn't in camelCase
@IBInspectable var badlynamedvariable:String!
@IBInspectable var borderColor:UIColor = UIColor.appPink() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 1 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius:CGFloat = 2 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var circleColor: UIColor = UIColor(red: (171.0/255.0), green: (250.0/255), blue: (81.0/255.0), alpha: 1.0)
@IBInspectable var circleRadius:CGFloat = 150
// items that don't display in IB
@IBInspectable var enumInput:ExampleEnum = .Value1
@IBInspectable var layoutConstraint:NSLayoutConstraint!
@IBInspectable var listValues:[String]!
@IBInspectable var edgeInsets:UIEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
@IBInspectable var cgVectorInput:CGVector!
@IBInspectable var cgTransform:CGAffineTransform! = CGAffineTransformIdentity
@IBInspectable var nsDate:NSDate!
// MARK: Lifecycle
required override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupView()
}
override func prepareForInterfaceBuilder() {
self.setupView()
}
func setupView() {
layer.borderColor = borderColor.CGColor
layer.borderWidth = borderWidth
layer.cornerRadius = cornerRadius
}
override func drawRect(rect: CGRect) {
// self.addCirle(self.circleRadius, capRadius: 20, color: self.circleColor)
}
// MARK: Private methods
func addCirle(arcRadius: CGFloat, capRadius: CGFloat, color: UIColor) {
let X = CGRectGetMidX(self.bounds)
let Y = CGRectGetMidY(self.bounds)
// Bottom Oval
let pathBottom = UIBezierPath(ovalInRect: CGRectMake((X - (arcRadius/2)), (Y - (arcRadius/2)), arcRadius, arcRadius)).CGPath
self.addOval(20.0, path: pathBottom, strokeStart: 0, strokeEnd: 0.5, strokeColor: color, fillColor: UIColor.clearColor(), shadowRadius: 0, shadowOpacity: 0, shadowOffsset: CGSizeZero)
// Middle Cap
let pathMiddle = UIBezierPath(ovalInRect: CGRectMake((X - (capRadius/2)) - (arcRadius/2), (Y - (capRadius/2)), capRadius, capRadius)).CGPath
self.addOval(0.0, path: pathMiddle, strokeStart: 0, strokeEnd: 1.0, strokeColor: color, fillColor: color, shadowRadius: 5.0, shadowOpacity: 0.5, shadowOffsset: CGSizeZero)
// Top Oval
let pathTop = UIBezierPath(ovalInRect: CGRectMake((X - (arcRadius/2)), (Y - (arcRadius/2)), arcRadius, arcRadius)).CGPath
self.addOval(20.0, path: pathTop, strokeStart: 0.5, strokeEnd: 1.0, strokeColor: color, fillColor: UIColor.clearColor(), shadowRadius: 0, shadowOpacity: 0, shadowOffsset: CGSizeZero)
}
func addOval(lineWidth: CGFloat, path: CGPathRef, strokeStart: CGFloat, strokeEnd: CGFloat, strokeColor: UIColor, fillColor: UIColor, shadowRadius: CGFloat, shadowOpacity: Float, shadowOffsset: CGSize) {
let arc = CAShapeLayer()
arc.lineWidth = lineWidth
arc.path = path
arc.strokeStart = strokeStart
arc.strokeEnd = strokeEnd
arc.strokeColor = strokeColor.CGColor
arc.fillColor = fillColor.CGColor
arc.shadowColor = UIColor.blackColor().CGColor
arc.shadowRadius = shadowRadius
arc.shadowOpacity = shadowOpacity
arc.shadowOffset = shadowOffsset
layer.addSublayer(arc)
}
}
| mit | 12d66ec54fd5f54cb1c1e1ec01081b31 | 36.908333 | 207 | 0.667399 | 4.499505 | false | false | false | false |
corey-lin/swift-tasks | Task2-MapKit/Task2-MapKit/RegionMapViewController.swift | 1 | 1722 | //
// RegionMapViewController.swift
// Task2-MapKit
//
// Created by coreylin on 4/1/16.
// Copyright © 2016 coreylin. All rights reserved.
//
import MapKit
class RegionMapViewController: UIViewController {
@IBOutlet var mapView: MKMapView!
override func viewDidLoad() {
mapView.delegate = self
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.destinationViewController is RegionListViewController {
let regionList = segue.destinationViewController as! RegionListViewController
regionList.delegate = self
regionList.selectFinished = {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
}
extension RegionMapViewController: RegionsProtocol {
func loadOverlayForRegionWithLatitude(latitude: Double, andLongitude longitude: Double) {
mapView.removeOverlays(mapView.overlays)
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let circle = MKCircle(centerCoordinate: coordinate, radius: 200000)
mapView.setRegion(MKCoordinateRegionMakeWithDistance(coordinate, 800000, 800000), animated: true)
mapView.addOverlay(circle)
}
}
extension RegionMapViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
if let circle = overlay as? MKCircle {
let circleRenderer = MKCircleRenderer(circle: circle)
circleRenderer.fillColor = UIColor.redColor().colorWithAlphaComponent(0.1)
circleRenderer.strokeColor = UIColor.redColor()
circleRenderer.lineWidth = 1
return circleRenderer
} else {
return MKOverlayRenderer(overlay: overlay);
}
}
}
| mit | aa9683d240e3ce702d7f12cbe279fbe5 | 32.096154 | 101 | 0.750145 | 4.945402 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Core/NavigationControllerMemento.swift | 1 | 1582 | import Foundation
class NavigationControllerMemento {
var navBarTintColor: UIColor?
var navTintColor: UIColor?
var navTitleTextAttributes: [NSAttributedString.Key: Any]?
var navIsTranslucent: Bool = false
var navViewBackgroundColor: UIColor?
var navBackgroundColor: UIColor?
var navBackgroundImage: UIImage?
var navShadowImage: UIImage?
var navBarStyle: UIBarStyle?
weak var customDelegate: UINavigationControllerDelegate?
var swipeBackGesture: Bool = true
var isNavigationBarHidden: Bool = true
init(navigationController: UINavigationController) {
navBarTintColor = navigationController.navigationBar.barTintColor
navTintColor = navigationController.navigationBar.tintColor
navTitleTextAttributes = navigationController.navigationBar.titleTextAttributes
navIsTranslucent = navigationController.navigationBar.isTranslucent
navViewBackgroundColor = navigationController.view.backgroundColor
navBackgroundColor = navigationController.navigationBar.backgroundColor
navBackgroundImage = navigationController.navigationBar.backgroundImage(for: .default)
navShadowImage = navigationController.navigationBar.shadowImage
navBarStyle = navigationController.navigationBar.barStyle
customDelegate = navigationController.delegate
isNavigationBarHidden = navigationController.isNavigationBarHidden
if let backGesture = navigationController.interactivePopGestureRecognizer?.isEnabled {
swipeBackGesture = backGesture
}
}
}
| mit | 1e351b451194419a6cb65716c09093fd | 46.939394 | 94 | 0.780025 | 6.848485 | false | false | false | false |
siejkowski/swift-dsl-toolbelt | 7-ending.playground/section-1.swift | 1 | 207 | enum Show { case IsFinished }
let author = "Krzysztof Siejkowski"
let twitter = "@_siejkowski"
let company = "Touk"
let reason = "Swift Warsaw"
let source = "https://github.com/siejkowski/swift-dsl-toolbelt" | mit | 5923c9acc50db699d612a993c7eb01b2 | 33.666667 | 63 | 0.73913 | 2.915493 | false | false | false | false |
fedepo/phoneid_iOS | Pod/Classes/ui/customization/UICustomization.swift | 2 | 9489 | //
// UICustomization.swift
// phoneid_iOS
//
// Copyright 2015 phone.id - 73 knots, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public protocol Customizable: NSObjectProtocol{
var colorScheme: ColorScheme! {get }
var localizationBundle:Bundle! {get }
var localizationTableName:String! {get }
}
@objcMembers
open class ColorScheme : NSObject{
// MARK: Common colors defining color scheme
open var mainAccent:UIColor = UIColor(hex: 0x009688)
open var extraAccent:UIColor = UIColor(hex: 0x00796B)
open var lightText:UIColor = UIColor(hex: 0xFFFFFF)
open var darkText:UIColor = UIColor(hex: 0x000000)
open var disabledText:UIColor = UIColor(hex: 0xB0B0B0)
open var inputBackground:UIColor = UIColor(hex: 0xFFFFFF)
open var diabledBackground:UIColor = UIColor(hex: 0xEFEFF4)
open var activityIndicator:UIColor = UIColor(hex: 0x203034).withAlphaComponent(0.75)
open var success:UIColor = UIColor(hex: 0x037AFF)
open var fail:UIColor = UIColor(hex: 0xD0021B)
// MARK: Specific colors: phone.id button
open var activityIndicatorInitial:UIColor!
open var buttonSeparator:UIColor!
// phone.id button background
open var buttonDisabledBackground:UIColor!
open var buttonNormalBackground:UIColor!
open var buttonHighlightedBackground:UIColor!
// phone.id button image
open var buttonDisabledImage:UIColor!
open var buttonNormalImage:UIColor!
open var buttonHighlightedImage:UIColor!
// phone.id button text
open var buttonDisabledText:UIColor!
open var buttonNormalText:UIColor!
open var buttonHighlightedText:UIColor!
// MARK: Specific colors: fullscreen mode
open var mainViewBackground:UIColor!
open var labelTopNoteText:UIColor!
open var labelMidNoteText:UIColor!
open var labelBottomNoteText:UIColor!
open var labelBottomNoteLinkText:UIColor!
open var headerBackground:UIColor!
open var headerTitleText:UIColor!
open var headerButtonText:UIColor!
// MARK: Specific colors: related to number input
open var activityIndicatorNumber:UIColor!
open var buttonOKNormalText:UIColor!
open var buttonOKHighlightedText:UIColor!
open var buttonOKDisabledText:UIColor!
open var inputPrefixText:UIColor!
open var inputNumberText:UIColor!
open var inputNumberPlaceholderText:UIColor!
open var inputNumberBackground:UIColor!
// MARK: Specific colors: related to code verification
open var activityIndicatorCode:UIColor!
open var inputCodeBackbuttonNormal:UIColor!
open var inputCodeBackbuttonDisabled:UIColor!
open var inputCodePlaceholder:UIColor!
open var inputCodeText:UIColor!
open var inputCodeBackground:UIColor!
open var inputCodeFailIcon:UIColor!
open var inputCodeSuccessIcon:UIColor!
// MARK: Specific colors: related to country-code picker
open var labelPrefixText:UIColor!
open var labelCountryNameText:UIColor!
open var labelPrefixBackground:UIColor!
open var sectionIndexText:UIColor!
// MARK: Specific colors: related to profile
open var profileCommentSectionText:UIColor!
open var profileCommentSectionBackground:UIColor!
open var profileDataSectionTitleText:UIColor!
open var profileDataSectionValueText:UIColor!
open var profileDataSectionBackground:UIColor!
open var profilePictureSectionBackground:UIColor!
open var profilePictureBackground:UIColor!
open var profileTopUsernameText:UIColor!
open var profilePictureEditingHintText:UIColor!
open var profileActivityIndicator:UIColor!
override public init() {
super.init()
applyCommonColors()
}
open func applyCommonColors(){
/// Colors of phone.id button
activityIndicatorInitial = activityIndicator
buttonSeparator = darkText.withAlphaComponent(0.12)
buttonDisabledBackground = diabledBackground
buttonNormalBackground = mainAccent
buttonHighlightedBackground = extraAccent
buttonDisabledImage = disabledText
buttonNormalImage = lightText
buttonHighlightedImage = disabledText
buttonDisabledText = disabledText
buttonNormalText = lightText
buttonHighlightedText = disabledText
/// Colors common for fullscreen mode
mainViewBackground = mainAccent
labelTopNoteText = lightText
labelMidNoteText = lightText
labelBottomNoteText = darkText
labelBottomNoteLinkText = darkText
headerBackground = extraAccent
headerTitleText = lightText
headerButtonText = lightText
/// Colors of number input
activityIndicatorNumber = activityIndicator
buttonOKNormalText = mainAccent
buttonOKHighlightedText = extraAccent
buttonOKDisabledText = disabledText
inputPrefixText = mainAccent
inputNumberText = darkText
inputNumberPlaceholderText = disabledText
inputNumberBackground = inputBackground
/// Colors of verification code input
activityIndicatorCode = activityIndicator
inputCodeBackbuttonNormal = mainAccent
inputCodeBackbuttonDisabled = disabledText
inputCodePlaceholder = mainAccent
inputCodeText = darkText
inputCodeBackground = inputBackground
inputCodeFailIcon = fail
inputCodeSuccessIcon = success
/// Colors of country-code picker
labelPrefixText = lightText
labelCountryNameText = darkText
labelPrefixBackground = mainAccent
sectionIndexText = mainAccent
/// Colors of profile
profileCommentSectionText = darkText
profileCommentSectionBackground = diabledBackground
profileDataSectionTitleText = darkText
profileDataSectionValueText = disabledText
profileDataSectionBackground = inputBackground
profilePictureSectionBackground = mainAccent
profilePictureBackground = inputBackground
profileTopUsernameText = lightText
profilePictureEditingHintText = darkText
profileActivityIndicator = activityIndicator
}
}
public extension ColorScheme {
func replaceNamedColors(_ input:String)->String
{
let result:NSMutableString = input.mutableCopy() as! NSMutableString
let members = Mirror(reflecting: self).children
var names = [String]()
for (name,_) in members
{
if name == "super"{continue}
names.append(name!)
}
for name in names{
if let color = ((self as AnyObject).value(forKeyPath: name) as? UIColor){
let hexColor = color.hexString()
result.replaceOccurrences(of: "$\(name)", with: hexColor, options:NSString.CompareOptions.literal, range: NSMakeRange(0, result.length))
}
}
return result as String
}
}
public extension Customizable{
internal func localizedString(_ key:String, formatting:((String)->String)? = nil) ->String{
var result = NSLocalizedString(key, tableName: localizationTableName , bundle: localizationBundle, comment:key)
// TODO: this is actually not a part of localization.
// However text-formatting appeared to be tightly coupled with text-content.
// Need more graceful solution
result = self.colorScheme.replaceNamedColors(result)
if let formatting = formatting{
result = formatting(result)
}
return result
}
internal func localizedStringAttributed(_ key:String, formatting:((String)->String)? = nil) ->NSAttributedString{
let text = localizedString(key, formatting: formatting)
let accessAttributedText = try! NSAttributedString(
data: text.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
return accessAttributedText
}
}
public extension UIColor {
@objc public convenience init(red: Int, green: Int, blue: Int) {
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
@objc public convenience init(hex:Int) {
self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff)
}
@objc public func hexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
}
| apache-2.0 | b61f46432a0b12fd01e8a340090516a9 | 35.496154 | 152 | 0.690378 | 5.085209 | false | false | false | false |
i-schuetz/clojushop_client_ios_swift | clojushop_client_ios/ProductsListViewController.swift | 1 | 3503 | //
// ProductsListViewController2.swift
// clojushop_client_ios
//
// Created by ischuetz on 08/06/2014.
// Copyright (c) 2014 ivanschuetz. All rights reserved.
//
import UIKit
class ProductsListViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate, UISplitViewControllerDelegate {
var products:Product[]!
@IBOutlet var tableView:UITableView!
var detailsViewController:ProductDetailViewController!
init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.title = "Rest client"
}
override func viewDidLoad() {
super.viewDidLoad()
let productCellNib:UINib = UINib(nibName: "CSProductCell", bundle: nil)
tableView.registerNib(productCellNib, forCellReuseIdentifier: "CSProductCell")
self.requestProducts()
}
func requestProducts() {
self.setProgressHidden(false)
DataStore.sharedDataStore().getProducts(0, size: 4,
successHandler: {(products:Product[]!) -> Void in
self.setProgressHidden(true)
self.onRetrievedProducts(products)
},
failureHandler: {(Int) -> Bool in
return false
})
}
func onRetrievedProducts(products:Product[]) {
self.products = products
tableView.reloadData()
}
func tableView(tableView:UITableView, numberOfRowsInSection section:NSInteger) -> Int {
return products ? products.count : 0
}
func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell! {
let cellIdentifier:String = "CSProductCell"
let cell:ProductCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as ProductCell
let product:Product = products[indexPath.row]
cell.productName.text = product.name
cell.productDescr.text = product.descr
cell.productBrand.text = product.seller
cell.productPrice.text = CurrencyManager.sharedCurrencyManager().getFormattedPrice(product.price, currencyId: product.currency)
cell.productImg.setImageWithURL(NSURL.URLWithString(product.imgList))
return cell
}
func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
let product = products[indexPath.row]
if !self.splitViewController {
let detailsViewController:ProductDetailViewController = ProductDetailViewController(nibName: "CSProductDetailsViewController", bundle: nil)
detailsViewController.product = product
detailsViewController.listViewController(product)
navigationController.pushViewController(detailsViewController, animated: true)
} else {
detailsViewController.listViewController(product)
}
}
func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> Double {
return 133
}
func splitViewController(svc: UISplitViewController!, willShowViewController aViewController: UIViewController!, invalidatingBarButtonItem barButtonItem: UIBarButtonItem!) {
if (barButtonItem == self.navigationItem.leftBarButtonItem) {
self.navigationItem.setLeftBarButtonItem(nil, animated: false)
}
}
}
| apache-2.0 | 1bb277f6f6e34558948e3fbc9e38c77b | 35.489583 | 177 | 0.677705 | 5.771005 | false | false | false | false |
taka0125/TAKKitSwift | Example/ios/TAKKitSwiftSample/PhotoSelectorSampleViewController.swift | 1 | 2484 | //
// PhotoSelectorSampleViewController.swift
// TAKKitSwift
//
// Created by Takahiro Ooishi
// Copyright (c) 2015 Takahiro Ooishi. All rights reserved.
// Released under the MIT license.
//
import Foundation
import UIKit
import TAKKitSwift
class PhotoSelectorSampleViewController: UITableViewController {
@IBOutlet fileprivate weak var imageView: UIImageView!
fileprivate var selector: PhotoSelector?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section != 1 { return }
switch indexPath.row {
case 0:
launchPhotoLibrary(allowEditing: false)
case 1:
launchPhotoLibrary(allowEditing: true)
case 2:
launchFrontCamera()
case 3:
launchRearCamera()
default:
break
}
}
override func viewDidLoad() {
selector = PhotoSelector()
}
fileprivate func launchPhotoLibrary(allowEditing: Bool) {
selector?.launchPhotoLibrary(allowEditing,
success: { [weak self] image in
self?.imageView.image = image
},
failure: { error in
switch error {
case .photoAccessDenied:
TAKAlert.show("Photo access denied.")
case .cancelled:
TAKAlert.show("Cancelled")
default:
print(error)
}
}
)
}
fileprivate func launchFrontCamera() {
selector?.launchFrontCamera(true,
success: { [weak self] image in
self?.imageView.image = image
},
failure: { error in
switch error {
case .cameraIsNotAvailable, .frontCameraIsNotAvailable:
TAKAlert.show("Can't launch front camera.")
case .cameraAccessDenied:
TAKAlert.show("Camera access denied.")
case .cancelled:
TAKAlert.show("Cancelled")
default:
print(error)
}
}
)
}
fileprivate func launchRearCamera() {
selector?.launchRearCamera(true,
success: { [weak self] image in
self?.imageView.image = image
},
failure: { error in
switch error {
case .cameraIsNotAvailable, .rearCameraIsNotAvailable:
TAKAlert.show("Can't launch rear camera.")
case .cameraAccessDenied:
TAKAlert.show("Camera access denied.")
case .cancelled:
TAKAlert.show("Cancelled")
default:
print(error)
}
}
)
}
}
| mit | 41a9a5c295df6075d501aa6c9a318b38 | 24.090909 | 90 | 0.623994 | 4.851563 | false | false | false | false |
jawwad/swift-algorithm-club | Introsort/Introsort.playground/Sources/HeapSort.swift | 6 | 1719 | import Foundation
private func shiftDown<T>(_ elements: inout [T], _ index: Int, _ range: Range<Int>, by areInIncreasingOrder: (T, T) -> Bool) {
let countToIndex = elements.distance(from: range.lowerBound, to: index)
let countFromIndex = elements.distance(from: index, to: range.upperBound)
guard countToIndex + 1 < countFromIndex else { return }
let left = elements.index(index, offsetBy: countToIndex + 1)
var largest = index
if areInIncreasingOrder(elements[largest], elements[left]) {
largest = left
}
if countToIndex + 2 < countFromIndex {
let right = elements.index(after: left)
if areInIncreasingOrder(elements[largest], elements[right]) {
largest = right
}
}
if largest != index {
elements.swapAt(index, largest)
shiftDown(&elements, largest, range, by: areInIncreasingOrder)
}
}
private func heapify<T>(_ list: inout [T], _ range: Range<Int>, by areInIncreasingOrder: (T, T) -> Bool) {
let root = range.lowerBound
var node = list.index(root, offsetBy: list.distance(from: range.lowerBound, to: range.upperBound)/2)
while node != root {
list.formIndex(before: &node)
shiftDown(&list, node, range, by: areInIncreasingOrder)
}
}
public func heapsort<T>(for array: inout [T], range: Range<Int>, by areInIncreasingOrder: (T, T) -> Bool) {
var hi = range.upperBound
let lo = range.lowerBound
heapify(&array, range, by: areInIncreasingOrder)
array.formIndex(before: &hi)
while hi != lo {
array.swapAt(lo, hi)
shiftDown(&array, lo, lo..<hi, by: areInIncreasingOrder)
array.formIndex(before: &hi)
}
}
| mit | 9d43279767a6131a130286e85ffb7330 | 33.38 | 126 | 0.641652 | 4.025761 | false | false | false | false |
zadr/conservatory | Code/Components/Geometry.swift | 1 | 9407 | /**
The native Point type in Conservatory, used to represent an x, y coordinate on a coordinate system .
*/
public struct Point {
public let x: Double
public let y: Double
/**
Initialize a *Point* object by passing in *x*, and *y* values as *Int*s.
- Parameter x: An integral value that controls the *x* value. There is no default value.
- Parameter y: A integral value that controls the *y* channel. There is no default value.
*/
public init(x _x: Int, y _y: Int) {
self.init(x: Double(_x), y: Double(_y))
}
/**
Initialize a *Point* object by passing in *x*, and *y* values as *Double*s.
- Parameter x: A decimal value that controls the *x* value. The default value is **0.0**.
- Parameter y: A decimal value that controls the *y* channel. The default value is **0.0**.
*/
public init(x _x: Double = 0.0, y _y: Double = 0.0) {
x = _x
y = _y
}
/**
- Returns: An empty Point, with the *x* and *y* values of **0.0**.
*/
public static var zero: Point {
return Point()
}
/**
- Parameter transform: A *Transform* to apply to the a point.
- Returns: A new *Point*.
*/
public func apply(_ transform: Transform) -> Point {
return transform.apply(to: self)
}
/**
- Parameter point: A second point in the current coordinate space.
- Returns: The angle required to join two points together.
*/
public func angle(_ point: Point) -> Double {
return Degree(degrees: (point.y - y).arcTangent(point.x - x))
}
/**
- Parameter point: A second point in the current coordinate space.
- Returns: The distance between two points.
*/
public func distance(_ point: Point) -> Double {
return Degree(degrees: ((point.x - x).squareRoot() ** 2) + ((point.y - y) ** 2))
}
/**
- Parameter radius: How far away from the current coordinate are we going.
- Parameter angle: How far to rotate from the current coordinate before drawing a line *radius* units long.
- Returns: A new coordinate radius units away at angle° from the current point.
*/
public func coordinate(_ radius: Double, angle: Degree) -> Point {
precondition(angle > -360.0)
precondition(angle < 360.0)
return Point(
x: Radian(angle).cosine * radius,
y: Radian(angle).sine * radius
)
}
}
extension Point: CustomStringConvertible {
public var description: String {
return "Point(x: \(x), y: \(y))"
}
}
extension Point: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
_ = hasher.finalize()
}
}
public func ==(x: Point, y: Point) -> Bool {
return x.x == y.x && x.y == y.y
}
public func +(x: Point, y: Point) -> Point {
return Point(x: x.x + y.x, y: x.y + y.y)
}
public func -(x: Point, y: Point) -> Point {
return Point(x: x.x - y.x, y: x.y - y.y)
}
public func +=(x: inout Point, y: Point) {
x = x + y
}
public func -=(x: inout Point, y: Point) {
x = x - y
}
// MARK: -
/**
The native Size type in Conservatory, used to represent the width and height of an object in a coordinate system.
*/
public struct Size {
public var width: Double
public var height: Double
/**
Initialize a *Size* object by passing in *width*, and *height* values as *Int*s.
- Parameter width: An integral value that controls the *width* value. There is no default value.
- Parameter height: A integral value that controls the *height* channel. There is no default value.
*/
public init(width _width: Int, height _height: Int) {
self.init(width: Double(_width), height: Double(_height))
}
/**
Initialize a *Size* object by passing in *width*, and *height* values as *Double*s.
- Parameter width: A decimal value that controls the *width* value. The default value is **0.0**.
- Parameter height: A decimal value that controls the *height* channel. The default value is **0.0**.
*/
public init(width _width: Double = 0.0, height _height: Double = 0.0) {
width = _width
height = _height
}
/**
- Returns: An empty Size, with the *width* and *height* values of **0.0**.
*/
public static var zero: Size {
return Size()
}
}
extension Size: CustomStringConvertible {
public var description: String {
return "Size(width: \(width), height: \(height))"
}
}
extension Size: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(width)
hasher.combine(height)
_ = hasher.finalize()
}
}
public func ==(x: Size, y: Size) -> Bool {
return x.width == y.width && x.height == y.height
}
public func +(x: Size, y: Size) -> Size {
return Size(width: x.width + y.width, height: x.height + y.height)
}
public func -(x: Size, y: Size) -> Size {
return Size(width: x.width - y.width, height: x.height - y.height)
}
public func *(x: Size, y: Double) -> Size {
return Size(width: x.width * y, height: x.height * y)
}
public func /(x: Size, y: Double) -> Size {
return Size(width: x.width / y, height: x.height / y)
}
public func +=(x: inout Size, y: Size) {
x = x + y
}
public func -=(x: inout Size, y: Size) {
x = x - y
}
public func *=(x: inout Size, y: Double) {
x = x * y
}
public func /=(x: inout Size, y: Double) {
x = x / y
}
// MARK: -
/**
A *Grid* is an enumeration to represent dimensions of a coordinate system.
*/
public enum Grid {
/**
A *Column* is an enumeration of vertical positions within a coordinate system.
*/
public enum Column {
case top
case middle
case bottom
}
/**
A *Row* is an enumeration of horizontal positions within a coordinate system.
*/
public enum Row {
case left
case center
case right
}
}
// Do we really need this?
/**
The native bounding box type in Conservatory, combines a *Point* and a *Size* to represent the area and volume of an object in a coordinate system.
*/
public struct Box {
public var location: Point
public var size: Size
/**
Initialize a *Box* object by passing in a *location*, and *size* values.
- Parameter location: A *Point* that represents the topmost, leftmost corner of a bounding box.
- Parameter size: A *Size* that represents the area of a bounding box.
*/
public init(location _location: Point = Point.zero, size _size: Size = Size.zero) {
location = _location
size = _size
}
/**
- Returns: an empty *Box*, equivalent to `Box(Point.zero, size: Size.zero)`.
*/
public static var zero: Box {
return Box()
}
/**
- Returns: the *Point* of a requested section of the box.
- Parameter horizontal: The requested *x* coordinate. This parameter is required.
- Parameter vertical: The requested *y* coordinate. This parameter is required.
```
let box = Box(location: Point(x: 10, y: 10),
size: Size(width: 10, height: 10))
let topLeft = box[.Left, .Top] // Point(x: 10, y: 10)
let midpoint = box[.Center, .Middle] // Point(x: 15, y: 15)
let bottomRight = box[.Right, .Bottom] // Point(x: 20, y: 20)
```
*/
subscript(horizontal: Grid.Row, vertical: Grid.Column) -> Point {
let x: Double = {
switch horizontal {
case .left:
return location.x
case .center:
return location.x + (size.width / 2.0)
case .right:
return location.x + size.width
}
}()
let y: Double = {
switch vertical {
case .top:
return location.y
case .middle:
return location.y + (size.height / 2.0)
case .bottom:
return location.y + size.height
}
}()
return Point(x: x, y: y)
}
/**
- Returns: A random coordinate within the current bounding box.
*/
public func randomCoordinate() -> Point {
return Point(x: Double.random(in: 0 ... size.width), y: Double.random(in: 0 ... size.height))
}
/**
Determines if a *Point* lies within a bounding box.
- Returns: **true** or **false**.
*/
public func contains(_ point: Point) -> Bool {
if point.x > size.width || point.x < 0.0 {
return false
}
if point.y > size.height || point.y < 0.0 {
return false
}
return true
}
}
extension Box: CustomStringConvertible {
public var description: String {
return "Box(location: \(location), size: \(size))"
}
}
extension Box: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(location)
hasher.combine(size)
_ = hasher.finalize()
}
}
public func ==(x: Box, y: Box) -> Bool {
return x.location == y.location && x.size == y.size
}
public func +(x: Box, y: Box) -> Box {
return Box(location: x.location + y.location, size: x.size + y.size)
}
public func +(x: Box, y: Point) -> Box {
return Box(location: x.location + y, size: x.size)
}
public func +(x: Box, y: Size) -> Box {
return Box(location: x.location, size: x.size + y)
}
public func -(x: Box, y: Box) -> Box {
return Box(location: x.location - y.location, size: x.size - y.size)
}
public func -(x: Box, y: Point) -> Box {
return Box(location: x.location - y, size: x.size)
}
public func -(x: Box, y: Size) -> Box {
return Box(location: x.location, size: x.size - y)
}
public func *(x: Box, y: Double) -> Box {
return Box(location: x.location, size: x.size * y)
}
public func /(x: Box, y: Double) -> Box {
return Box(location: x.location, size: x.size / y)
}
public func += (x: inout Box, y: Box) {
x = x + y
}
public func += (x: inout Box, y: Point) {
x = x + y
}
public func += (x: inout Box, y: Size) {
x = x + y
}
public func -= (x: inout Box, y: Box) {
x = x - y
}
public func -= (x: inout Box, y: Point) {
x = x - y
}
public func -= (x: inout Box, y: Size) {
x = x - y
}
public func *= (x: inout Box, y: Double) {
x = x * y
}
public func /= (x: inout Box, y: Double) {
x = x / y
}
| bsd-2-clause | e2cde2f5e01480596fcbcaade20a1e02 | 22.515 | 147 | 0.640336 | 2.9813 | false | false | false | false |
haskellswift/swift-package-manager | Sources/Basic/TerminalController.swift | 1 | 4354 | /*
This source file is part of the Swift.org open source project
Copyright 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 Swift project authors
*/
import libc
import func POSIX.getenv
/// A class to have better control on tty output streams: standard output and standard error.
/// Allows operations like cursor movement and colored text output on tty.
public final class TerminalController {
/// Terminal color choices.
public enum Color {
case noColor
case red
case green
case yellow
case cyan
case white
case black
case grey
/// Returns the color code which can be prefixed on a string to display it in that color.
fileprivate var string: String {
switch self {
case .noColor: return ""
case .red: return "\u{001B}[31m"
case .green: return "\u{001B}[32m"
case .yellow: return "\u{001B}[33m"
case .cyan: return "\u{001B}[36m"
case .white: return "\u{001B}[37m"
case .black: return "\u{001B}[30m"
case .grey: return "\u{001B}[30;1m"
}
}
}
/// Pointer to output stream to operate on.
private var stream: LocalFileOutputByteStream
/// Width of the terminal.
public let width: Int
/// Code to clear the line on a tty.
private let clearLineString = "\u{001B}[2K"
/// Code to end any currently active wrapping.
private let resetString = "\u{001B}[0m"
/// Code to make string bold.
private let boldString = "\u{001B}[1m"
/// Constructs the instance if the stream is a tty.
public init?(stream: LocalFileOutputByteStream) {
// Make sure this file stream is tty.
guard isatty(fileno(stream.fp)) != 0 else {
return nil
}
width = TerminalController.terminalWidth() ?? 80 // Assume default if we are not able to determine.
self.stream = stream
}
/// Tries to get the terminal width first using COLUMNS env variable and
/// if that fails ioctl method testing on stdout stream.
///
/// - Returns: Current width of terminal if it was determinable.
public static func terminalWidth() -> Int? {
// Try to get from environment.
if let columns = POSIX.getenv("COLUMNS"), let width = Int(columns) {
return width
}
// Try determining using ioctl.
var ws = winsize()
if ioctl(1, UInt(TIOCGWINSZ), &ws) == 0 {
return Int(ws.ws_col)
}
return nil
}
/// Flushes the stream.
public func flush() {
stream.flush()
}
/// Clears the current line and moves the cursor to beginning of the line..
public func clearLine() {
stream <<< clearLineString <<< "\r"
flush()
}
/// Moves the cursor y columns up.
public func moveCursor(y: Int) {
stream <<< "\u{001B}[\(y)A"
flush()
}
/// Writes a string to the stream.
public func write(_ string: String, inColor color: Color = .noColor, bold: Bool = false) {
writeWrapped(string, inColor: color, bold: bold, stream: stream)
flush()
}
/// Inserts a new line character into the stream.
public func endLine() {
stream <<< "\n"
flush()
}
/// Wraps the string into the color mentioned.
public func wrap(_ string: String, inColor color: Color, bold: Bool = false) -> String {
let stream = BufferedOutputByteStream()
writeWrapped(string, inColor: color, bold: bold, stream: stream)
guard let string = stream.bytes.asString else {
fatalError("Couldn't get string value from stream.")
}
return string
}
private func writeWrapped(_ string: String, inColor color: Color, bold: Bool = false, stream: OutputByteStream) {
// Don't wrap if string is empty or color is no color.
guard !string.isEmpty && color != .noColor else {
stream <<< string
return
}
stream <<< color.string <<< (bold ? boldString : "") <<< string <<< resetString
}
}
| apache-2.0 | 945aa70f4ea7afd9ca6458cbef22dd6b | 31.014706 | 117 | 0.598989 | 4.433809 | false | false | false | false |
mlilback/rc2SwiftClient | MacClient/App-TopLevel/LoginViewController.swift | 1 | 2527 | //
// LoginViewController.swift
//
// Copyright ©2018 Mark Lilback. This file is licensed under the ISC license.
//
import Cocoa
import Networking
class LoginViewController: NSViewController {
@IBOutlet private weak var serverPopUp: NSPopUpButton!
@IBOutlet private weak var userField: NSTextField!
@IBOutlet private weak var passwordField: NSTextField!
@IBOutlet private weak var loginButon: NSButton!
@IBOutlet private weak var statusField: NSTextField!
@IBOutlet private weak var progressSpinner: NSProgressIndicator!
var initialHost: ServerHost?
var enteredPassword: String { return passwordField.stringValue }
var selectedHost: ServerHost?
var statusMessage: String { get { return statusField.stringValue } set { statusField.stringValue = newValue } }
var userLogin: String { get { return userField.stringValue } set { userField.stringValue = newValue } }
var completionHandler: ((ServerHost?) -> Void)?
override func viewWillAppear() {
super.viewWillAppear()
statusField.stringValue = ""
userField.stringValue = initialHost?.user ?? ""
passwordField.stringValue = ""
serverPopUp.selectItem(at: initialHost?.name == ServerHost.betaHost.name ? 1 : 0)
loginButon.isEnabled = false
}
func clearPassword() {
passwordField.stringValue = ""
}
@IBAction func cancelLogin(_ sender: Any?) {
completionHandler?(nil)
}
@IBAction func performLogin(_ sender: Any?) {
// TODO: login button should be disabled until values are entered
guard userField.stringValue.count > 0, passwordField.stringValue.count > 0 else {
NSSound.beep()
return
}
let baseHost: ServerHost = serverPopUp.indexOfSelectedItem == 0 ? .cloudHost : .betaHost
selectedHost = ServerHost(name: baseHost.name, host: baseHost.host, port: baseHost.port, user: userField.stringValue, urlPrefix: baseHost.urlPrefix, secure: true)
completionHandler?(selectedHost)
}
}
extension LoginViewController: NSTextFieldDelegate {
func controlTextDidChange(_ obj: Notification) {
let userValid = userField.stringValue.count > 3
let passValid = passwordField.stringValue.count > 4
loginButon.isEnabled = userValid && passValid
}
func control(_ control: NSControl, isValidObject obj: Any?) -> Bool {
guard obj != nil else { return false }
let userValid = userField.stringValue.count > 3
let passValid = passwordField.stringValue.count > 4
loginButon.isEnabled = userValid && passValid
if control == userField { return userValid }
if control == passwordField { return passValid }
return true
}
}
| isc | 22ad13202c9fa3328530c69fb7b7e397 | 34.083333 | 164 | 0.752969 | 4.238255 | false | false | false | false |
HenryFanDi/HFSideMenuViewController | HFSideMenuViewController/LeftMenuViewController.swift | 1 | 924 | //
// LeftMenuViewController.swift
// HFSideMenuViewController
//
// Created by HenryFan on 15/8/2016.
// Copyright © 2016 HenryFanDi. All rights reserved.
//
import UIKit
class LeftMenuViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupLeftMenuViewController()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Private
fileprivate func setupLeftMenuViewController() {
view.backgroundColor = UIColor.init(red: 230.0/255.0, green: 230.0/255.0, blue: 230.0/255.0, alpha: 1.0)
setupTitleLabel()
}
fileprivate func setupTitleLabel() {
titleLabel.text = "LeftMenuViewController"
titleLabel.textColor = UIColor.black
titleLabel.textAlignment = .center
titleLabel.font = UIFont.systemFont(ofSize: 16.0)
}
}
| mit | d17424738fbfcfa3dd9026b334828523 | 22.075 | 108 | 0.705309 | 4.374408 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/PhotoLibrary/View/PhotoLibraryItemCell.swift | 1 | 5487 | import ImageSource
import UIKit
final class PhotoLibraryItemCell: PhotoCollectionViewCell, Customizable {
private let cloudIconView = UIImageView()
private var getSelectionIndex: (() -> Int?)?
private let selectionIndexBadgeContainer = UIView()
private let selectionIndexBadge: UILabel = {
let label = UILabel()
label.backgroundColor = UIColor(red: 0, green: 0.67, blue: 1, alpha: 1)
label.textColor = .white
label.font = .boldSystemFont(ofSize: 16)
label.size = CGSize(width: 24, height: 24)
label.textAlignment = .center
label.layer.cornerRadius = 11
label.layer.masksToBounds = true
return label
}()
var selectionIndexFont: UIFont? {
get { return selectionIndexBadge.font }
set { selectionIndexBadge.font = newValue }
}
var isRedesign = false
// MARK: - UICollectionViewCell
override var backgroundColor: UIColor? {
get { return backgroundView?.backgroundColor }
set { backgroundView?.backgroundColor = newValue }
}
override var isSelected: Bool {
didSet {
if isRedesign {
layer.borderWidth = 0
}
}
}
func adjustAppearanceForSelected(_ isSelected: Bool, animated: Bool) {
func adjustAppearance() {
if isSelected {
self.imageView.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
self.selectionIndexBadgeContainer.transform = self.imageView.transform
self.selectionIndexBadgeContainer.alpha = 1
} else {
self.imageView.transform = .identity
self.selectionIndexBadgeContainer.transform = self.imageView.transform
self.selectionIndexBadgeContainer.alpha = 0
}
}
if animated {
UIView.animate(withDuration: 0.2, animations: adjustAppearance)
} else {
adjustAppearance()
}
}
override func prepareForReuse() {
super.prepareForReuse()
getSelectionIndex = nil
}
override init(frame: CGRect) {
super.init(frame: frame)
let backgroundView = UIView()
let onePixel = 1.0 / UIScreen.main.nativeScale
selectedBorderThickness = 5
imageView.isAccessibilityElement = true
imageViewInsets = UIEdgeInsets(top: onePixel, left: onePixel, bottom: onePixel, right: onePixel)
setUpRoundedCorners(for: self)
setUpRoundedCorners(for: backgroundView)
setUpRoundedCorners(for: imageView)
setUpRoundedCorners(for: selectionIndexBadgeContainer)
selectionIndexBadgeContainer.alpha = 0
selectionIndexBadgeContainer.backgroundColor = UIColor.black.withAlphaComponent(0.4)
selectionIndexBadgeContainer.addSubview(selectionIndexBadge)
contentView.insertSubview(cloudIconView, at: 0)
contentView.addSubview(selectionIndexBadgeContainer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let onePixel = CGFloat(1) / UIScreen.main.nativeScale
let backgroundInsets = UIEdgeInsets(top: onePixel, left: onePixel, bottom: onePixel, right: onePixel)
backgroundView?.frame = imageView.frame.inset(by: backgroundInsets)
cloudIconView.sizeToFit()
cloudIconView.right = contentView.bounds.right
cloudIconView.bottom = contentView.bounds.bottom
selectionIndexBadgeContainer.center = imageView.center
selectionIndexBadgeContainer.bounds = imageView.bounds
selectionIndexBadge.center = CGPoint(x: 18, y: 18)
}
override func didRequestImage(requestId imageRequestId: ImageRequestId) {
self.imageRequestId = imageRequestId
}
override func imageRequestResultReceived(_ result: ImageRequestResult<UIImage>) {
if result.requestId == self.imageRequestId {
onImageSetFromSource?()
}
}
// MARK: - PhotoLibraryItemCell
func setBadgeBackgroundColor(_ color: UIColor?) {
selectionIndexBadge.backgroundColor = color
}
func setBadgeTextColor(_ color: UIColor?) {
selectionIndexBadge.textColor = color
}
func setCloudIcon(_ icon: UIImage?) {
cloudIconView.image = icon
setNeedsLayout()
}
func setAccessibilityId(index: Int) {
accessibilityIdentifier = AccessibilityId.mediaItemThumbnailCell.rawValue + "-\(index)"
}
func setSelectionIndex(_ selectionIndex: Int?) {
selectionIndexBadge.text = selectionIndex.flatMap { String($0) }
}
// MARK: - Customizable
var onImageSetFromSource: (() -> ())?
func customizeWithItem(_ item: PhotoLibraryItemCellData) {
imageSource = item.image
getSelectionIndex = item.getSelectionIndex
}
// MARK: - Private
private var imageRequestId: ImageRequestId?
private func setUpRoundedCorners(for view: UIView) {
view.layer.cornerRadius = 6
view.layer.masksToBounds = true
view.layer.shouldRasterize = true
view.layer.rasterizationScale = UIScreen.main.nativeScale
}
}
| mit | fac8b7edd2a75ebb2f03b1b058aa0fe7 | 31.467456 | 109 | 0.63368 | 5.63926 | false | false | false | false |
nextcloud/ios | File Provider Extension/FileProviderDomain.swift | 1 | 3705 | //
// FileProviderDomain.swift
// Nextcloud
//
// Created by Marino Faggiana on 04/06/2019.
// Copyright © 2019 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
class FileProviderDomain: NSObject {
func registerDomains() {
NSFileProviderManager.getDomainsWithCompletionHandler { fileProviderDomain, error in
var domains: [String] = []
let pathRelativeToDocumentStorage = NSFileProviderManager.default.documentStorageURL.absoluteString
let accounts = NCManageDatabase.shared.getAllAccount()
for domain in fileProviderDomain {
domains.append(domain.identifier.rawValue)
}
// Delete
for domain in domains {
var domainFound = false
for account in accounts {
guard let urlBase = NSURL(string: account.urlBase) else { continue }
guard let host = urlBase.host else { continue }
let accountDomain = account.userId + " (" + host + ")"
if domain == accountDomain {
domainFound = true
break
}
}
if !domainFound {
let domainRawValue = NSFileProviderDomain(identifier: NSFileProviderDomainIdentifier(rawValue: domain), displayName: domain, pathRelativeToDocumentStorage: pathRelativeToDocumentStorage)
NSFileProviderManager.remove(domainRawValue, completionHandler: { error in
if error != nil {
print("Error domain: \(domainRawValue) error: \(String(describing: error))")
}
})
}
}
// Add
for account in accounts {
var domainFound = false
guard let urlBase = NSURL(string: account.urlBase) else { continue }
guard let host = urlBase.host else { continue }
let accountDomain = account.userId + " (" + host + ")"
for domain in domains {
if domain == accountDomain {
domainFound = true
break
}
}
if !domainFound {
let domainRawValue = NSFileProviderDomain(identifier: NSFileProviderDomainIdentifier(rawValue: accountDomain), displayName: accountDomain, pathRelativeToDocumentStorage: pathRelativeToDocumentStorage)
NSFileProviderManager.add(domainRawValue, completionHandler: { error in
if error != nil {
print("Error domain: \(domainRawValue) error: \(String(describing: error))")
}
})
}
}
}
}
func removeAllDomains() {
NSFileProviderManager.removeAllDomains { _ in }
}
}
| gpl-3.0 | a2c63474e8007d137da8cc56ba4cfa68 | 40.155556 | 220 | 0.576134 | 5.680982 | false | false | false | false |
leuski/Coiffeur | Coiffeur/src/formatter/CoiffeurController.swift | 1 | 10951 | //
// CoiffeurController.swift
// Coiffeur
//
// Created by Anton Leuski on 4/5/15.
// Copyright (c) 2015 Anton Leuski. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
import Foundation
import CoreData
protocol CoiffeurControllerDelegate: class {
func coiffeurControllerArguments(_ controller: CoiffeurController)
-> CoiffeurController.Arguments
func coiffeurController(_ coiffeurController: CoiffeurController,
setText text: String)
}
class CoiffeurController: NSObject {
class Arguments {
let text: String
let language: Language
var fragment = false
init(_ text: String, language: Language)
{
self.text = text
self.language = language
}
}
enum OptionType: String {
case signed
case unsigned
case string
case stringList
}
class var availableTypes: [CoiffeurController.Type] {
return [ ClangFormatController.self, UncrustifyController.self ] }
class var documentType: String { return "" }
class var localizedExecutableTitle: String { return "Executable" }
class var currentExecutableName: String { return "" }
class var currentExecutableURLUDKey: String { return "" }
class var defaultExecutableURL: URL? {
let bundle = Bundle(for: self)
if let url = bundle.url(forAuxiliaryExecutable: self.currentExecutableName)
{
if FileManager.default.isExecutableFile(atPath: url.path) {
return url
}
}
return nil
}
class var currentExecutableURL: URL? {
get {
if let url = UserDefaults.standard.url(
forKey: self.currentExecutableURLUDKey)
{
if FileManager.default.isExecutableFile(atPath: url.path) {
return url
} else {
UserDefaults.standard.removeObject(
forKey: self.currentExecutableURLUDKey)
NSApp.presentError(Errors.failedLocateExecutable(url))
}
}
return self.defaultExecutableURL
}
set (value) {
if let value = value, value != self.defaultExecutableURL {
UserDefaults.standard.set(value, forKey: self.currentExecutableURLUDKey)
} else {
UserDefaults.standard.removeObject(forKey: self.currentExecutableURLUDKey)
}
}
}
class var keySortDescriptor: NSSortDescriptor
{
return NSSortDescriptor(key: "indexKey", ascending: true)
}
let managedObjectContext: NSManagedObjectContext
let managedObjectModel: NSManagedObjectModel
let executableURL: URL
@objc var root: ConfigRoot? {
do {
return try self.managedObjectContext.fetchSingle(ConfigRoot.self)
} catch _ {
return nil
}
}
var pageGuideColumn: Int { return 0 }
weak var delegate: CoiffeurControllerDelegate?
class func findExecutableURL() throws -> URL
{
if let url = self.currentExecutableURL {
return url
}
throw Errors.noFormatExecutableURL
}
class func createCoiffeur() throws -> CoiffeurController
{
let url = try self.findExecutableURL()
let bundles = [Bundle(for: CoiffeurController.self)]
guard let mom = NSManagedObjectModel.mergedModel(from: bundles)
else { throw Errors.failedToInitializeManagedObjectModel }
let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
moc.persistentStoreCoordinator = NSPersistentStoreCoordinator(
managedObjectModel: mom)
guard let psc = moc.persistentStoreCoordinator
else { throw Errors.failedToInitializeStoreCoordinator }
try psc.addPersistentStore(
ofType: NSInMemoryStoreType, configurationName: nil,
at: nil, options: nil)
moc.undoManager = UndoManager()
return self.init(
executableURL: url, managedObjectModel: mom, managedObjectContext: moc)
}
class func coiffeurWithType(_ type: String) throws -> CoiffeurController
{
for coiffeurClass in CoiffeurController.availableTypes
where type == coiffeurClass.documentType
{
return try coiffeurClass.createCoiffeur()
}
throw Errors.unknownType(type)
}
class func contentsIsValidInString(_ string: String) -> Bool
{
return false
}
required init(executableURL: URL, managedObjectModel: NSManagedObjectModel,
managedObjectContext: NSManagedObjectContext)
{
self.executableURL = executableURL
self.managedObjectModel = managedObjectModel
self.managedObjectContext = managedObjectContext
super.init()
NotificationCenter.default.addObserver(
self,
selector: #selector(CoiffeurController.modelDidChange(_:)),
name: NSNotification.Name.NSManagedObjectContextObjectsDidChange,
object: self.managedObjectContext)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func modelDidChange(_:AnyObject?)
{
self.format()
}
@discardableResult
func format() -> Bool
{
var result = false
if let del = self.delegate {
let arguments = del.coiffeurControllerArguments(self)
result = self.format(arguments) {
(result: StringResult) in
switch result {
case .failure(let err):
NSLog("%@", err.localizedDescription)
case .success(let text):
del.coiffeurController(self, setText: text)
}
}
}
return result
}
func format(_ args: Arguments,
completionHandler: @escaping (_:StringResult) -> Void) -> Bool
{
return false
}
func readOptionsFromLineArray(_ lines: [String]) throws
{
}
func readValuesFromLineArray(_ lines: [String]) throws
{
}
func readOptionsFromString(_ text: String) throws
{
let lines = text.components(separatedBy: "\n")
self.managedObjectContext.disableUndoRegistration()
defer { self.managedObjectContext.enableUndoRegistration() }
ConfigRoot.objectInContext(self.managedObjectContext, parent: nil)
try self.readOptionsFromLineArray(lines)
_clusterOptions()
}
func readValuesFromString(_ text: String) throws
{
let lines = text.components(separatedBy: "\n")
self.managedObjectContext.disableUndoRegistration()
defer { self.managedObjectContext.enableUndoRegistration() }
try self.readValuesFromLineArray(lines)
}
func readValuesFromURL(_ absoluteURL: URL) throws {
let data = try String(contentsOf: absoluteURL, encoding: .utf8)
try self.readValuesFromString(data)
}
func writeValuesToURL(_ absoluteURL: URL) throws {
throw Errors.failedToWriteStyle(absoluteURL)
}
func optionWithKey(_ key: String) -> ConfigOption?
{
do {
return try self.managedObjectContext.fetchSingle(
ConfigOption.self, withFormat: "indexKey = %@", key)
} catch _ {
return nil
}
}
private func _clusterOptions()
{
for index in stride(from: 8, to: 1, by: -1) {
self._cluster(index)
}
_makeOthersSubsection()
// if the root contains only one child, pull its children into the root,
// and remove it
if
let root = self.root,
root.children.count == 1,
let subroot = root.children.object(at: 0) as? ConfigNode
{
for case let node as ConfigNode in subroot.children.array {
node.parent = root
}
self.managedObjectContext.delete(subroot)
}
self.root?.sortAndIndexChildren()
}
private func _splitTokens(_ title: String, boundary: Int, stem: Bool = false)
-> (head: [String], tail: [String])
{
let tokens = title.components(separatedBy: " ")
var head = [String]()
var tail = [String]()
for token in tokens {
if head.count < boundary {
var lcToken = token.lowercased()
if lcToken.isEmpty || lcToken == "a" || lcToken == "the" {
continue
}
if stem {
if lcToken.hasSuffix("ing") {
lcToken = lcToken.stringByTrimmingSuffix("ing")
} else if lcToken.hasSuffix("ed") {
lcToken = lcToken.stringByTrimmingSuffix("ed")
} else if lcToken.hasSuffix("s") {
lcToken = lcToken.stringByTrimmingSuffix("s")
}
}
head.append(lcToken)
} else {
tail.append(token)
}
}
return (head:head, tail:tail)
}
private func _cluster(_ tokenLimit: Int)
{
for case let section as ConfigSection in self.root?.children ?? [] {
var index = [String: [ConfigOption]]()
for case let option as ConfigOption in section.children {
let (head, tail) = _splitTokens(
option.title, boundary: tokenLimit, stem: true)
if tail.isEmpty {
continue
}
let key = head.reduce("") { $0.isEmpty ? $1 : "\($0) \($1)" }
if index[key] == nil {
index[key] = [ConfigOption]()
}
index[key]?.append(option)
}
for (key, list) in index {
if list.count < 5 || list.count == section.children.count {
continue
}
let subsection = ConfigSection.objectInContext(
self.managedObjectContext,
parent: section, title: "\(key) …")
var count = 0
for option in list {
option.parent = subsection
let (head, tail) = _splitTokens(option.title, boundary: tokenLimit)
option.title = tail.reduce("") { $0.isEmpty ? $1 : "\($0) \($1)" }
count += 1
if count == 1 {
let title = head.reduce("") { $0.isEmpty ? $1 : "\($0) \($1)" }
subsection.title = "\(title.stringByCapitalizingFirstWord) …"
}
}
}
}
}
private func _makeOthersSubsection()
{
for case let section as ConfigSection in self.root?.children ?? [] {
var index = [ConfigOption]()
var foundSubSection = false
for node in section.children {
if let section = node as? ConfigOption {
index.append(section)
} else {
foundSubSection = true
}
}
if !foundSubSection || index.isEmpty {
continue
}
let other = String(format: NSLocalizedString("Other %@", comment: ""),
section.title.lowercased())
let subsection = ConfigSection.objectInContext(self.managedObjectContext,
parent: section,
title: "\u{200B}\(other)")
for option in index {
option.parent = subsection
}
}
}
}
| apache-2.0 | cee931b00bdf772e1f2c8de681f56ba6 | 26.854962 | 82 | 0.64319 | 4.620937 | false | false | false | false |
Floater-ping/DYDemo | DYDemo/DYDemo/Classes/Home/View/RecommendCycleView.swift | 1 | 4060 | //
// RecommendCycleView.swift
// DYDemo
//
// Created by ZYP-MAC on 2017/8/9.
// Copyright © 2017年 ZYP-MAC. All rights reserved.
//
import UIKit
fileprivate let pCycleCellID = "pCycleCellID"
class RecommendCycleView: UIView {
//MARK:- 定义属性
var cycleTimer : Timer?
var cycleModelArr : [CycleModel]? {
didSet {
// 1.刷新表格
collectionView.reloadData()
// 2设置pageControl的个数
pageControl.numberOfPages = cycleModelArr?.count ?? 0
// 3.默认滚动到中间的位置
let indexPath = NSIndexPath(item: (cycleModelArr?.count ?? 0) * 10, section: 0)
collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false)
// 4.添加定时器
removeCycleTimer()
addCycleTimer()
}
}
//MARK:- 控件属性
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
//MARK:- 系统回调函数
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = UIViewAutoresizing()
// 注册cell
collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: pCycleCellID)
}
override func layoutSubviews() {
// 设置collectionView的layout
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
//MARK:- 快速创建方法
extension RecommendCycleView {
class func recommendCycleView() -> RecommendCycleView {
return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView
}
}
//MARK:- UICollectionViewDataSource
extension RecommendCycleView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (cycleModelArr?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pCycleCellID, for: indexPath) as! CollectionCycleCell
let cycleModle = cycleModelArr![indexPath.item % cycleModelArr!.count]
cell.cycleModel = cycleModle
return cell
}
}
//MARK:- UICollectionViewDelegate
extension RecommendCycleView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 1.获取滚动偏移量 +scrollView.bounds.width * 0.5:滚动到一半的时候就变
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
// 2.计算pageControl的currentIndex
pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModelArr?.count ?? 1)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeCycleTimer()
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
addCycleTimer()
}
}
//MARK:- 对定时器的操作方法
extension RecommendCycleView {
/// 创建定时器
fileprivate func addCycleTimer() {
cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes)
}
/// 移除定时器
fileprivate func removeCycleTimer() {
cycleTimer?.invalidate()
cycleTimer = nil
}
@objc fileprivate func scrollToNext() {
let currentOffsetX = collectionView.contentOffset.x
let offsetX = currentOffsetX + collectionView.bounds.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
| mit | b10db634e603a42151bee0cb395f4dbd | 28.625954 | 129 | 0.647771 | 5.316438 | false | false | false | false |
xin-wo/kankan | kankan/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift | 10 | 14761 | //
// UIButton+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/13.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/**
* Set image to use from web for a specified state.
*/
extension UIButton {
/**
Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setImageWithURL(URL: NSURL?,
forState state: UIControlState,
placeholderImage: UIImage? = nil,
optionsInfo: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
let resource = URL.map { Resource(downloadURL: $0) }
return kf_setImageWithResource(resource,
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setImageWithResource(resource: Resource?,
forState state: UIControlState,
placeholderImage: UIImage? = nil,
optionsInfo: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
setImage(placeholderImage, forState: state)
guard let resource = resource else {
completionHandler?(image: nil, error: nil, cacheType: .None, imageURL: nil)
return RetrieveImageTask.emptyTask
}
kf_setWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
progressBlock: { receivedSize, totalSize in
if let progressBlock = progressBlock {
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
}
},
completionHandler: {[weak self] image, error, cacheType, imageURL in
dispatch_async_safely_to_main_queue {
guard let sSelf = self where imageURL == sSelf.kf_webURLForState(state) else {
return
}
sSelf.kf_setImageTask(nil)
if image != nil {
sSelf.setImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
})
kf_setImageTask(task)
return task
}
}
private var lastURLKey: Void?
private var imageTaskKey: Void?
// MARK: - Runtime for UIButton image
extension UIButton {
/**
Get the image URL binded to this button for a specified state.
- parameter state: The state that uses the specified image.
- returns: Current URL for image.
*/
public func kf_webURLForState(state: UIControlState) -> NSURL? {
return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setWebURL(URL: NSURL, forState state: UIControlState) {
kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_webURLs: NSMutableDictionary {
var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setWebURLs(dictionary!)
}
return dictionary!
}
private func kf_setWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private var kf_imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(self, &imageTaskKey) as? RetrieveImageTask
}
private func kf_setImageTask(task: RetrieveImageTask?) {
objc_setAssociatedObject(self, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/**
* Set background image to use from web for a specified state.
*/
extension UIButton {
/**
Set the background image to use for a specified state with a URL,
a placeholder image, options progress handler and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL?,
forState state: UIControlState,
placeholderImage: UIImage? = nil,
optionsInfo: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
let resource = URL.map { Resource(downloadURL: $0) }
return kf_setBackgroundImageWithResource(resource,
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a resource,
a placeholder image, options progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setBackgroundImageWithResource(resource: Resource?,
forState state: UIControlState,
placeholderImage: UIImage? = nil,
optionsInfo: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
setBackgroundImage(placeholderImage, forState: state)
guard let resource = resource else {
completionHandler?(image: nil, error: nil, cacheType: .None, imageURL: nil)
return RetrieveImageTask.emptyTask
}
kf_setBackgroundWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
progressBlock: { receivedSize, totalSize in
if let progressBlock = progressBlock {
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
}
},
completionHandler: { [weak self] image, error, cacheType, imageURL in
dispatch_async_safely_to_main_queue {
guard let sSelf = self where imageURL == sSelf.kf_backgroundWebURLForState(state) else {
return
}
sSelf.kf_setBackgroundImageTask(nil)
if image != nil {
sSelf.setBackgroundImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
})
kf_setBackgroundImageTask(task)
return task
}
}
private var lastBackgroundURLKey: Void?
private var backgroundImageTaskKey: Void?
// MARK: - Runtime for UIButton background image
extension UIButton {
/**
Get the background image URL binded to this button for a specified state.
- parameter state: The state that uses the specified background image.
- returns: Current URL for background image.
*/
public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? {
return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) {
kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_backgroundWebURLs: NSMutableDictionary {
var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setBackgroundWebURLs(dictionary!)
}
return dictionary!
}
private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private var kf_backgroundImageTask: RetrieveImageTask? {
return objc_getAssociatedObject(self, &backgroundImageTaskKey) as? RetrieveImageTask
}
private func kf_setBackgroundImageTask(task: RetrieveImageTask?) {
objc_setAssociatedObject(self, &backgroundImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Cancel image download tasks.
extension UIButton {
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func kf_cancelImageDownloadTask() {
kf_imageTask?.downloadTask?.cancel()
}
/**
Cancel the background image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func kf_cancelBackgroundImageDownloadTask() {
kf_backgroundImageTask?.downloadTask?.cancel()
}
}
| mit | efa12a7130f46089547ed8eff993553d | 45.564669 | 133 | 0.620419 | 5.906763 | false | false | false | false |
pratikgujarati/iOS-Projects | SpriteKitSwiftAccelerometerTutorial/SpriteKitSwiftAccelerometerTutorial/GameViewController.swift | 4 | 2180 | //
// GameViewController.swift
// SpriteKitSwiftAccelerometerTutorial
//
// Created by Arthur Knopper on 10/12/14.
// Copyright (c) 2014 Arthur Knopper. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | 18d391d02dcd07ef370b4fe76ba7bd0c | 30.594203 | 104 | 0.630275 | 5.662338 | false | false | false | false |
hikelee/cinema | Sources/App/Controllers/RechargeController.swift | 1 | 1889 | import Foundation
import Vapor
import HTTP
final class RechargeAdminController : ChannelBasedController<Recharge> {
typealias Model = Recharge
override var path:String {return "/admin/cinema/recharge"}
override func getModel(_ request:Request) throws -> Recharge{
let model = try super.getModel(request)
model.userId = request.user?.id
model.rechargeTime = Date().string()
if request.isCreate {
let date = Date()
model.addDate = date.string(format:"yyyy-MM-dd")
model.addMonth = date.string(format:"yyyy-MM")
model.addYear = date.string(format:"yyyy")
}
return model
}
override func delete(_ request: Request,_ model: Model) throws -> ResponseRepresentable {
throw RechargeError.unSupportOperation(message:"no hack")
}
override func update(_ request: Request,_ model: Model) throws -> ResponseRepresentable {
throw RechargeError.unSupportOperation(message:"no hack")
}
override func additonalFormData(_ request: Request) throws ->[String:Node]{
var data = try [
"recharge_types": Model.rechargeTypes.allNode(),
"members" : Member.allNodes(channelId:request.channelId).makeNode(),
]
if request.isCreate {
let model = Recharge()
model.memberId = Node(request.data["member_id"]?.int ?? 0)
data["node"] = try model.makeNode()
}
if request.user?.isRoot ?? false {
data["channels"] = try Channel.allNode()
}
return data
}
override func postCreate(request:Request,model:Model) throws{
if let memberId = model.memberId?.int,memberId>0 {
if var member = try Member.load(memberId){
member.balance += model.amount
try member.save()
}
}
}
}
| mit | c4d0b19820a97082d34b00b500f45edd | 35.326923 | 93 | 0.611964 | 4.540865 | false | false | false | false |
weareopensource/Sample-iOS_Swift_Instagram | Sample-Swift_instagram/PostController.swift | 1 | 2869 | //
// PostController.swift
//
//
// Created by RYPE on 14/05/2015.
//
//
import UIKit
class PostController: UIViewController {
/*************************************************/
// Main
/*************************************************/
// Boulet
/*************************/
@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myText: UITextView!
@IBOutlet weak var myScrollView: UIScrollView!
// Var
/*************************/
var post: Post?
var chachedImage: UIImage?
// init
/*************************/
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// Base
/*************************/
override func viewDidLoad() {
super.viewDidLoad()
// custom
// ---------------------
// back button text
let backButton = UIBarButtonItem(
title: "",
style: UIBarButtonItemStyle.Plain,
target: nil,
action: nil
);
self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
// back uiColor
myScrollView.backgroundColor = UIColor(netHex:GlobalConstants.BackgroundColor)
// police Color
myText.textColor = UIColor(netHex:GlobalConstants.FontColor)
// ---------------------
// Set Data
myImage.image = self.chachedImage
// resize image
let size = CGSizeMake(self.view.bounds.width, self.view.bounds.width)
myImage.image! = imageResize(image: myImage.image!,sizeChange: size)
myText.text = self.post?.text
// resize height of text view
myText.scrollEnabled = false
let contentSize = myText.sizeThatFits(CGSizeMake(myText.frame.size.width, CGFloat.max))
for c in myText.constraints {
if c.isKindOfClass(NSLayoutConstraint) {
let constraint = c as NSLayoutConstraint
if constraint.firstAttribute == NSLayoutAttribute.Height {
constraint.constant = contentSize.height
break
}
}
}
}
/*************************************************/
// Functions
/*************************************************/
// Other
/*************************/
func imageResize (image image:UIImage, sizeChange:CGSize)-> UIImage{
let hasAlpha = true
let scale: CGFloat = 0.0 // Use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
image.drawInRect(CGRect(origin: CGPointZero, size: sizeChange))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
return scaledImage
}
}
| mit | d8779dbcff1ec0b2d31e4da141908325 | 27.979798 | 95 | 0.502266 | 5.939959 | false | false | false | false |
openHPI/xikolo-ios | iOS/ViewControllers/Channels/ChannelListViewController.swift | 1 | 5584 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import BrightFutures
import Common
import CoreData
import UIKit
class ChannelListViewController: CustomWidthCollectionViewController {
private var dataSource: CoreDataCollectionViewDataSource<ChannelListViewController>!
override func viewDidLoad() {
self.collectionView?.register(R.nib.channelCell)
super.viewDidLoad()
self.navigationItem.largeTitleDisplayMode = .always
self.adjustScrollDirection(for: self.collectionView.bounds.size)
let reuseIdentifier = R.reuseIdentifier.channelCell.identifier
let request = ChannelHelper.FetchRequest.orderedChannels
let resultsController = CoreDataHelper.createResultsController(request, sectionNameKeyPath: nil)
self.dataSource = CoreDataCollectionViewDataSource(self.collectionView,
fetchedResultsControllers: [resultsController],
cellReuseIdentifier: reuseIdentifier,
delegate: self)
self.refresh()
self.setupEmptyState()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.adjustScrollDirection(for: self.collectionView.bounds.size)
self.collectionViewLayout.invalidateLayout()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.adjustScrollDirection(for: size)
coordinator.animate { _ in
self.navigationController?.navigationBar.sizeToFit()
self.collectionViewLayout.invalidateLayout()
}
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let channel = self.dataSource.object(at: indexPath)
self.performSegue(withIdentifier: R.segue.channelListViewController.showCourseList, sender: channel)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let typedInfo = R.segue.channelListViewController.showCourseList(segue: segue), let channel = sender as? Channel {
typedInfo.destination.configuration = .coursesInChannel(channel)
} else {
super.prepare(for: segue, sender: sender)
}
}
private func adjustScrollDirection(for size: CGSize) {
let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout
flowLayout?.scrollDirection = self.traitCollection.horizontalSizeClass == .regular && size.width > size.height ? .horizontal : .vertical
}
}
extension ChannelListViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let sectionInsets = self.collectionView(collectionView, layout: collectionViewLayout, insetForSectionAt: indexPath.section)
let boundingHeight = collectionView.bounds.height - collectionView.layoutMargins.top - collectionView.layoutMargins.bottom
var boundingWidth = collectionView.bounds.width - sectionInsets.left - sectionInsets.right
if self.traitCollection.horizontalSizeClass == .regular, collectionView.bounds.width > collectionView.bounds.height {
boundingWidth = min(600, boundingWidth)
}
let channel = self.dataSource.object(at: indexPath)
var height = ceil(ChannelCell.heightForChannelList(forWidth: boundingWidth, for: channel))
height = min(boundingHeight, height)
return CGSize(width: boundingWidth, height: height)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
let leftPadding = collectionView.layoutMargins.left - ChannelCell.cardInset
let rightPadding = collectionView.layoutMargins.right - ChannelCell.cardInset
return UIEdgeInsets(top: 0, left: leftPadding, bottom: collectionView.layoutMargins.bottom, right: rightPadding)
}
}
extension ChannelListViewController: CoreDataCollectionViewDataSourceDelegate {
typealias HeaderView = UICollectionReusableView
func configure(_ cell: ChannelCell, for object: Channel) {
cell.configure(object)
}
}
extension ChannelListViewController: EmptyStateDataSource, EmptyStateDelegate {
var emptyStateTitleText: String {
return NSLocalizedString("empty-view.channels.title", comment: "title for empty channel list")
}
func didTapOnEmptyStateView() {
self.refresh()
}
func setupEmptyState() {
self.collectionView.emptyStateDataSource = self
self.collectionView.emptyStateDelegate = self
}
}
extension ChannelListViewController: RefreshableViewController {
func refreshingAction() -> Future<Void, XikoloError> {
return ChannelHelper.syncAllChannels().asVoid()
}
}
| gpl-3.0 | 4deead7750b44fc3b364029f7bd0292f | 38.595745 | 160 | 0.709296 | 5.93305 | false | false | false | false |
CherishSmile/ZYBase | ZYBase/BaseSet/BaseSearchVC.swift | 1 | 3321 | //
// BaseSearchVC.swift
// ZYBase
//
// Created by MAC on 2017/5/6.
// Copyright © 2017年 Mzywx. All rights reserved.
//
import UIKit
open class BaseSearchVC: UISearchController {
/**
* SearchBar的输入框
*/
public lazy var textField:UITextField? = {
var searchField:UITextField?
if let seaField = self.searchBar.value(forKey: "_searchField") {
searchField = seaField as? UITextField
}
return searchField
}()
/**
* SearchBar的背景视图
*/
public lazy var backgroudView:UIImageView? = {
var background:UIImageView?
if let bgView = self.searchBar.value(forKey: "_background") {
background = bgView as? UIImageView
}
return background
}()
/**
* SearchBar的取消按钮
*/
public lazy var cancleButton:UIButton? = {
var cancelBtn:UIButton?
if let cancle = self.searchBar.value(forKey: "_cancelButton") {
cancelBtn = cancle as? UIButton
}
return cancelBtn
}()
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setSearchBarColor(UIColorFromRGB(0xf3f2f7))
setCursorAndCancleColor(UIColorFromRGB(0x39b65e))
}
public override init(searchResultsController: UIViewController?) {
super.init(searchResultsController: searchResultsController)
setSearchBarColor(UIColorFromRGB(0xf3f2f7))
setCursorAndCancleColor(UIColorFromRGB(0x39b65e))
}
/**
* 设置placholder的颜色
*/
public func setPlaceholderColor(_ color:UIColor){
if let searchFiled = textField {
if let placholder = searchFiled.value(forKey: "_placeholderLabel") {
let placholderlbl:UILabel? = placholder as? UILabel
placholderlbl?.textColor = color
}
}
}
/**
* 设置searchBar的颜色
*/
func setSearchBarColor(_ color:UIColor){
searchBar.barTintColor = color
}
/**
* 同时设置光标和取消按钮的颜色
*/
public func setCursorAndCancleColor(_ color:UIColor){
searchBar.tintColor = color
}
/**
* 设置光标颜色
*/
public func setCursorColor(_ color:UIColor){
textField?.tintColor = color
}
/**
* 设置取消按钮的字体颜色,只有在showsCancelButton = true 的情况下生效
*/
public func setCancleColor(_ color:UIColor){
cancleButton?.setTitleColor(color, for: .normal)
}
/**
* 设置取消按钮的文字,只有在showsCancelButton = true 的情况下生效
*/
public func setCancleTitle(_ title:String){
cancleButton?.setTitle(title, for: .normal)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 35b0dd00f3f275c355382d8064a63ed2 | 25.694915 | 89 | 0.611429 | 4.618768 | false | false | false | false |
Palleas/ReactiveCSVParser | ReactiveCSVParser/Parser.swift | 1 | 2015 | //
// Parser.swift
// ReactiveCSVParser
//
// Created by Romain Pouclet on 2015-01-27.
// Copyright (c) 2015 Perfectly-Cooked. All rights reserved.
//
import Cocoa
import ReactiveCocoa
public class Parser: NSObject {
let path: String
public init(path: String) {
self.path = path
}
public func parse() -> RACSignal {
return RACSignal.createSignal({ (subscriber: RACSubscriber!) -> RACDisposable! in
if let handler = NSFileHandle(forReadingAtPath: self.path) {
var offset = UInt64(0)
var data = handler.readDataOfLength(1024)
var stringBuffer: String?
while(data.length > 0) {
var chunk = ""
if stringBuffer != nil {
chunk += stringBuffer!
}
chunk += NSString(data: data, encoding: NSUTF8StringEncoding) ?? ""
let lines = chunk.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
for (index, line) in enumerate(lines[0..<lines.count - 1]) {
subscriber.sendNext(line)
}
stringBuffer = lines[lines.count - 1]
offset += data.length
handler.seekToFileOffset(offset)
data = handler.readDataOfLength(1024)
}
subscriber.sendCompleted()
} else {
subscriber.sendError(NSError())
}
return RACDisposable(block: { () -> Void in
})
}).map({ (line) -> AnyObject! in
return line.componentsSeparatedByString(",").map({ (col) -> AnyObject! in
return (col as String).stringByReplacingOccurrencesOfString("\"", withString: "")
})
})
}
}
| mit | 122c0b08bc1850c644a3cccb3215ce15 | 33.152542 | 112 | 0.489826 | 5.773639 | false | false | false | false |
tullie/CareerCupAPI | CCQuestion.swift | 1 | 595 | //
// Question.swift
// AlgorithmMatch
//
// Created by Tullie on 16/03/2015.
// Copyright (c) 2015 Tullie. All rights reserved.
//
import UIKit
public class CCQuestion: NSObject {
var questionText: String = ""
var id: String?
var company: String?
var tags: [String] = []
init(text: String, id: String?, company: String?, tags: [String]) {
super.init()
self.questionText = text.capitilizedFirstLetter
self.id = id
self.company = company?.capitilizedFirstLetter
self.tags = tags.map({$0.capitilizedFirstLetter})
}
}
| mit | bab4d6cc1ecefac3673799636b4aa0bf | 22.8 | 71 | 0.62521 | 3.628049 | false | false | false | false |
iOS-Swift-Developers/Swift | 实战前技术点/1.OOP到POP/OOP到POP/User.swift | 1 | 861 | //
// User.swift
// OOP到POP
//
// Created by 韩俊强 on 2017/7/17.
// Copyright © 2017年 HaRi. All rights reserved.
//
import UIKit
struct User {
var name : String = ""
var message : String = ""
init?(data : Data) {
guard let dictT = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String : Any] else {
return nil
}
let dict = dictT?["args"] as? [String : Any]
guard let name = dict?["username"] as? String else {
return nil
}
guard let message = dict?["age"] as? String else {
return nil
}
self.name = name
self.message = message
}
}
extension User: Decodable {
static func parse(_ data: Data) -> User? {
return User(data: data)
}
}
| mit | 2a04b3c11b7ad86d60bed4c67250ae0b | 18.767442 | 126 | 0.523529 | 3.953488 | false | false | false | false |
klemenkosir/SwiftExtensions | SwiftExtensions/SwiftExtensions/StringExtension.swift | 1 | 2206 | //
// StringExtension.swift
//
//
// Created by Klemen Kosir on 02/06/16.
// Copyright © 2016 Klemen Košir. All rights reserved.
//
import Foundation
public extension String {
func deleteHTMLTag(_ tag:String) -> String {
return self.replacingOccurrences(of: "(?i)</?\(tag)\\b[^<]*>", with: "", options: .regularExpression, range: nil)
}
func deleteHTMLTags(_ tags:[String]) -> String {
var mutableString = self
for tag in tags {
mutableString = mutableString.deleteHTMLTag(tag)
}
return mutableString
}
func deleteAllHTMLTags() -> String {
return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
}
var length: Int {
return self.characters.count
}
func isValidEmailInternational() -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
func isValidEmail() -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
func isValidPhoneNumber() -> Bool {
let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
return phoneTest.evaluate(with: self)
}
var URLString: String {
var string = self
if !string.contains("http://") && !string.contains("https://") {
string = "http://" + string
}
return string
}
init(htmlEncodedString: String?) throws {
self.init()
guard let htmlEncodedString = htmlEncodedString, let encodedData = htmlEncodedString.data(using: String.Encoding.utf8) else {
return
}
let attributedOptions: [String: Any] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue]
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
self = attributedString.string
}
}
//public extension CustomStringConvertible {
// var stringValue: String {
// return "\(self)"
// }
//}
| mit | 652271364f8b5f02f1874a37dd913d96 | 27.623377 | 127 | 0.671506 | 3.679466 | false | true | false | false |
Natoto/SWIFTMIAPP | swiftmi/Pods/Kingfisher/Kingfisher/UIButton+Kingfisher.swift | 1 | 31867 | //
// UIButton+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/13.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
* Set image to use from web for a specified state.
*/
public extension UIButton {
/**
Set an image to use for a specified state with a resource.
It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL.
It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource and a placeholder image.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL and a placeholder image.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource, a placeholder image and options.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL, a placeholder image and options.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a URL, a placeholder image, options and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
setImage(placeholderImage, forState: state)
kf_setWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
}) {[weak self] (image, error, cacheType, imageURL) -> () in
// dispatch_async_safely_main_queue {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let sSelf = self {
if (imageURL == sSelf.kf_webURLForState(state) && image != nil) {
sSelf.setImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
})
}
return task
}
/**
Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithResource(Resource(downloadURL: URL),
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
}
private var lastURLKey: Void?
public extension UIButton {
/**
Get the image URL binded to this button for a specified state.
- parameter state: The state that uses the specified image.
- returns: Current URL for image.
*/
public func kf_webURLForState(state: UIControlState) -> NSURL? {
return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setWebURL(URL: NSURL, forState state: UIControlState) {
kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_webURLs: NSMutableDictionary {
get {
var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setWebURLs(dictionary!)
}
return dictionary!
}
}
private func kf_setWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/**
* Set background image to use from web for a specified state.
*/
public extension UIButton {
/**
Set the background image to use for a specified state with a resource.
It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL.
It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource and a placeholder image.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL and a placeholder image.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource, a placeholder image and options.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL, a placeholder image and options.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource, a placeholder image, options and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a URL, a placeholder image, options and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a resource,
a placeholder image, options progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
setBackgroundImage(placeholderImage, forState: state)
kf_setBackgroundWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
}) { [weak self] (image, error, cacheType, imageURL) -> () in
// dispatch_async_safely_main_queue {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let sSelf = self {
if (imageURL == sSelf.kf_backgroundWebURLForState(state) && image != nil) {
sSelf.setBackgroundImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
})
}
return task
}
/**
Set the background image to use for a specified state with a URL,
a placeholder image, options progress handler and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(Resource(downloadURL: URL),
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
}
private var lastBackgroundURLKey: Void?
public extension UIButton {
/**
Get the background image URL binded to this button for a specified state.
- parameter state: The state that uses the specified background image.
- returns: Current URL for background image.
*/
public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? {
return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) {
kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_backgroundWebURLs: NSMutableDictionary {
get {
var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setBackgroundWebURLs(dictionary!)
}
return dictionary!
}
}
private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated
public extension UIButton {
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil)
}
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler)
}
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler)
}
@available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil)
}
@available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler)
}
@available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler)
}
}
| mit | f3891220225d3296ee4759c64543ad5a | 52.468121 | 242 | 0.648037 | 5.987787 | false | false | false | false |
tschob/ContainerController | Example/Core/ViewController/MenuContainerViewController.swift | 1 | 2356 | //
// MenuContainerViewController.swift
// Example
//
// Created by Hans Seiffert on 06.08.16.
// Copyright © 2016 Hans Seiffert. All rights reserved.
//
import UIKit
import ContainerController
class MenuContainerViewController: UIViewController {
private var customContainerViewController : ContainerViewController?
private var isMenuCollapsed = false
@IBOutlet private weak var menuWidthConstraint : NSLayoutConstraint?
@IBAction private func didPressToggleMenuButton(_ sender: AnyObject) {
self.menuWidthConstraint?.constant = (isMenuCollapsed ? 240 : 120)
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
self.isMenuCollapsed = !self.isMenuCollapsed
})
}
@IBAction private func didPressContentAButton(_ sender: AnyObject) {
self.customContainerViewController?.display(segue: "showContentA")
}
@IBAction private func didPressContentBButton(_ sender: AnyObject) {
self.customContainerViewController?.display(segue: "showContentB")
}
@IBAction private func didPressContentCButton(_ sender: AnyObject) {
self.customContainerViewController?.display(segue: "showContentC")
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if
segue.identifier == "customSegueIdentifier",
let containerViewController = segue.destination as? ContainerViewController {
self.customContainerViewController = containerViewController
self.customContainerViewController?.shouldReuseContentController = false
self.customContainerViewController?.defaultSegueIdentifier = "showContentA"
self.customContainerViewController?.delegate = self
}
}
}
extension MenuContainerViewController: ContainerViewControllerDelegate {
func containerViewController(_ containerViewController: ContainerViewController, willDisplay contentController: UIViewController, isReused: Bool) {
guard !isReused else {
return
}
if
let navigationController = contentController as? UINavigationController,
let contentController = navigationController.viewControllers.first as? ContentViewController {
contentController.bottomText = "Text set from the calling UIViewController"
} else if let contentController = contentController as? ContentViewController {
contentController.bottomText = "Text set from the calling UIViewController"
}
}
}
| mit | a614444c2249a2c898e68a3c7380950e | 33.632353 | 148 | 0.789384 | 4.916493 | false | false | false | false |
QuarkX/Quark | Sources/Quark/Core/Environment/Environment.swift | 1 | 1811 | import CEnvironment
public var environment = Environment()
public struct Environment {
public lazy var variables: [String: String] = {
var envs: [String: String] = [:]
#if os(Linux)
guard var env = __environ else {
return envs
}
#else
guard var env = environ else {
return envs
}
#endif
while true {
guard let envPointee = env.pointee else {
break
}
guard let envString = String(validatingUTF8: envPointee) else {
env += 1
continue
}
guard let index = envString.characters.index(of: "=") else {
env += 1
continue
}
let name = String(envString.characters.prefix(upTo: index))
let value = String(envString.characters.suffix(from: envString.index(index, offsetBy: 1)))
envs[name] = value
env += 1
}
return envs
}()
public subscript(variable: String) -> String? {
get {
return get(variable: variable)
}
nonmutating set(value) {
if let value = value {
set(value: value, to: variable, replace: true)
} else {
remove(variable: variable)
}
}
}
public func get(variable: String) -> String? {
guard let value = getenv(variable) else {
return nil
}
return String(validatingUTF8: value)
}
public func set(value: String, to variable: String, replace: Bool = true) {
setenv(variable, value, replace ? 1 : 0)
}
public func remove(variable: String) {
unsetenv(variable)
}
}
| mit | fb5f79990c782b245ad2d783b8a5636a | 24.507042 | 102 | 0.500276 | 4.778364 | false | false | false | false |
apple/swift-format | Sources/swift-format/Frontend/LintFrontend.swift | 1 | 2134 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import SwiftDiagnostics
import SwiftFormat
import SwiftFormatConfiguration
import SwiftSyntax
/// The frontend for linting operations.
class LintFrontend: Frontend {
override func processFile(_ fileToProcess: FileToProcess) {
let linter = SwiftLinter(
configuration: fileToProcess.configuration, findingConsumer: diagnosticsEngine.consumeFinding)
linter.debugOptions = debugOptions
let url = fileToProcess.url
guard let source = fileToProcess.sourceText else {
diagnosticsEngine.emitError(
"Unable to lint \(url.relativePath): file is not readable or does not exist.")
return
}
do {
try linter.lint(
source: source,
assumingFileURL: url) { (diagnostic, location) in
guard !self.lintFormatOptions.ignoreUnparsableFiles else {
// No diagnostics should be emitted in this mode.
return
}
self.diagnosticsEngine.consumeParserDiagnostic(diagnostic, location)
}
} catch SwiftFormatError.fileNotReadable {
diagnosticsEngine.emitError(
"Unable to lint \(url.relativePath): file is not readable or does not exist.")
return
} catch SwiftFormatError.fileContainsInvalidSyntax {
guard !lintFormatOptions.ignoreUnparsableFiles else {
// The caller wants to silently ignore this error.
return
}
// Otherwise, relevant diagnostics about the problematic nodes have been emitted.
return
} catch {
diagnosticsEngine.emitError("Unable to lint \(url.relativePath): \(error)")
return
}
}
}
| apache-2.0 | b13a61ad610703fce0a88f5e8f2a25bb | 34.566667 | 100 | 0.65089 | 5.192214 | false | false | false | false |
sessionm/ios-smp-example | Auth/WebLoginViewController.swift | 1 | 4642 | //
// WebLoginViewController.swift
// SMPExample
//
// Copyright © 2018 SessionM. All rights reserved.
//
import SessionMWebAuthKit
import UIKit
class WebLoginViewController: UIViewController {
@IBOutlet var clientID: UILabel!
@IBOutlet var authEndpoint: UILabel!
@IBOutlet var tokenEndpoint: UILabel!
@IBOutlet var redirectURI: UILabel!
@IBOutlet var logout: UIBarButtonItem!
@IBOutlet var status: UILabel!
@IBOutlet var userInfo: UIButton!
private var rawClientID: String?
private var rawAuthEndpoint: String?
private var rawTokenEndpoint: String?
private var rawRedirectURI: String?
private let authProvider = SessionM.authenticationProvider() as? SessionMOAuthProvider
private let userManager = SMUserManager.instance()
override func viewDidLoad() {
super.viewDidLoad()
guard let configFile = Bundle.main.path(forResource: "SMPConfig", ofType: "plist") else {
return
}
let info = NSDictionary(contentsOfFile: configFile)
if let kClientID = info?["OAuthClientID"] as? String {
rawClientID = kClientID
clientID.text = "Client ID: \(kClientID)"
}
if let kRedirectURI = info?["OAuthRedirectURI"] as? String {
rawRedirectURI = kRedirectURI
redirectURI.text = "Redirect URI: \(kRedirectURI)"
}
if let kOAuthHostURL = info?["OAuthHostURL"] as? String {
let kAuthEndpoint = kOAuthHostURL.appending("/authorize")
rawAuthEndpoint = kAuthEndpoint
authEndpoint.text = "Auth Endpoint: \(kAuthEndpoint)"
let kTokenEndpoint = kOAuthHostURL.appending("/token")
rawTokenEndpoint = kTokenEndpoint
tokenEndpoint.text = "Token Endpoint: \(kTokenEndpoint)"
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let user = userManager.currentUser {
logout.isEnabled = true
userInfo.isEnabled = true
let email = (user.email != nil) ? user.email! : "Anonymous User"
status.text? = "Email: \(email)\nID: \(user.userID)"
} else {
logout.isEnabled = false
userInfo.isEnabled = false
status.text? = "Logged Out"
}
NotificationCenter.default.addObserver(self, selector: #selector(authStateDidUpdate(_:)), name: NSNotification.Name(updatedAuthStateNotification), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDidUpdate(_:)), name: NSNotification.Name(updatedUserNotification), object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
super.viewWillDisappear(animated)
}
@objc private func authStateDidUpdate(_ notification: NSNotification) {
guard let state = notification.userInfo?[kManagerNotificationData] as? NSNumber else {
return
}
guard let authState = SMAuthState(rawValue: state.uintValue) else {
return
}
switch authState {
case .loggedOut:
logout.isEnabled = false
userInfo.isEnabled = false
status.text? = "Logged Out"
default:
break
}
}
@objc private func userDidUpdate(_ notification: NSNotification) {
if let user = userManager.currentUser {
logout.isEnabled = true
userInfo.isEnabled = true
let email = (user.email != nil) ? user.email! : "Anonymous User"
status.text? = "Email: \(email)\nID: \(user.userID)"
} else {
logout.isEnabled = false
userInfo.isEnabled = false
status.text? = "Logged Out"
}
}
@IBAction func openWebAuthentication(_ sender: UIButton) {
authProvider?.startWebAuthorization(in: self) { (state: SMAuthState, error: SMError?) in
if let error = error {
Util.failed(self, message: error.message)
}
}
}
@IBAction private func logoutUser(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: "Logging out...", message: nil, preferredStyle: .alert)
present(alert, animated: true) {
self.authProvider?.logOutUser { (state: SMAuthState, error: SMError?) in
alert.dismiss(animated: true) {
if let error = error {
Util.failed(self, message: error.message)
}
}
}
}
}
}
| mit | e9f9f6e7bc79f7c4531baefb43125c41 | 34.976744 | 167 | 0.616246 | 4.958333 | false | false | false | false |
PJayRushton/stats | Pods/SpreadsheetView/Framework/Sources/SpreadsheetView+CirclularScrolling.swift | 1 | 4665 | //
// SpreadsheetView+CirclularScrolling.swift
// SpreadsheetView
//
// Created by Kishikawa Katsumi on 5/1/17.
// Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//
import UIKit
extension SpreadsheetView {
func scrollToHorizontalCenter() {
rowHeaderView.state.contentOffset.x = centerOffset.x
tableView.state.contentOffset.x = centerOffset.x
}
func scrollToVerticalCenter() {
columnHeaderView.state.contentOffset.y = centerOffset.y
tableView.state.contentOffset.y = centerOffset.y
}
func recenterHorizontallyIfNecessary() {
let currentOffset = tableView.state.contentOffset
let distance = currentOffset.x - centerOffset.x
let threshold = tableView.state.contentSize.width / 4
if fabs(distance) > threshold {
if distance > 0 {
rowHeaderView.state.contentOffset.x = distance
tableView.state.contentOffset.x = distance
} else {
let offset = centerOffset.x + (centerOffset.x - threshold)
rowHeaderView.state.contentOffset.x = offset
tableView.state.contentOffset.x = offset
}
}
}
func recenterVerticallyIfNecessary() {
let currentOffset = tableView.state.contentOffset
let distance = currentOffset.y - centerOffset.y
let threshold = tableView.state.contentSize.height / 4
if fabs(distance) > threshold {
if distance > 0 {
columnHeaderView.state.contentOffset.y = distance
tableView.state.contentOffset.y = distance
} else {
let offset = centerOffset.y + (centerOffset.y - threshold)
columnHeaderView.state.contentOffset.y = offset
tableView.state.contentOffset.y = offset
}
}
}
func determineCircularScrollScalingFactor() -> (horizontal: Int, vertical: Int) {
return (determineHorizontalCircularScrollScalingFactor(), determineVerticalCircularScrollScalingFactor())
}
func determineHorizontalCircularScrollScalingFactor() -> Int {
guard circularScrollingOptions.direction.contains(.horizontally) else {
return 1
}
let tableContentWidth = layoutProperties.columnWidth - layoutProperties.frozenColumnWidth
let tableWidth = frame.width - layoutProperties.frozenColumnWidth
var scalingFactor = 3
while tableContentWidth > 0 && Int(tableContentWidth) * scalingFactor < Int(tableWidth) * 3 {
scalingFactor += 3
}
return scalingFactor
}
func determineVerticalCircularScrollScalingFactor() -> Int {
guard circularScrollingOptions.direction.contains(.vertically) else {
return 1
}
let tableContentHeight = layoutProperties.rowHeight - layoutProperties.frozenRowHeight
let tableHeight = frame.height - layoutProperties.frozenRowHeight
var scalingFactor = 3
while tableContentHeight > 0 && Int(tableContentHeight) * scalingFactor < Int(tableHeight) * 3 {
scalingFactor += 3
}
return scalingFactor
}
func calculateCenterOffset() -> CGPoint {
var centerOffset = CGPoint.zero
if circularScrollingOptions.direction.contains(.horizontally) {
for column in 0..<layoutProperties.numberOfColumns {
centerOffset.x += layoutProperties.columnWidthCache[column % numberOfColumns] + intercellSpacing.width
}
if circularScrollingOptions.tableStyle.contains(.columnHeaderNotRepeated) {
for column in 0..<layoutProperties.frozenColumns {
centerOffset.x -= layoutProperties.columnWidthCache[column]
}
centerOffset.x -= intercellSpacing.width * CGFloat(layoutProperties.frozenColumns)
}
centerOffset.x *= CGFloat(circularScrollScalingFactor.horizontal / 3)
}
if circularScrollingOptions.direction.contains(.vertically) {
for row in 0..<layoutProperties.numberOfRows {
centerOffset.y += layoutProperties.rowHeightCache[row % numberOfRows] + intercellSpacing.height
}
if circularScrollingOptions.tableStyle.contains(.rowHeaderNotRepeated) {
for column in 0..<layoutProperties.frozenRows {
centerOffset.y -= layoutProperties.rowHeightCache[column]
}
centerOffset.y -= intercellSpacing.height * CGFloat(layoutProperties.frozenRows)
}
}
return centerOffset
}
}
| mit | 7b75704735a3402f3a5b724610695885 | 41.018018 | 118 | 0.648799 | 5.612515 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Loader/LoadingAnimatingView.swift | 1 | 4330 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import UIKit
public final class LoadingAnimatingView: LoadingCircleView {
// MARK: - Static Properties
private static let strokeEndKeyPath: String = "strokeEnd"
private static let transformRotationKeyPath: String = "transform.rotation"
// MARK: - Types
private struct Descriptor {
/// Describes the start time in relation to the previous start time.
let startTime: CFTimeInterval
/// Describes the start angle ratio to a full circle
let startAngle: CGFloat
/// Describes the length of the circumference
let length: CGFloat
init(startTime: CFTimeInterval, startAngle: CGFloat, length: CGFloat) {
self.startTime = startTime
self.startAngle = startAngle
self.length = length
}
}
private struct Summary {
var times: [CFTimeInterval] = []
var angles: [CGFloat] = []
var lengths: [CGFloat] = []
}
// MARK: - Properties
/// Represents the changes in times, start & end positions of stroke
private let descriptors = [
Descriptor(startTime: 0, startAngle: 0, length: 0),
Descriptor(startTime: 0.15, startAngle: 0, length: 0.15),
Descriptor(startTime: 0.3, startAngle: 0, length: 0.25),
Descriptor(startTime: 0.5, startAngle: 0, length: 0.5),
Descriptor(startTime: 0.3, startAngle: 0.25, length: 0.7),
Descriptor(startTime: 0.2, startAngle: 0.5, length: 0.5),
Descriptor(startTime: 0.2, startAngle: 0.7, length: 0.3),
Descriptor(startTime: 0.2, startAngle: 0.9, length: 0.1),
Descriptor(startTime: 0.1, startAngle: 0.95, length: 0.05),
Descriptor(startTime: 0, startAngle: 1, length: 0)
]
// MARK: - Setup
override public init(diameter: CGFloat, strokeColor: UIColor, strokeBackgroundColor: UIColor, fillColor: UIColor, strokeWidth: CGFloat = 8) {
super.init(
diameter: diameter,
strokeColor: strokeColor,
strokeBackgroundColor: strokeBackgroundColor,
fillColor: fillColor,
strokeWidth: strokeWidth
)
accessibility = .id(Accessibility.Identifier.LoadingView.loadingView)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Starts the animation
public func animate() {
// Calculate the total time of the animation
let totalTime = descriptors
.map(\.startTime)
.reduce(0, +)
let fullAngle: CGFloat = 2 * .pi
var time: CFTimeInterval = 0
var summary = descriptors
.reduce(into: Summary()) { result, current in
time += current.startTime
result.times.append(time / totalTime)
result.angles.append(current.startAngle * fullAngle)
result.lengths.append(current.length)
}
summary.times.append(summary.times[0])
summary.angles.append(summary.angles[0])
summary.lengths.append(summary.lengths[0])
// Animate length
animateKeyPath(
keyPath: LoadingAnimatingView.strokeEndKeyPath,
duration: totalTime,
times: summary.times,
values: summary.lengths
)
// Animate rotation
animateKeyPath(
keyPath: LoadingAnimatingView.transformRotationKeyPath,
duration: totalTime,
times: summary.times,
values: summary.angles
)
}
public func stop() {
layer.removeAnimation(forKey: LoadingAnimatingView.strokeEndKeyPath)
layer.removeAnimation(forKey: LoadingAnimatingView.transformRotationKeyPath)
}
private func animateKeyPath(
keyPath: String,
duration: CFTimeInterval,
times: [CFTimeInterval],
values: [CGFloat]
) {
let animation = CAKeyframeAnimation(keyPath: keyPath)
animation.keyTimes = times as [NSNumber]
animation.values = values
animation.calculationMode = .cubic
animation.duration = duration
animation.repeatCount = .infinity
layer.add(animation, forKey: keyPath)
}
}
| lgpl-3.0 | fc0ba244702050159158f2b9ae751616 | 32.045802 | 145 | 0.622777 | 4.886005 | false | false | false | false |
pengpengCoder/Refresher | Refresher/GIFItem.swift | 1 | 4996 | //
// GIFItem.swift
// Refresher
//
// Created by MingChen on 2017/10/20.
// Copyright © 2017年 MingChen. All rights reserved.
//
import UIKit
import ImageIO
import MobileCoreServices
final class GIFItem {
private let data: Data
private let isBig: Bool
private let height: CGFloat
let imageView = GIFAnimatedImageView()
init(data: Data, isBig: Bool, height: CGFloat) {
self.data = data
self.isBig = isBig
self.height = height
guard let animatedImage = GIFAnimatedImage(data: data) else {
print("Error: data is not an animated image")
return
}
imageView.animatedImage = animatedImage
if isBig {
imageView.bounds.size = CGSize(width: UIScreen.main.bounds.width, height: height)
imageView.contentMode = .scaleAspectFill
} else {
let ratio = animatedImage.size.width / animatedImage.size.height
imageView.bounds.size = CGSize(width: ratio * height * 0.67, height: height * 0.67)
imageView.contentMode = .scaleAspectFit
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("SwiftPullToRefresh: init(coder:) has not been implemented")
}
func didUpdateState(_ isRefreshing: Bool) {
isRefreshing ? imageView.startAnimating() : imageView.stopAnimating()
}
func didUpdateProgress(_ progress: CGFloat) {
guard let count = imageView.animatedImage?.frameCount else { return }
if progress == 1 {
imageView.startAnimating()
} else {
imageView.stopAnimating()
imageView.index = Int(CGFloat(count - 1) * progress)
}
}
}
protocol AnimatedImage: class {
var size: CGSize { get }
var frameCount: Int { get }
func frameDurationForImage(at index: Int) -> TimeInterval
subscript(index: Int) -> UIImage { get }
}
final class GIFAnimatedImage: AnimatedImage {
typealias ImageInfo = (image: UIImage, duration: TimeInterval)
private var images: [ImageInfo] = []
var size: CGSize {
return images.first?.image.size ?? .zero
}
var frameCount: Int {
return images.count
}
init?(data: Data) {
guard
let source = CGImageSourceCreateWithData(data as CFData, nil),
let type = CGImageSourceGetType(source)
else { return nil }
let isTypeGIF = UTTypeConformsTo(type, kUTTypeGIF)
let count = CGImageSourceGetCount(source)
if !isTypeGIF || count <= 1 { return nil }
for index in 0 ..< count {
guard
let image = CGImageSourceCreateImageAtIndex(source, index, nil),
let info = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [String : Any],
let gifInfo = info[kCGImagePropertyGIFDictionary as String] as? [String: Any]
else { continue }
var duration: Double = 0
if let unclampedDelay = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? Double {
duration = unclampedDelay
} else {
duration = gifInfo[kCGImagePropertyGIFDelayTime as String] as? Double ?? 0.1
}
if duration <= 0.001 {
duration = 0.1
}
images.append((UIImage(cgImage: image), duration))
}
}
func frameDurationForImage(at index: Int) -> TimeInterval {
return images[index].duration
}
subscript(index: Int) -> UIImage {
return images[index].image
}
}
final class GIFAnimatedImageView: UIImageView {
var animatedImage: AnimatedImage? {
didSet {
image = animatedImage?[0]
}
}
var index: Int = 0 {
didSet {
if index != oldValue {
image = animatedImage?[index]
}
}
}
private var animated = false
private var lastTimestampChange = CFTimeInterval(0)
private lazy var displayLink: CADisplayLink = {
let displayLink = CADisplayLink(target: self, selector: #selector(refreshDisplay))
displayLink.add(to: .main, forMode: .commonModes)
displayLink.isPaused = true
return displayLink
}()
override func startAnimating() {
if animated { return }
displayLink.isPaused = false
animated = true
}
override func stopAnimating() {
if !animated { return }
displayLink.isPaused = true
animated = false
}
@objc private func refreshDisplay() {
guard animated, let animatedImage = animatedImage else { return }
let currentFrameDuration = animatedImage.frameDurationForImage(at: index)
let delta = displayLink.timestamp - lastTimestampChange
if delta >= currentFrameDuration {
index = (index + 1) % animatedImage.frameCount
lastTimestampChange = displayLink.timestamp
}
}
}
| mit | 028c44faff074c1664301b2185784aad | 27.531429 | 105 | 0.608852 | 5.028197 | false | false | false | false |
onlynight/RichEditorView | RichEditorView/Classes/RichEditorToolbar.swift | 4 | 5076 | //
// RichEditorToolbar.swift
//
// Created by Caesar Wirth on 4/2/15.
// Copyright (c) 2015 Caesar Wirth. All rights reserved.
//
import UIKit
/**
RichEditorToolbarDelegate is a protocol for the RichEditorToolbar.
Used to receive actions that need extra work to perform (eg. display some UI)
*/
public protocol RichEditorToolbarDelegate: class {
/**
Called when the Text Color toolbar item is pressed.
*/
func richEditorToolbarChangeTextColor(toolbar: RichEditorToolbar)
/**
Called when the Background Color toolbar item is pressed.
*/
func richEditorToolbarChangeBackgroundColor(toolbar: RichEditorToolbar)
/**
Called when the Insert Image toolbar item is pressed.
*/
func richEditorToolbarInsertImage(toolbar: RichEditorToolbar)
/**
Called when the Isert Link toolbar item is pressed.
*/
func richEditorToolbarChangeInsertLink(toolbar: RichEditorToolbar)
}
/**
RichBarButtonItem is a subclass of UIBarButtonItem that takes a callback as opposed to the target-action pattern
*/
public class RichBarButtonItem: UIBarButtonItem {
public var actionHandler: (Void -> Void)?
public convenience init(image: UIImage? = nil, handler: (Void -> Void)? = nil) {
self.init(image: image, style: .Plain, target: nil, action: nil)
target = self
action = Selector("buttonWasTapped")
actionHandler = handler
}
public convenience init(title: String = "", handler: (Void -> Void)? = nil) {
self.init(title: title, style: .Plain, target: nil, action: nil)
target = self
action = Selector("buttonWasTapped")
actionHandler = handler
}
func buttonWasTapped() {
actionHandler?()
}
}
/**
RichEditorToolbar is UIView that contains the toolbar for actions that can be performed on a RichEditorView
*/
public class RichEditorToolbar: UIView {
/**
The delegate to receive events that cannot be automatically completed
*/
public weak var delegate: RichEditorToolbarDelegate?
/**
A reference to the RichEditorView that it should be performing actions on
*/
public weak var editor: RichEditorView?
/**
The list of options to be displayed on the toolbar
*/
public var options: [RichEditorOption] = [] {
didSet {
updateToolbar()
}
}
private var toolbarScroll: UIScrollView
private var toolbar: UIToolbar
private var backgroundToolbar: UIToolbar
public override init(frame: CGRect) {
toolbarScroll = UIScrollView()
toolbar = UIToolbar()
backgroundToolbar = UIToolbar()
super.init(frame: frame)
setup()
}
public required init(coder aDecoder: NSCoder) {
toolbarScroll = UIScrollView()
toolbar = UIToolbar()
backgroundToolbar = UIToolbar()
super.init(coder: aDecoder)
setup()
}
private func setup() {
self.autoresizingMask = .FlexibleWidth
backgroundToolbar.frame = self.bounds
backgroundToolbar.autoresizingMask = .FlexibleHeight | .FlexibleWidth
toolbar.autoresizingMask = .FlexibleWidth
toolbar.setBackgroundImage(UIImage(), forToolbarPosition: .Any, barMetrics: .Default)
toolbar.setShadowImage(UIImage(), forToolbarPosition: .Any)
toolbarScroll.frame = self.bounds
toolbarScroll.autoresizingMask = .FlexibleHeight | .FlexibleWidth
toolbarScroll.showsHorizontalScrollIndicator = false
toolbarScroll.showsVerticalScrollIndicator = false
toolbarScroll.backgroundColor = UIColor.clearColor()
toolbarScroll.addSubview(toolbar)
self.addSubview(backgroundToolbar)
self.addSubview(toolbarScroll)
}
private func updateToolbar() {
var buttons = [UIBarButtonItem]()
for option in options {
if let image = option.image() {
let button = RichBarButtonItem(image: image) { [weak self] in option.action(self) }
buttons.append(button)
} else {
let title = option.title()
let button = RichBarButtonItem(title: title) { [weak self] in option.action(self) }
buttons.append(button)
}
}
toolbar.items = buttons
let defaultIconWidth: CGFloat = 22
let barButtonItemMargin: CGFloat = 11
var width: CGFloat = buttons.reduce(0) {sofar, new in
if let view = new.valueForKey("view") as? UIView {
return sofar + view.frame.size.width + barButtonItemMargin
} else {
return sofar + (defaultIconWidth + barButtonItemMargin)
}
}
if width < self.frame.size.width {
toolbar.frame.size.width = self.frame.size.width
} else {
toolbar.frame.size.width = width
}
toolbar.frame.size.height = 44
toolbarScroll.contentSize.width = width
}
}
| bsd-3-clause | f7550d2e6f0b1c96d225f48eb217b4bc | 30.141104 | 116 | 0.640071 | 5.142857 | false | false | false | false |
Galeas/scorocode-SDK-swift | SC/SCSignupViewController.swift | 1 | 2711 | //
// SCSignupViewController.swift
// SC
//
// Created by Aleksandr Konakov on 24/05/16.
// Copyright © 2016 Aleksandr Konakov. All rights reserved.
//
import UIKit
class SCSignupViewController: UIViewController {
@IBOutlet private weak var usernameTextField: UITextField!
@IBOutlet private weak var emailTextField: UITextField!
@IBOutlet private weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction private func signupPressed() {
guard let email = emailTextField.text where email != "",
let password = passwordTextField.text where password != "",
let username = usernameTextField.text where username != "" else {
let alert = UIAlertController(title: "Регистрация невозможна", message: "Не указан email, пароль или имя пользователя", preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default) {
action in
return
}
alert.addAction(ok)
presentViewController(alert, animated: true, completion: nil)
return
}
let user = SCUser()
user.signup(username, email: email, password: password) {
success, error, result in
if success {
let alert = UIAlertController(title: "Пользователь зарегистрирован", message: nil, preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default) {
action in
self.dismissViewControllerAnimated(true, completion: nil)
}
alert.addAction(ok)
self.presentViewController(alert, animated: true, completion: nil)
} else {
var message = ""
switch error! {
case .API(_, let apiMessage):
message = apiMessage
default:
break
}
let alert = UIAlertController(title: "Ошибка при регистрации", message: message, preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default) {
action in
}
alert.addAction(ok)
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
@IBAction private func cancelPressed() {
dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 51af78b858c180d65eb19ddc960efb13 | 36.285714 | 159 | 0.567433 | 5.147929 | false | false | false | false |
saturnboy/learning_spritekit_swift | LearningSpriteKit/LearningSpriteKit/GameScene2.swift | 1 | 2154 | //
// GameScene2.swift
// LearningSpriteKit
//
// Created by Justin on 12/1/14.
// Copyright (c) 2014 SaturnBoy. All rights reserved.
//
import SpriteKit
class GameScene2: SKScene {
let alien = SKSpriteNode(imageNamed: "alien1")
override func didMoveToView(view: SKView) {
println("GameScene2: \(view.frame.size)")
self.backgroundColor = UIColor(red: 0.1, green: 0.3, blue: 0.1, alpha: 1.0)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if let touch: AnyObject = touches.anyObject() {
let loc = touch.locationInNode(self)
println("touch: \(loc)")
// move alien to touch pos
let alien = SKSpriteNode(imageNamed: "alien1")
alien.position = loc
self.addChild(alien)
let move = SKAction.moveByX(25.0, y: 75.0, duration: 0.5)
let rotate = SKAction.rotateByAngle(3.14, duration: 0.5)
let fadeOut = SKAction.fadeOutWithDuration(0.5)
let remove = SKAction.removeFromParent()
// Try some other actions...
// 1. wait
//let wait = SKAction.waitForDuration(1.0)
// 2. fadeIn
//let fadeIn = SKAction.fadeInWithDuration(1.0)
// 3. scale
//let doubleSize = SKAction.scaleBy(2.0, duration: 1.0)
//let halfSize = SKAction.scaleBy(0.5, duration:1.0)
// 4. colorize
//let green = SKAction.colorizeWithColor(UIColor.greenColor(), colorBlendFactor: 1.0, duration: 1.0)
//let ungreen = SKAction.colorizeWithColor(UIColor.greenColor(), colorBlendFactor: 0, duration: 1.0)
// 5. actions in parallel
//let parallel = SKAction.group([move, rotate, halfSize]);
// run these actions on alien in order
alien.runAction(SKAction.sequence([move, rotate, fadeOut, remove]))
}
}
override func update(currentTime: CFTimeInterval) {
//pass
}
}
| mit | 083d2ae7b743e6331fac0b595e6f3088 | 33.190476 | 112 | 0.557103 | 4.47817 | false | false | false | false |
arslanbilal/Sample-OSX-MenuBarApp | Quotes/Quotes/EventMonitor.swift | 1 | 733 | //
// EventMonitor.swift
// Quotes
//
// Created by Bilal Arslan on 02/06/15.
// Copyright (c) 2015 Bilal Arslan. All rights reserved.
//
import Cocoa
public class EventMonitor {
private var monitor: AnyObject?
private let mask: NSEventMask
private let handler: NSEvent? -> ()
public init(mask: NSEventMask, handler: NSEvent? -> ()) {
self.mask = mask
self.handler = handler
}
deinit {
stop()
}
public func start() {
monitor = NSEvent.addGlobalMonitorForEventsMatchingMask(mask, handler: handler)
}
public func stop() {
if monitor != nil {
NSEvent.removeMonitor(monitor!)
monitor = nil
}
}
} | mit | f8e1cc7db7f07e03c9c61defd709e287 | 19.971429 | 87 | 0.583902 | 4.28655 | false | false | false | false |
64characters/Telephone | UseCasesTests/MatchedContactTests.swift | 1 | 1572 | //
// MatchedContactTests.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UseCases
import XCTest
final class MatchedContactTests: XCTestCase {
func testNameIsURIDisplayNameOnCreationFromURI() {
let uri = URI(user: "any-user", host: "any-host", displayName: "any-name")
let result = MatchedContact(uri: uri)
XCTAssertEqual(result.name, uri.displayName)
}
func testAddressIsEmailComposedOfUserAndHostWhenHostIsNotEmptyOnCreationFromURI() {
let uri = URI(user: "any-user", host: "any-host", displayName: "any-name")
let result = MatchedContact(uri: uri)
XCTAssertEqual(result.address, .email(address: "\(uri.user)@\(uri.host)", label:""))
}
func testAddressIsPhoneComposedOfUserWhenHostIsEmptyOnCreationFromURI() {
let uri = URI(user: "any-user", host: "", displayName: "any-name")
let result = MatchedContact(uri: uri)
XCTAssertEqual(result.address, .phone(number: uri.user, label: ""))
}
}
| gpl-3.0 | 8f96ce6440b2392948ee0ed5aa58e2bf | 33.130435 | 92 | 0.701911 | 4.056848 | false | true | false | false |
cwaffles/Soulcast | Soulcast/SoulPlayer.swift | 1 | 2152 |
import UIKit
import TheAmazingAudioEngine
let soulPlayer = SoulPlayer()
protocol SoulPlayerDelegate: AnyObject {
func didStartPlaying(_ soul:Soul)
func didFinishPlaying(_ soul:Soul)
func didFailToPlay(_ soul:Soul)
}
class SoulPlayer: NSObject {
fileprivate var tempSoul: Soul?
fileprivate var player: AEAudioFilePlayer?
static var playing = false
fileprivate var subscribers:[SoulPlayerDelegate] = []
func startPlaying(_ soul:Soul!) {
guard !SoulPlayer.playing else{
reset()
startPlaying(soul)
return
}
tempSoul = soul
let filePath = URL(fileURLWithPath: soul.localURL! as String)
do {
player = try AEAudioFilePlayer(url: filePath)
audioController?.addChannels([player!])
player?.removeUponFinish = true
SoulPlayer.playing = true
sendStartMessage(soul)
player?.completionBlock = {
self.reset()
self.sendFinishMessage(soul)
}
} catch {
assert(false);
sendFailMessage(soul)
print("oh noes! playAudioAtPath fail")
return
}
}
func lastSoul() -> Soul? {
return tempSoul
}
func sendStartMessage(_ soul:Soul) {
for eachSubscriber in subscribers {
eachSubscriber.didStartPlaying(soul)
}
}
func sendFinishMessage(_ soul:Soul) {
for eachSubscriber in subscribers {
eachSubscriber.didFinishPlaying(soul)
}
}
func sendFailMessage(_ soul:Soul) {
for eachSubscriber in subscribers {
eachSubscriber.didFailToPlay(soul)
}
}
func reset() {
if player != nil {
audioController?.removeChannels([player!])
SoulPlayer.playing = false
}
}
func subscribe(_ subscriber:SoulPlayerDelegate) {
var contains = false
for eachSubscriber in subscribers {
if eachSubscriber === subscriber {
contains = true
break
}
}
if !contains {
subscribers.append(subscriber)
}
}
func unsubscribe(_ subscriber:SoulPlayerDelegate) {
if let removalIndex = subscribers.index(where: {$0 === subscriber}) {
subscribers.remove(at: removalIndex)
}
}
}
| mit | 98c8aae5745e0e0458dcacaa3ca04191 | 20.959184 | 73 | 0.649164 | 4.521008 | false | false | false | false |
volendavidov/NagBar | NagBar/MenuAction.swift | 1 | 4103 | //
// MenuAction.swift
// NagBar
//
// Created by Volen Davidov on 24.07.16.
// Copyright © 2016 Volen Davidov. All rights reserved.
//
import Foundation
import Cocoa
@objc protocol MenuAction {
func action(_ sender: NSMenuItem)
}
class RecheckAction: NSObject, MenuAction {
func action(_ sender: NSMenuItem) {
let monitoringItems = sender.representedObject as! Array<MonitoringItem>
let monitoringInstance = monitoringItems[0].monitoringInstance
monitoringInstance!.monitoringProcessor().command().recheck(monitoringItems)
}
}
class ScheduleDowntimeAction: NSObject, MenuAction {
private var downtimeWindow: ScheduleDowntimeWindow?
func action(_ sender: NSMenuItem) {
if self.downtimeWindow == nil {
self.downtimeWindow = ScheduleDowntimeWindow(windowNibName: "ScheduleDowntimeWindow")
}
self.downtimeWindow!.monitoringItems = sender.representedObject as! Array<MonitoringItem>
self.downtimeWindow!.showWindow(self)
}
}
class AcknowledgeAction: NSObject, MenuAction {
private var downtimeWindow: AcknowledgeWindow?
func action(_ sender: NSMenuItem) {
if self.downtimeWindow == nil {
self.downtimeWindow = AcknowledgeWindow(windowNibName: "AcknowledgeWindow")
}
self.downtimeWindow!.monitoringItems = sender.representedObject as! Array<MonitoringItem>
self.downtimeWindow!.showWindow(self)
}
}
class AddToFilterAction : NSObject, MenuAction {
func action(_ sender: NSMenuItem) {
let alert = NSAlert()
alert.addButton(withTitle: NSLocalizedString("no", comment: ""))
alert.addButton(withTitle: NSLocalizedString("yes", comment: ""))
alert.messageText = NSLocalizedString("addToFilter", comment: "")
alert.informativeText = NSLocalizedString("addToFilterConfirm", comment: "")
alert.alertStyle = .warning
if alert.runModal() == NSApplication.ModalResponse.alertSecondButtonReturn {
let monitoringItems = sender.representedObject as! Array<MonitoringItem>
self.addToFilter(monitoringItems)
}
}
private func addToFilter(_ monitoringItems: Array<MonitoringItem>) {
let filterItemServiceStatus = ["CRITICAL": 16, "UNKNOWN": 8, "WARNING": 4, "PENDING" : 1]
let filterItemHostStatus = ["UNREACHABLE": 8, "DOWN": 4, "PENDING" : 1]
for monitoringItem in monitoringItems {
let key = FilterItems.generateKey(monitoringItem.host, service: monitoringItem.service)
// this is the case where the monitoring item already has a filter, but it is
// for a different status
if let filterItem = FilterItems().getByKey(key) {
if monitoringItem.monitoringItemType == .service {
// There is no need to use bitwise operations, as if the value already exists, it won't be displayed in the table view at first place. But bitwise is the proper way to do it.
FilterItems().updateStatus(filterItem: filterItem, status: filterItem.status | filterItemServiceStatus[monitoringItem.status]!)
} else {
FilterItems().updateStatus(filterItem: filterItem, status: filterItem.status | filterItemHostStatus[monitoringItem.status]!)
}
} else {
var statusCode = 0
if monitoringItem.monitoringItemType == .service {
statusCode = filterItemServiceStatus[monitoringItem.status]!
} else {
statusCode = filterItemHostStatus[monitoringItem.status]!
}
let filterItem = FilterItem().initDefault(host: monitoringItem.host, service: monitoringItem.service, status: statusCode)
FilterItems().insert(key: key, value: filterItem)
}
}
}
}
| apache-2.0 | 6d87d27e15c20d73f5cec1f23b73cf03 | 37.698113 | 194 | 0.632131 | 5.306598 | false | false | false | false |
mspvirajpatel/SwiftyBase | Example/SwiftyBase/Controller/ImageViewer/DisplayAllImageView.swift | 1 | 10446 | //
// DisplayAllImageView.swift
// SwiftyBase
//
// Created by MacMini-2 on 18/09/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
import SwiftyBase
class DisplayAllImageView: BaseView,UICollectionViewDelegate,UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{
// MARK: - Attribute -
var photoCollectionView:UICollectionView!
var flowLayout:UICollectionViewFlowLayout!
var photoListArray:NSMutableArray!
var photoListCount:NSInteger!
var previousPhotoListCount:NSInteger!
var nextPhotoListCount:NSInteger!
var collectionCellSize:CGSize! = AppInterfaceUtility.getAppropriateSizeFromSize(UIScreen.main.bounds.size, withDivision: 3.0, andInterSpacing: 5.0)
// MARK: - Lifecycle -
override init(frame: CGRect)
{
super.init(frame:frame)
self.loadViewControls()
self.setViewlayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}
deinit{
}
// MARK: - Layout -
override func loadViewControls()
{
super.loadViewControls()
photoListArray = [
"http://www.intrawallpaper.com/static/images/HD-Wallpapers1_Q75eDHE_lG95giJ.jpeg",
"http://www.intrawallpaper.com/static/images/hd-wallpapers-8_FY4tW4s.jpg",
"http://www.intrawallpaper.com/static/images/tiger-wallpapers-hd-Bengal-Tiger-hd-wallpaper.jpg",
"http://www.intrawallpaper.com/static/images/3D-Beach-Wallpaper-HD-Download_QssSQPf.jpg",
"http://www.intrawallpaper.com/static/images/pixars_up_hd_wide-wide.jpg",
"http://www.intrawallpaper.com/static/images/tree_snake_hd-wide.jpg",
"http://www.intrawallpaper.com/static/images/3D-Wallpaper-HD-35_hx877p1.jpg",
"http://www.intrawallpaper.com/static/images/tropical-beach-background-8.jpg",
"http://www.intrawallpaper.com/static/images/1912472_ePOwBxX.jpg",
"http://www.intrawallpaper.com/static/images/Colors_digital_hd_wallpaper_F37Cy15.jpg",
"http://www.intrawallpaper.com/static/images/funky-wallpaper-hd_4beLiY2.jpg",
"http://www.intrawallpaper.com/static/images/dna_nano_tech-wide_dyyhibN.jpg",
"http://www.intrawallpaper.com/static/images/dream_village_hd-HD.jpg",
"http://www.intrawallpaper.com/static/images/hd-wallpaper-25_hOaS0Jp.jpg","http://www.intrawallpaper.com/static/images/Golden-Gate-Bridge-HD-Wallpapers-WideScreen2.jpg"
,"http://www.intrawallpaper.com/static/images/hd-wallpaper-40_HM6Q9LK.jpg"
]
photoListCount = photoListArray.count
/* photoCollectionView Allocation */
flowLayout = UICollectionViewFlowLayout.init()
flowLayout.scrollDirection = .vertical
photoCollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: flowLayout)
photoCollectionView.translatesAutoresizingMaskIntoConstraints = false
photoCollectionView.allowsMultipleSelection = false
photoCollectionView.backgroundColor = UIColor.clear
photoCollectionView.delegate = self
photoCollectionView.dataSource = self
photoCollectionView .register(PhotoCollectionCell.self, forCellWithReuseIdentifier: CellIdentifire.defaultCell)
self.addSubview(photoCollectionView)
}
override func setViewlayout()
{
super.setViewlayout()
baseLayout.expandView(photoCollectionView, insideView: self)
self.layoutSubviews()
self.layoutIfNeeded()
}
// MARK: - Public Interface -
// MARK: - User Interaction -
// MARK: - Internal Helpers -
// MARK: - UICollectionView DataSource Methods -
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if photoListCount == 0 {
self.displayErrorMessageLabel("No Record Found")
}
else
{
self.displayErrorMessageLabel(nil)
}
return photoListCount ?? 0
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell : PhotoCollectionCell!
cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifire.defaultCell, for: indexPath) as? PhotoCollectionCell
if cell == nil
{
cell = PhotoCollectionCell(frame: CGRect.zero)
}
if(indexPath.row < photoListArray.count){
var imageString:NSString? = photoListArray[indexPath.row] as? NSString
cell.displayImage(image: imageString!)
imageString = nil;
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
func setPhoto() -> [PhotoModel] {
var photos: [PhotoModel] = []
for photoURLString in photoListArray {
let photoModel = PhotoModel(imageUrlString: photoURLString as? String, sourceImageView: nil)
photos.append(photoModel)
}
return photos
}
let photoBrowser = PhotoBrowser(photoModels: setPhoto())
photoBrowser.delegate = self
photoBrowser.show(inVc: self.getViewControllerFromSubView()!, beginPage: indexPath.row)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionCellSize
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0)
}
// MARK: - Server Request -
// public func getAllImagesRequest()
// {
//
// operationQueue.addOperation { [weak self] in
// if self == nil{
// return
// }
//
// BaseAPICall.shared.postReques(URL: APIConstant.userPhotoList, Parameter: NSDictionary(), Type: APITask.GetAllImages) { [weak self] (result) in
// if self == nil{
// return
// }
//
// switch result{
// case .Success(let object,let error):
//
// self!.hideProgressHUD()
//
// var imageArray: NSMutableArray! = object as! NSMutableArray
// self!.previousPhotoListCount = self!.photoListArray.count
// self!.nextPhotoListCount = imageArray.count
// self!.photoListArray = imageArray
// self!.photoListCount = self!.photoListArray.count
//
// AppUtility.executeTaskInMainQueueWithCompletion { [weak self] in
// if self == nil{
// return
// }
// self!.photoCollectionView.reloadData()
// }
//
// defer{
// imageArray = nil
// }
//
// break
// case .Error(let error):
//
// self!.hideProgressHUD()
// AppUtility.executeTaskInMainQueueWithCompletion {
// AppUtility.showWhisperAlert(message: error!.serverMessage, duration: 1.0)
// }
//
// break
// case .Internet(let isOn):
// self!.handleNetworkCheck(isAvailable: isOn)
// break
// }
// }
// }
// }
//
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
extension DisplayAllImageView: PhotoBrowserDelegate {
func photoBrowserWillEndDisplay(_ endPage: Int) {
let currentIndexPath = IndexPath(row: endPage, section: 0)
let cell = photoCollectionView.cellForItem(at: currentIndexPath) as? PhotoCollectionCell
cell?.alpha = 0.0
}
func photoBrowserDidEndDisplay(_ endPage: Int) {
let currentIndexPath = IndexPath(row: endPage, section: 0)
let cell = photoCollectionView.cellForItem(at: currentIndexPath) as? PhotoCollectionCell
cell?.alpha = 1.0
}
func photoBrowserDidDisplayPage(_ currentPage: Int, totalPages: Int) {
let visibleIndexPaths = photoCollectionView.indexPathsForVisibleItems
let currentIndexPath = IndexPath(row: currentPage, section: 0)
if !visibleIndexPaths.contains(currentIndexPath) {
photoCollectionView.scrollToItem(at: currentIndexPath, at: .top, animated: false)
photoCollectionView.layoutIfNeeded()
}
}
func sourceImageViewForCurrentIndex(_ index: Int) -> UIImageView? {
let currentIndexPath = IndexPath(row: index, section: 0)
let cell = photoCollectionView.cellForItem(at: currentIndexPath) as? PhotoCollectionCell
let sourceView = cell?.feedImageView
return sourceView
}
}
| mit | df21c3a715ae5951a87393f95b376a24 | 34.893471 | 180 | 0.603925 | 5.173353 | false | false | false | false |
kesun421/firefox-ios | fastlane/SnapshotHelper.swift | 2 | 9370 | //
// SnapshotHelper.swift
// Example
//
// Created by Felix Krause on 10/8/15.
// Copyright © 2015 Felix Krause. All rights reserved.
//
// -----------------------------------------------------
// IMPORTANT: When modifying this file, make sure to
// increment the version number at the very
// bottom of the file to notify users about
// the new SnapshotHelper.swift
// -----------------------------------------------------
import Foundation
import XCTest
var deviceLanguage = ""
var locale = ""
func setupSnapshot(_ app: XCUIApplication) {
Snapshot.setupSnapshot(app)
}
func snapshot(_ name: String, waitForLoadingIndicator: Bool) {
if waitForLoadingIndicator {
Snapshot.snapshot(name)
} else {
Snapshot.snapshot(name, timeWaitingForIdle: 0)
}
}
/// - Parameters:
/// - name: The name of the snapshot
/// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait.
func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) {
Snapshot.snapshot(name, timeWaitingForIdle: timeout)
}
enum SnapshotError: Error, CustomDebugStringConvertible {
case cannotDetectUser
case cannotFindHomeDirectory
case cannotFindSimulatorHomeDirectory
case cannotAccessSimulatorHomeDirectory(String)
var debugDescription: String {
switch self {
case .cannotDetectUser:
return "Couldn't find Snapshot configuration files - can't detect current user "
case .cannotFindHomeDirectory:
return "Couldn't find Snapshot configuration files - can't detect `Users` dir"
case .cannotFindSimulatorHomeDirectory:
return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable."
case .cannotAccessSimulatorHomeDirectory(let simulatorHostHome):
return "Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?"
}
}
}
open class Snapshot: NSObject {
static var app: XCUIApplication!
static var cacheDirectory: URL!
static var screenshotsDirectory: URL? {
return cacheDirectory.appendingPathComponent("screenshots", isDirectory: true)
}
open class func setupSnapshot(_ app: XCUIApplication) {
do {
let cacheDir = try pathPrefix()
Snapshot.cacheDirectory = cacheDir
Snapshot.app = app
setLanguage(app)
setLocale(app)
setLaunchArguments(app)
} catch let error {
print(error)
}
}
class func setLanguage(_ app: XCUIApplication) {
let path = cacheDirectory.appendingPathComponent("language.txt")
do {
let trimCharacterSet = CharacterSet.whitespacesAndNewlines
deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)
app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"]
} catch {
print("Couldn't detect/set language...")
}
}
class func setLocale(_ app: XCUIApplication) {
let path = cacheDirectory.appendingPathComponent("locale.txt")
do {
let trimCharacterSet = CharacterSet.whitespacesAndNewlines
locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)
} catch {
print("Couldn't detect/set locale...")
}
if locale.isEmpty {
locale = Locale(identifier: deviceLanguage).identifier
}
app.launchArguments += ["-AppleLocale", "\"\(locale)\""]
}
class func setLaunchArguments(_ app: XCUIApplication) {
let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt")
app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"]
do {
let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8)
let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: [])
let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count))
let results = matches.map { result -> String in
(launchArguments as NSString).substring(with: result.range)
}
app.launchArguments += results
} catch {
print("Couldn't detect/set launch_arguments...")
}
}
open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) {
if timeout > 0 {
waitForLoadingIndicatorToDisappear(within: timeout)
}
print("snapshot: \(name)") // more information about this, check out https://github.com/fastlane/fastlane/tree/master/snapshot#how-does-it-work
sleep(1) // Waiting for the animation to be finished (kind of)
#if os(OSX)
XCUIApplication().typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: [])
#else
let screenshot = app.windows.firstMatch.screenshot()
guard let simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return }
let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png")
do {
try screenshot.pngRepresentation.write(to: path)
} catch let error {
print("Problem writing screenshot: \(name) to \(path)")
print(error)
}
#endif
}
class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) {
#if os(tvOS)
return
#endif
let networkLoadingIndicator = XCUIApplication().otherElements.deviceStatusBars.networkLoadingIndicators.element
let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator)
XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout)
}
class func pathPrefix() throws -> URL? {
let homeDir: URL
// on OSX config is stored in /Users/<username>/Library
// and on iOS/tvOS/WatchOS it's in simulator's home dir
#if os(OSX)
guard let user = ProcessInfo().environment["USER"] else {
throw SnapshotError.cannotDetectUser
}
guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else {
throw SnapshotError.cannotFindHomeDirectory
}
homeDir = usersDir.appendingPathComponent(user)
#else
guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else {
throw SnapshotError.cannotFindSimulatorHomeDirectory
}
guard let homeDirUrl = URL(string: simulatorHostHome) else {
throw SnapshotError.cannotAccessSimulatorHomeDirectory(simulatorHostHome)
}
homeDir = URL(fileURLWithPath: homeDirUrl.path)
#endif
return homeDir.appendingPathComponent("Library/Caches/tools.fastlane")
}
}
private extension XCUIElementAttributes {
var isNetworkLoadingIndicator: Bool {
if hasWhiteListedIdentifier { return false }
let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20)
let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3)
return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize
}
var hasWhiteListedIdentifier: Bool {
let whiteListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"]
return whiteListedIdentifiers.contains(identifier)
}
func isStatusBar(_ deviceWidth: CGFloat) -> Bool {
if elementType == .statusBar { return true }
guard frame.origin == .zero else { return false }
let oldStatusBarSize = CGSize(width: deviceWidth, height: 20)
let newStatusBarSize = CGSize(width: deviceWidth, height: 44)
return [oldStatusBarSize, newStatusBarSize].contains(frame.size)
}
}
private extension XCUIElementQuery {
var networkLoadingIndicators: XCUIElementQuery {
let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in
guard let element = evaluatedObject as? XCUIElementAttributes else { return false }
return element.isNetworkLoadingIndicator
}
return self.containing(isNetworkLoadingIndicator)
}
var deviceStatusBars: XCUIElementQuery {
let deviceWidth = XCUIApplication().frame.width
let isStatusBar = NSPredicate { (evaluatedObject, _) in
guard let element = evaluatedObject as? XCUIElementAttributes else { return false }
return element.isStatusBar(deviceWidth)
}
return self.containing(isStatusBar)
}
}
private extension CGFloat {
func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool {
return numberA...numberB ~= self
}
}
// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperVersion [1.6]
| mpl-2.0 | 38bbf845c0dfc626fda04820d3efc22a | 37.240816 | 158 | 0.652257 | 5.412478 | false | false | false | false |
Dagers/macGHCi | HaskellEditor/TerminalManager.swift | 1 | 4151 | //
// TerminalManager.swift
// macGHCi
//
// Created by Daniel Strebinger on 21.02.17.
// Copyright © 2017 Daniel Strebinger. All rights reserved.
//
import Foundation
/**
Represents the interaction with the console of the system.
- Author: Daniel Strebinger
- Version: 1.0
*/
public class TerminalManager
{
/**
Represents the reference to the process of the terminal.
*/
private let process : Process
/**
Represents the read pipe object.
*/
private let readPipe : Pipe
/**
Represents the write pipe object.
*/
private let writePipe : Pipe
/**
Represents the error pipe object.
*/
private let errorPipe : Pipe
/**
Represents the read stream.
*/
private var readStream : FileHandle
/**
Represents the write stream.
*/
private var writeStream : FileHandle
/**
Represents the error stream.
*/
private var errorStream : FileHandle
/**
Initializes a new instance of the ProcessInstance class.
*/
public init()
{
self.process = Process()
self.readPipe = Pipe()
self.writePipe = Pipe()
self.errorPipe = Pipe()
self.readStream = FileHandle()
self.writeStream = FileHandle()
self.errorStream = FileHandle()
}
/**
Starts a process with command line arguments.
*/
public func start(_ command: String, args: [String]) {
self.process.launchPath = command
self.process.arguments = args
self.process.standardOutput = self.readPipe
self.process.standardInput = self.writePipe
self.process.standardError = self.errorPipe
self.errorStream = self.errorPipe.fileHandleForReading
self.errorStream.waitForDataInBackgroundAndNotify()
self.readStream = self.readPipe.fileHandleForReading
self.readStream.waitForDataInBackgroundAndNotify()
self.writeStream = self.writePipe.fileHandleForWriting
NotificationCenter.default.addObserver(self, selector: #selector(receivedTerminalData(notification:)), name: NSNotification.Name.NSFileHandleDataAvailable, object: self.readStream)
NotificationCenter.default.addObserver(self, selector: #selector(receivedTerminalData(notification:)), name: NSNotification.Name.NSFileHandleDataAvailable, object: self.errorStream)
self.process.launch()
}
/**
Writes to the terminal.
*/
public func write(_ command: String)
{
var computeCommand : String = command
computeCommand.append("\n")
self.writeStream.write(computeCommand.data(using: .utf8)!)
}
/**
Stops the terminal.
*/
public func stop()
{
self.process.terminate()
self.readStream.closeFile()
self.writeStream.closeFile()
}
/**
Interrupts the process for a specific time.
*/
public func interrupt()
{
self.process.interrupt()
}
/**
Resumes the process.
*/
public func resume()
{
self.process.resume()
}
/**
Represents the get data function for new data of the terminal.
*/
@objc private func receivedTerminalData(notification: Notification)
{
let fh : FileHandle = notification.object as! FileHandle
var data : Data = fh.availableData
if (data.count > 0)
{
fh.waitForDataInBackgroundAndNotify()
let str = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if (fh == self.readStream)
{
NotificationCenter.default.post(name:Notification.Name(rawValue:"OnNewDataReceived"),
object: nil, userInfo: ["message": str!])
return
}
NotificationCenter.default.post(name:Notification.Name(rawValue:"OnErrorDataReceived"),
object: nil, userInfo: ["message": str!])
}
}
}
| gpl-3.0 | 78caba316c9aafa97748822776b693a2 | 26.124183 | 189 | 0.600723 | 5.018138 | false | false | false | false |
iCodeForever/ifanr | ifanr/ifanr/Views/CategoryView/CategoryListHeaderView.swift | 1 | 2393 | //
// CategoryListHeaderView.swift
// ifanr
//
// Created by 梁亦明 on 16/8/1.
// Copyright © 2016年 ifanrOrg. All rights reserved.
//
import Foundation
class CategoryListHeaderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(backgroundImage)
addSubview(coverView)
addSubview(titleLabel)
addSubview(subTitleLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var model: CategoryModel! {
didSet {
backgroundImage.image = model.listImage
coverView.backgroundColor = model.coverColor
titleLabel.text = model.title
subTitleLabel.text = model.subTitle
}
}
var labelAlpha: CGFloat = 1{
didSet {
self.titleLabel.alpha = labelAlpha
self.subTitleLabel.alpha = labelAlpha
}
}
/// 背景图
fileprivate lazy var backgroundImage: UIImageView = {
var backgroundImage = UIImageView()
backgroundImage.origin = CGPoint.zero
backgroundImage.size = self.size
backgroundImage.clipsToBounds = true
backgroundImage.contentMode = .scaleAspectFill
return backgroundImage
}()
/// 标题
fileprivate lazy var titleLabel: UILabel = {
var titleLable = UILabel()
titleLable.origin = CGPoint(x: UIConstant.UI_MARGIN_20, y: self.center.y)
titleLable.size = CGSize(width: self.width-2*UIConstant.UI_MARGIN_20, height: 20)
titleLable.textColor = UIColor.white
titleLable.font = UIFont.customFont_FZLTZCHJW(fontSize: 20)
return titleLable
}()
// alpa
fileprivate lazy var coverView: UIView = {
let coverView = UIView()
coverView.origin = CGPoint.zero
coverView.size = self.size
return coverView
}()
/// 子标题
fileprivate lazy var subTitleLabel: UILabel = {
var subTitleLabel = UILabel()
subTitleLabel.origin = CGPoint(x: self.titleLabel.x, y: self.titleLabel.frame.maxY+UIConstant.UI_MARGIN_10)
subTitleLabel.size = self.titleLabel.size
subTitleLabel.textColor = UIColor.white
subTitleLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 12)
return subTitleLabel
}()
}
| mit | adee5b602866ad96bd27f063668e22ee | 30.157895 | 115 | 0.628801 | 4.852459 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceKit/Tests/EurofurenceKitTests/Messages/EurofurenceModelMessagesTests.swift | 1 | 9696 | import CoreData
@testable import EurofurenceKit
import EurofurenceWebAPI
import XCTAsyncAssertions
import XCTest
class EurofurenceModelMessagesTests: EurofurenceKitTestCase {
func testWhenSignedInMessagesAreCachedIntoContext() async throws {
let scenario = await EurofurenceModelTestBuilder().with(keychain: UnauthenticatedKeychain()).build()
let login = Login(registrationNumber: 42, username: "Some Guy", password: "p455w0rd")
let loginRequest = APIRequests.Login(registrationNumber: 42, username: "Some Guy", password: "p455w0rd")
let user = AuthenticatedUser(
userIdentifier: 42,
username: "Some Guy",
token: "Token",
tokenExpires: .distantFuture
)
let (firstReceived, firstRead) = (Date(), Date())
let secondReceived = Date()
let messages = [
EurofurenceWebAPI.Message(
id: "First Identifier",
author: "First Author",
subject: "First Subject",
message: "First Message",
receivedDate: firstReceived,
readDate: firstRead
),
EurofurenceWebAPI.Message(
id: "Second Identifier",
author: "Second Author",
subject: "Second Subject",
message: "Second Message",
receivedDate: secondReceived,
readDate: nil
)
]
scenario.api.stub(request: loginRequest, with: .success(user))
scenario.api.stub(
request: APIRequests.FetchMessages(authenticationToken: AuthenticationToken("Token")),
with: .success(messages)
)
try await scenario.model.signIn(with: login)
for message in messages {
let entity = try scenario.model.message(identifiedBy: message.id)
message.assert(against: entity)
}
}
func testAfterSigningOutMessagesAreRemovedFromContext() async throws {
let scenario = await EurofurenceModelTestBuilder().with(keychain: UnauthenticatedKeychain()).build()
let login = Login(registrationNumber: 42, username: "Some Guy", password: "p455w0rd")
let loginRequest = APIRequests.Login(registrationNumber: 42, username: "Some Guy", password: "p455w0rd")
let user = AuthenticatedUser(
userIdentifier: 42,
username: "Some Guy",
token: "Token",
tokenExpires: .distantFuture
)
let logoutRequest = APIRequests.Logout(pushNotificationDeviceToken: nil)
let (received, read) = (Date(), Date())
let messages = [
EurofurenceWebAPI.Message(
id: "Identifier",
author: "Author",
subject: "Subject",
message: "Message",
receivedDate: received,
readDate: read
)
]
scenario.api.stub(request: loginRequest, with: .success(user))
scenario.api.stub(
request: APIRequests.FetchMessages(authenticationToken: AuthenticationToken("Token")),
with: .success(messages)
)
scenario.api.stub(request: logoutRequest, with: .success(()))
try await scenario.model.signIn(with: login)
try await scenario.model.signOut()
XCTAssertThrowsSpecificError(
EurofurenceError.invalidMessage("Identifier"),
try scenario.model.message(identifiedBy: "Identifier")
)
}
func testWhenSignedInFutureReloadsIncludeMessages() async throws {
let scenario = await EurofurenceModelTestBuilder().with(keychain: UnauthenticatedKeychain()).build()
let login = Login(registrationNumber: 42, username: "Some Guy", password: "p455w0rd")
let loginRequest = APIRequests.Login(registrationNumber: 42, username: "Some Guy", password: "p455w0rd")
let user = AuthenticatedUser(
userIdentifier: 42,
username: "Some Guy",
token: "Token",
tokenExpires: .distantFuture
)
scenario.api.stub(request: loginRequest, with: .success(user))
try await scenario.model.signIn(with: login)
// The next update should include a fetch for messages now we are authenticated.
let (received, read) = (Date(), Date())
let message = EurofurenceWebAPI.Message(
id: "Identifier",
author: "Author",
subject: "Subject",
message: "Message",
receivedDate: received,
readDate: read
)
scenario.api.stub(
request: APIRequests.FetchMessages(authenticationToken: AuthenticationToken("Token")),
with: .success([message])
)
try await scenario.updateLocalStore(using: .ef26)
let entity = try scenario.model.message(identifiedBy: "Identifier")
message.assert(against: entity)
}
func testLoadingSameMessageMultipleTimesDoesNotDuplicateMessageInContext() async throws {
let scenario = await EurofurenceModelTestBuilder().with(keychain: UnauthenticatedKeychain()).build()
let login = Login(registrationNumber: 42, username: "Some Guy", password: "p455w0rd")
let loginRequest = APIRequests.Login(registrationNumber: 42, username: "Some Guy", password: "p455w0rd")
let user = AuthenticatedUser(
userIdentifier: 42,
username: "Some Guy",
token: "Token",
tokenExpires: .distantFuture
)
let (received, read) = (Date(), Date())
let message = EurofurenceWebAPI.Message(
id: "Identifier",
author: "Author",
subject: "Subject",
message: "Message",
receivedDate: received,
readDate: read
)
scenario.api.stub(
request: APIRequests.FetchMessages(authenticationToken: AuthenticationToken("Token")),
with: .success([message])
)
scenario.api.stub(request: loginRequest, with: .success(user))
try await scenario.model.signIn(with: login)
// The message already exists in the persistent store - there should only be one instance when fetching again.
try await scenario.updateLocalStore(using: .ef26)
let fetchRequest: NSFetchRequest<EurofurenceKit.Message> = EurofurenceKit.Message.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "identifier == %@", "Identifier")
fetchRequest.resultType = .countResultType
let count = try scenario.viewContext.count(for: fetchRequest)
XCTAssertEqual(1, count, "Only one instance of a message should exist in the store, based on its ID")
}
func testSignedIn_CredentialExpiresMidSession_DoesNotRequestMessagesDuringNextRefresh() async throws {
let keychain = AuthenticatedKeychain()
let scenario = await EurofurenceModelTestBuilder().with(keychain: keychain).build()
var expiredCredental = try XCTUnwrap(keychain.credential)
expiredCredental.tokenExpiryDate = .distantPast
keychain.credential = expiredCredental
let error = NSError(domain: NSURLErrorDomain, code: URLError.badServerResponse.rawValue)
scenario.api.stub(
request: APIRequests.FetchMessages(authenticationToken: expiredCredental.authenticationToken),
with: .failure(error)
)
// The update should not fail as we should not attempt to request messages with an invalid token.
await XCTAssertEventuallyNoThrows { try await scenario.updateLocalStore(using: .ef26) }
}
func testWhenSignedInAndCredentialIsNoLongerValid_MessagesAreRemovedFromContext() async throws {
let keychain = AuthenticatedKeychain()
let scenario = await EurofurenceModelTestBuilder().with(keychain: keychain).build()
let (received, read) = (Date(), Date())
let message = EurofurenceWebAPI.Message(
id: "Identifier",
author: "Author",
subject: "Subject",
message: "Message",
receivedDate: received,
readDate: read
)
var credental = try XCTUnwrap(keychain.credential)
scenario.api.stub(
request: APIRequests.FetchMessages(authenticationToken: AuthenticationToken("ABC")),
with: .success([message])
)
let payload = try SampleResponse.ef26.loadResponse()
await scenario.stubSyncResponse(with: .success(payload))
await XCTAssertEventuallyNoThrows { try await scenario.updateLocalStore() }
credental.tokenExpiryDate = .distantPast
keychain.credential = credental
let noChanges = try SampleResponse.noChanges.loadResponse()
await scenario.stubSyncResponse(with: .success(noChanges), for: payload.synchronizationToken)
await XCTAssertEventuallyNoThrows { try await scenario.updateLocalStore() }
let fetchRequest: NSFetchRequest<EurofurenceKit.Message> = EurofurenceKit.Message.fetchRequest()
fetchRequest.predicate = NSPredicate(value: true)
fetchRequest.resultType = .countResultType
let count = try scenario.viewContext.count(for: fetchRequest)
XCTAssertEqual(0, count, "Messages should be removed from the persistent store on next refresh after sign-out")
}
}
| mit | 85af676e1f141b6a3015dd9a32c4ff21 | 41.156522 | 119 | 0.623247 | 5.404682 | false | true | false | false |
Demoxica/HackingWithSwift | project9/Project7/SwiftyJSON.swift | 40 | 35402 | // SwiftyJSON.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// 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
// MARK: - Error
///Error domain
public let ErrorDomain: String! = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int! = 999
public let ErrorIndexOutOfBounds: Int! = 900
public let ErrorWrongType: Int! = 901
public let ErrorNotExist: Int! = 500
// MARK: - JSON Type
/**
JSON's type definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Type :Int{
case Number
case String
case Bool
case Array
case Dictionary
case Null
case Unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
:param: data The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
:param: opt The JSON serialization reading options. `.AllowFragments` by default.
:param: error error The NSErrorPointer used to return the error. `nil` by default.
:returns: The created JSON
*/
public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
if let object: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: opt, error: error) {
self.init(object)
} else {
self.init(NSNull())
}
}
/**
Creates a JSON using the object.
:param: object The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
:returns: The created JSON
*/
public init(_ object: AnyObject) {
self.object = object
}
/// Private object
private var _object: AnyObject = NSNull()
/// Private type
private var _type: Type = .Null
/// prviate error
private var _error: NSError?
/// Object in JSON
public var object: AnyObject {
get {
return _object
}
set {
_object = newValue
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .Bool
} else {
_type = .Number
}
case let string as NSString:
_type = .String
case let null as NSNull:
_type = .Null
case let array as [AnyObject]:
_type = .Array
case let dictionary as [String : AnyObject]:
_type = .Dictionary
default:
_type = .Unknown
_object = NSNull()
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// json type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null json
public static var nullJSON: JSON { get { return JSON(NSNull()) } }
}
// MARK: - SequenceType
extension JSON: SequenceType{
/// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`.
var isEmpty: Bool {
get {
switch self.type {
case .Array:
return (self.object as! [AnyObject]).isEmpty
case .Dictionary:
return (self.object as! [String : AnyObject]).isEmpty
default:
return false
}
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
public var count: Int {
get {
switch self.type {
case .Array:
return self.arrayValue.count
case .Dictionary:
return self.dictionaryValue.count
default:
return 0
}
}
}
/**
If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary, otherwise return a generator over empty.
:returns: Return a *generator* over the elements of this *sequence*.
*/
public func generate() -> GeneratorOf <(String, JSON)> {
switch self.type {
case .Array:
let array_ = object as! [AnyObject]
var generate_ = array_.generate()
var index_: Int = 0
return GeneratorOf<(String, JSON)> {
if let element_: AnyObject = generate_.next() {
return ("\(index_++)", JSON(element_))
} else {
return nil
}
}
case .Dictionary:
let dictionary_ = object as! [String : AnyObject]
var generate_ = dictionary_.generate()
return GeneratorOf<(String, JSON)> {
if let (key_: String, value_: AnyObject) = generate_.next() {
return (key_, JSON(value_))
} else {
return nil
}
}
default:
return GeneratorOf<(String, JSON)> {
return nil
}
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public protocol SubscriptType {}
extension Int: SubscriptType {}
extension String: SubscriptType {}
extension JSON {
/// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error.
private subscript(#index: Int) -> JSON {
get {
if self.type != .Array {
var errorResult_ = JSON.nullJSON
errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return errorResult_
}
let array_ = self.object as! [AnyObject]
if index >= 0 && index < array_.count {
return JSON(array_[index])
}
var errorResult_ = JSON.nullJSON
errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return errorResult_
}
set {
if self.type == .Array {
var array_ = self.object as! [AnyObject]
if array_.count > index {
array_[index] = newValue.object
self.object = array_
}
}
}
}
/// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error.
private subscript(#key: String) -> JSON {
get {
var returnJSON = JSON.nullJSON
if self.type == .Dictionary {
if let object_: AnyObject = self.object[key] {
returnJSON = JSON(object_)
} else {
returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return returnJSON
}
set {
if self.type == .Dictionary {
var dictionary_ = self.object as! [String : AnyObject]
dictionary_[key] = newValue.object
self.object = dictionary_
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
private subscript(#sub: SubscriptType) -> JSON {
get {
if sub is String {
return self[key:sub as! String]
} else {
return self[index:sub as! Int]
}
}
set {
if sub is String {
self[key:sub as! String] = newValue
} else {
self[index:sub as! Int] = newValue
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
:param: path The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
:returns: Return a json found by the path or a null json with error
*/
public subscript(path: [SubscriptType]) -> JSON {
get {
if path.count == 0 {
return JSON.nullJSON
}
var next = self
for sub in path {
next = next[sub:sub]
}
return next
}
set {
switch path.count {
case 0: return
case 1: self[sub:path[0]] = newValue
default:
var last = newValue
var newPath = path
newPath.removeLast()
for sub in path.reverse() {
var previousLast = self[newPath]
previousLast[sub:sub] = last
last = previousLast
if newPath.count <= 1 {
break
}
newPath.removeLast()
}
self[sub:newPath[0]] = last
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
:param: path The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
:returns: Return a json found by the path or a null json with error
*/
public subscript(path: SubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, AnyObject)...) {
var dictionary_ = [String : AnyObject]()
for (key_, value) in elements {
dictionary_[key_] = value
}
self.init(dictionary_)
}
}
extension JSON: ArrayLiteralConvertible {
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
}
extension JSON: NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
// MARK: - Raw
extension JSON: RawRepresentable {
public init?(rawValue: AnyObject) {
if JSON(rawValue).type == .Unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: AnyObject {
return self.object
}
public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(0), error: NSErrorPointer = nil) -> NSData? {
return NSJSONSerialization.dataWithJSONObject(self.object, options: opt, error:error)
}
public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
switch self.type {
case .Array, .Dictionary:
if let data = self.rawData(options: opt) {
return NSString(data: data, encoding: encoding) as String?
} else {
return nil
}
case .String:
return (self.object as! String)
case .Number:
return (self.object as! NSNumber).stringValue
case .Bool:
return (self.object as! Bool).description
case .Null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Printable, DebugPrintable {
public var description: String {
if let string = self.rawString(options:.PrettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .Array {
return map(self.object as! [AnyObject]){ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [AnyObject]
public var arrayObject: [AnyObject]? {
get {
switch self.type {
case .Array:
return self.object as? [AnyObject]
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSMutableArray(array: newValue!, copyItems: true)
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] {
var result = [Key: NewValue](minimumCapacity:source.count)
for (key,value) in source {
result[key] = transform(value)
}
return result
}
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
get {
if self.type == .Dictionary {
return _map(self.object as! [String : AnyObject]){ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
get {
return self.dictionary ?? [:]
}
}
//Optional [String : AnyObject]
public var dictionaryObject: [String : AnyObject]? {
get {
switch self.type {
case .Dictionary:
return self.object as? [String : AnyObject]
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true)
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON: BooleanType {
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .Bool:
return self.object.boolValue
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSNumber(bool: newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .Bool, .Number, .String:
return self.object.boolValue
default:
return false
}
}
set {
self.object = NSNumber(bool: newValue)
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .String:
return self.object as? String
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSString(string:newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .String:
return self.object as! String
case .Number:
return self.object.stringValue
case .Bool:
return (self.object as! Bool).description
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .Number, .Bool:
return self.object as? NSNumber
default:
return nil
}
}
set {
self.object = newValue?.copy() ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .String:
let scanner = NSScanner(string: self.object as! String)
if scanner.scanDouble(nil){
if (scanner.atEnd) {
return NSNumber(double:(self.object as! NSString).doubleValue)
}
}
return NSNumber(double: 0.0)
case .Number, .Bool:
return self.object as! NSNumber
default:
return NSNumber(double: 0.0)
}
}
set {
self.object = newValue.copy()
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .Null:
return NSNull()
default:
return nil
}
}
set {
self.object = NSNull()
}
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: NSURL? {
get {
switch self.type {
case .String:
if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
return NSURL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if newValue != nil {
self.object = NSNumber(double: newValue!)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(double: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if newValue != nil {
self.object = NSNumber(float: newValue!)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(float: newValue)
}
}
public var int: Int? {
get {
return self.number?.longValue
}
set {
if newValue != nil {
self.object = NSNumber(integer: newValue!)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.integerValue
}
set {
self.object = NSNumber(integer: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.unsignedLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.unsignedLongValue
}
set {
self.object = NSNumber(unsignedLong: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.charValue
}
set {
if newValue != nil {
self.object = NSNumber(char: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.charValue
}
set {
self.object = NSNumber(char: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.unsignedCharValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedChar: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.unsignedCharValue
}
set {
self.object = NSNumber(unsignedChar: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.shortValue
}
set {
if newValue != nil {
self.object = NSNumber(short: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.shortValue
}
set {
self.object = NSNumber(short: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.unsignedShortValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedShort: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.unsignedShortValue
}
set {
self.object = NSNumber(unsignedShort: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.intValue
}
set {
if newValue != nil {
self.object = NSNumber(int: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(int: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.unsignedIntValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedInt: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.unsignedIntValue
}
set {
self.object = NSNumber(unsignedInt: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.longLongValue
}
set {
if newValue != nil {
self.object = NSNumber(longLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.longLongValue
}
set {
self.object = NSNumber(longLong: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.unsignedLongLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLongLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.unsignedLongLongValue
}
set {
self.object = NSNumber(unsignedLongLong: newValue)
}
}
}
//MARK: - Comparable
extension JSON: Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) == (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) == (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as! Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as! NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) <= (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as! Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as! NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) >= (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as! Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as! NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) > (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) > (rhs.object as! String)
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) < (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) < (rhs.object as! String)
default:
return false
}
}
private let trueNumber = NSNumber(bool: true)
private let falseNumber = NSNumber(bool: false)
private let trueObjCType = String.fromCString(trueNumber.objCType)
private let falseObjCType = String.fromCString(falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber: Comparable {
var isBool:Bool {
get {
let objCType = String.fromCString(self.objCType)
if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
}
public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(rhs == rhs)
}
public func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}
}
public func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}
}
public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
}
}
public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
}
}
//MARK:- Unavailable
@availability(*, unavailable, renamed="JSON")
public typealias JSONValue = JSON
extension JSON {
@availability(*, unavailable, message="use 'init(_ object:AnyObject)' instead")
public init(object: AnyObject) {
self = JSON(object)
}
@availability(*, unavailable, renamed="dictionaryObject")
public var dictionaryObjects: [String : AnyObject]? {
get { return self.dictionaryObject }
}
@availability(*, unavailable, renamed="arrayObject")
public var arrayObjects: [AnyObject]? {
get { return self.arrayObject }
}
@availability(*, unavailable, renamed="int8")
public var char: Int8? {
get {
return self.number?.charValue
}
}
@availability(*, unavailable, renamed="int8Value")
public var charValue: Int8 {
get {
return self.numberValue.charValue
}
}
@availability(*, unavailable, renamed="uInt8")
public var unsignedChar: UInt8? {
get{
return self.number?.unsignedCharValue
}
}
@availability(*, unavailable, renamed="uInt8Value")
public var unsignedCharValue: UInt8 {
get{
return self.numberValue.unsignedCharValue
}
}
@availability(*, unavailable, renamed="int16")
public var short: Int16? {
get{
return self.number?.shortValue
}
}
@availability(*, unavailable, renamed="int16Value")
public var shortValue: Int16 {
get{
return self.numberValue.shortValue
}
}
@availability(*, unavailable, renamed="uInt16")
public var unsignedShort: UInt16? {
get{
return self.number?.unsignedShortValue
}
}
@availability(*, unavailable, renamed="uInt16Value")
public var unsignedShortValue: UInt16 {
get{
return self.numberValue.unsignedShortValue
}
}
@availability(*, unavailable, renamed="int")
public var long: Int? {
get{
return self.number?.longValue
}
}
@availability(*, unavailable, renamed="intValue")
public var longValue: Int {
get{
return self.numberValue.longValue
}
}
@availability(*, unavailable, renamed="uInt")
public var unsignedLong: UInt? {
get{
return self.number?.unsignedLongValue
}
}
@availability(*, unavailable, renamed="uIntValue")
public var unsignedLongValue: UInt {
get{
return self.numberValue.unsignedLongValue
}
}
@availability(*, unavailable, renamed="int64")
public var longLong: Int64? {
get{
return self.number?.longLongValue
}
}
@availability(*, unavailable, renamed="int64Value")
public var longLongValue: Int64 {
get{
return self.numberValue.longLongValue
}
}
@availability(*, unavailable, renamed="uInt64")
public var unsignedLongLong: UInt64? {
get{
return self.number?.unsignedLongLongValue
}
}
@availability(*, unavailable, renamed="uInt64Value")
public var unsignedLongLongValue: UInt64 {
get{
return self.numberValue.unsignedLongLongValue
}
}
@availability(*, unavailable, renamed="int")
public var integer: Int? {
get {
return self.number?.integerValue
}
}
@availability(*, unavailable, renamed="intValue")
public var integerValue: Int {
get {
return self.numberValue.integerValue
}
}
@availability(*, unavailable, renamed="uInt")
public var unsignedInteger: Int? {
get {
return self.number?.unsignedIntegerValue
}
}
@availability(*, unavailable, renamed="uIntValue")
public var unsignedIntegerValue: Int {
get {
return self.numberValue.unsignedIntegerValue
}
}
}
| unlicense | c9e44bcedea3d79a06cb32fb75f0a6d3 | 25.518352 | 259 | 0.527682 | 4.720267 | false | false | false | false |
brave/browser-ios | Client/Frontend/Browser/Punycode.swift | 2 | 6080 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
private let base = 36
private let tMin = 1
private let tMax = 26
private let initialBias = 72
private let initialN: Int = 128 // 0x80
private let delimiter: Character = "-"; // '\x2D'
private let prefixPunycode = "xn--"
private let asciiPunycode = [Character]("abcdefghijklmnopqrstuvwxyz0123456789".characters)
extension String {
fileprivate func toValue(_ index: Int) -> Character {
return asciiPunycode[index]
}
fileprivate func toIndex(_ value: Character) -> Int {
return asciiPunycode.index(of: value)!
}
fileprivate func adapt(_ delta: Int, numPoints: Int, firstTime: Bool) -> Int {
let skew = 38
let damp = firstTime ? 700 : 2
var delta = delta
delta = delta / damp
delta += delta / numPoints
var k = 0
while (delta > ((base - tMin) * tMax) / 2) {
delta /= (base - tMin)
k += base
}
return k + ((base - tMin + 1) * delta) / (delta + skew)
}
fileprivate func encode(_ input: String) -> String {
var output = ""
var d: Int = 0
var extendedChars = [Int]()
for c in input.unicodeScalars {
if Int(c.value) < initialN {
d += 1
output.append(String(c))
} else {
extendedChars.append(Int(c.value))
}
}
if extendedChars.count == 0 {
return output
}
if d > 0 {
output.append(delimiter)
}
var n = initialN
var delta = 0
var bias = initialBias
var h: Int = 0
var b: Int = 0
if d > 0 {
h = output.unicodeScalars.count - 1
b = output.unicodeScalars.count - 1
} else {
h = output.unicodeScalars.count
b = output.unicodeScalars.count
}
while h < input.unicodeScalars.count {
var char = Int(0x7fffffff)
for c in input.unicodeScalars {
let ci = Int(c.value)
if char > ci && ci >= n {
char = ci
}
}
delta = delta + (char - n) * (h + 1)
if delta < 0 {
print("error: invalid char:")
output = ""
return output
}
n = char
for c in input.unicodeScalars {
let ci = Int(c.value)
if ci < n || ci < initialN {
delta += 1
continue
}
if ci > n {
continue
}
var q = delta
var k = base
while true {
let t = max(min(k - bias, tMax), tMin)
if q < t {
break
}
let code = t + ((q - t) % (base - t))
output.append(toValue(code))
q = (q - t) / (base - t)
k += base
}
output.append(toValue(q))
bias = self.adapt(delta, numPoints: h + 1, firstTime: h == b)
delta = 0
h += 1
}
delta += 1
n += 1
}
return output
}
fileprivate func decode(_ punycode: String) -> String {
var input = [Character](punycode.characters)
var output = [Character]()
var i = 0
var n = initialN
var bias = initialBias
var pos = 0
if let ipos = input.index(of: delimiter) {
pos = ipos
output.append(contentsOf: input[0 ..< pos])
pos += 1
}
var outputLength = output.count
let inputLength = input.count
while pos < inputLength {
let oldi = i
var w = 1
var k = base
while true {
let digit = toIndex(input[pos])
pos += 1
i += digit * w
let t = max(min(k - bias, tMax), tMin)
if digit < t {
break
}
w = w * (base - t)
k += base
}
outputLength += 1
bias = adapt(i - oldi, numPoints: outputLength, firstTime: (oldi == 0))
n = n + i / outputLength
i = i % outputLength
output.insert(Character(UnicodeScalar(n)!), at: i)
i += 1
}
return String(output)
}
fileprivate func isValidUnicodeScala(_ s: String) -> Bool {
for c in s.unicodeScalars {
let ci = Int(c.value)
if ci >= initialN {
return false
}
}
return true
}
fileprivate func isValidPunycodeScala(_ s: String) -> Bool {
return s.hasPrefix(prefixPunycode)
}
public func utf8HostToAscii() -> String {
if isValidUnicodeScala(self) {
return self
}
var labels = self.components(separatedBy: ".")
for (i, part) in labels.enumerated() {
if !isValidUnicodeScala(part) {
let a = encode(part)
labels[i] = prefixPunycode + a
}
}
let resultString = labels.joined(separator: ".")
return resultString
}
public func asciiHostToUTF8() -> String {
var labels = self.components(separatedBy: ".")
for (index, part) in labels.enumerated() {
if isValidPunycodeScala(part) {
let changeStr = part.substring(from: part.characters.index(part.startIndex, offsetBy: 4))
labels[index] = decode(changeStr)
}
}
let resultString = labels.joined(separator: ".")
return resultString
}
}
| mpl-2.0 | 2985b21bb59427d188d3bf9637b2b749 | 29.707071 | 105 | 0.467105 | 4.595616 | false | false | false | false |
material-components/material-components-ios | components/NavigationDrawer/examples/BottomDrawerNoHeaderLessContentExample.swift | 2 | 3745 | // Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import MaterialComponents.MaterialBottomAppBar
import MaterialComponents.MaterialNavigationDrawer
import MaterialComponents.MaterialColorScheme
class BottomDrawerNoHeaderLessContentExample: UIViewController {
@objc var colorScheme = MDCSemanticColorScheme(defaults: .material201804)
let bottomAppBar = MDCBottomAppBarView()
let contentViewController = DrawerContentViewController()
let bottomDrawerTransitionController = MDCBottomDrawerTransitionController()
override func viewDidLoad() {
super.viewDidLoad()
contentViewController.preferredHeight = UIScreen.main.bounds.size.height
view.backgroundColor = colorScheme.backgroundColor
contentViewController.view.backgroundColor = colorScheme.primaryColor
bottomAppBar.isFloatingButtonHidden = true
let barButtonLeadingItem = UIBarButtonItem()
let menuImage = UIImage(named: "system_icons/menu")?.withRenderingMode(.alwaysTemplate)
barButtonLeadingItem.image = menuImage
barButtonLeadingItem.target = self
barButtonLeadingItem.action = #selector(presentNavigationDrawer)
bottomAppBar.leadingBarButtonItems = [barButtonLeadingItem]
bottomAppBar.barTintColor = colorScheme.surfaceColor
let barItemTintColor = colorScheme.onSurfaceColor.withAlphaComponent(0.6)
bottomAppBar.leadingBarItemsTintColor = barItemTintColor
bottomAppBar.trailingBarItemsTintColor = barItemTintColor
bottomAppBar.floatingButton.setBackgroundColor(colorScheme.primaryColor, for: .normal)
bottomAppBar.floatingButton.setTitleColor(colorScheme.onPrimaryColor, for: .normal)
bottomAppBar.floatingButton.setImageTintColor(colorScheme.onPrimaryColor, for: .normal)
view.addSubview(bottomAppBar)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
layoutBottomAppBar()
}
private func layoutBottomAppBar() {
let size = bottomAppBar.sizeThatFits(view.bounds.size)
var bottomBarViewFrame = CGRect(
x: 0,
y: view.bounds.size.height - size.height,
width: size.width,
height: size.height)
bottomBarViewFrame.size.height += view.safeAreaInsets.bottom
bottomBarViewFrame.origin.y -= view.safeAreaInsets.bottom
bottomAppBar.frame = bottomBarViewFrame
}
@objc func presentNavigationDrawer() {
// This shows that it is possible to present the content view controller directly without
// the need of the MDCBottomDrawerViewController wrapper. To present the view controller
// inside the drawer, both the transition controller and the custom presentation controller
// of the drawer need to be set.
contentViewController.transitioningDelegate = bottomDrawerTransitionController
contentViewController.modalPresentationStyle = .custom
present(contentViewController, animated: true, completion: nil)
}
}
extension BottomDrawerNoHeaderLessContentExample {
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["Navigation Drawer", "Bottom Drawer No Header Less Content"],
"primaryDemo": false,
"presentable": false,
]
}
}
| apache-2.0 | be5e1404c12d038a54c797836ef6a5df | 39.268817 | 95 | 0.778905 | 5.186981 | false | false | false | false |
cloudinary/cloudinary_ios | Example/Tests/TransformationTests/CLDVariableTests/CLDVariableTests.swift | 1 | 12879 | //
// CLDTransformationTests.swift
//
//
// 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.
//
@testable import Cloudinary
import Foundation
import XCTest
class CLDVariableTests: BaseTestCase {
var sut : CLDVariable!
// MARK: - setup and teardown
override func setUp() {
super.setUp()
}
override func tearDown() {
sut = nil
super.tearDown()
}
// MARK: - test initilization methods - empty
func test_init_emptyInputParamaters_shouldStoreEmptyProperties() {
// Given
let name = String()
// When
sut = CLDVariable()
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should contain a valid prefix")
XCTAssertEqual(sut.value, String(), "Initilized object should contain an empty string as value property")
XCTAssertNotEqual(sut.name , name, "Name property should contain \"\(CLDVariable.variableNamePrefix)\" prefix")
}
// MARK: - test initilization methods - value
func test_init_emptyNameParamater_shouldStoreEmptyNameProperty() {
// Given
let name = String()
let value = "alue"
// When
sut = CLDVariable(name: name, value: value)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, value, "Initilized object should contain an empty string as value property")
}
func test_init_validStringParamatersAndNoNamePrefix_shouldStoreValidProperties() {
// Given
let name = "name"
let value = "alue"
// When
sut = CLDVariable(name: name, value: value)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, value, "Initilized object should contain a string as value property")
}
func test_init_validStringParamaters_shouldStoreValidProperties() {
// Given
let name = "$foo"
let value = "alue"
// When
sut = CLDVariable(name: name, value: value)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, value, "Initilized object should contain a string as value property")
}
func test_init_emptyNameParamaterIntValue_shouldStoreEmptyNameProperty() {
// Given
let name = String()
let value = 4
// When
sut = CLDVariable(name: name, value: value)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, String(value), "Initilized object should contain a string as value property")
}
func test_init_validIntValue_shouldStoreValidProperties() {
// Given
let name = "name"
let value = 4
// When
sut = CLDVariable(name: name, value: value)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, String(value), "Initilized object should contain a string as value property")
}
func test_init_emptyNameParamaterDoubleValue_shouldStoreEmptyNameProperty() {
// Given
let name = String()
let value = 3.14
// When
sut = CLDVariable(name: name, value: value)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, String(value), "Initilized object should contain a string as value property")
}
func test_init_validDoubleValue_shouldStoreValidProperties() {
// Given
let name = "name"
let value = 3.14
// When
sut = CLDVariable(name: name, value: value)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, String(value), "Initilized object should contain a string as value property")
}
// MARK: - test initilization methods - values
func test_initWithValuesArray_emptyInputParamaters_shouldStoreEmptyProperties() {
// Given
let name = String()
let values = [String]()
// When
sut = CLDVariable(name: name, values: values)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name, CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, String(), "Initilized object should contain an empty string as value property")
}
func test_initWithValuesArray_emptyValueParamater_shouldStoreEmptyValueProperty() {
// Given
let name = "name"
let values = [String]()
// When
sut = CLDVariable(name: name, values: values)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, String(), "Initilized object should contain an empty string as value property")
}
func test_initWithValuesArray_validOneValueArray_shouldStoreValidProperties() {
// Given
let name = "foo"
let values = ["my"]
let expectedResult = "!my!"
// When
sut = CLDVariable(name: name, values: values)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, expectedResult, "Initilized object should contain an encoded string as value property")
}
func test_initWithValuesArray_validTwoValuesArray_shouldStoreValidProperties() {
// Given
let name = "foo"
let values = ["my","str"]
let expectedResult = "!my:str!"
// When
sut = CLDVariable(name: name, values: values)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, expectedResult, "Initilized object should contain an encoded string as value property")
}
func test_initWithValuesArray_validThreeValuesArray_shouldStoreValidProperties() {
// Given
let name = "foo"
let values = ["my","str","ing"]
let expectedResult = "!my:str:ing!"
// When
sut = CLDVariable(name: name, values: values)
// Then
XCTAssertNotNil(sut.name , "Initilized object should contain a none nil name property")
XCTAssertNotNil(sut.value, "Initilized object should contain a none nil value property")
XCTAssertEqual(sut.name , CLDVariable.variableNamePrefix + name, "Name property should have a valid prefix")
XCTAssertEqual(sut.value, expectedResult, "Initilized object should contain an encoded string as value property")
}
// MARK: - test asString()
func test_asString_emptyInputParamaters_shouldReturnEmptyString() {
// Given
let name = String()
let value = String()
let expectedResult = String()
// When
sut = CLDVariable(name: name, value: value)
let actualResult = sut.asString()
// Then
XCTAssertEqual(actualResult, expectedResult, "Calling asString on an empty CLDVariable, should return an empty string")
}
func test_asString_validParamaters_shouldReturnValidString() {
// Given
let name = "$foo"
let value = "bar"
let expectedResult = "$foo_bar"
// When
sut = CLDVariable(name: name, value: value)
let actualResult = sut.asString()
// Then
XCTAssertEqual(actualResult, expectedResult, "Calling asString on a CLDVariable, should return a string")
}
// MARK: - test asParams()
func test_asParams_emptyInputParamaters_shouldReturnEmptyString() {
// Given
let name = String()
let value = String()
let expectedResult = [String:String]()
// When
sut = CLDVariable(name: name, value: value)
let actualResult = sut.asParams()
// Then
XCTAssertEqual(actualResult, expectedResult, "Calling asParams, should build a paramater representation")
}
func test_asParams_validParamaters_shouldReturnValidString() {
// Given
let name = "foo"
let values = ["my","str","ing"]
let expectedResult = ["$foo":"!my:str:ing!"]
// When
sut = CLDVariable(name: name, values: values)
let actualResult = sut.asParams()
// Then
XCTAssertEqual(actualResult, expectedResult, "Calling asParams, should build a paramater representation")
}
}
| mit | ee7d0879bbc3be3e2099917c25c693f9 | 39.121495 | 127 | 0.640267 | 5.178528 | false | true | false | false |
xuanyi0627/jetstream-ios | Jetstream/Logging.swift | 1 | 4674 | //
// Logging.swift
// Jetstream
//
// Copyright (c) 2014 Uber Technologies, Inc.
//
// 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
let disabledLoggers = [String: Bool]()
public enum LogLevel: String {
case Trace = "TRACE"
case Debug = "DEBUG"
case Info = "INFO"
case Warning = "WARN"
case Error = "ERROR"
}
/// Jetstreams logging class. To subscribe to logging events from Jetstream, subscribe to the
/// Logging.onMessage - signal.
public class Logging {
struct Static {
static let baseLoggerName = "Jetstream"
static var enabled = false
static var consoleEnabled = true
static var loggers = [String: Logger]()
static let onMessage = Signal<(level: LogLevel, message: String)>()
}
class var logger: Logger {
get {
if let logger = Static.loggers[Static.baseLoggerName] {
return logger
}
let logger = Logger(name: Static.baseLoggerName)
Static.loggers[Static.baseLoggerName] = logger
return logger
}
}
public class func loggerFor(str: String) -> Logger {
let loggerName = "\(Static.baseLoggerName).\(str)"
var logger = Static.loggers[loggerName]
if logger == nil {
logger = Logger(name: loggerName)
Static.loggers[loggerName] = logger
}
if disabledLoggers[str] == true {
logger!.enabled = false
}
return logger!
}
/// A signal that is fired whenever Jetstream logs. The signal fires with the parameters LogLevel
/// and Message.
public class var onMessage: Signal<(level: LogLevel, message: String)> {
get {
return Static.onMessage
}
}
/// Enables all logging.
public class func enableAll() {
Static.enabled = true
}
/// Disables all logging.
public class func disableAll() {
Static.enabled = false
}
/// Enables logging to the console.
public class func enableConsole() {
Static.enabled = true
Static.consoleEnabled = true
}
/// Disables logging to the console
public class func disableConsole() {
Static.consoleEnabled = false
}
}
public class Logger {
let name: String
var enabled: Bool
init(name: String, enabled: Bool) {
self.name = name
self.enabled = enabled
}
convenience init(name: String) {
self.init(name: name, enabled: true)
}
public func trace<T>(message: T) {
if !Logging.Static.enabled || !enabled {
return
}
log(.Trace, message: message)
}
public func debug<T>(message: T) {
if !Logging.Static.enabled || !enabled {
return
}
log(.Debug, message: message)
}
public func info<T>(message: T) {
if !Logging.Static.enabled || !enabled {
return
}
log(.Info, message: message)
}
public func warn<T>(message: T) {
if !Logging.Static.enabled || !enabled {
return
}
log(.Warning, message: message)
}
public func error<T>(message: T) {
if !Logging.Static.enabled || !enabled {
return
}
log(.Error, message: message)
}
func log<T>(level: LogLevel, message: T) {
let str = "\(name): \(message)"
if Logging.Static.consoleEnabled {
println("\(level) \(str)")
}
Logging.Static.onMessage.fire((level: level, message: str))
}
}
| mit | 361999c359a4018c2a7fd17857b1d22d | 28.396226 | 101 | 0.60997 | 4.472727 | false | false | false | false |
steelwheels/Coconut | CoconutData/Test/ResourceTest/UTStorageData.swift | 1 | 4121 | //
// UTStorage.swift
// CoconutData
//
// Created by Tomoo Hamada on 2021/12/25.
//
import CoconutData
import Foundation
public func UTStorageData() -> Bool {
NSLog("*** UTStorageData")
let storage: CNStorage
switch loadStorage() {
case .success(let strg):
storage = strg
case .failure(let err):
CNLog(logLevel: .error, message: "Failed to load: \(err.toString())", atFunction: #function, inFile: #file)
return false
}
let res0 = testStorageArray(storage: storage)
let res1 = testStorageDictionary(storage: storage)
let res2 = testStorageSet(storage: storage)
let summary = res0 && res1 && res2
if summary {
NSLog("UTStorageData: OK")
} else {
NSLog("UTStorageData: Error")
}
return summary
}
private func loadStorage() -> Result<CNStorage, NSError> {
guard let srcfile = CNFilePath.URLForResourceFile(fileName: "data", fileExtension: "json", subdirectory: "Data", forClass: ViewController.self) else {
return .failure(NSError.fileError(message: "Failed to allocate source url"))
}
let cachefile = CNFilePath.URLForApplicationSupportFile(fileName: "data", fileExtension: "json", subdirectory: "Data")
let srcdir = srcfile.deletingLastPathComponent()
let cachedir = cachefile.deletingLastPathComponent()
let storage = CNStorage(sourceDirectory: srcdir, cacheDirectory: cachedir, filePath: "data.json")
switch storage.load() {
case .success(_):
return .success(storage)
case .failure(let err):
return .failure(NSError.fileError(message: "Failed to load storage: \(err.toString())"))
}
}
private func testStorageDictionary(storage strg: CNStorage) -> Bool {
var result = true
NSLog("* testStorageDictionary")
let vpath = CNValuePath(identifier: nil, elements: [.member("dict0")])
let dict0 = CNStorageDictionary(path: vpath, storage: strg)
var res0 = false
if let val = dict0.value(forKey: "a") {
if let num = val.toNumber() {
if num.intValue == 10 {
res0 = true
}
}
}
if res0 {
NSLog("value(a) ... OK")
} else {
NSLog("value(a) ... Error")
result = false
}
if dict0.set(value: .stringValue("Good morning"), forKey: "c") {
NSLog("set(c) ... OK")
} else {
NSLog("set(c) ... Error")
result = false
}
if strg.save() {
NSLog("save ... OK")
} else {
NSLog("save ... Error")
result = false
}
return result
}
private func testStorageArray(storage strg: CNStorage) -> Bool {
var result = true
NSLog("* testStorageArray")
let vpath = CNValuePath(identifier: nil, elements: [.member("array0")])
let arr0 = CNStorageArray(path: vpath, storage: strg)
dump(storageArray: arr0)
if !arr0.append(value: .numberValue(NSNumber(integerLiteral: 3))) {
NSLog("Failed to append")
result = false
}
if !arr0.set(value: .numberValue(NSNumber(integerLiteral: 4)), at: 0) {
NSLog("Failed to set")
result = false
}
dump(storageArray: arr0)
return result
}
private func testStorageSet(storage strg: CNStorage) -> Bool {
var result = true
NSLog("* testStorageSet")
let vpath = CNValuePath(identifier: nil, elements: [.member("set0")])
let set0 = CNStorageSet(path: vpath, storage: strg)
dump(storageSet: set0)
NSLog("insert 4")
if !set0.insert(value: .numberValue(NSNumber(integerLiteral: 4))){
NSLog("Error: Failed to insert (0)")
result = false
}
dump(storageSet: set0)
NSLog("insert 2")
if !set0.insert(value: .numberValue(NSNumber(integerLiteral: 2))) {
NSLog("Error: Failed to insert (1)")
result = false
}
dump(storageSet: set0)
if set0.values.count != 4 {
NSLog("Error: Unexpected element count")
result = false
}
return result
}
private func dump(storageArray arr: CNStorageArray) {
NSLog("values = ")
let count = arr.values.count
var line: String = "["
for i in 0..<count {
if let val = arr.value(at: i) {
line += val.toText().toStrings().joined(separator: "\n") + " "
} else {
NSLog("Failed to access array")
}
}
line += "]"
NSLog("values in array = \(line)")
}
private func dump(storageSet sset: CNStorageSet) {
NSLog("values in set = ")
for val in sset.values {
let txt = val.toText().toStrings().joined(separator: "\n")
NSLog(" * \(txt)")
}
}
| lgpl-2.1 | e040ee83dfbc8aad56b992d049414c6f | 23.529762 | 151 | 0.681388 | 3.209502 | false | true | false | false |
kousun12/RxSwift | RxSwift/Observables/Implementations/Sample.swift | 8 | 3373 | //
// Sample.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/1/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class SamplerSink<O: ObserverType, ElementType, SampleType where O.E == ElementType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias E = SampleType
typealias Parent = SampleSequenceSink<O, SampleType>
private let _parent: Parent
var _lock: NSRecursiveLock {
return _parent._lock
}
init(parent: Parent) {
_parent = parent
}
func on(event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(event: Event<E>) {
switch event {
case .Next:
if let element = _parent._element {
if _parent._parent._onlyNew {
_parent._element = nil
}
_parent.forwardOn(.Next(element))
}
if _parent._atEnd {
_parent.forwardOn(.Completed)
_parent.dispose()
}
case .Error(let e):
_parent.forwardOn(.Error(e))
_parent.dispose()
case .Completed:
if let element = _parent._element {
_parent._element = nil
_parent.forwardOn(.Next(element))
}
if _parent._atEnd {
_parent.forwardOn(.Completed)
_parent.dispose()
}
}
}
}
class SampleSequenceSink<O: ObserverType, SampleType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = O.E
typealias Parent = Sample<Element, SampleType>
private let _parent: Parent
let _lock = NSRecursiveLock()
// state
private var _element = nil as Element?
private var _atEnd = false
private let _sourceSubscription = SingleAssignmentDisposable()
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func run() -> Disposable {
_sourceSubscription.disposable = _parent._source.subscribe(self)
let samplerSubscription = _parent._sampler.subscribe(SamplerSink(parent: self))
return StableCompositeDisposable.create(_sourceSubscription, samplerSubscription)
}
func on(event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(event: Event<Element>) {
switch event {
case .Next(let element):
_element = element
case .Error:
forwardOn(event)
dispose()
case .Completed:
_atEnd = true
_sourceSubscription.dispose()
}
}
}
class Sample<Element, SampleType> : Producer<Element> {
private let _source: Observable<Element>
private let _sampler: Observable<SampleType>
private let _onlyNew: Bool
init(source: Observable<Element>, sampler: Observable<SampleType>, onlyNew: Bool) {
_source = source
_sampler = sampler
_onlyNew = onlyNew
}
override func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable {
let sink = SampleSequenceSink(parent: self, observer: observer)
sink.disposable = sink.run()
return sink
}
} | mit | c7f1231da6be172f89d365021d042af8 | 25.155039 | 89 | 0.569819 | 4.77762 | false | false | false | false |
jakub-tucek/fit-checker-2.0 | fit-checker/networking/EduxRouter.swift | 1 | 2399 | //
// EduxRouter.swift
// fit-checker
//
// Created by Josef Dolezal on 13/01/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import Foundation
import Alamofire
/// Edux requests router.
enum EduxRouter {
/// Remote request configuration data
enum RequestData {
case multiEncoded(method: HTTPMethod, path: String, query: Parameters, body: Parameters)
case singleEncoded(method: HTTPMethod, path: String, parameters: Parameters?)
}
case login(query: Parameters, body: Parameters)
case courseClassification(courseId: String, student: String)
case courseList(query: Parameters, body: Parameters)
/// Edux site base URL
static let baseURLString = "https://edux.fit.cvut.cz/"
/// Returns route associated values as request configuration
var requestData: RequestData {
switch self {
case let .login(query, body):
return .multiEncoded(method: .post, path: "start", query: query, body: body)
case let .courseClassification(courseId, student):
return .singleEncoded(method: .get, path: "courses/\(courseId)/classification/student/\(student)/start", parameters: nil)
case let .courseList(query, body):
return .multiEncoded(method: .post, path: "lib/exe/ajax.php", query: query, body: body)
}
}
}
// MARK: - URLRequestConvertible
extension EduxRouter: URLRequestConvertible {
func asURLRequest() throws -> URLRequest {
let data = requestData
let url = try EduxRouter.baseURLString.asURL()
// As some requests requires both query string parameters and
// body parameters, we need to encoded parameters twice
switch data {
case .multiEncoded(let method, let path, let query, let body):
let urlRequest = URLRequest(url: url.appendingPathComponent(path))
var urlEncoded = try URLEncoding.queryString.encode(urlRequest, with: query)
urlEncoded.httpMethod = method.rawValue
return try URLEncoding.default.encode(urlEncoded, with: body)
case .singleEncoded(let method, let path, let parameters):
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
return try URLEncoding.default.encode(urlRequest, with: parameters)
}
}
}
| mit | 80fe59b56b5be7b6b4c9b921c0cbb138 | 34.791045 | 133 | 0.671393 | 4.66537 | false | false | false | false |
victorchee/Live | Live/RTMP/RTMPConnector.swift | 1 | 4241 | //
// RTMPConnector.swift
// RTMP
//
// Created by VictorChee on 2016/12/22.
// Copyright © 2016年 VictorChee. All rights reserved.
//
import Foundation
class RTMPConnector {
var socket: RTMPSocket!
var messageReceiver: RTMPReceiver!
init(socket: RTMPSocket) {
self.socket = socket
self.messageReceiver = RTMPReceiver(socket: socket)
}
/// 握手之后先发送一个AMF格式的connect命令消息
func connectApp() {
// connect命令的事务ID必须为1
let command = RTMPCommandMessage(commandName: "connect", transactionID: 0x01, messageStreamID: 0x00)
let object = Amf0Object()
object.setProperties(key: "app", value: socket.app)
object.setProperties(key: "flashVer", value: "FMLE/3.0 (compatible; FMSc/1.0)")
object.setProperties(key: "swfUrl", value: "")
object.setProperties(key: "tcUrl", value: socket.hostname+"/"+socket.app)
object.setProperties(key: "fpad", value: false);
object.setProperties(key: "capabilities", value: 239);
object.setProperties(key: "audioCodecs", value: 3575);
object.setProperties(key: "pageUrl", value: "");
object.setProperties(key: "objectEncoding", value: 0);
// 音视频编码信息不能少
object.setProperties(key: "videoCodecs", value: 252);
object.setProperties(key: "videoFunction", value: 1);
command.commandObjects.append(object)
socket.write(message: command, chunkType: RTMPChunk.ChunkType.zero, chunkStreamID: RTMPChunk.CommandChannel)
// 发送完connect命令之后一般会发一个set chunk size消息来设置chunk size的大小,也可以不发
// Set client out chunk size 1024*8
socket.outChunkSize = 1024 * 8
let setChunkSize = RTMPSetChunkSizeMessage(chunkSize: socket.outChunkSize)
socket.write(message: setChunkSize, chunkType: RTMPChunk.ChunkType.zero, chunkStreamID: RTMPChunk.ControlChannel)
if let message = messageReceiver.expectCommandMessage(transactionID: 0x01) {
if message.commandName == "_result" {
print("App connect success")
} else if message.commandName == "_error" {
print("App connect refused")
}
}
}
/// 创建RTMP流
/// 客户端要向服务器发送一个releaseStream命令消息,之后是FCPublish命令消息,在之后是createStream命令消息。当发送完createStream消息之后,解析服务器返回的消息会得到一个stream ID, 这个ID也就是以后和服务器通信的 message stream ID, 一般返回的是1,不固定
func createStream() {
let releaseStream = RTMPCommandMessage(commandName: "releaseStream", transactionID: 0x02, messageStreamID: 0)
releaseStream.commandObjects.append(Amf0Null())
releaseStream.commandObjects.append(Amf0String(value: socket.stream))
socket.write(message: releaseStream, chunkType: RTMPChunk.ChunkType.one, chunkStreamID: RTMPChunk.CommandChannel)
let FCPublish = RTMPCommandMessage(commandName: "FCPublish", transactionID: 0x03, messageStreamID: 0)
FCPublish.timestamp = 0
FCPublish.commandObjects.append(Amf0Null())
FCPublish.commandObjects.append(Amf0String(value: socket.stream))
socket.write(message: FCPublish, chunkType: RTMPChunk.ChunkType.one, chunkStreamID: RTMPChunk.CommandChannel)
let createStream = RTMPCommandMessage(commandName: "createStream", transactionID: 0x04, messageStreamID: 0)
createStream.timestamp = 0
createStream.commandObjects.append(Amf0Null())
socket.write(message: createStream, chunkType: RTMPChunk.ChunkType.one, chunkStreamID: RTMPChunk.CommandChannel)
guard let result = messageReceiver.expectCommandMessage(transactionID: 0x04) else {
// Error
return
}
guard let amf0Number = result.commandObjects[1] as? Amf0Number else {
// Error
return
}
RTMPStream.messageStreamID = UInt32(amf0Number.value)
print("Create stream success")
}
}
| mit | 61f9336607d86617b6e9131314340acc | 43.337079 | 170 | 0.67182 | 4.341034 | false | true | false | false |
codefirst/AsakusaSatelliteSwiftClient | Classes/Client.swift | 1 | 4416 | //
// Client.swift
//
//
// Created by BAN Jun on 2015/03/01.
//
//
import Foundation
import Alamofire
open class Client {
public let rootURL: String
var apiBaseURL: String { return rootURL.appendingFormat("api/v1") }
let apiKey: String?
public convenience init(apiKey: String?) {
self.init(rootURL: "https://asakusa-satellite.herokuapp.com/", apiKey: apiKey)
}
public init(rootURL: String, apiKey: String?) {
self.rootURL = rootURL
self.apiKey = apiKey
// remove all AasakusaSatellite cookies
// make sure AsakusaSatellite cause error result with invalid apiKey
removeCookies()
}
private func removeCookies() {
AsakusaSatellite.removeCookiesForURL(URL(string: rootURL)!)
}
// MARK: - public APIs
open func serviceInfo(_ completion: @escaping (Response<ServiceInfo>) -> Void) {
request(Endpoint.serviceInfo, completion: completion)
}
open func user(_ completion: @escaping (Response<User>) -> Void) {
request(Endpoint.user, completion: completion)
}
open func roomList(_ completion: @escaping (Response<[Room]>) -> Void) {
request(Endpoint.roomList, completion: completion)
}
open func postMessage(_ message: String, roomID: String, files: [String], completion: @escaping (Response<PostMessage>) -> Void) {
request(Endpoint.postMessage(message: message, roomID: roomID, files: files), completion: completion)
}
open func messageList(_ roomID: String, count: Int?, sinceID: String?, untilID: String?, order: SortOrder?, completion: @escaping (Response<[Message]>) -> Void) {
request(Endpoint.messageList(roomID: roomID, count: count, sinceID: sinceID, untilID: untilID, order: order), completion: completion)
}
open func addDevice(_ deviceToken: Data, name: String, completion: @escaping (Response<Nothing>) -> Void) {
request(Endpoint.addDevice(deviceToken: deviceToken, name: name), requestModifier: {$0.validate(statusCode: [200])}, completion: completion)
}
open func messagePusher(_ roomID: String, completion: @escaping ((MessagePusherClient?) -> Void)) {
serviceInfo { response in
switch response {
case .success(let serviceInfo):
if let engine = MessagePusherClient.Engine(messagePusher: serviceInfo.message_pusher) {
completion(MessagePusherClient(engine: engine, roomID: roomID))
} else {
completion(nil)
}
case .failure(_):
completion(nil)
}
}
}
// MARK: -
private func request<T: APIModel>(_ endpoint: Endpoint, requestModifier: ((DataRequest) -> DataRequest) = {$0}, completion: @escaping (Response<T>) -> Void) {
requestModifier(Alamofire.request(endpoint.URLRequest(apiBaseURL, apiKey: apiKey))).responseData { response in
switch response.result {
case .success(let value):
let json = try? JSONSerialization.jsonObject(with: value, options: .allowFragments)
let jsonArray = json as? [[String: Any]]
self.completeWithResponse(response.response, jsonArray.flatMap {try? JSONSerialization.data(withJSONObject: endpoint.modifyJSON($0), options: [])} ?? value, nil, completion: completion)
case .failure(let error):
NSLog("%@", "failure in Client.request(\(endpoint)): \(error)")
completion(.failure(error as NSError))
}
}
}
private func completeWithResponse<T: APIModel>(_ response: HTTPURLResponse?, _ json: Data, _ error: NSError?, completion: (Response<T>) -> Void) {
do {
let responseItem = try T.decoder.decode(T.self, from: json)
completion(Response.success(responseItem))
} catch {
NSLog("%@", "failure in completeWithResponse")
completion(.failure(error as NSError))
}
}
}
public enum Response<T> {
case success(T)
case failure(NSError?)
}
public enum SortOrder: String {
case Asc = "asc"
case Desc = "desc"
}
internal func removeCookiesForURL(_ URL: Foundation.URL) {
let cs = HTTPCookieStorage.shared
for cookie in cs.cookies(for: URL) ?? [] {
cs.deleteCookie(cookie)
}
}
| mit | 7c4285f170b51ef7a5bedb7f33e674c3 | 35.495868 | 201 | 0.624321 | 4.552577 | false | false | false | false |
longsirhero/DinDinShop | DinDinShopDemo/DinDinShopDemo/分类/Views/WCClassifyGoodsCell.swift | 1 | 1419 | //
// WCClassifyGoodsCell.swift
// DinDinShopDemo
//
// Created by longsirHERO on 2017/8/28.
// Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved.
//
import UIKit
class WCClassifyGoodsCell: UICollectionViewCell {
let imagV:UIImageView = UIImageView()
let titleLab:UILabel = UILabel()
var model:WCClassifyFiterModel = WCClassifyFiterModel() {
didSet {
imagV.kf.setImage(with: URL(string: model.logPath!))
titleLab.text = model.name
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = RGBA(r: 240, g: 240, b: 239, a: 1.0)
self.contentView.addSubview(imagV)
titleLab.font = k15Font
titleLab.textAlignment = .center
self.contentView.addSubview(titleLab)
imagV.snp.makeConstraints { (make) in
make.left.top.equalToSuperview().offset(2)
make.right.equalToSuperview().offset(-2)
make.bottom.equalTo(titleLab.snp.top).offset(0)
}
titleLab.snp.makeConstraints { (make) in
make.left.right.bottom.equalToSuperview()
make.height.equalTo(30)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | b7e56b84ee19ae2e9143dd2a8070055d | 26.230769 | 86 | 0.600282 | 4.140351 | false | false | false | false |
crescentflare/SmartMockServer | MockLibIOS/Example/Pods/AlamofireImage/Source/ImageCache.swift | 1 | 13811 | //
// ImageCache.swift
//
// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import Foundation
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
// MARK: ImageCache
/// The `ImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache.
public protocol ImageCache {
/// Adds the image to the cache with the given identifier.
func add(_ image: Image, withIdentifier identifier: String)
/// Removes the image from the cache matching the given identifier.
func removeImage(withIdentifier identifier: String) -> Bool
/// Removes all images stored in the cache.
@discardableResult
func removeAllImages() -> Bool
/// Returns the image in the cache associated with the given identifier.
func image(withIdentifier identifier: String) -> Image?
}
/// The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and
/// fetching images from a cache given an `URLRequest` and additional identifier.
public protocol ImageRequestCache: ImageCache {
/// Adds the image to the cache using an identifier created from the request and identifier.
func add(_ image: Image, for request: URLRequest, withIdentifier identifier: String?)
/// Removes the image from the cache using an identifier created from the request and identifier.
func removeImage(for request: URLRequest, withIdentifier identifier: String?) -> Bool
/// Returns the image from the cache associated with an identifier created from the request and identifier.
func image(for request: URLRequest, withIdentifier identifier: String?) -> Image?
}
// MARK: -
/// The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When
/// the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously
/// purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the
/// internal access date of the image is updated.
open class AutoPurgingImageCache: ImageRequestCache {
class CachedImage {
let image: Image
let identifier: String
let totalBytes: UInt64
var lastAccessDate: Date
init(_ image: Image, identifier: String) {
self.image = image
self.identifier = identifier
self.lastAccessDate = Date()
self.totalBytes = {
#if os(iOS) || os(tvOS) || os(watchOS)
let size = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale)
#elseif os(macOS)
let size = CGSize(width: image.size.width, height: image.size.height)
#endif
let bytesPerPixel: CGFloat = 4.0
let bytesPerRow = size.width * bytesPerPixel
let totalBytes = UInt64(bytesPerRow) * UInt64(size.height)
return totalBytes
}()
}
func accessImage() -> Image {
lastAccessDate = Date()
return image
}
}
// MARK: Properties
/// The current total memory usage in bytes of all images stored within the cache.
open var memoryUsage: UInt64 {
var memoryUsage: UInt64 = 0
synchronizationQueue.sync { memoryUsage = self.currentMemoryUsage }
return memoryUsage
}
/// The total memory capacity of the cache in bytes.
public let memoryCapacity: UInt64
/// The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory
/// capacity drops below this limit.
public let preferredMemoryUsageAfterPurge: UInt64
private let synchronizationQueue: DispatchQueue
private var cachedImages: [String: CachedImage]
private var currentMemoryUsage: UInt64
// MARK: Initialization
/// Initializes the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
/// after purge limit.
///
/// Please note, the memory capacity must always be greater than or equal to the preferred memory usage after purge.
///
/// - parameter memoryCapacity: The total memory capacity of the cache in bytes. `100 MB` by default.
/// - parameter preferredMemoryUsageAfterPurge: The preferred memory usage after purge in bytes. `60 MB` by default.
///
/// - returns: The new `AutoPurgingImageCache` instance.
public init(memoryCapacity: UInt64 = 100_000_000, preferredMemoryUsageAfterPurge: UInt64 = 60_000_000) {
self.memoryCapacity = memoryCapacity
self.preferredMemoryUsageAfterPurge = preferredMemoryUsageAfterPurge
precondition(
memoryCapacity >= preferredMemoryUsageAfterPurge,
"The `memoryCapacity` must be greater than or equal to `preferredMemoryUsageAfterPurge`"
)
self.cachedImages = [:]
self.currentMemoryUsage = 0
self.synchronizationQueue = {
let name = String(format: "org.alamofire.autopurgingimagecache-%08x%08x", arc4random(), arc4random())
return DispatchQueue(label: name, attributes: .concurrent)
}()
#if os(iOS) || os(tvOS)
#if swift(>=4.2)
let notification = UIApplication.didReceiveMemoryWarningNotification
#else
let notification = Notification.Name.UIApplicationDidReceiveMemoryWarning
#endif
NotificationCenter.default.addObserver(
self,
selector: #selector(AutoPurgingImageCache.removeAllImages),
name: notification,
object: nil
)
#endif
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: Add Image to Cache
/// Adds the image to the cache using an identifier created from the request and optional identifier.
///
/// - parameter image: The image to add to the cache.
/// - parameter request: The request used to generate the image's unique identifier.
/// - parameter identifier: The additional identifier to append to the image's unique identifier.
open func add(_ image: Image, for request: URLRequest, withIdentifier identifier: String? = nil) {
let requestIdentifier = imageCacheKey(for: request, withIdentifier: identifier)
add(image, withIdentifier: requestIdentifier)
}
/// Adds the image to the cache with the given identifier.
///
/// - parameter image: The image to add to the cache.
/// - parameter identifier: The identifier to use to uniquely identify the image.
open func add(_ image: Image, withIdentifier identifier: String) {
synchronizationQueue.async(flags: [.barrier]) {
let cachedImage = CachedImage(image, identifier: identifier)
if let previousCachedImage = self.cachedImages[identifier] {
self.currentMemoryUsage -= previousCachedImage.totalBytes
}
self.cachedImages[identifier] = cachedImage
self.currentMemoryUsage += cachedImage.totalBytes
}
synchronizationQueue.async(flags: [.barrier]) {
if self.currentMemoryUsage > self.memoryCapacity {
let bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge
var sortedImages = self.cachedImages.map { $1 }
sortedImages.sort {
let date1 = $0.lastAccessDate
let date2 = $1.lastAccessDate
return date1.timeIntervalSince(date2) < 0.0
}
var bytesPurged = UInt64(0)
for cachedImage in sortedImages {
self.cachedImages.removeValue(forKey: cachedImage.identifier)
bytesPurged += cachedImage.totalBytes
if bytesPurged >= bytesToPurge {
break
}
}
self.currentMemoryUsage -= bytesPurged
}
}
}
// MARK: Remove Image from Cache
/// Removes the image from the cache using an identifier created from the request and optional identifier.
///
/// - parameter request: The request used to generate the image's unique identifier.
/// - parameter identifier: The additional identifier to append to the image's unique identifier.
///
/// - returns: `true` if the image was removed, `false` otherwise.
@discardableResult
open func removeImage(for request: URLRequest, withIdentifier identifier: String?) -> Bool {
let requestIdentifier = imageCacheKey(for: request, withIdentifier: identifier)
return removeImage(withIdentifier: requestIdentifier)
}
/// Removes all images from the cache created from the request.
///
/// - parameter request: The request used to generate the image's unique identifier.
///
/// - returns: `true` if any images were removed, `false` otherwise.
@discardableResult
open func removeImages(matching request: URLRequest) -> Bool {
let requestIdentifier = imageCacheKey(for: request, withIdentifier: nil)
var removed = false
synchronizationQueue.sync(flags: [.barrier]) {
for key in self.cachedImages.keys where key.hasPrefix(requestIdentifier) {
if let cachedImage = self.cachedImages.removeValue(forKey: key) {
self.currentMemoryUsage -= cachedImage.totalBytes
removed = true
}
}
}
return removed
}
/// Removes the image from the cache matching the given identifier.
///
/// - parameter identifier: The unique identifier for the image.
///
/// - returns: `true` if the image was removed, `false` otherwise.
@discardableResult
open func removeImage(withIdentifier identifier: String) -> Bool {
var removed = false
synchronizationQueue.sync(flags: [.barrier]) {
if let cachedImage = self.cachedImages.removeValue(forKey: identifier) {
self.currentMemoryUsage -= cachedImage.totalBytes
removed = true
}
}
return removed
}
/// Removes all images stored in the cache.
///
/// - returns: `true` if images were removed from the cache, `false` otherwise.
@discardableResult @objc
open func removeAllImages() -> Bool {
var removed = false
synchronizationQueue.sync(flags: [.barrier]) {
if !self.cachedImages.isEmpty {
self.cachedImages.removeAll()
self.currentMemoryUsage = 0
removed = true
}
}
return removed
}
// MARK: Fetch Image from Cache
/// Returns the image from the cache associated with an identifier created from the request and optional identifier.
///
/// - parameter request: The request used to generate the image's unique identifier.
/// - parameter identifier: The additional identifier to append to the image's unique identifier.
///
/// - returns: The image if it is stored in the cache, `nil` otherwise.
open func image(for request: URLRequest, withIdentifier identifier: String? = nil) -> Image? {
let requestIdentifier = imageCacheKey(for: request, withIdentifier: identifier)
return image(withIdentifier: requestIdentifier)
}
/// Returns the image in the cache associated with the given identifier.
///
/// - parameter identifier: The unique identifier for the image.
///
/// - returns: The image if it is stored in the cache, `nil` otherwise.
open func image(withIdentifier identifier: String) -> Image? {
var image: Image?
synchronizationQueue.sync(flags: [.barrier]) {
if let cachedImage = self.cachedImages[identifier] {
image = cachedImage.accessImage()
}
}
return image
}
// MARK: Image Cache Keys
/// Returns the unique image cache key for the specified request and additional identifier.
///
/// - parameter request: The request.
/// - parameter identifier: The additional identifier.
///
/// - returns: The unique image cache key.
open func imageCacheKey(for request: URLRequest, withIdentifier identifier: String?) -> String {
var key = request.url?.absoluteString ?? ""
if let identifier = identifier {
key += "-\(identifier)"
}
return key
}
}
| mit | e4980d6d1cc12f8c4ae60be8b9b03723 | 38.46 | 121 | 0.65665 | 5.241366 | false | false | false | false |
crescentflare/SmartMockServer | MockLibIOS/Example/SmartMockLib/LoginViewController.swift | 1 | 1497 | //
// LoginViewController.swift
// SmartMockLib Example
//
// The login view can log in the user, when successful, it closes
//
import UIKit
class LoginViewController: UIViewController {
// --
// MARK: Members
// --
@IBOutlet private var _usernameField: UITextField! = nil
@IBOutlet private var _passwordField: UITextField! = nil
@IBOutlet private var _loginButton: UIButton! = nil
// --
// MARK: Interaction
// --
@IBAction func loginButtonPressed() {
_usernameField.isEnabled = false
_passwordField.isEnabled = false
_loginButton.isEnabled = false
Api.authenticationService.login(withUsername: _usernameField.text ?? "", andPassword: _passwordField.text ?? "", success: { user in
Api.setCurrentUser(user)
_ = self.navigationController?.popViewController(animated: true)
}, failure: { apiError in
self._usernameField.isEnabled = true
self._passwordField.isEnabled = true
self._loginButton.isEnabled = true
let alert = UIAlertController.init(title: "Login failed", message: apiError?.message ?? Api.defaultErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
})
}
@IBAction func toPasswordEditing() {
_passwordField.becomeFirstResponder()
}
}
| mit | ec5b3523805d6d22cc12b12f82dbf78e | 30.851064 | 148 | 0.636607 | 4.940594 | false | false | false | false |
pebble8888/cpp2swift | src/cpp2swift/MyPlayground.playground/Contents.swift | 1 | 392 | //: Playground - noun: a place where people can play
import Cocoa
var str = "Hello;cat"
var i:String.Index = str.startIndex
var pin:String.Index = str.endIndex
while i < str.endIndex {
while i < str.endIndex {
if str[i] == ";" {
break
} else {
++i
}
}
let aa = str.substringWithRange(Range(start:pin, end:i))
pin = i
}
| mit | 7dcf911ee8ee324a1c23f085e1c9e561 | 17.666667 | 60 | 0.55102 | 3.5 | false | false | false | false |
rene-dohan/CS-IOS | Renetik/Renetik/Classes/Core/CSLang.swift | 1 | 3302 | //
// Created by Rene on 2018-11-22.
// Copyright (c) 2018 Renetik Software. All rights reserved.
//
import Foundation
public typealias Boolean = Bool
public typealias Func = () -> Void
public typealias ArgFunc<Argument> = (Argument) -> Void
extension TimeInterval {
public static let defaultAnimation: TimeInterval = 0.25
}
enum CSError: Error {
case todo
case unsupported
case failed
}
struct RuntimeError: Error {
let message: String
init(_ message: String) { self.message = message }
public var localizedDescription: String { message }
}
let isDebug: Bool = {
var isDebug = false
func setDebug() -> Bool {
isDebug = true
return true
}
assert(setDebug())
return isDebug
}()
let csBundle: Bundle = {
// When use_frameworks! let bundle = Bundle(identifier: "org.cocoapods.Renetik")!
// When #use_modular_headers! Bundle.main
// TODO?: How to solve this universally
let bundle = Bundle(identifier: "org.cocoapods.Renetik")!
return Bundle(path: bundle.path(forResource: "RenetikBundle", ofType: "bundle")!)!
}()
public func localized(_ key: String) -> String {
var string = Bundle.main.localizedString(forKey: key, value: nil, table: nil)
if string == key {
string = csBundle.localizedString(forKey: key, value: nil, table: nil)
if string == key { logWarn("localized key ot found \(key)") }
}
return string
}
public func later(function: @escaping Func) {
DispatchQueue.main.async(execute: function)
}
public func later(seconds: TimeInterval, function: @escaping Func) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: function)
}
private let userInitiatedQueue = DispatchQueue(label: "CSUserInitiatedQueue", qos: .userInitiated)
private let utilityQueue = DispatchQueue(label: "CSUtilityQueue", qos: .utility)
public func background(function: @escaping Func) {
userInitiatedQueue.async(execute: function)
}
public func stringify<Subject>(_ value: Subject) -> String {
if value == nil { return "" }
return (value as? OptionalProtocol)?.asString ?? String(describing: value)
}
public func describe<Subject>(_ value: Subject) -> String {
if value == nil { return "nil" }
return String(describing: value)
}
public func notNil(_ items: Any?...) -> Bool {
for it in items { if it.isNil { return false } }
return true
}
public func isAllNil(_ items: Any?...) -> Bool {
for it in items { if it.notNil { return false } }
return true
}
public func isAnyNil(_ items: Any?...) -> Bool {
for it in items { if it.isNil { return true } }
return false
}
public func when<Type>(notNil item: Type?, then: ArgFunc<Type>) {
if item.notNil { then(item!) }
}
public func when<Type>(isNil item: Type?, then: Func) {
if item.isNil { then() }
}
open class CSObject: CSAnyProtocol, Equatable, CustomStringConvertible {
public init() {}
}
public class Nil: CSAnyProtocol, Equatable {
private init() {}
public static var instance: Nil = Nil()
public static func ==(lhs: Nil, rhs: Nil) -> Bool { true }
}
public class CSConditionalResult {
let isDoElse: Bool
public init(doElseIf: Bool) { isDoElse = doElseIf }
public func elseDo(_ function: Func) { if isDoElse { function() } }
}
| mit | 440aff3837eae7e23430d468a0e3241f | 25.206349 | 98 | 0.672623 | 3.875587 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/E2EE/UserClientEventConsumerTests.swift | 1 | 10784 | // Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
class UserClientEventConsumerTests: RequestStrategyTestBase {
var sut: UserClientEventConsumer!
var clientRegistrationStatus: ZMMockClientRegistrationStatus!
var clientUpdateStatus: ZMMockClientUpdateStatus!
var cookieStorage: ZMPersistentCookieStorage!
override func setUp() {
super.setUp()
self.syncMOC.performGroupedBlockAndWait {
self.cookieStorage = ZMPersistentCookieStorage(forServerName: "myServer",
userIdentifier: self.userIdentifier)
self.clientUpdateStatus = ZMMockClientUpdateStatus(syncManagedObjectContext: self.syncMOC)
self.clientRegistrationStatus = ZMMockClientRegistrationStatus(managedObjectContext: self.syncMOC,
cookieStorage: self.cookieStorage,
registrationStatusDelegate: nil)
self.sut = UserClientEventConsumer(managedObjectContext: self.syncMOC,
clientRegistrationStatus: self.clientRegistrationStatus,
clientUpdateStatus: self.clientUpdateStatus)
let selfUser = ZMUser.selfUser(in: self.syncMOC)
selfUser.remoteIdentifier = self.userIdentifier
self.syncMOC.saveOrRollback()
}
}
override func tearDown() {
self.clientRegistrationStatus.tearDown()
self.clientRegistrationStatus = nil
self.clientUpdateStatus = nil
self.sut = nil
super.tearDown()
}
static func payloadForAddingClient(_ clientId: String,
label: String = "device label",
time: Date = Date(timeIntervalSince1970: 12345)
) -> ZMTransportData {
return [
"client": [
"id": clientId,
"label": label,
"time": time.transportString(),
"type": "permanent"
],
"type": "user.client-add"
] as ZMTransportData
}
static func payloadForDeletingClient(_ clientId: String) -> ZMTransportData {
return [
"client": [
"id": clientId
],
"type": "user.client-remove"
] as ZMTransportData
}
func testThatItAddsAnIgnoredSelfUserClientWhenReceivingAPush() {
// given
let clientId = "94766bd92f56923d"
let clientLabel = "iPhone 23sd Plus Air Pro C"
let clientTime = Date(timeIntervalSince1970: 1234555)
var selfUser: ZMUser! = nil
var selfClient: UserClient! = nil
syncMOC.performGroupedBlock {
selfUser = ZMUser.selfUser(in: self.syncMOC)
selfClient = self.createSelfClient()
_ = self.createRemoteClient()
XCTAssertEqual(selfUser.clients.count, 1)
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
let payload: [String: Any] = [
"id": "27330a52-bab6-11e5-8183-22000b080265",
"payload": [
type(of: self).payloadForAddingClient(clientId, label: clientLabel, time: clientTime)
],
"transient": false
]
let events = ZMUpdateEvent.eventsArray(fromPushChannelData: payload as ZMTransportData)
guard let event = events!.first else {
XCTFail()
return
}
// when
syncMOC.performGroupedBlockAndWait {
self.sut.processEvents([event], liveEvents: true, prefetchResult: .none)
// then
XCTAssertEqual(selfUser.clients.count, 2)
guard let newClient = selfUser.clients.filter({ $0 != selfClient}).first else {
XCTFail()
return
}
XCTAssertEqual(newClient.remoteIdentifier, clientId)
XCTAssertEqual(newClient.label, clientLabel)
XCTAssertEqual(newClient.activationDate, clientTime)
XCTAssertTrue(selfClient.ignoredClients.contains(newClient))
}
}
func testThatItAddsASelfUserClientWhenDownloadingAClientEvent() {
// given
let clientId = "94766bd92f56923d"
var selfUser: ZMUser! = nil
syncMOC.performGroupedBlockAndWait {
selfUser = ZMUser.selfUser(in: self.syncMOC)
XCTAssertEqual(selfUser.clients.count, 0)
}
let payload = type(of: self).payloadForAddingClient(clientId)
let event = ZMUpdateEvent(fromEventStreamPayload: payload, uuid: nil)!
// when
self.syncMOC.performGroupedBlock {
self.sut.processEvents([event], liveEvents: false, prefetchResult: .none)
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
self.syncMOC.performGroupedBlockAndWait {
XCTAssertEqual(selfUser.clients.count, 1)
guard let newClient = selfUser.clients.first else {
XCTFail()
return
}
XCTAssertEqual(newClient.remoteIdentifier, clientId)
}
}
func testThatItDoesNotAddASelfUserClientWhenReceivingAPushIfTheClientExistsAlready() {
// given
var selfUser: ZMUser! = nil
var existingClient: UserClient! = nil
syncMOC.performGroupedBlockAndWait {
selfUser = ZMUser.selfUser(in: self.syncMOC)
existingClient = self.createSelfClient()
XCTAssertEqual(selfUser.clients.count, 1)
}
// when
syncMOC.performGroupedBlockAndWait {
let payload: [String: Any] = [
"id": "27330a52-bab6-11e5-8183-22000b080265",
"payload": [
type(of: self).payloadForAddingClient(existingClient.remoteIdentifier!)
],
"transient": false
]
let events = ZMUpdateEvent.eventsArray(fromPushChannelData: payload as ZMTransportData)
guard let event = events!.first else {
XCTFail()
return
}
self.sut.processEvents([event], liveEvents: true, prefetchResult: .none)
}
// then
syncMOC.performGroupedBlockAndWait {
XCTAssertEqual(selfUser.clients.count, 1)
guard let newClient = selfUser.clients.first else {
XCTFail()
return
}
XCTAssertEqual(newClient, existingClient)
}
}
func testThatItDeletesASelfClientWhenReceivingAPush() {
syncMOC.performGroupedBlockAndWait {
// given
let selfUser = ZMUser.selfUser(in: self.syncMOC)
let existingClient1 = self.createSelfClient()
let existingClient2 = UserClient.insertNewObject(in: self.syncMOC)
existingClient2.user = selfUser
existingClient2.remoteIdentifier = "aabbcc112233"
self.syncMOC.saveOrRollback()
XCTAssertEqual(selfUser.clients.count, 2)
let payload: [String: Any] = [
"id": "27330a52-bab6-11e5-8183-22000b080265",
"payload": [
type(of: self).payloadForDeletingClient(existingClient2.remoteIdentifier!)
],
"transient": false
]
let events = ZMUpdateEvent.eventsArray(fromPushChannelData: payload as ZMTransportData)
guard let event = events!.first else {
XCTFail()
return
}
// when
self.sut.processEvents([event], liveEvents: true, prefetchResult: .none)
// then
XCTAssertEqual(selfUser.clients.count, 1)
guard let newClient = selfUser.clients.first else {
XCTFail()
return
}
XCTAssertEqual(newClient, existingClient1)
}
}
func testThatItInvalidatesTheCurrentSelfClientAndWipeCryptoBoxWhenReceivingAPush() {
syncMOC.performGroupedBlockAndWait {
// given
let selfUser = ZMUser.selfUser(in: self.syncMOC)
let existingClient = self.createSelfClient()
var fingerprint: Data?
self.syncMOC.zm_cryptKeyStore.encryptionContext.perform { (sessionsDirectory) in
fingerprint = sessionsDirectory.localFingerprint
}
let previousLastPrekey = try? self.syncMOC.zm_cryptKeyStore.lastPreKey()
XCTAssertEqual(selfUser.clients.count, 1)
let payload: [String: Any] = [
"id": "27330a52-bab6-11e5-8183-22000b080265",
"payload": [
type(of: self).payloadForDeletingClient(existingClient.remoteIdentifier!)
],
"transient": false
] as [String: Any]
let events = ZMUpdateEvent.eventsArray(fromPushChannelData: payload as ZMTransportData)
guard let event = events!.first else { return XCTFail() }
// when
self.sut.processEvents([event], liveEvents: true, prefetchResult: .none)
// then
var newFingerprint: Data?
self.syncMOC.zm_cryptKeyStore.encryptionContext.perform { (sessionsDirectory) in
newFingerprint = sessionsDirectory.localFingerprint
}
let newLastPrekey = try? self.syncMOC.zm_cryptKeyStore.lastPreKey()
XCTAssertNotNil(fingerprint)
XCTAssertNotNil(newFingerprint)
XCTAssertNotEqual(fingerprint, newFingerprint)
XCTAssertNil(selfUser.clients.first?.remoteIdentifier)
XCTAssertNil(self.syncMOC.persistentStoreMetadata(forKey: ZMPersistedClientIdKey))
XCTAssertNotNil(fingerprint)
XCTAssertNotNil(newFingerprint)
XCTAssertNotEqual(previousLastPrekey, newLastPrekey)
}
}
}
| gpl-3.0 | 3b47129a4f2beb6bcbe7f405560a3376 | 36.314879 | 110 | 0.596903 | 5.42182 | false | true | false | false |
IBM-MIL/BluePic | BluePic-iOS/BluePic/Views/CameraConfirmationView.swift | 1 | 5519 | /**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
/// Confirmation view to allow user to add a caption to a photo and upload or cancel photo upload
class CameraConfirmationView: UIView, UITextFieldDelegate {
/// Image view to show the chosen photo in
@IBOutlet weak var photoImageView: UIImageView!
/// Cancel button to cancel uploading a photo
@IBOutlet weak var cancelButton: UIButton!
/// Post button to post a photo
@IBOutlet weak var postButton: UIButton!
/// Caption text field to specify a photo caption
@IBOutlet weak var titleTextField: UITextField!
/// Loading indicator while uploading
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
/// Reference to the original frame
var originalFrame: CGRect!
/**
Return an instance of this view
- returns: an instance of this view
*/
static func instanceFromNib() -> CameraConfirmationView {
return UINib(nibName: "CameraConfirmationView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! CameraConfirmationView
}
/**
Method called when the view wakes from nib and then sets up the view
*/
override func awakeFromNib() {
super.awakeFromNib()
self.setupView()
self.addKeyboardObservers()
//titleTextField.resignFirstResponder()
}
/**
Method to setup the view and its outlets
*/
func setupView() {
let localizedString = NSLocalizedString("GIVE IT A TITLE", comment: "")
self.titleTextField.attributedPlaceholder = NSAttributedString(string:localizedString,
attributes:[NSForegroundColorAttributeName: UIColor.grayColor()])
self.translatesAutoresizingMaskIntoConstraints = true
self.titleTextField.tintColor = UIColor.whiteColor()
}
/**
Method called when keyboard will show
- parameter notification: show notification
*/
func keyboardWillShow(notification:NSNotification) {
UIApplication.sharedApplication().statusBarHidden = true
adjustingHeight(true, notification: notification)
}
/**
Method called when keyboard will hide
- parameter notification: hide notification
*/
func keyboardWillHide(notification:NSNotification) {
adjustingHeight(false, notification: notification)
}
/**
Method called when touches began to hide keyboard
- parameter touches: touches that began
- parameter event: event when touches began
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.endEditing(true)
}
/**
Method to add show and hide keyboard observers
*/
func addKeyboardObservers() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
/**
Method to removed show and hide keyboard observers
*/
func removeKeyboardObservers() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
/**
Method to move the whole view up/down when user pulls the keyboard up/down
- parameter show: whether or raise or lower view
- parameter notification: hide or show notification called
*/
func adjustingHeight(show:Bool, notification:NSNotification) {
// 1
var userInfo = notification.userInfo!
// 2
let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
// 3
let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
// 4
let changeInHeight = (CGRectGetHeight(keyboardFrame)) * (show ? -1 : 1)
//5
if (show){
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
self.frame = CGRect(x: 0, y: 0 + changeInHeight, width: self.frame.width, height: self.frame.height)
})
}
else {
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
self.frame = self.originalFrame
})
}
}
/**
Method called when text field should return (return tapped) to hide the keyboard
- parameter textField: textfield in question
- returns: end editing- true or false
*/
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.endEditing(true)
return true
}
}
| apache-2.0 | da7097cfa9e7146bbd2343a6676ad618 | 31.85119 | 144 | 0.666606 | 5.486083 | false | false | false | false |
Touchwonders/Transition | Transition/Classes/Convenience/Transitions/MoveTransitionAnimation.swift | 1 | 2762 | //
// MIT License
//
// Copyright (c) 2017 Touchwonders B.V.
//
// 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.
open class MoveTransitionAnimation : EdgeTransitionAnimation {
private weak var topView: UIView?
private var targetTransform: CGAffineTransform = .identity
private var isDismissing: Bool = false
open override func setup(in operationContext: TransitionOperationContext) {
let context = operationContext.context
guard let topView = context.defaultViewSetup(for: operationContext.operation),
let transitionEdge = transitionScreenEdgeFor(operation: operationContext.operation)
else { return }
self.topView = topView
isDismissing = operationContext.operation.isDismissing
let effectiveTransitionEdge = isDismissing ? transitionEdge.opposite : transitionEdge
let hiddenTransform = transformForTranslatingViewTo(edge: effectiveTransitionEdge, outside: context.containerView.bounds)
let initialTransform = isDismissing ? .identity : hiddenTransform
targetTransform = isDismissing ? hiddenTransform : .identity
topView.transform = initialTransform
}
open override var layers: [AnimationLayer] {
return [AnimationLayer(timingParameters: AnimationTimingParameters(animationCurve: animationCurve), animation: animate)]
}
open func animate() {
topView?.transform = targetTransform
}
open override func completion(position: UIViewAnimatingPosition) {
if position != .end && !isDismissing {
topView?.removeFromSuperview()
}
}
}
| mit | b7c503a823871a9051bfd9f9eb7fcb0a | 40.848485 | 129 | 0.707096 | 5.260952 | false | false | false | false |
WilliamHester/Breadit-iOS | Breadit/ViewControllers/UserViewController.swift | 1 | 2077 | //
// Created by William Hester on 6/10/16.
// Copyright (c) 2016 William Hester. All rights reserved.
//
import UIKit
class UserViewController: ListingViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(SubmissionCommentCellView.self, forCellReuseIdentifier: "SubmissionCommentCellView")
}
override func setUpRowForComment(comment: Comment, atIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell
if let textComment = comment as? TextComment {
let textCommentCell = tableView.dequeueReusableCellWithIdentifier("SubmissionCommentCellView")
as! SubmissionCommentCellView
setUpSubmissionCommentView(textCommentCell, forComment: textComment)
setUpTextCommentView(textCommentCell, forComment: textComment)
cell = textCommentCell
} else {
let moreComments = tableView.dequeueReusableCellWithIdentifier("MoreCommentCellView")
as! MoreCommentCellView
setUpMoreCommentView(moreComments, forComment: comment)
cell = moreComments
}
return cell
}
func setUpSubmissionCommentView(cell: SubmissionCommentCellView, forComment comment: TextComment) {
let string = NSMutableAttributedString(string: comment.submissionTitle!, attributes: [
NSFontAttributeName: UIFont.italicSystemFontOfSize(13)
])
string.appendAttributedString(NSAttributedString(string: " by "))
string.appendAttributedString(NSAttributedString(string: "/u/\(comment.submissionAuthor!)", attributes: [
NSForegroundColorAttributeName: Colors.infoColor
]))
string.appendAttributedString(NSAttributedString(string: " in "))
string.appendAttributedString(NSAttributedString(string: "/r/\(comment.subredditDisplay!)", attributes: [
NSForegroundColorAttributeName: Colors.infoColor
]))
cell.submissionTitle.attributedText = string
}
}
| apache-2.0 | bddd350d7e8b9acbd4ce22dfa129d211 | 42.270833 | 116 | 0.70053 | 6.037791 | false | false | false | false |
farshadtx/Fleet | Fleet/CoreExtensions/UITextField+Fleet.swift | 1 | 5493 | import UIKit
private var fleet_isFocusedAssociatedKey: UInt = 0
extension UITextField {
fileprivate var fleet_isFocused: Bool? {
get {
let fleet_isFocusedValue = objc_getAssociatedObject(self, &fleet_isFocusedAssociatedKey) as? NSNumber
return fleet_isFocusedValue?.boolValue
}
set {
var fleet_isFocusedValue: NSNumber?
if let newValue = newValue {
fleet_isFocusedValue = NSNumber(value: newValue as Bool)
}
objc_setAssociatedObject(self, &fleet_isFocusedAssociatedKey, fleet_isFocusedValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
public enum FLTTextFieldError: Error {
case disabledTextFieldError
}
extension UITextField {
/**
Gives the text field focus, firing the .EditingDidBegin events. It
does not give the text field first responder.
- Throws: `FLTTextFieldError.DisabledTextFieldError` if the
text field is disabled.
*/
public func focus() throws {
if fleet_isFocused != nil && fleet_isFocused! {
Logger.logWarning("Attempting to enter a UITextField that was already entered")
return
}
if !isEnabled {
throw FLTTextFieldError.disabledTextFieldError
}
fleet_isFocused = true
if let delegate = delegate {
_ = delegate.textFieldShouldBeginEditing?(self)
_ = delegate.textFieldDidBeginEditing?(self)
}
self.sendActions(for: .editingDidBegin)
}
/**
Ends focus in the text field, firing the .EditingDidEnd events. It
does make the text field resign first responder.
*/
public func unfocus() {
if fleet_isFocused == nil || !fleet_isFocused! {
Logger.logWarning("Attempting to end focus for a UITextField that was never focused")
return
}
if let delegate = delegate {
_ = delegate.textFieldShouldEndEditing?(self)
_ = delegate.textFieldDidEndEditing?(self)
}
self.sendActions(for: .editingDidEnd)
fleet_isFocused = false
}
/**
Focuses the text field, enters the given text, and unfocuses it, firing
the .EditingDidBegin, .EditingChanged, and .EditingDidEnd events
as appropriate. Does not manipulate first responder.
If the text field has no delegate, the text is still entered into the
field and the .EditingChanged event is still fired.
- Parameter text: The text to type into the field
- Throws: `FLTTextFieldError.DisabledTextFieldError` if the
text field is disabled.
*/
public func enter(text: String) throws {
try self.focus()
self.type(text)
self.unfocus()
}
/**
Types the given text into the text field, firing the .EditingChanged
event once for each character, as would happen had a real user
typed the text into the field.
If the text field has no delegate, the text is still entered into the
field and the .EditingChanged event is still fired.
- Parameter text: The text to type into the field
*/
public func type(_ text: String) {
if fleet_isFocused == nil || !fleet_isFocused! {
Logger.logWarning("Attempting to type \"\(text)\" into a UITextField that was never focused")
return
}
if let delegate = delegate {
self.text = ""
for (index, char) in text.characters.enumerated() {
_ = delegate.textField?(self, shouldChangeCharactersIn: NSRange.init(location: index, length: 1), replacementString: String(char))
self.text?.append(char)
self.sendActions(for: .editingChanged)
}
} else {
self.text = ""
for (_, char) in text.characters.enumerated() {
self.text?.append(char)
self.sendActions(for: .editingChanged)
}
}
}
/**
Types the given text into the text field, firing the .EditingChanged
event just once for the entire string, as would happen had a real user
pasted the text into the field.
If the text field has no delegate, the text is still entered into the
field and the .EditingChanged event is still fired.
- Parameter text: The text to paste into the field
*/
public func paste(text: String) {
if fleet_isFocused == nil || !fleet_isFocused! {
Logger.logWarning("Attempting to paste \"\(text)\" into a UITextField that was never focused")
return
}
if let delegate = delegate {
let length = text.characters.count
_ = delegate.textField?(self, shouldChangeCharactersIn: NSRange.init(location: 0, length:length), replacementString: text)
} else {
self.text = text
}
self.sendActions(for: .editingChanged)
}
/**
Clears all text from the text field, firing the textFieldShouldClear?
event as happens when the user clears the field through the UI.
If the text field has no delegate, the text is still cleared from the
field.
*/
public func clearText() {
self.text = ""
if let delegate = delegate {
let _ = delegate.textFieldShouldClear?(self)
}
}
}
| apache-2.0 | 86ffb678ce08abdccacef64341f92192 | 32.699387 | 146 | 0.612598 | 5.044077 | false | false | false | false |
resmio/TastyTomato | TastyTomato/Code/Extensions/Public/UIView/UIView (TemporaryPositionAndDimensions).swift | 1 | 9182 | //
// UIView (TemporaryPositionAndDimensions).swift
// TastyTomato
//
// Created by Jan Nash on 9/11/17.
// Copyright © 2017 resmio. All rights reserved.
//
import UIKit
import SignificantSpices
/**
This extension provides functionality to temporarily change the position and dimensions
of Views. You might for example use it to reduce the height of a UITextView, so it is
not hidden beneath the keyboard, or to move the complete window upwards, so a focussed
UITextField is not hidden beneath the keyboard. The main advantage of using this
extension is the fact that you don't have to backup the original position/dimensions
in your viewcontroller. Instead, it is completely encapsulated in the View.
*/
// MARK: // Public
public extension UIView {
// Readonly
// Temporary position and dimensions
/**
The temporary x-position of the view. nil, if no temporary x is set.
*/
var tempX: CGFloat? {
return self._tempX
}
/**
The temporary y-position of the view. nil, if no temporary y is set.
*/
var tempY: CGFloat? {
return self._tempY
}
/**
The temporary width of the view. nil, if no temporary width is set.
*/
var tempWidth: CGFloat? {
return self._tempWidth
}
/**
The temporary height of the view. nil, if no temporary height is set.
*/
var tempHeight: CGFloat? {
return self._tempHeight
}
// Original dimensions
/**
The original x-position of the view. frame.origin.x, if no temporary x is set.
*/
var originalX: CGFloat {
return self._originalX ?? self.frame.origin.x
}
/**
The original y-position of the view. frame.origin.y, if no temporary y is set.
*/
var originalY: CGFloat {
return self._originalY ?? self.frame.origin.y
}
/**
The original width of the view. frame.size.width, if no temporary width is set.
*/
var originalWidth: CGFloat {
return self._originalWidth ?? self.frame.size.width
}
/**
The original height of the view. frame.size.height, if no temporary height is set.
*/
var originalHeight: CGFloat {
return self._originalHeight ?? self.frame.size.height
}
// Offsets
/**
The current x-offset of the view. 0, if no temporary x is set.
*/
var xOffset: CGFloat {
return (self.tempX ?? self.originalX) - self.originalX
}
/**
The current y-offset of the view. 0, if no temporary y is set.
*/
var yOffset: CGFloat {
return (self.tempY ?? self.originalY) - self.originalY
}
/**
The current width-offset of the view. 0, if no temporary width is set.
*/
var widthOffset: CGFloat {
return (self.tempWidth ?? self.originalWidth) - self.originalWidth
}
/**
The current height-offset of the view. 0, if no temporary height is set.
*/
var heightOffset: CGFloat {
return (self.tempHeight ?? self.originalHeight) - self.originalHeight
}
// Functions
/**
Sets the temporary x position of the view.
*/
func setTempX(_ tempX: CGFloat) {
self._setTempX(tempX)
}
/**
Sets the temporary y position of the view.
*/
func setTempY(_ tempY: CGFloat) {
self._setTempY(tempY)
}
/**
Sets the temporary width of the view.
*/
func setTempWidth(_ tempWidth: CGFloat) {
self._setTempWidth(tempWidth)
}
/**
Sets the temporary height of the view.
*/
func setTempHeight(_ tempHeight: CGFloat) {
self._setTempHeight(tempHeight)
}
/**
Resets the x-position of the view to its original value.
*/
func resetX() {
self._resetX()
}
/**
Resets the y-position of the view to its original value.
*/
func resetY() {
self._resetY()
}
/**
Resets the width of the view to its original value.
*/
func resetWidth() {
self._resetWidth()
}
/**
Resets the height of the view to its original value.
*/
func resetHeight() {
self._resetHeight()
}
}
// MARK: // Internal
// MARK: AssociationOwner
extension UIView: AssociationOwner {}
// MARK: // Private
// MARK: AssociationKeys
private extension ValueAssociationKey {
static var _XBackup: ValueAssociationKey = ValueAssociationKey()
static var _XTemp: ValueAssociationKey = ValueAssociationKey()
static var _YBackup: ValueAssociationKey = ValueAssociationKey()
static var _YTemp: ValueAssociationKey = ValueAssociationKey()
static var _WidthBackup: ValueAssociationKey = ValueAssociationKey()
static var _WidthTemp: ValueAssociationKey = ValueAssociationKey()
static var _HeightBackup: ValueAssociationKey = ValueAssociationKey()
static var _HeightTemp: ValueAssociationKey = ValueAssociationKey()
}
// MARK: Associated Variables
private extension UIView {
var _tempX: CGFloat? {
get {
return self.associatedValue(for: &._XTemp)
}
set(newTempX) {
self.associate(newTempX, by: &._XTemp)
}
}
var _originalX: CGFloat? {
get {
return self.associatedValue(for: &._XBackup)
}
set(newOriginalX) {
self.associate(newOriginalX, by: &._XBackup)
}
}
var _tempY: CGFloat? {
get {
return self.associatedValue(for: &._YTemp)
}
set(newTempY) {
self.associate(newTempY, by: &._YTemp)
}
}
var _originalY: CGFloat? {
get {
return self.associatedValue(for: &._YBackup)
}
set(newOriginalY) {
self.associate(newOriginalY, by: &._YBackup)
}
}
var _tempWidth: CGFloat? {
get {
return self.associatedValue(for: &._WidthTemp)
}
set(newTempWidth) {
self.associate(newTempWidth, by: &._WidthTemp)
}
}
var _originalWidth: CGFloat? {
get {
return self.associatedValue(for: &._WidthBackup)
}
set(newOriginalWidth) {
self.associate(newOriginalWidth, by: &._WidthBackup)
}
}
var _tempHeight: CGFloat? {
get {
return self.associatedValue(for: &._HeightTemp)
}
set(newTempHeight) {
self.associate(newTempHeight, by: &._HeightTemp)
}
}
var _originalHeight: CGFloat? {
get {
return self.associatedValue(for: &._HeightBackup)
}
set(newOriginalHeight) {
self.associate(newOriginalHeight, by: &._HeightBackup)
}
}
}
// MARK: Sets
private extension UIView {
func _setTempX(_ tempX: CGFloat) {
self._setTemp(
setter: &self.left,
tempValue: tempX,
tempSave: &self._tempX,
originalBackup: &self._originalX
)
}
func _setTempY(_ tempY: CGFloat) {
self._setTemp(
setter: &self.top,
tempValue: tempY,
tempSave: &self._tempY,
originalBackup: &self._originalY
)
}
func _setTempWidth(_ tempWidth: CGFloat) {
self._setTemp(
setter: &self.width,
tempValue: tempWidth,
tempSave: &self._tempWidth,
originalBackup: &self._originalWidth
)
}
func _setTempHeight(_ tempHeight: CGFloat) {
self._setTemp(
setter: &self.height,
tempValue: tempHeight,
tempSave: &self._tempHeight,
originalBackup: &self._originalHeight
)
}
// Private Helper
private func _setTemp(setter: inout CGFloat, tempValue: CGFloat, tempSave: inout CGFloat?, originalBackup: inout CGFloat?) {
if originalBackup == nil {
originalBackup = setter
}
setter = tempValue
tempSave = tempValue
}
}
// MARK: Resets
private extension UIView {
func _resetX() {
self._reset(
setter: &self.left,
originalBackup: &self._originalX,
tempSave: &self._tempX
)
}
func _resetY() {
self._reset(
setter: &self.top,
originalBackup: &self._originalY,
tempSave: &self._tempY
)
}
func _resetWidth() {
self._reset(
setter: &self.width,
originalBackup: &self._originalWidth,
tempSave: &self._tempWidth
)
}
func _resetHeight() {
self._reset(
setter: &self.height,
originalBackup: &self._originalHeight,
tempSave: &self._tempHeight
)
}
// Private Helper
private func _reset(setter: inout CGFloat, originalBackup: inout CGFloat?, tempSave: inout CGFloat?) {
if let original: CGFloat = originalBackup {
setter = original
originalBackup = nil
tempSave = nil
}
}
}
| mit | cf943a94fab4a717a4422ec24d2a4a73 | 24.789326 | 128 | 0.574883 | 4.567662 | false | false | false | false |
brentsimmons/Evergreen | Account/Sources/Account/URLRequest+Account.swift | 1 | 3588 | //
// URLRequest+Account.swift
// NetNewsWire
//
// Created by Brent Simmons on 12/27/16.
// Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import RSWeb
import Secrets
public extension URLRequest {
init(url: URL, credentials: Credentials?, conditionalGet: HTTPConditionalGetInfo? = nil) {
self.init(url: url)
guard let credentials = credentials else {
return
}
switch credentials.type {
case .basic:
let data = "\(credentials.username):\(credentials.secret)".data(using: .utf8)
let base64 = data?.base64EncodedString()
let auth = "Basic \(base64 ?? "")"
setValue(auth, forHTTPHeaderField: HTTPRequestHeader.authorization)
case .feedWranglerBasic:
self.url = url.appendingQueryItems([
URLQueryItem(name: "email", value: credentials.username),
URLQueryItem(name: "password", value: credentials.secret),
URLQueryItem(name: "client_key", value: SecretsManager.provider.feedWranglerKey)
])
case .feedWranglerToken:
self.url = url.appendingQueryItem(URLQueryItem(name: "access_token", value: credentials.secret))
case .newsBlurBasic:
setValue("application/x-www-form-urlencoded", forHTTPHeaderField: HTTPRequestHeader.contentType)
httpMethod = "POST"
var postData = URLComponents()
postData.queryItems = [
URLQueryItem(name: "username", value: credentials.username),
URLQueryItem(name: "password", value: credentials.secret),
]
httpBody = postData.enhancedPercentEncodedQuery?.data(using: .utf8)
case .newsBlurSessionId:
setValue("\(NewsBlurAPICaller.SessionIdCookie)=\(credentials.secret)", forHTTPHeaderField: "Cookie")
httpShouldHandleCookies = true
case .readerBasic:
setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
httpMethod = "POST"
var postData = URLComponents()
postData.queryItems = [
URLQueryItem(name: "Email", value: credentials.username),
URLQueryItem(name: "Passwd", value: credentials.secret)
]
httpBody = postData.enhancedPercentEncodedQuery?.data(using: .utf8)
case .readerAPIKey:
let auth = "GoogleLogin auth=\(credentials.secret)"
setValue(auth, forHTTPHeaderField: HTTPRequestHeader.authorization)
case .oauthAccessToken:
let auth = "OAuth \(credentials.secret)"
setValue(auth, forHTTPHeaderField: "Authorization")
case .oauthAccessTokenSecret:
assertionFailure("Token secrets are used by OAuth1. Did you mean to use `OAuthSwift` instead of a URLRequest?")
break
case .oauthRefreshToken:
// While both access and refresh tokens are credentials, it seems the `Credentials` cases
// enumerates how the identity of the user can be proved rather than
// credentials-in-general, such as in this refresh token case,
// the authority to prove an identity.
assertionFailure("Refresh tokens are used to replace expired access tokens. Did you mean to use `accessToken` instead?")
break
}
guard let conditionalGet = conditionalGet else {
return
}
// Bug seen in the wild: lastModified with last possible 32-bit date, which is in 2038. Ignore those.
// TODO: drop this check in late 2037.
if let lastModified = conditionalGet.lastModified, !lastModified.contains("2038") {
setValue(lastModified, forHTTPHeaderField: HTTPRequestHeader.ifModifiedSince)
}
if let etag = conditionalGet.etag {
setValue(etag, forHTTPHeaderField: HTTPRequestHeader.ifNoneMatch)
}
}
}
| mit | dd397a2ba311bf05301cf44bc160f071 | 38.417582 | 132 | 0.708949 | 4.390453 | false | false | false | false |
bluesnap/bluesnap-ios | BluesnapSDK/BluesnapSDK/BSApplepayOperation.swift | 1 | 6333 | //
// Created by oz on 15/06/2017.
// Copyright (c) 2017 Bluesnap. All rights reserved.
//
import Foundation
import PassKit
open class BSApplepayOperation: Operation {
enum State {
case initial
case finished
case executing
case canceled
}
var state: State = .initial {
willSet {
willChangeValue(forKey: "state");
}
didSet {
didChangeValue(forKey: "state");
}
}
class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> {
return ["state" as NSObject]
}
class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> {
return ["state" as NSObject]
}
class func keyPathsForValuesAffectingIsCancelled() -> Set<NSObject> {
return ["state" as NSObject]
}
override open func start() {
self.state = .executing;
self.execute();
}
open func execute() {
NSLog("This method should be implemented")
}
func finish() {
self.state = .finished;
}
override open var isFinished: Bool {
return self.state == .finished;
}
override open var isCancelled: Bool {
return self.state == .canceled;
}
override open var isExecuting: Bool {
return self.state == .executing;
}
}
public enum PaymentValidationResult {
case valid
case invalidShippingContact
case invalidBillingPostalAddress
case invalidShippingPostalAddress
fileprivate func asPKPaymentStatus() -> PKPaymentAuthorizationStatus? {
switch self {
case .invalidShippingContact:
return PKPaymentAuthorizationStatus.invalidShippingContact;
case .invalidBillingPostalAddress:
return PKPaymentAuthorizationStatus.invalidBillingPostalAddress;
case .invalidShippingPostalAddress:
return PKPaymentAuthorizationStatus.invalidShippingPostalAddress;
default:
return nil;
}
}
}
public protocol PaymentOperationDelegate: class {
func validate(payment: PKPayment, completion: @escaping(PaymentValidationResult) -> Void)
func send(paymentInformation: BSApplePayInfo, completion: @escaping (BSErrors?) -> Void)
func didSelectPaymentMethod(method: PKPaymentMethod, completion: @escaping ([PKPaymentSummaryItem]) -> Void)
func didSelectShippingContact(contact: PKContact, completion: @escaping (PKPaymentAuthorizationStatus, [PKShippingMethod], [PKPaymentSummaryItem]) -> Void);
}
public class PaymentOperation: BSApplepayOperation, PKPaymentAuthorizationViewControllerDelegate {
public let request: PKPaymentRequest
private var requestController: PKPaymentAuthorizationViewController!
private var status: PKPaymentAuthorizationStatus = .failure;
public var error: BSErrors?
private let delegate: PaymentOperationDelegate
private var finishCompletion: ((BSErrors?) -> Void)
public init(request: PKPaymentRequest, delegate: PaymentOperationDelegate, completion: @escaping (BSErrors?) -> Void) {
self.request = request
self.finishCompletion = completion
self.requestController = PKPaymentAuthorizationViewController(paymentRequest: request)
self.delegate = delegate
}
public func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController,
didAuthorizePayment payment: PKPayment,
completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {
NSLog("ApplePaymentAuthorizationViewController Validate")
delegate.validate(payment: payment) {
switch $0 {
case .valid:
self.delegate.send(paymentInformation: BSApplePayInfo(payment: payment)) {
if let error = $0 {
self.status = .failure;
self.error = error;
} else {
self.status = .success;
}
completion(self.status);
};
default:
self.status = $0.asPKPaymentStatus()!;
completion(self.status);
}
}
}
public func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didSelect paymentMethod: PKPaymentMethod, completion: @escaping ([PKPaymentSummaryItem]) -> Void) {
delegate.didSelectPaymentMethod(method: paymentMethod, completion: completion);
}
public func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didSelectShippingContact contact: PKContact, completion: @escaping (PKPaymentAuthorizationStatus, [PKShippingMethod], [PKPaymentSummaryItem]) -> Void) {
delegate.didSelectShippingContact(contact: contact, completion: completion);
}
func finish(with error: BSErrors? = nil) {
self.error = error;
self.finish();
}
public func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
NSLog("Apple pay controller finish")
controller.dismiss(animated: true) {
if case .success = self.status {
NSLog("Apple pay controller dismissm successfuly")
self.finish();
self.finishCompletion(nil)
} else if self.status.rawValue > 1 {
NSLog("Apple pay operation error \(self.status.rawValue)")
self.finish(with: BSErrors.applePayOperationError);
} else {
self.finish(with: BSErrors.applePayCanceled);
}
};
}
deinit {
NSLog("BSApplepayOperation deinint");
}
override public func execute() {
if !PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: self.request.supportedNetworks) {
self.finish(with: BSErrors.cantMakePaymentError);
}
self.requestController!.delegate = self;
DispatchQueue.main.async {
UIApplication.shared.keyWindow?.rootViewController?.present(self.requestController, animated: true, completion: nil) ?? {
self.finish(with: BSErrors.unknown);
}()
}
}
}
| mit | 373aea2d67f1915f497b80b50483eb71 | 31.813472 | 255 | 0.646297 | 5.609389 | false | false | false | false |
RockyAo/Dictionary | Dictionary/Classes/Home/View/VocabularyView.swift | 1 | 6610 | //
// WordView.swift
// Dictionary
//
// Created by Rocky on 2017/5/26.
// Copyright © 2017年 Rocky. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Action
class VocabularyView: UIView {
let disposeBag = DisposeBag()
fileprivate lazy var centerSeperateView:UIView = {
return UIView.getSeperateView()
}()
fileprivate lazy var bottomSeperateView:UIView = {
return UIView.getSeperateView()
}()
fileprivate lazy var titleLabel: UILabel = {
let tl = UILabel()
tl.textColor = UIColor.Main.gray.dark
tl.font = UIFont.main.titleFont
tl.sizeToFit()
return tl
}()
lazy var playButton: UIButton = {
let pb = UIButton(type: .custom)
pb.setBackgroundImage(#imageLiteral(resourceName: "home_play_button"), for: .normal)
return pb
}()
lazy var collectionButton: UIButton = {
let cb = UIButton(type: .custom)
cb.setBackgroundImage(#imageLiteral(resourceName: "collect"), for: .normal)
cb.setBackgroundImage(#imageLiteral(resourceName: "select_collect"), for: .selected)
return cb
}()
fileprivate lazy var usPronounceLabel: UILabel = {
let up = UILabel()
up.textColor = UIColor.Main.gray.weak
up.font = UIFont.main.desFont
up.sizeToFit()
return up
}()
fileprivate lazy var ukPronounceLabel: UILabel = {
let up = UILabel()
up.textColor = UIColor.Main.gray.weak
up.font = UIFont.main.desFont
up.sizeToFit()
return up
}()
fileprivate lazy var descriptionLabel: UILabel = {
let dl = UILabel()
dl.textColor = UIColor.Main.gray.middle
dl.font = UIFont.main.desFont
dl.sizeToFit()
dl.numberOfLines = 0
return dl
}()
var data:WordModel?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.left.top.equalTo(25)
}
addSubview(collectionButton)
collectionButton.snp.makeConstraints { (make) in
make.right.equalTo(-25)
make.centerY.equalTo(titleLabel.snp.centerY).offset(0)
make.height.width.equalTo(18)
}
addSubview(playButton)
playButton.snp.makeConstraints { (make) in
make.right.equalTo(collectionButton.snp.left).offset(-25)
make.centerY.equalTo(titleLabel.snp.centerY).offset(1)
make.width.height.equalTo(18)
}
addSubview(usPronounceLabel)
usPronounceLabel.snp.makeConstraints { (make) in
make.left.equalTo(25)
make.top.equalTo(titleLabel.snp.bottom).offset(30)
}
addSubview(ukPronounceLabel)
ukPronounceLabel.snp.makeConstraints { (make) in
make.top.equalTo(usPronounceLabel.snp.bottom).offset(25)
make.left.equalTo(25)
}
addSubview(centerSeperateView)
centerSeperateView.snp.makeConstraints { (make) in
make.top.equalTo(ukPronounceLabel.snp.bottom).offset(25)
make.left.equalTo(25)
make.right.equalTo(0)
make.height.equalTo(0.5)
}
addSubview(descriptionLabel)
descriptionLabel.snp.makeConstraints { (make) in
make.left.equalTo(25)
make.right.equalTo(-25)
make.top.equalTo(centerSeperateView.snp.bottom).offset(25)
}
addSubview(bottomSeperateView)
bottomSeperateView.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(0)
make.top.equalTo(descriptionLabel.snp.bottom).offset(25)
make.height.equalTo(0.5)
}
collectionButton.rx.tap
.asDriver()
.map{ [unowned self] in
return !self.collectionButton.isSelected
}
.drive(collectionButton.rx.isSelected)
.addDisposableTo(disposeBag)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureAction(collectAction:Action<WordModel,WordModel>,playAudioAction:Action<String,Void>) -> Void {
collectionButton.rx.bind(to: collectAction){ _ in
self.data?.selected = self.collectionButton.isSelected
return self.data!
}
playButton.rx.bind(to: playAudioAction){ _ in
return self.data?.finalUrl ?? ""
}
}
}
extension Reactive where Base:VocabularyView{
var configureData:UIBindingObserver<Base,WordModel>{
return UIBindingObserver(UIElement: base, binding: { (wordView, data) in
wordView.data = data
wordView.titleLabel.text = data.query
if let ukString = data.basicTranslation?.ukPhonetic,
let usString = data.basicTranslation?.usPhonetic{
wordView.ukPronounceLabel.text = "英:\(ukString)"
wordView.usPronounceLabel.text = "美:\(usString)"
}else{
wordView.usPronounceLabel.text = ""
wordView.ukPronounceLabel.text = ""
}
guard let explains = data.basicTranslation?.explains else { return }
var desString:String = ""
for text in explains{
desString.append(text)
desString.append("\n")
}
let attrString = NSMutableAttributedString(string: desString)
let style = NSMutableParagraphStyle()
style.lineSpacing = 20
attrString.addAttributes([NSParagraphStyleAttributeName:style], range: NSRange(location: 0, length: desString.characters.count))
wordView.descriptionLabel.attributedText = attrString
wordView.collectionButton.isSelected = data.selected
})
}
}
| agpl-3.0 | 6fb3ee2737894a718d9b27a4a7871f3c | 27.217949 | 140 | 0.553839 | 5.094907 | false | false | false | false |
ccortessanchez/Flo | Flo/Flo/BackgroundView.swift | 1 | 2138 | //
// BackgroundView.swift
// Flo
//
// Created by Carlos Cortés Sánchez on 28/09/2017.
// Copyright © 2017 Carlos Cortés Sánchez. All rights reserved.
//
import UIKit
@IBDesignable class BackgroundView: UIView {
@IBInspectable var lightColor: UIColor = UIColor.orange
@IBInspectable var darkColor: UIColor = UIColor.yellow
@IBInspectable var patternSize: CGFloat = 200
override func draw(_ rect: CGRect) {
//get the view's context
let context = UIGraphicsGetCurrentContext()!
//set fill color of the context
context.setFillColor(darkColor.cgColor)
//fill entire context with the color
context.fill(rect)
let drawSize = CGSize(width: patternSize, height: patternSize)
UIGraphicsBeginImageContextWithOptions(drawSize, true, 0.0)
let drawingContext = UIGraphicsGetCurrentContext()!
//set the fill color for the new context
darkColor.setFill()
drawingContext.fill(CGRect(x: 0, y: 0, width: drawSize.width, height: drawSize.height))
let trianglePath = UIBezierPath()
trianglePath.move(to: CGPoint(x: drawSize.width/2, y: 0))
trianglePath.addLine(to: CGPoint(x: 0, y: drawSize.height/2))
trianglePath.addLine(to: CGPoint(x: drawSize.width, y: drawSize.height/2))
trianglePath.move(to:CGPoint(x: 0, y: drawSize.height/2))
trianglePath.addLine(to: CGPoint(x: drawSize.width/2, y: drawSize.height))
trianglePath.addLine(to: CGPoint(x: 0, y: drawSize.height))
trianglePath.move(to: CGPoint(x: drawSize.width, y: drawSize.height/2))
trianglePath.addLine(to: CGPoint(x: drawSize.width/2, y: drawSize.height))
trianglePath.addLine(to: CGPoint(x: drawSize.width, y: drawSize.height))
lightColor.setFill()
trianglePath.fill()
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
UIColor(patternImage: image).setFill()
context.fill(rect)
}
}
| mit | 3b3699d1ce4464551d02ba4738806229 | 33.967213 | 95 | 0.642288 | 4.557692 | false | false | false | false |
divadretlaw/very | Sources/very/Subcommands/Clean.swift | 1 | 1880 | //
// Clean.swift
// very
//
// Created by David Walter on 05.07.20.
//
import ArgumentParser
import Foundation
extension Very {
struct Clean: ParsableCommand {
@OptionGroup var options: Options
static var configuration = CommandConfiguration(
commandName: "clean",
abstract: "Cleans the system"
)
@Flag(help: "Runs additional clean commands.")
var additional = false
@Flag(help: "Removes contents of directories.")
var directories = false
@Flag(help: "Empties the trash.")
var trash = false
@Flag(help: "Runs all clean commands.")
var wow = false
func run() throws {
try options.load()
let freeSpaceBefore = DiskCommands.getFreeSpace()
if wow {
CleanCommands.all()
} else if anyFlag {
CleanCommands.default()
if trash {
CleanCommands.trash()
}
if additional {
CleanCommands.additional()
}
if directories {
CleanCommands.directories()
}
} else {
CleanCommands.default()
}
guard let bytes = DiskCommands.getFreeSpace(relativeTo: freeSpaceBefore) else {
Log.done()
return
}
let formatter = ByteCountFormatter()
formatter.countStyle = .file
Log.done("\(formatter.string(fromByteCount: Int64(bytes)).cyan) of space was saved.")
}
var anyFlag: Bool {
additional || directories || trash || wow
}
}
}
| apache-2.0 | a84b38eb15f7d829d46e6dfce4d6f0f0 | 25.857143 | 97 | 0.474468 | 5.802469 | false | false | false | false |
RevenueCat/purchases-ios | Contributing/SwiftStyleGuide.swift | 1 | 5876 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// SwiftStyleGuide.swift
//
// Created by Andrés Boedo on 7/12/21.
//
// imports should be alphabetized
import Foundation
// keep one empty line after type declarations, and one before the end of it
protocol ValuePrintable {
// make protocol variables read-only unless needed
func foo() -> String
}
// use protocol extensions for default implementations of protocols for types
extension ValuePrintable where Self: NSNumber {
func foo() -> String {
return "the number as float is: \(self.floatValue)"
}
}
// prefer structs to classes whenever possible.
// keep in mind that structs are value types.
// More info here: https://developer.apple.com/documentation/swift/choosing_between_structures_and_classes
// documentation is required for each public entity.
// Use jazzy-compatible syntax for documentation: https://github.com/realm/jazzy#supported-documentation-keywords
/// The MyStruct struct is responsible for ...
struct MyStruct {
// don't explicitly define types unless needed.
// prefer let to var whenever possible.
// public properties, then internal, then private.
/// mercury is used for ...
public let mercury = false
/// saturn is used for ...
public var saturn: String?
/// eath is used for ...
public static var Earth = "earth"
// use public private(set) when a public var is only written to within the class scope
/// this variable will be readonly to the outside, but variable from inside the scope
public private(set) var onlyReadFromOutside = 2.0
// for internal properties, omit `internal` keyword since it's default
let mars = 4.0
private var jupiter = 2
// use the valuesByKey naming convention for dictionary types
private var productsByIdentifier: [String: Product]
// public methods in the main declaration
/// This method prints the planets
public func foo() {
// use explicit `self` to make it clear that it's accessing a member
// versus a global or value in the local context
print(self.mercury)
}
func whenMethodIsTooLongToFitInOneLine(becauseOfTooMany: Int,
parameters: String,
eachOne: Float,
shouldBeInItsOwnLine: Double) {}
// swiftlint:disable:next multiline_parameters
func whenMethodIsTooLongToFitInOneLine(
becauseOfTooMany: Int,
parameters: String,
eachOne: Float,
shouldBeInItsOwnLine: Double,
// special file / function / line parameters may be grouped together in their own line
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) {
}
}
// separate protocol conformance into extension
// so methods from the protocol are easy to locate
extension MyStruct: MyProtocol {
// return can be omitted for one-liners
func foo() -> String { "foo" }
}
// use protocol-oriented programming to add behaviors to types
// https://developer.apple.com/videos/play/wwdc2015/408/
extension MyStruct: PrettyPrintable { }
// add error extensions to make it easy to map errors to situations
enum MyCustomError: Error {
case invalidDateComponents(_ dateComponents: DateComponents)
case networkError
}
// private methods in an extension
private extension MyStruct {
func somethingPrivate() -> String {
return Bool.random() ? .saturn : .nepturn
}
func someMethodThatThrows() throws {
throw Bool.random() ? MyCustomError.invalidDateComponents(DateComponents())
: MyCustomError.networkError
}
func methodThatNeedsToCaptureSelf() {
// great guide on when and when not to capture self strongly
// https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html#ID56
// no need to explicitly capture self if you need a strong reference
foo.methodThatNeedsStrongCapture {
// ...
self.bar()
}
// but of course we do add it for weak references
foo.methodThatNeedsWeakCapture { [weak self] in
// we need to make self strong again, because the object could be dealloc'ed while
// this completion block is running.
// so we capture it strongly only within the scope of this completion block.
guard let self = self else { return }
// from this point on, you can use self as usual
self.doThings()
// ...
}
}
}
// use private extensions of basic types to define constants
private extension String {
static let saturn = "saturn"
static let neptune = "neptune"
}
// Use one line per let in a guard with multiple lets.
let taco = restaurant.order("taco")
let coffee = restaurant.order("coffee")
guard let taco = taco,
let coffee = coffee else {
return
}
// Also use one line per condition.
guard 1 == 1,
2 == 2,
3 == 3 else {
print("Universe is broken")
return
}
// use _ = Task<Void, Never> for task initialization, so that if a part of the
// Task throws, the compiler forces us to handle the exception
// More info here: https://rev.cat/catching-exceptions-from-tasks
_ = Task<Void, Never> { // Note: this implicitly captures `self`, so have to think about retain cycles.
try await self.myMethodThatThrows()
}
// Alternatively, if possible, store a reference to the task to call `cancel()`
// on `deinit`.
self.taskHandle = Task { [weak self] in
try await self?.myMethod()
}
| mit | 666e9c3fb5a6403a32cd23ef8c23dd1e | 30.25 | 113 | 0.667234 | 4.508826 | false | false | false | false |
apple/swift-syntax | Tests/SwiftParserTest/translated/OperatorDeclDesignatedTypesTests.swift | 1 | 8157 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test file has been translated from swift/test/Parse/operator_decl_designated_types.swift
import XCTest
final class OperatorDeclDesignatedTypesTests: XCTestCase {
func testOperatorDeclDesignatedTypes1() {
AssertParse(
"""
precedencegroup LowPrecedence {
associativity: right
}
"""
)
}
func testOperatorDeclDesignatedTypes2() {
AssertParse(
"""
precedencegroup MediumPrecedence {
associativity: left
higherThan: LowPrecedence
}
"""
)
}
func testOperatorDeclDesignatedTypes3() {
AssertParse(
"""
protocol PrefixMagicOperatorProtocol {
}
"""
)
}
func testOperatorDeclDesignatedTypes4() {
AssertParse(
"""
protocol PostfixMagicOperatorProtocol {
}
"""
)
}
func testOperatorDeclDesignatedTypes5() {
AssertParse(
"""
protocol InfixMagicOperatorProtocol {
}
"""
)
}
func testOperatorDeclDesignatedTypes6() {
AssertParse(
"""
prefix operator ^^ : PrefixMagicOperatorProtocol
infix operator <*< : MediumPrecedence, InfixMagicOperatorProtocol
postfix operator ^^ : PostfixMagicOperatorProtocol
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler; please remove the designated type list from this operator declaration, Fix-It replacements: 20 - 49 = ''
// TODO: Old parser expected warning on line 2: designated types are no longer used by the compiler, Fix-It replacements: 39 - 67 = ''
// TODO: Old parser expected warning on line 3: designated types are no longer used by the compiler, Fix-It replacements: 21 - 51 = ''
]
)
}
func testOperatorDeclDesignatedTypes7() {
AssertParse(
"""
infix operator ^*^
prefix operator *^^
postfix operator ^^*
"""
)
}
func testOperatorDeclDesignatedTypes8() {
AssertParse(
"""
infix operator **>> : UndeclaredPrecedence
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler, Fix-It replacements: 21 - 43 = ''
]
)
}
func testOperatorDeclDesignatedTypes9() {
AssertParse(
"""
infix operator **+> : MediumPrecedence, UndeclaredProtocol
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler, Fix-It replacements: 39 - 59 = ''
]
)
}
func testOperatorDeclDesignatedTypes10() {
AssertParse(
"""
prefix operator *+*> : MediumPrecedence
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler, Fix-It replacements: 22 - 40 = ''
]
)
}
func testOperatorDeclDesignatedTypes11() {
AssertParse(
"""
postfix operator ++*> : MediumPrecedence
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler, Fix-It replacements: 23 - 41 = ''
]
)
}
func testOperatorDeclDesignatedTypes12() {
AssertParse(
"""
prefix operator *++> : UndeclaredProtocol
postfix operator +*+> : UndeclaredProtocol
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler, Fix-It replacements: 22 - 42 = ''
// TODO: Old parser expected warning on line 2: designated types are no longer used by the compiler, Fix-It replacements: 23 - 43 = ''
]
)
}
func testOperatorDeclDesignatedTypes13() {
AssertParse(
"""
struct Struct {}
class Class {}
infix operator *>*> : Struct
infix operator >**> : Class
""",
diagnostics: [
// TODO: Old parser expected warning on line 3: designated types are no longer used by the compiler, Fix-It replacements: 21 - 29 = ''
// TODO: Old parser expected warning on line 4: designated types are no longer used by the compiler, Fix-It replacements: 21 - 28 = ''
]
)
}
func testOperatorDeclDesignatedTypes14() {
AssertParse(
"""
prefix operator **>> : Struct
prefix operator *>*> : Class
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler, Fix-It replacements: 22 - 30 = ''
// TODO: Old parser expected warning on line 2: designated types are no longer used by the compiler, Fix-It replacements: 22 - 29 = ''
]
)
}
func testOperatorDeclDesignatedTypes15() {
AssertParse(
"""
postfix operator >*>* : Struct
postfix operator >>** : Class
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler, Fix-It replacements: 23 - 31 = ''
// TODO: Old parser expected warning on line 2: designated types are no longer used by the compiler, Fix-It replacements: 23 - 30 = ''
]
)
}
func testOperatorDeclDesignatedTypes16() {
AssertParse(
"""
infix operator <*<<< : MediumPrecedence, &
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler, Fix-It replacements: 41 - 44 = ''
]
)
}
func testOperatorDeclDesignatedTypes17() {
AssertParse(
"""
infix operator **^^ : MediumPrecedence
infix operator **^^ : InfixMagicOperatorProtocol
""",
diagnostics: [
// TODO: Old parser expected warning on line 2: designated types are no longer used by the compiler, Fix-It replacements: 21 - 50 = ''
]
)
}
func testOperatorDeclDesignatedTypes18() {
AssertParse(
"""
infix operator ^%*%^ : MediumPrecedence, Struct, Class
infix operator ^%*%% : Struct, Class
prefix operator %^*^^ : Struct, Class
postfix operator ^^*^% : Struct, Class
prefix operator %%*^^ : LowPrecedence, Class
postfix operator ^^*%% : MediumPrecedence, Class
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler, Fix-It replacements: 40 - 55 = ''
// TODO: Old parser expected warning on line 2: designated types are no longer used by the compiler, Fix-It replacements: 30 - 37 = ''
// TODO: Old parser expected warning on line 2: designated types are no longer used by the compiler, Fix-It replacements: 22 - 30 = ''
// TODO: Old parser expected warning on line 3: designated types are no longer used by the compiler, Fix-It replacements: 23 - 38 = ''
// TODO: Old parser expected warning on line 4: designated types are no longer used by the compiler, Fix-It replacements: 24 - 39 = ''
// TODO: Old parser expected warning on line 5: designated types are no longer used by the compiler, Fix-It replacements: 23 - 45 = ''
// TODO: Old parser expected warning on line 6: designated types are no longer used by the compiler, Fix-It replacements: 24 - 49 = ''
]
)
}
func testOperatorDeclDesignatedTypes19() {
AssertParse(
"""
infix operator <*<>*> : AdditionPrecedence,
""",
diagnostics: [
// TODO: Old parser expected warning on line 1: designated types are no longer used by the compiler, Fix-It replacements: 43 - 44 = ''
]
)
}
}
| apache-2.0 | a838115016752500ff0078e2befd443c | 32.293878 | 213 | 0.618978 | 4.982896 | false | true | false | false |
vapor/node | Sources/Node/StructuredData/StructuredData+Init.swift | 1 | 1345 | extension StructuredDataWrapper {
public init(_ value: Bool, in context: Context? = Self.defaultContext) {
self = .bool(value, in: context)
}
public init(_ value: String, in context: Context? = Self.defaultContext) {
self = .string(value, in: context)
}
public init(_ int: Int, in context: Context? = Self.defaultContext) {
self = .number(StructuredData.Number(int), in: context)
}
public init(_ double: Double, in context: Context? = Self.defaultContext) {
self = .number(StructuredData.Number(double), in: context)
}
public init(_ uint: UInt, in context: Context? = Self.defaultContext) {
self = .number(StructuredData.Number(uint), in: context)
}
public init(_ number: StructuredData.Number, in context: Context? = Self.defaultContext) {
self = .number(number, in: context)
}
public init(_ value: [StructuredData], in context: Context? = Self.defaultContext) {
let array = StructuredData.array(value)
self.init(array, in: context)
}
public init(_ value: [String : StructuredData], in context: Context? = Self.defaultContext) {
self = Self(.object(value), in: context)
}
public init(bytes: [UInt8], in context: Context? = Self.defaultContext) {
self = .bytes(bytes, in: context)
}
}
| mit | 0136309ccd8649b516163065d953f497 | 34.394737 | 97 | 0.637918 | 3.944282 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureCryptoDomain/Sources/FeatureCryptoDomainUI/Accessibility+CryptoDomain.swift | 1 | 2918 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
enum AccessibilityIdentifiers {
// MARK: - How it Works Sceren
enum HowItWorks {
static let prefix = "HowItWorksScreen."
static let headerTitle = "\(prefix)headerTitle"
static let headerDescription = "\(prefix)headerDescription"
static let introductionList = "\(prefix)instructionList"
static let smallButton = "\(prefix)smallButton"
static let instructionText = "\(prefix)instructionText"
static let ctaButton = "\(prefix)ctaButton"
}
// MARK: - Benefits Screen
enum Benefits {
static let prefix = "CryptoDomainBenefitsScreen."
static let headerTitle = "\(prefix)headerTitle"
static let headerDescription = "\(prefix)headerDescription"
static let benefitsList = "\(prefix)benefitsList"
static let ctaButton = "\(prefix)ctaButton"
}
// MARK: - Search Domain Screen
enum SearchDomain {
static let prefix = "SearchDomainScreen."
static let searchBar = "\(prefix)searchBar"
static let alertCard = "\(prefix)alertCard"
static let domainList = "\(prefix)domainList"
static let domainListRow = "\(prefix)domainListRow"
}
// MARK: - Domain Checkout Screen
enum DomainCheckout {
static let prefix = "DomainCheckoutScreen."
static let selectedDomainList = "\(prefix)selectedDomainList"
static let termsSwitch = "\(prefix)termsSwitch"
static let termsText = "\(prefix)termsText"
static let ctaButton = "\(prefix)ctaButton"
static let emptyStateIcon = "\(prefix)emptyStateIcon"
static let emptyStateTitle = "\(prefix)emptyStateTitle"
static let emptyStateDescription = "\(prefix)emptyStateDescription"
static let browseButton = "\(prefix)browseButton"
}
enum RemoveDomainBottomSheet {
static let prefix = "RemoveDomainBottomSheet."
static let removeIcon = "\(prefix)removeIcon"
static let removeTitle = "\(prefix)removeTitle"
static let removeButton = "\(prefix)removeButton"
static let nevermindButton = "\(prefix)nevermindButton"
}
enum BuyDomainBottomSheet {
static let prefix = "BuyDomainBottomSheet."
static let buyTitle = "\(prefix)buyTitle"
static let buyDescription = "\(prefix)buyTitle"
static let buyButton = "\(prefix)buyButton"
static let goBackButton = "\(prefix)goBackButton"
}
// MARK: - Checkout Confirmation Screen
enum CheckoutConfirmation {
static let prefix = "DomainCheckoutConfirmationScreen."
static let icon = "\(prefix)icon"
static let title = "\(prefix)title"
static let description = "\(prefix)description"
static let learnMoreButton = "\(prefix)learnMoreButton"
static let okayButton = "\(prefix)okayButton"
}
}
| lgpl-3.0 | cb158e47f0c258ac74d35c88f43f8a09 | 36.883117 | 75 | 0.661981 | 4.952462 | false | false | false | false |
PJayRushton/stats | Stats/GameViewController.swift | 1 | 13642 | //
// GameViewController.swift
// Stats
//
// Created by Parker Rushton on 4/18/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import UIKit
import IGListKit
import LTMorphingLabel
import Presentr
class GameViewController: Component, AutoStoryboardInitializable {
@IBOutlet weak var settingsButton: UIBarButtonItem!
@IBOutlet weak var awayTeamLabel: UILabel!
@IBOutlet weak var scoreLabel: LTMorphingLabel!
@IBOutlet weak var homeTeamLabel: UILabel!
@IBOutlet weak var inningOutStack: UIStackView!
@IBOutlet weak var previousInningButton: UIButton!
@IBOutlet weak var inningLabel: LTMorphingLabel!
@IBOutlet weak var nextInningButton: UIButton!
@IBOutlet weak var playerHolderView: UIView!
@IBOutlet weak var playerPickerView: AKPickerView!
@IBOutlet weak var newAtBatView: UIView!
@IBOutlet weak var plusImageView: UIImageView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet var outButtons: [UIButton]!
@IBOutlet weak var emptyLineupView: UIView!
fileprivate lazy var adapter: ListAdapter = {
return ListAdapter(updater: ListAdapterUpdater(), viewController: self, workingRangeSize: 0)
}()
fileprivate var scorePresenter: Presentr {
let centerPoint = CGPoint(x: view.center.x, y: view.center.y - 100)
let customPresentation = PresentationType.custom(width: ModalSize.custom(size: 250), height: .custom(size: 300), center: ModalCenterPosition.custom(centerPoint: centerPoint))
let presenter = Presentr(presentationType: customPresentation)
presenter.transitionType = TransitionType.coverHorizontalFromRight
presenter.dismissTransitionType = TransitionType.coverHorizontalFromRight
return presenter
}
var currentPlayer: Player? {
return core.state.gameState.currentPlayer
}
var gamePlayers: [Player] {
guard let game = game else { return [] }
return game.lineupIds.compactMap { core.state.playerState.player(withId: $0) }
}
var currentAtBats: [AtBat] {
guard let player = currentPlayer, let game = game else { return [] }
return core.state.atBatState.atBats(for: player, in: game).sorted(by: { $0.creationDate > $1.creationDate })
}
var game: Game? {
return core.state.gameState.currentGame
}
var names = [String]() {
didSet {
if names != oldValue {
playerPickerView.reloadData()
}
}
}
var hasEditRights: Bool {
guard let currentUser = core.state.userState.currentUser, let team = core.state.teamState.currentTeam else { return false }
return currentUser.isOwnerOrManager(of: team)
}
override func viewDidLoad() {
super.viewDidLoad()
adapter.collectionView = collectionView
adapter.dataSource = self
guard let game = game else { return }
if let player = gamePlayers.first {
core.fire(event: Selected<Player>(player))
}
updateUI(with: game)
plusImageView.tintColor = .white
scoreLabel.morphingEffect = .fall
previousInningButton?.isHidden = game.isCompleted || !hasEditRights
nextInningButton?.isHidden = game.isCompleted || !hasEditRights
previousInningButton?.tintColor = .icon
nextInningButton?.tintColor = .icon
inningLabel.morphingEffect = .scale
setUpPickerView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
scoreLabel.text = game?.scoreString
}
@IBAction func settingsTapped(_ sender: UIBarButtonItem) {
showOptionsForGame()
}
@IBAction func scoreLabelPressed(_ sender: Any) {
let scoreEditVC = OpponentScoreViewController.initializeFromStoryboard()
customPresentViewController(scorePresenter, viewController: scoreEditVC, animated: true, completion: nil)
}
@IBAction func inningArrowPressed(_ sender: UIButton) {
guard let game = game, hasEditRights else { return }
let previousButtonWasPressed = sender == previousInningButton
let newInning = previousButtonWasPressed ? game.inning - 1 : game.inning + 1
updateInning(newInning)
}
@IBAction func newAtBatPressed(_ sender: UITapGestureRecognizer) {
self.presentAtBatCreation()
}
@IBAction func outButtonPressed(_ sender: UIButton) {
guard let index = outButtons.index(of: sender) else { return }
let outs = game?.outs ?? 0
if outs == 2 && index == 2 {
saveOuts(outs: 3)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
self.saveOuts(outs: 0)
self.updateInning()
})
} else if index == outs {
saveOuts(outs: outs + 1)
} else {
saveOuts(outs: outs - 1)
}
}
@IBAction func emptyLineupButtonPressed(_ sender: Any) {
presentGameEditVC(lineup: true)
}
// MARK: - Subscriber
override func update(with state: AppState) {
if let game = game {
updateUI(with: game)
updatePicker(game: game)
if scoreLabel.text != "-" {
scoreLabel.text = game.scoreString
}
}
var playerNames = gamePlayers.map { $0.name }
if playerNames.count > 1 {
playerNames.append("⬅️")
}
names = playerNames
updateOuts(outs: game?.outs ?? 0)
adapter.performUpdates(animated: true)
}
fileprivate func updateOuts(outs: Int) {
for (index, button) in outButtons.enumerated() {
button.isEnabled = index <= outs
if index > outs {
button.alpha = 0
} else if index == outs {
button.alpha = 0.3
} else {
button.alpha = 1
}
}
}
}
extension GameViewController {
fileprivate func updateUI(with game: Game) {
if let team = core.state.teamState.currentTeam {
awayTeamLabel.text = game.isHome ? game.opponent : team.name
homeTeamLabel.text = game.isHome ? team.name : game.opponent
navigationItem.rightBarButtonItem = hasEditRights ? settingsButton : nil
}
let hasLineupPlayers = !game.lineupIds.isEmpty
inningOutStack.isHidden = game.isCompleted
newAtBatView.isHidden = game.isCompleted || !hasLineupPlayers
inningLabel.text = game.status
previousInningButton?.tintColor = game.inning == 1 ? .white : .icon
previousInningButton?.isEnabled = game.inning > 1
playerHolderView.isHidden = !hasLineupPlayers
emptyLineupView.isHidden = hasLineupPlayers
collectionView.isHidden = !hasLineupPlayers
}
fileprivate func updatePicker(game: Game) {
guard let currentPlayer = core.state.gameState.currentPlayer,
let index = game.lineupIds.index(of: currentPlayer.id),
playerPickerView.selectedItem != index else { return }
playerPickerView.selectItem(index, animated: true)
}
fileprivate func updateInning(_ inning: Int? = nil) {
guard var updatedGame = game, hasEditRights else { return }
let newInning = inning ?? updatedGame.inning + 1
updatedGame.inning = newInning
updatedGame.outs = 0
core.fire(command: UpdateObject(updatedGame))
}
fileprivate func showOptionsForGame() {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Edit Game ✏️", style: .default, handler: { _ in
self.editGamePressed()
}))
let emojiForStatus = game != nil && game!.score > game!.opponentScore ? "😎" : "😞"
let endGameAction = UIAlertAction(title: "End Game \(emojiForStatus)", style: .default, handler: { _ in
self.changeGameCompletion(isCompleted: true)
})
if let game = game, !game.isCompleted {
alert.addAction(endGameAction)
}
alert.addAction(UIAlertAction(title: "Delete game ☠️", style: .destructive, handler: { _ in
self.presentConfirmationAlert()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
fileprivate func editGamePressed() {
guard let game = game else { return }
if game.isCompleted {
self.changeGameCompletion(isCompleted: false)
} else {
self.presentGameEditVC()
}
}
func presentAtBatCreation() {
let newAtBatVC = AtBatCreationViewController.initializeFromStoryboard()
newAtBatVC.showOpponentScoreEdit = {
self.scoreLabelPressed(self)
}
newAtBatVC.modalPresentationStyle = .overFullScreen
present(newAtBatVC, animated: false, completion: nil)
}
func presentAtBatEdit(atBat: AtBat) {
guard let game = game, !game.isCompleted else { return }
let newAtBatVC = AtBatCreationViewController.initializeFromStoryboard()
newAtBatVC.editingAtBat = atBat
newAtBatVC.modalPresentationStyle = .overFullScreen
present(newAtBatVC, animated: false, completion: nil)
}
fileprivate func presentGameEditVC(lineup: Bool = false) {
let gameCreationVC = GameCreationViewController.initializeFromStoryboard()
gameCreationVC.editingGame = game
gameCreationVC.showLineup = lineup
let gameCreationNav = gameCreationVC.embededInNavigationController
gameCreationVC.modalPresentationStyle = .overFullScreen
present(gameCreationNav, animated: true, completion: nil)
}
fileprivate func changeGameCompletion(isCompleted: Bool) {
guard var game = game, hasEditRights else { return }
game.isCompleted = isCompleted
core.fire(command: UpdateObject(game))
if isCompleted {
core.fire(command: SaveGameStats(for: game))
core.fire(command: UpdateTrophies(for: game))
core.fire(event: UpdateRecentlyCompletedGame(game: game))
navigationController?.popViewController(animated: true)
}
}
fileprivate func saveOuts(outs: Int) {
guard var game = game, hasEditRights else { return }
game.outs = outs
core.fire(command: UpdateObject(game))
}
fileprivate func presentConfirmationAlert() {
let alert = Presentr.alertViewController(title: "Are you sure?", body: "This cannot be undone")
alert.addAction(AlertAction(title: "Cancel 😳", style: .cancel, handler: nil))
alert.addAction(AlertAction(title: "☠️", style: .destructive) { _ in
guard let game = self.game, self.hasEditRights else { return }
self.core.fire(command: DeleteGame(game))
_ = self.navigationController?.popToRootViewController(animated: true)
})
customPresentViewController(alertPresenter, viewController: alert, animated: true, completion: nil)
}
}
extension GameViewController: ListAdapterDataSource {
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
var objects = [ListDiffable]()
for (index, atBat) in currentAtBats.enumerated() {
objects.append(AtBatSection(atBat: atBat, order: currentAtBats.count - index))
}
return objects
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
guard let game = game else { fatalError() }
let canEdit = hasEditRights && !game.isCompleted
let atBatSectionController = AtBatSectionController(canEdit: canEdit)
atBatSectionController.didSelectAtBat = { [weak self] atBat in
guard let weakSelf = self else { return }
guard weakSelf.hasEditRights else { return }
weakSelf.presentAtBatEdit(atBat: atBat)
}
return atBatSectionController
}
func emptyView(for listAdapter: ListAdapter) -> UIView? {
return nil
}
}
// MARK: - AKPickerView
extension GameViewController: AKPickerViewDelegate, AKPickerViewDataSource {
func setUpPickerView() {
playerPickerView.delegate = self
playerPickerView.dataSource = self
playerPickerView.font = FontType.lemonMilk.font(withSize: 15)
playerPickerView.highlightedFont = FontType.lemonMilk.font(withSize: 16)
playerPickerView.highlightedTextColor = UIColor.secondaryAppColor
playerPickerView.interitemSpacing = 32
playerPickerView.pickerViewStyle = .flat
}
func numberOfItemsInPickerView(_ pickerView: AKPickerView) -> Int {
return names.count
}
func pickerView(_ pickerView: AKPickerView, titleForItem item: Int) -> String {
return names[item]
}
func pickerView(_ pickerView: AKPickerView, didSelectItem item: Int) {
if item == gamePlayers.count {
pickerView.selectItem(0, animated: true)
} else {
core.fire(event: Selected<Player>(gamePlayers[item]))
}
}
}
// MARK: - SegueHandling
extension GameViewController: SegueHandling {
enum SegueIdentifier: String {
case presentAtBatCreation
}
}
| mit | dc93438003dc477546af50b572ec89e8 | 35.899729 | 182 | 0.643434 | 4.980249 | false | false | false | false |
eBay/NMessenger | nMessenger/Source/MessageNodes/BubbleConfiguration/StandardBubbleConfiguration.swift | 4 | 1913 | //
// Copyright (c) 2016 eBay Software Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import UIKit
/** Uses a default bubble as primary and a stacked bubble as secondary. Incoming color is pale grey and outgoing is blue */
open class StandardBubbleConfiguration: BubbleConfigurationProtocol {
open var isMasked = false
public init() {}
open func getIncomingColor() -> UIColor
{
return UIColor.n1PaleGreyColor()
}
open func getOutgoingColor() -> UIColor
{
return UIColor.n1ActionBlueColor()
}
open func getBubble() -> Bubble
{
let newBubble = DefaultBubble()
newBubble.hasLayerMask = isMasked
return newBubble
}
open func getSecondaryBubble() -> Bubble
{
let newBubble = StackedBubble()
newBubble.hasLayerMask = isMasked
return newBubble
}
}
| mit | d0ddc05b76fb4133179bed685765e7e9 | 42.477273 | 463 | 0.726607 | 5.007853 | false | false | false | false |
tianbinbin/DouYuShow | DouYuShow/DouYuShow/Classes/Home/Model/RecommendViewModel.swift | 1 | 3168 | //
// RecommendViewModel.swift
// DouYuShow
//
// Created by 田彬彬 on 2017/6/4.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
class RecommendViewModel {
// 懒加载一个数组 存放 解析过后的模型
fileprivate lazy var anChorArr:[AnchorGroup] = [AnchorGroup]()
}
// mark: 发送网络请求
extension RecommendViewModel{
func requestData(){
//1. 请求第一部分推荐数据
// http://capi.douyucdn.cn/api/v1/getbigDataRoom
//2. 请求第二部分颜值数据
// http://capi.douyucdn.cn/api/v1/getVerticalRoom
//3. 请求第三部分的游戏数据
// http://capi.douyucdn.cn/api/v1/getHotCate?limit=4&offset=0&time=1496581342
// print(NSDate.getCurrentTime())
NetWorkTools.RequestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters:["limit":"4","offset":"0","time":NSDate.getCurrentTime() as NSString], SuccessCallBack: { (reslut) in
// 将 reslut 由 (Anyobject) 类型 转换成 [String:NSObject] 字典类型
guard let reslutDict = reslut as? [String:Any] else {
print("reslut先由(Anyobject) 类型 转换成 [String:NSObject]? 如果转换成功那么 reslut 将变成 [String:NSObject]? 类型 ,然后通过guard 可选绑定 由[String:NSObject]? 类型转换成 [String:NSObject] 如果转换成功 那么 reslutDict 就是[String:NSObject] 类型 如果转换失败 那么就会输出这段文字")
return
}
/*
let data = reslutDict["data"]
let dataArray = data as? [[String:NSObject]]
reslutDict 是一个 [String:NSObject] 类型 字典中取出可能取出NSObject 也可能取出nil
所以 data 是一个 NSObject?
然后 将 data 通过 as? 转换成一个数组的可选类型[]? 这个数组[]? 里面存储的是一个 [String:NSObject] 字典类型
所以 dataArray 的类型就是一个 [[String:NSObject]]? 类型
// 这一步是通过可选绑定 将 reslutDict["data"] as? [[String:NSObject]] 由原来的 [[String:NSObject]] ? 转换成[[String:NSObject]] 类型
guard let dataArray = reslutDict["data"] as? [[String:NSObject]] else { return }
*/
guard let dataArray = reslutDict["data"] as? [[String:Any]] else { return }
// 遍历 dataArray 使用kvc的形式将字典 转换成模型对象
for dict in dataArray{
let group = AnchorGroup(dict:dict)
self.anChorArr.append(group)
}
for group in self.anChorArr{
print(group.tag_name)
}
}) { (reslut) in
print(reslut)
}
}
}
| mit | feee0c9e7e679cbc4635d62b2c3246e6 | 27.242105 | 234 | 0.520313 | 4.362602 | false | false | false | false |
stevestreza/Relayout | Framework/Layout/TraitCollectionLayout.swift | 1 | 10487 | #if os(iOS) || os(tvOS)
import UIKit
/**
* A LayingOut object that returns NSLayoutConstraint objects only when the rootView has certain
* traits in its UITraitCollection.
*
* Not available on OS X.
*/
public struct TraitCollectionLayout: LayingOut {
/// The UITraitCollection to match traits against.
let matchingTraitCollection: UITraitCollection
/// The LayingOut object to derive NSLayoutConstraint objects from if the rootView contains the
/// traits in the `matchingTraitCollection`.
let layout: LayingOut
/**
Creates a new TraitCollectionLayout checking against a given UITraitCollection and returning
the NSLayoutConstraint objects from a given LayingOut object.
- parameter matching: The UITraitCollection to match traits against.
- parameter layout: The LayingOut object to derive NSLayoutConstraint objects from if the
rootView contains the traits in the `matchingTraitCollection`.
- returns: A new TraitCollectionLayout checking against a given UITraitCollection and returning
the NSLayoutConstraint objects from a given LayingOut object.
*/
public init(matching: UITraitCollection, layout: LayingOut) {
self.matchingTraitCollection = matching
self.layout = layout
}
/**
Returns the NSLayoutConstraint objects from the given LayingOut object if the `view` contains
the traits in the `matchingTraitCollection`, or an empty Array<NSLayoutConstraint> if not.
- parameter view: The root view to generate NSLayoutConstraint objects for.
- returns: An Array<NSLayoutConstraint> to use for the given view.
*/
public func constraints(in view: UIView) -> [NSLayoutConstraint] {
let traitCollection = view.traitCollection
if traitCollection.containsTraitsInCollection(matchingTraitCollection) {
return layout.constraints(in: view)
}
else {
return []
}
}
}
public extension TraitCollectionLayout {
/**
Creates a new TraitCollectionLayout checking against given traits and returning the
NSLayoutConstraint objects from a given LayingOut object if they match.
- parameter idiom: A UIUserInfterfaceIdiom to check against, or nil if you don't
want to check against it
- parameter scale: A display scale to check against, or nil if you don't want to
check against it
- parameter horizontalSizeClass: A horizontal UIUserInterfaceSizeClass to check against, or nil
if you don't want to check against it
- parameter verticalSizeClass: A vertical UIUserInterfaceSizeClass to check against, or nil
if you don't want to check against it
- parameter layout: The LayingOut object to derive NSLayoutConstraint objects from if the
rootView contains the traits in the `matchingTraitCollection`.
- returns: A new TraitCollectionLayout checking against a given UITraitCollection and returning
the NSLayoutConstraint objects from a given LayingOut object.
*/
public init(
userInterfaceIdiom idiom: UIUserInterfaceIdiom? = nil,
displayScale scale: CGFloat? = nil,
horizontalSizeClass: UIUserInterfaceSizeClass? = nil,
verticalSizeClass: UIUserInterfaceSizeClass? = nil,
layout: LayingOut
) {
let traitCollection = UITraitCollection(userInterfaceIdiom: idiom, displayScale: scale, horizontalSizeClass: horizontalSizeClass, verticalSizeClass: verticalSizeClass)
self.init(matching: traitCollection, layout: layout)
}
}
extension LayingOut {
/**
Creates a new TraitCollectionLayout checking against a given user interface idiom and returning
the NSLayoutConstraint objects from the called LayingOut object if they match.
- parameter idiom: A UIUserInfterfaceIdiom to check against
- returns: A new TraitCollectionLayout checking against a given UITraitCollection and returning
the NSLayoutConstraint objects from the called LayingOut object.
*/
func when(userInterfaceIdiom idiom: UIUserInterfaceIdiom) -> TraitCollectionLayout {
return TraitCollectionLayout(userInterfaceIdiom: idiom, layout: self)
}
/**
Creates a new TraitCollectionLayout checking against a given display scale and returning
the NSLayoutConstraint objects from the called LayingOut object if they match.
- parameter scale: A display scale to check against
- returns: A new TraitCollectionLayout checking against a given UITraitCollection and returning
the NSLayoutConstraint objects from the called LayingOut object.
*/
func when(displayScale scale: CGFloat) -> TraitCollectionLayout {
return TraitCollectionLayout(displayScale: scale, layout: self)
}
/**
Creates a new TraitCollectionLayout checking against a given horizontal size class and
returning the NSLayoutConstraint objects from the called LayingOut object if they match.
- parameter horizontalSizeClass: A horizontal UIUserInterfaceSizeClass to check against
- returns: A new TraitCollectionLayout checking against a given UITraitCollection and returning
the NSLayoutConstraint objects from the called LayingOut object.
*/
func when(horizontalSizeClass sizeClass: UIUserInterfaceSizeClass) -> TraitCollectionLayout {
return TraitCollectionLayout(horizontalSizeClass: sizeClass, layout: self)
}
/**
Creates a new TraitCollectionLayout checking against a given vertical size class and returning
the NSLayoutConstraint objects from the called LayingOut object if they match.
- parameter verticalSizeClass: A vertical UIUserInterfaceSizeClass to check against
- returns: A new TraitCollectionLayout checking against a given UITraitCollection and returning
the NSLayoutConstraint objects from the called LayingOut object.
*/
func when(verticalSizeClass sizeClass: UIUserInterfaceSizeClass) -> TraitCollectionLayout {
return TraitCollectionLayout(verticalSizeClass: sizeClass, layout: self)
}
/**
Creates a new TraitCollectionLayout checking against given size classes and returning
the NSLayoutConstraint objects from the called LayingOut object if they match.
- parameter horizontalSizeClass: A horizontal UIUserInterfaceSizeClass to check against
- parameter verticalSizeClass: A vertical UIUserInterfaceSizeClass to check against
- returns: A new TraitCollectionLayout checking against a given UITraitCollection and returning
the NSLayoutConstraint objects from the called LayingOut object.
*/
func when(horizontalSizeClass horizontalSizeClass: UIUserInterfaceSizeClass, verticalSizeClass: UIUserInterfaceSizeClass) -> TraitCollectionLayout {
return TraitCollectionLayout(horizontalSizeClass: horizontalSizeClass, verticalSizeClass: verticalSizeClass, layout: self)
}
/// Creates a new TraitCollectionLayout checking if the user interface idiom is a phone and
/// returning the NSLayoutConstraint objects from the called LayingOut object if they match.
var whenPhone: TraitCollectionLayout {
return when(userInterfaceIdiom: .Phone)
}
/// Creates a new TraitCollectionLayout checking if the user interface idiom is a pad and
/// returning the NSLayoutConstraint objects from the called LayingOut object if they match.
var whenPad: TraitCollectionLayout {
return when(userInterfaceIdiom: .Pad)
}
/// Creates a new TraitCollectionLayout checking if the user interface idiom is a TV and
/// returning the NSLayoutConstraint objects from the called LayingOut object if they match.
@available(iOS 9, *)
var whenTV: TraitCollectionLayout {
return when(userInterfaceIdiom: .TV)
}
/// Creates a new TraitCollectionLayout checking if the user interface idiom is in CarPlay mode
/// and returning the NSLayoutConstraint objects from the called LayingOut object if they match.
@available(iOS 9, *)
var whenCarPlay: TraitCollectionLayout {
return when(userInterfaceIdiom: .CarPlay)
}
/// Creates a new TraitCollectionLayout checking if the user interface idiom is horizontally
/// compact and returning the NSLayoutConstraint objects from the called LayingOut object if
/// they match.
var whenHorizontallyCompact: TraitCollectionLayout {
return when(horizontalSizeClass: .Compact)
}
/// Creates a new TraitCollectionLayout checking if the user interface idiom is horizontally
/// regular and returning the NSLayoutConstraint objects from the called LayingOut object if
/// they match.
var whenHorizontallyRegular: TraitCollectionLayout {
return when(horizontalSizeClass: .Regular)
}
/// Creates a new TraitCollectionLayout checking if the user interface idiom is vertically
/// compact and returning the NSLayoutConstraint objects from the called LayingOut object if
/// they match.
var whenVerticallyCompact: TraitCollectionLayout {
return when(verticalSizeClass: .Compact)
}
/// Creates a new TraitCollectionLayout checking if the user interface idiom is vertically
/// regular and returning the NSLayoutConstraint objects from the called LayingOut object if
/// they match.
var whenVerticallyRegular: TraitCollectionLayout {
return when(verticalSizeClass: .Regular)
}
}
private extension UITraitCollection {
private convenience init(
userInterfaceIdiom idiom: UIUserInterfaceIdiom? = nil,
displayScale scale: CGFloat? = nil,
horizontalSizeClass: UIUserInterfaceSizeClass? = nil,
verticalSizeClass: UIUserInterfaceSizeClass? = nil
) {
var collections: [UITraitCollection] = []
if let idiom = idiom {
collections.append(UITraitCollection(userInterfaceIdiom: idiom))
}
if let scale = scale {
collections.append(UITraitCollection(displayScale: scale))
}
if let horizontalSizeClass = horizontalSizeClass {
collections.append(UITraitCollection(horizontalSizeClass: horizontalSizeClass))
}
if let verticalSizeClass = verticalSizeClass {
collections.append(UITraitCollection(verticalSizeClass: verticalSizeClass))
}
self.init(traitsFromCollections: collections)
}
}
#endif
| isc | 8abbf624d222095a6035ed2f8efc004f | 43.625532 | 175 | 0.736626 | 6.238548 | false | false | false | false |
inacioferrarini/glasgow | Example/Tests/Networking/AppBaseApiSpec.swift | 1 | 15486 | // The MIT License (MIT)
//
// Copyright (c) 2017 Inácio Ferrarini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Quick
import Nimble
import OHHTTPStubs
@testable import Glasgow
class AppBaseApiSpec: QuickSpec {
// swiftlint:disable function_body_length
// swiftlint:disable cyclomatic_complexity
override func spec() {
describe("Base Api Request") {
context("GET", {
it("if request succeeds, must return valid object") {
// Given
stub(condition: isHost("www.apiurl.com")) { _ in
let notConnectedError = NSError(domain:NSURLErrorDomain, code:Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue), userInfo:nil)
let error = OHHTTPStubsResponse(error:notConnectedError)
guard let fixtureFile = OHPathForFile("ApiRequestResponseFixture.json", type(of: self)) else { return error }
return OHHTTPStubsResponse(
fileAtPath: fixtureFile,
statusCode: 200,
headers: ["Content-Type": "application/json"]
)
}
var returnedPersonList: [Person]?
let api = AppBaseApi("https://www.apiurl.com")
let targetUrl = "/path"
let transformer = ApiResponseToPersonArrayTransformer()
// When
waitUntil { done in
api.get(targetUrl,
responseTransformer: transformer,
success: { (persons) in
returnedPersonList = persons
done()
}, failure: { _ in
fail("Mocked response returned error")
done()
}, retryAttempts: 30)
}
// Then
expect(returnedPersonList?.count).to(equal(3))
expect(returnedPersonList?[0].name).to(equal("Fulano da Silva"))
expect(returnedPersonList?[0].age).to(equal(35))
expect(returnedPersonList?[0].boolValue).to(equal(true))
expect(returnedPersonList?[1].name).to(equal("Sincrano"))
expect(returnedPersonList?[1].age).to(equal(40))
expect(returnedPersonList?[1].boolValue).to(equal(false))
expect(returnedPersonList?[2].name).to(equal("Beltrano"))
expect(returnedPersonList?[2].age).to(equal(37))
expect(returnedPersonList?[2].boolValue).to(equal(true))
}
it("if request with body succeeds, must return valid object") {
// Given
stub(condition: isHost("www.apiurl.com")) { request in
let notConnectedError = NSError(domain:NSURLErrorDomain, code:Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue), userInfo:nil)
let error = OHHTTPStubsResponse(error:notConnectedError)
guard let fixtureFile = OHPathForFile("ApiRequestResponseFixture.json", type(of: self)) else { return error }
guard let bodyInputStream = request.httpBodyStream else { return error }
let bodyData = Data(reading: bodyInputStream)
guard let body = try? JSONSerialization.jsonObject(with: bodyData, options: []) as? [String : String] else { return error }
guard body?["token"] == "value" else { return error }
guard request.allHTTPHeaderFields?["X-AUTH-TOKEN"] == "1234-ABCDEF-1234-UGH" else { return error }
return OHHTTPStubsResponse(
fileAtPath: fixtureFile,
statusCode: 200,
headers: ["Content-Type": "application/json"]
)
}
var returnedPersonList: [Person]?
let api = AppBaseApi("https://www.apiurl.com")
let targetUrl = "/path"
let transformer = ApiResponseToPersonArrayTransformer()
let params = ["token": "value"]
let headers = ["X-AUTH-TOKEN": "1234-ABCDEF-1234-UGH"]
// When
waitUntil { done in
api.get(targetUrl,
responseTransformer: transformer,
parameters: params,
headers: headers,
success: { (persons) in
returnedPersonList = persons
done()
}, failure: { _ in
fail("Mocked response returned error")
done()
}, retryAttempts: 30)
}
// Then
expect(returnedPersonList?.count).to(equal(3))
expect(returnedPersonList?[0].name).to(equal("Fulano da Silva"))
expect(returnedPersonList?[0].age).to(equal(35))
expect(returnedPersonList?[0].boolValue).to(equal(true))
expect(returnedPersonList?[1].name).to(equal("Sincrano"))
expect(returnedPersonList?[1].age).to(equal(40))
expect(returnedPersonList?[1].boolValue).to(equal(false))
expect(returnedPersonList?[2].name).to(equal("Beltrano"))
expect(returnedPersonList?[2].age).to(equal(37))
expect(returnedPersonList?[2].boolValue).to(equal(true))
}
it("if request fails, must execute failure block") {
// Given
stub(condition: isHost("www.apiurl.com")) { _ in
let notConnectedError = NSError(domain:NSURLErrorDomain, code:Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue), userInfo:nil)
return OHHTTPStubsResponse(error: notConnectedError)
}
var returnedPlaylists: [Person]?
let api = AppBaseApi("https://www.apiurl.com")
let targetUrl = "/path"
let transformer = ApiResponseToPersonArrayTransformer()
// When
waitUntil { done in
api.get(targetUrl,
responseTransformer: transformer,
success: { (playlists) in
fail("Mocked response returned success")
returnedPlaylists = playlists
done()
}, failure: { _ in
done()
}, retryAttempts: 30)
}
// Then
expect(returnedPlaylists).to(beNil())
}
})
context("POST", {
it("if request succeeds, must return valid object") {
// Given
stub(condition: isHost("www.apiurl.com")) { _ in
let notConnectedError = NSError(domain:NSURLErrorDomain, code:Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue), userInfo:nil)
let error = OHHTTPStubsResponse(error:notConnectedError)
guard let fixtureFile = OHPathForFile("ApiRequestResponseFixture.json", type(of: self)) else { return error }
return OHHTTPStubsResponse(
fileAtPath: fixtureFile,
statusCode: 200,
headers: ["Content-Type": "application/json"]
)
}
var returnedPersonList: [Person]?
let api = AppBaseApi("https://www.apiurl.com")
let targetUrl = "/path"
let transformer = ApiResponseToPersonArrayTransformer()
// When
waitUntil { done in
api.post(targetUrl,
responseTransformer: transformer,
success: { (persons) in
returnedPersonList = persons
done()
}, failure: { _ in
fail("Mocked response returned error")
done()
}, retryAttempts: 30)
}
// Then
expect(returnedPersonList?.count).to(equal(3))
expect(returnedPersonList?[0].name).to(equal("Fulano da Silva"))
expect(returnedPersonList?[0].age).to(equal(35))
expect(returnedPersonList?[0].boolValue).to(equal(true))
expect(returnedPersonList?[1].name).to(equal("Sincrano"))
expect(returnedPersonList?[1].age).to(equal(40))
expect(returnedPersonList?[1].boolValue).to(equal(false))
expect(returnedPersonList?[2].name).to(equal("Beltrano"))
expect(returnedPersonList?[2].age).to(equal(37))
expect(returnedPersonList?[2].boolValue).to(equal(true))
}
it("if request with body succeeds, must return valid object") {
// Given
stub(condition: isHost("www.apiurl.com")) { request in
let notConnectedError = NSError(domain:NSURLErrorDomain, code:Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue), userInfo:nil)
let error = OHHTTPStubsResponse(error:notConnectedError)
guard let fixtureFile = OHPathForFile("ApiRequestResponseFixture.json", type(of: self)) else { return error }
guard let bodyInputStream = request.httpBodyStream else { return error }
let bodyData = Data(reading: bodyInputStream)
guard let body = try? JSONSerialization.jsonObject(with: bodyData, options: []) as? [String : String] else { return error }
guard body?["token"] == "value" else { return error }
guard request.allHTTPHeaderFields?["X-AUTH-TOKEN"] == "1234-ABCDEF-1234-UGH" else { return error }
return OHHTTPStubsResponse(
fileAtPath: fixtureFile,
statusCode: 200,
headers: ["Content-Type": "application/json"]
)
}
var returnedPersonList: [Person]?
let api = AppBaseApi("https://www.apiurl.com")
let targetUrl = "/path"
let transformer = ApiResponseToPersonArrayTransformer()
let params = ["token": "value"]
let headers = ["X-AUTH-TOKEN": "1234-ABCDEF-1234-UGH"]
// When
waitUntil { done in
api.post(targetUrl,
responseTransformer: transformer,
parameters: params,
headers: headers,
success: { (persons) in
returnedPersonList = persons
done()
}, failure: { _ in
fail("Mocked response returned error")
done()
}, retryAttempts: 30)
}
// Then
expect(returnedPersonList?.count).to(equal(3))
expect(returnedPersonList?[0].name).to(equal("Fulano da Silva"))
expect(returnedPersonList?[0].age).to(equal(35))
expect(returnedPersonList?[0].boolValue).to(equal(true))
expect(returnedPersonList?[1].name).to(equal("Sincrano"))
expect(returnedPersonList?[1].age).to(equal(40))
expect(returnedPersonList?[1].boolValue).to(equal(false))
expect(returnedPersonList?[2].name).to(equal("Beltrano"))
expect(returnedPersonList?[2].age).to(equal(37))
expect(returnedPersonList?[2].boolValue).to(equal(true))
}
it("if request fails, must execute failure block") {
// Given
stub(condition: isHost("www.apiurl.com")) { _ in
let notConnectedError = NSError(domain:NSURLErrorDomain, code:Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue), userInfo:nil)
return OHHTTPStubsResponse(error: notConnectedError)
}
var returnedPlaylists: [Person]?
let api = AppBaseApi("https://www.apiurl.com")
let targetUrl = "/path"
let transformer = ApiResponseToPersonArrayTransformer()
// When
waitUntil { done in
api.post(targetUrl,
responseTransformer: transformer,
success: { (playlists) in
fail("Mocked response returned success")
returnedPlaylists = playlists
done()
}, failure: { _ in
done()
}, retryAttempts: 30)
}
// Then
expect(returnedPlaylists).to(beNil())
}
})
}
}
// swiftlint:enable cyclomatic_complexity
// swiftlint:enable body_length
}
| mit | b2d311b93cf7c831bdcf21b9d389560d | 45.924242 | 163 | 0.49661 | 6.164411 | false | false | false | false |
BoutFitness/Concept2-SDK | Pod/Classes/Stores/PerformanceMonitorStore.swift | 1 | 1624 | //
// PerformanceMonitorStore.swift
// Pods
//
// Created by Jesse Curry on 9/30/15.
// Copyright © 2015 Bout Fitness, LLC. All rights reserved.
//
import CoreBluetooth
let PerformanceMonitorStoreDidAddItemNotification = NSNotification.Name("PerformanceMonitorStoreDidAddItemNotification")
let PerformanceMonitorStoreDidRemoveItemNotification = NSNotification.Name("PerformanceMonitorStoreDidRemoveItemNotification")
final class PerformanceMonitorStore {
// Singleton
static let sharedInstance = PerformanceMonitorStore()
//////////////////////////////////////////////////////////////////////////////////////////////////
var performanceMonitors = Set<PerformanceMonitor>()
func addPerformanceMonitor(performanceMonitor:PerformanceMonitor) {
performanceMonitors.insert(performanceMonitor)
NotificationCenter.default.post(
name: PerformanceMonitorStoreDidAddItemNotification,
object: self
)
}
func performanceMonitorWithPeripheral(peripheral:CBPeripheral) -> PerformanceMonitor? {
var pm:PerformanceMonitor?
performanceMonitors.forEach { (performanceMonitor:PerformanceMonitor) -> () in
if performanceMonitor.peripheral == peripheral {
pm = performanceMonitor
}
}
return pm
}
func removePerformanceMonitor(performanceMonitor:PerformanceMonitor) {
performanceMonitors.remove(performanceMonitor)
NotificationCenter.default.post(
name: PerformanceMonitorStoreDidRemoveItemNotification,
object: self
)
}
}
| mit | 2d08be0861be520fd5755bb47c154cbe | 31.46 | 126 | 0.678373 | 6.62449 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.