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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
juliangrosshauser/HomeControl | HomeControl/Source/Accessory.swift | 1 | 750 | //
// Accessory.swift
// HomeControl
//
// Created by Julian Grosshauser on 22/12/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import Foundation
/// Representing an accessory, like lights, blinds and consumers.
public protocol Accessory: Equatable {
//MARK: Properties
/// Accessory name
var name: String { get }
/// Action ID of accessory. Can be used to trigger accessory actions.
var actionID: String { get }
//MARK: Initialization
/// Construct an `Accessory` with a name and action ID.
init(name: String, actionID: String)
}
//MARK: Equatable
public func ==<T: Accessory>(lhs: T, rhs: T) -> Bool {
return lhs.name == rhs.name && lhs.actionID == lhs.actionID
}
| mit | 75a415af01c772c02ad4392e29ac580a | 22.40625 | 73 | 0.659546 | 3.921466 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/Login/LoginController.swift | 1 | 8722 | //
// LoginController.swift
// PennMobile
//
// Created by Josh Doman on 2/25/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import Foundation
import UIKit
class LoginController: UIViewController, ShowsAlert {
fileprivate var backgroundImage: UIImageView!
fileprivate var iconShadow: CAShapeLayer!
fileprivate var icon: UIImageView!
fileprivate var titleLabel: UILabel!
fileprivate var loginShadow: CAShapeLayer!
fileprivate var loginGradient: CAGradientLayer!
fileprivate var loginButton: UIButton!
fileprivate var skipShadow: CAShapeLayer!
fileprivate var skipButton: UIButton!
fileprivate var isFirstAttempt = true
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .uiBackground
prepareUI()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
loginGradient.frame = loginButton.bounds
loginButton.layer.insertSublayer(loginGradient, at: 0)
loginShadow.path = UIBezierPath(roundedRect: loginButton.bounds, cornerRadius: 20).cgPath
loginShadow.shadowPath = loginShadow.path
loginButton.layer.insertSublayer(loginShadow, at: 0)
skipShadow.path = UIBezierPath(roundedRect: skipButton.bounds, cornerRadius: 20).cgPath
skipShadow.shadowPath = skipShadow.path
skipButton.layer.insertSublayer(skipShadow, at: 0)
}
}
// MARK: - Login Completion Handler
extension LoginController {
func loginCompletion(_ successful: Bool) {
if successful {
// Login Successful
AppDelegate.shared.rootViewController.applicationWillEnterForeground()
} else {
// Failed to retrieve Account from Platform (possibly down)
if !self.isFirstAttempt {
AppDelegate.shared.rootViewController.applicationWillEnterForeground()
} else {
self.isFirstAttempt = false
}
HTTPCookieStorage.shared.removeCookies(since: Date(timeIntervalSince1970: 0))
}
}
}
// MARK: - Login and Skip Button Pressed Handlers {
extension LoginController {
@objc fileprivate func handleLogin(_ sender: Any) {
let lwc = LabsLoginController { (success) in
self.loginCompletion(success)
}
let nvc = UINavigationController(rootViewController: lwc)
present(nvc, animated: true, completion: nil)
}
@objc fileprivate func handleSkip(_ sender: Any) {
AppDelegate.shared.rootViewController.switchToMainScreen()
AppDelegate.shared.rootViewController.clearAccountData()
FirebaseAnalyticsManager.shared.trackEvent(action: "Selected Continue as Guest", result: "Selected Continue as Guest", content: "Selected Continue as Guest")
}
}
// MARK: - Prepare UI
extension LoginController {
fileprivate func prepareUI() {
prepareBackgroundImage()
prepareLoginButton()
prepareSkipButton()
prepareIcon()
prepareTitleLabel()
}
fileprivate func prepareBackgroundImage() {
let iconImage: UIImage = UIImage(named: "LoginBackground")!
backgroundImage = UIImageView(image: iconImage)
backgroundImage.contentMode = .scaleAspectFill
view.addSubview(backgroundImage)
backgroundImage.anchorToTop(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor)
}
fileprivate func prepareLoginButton() {
loginButton = UIButton(type: .system)
loginButton.translatesAutoresizingMaskIntoConstraints = false
loginButton.layer.cornerRadius = 20
loginButton.layer.masksToBounds = false
// Add drop shadow
loginShadow = CAShapeLayer()
loginShadow.fillColor = UIColor.white.cgColor
loginShadow.shadowColor = UIColor.grey1.cgColor
loginShadow.shadowOffset = CGSize(width: 0.5, height: 1.5)
loginShadow.shadowOpacity = 0.5
loginShadow.shadowRadius = 2
// Add gradient
let color1 = UIColor(r: 11, g: 138, b: 204)
let color2 = UIColor(r: 26, g: 142, b: 221)
let color3 = UIColor(r: 31, g: 120, b: 206)
loginGradient = CAGradientLayer()
loginGradient.cornerRadius = 20
loginGradient.locations = [0, 0.3, 1]
loginGradient.startPoint = CGPoint(x: 0, y: 0)
loginGradient.endPoint = CGPoint(x: 1, y: 0)
loginGradient.colors = [color1.cgColor, color2.cgColor, color3.cgColor]
let attributedString = NSMutableAttributedString(string: "LOG IN WITH PENNKEY")
attributedString.addAttribute(NSAttributedString.Key.kern, value: CGFloat(1.2), range: NSRange(location: 0, length: attributedString.length))
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range: NSRange(location: 0, length: attributedString.length))
loginButton.setAttributedTitle(attributedString, for: .normal)
loginButton.titleLabel?.font = UIFont.avenirMedium.withSize(15)
loginButton.addTarget(self, action: #selector(handleLogin(_:)), for: .touchUpInside)
view.addSubview(loginButton)
loginButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loginButton.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 30).isActive = true
loginButton.widthAnchor.constraint(equalToConstant: 250).isActive = true
loginButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
}
fileprivate func prepareSkipButton() {
let buttonColor = UIColor(r: 31, g: 120, b: 206)
skipButton = UIButton(type: .system)
skipButton.translatesAutoresizingMaskIntoConstraints = false
skipButton.backgroundColor = .white
skipButton.layer.cornerRadius = 20
skipButton.layer.borderWidth = 1.5
skipButton.layer.borderColor = buttonColor.cgColor
// Add drop shadow
skipShadow = CAShapeLayer()
skipShadow.fillColor = UIColor.white.cgColor
skipShadow.shadowColor = UIColor.grey1.cgColor
skipShadow.shadowOffset = CGSize(width: 0.5, height: 1)
skipShadow.shadowOpacity = 0.5
skipShadow.shadowRadius = 1
let attributedString = NSMutableAttributedString(string: "CONTINUE AS GUEST")
attributedString.addAttribute(NSAttributedString.Key.kern, value: CGFloat(1.2), range: NSRange(location: 0, length: attributedString.length))
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: buttonColor, range: NSRange(location: 0, length: attributedString.length))
skipButton.setAttributedTitle(attributedString, for: .normal)
skipButton.titleLabel?.font = UIFont.avenirMedium.withSize(15)
skipButton.addTarget(self, action: #selector(handleSkip(_:)), for: .touchUpInside)
view.addSubview(skipButton)
skipButton.topAnchor.constraint(equalTo: loginButton.bottomAnchor, constant: 30).isActive = true
skipButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
skipButton.widthAnchor.constraint(equalTo: loginButton.widthAnchor).isActive = true
skipButton.heightAnchor.constraint(equalTo: loginButton.heightAnchor).isActive = true
}
fileprivate func prepareIcon() {
let iconImage: UIImage = UIImage(named: "LaunchIcon")!
icon = UIImageView(image: iconImage)
icon.translatesAutoresizingMaskIntoConstraints = false
// Add drop shadow
icon.layer.shadowColor = UIColor.grey1.cgColor
icon.layer.shadowOffset = CGSize(width: 1, height: 2)
icon.layer.shadowOpacity = 0.5
icon.layer.shadowRadius = 1.0
icon.clipsToBounds = false
view.addSubview(icon)
icon.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
icon.bottomAnchor.constraint(equalTo: loginButton.topAnchor, constant: -150).isActive = true
icon.widthAnchor.constraint(equalToConstant: 80).isActive = true
icon.heightAnchor.constraint(equalToConstant: 80).isActive = true
}
fileprivate func prepareTitleLabel() {
titleLabel = UILabel()
titleLabel.font = UIFont.avenirMedium.withSize(25)
titleLabel.textColor = .labelPrimary
titleLabel.textAlignment = .center
titleLabel.text = "Penn Mobile"
titleLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(titleLabel)
titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: icon.bottomAnchor, constant: 12).isActive = true
}
}
| mit | c8e215cab8dd487b46c358cfb48f9b70 | 40.927885 | 165 | 0.701525 | 5.049797 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAuthentication/Sources/FeatureAuthenticationData/WalletAuthentication/NetworkClients/DeviceVerificationClient/Responses/WalletInfoPollResponse.swift | 1 | 828 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import FeatureAuthenticationDomain
import Foundation
import NetworkKit
struct WalletInfoPollResponse: Decodable {
enum CodingKeys: String, CodingKey {
case responseType = "response_type"
}
enum ResponseType: String, Decodable {
case walletInfo = "WALLET_INFO_POLLED"
case continuePolling = "CONTINUE_POLLING"
case requestDenied = "REQUEST_DENIED"
}
let responseType: ResponseType
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
responseType = try container.decode(ResponseType.self, forKey: .responseType)
}
}
enum WalletInfoPollResultResponse {
case walletInfo(WalletInfo)
case continuePolling
case requestDenied
}
| lgpl-3.0 | 62c0d5823c14b0ac32ddc9516fb5da8b | 25.677419 | 85 | 0.719468 | 4.725714 | false | false | false | false |
PJayRushton/stats | Pods/AIFlatSwitch/Source/AIFlatSwitch.swift | 1 | 13643 | //
// AIFlatSwitch.swift
// AIFlatSwitch
//
// Created by cocoatoucher on 11/02/15.
// Copyright (c) 2015 cocoatoucher. All rights reserved.
//
import UIKit
/**
A flat design switch alternative to UISwitch
*/
@IBDesignable open class AIFlatSwitch: UIControl {
/**
Animation duration for the whole selection transition
*/
fileprivate let animationDuration: CFTimeInterval = 0.3
/**
Percentage where the checkmark tail ends
*/
fileprivate let finalStrokeEndForCheckmark: CGFloat = 0.85
/**
Percentage where the checkmark head begins
*/
fileprivate let finalStrokeStartForCheckmark: CGFloat = 0.3
/**
Percentage of the bounce amount of checkmark near animation completion
*/
fileprivate let checkmarkBounceAmount: CGFloat = 0.1
/**
Line width for the circle, trail and checkmark parts of the switch.
*/
@IBInspectable open var lineWidth: CGFloat = 2.0 {
didSet {
self.circle.lineWidth = lineWidth
self.checkmark.lineWidth = lineWidth
self.trailCircle.lineWidth = lineWidth
}
}
/**
Set to false if the selection should not be animated with touch up inside events.
*/
@IBInspectable open var animatesOnTouch: Bool = true
/**
Stroke color for circle and checkmark.
Circle disappears and trail becomes visible when the switch is selected.
*/
@IBInspectable open var strokeColor: UIColor = UIColor.black {
didSet {
self.circle.strokeColor = strokeColor.cgColor
self.checkmark.strokeColor = strokeColor.cgColor
}
}
/**
Stroke color for trail.
Trail disappears and circle becomes visible when the switch is deselected.
*/
@IBInspectable open var trailStrokeColor: UIColor = UIColor.gray {
didSet {
self.trailCircle.strokeColor = trailStrokeColor.cgColor
}
}
/**
Overrides isSelected from UIControl using internal state flag.
Default value is false.
*/
@IBInspectable open override var isSelected: Bool {
get {
return isSelectedInternal
}
set {
super.isSelected = newValue
self.setSelected(newValue, animated: false)
}
}
/**
Internal flag to keep track of selected state.
*/
fileprivate var isSelectedInternal: Bool = false
/**
Trail layer. Trail is the circle which appears when the switch is in deselected state.
*/
fileprivate var trailCircle: CAShapeLayer = CAShapeLayer()
/**
Circle layer. Circle appears when the switch is in selected state.
*/
fileprivate var circle: CAShapeLayer = CAShapeLayer()
/**
Checkmark layer. Checkmark appears when the switch is in selected state.
*/
fileprivate var checkmark: CAShapeLayer = CAShapeLayer()
/**
Middle point of the checkmark layer. Calculated each time the sublayers are layout.
*/
fileprivate var checkmarkSplitPoint: CGPoint = CGPoint.zero
public override init(frame: CGRect) {
super.init(frame: frame)
// Configure switch when created with frame
self.configure()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Configure switch when created from xib
self.configure()
}
/**
Configures circle, trail and checkmark layers after initialization.
Setups switch with the default selection state.
Configures target for tocuh up inside event for triggering selection.
*/
fileprivate func configure() {
func configureShapeLayer(_ shapeLayer: CAShapeLayer) {
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineCap = kCALineCapRound
shapeLayer.lineWidth = self.lineWidth
shapeLayer.fillColor = UIColor.clear.cgColor
self.layer.addSublayer(shapeLayer)
}
// Setup layers
configureShapeLayer(trailCircle)
trailCircle.strokeColor = trailStrokeColor.cgColor
configureShapeLayer(circle)
circle.strokeColor = strokeColor.cgColor
configureShapeLayer(checkmark)
checkmark.strokeColor = strokeColor.cgColor
// Setup initial state
self.setSelected(false, animated: false)
// Add target for handling touch up inside event as a default manner
self.addTarget(self, action: #selector(AIFlatSwitch.handleTouchUpInside), for: UIControlEvents.touchUpInside)
}
/**
Switches between selected and deselected state with touch up inside events. Set animatesOnTouch to false to disable animation on touch.
Send valueChanged event as a result.
*/
@objc fileprivate func handleTouchUpInside() {
self.setSelected(!self.isSelected, animated: self.animatesOnTouch)
self.sendActions(for: UIControlEvents.valueChanged)
}
/**
Switches between selected and deselected state. Use this method to programmatically change the valeu of selected state.
- Parameter isSelected: Whether the switch should be selected or not
- Parameter animated: Whether the transition should be animated or not
*/
open func setSelected(_ isSelected: Bool, animated: Bool) {
self.isSelectedInternal = isSelected
// Remove all animations before switching to new state
checkmark.removeAllAnimations()
circle.removeAllAnimations()
trailCircle.removeAllAnimations()
// Reset sublayer values
self.resetLayerValues(self.isSelectedInternal, stateWillBeAnimated: animated)
// Animate to new state
if animated {
self.addAnimations(desiredSelectedState: isSelectedInternal)
}
}
open override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
guard layer == self.layer else {
return
}
var offset: CGPoint = CGPoint.zero
let radius = fmin(self.bounds.width, self.bounds.height) / 2 - (lineWidth / 2)
offset.x = (self.bounds.width - radius * 2) / 2.0
offset.y = (self.bounds.height - radius * 2) / 2.0
CATransaction.begin()
CATransaction.setDisableActions(true)
// Calculate frame for circle and trail circle
let circleAndTrailFrame = CGRect(x: offset.x, y: offset.y, width: radius * 2, height: radius * 2)
let circlePath = UIBezierPath(ovalIn: circleAndTrailFrame)
trailCircle.path = circlePath.cgPath
circle.transform = CATransform3DIdentity
circle.frame = self.bounds
circle.path = UIBezierPath(ovalIn: circleAndTrailFrame).cgPath
// Rotating circle by 212 degrees to be able to manipulate stroke end location.
circle.transform = CATransform3DMakeRotation(CGFloat(212 * Double.pi / 180), 0, 0, 1)
let origin = CGPoint(x: offset.x + radius, y: offset.y + radius)
// Calculate checkmark path
let checkmarkPath = UIBezierPath()
var checkmarkStartPoint = CGPoint.zero
// Checkmark will start from circle's stroke end calculated above.
checkmarkStartPoint.x = origin.x + radius * CGFloat(cos(212 * Double.pi / 180))
checkmarkStartPoint.y = origin.y + radius * CGFloat(sin(212 * Double.pi / 180))
checkmarkPath.move(to: checkmarkStartPoint)
self.checkmarkSplitPoint = CGPoint(x: offset.x + radius * 0.9, y: offset.y + radius * 1.4)
checkmarkPath.addLine(to: self.checkmarkSplitPoint)
var checkmarkEndPoint = CGPoint.zero
// Checkmark will end 320 degrees location of the circle layer.
checkmarkEndPoint.x = origin.x + radius * CGFloat(cos(320 * Double.pi / 180))
checkmarkEndPoint.y = origin.y + radius * CGFloat(sin(320 * Double.pi / 180))
checkmarkPath.addLine(to: checkmarkEndPoint)
checkmark.frame = self.bounds
checkmark.path = checkmarkPath.cgPath
CATransaction.commit()
}
/**
Switches layer values to selected or deselected state without any animation.
If the there is going to be an animation(stateWillBeAnimated parameter is true), then the layer values are reset to reverse of the desired state value to provide the transition for animation.
- Parameter desiredSelectedState: Desired selection state for the reset to handle
- Parameter stateWillBeAnimated: If the reset should prepare the layers for animation
*/
fileprivate func resetLayerValues(_ desiredSelectedState: Bool, stateWillBeAnimated: Bool) {
CATransaction.begin()
CATransaction.setDisableActions(true)
if (desiredSelectedState && stateWillBeAnimated) || (desiredSelectedState == false && stateWillBeAnimated == false) {
// Switch to deselected state
checkmark.strokeEnd = 0.0
checkmark.strokeStart = 0.0
trailCircle.opacity = 0.0
circle.strokeStart = 0.0
circle.strokeEnd = 1.0
} else {
// Switch to selected state
checkmark.strokeEnd = finalStrokeEndForCheckmark
checkmark.strokeStart = finalStrokeStartForCheckmark
trailCircle.opacity = 1.0
circle.strokeStart = 0.0
circle.strokeEnd = 0.0
}
CATransaction.commit()
}
/**
Animates the selected state transition.
- Parameter desiredSelectedState: Desired selection state for the animation to handle
*/
fileprivate func addAnimations(desiredSelectedState selected: Bool) {
let circleAnimationDuration = animationDuration * 0.5
let checkmarkEndDuration = animationDuration * 0.8
let checkmarkStartDuration = checkmarkEndDuration - circleAnimationDuration
let checkmarkBounceDuration = animationDuration - checkmarkEndDuration
let checkmarkAnimationGroup = CAAnimationGroup()
checkmarkAnimationGroup.isRemovedOnCompletion = false
checkmarkAnimationGroup.fillMode = kCAFillModeForwards
checkmarkAnimationGroup.duration = animationDuration
checkmarkAnimationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
let checkmarkStrokeEndAnimation = CAKeyframeAnimation(keyPath: "strokeEnd")
checkmarkStrokeEndAnimation.duration = checkmarkEndDuration + checkmarkBounceDuration
checkmarkStrokeEndAnimation.isRemovedOnCompletion = false
checkmarkStrokeEndAnimation.fillMode = kCAFillModeForwards
checkmarkStrokeEndAnimation.calculationMode = kCAAnimationPaced
if selected {
checkmarkStrokeEndAnimation.values = [NSNumber(value: 0.0 as Float), NSNumber(value: Float(finalStrokeEndForCheckmark + checkmarkBounceAmount) as Float), NSNumber(value: Float(finalStrokeEndForCheckmark) as Float)]
checkmarkStrokeEndAnimation.keyTimes = [NSNumber(value: 0.0 as Double), NSNumber(value: checkmarkEndDuration as Double), NSNumber(value: checkmarkEndDuration + checkmarkBounceDuration as Double)]
} else {
checkmarkStrokeEndAnimation.values = [NSNumber(value: Float(finalStrokeEndForCheckmark) as Float), NSNumber(value: Float(finalStrokeEndForCheckmark + checkmarkBounceAmount) as Float), NSNumber(value: -0.1 as Float)]
checkmarkStrokeEndAnimation.keyTimes = [NSNumber(value: 0.0 as Double), NSNumber(value: checkmarkBounceDuration as Double), NSNumber(value: checkmarkEndDuration + checkmarkBounceDuration as Double)]
}
let checkmarkStrokeStartAnimation = CAKeyframeAnimation(keyPath: "strokeStart")
checkmarkStrokeStartAnimation.duration = checkmarkStartDuration + checkmarkBounceDuration
checkmarkStrokeStartAnimation.isRemovedOnCompletion = false
checkmarkStrokeStartAnimation.fillMode = kCAFillModeForwards
checkmarkStrokeStartAnimation.calculationMode = kCAAnimationPaced
if selected {
checkmarkStrokeStartAnimation.values = [NSNumber(value: 0.0 as Float), NSNumber(value: Float(finalStrokeStartForCheckmark + checkmarkBounceAmount) as Float), NSNumber(value: Float(finalStrokeStartForCheckmark) as Float)]
checkmarkStrokeStartAnimation.keyTimes = [NSNumber(value: 0.0 as Double), NSNumber(value: checkmarkStartDuration as Double), NSNumber(value: checkmarkStartDuration + checkmarkBounceDuration as Double)]
} else {
checkmarkStrokeStartAnimation.values = [NSNumber(value: Float(finalStrokeStartForCheckmark) as Float), NSNumber(value: Float(finalStrokeStartForCheckmark + checkmarkBounceAmount) as Float), NSNumber(value: 0.0 as Float)]
checkmarkStrokeStartAnimation.keyTimes = [NSNumber(value: 0.0 as Double), NSNumber(value: checkmarkBounceDuration as Double), NSNumber(value: checkmarkStartDuration + checkmarkBounceDuration as Double)]
}
if selected {
checkmarkStrokeStartAnimation.beginTime = circleAnimationDuration
}
checkmarkAnimationGroup.animations = [checkmarkStrokeEndAnimation, checkmarkStrokeStartAnimation]
checkmark.add(checkmarkAnimationGroup, forKey: "checkmarkAnimation")
let circleAnimationGroup = CAAnimationGroup()
circleAnimationGroup.duration = animationDuration
circleAnimationGroup.isRemovedOnCompletion = false
circleAnimationGroup.fillMode = kCAFillModeForwards
circleAnimationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
let circleStrokeEnd = CABasicAnimation(keyPath: "strokeEnd")
circleStrokeEnd.duration = circleAnimationDuration
if selected {
circleStrokeEnd.beginTime = 0.0
circleStrokeEnd.fromValue = NSNumber(value: 1.0 as Float)
circleStrokeEnd.toValue = NSNumber(value: -0.1 as Float)
} else {
circleStrokeEnd.beginTime = animationDuration - circleAnimationDuration
circleStrokeEnd.fromValue = NSNumber(value: 0.0 as Float)
circleStrokeEnd.toValue = NSNumber(value: 1.0 as Float)
}
circleStrokeEnd.isRemovedOnCompletion = false
circleStrokeEnd.fillMode = kCAFillModeForwards
circleAnimationGroup.animations = [circleStrokeEnd]
circle.add(circleAnimationGroup, forKey: "circleStrokeEnd")
let trailCircleColor = CABasicAnimation(keyPath: "opacity")
trailCircleColor.duration = animationDuration
if selected {
trailCircleColor.fromValue = NSNumber(value: 0.0 as Float)
trailCircleColor.toValue = NSNumber(value: 1.0 as Float)
} else {
trailCircleColor.fromValue = NSNumber(value: 1.0 as Float)
trailCircleColor.toValue = NSNumber(value: 0.0 as Float)
}
trailCircleColor.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
trailCircleColor.fillMode = kCAFillModeForwards
trailCircleColor.isRemovedOnCompletion = false
trailCircle.add(trailCircleColor, forKey: "trailCircleColor")
}
}
| mit | 99e6e47c43065472c6d9ca219de693f6 | 37.215686 | 223 | 0.770578 | 4.299716 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Views/NibBasedView.swift | 1 | 1220 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import UIKit
/// Subclass your UIView from NibLoadView
/// to automatically load a xib with the same name
/// as your class
open class NibBasedView: UIView {
@IBOutlet var view: UIView!
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
nibSetup()
}
open var bundle: Bundle { Bundle(for: type(of: self)) }
override public init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
private func nibSetup() {
backgroundColor = .clear
view = loadViewFromNib(in: bundle)
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
addSubview(view)
}
private func loadViewFromNib(in bundle: Bundle) -> UIView {
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView
return nibView
}
}
| lgpl-3.0 | d32cf1f1f5e986abfdeeefd2081e71db | 26.088889 | 85 | 0.654635 | 4.706564 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureCoin/Sources/FeatureCoinDomain/HistoricalPrice/Model/Interval.swift | 1 | 952 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct Interval: Hashable {
public let value: Int
public let component: Calendar.Component
}
extension Interval {
public static let _15_minutes = Self(value: 15, component: .minute)
public static let day = Self(value: 1, component: .day)
public static let week = Self(value: 1, component: .weekOfMonth)
public static let month = Self(value: 1, component: .month)
public static let year = Self(value: 1, component: .year)
public static let all = Self(value: 20, component: .year)
}
public struct Scale: Hashable {
public let value: TimeInterval
}
extension Scale {
public static let _15_minutes = Self(value: 900)
public static let _1_hour = Self(value: 3600)
public static let _2_hours = Self(value: 7200)
public static let _1_day = Self(value: 86400)
public static let _5_days = Self(value: 432000)
}
| lgpl-3.0 | c7960b6cfee925310393d784f5803a19 | 31.793103 | 71 | 0.698212 | 3.758893 | false | false | false | false |
lsn-sokna/TextFieldEffects | TextFieldEffects/TextFieldEffects/MinoruTextField.swift | 1 | 4264 | //
// MinoruTextField.swift
// TextFieldEffects
//
// Created by Raúl Riera on 27/01/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
@IBDesignable public class MinoruTextField: TextFieldEffects {
@IBInspectable public var placeholderColor: UIColor? {
didSet {
updatePlaceholder()
}
}
override public var backgroundColor: UIColor? {
set {
backgroundLayerColor = newValue!
}
get {
return backgroundLayerColor
}
}
override public var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override public var bounds: CGRect {
didSet {
updateBorder()
updatePlaceholder()
}
}
private let borderThickness: CGFloat = 1
private let placeholderInsets = CGPoint(x: 6, y: 6)
private let textFieldInsets = CGPoint(x: 6, y: 6)
private let borderLayer = CALayer()
private var backgroundLayerColor: UIColor?
// MARK: - TextFieldsEffectsProtocol
override public func drawViewsForRect(rect: CGRect) {
let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height))
placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font!)
updateBorder()
updatePlaceholder()
layer.addSublayer(borderLayer)
addSubview(placeholderLabel)
}
private func updateBorder() {
borderLayer.frame = rectForBorder(frame)
borderLayer.backgroundColor = backgroundColor?.CGColor
}
private func updatePlaceholder() {
placeholderLabel.text = placeholder
placeholderLabel.textColor = placeholderColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder() {
animateViewsForTextEntry()
}
}
private func placeholderFontFromFont(font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.65)
return smallerFont
}
private func rectForBorder(bounds: CGRect) -> CGRect {
let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y)
return newRect
}
private func layoutPlaceholderInTextRect() {
if text!.isNotEmpty {
return
}
let textRect = textRectForBounds(bounds)
var originX = textRect.origin.x
switch textAlignment {
case .Center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .Right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height,
width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height)
}
override public func animateViewsForTextEntry() {
borderLayer.borderColor = textColor?.CGColor
borderLayer.shadowOffset = CGSizeZero
borderLayer.borderWidth = borderThickness
borderLayer.shadowColor = textColor?.CGColor
borderLayer.shadowOpacity = 0.5
borderLayer.shadowRadius = 1
}
override public func animateViewsForTextDisplay() {
borderLayer.borderColor = nil
borderLayer.shadowOffset = CGSizeZero
borderLayer.borderWidth = 0
borderLayer.shadowColor = nil
borderLayer.shadowOpacity = 0
borderLayer.shadowRadius = 0
}
// MARK: - Overrides
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = rectForBorder(bounds)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = rectForBorder(bounds)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
}
| mit | 0c963ac7f17f95f10dcd98ac74af8fb0 | 29.45 | 133 | 0.628431 | 5.558018 | false | false | false | false |
pavankataria/ChopChop | Demo/ChopChop/ImagePickerViewController.swift | 1 | 3843 | //
// ImagePickerViewController.swift
// PKImageMatrixCropper
//
// Created by Pavan Kataria on 10/01/2016.
// Copyright © 2016 Pavan Kataria. All rights reserved.
//
import UIKit
enum SegueIdentifiers: String {
case ImageViewer = "ShowImageViewer"
}
class ImagePickerViewController: UIViewController {
@IBOutlet weak var pickedImage: UIImageView!
@IBOutlet weak var rows: UITextField!
@IBOutlet weak var cols: UITextField!
var image: UIImage {
set {
pickedImage.image = newValue
self.navigationItem.rightBarButtonItem?.enabled = true
}
get {
if let image = pickedImage.image {
return image
}
assertionFailure("image is nil")
return UIImage()
}
}
var images = [UIImage]()
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
let pickerButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Camera, target: self, action: "displayPicker")
let processButton = UIBarButtonItem(title: "Process", style: UIBarButtonItemStyle.Done, target: self, action: Selector("process"))
processButton.enabled = false
self.navigationItem.leftBarButtonItem? = pickerButton
self.navigationItem.rightBarButtonItem? = processButton
imagePicker.delegate = self
displayHowToUseMessage()
}
func process(){
if rows.text?.characters.count == 0 {
rows.text = "2"
}
if cols.text?.characters.count == 0 {
cols.text = "2"
}
var rowsNum: Int = 2
var colsNum: Int = 2
if let text = rows.text {
rowsNum = Int(text)!
}
if let text = cols.text {
colsNum = Int(text)!
}
// You can use this method to chop by four
// images = image.cropToFourQuadrantsWithResize()
images = image.cropWithMatrix((rowsNum, colsNum))
performSegueWithIdentifier(SegueIdentifiers.ImageViewer.rawValue, sender: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func displayHowToUseMessage(){
let alertController = UIAlertController(title: "How to use", message: "Pick an image,\nspecify a small number for both rows and columns,\nthen tap process", preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(action)
presentViewController(alertController, animated: true, completion: nil)
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == SegueIdentifiers.ImageViewer.rawValue {
let controller = segue.destinationViewController as! ImageCollectionViewController
controller.images = images
}
}
}
extension ImagePickerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func displayPicker(){
imagePicker.allowsEditing = true
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
self.pickedImage.contentMode = .ScaleAspectFill
self.image = pickedImage
}
dismissViewControllerAnimated(true, completion: nil)
}
} | mit | 64ada16800ff27dd6f96b43576639bdf | 35.951923 | 210 | 0.668142 | 5.277473 | false | false | false | false |
tellowkrinkle/Sword | Sources/Sword/Gateway/Eventable.swift | 1 | 1766 | //
// Eventer.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2017 Alejandro Alonso. All rights reserved.
//
/// Create a nifty Event Emitter in Swift
public protocol Eventable: class {
/// Event Listeners
var listeners: [Event: [(Any) -> ()]] { get set }
/**
- parameter event: Event to listen for
*/
func on(_ event: Event, do function: @escaping (Any) -> ()) -> Int
/**
- parameter event: Event to emit
- parameter data: Array of stuff to emit listener with
*/
func emit(_ event: Event, with data: Any)
/**
- parameter event: Event to remove a listener from
- parameter position: Position of listener callback
*/
func removeListener(from event: Event, at position: Int)
}
extension Eventable {
/**
Listens for eventName
- parameter event: Event to listen for
*/
@discardableResult
public func on(_ event: Event, do function: @escaping (Any) -> ()) -> Int {
guard self.listeners[event] != nil else {
self.listeners[event] = [function]
return 0
}
self.listeners[event]!.append(function)
return self.listeners[event]!.count - 1
}
/**
Emits all listeners for eventName
- parameter event: Event to emit
- parameter data: Stuff to emit listener with
*/
public func emit(_ event: Event, with data: Any = ()) {
guard let listeners = self.listeners[event] else { return }
for listener in listeners {
listener(data)
}
}
/**
Removes a listener from an event
- parameter event: Event to remove a listener from
- parameter position: Position of listener callback
*/
public func removeListener(from event: Event, at position: Int) {
_ = self.listeners[event]?.remove(at: position)
}
}
| mit | 1c2820cd3edcbc352577e02f155a1482 | 21.922078 | 77 | 0.642493 | 4.104651 | false | false | false | false |
ochan1/OC-PublicCode | 5. Intro-Optionals-Dictionaries-Playground-swift3/Optionals-Dictionaries.playground/Pages/Challenge.xcplaygroundpage/Contents.swift | 1 | 4703 | /*:

# Dictionaries and Optionals Challenge
## Dictionaries as a phone book
In this exercise, we are going to create a simple phone book data structure using a dictionary.
### Core challenge
1. Create an empty dictionary of type `[String: String]`. This will store name `String`s as keys and phone number `String`s as values
1. Create a function called `addContact` with two parameters -- `name` of type `String` and `phoneNumber` of type `String`. Use it to add a new phone number to your dictionary with a key of `name`. It should also print "<contact name> has been added to your phone book."
1. Create a function called `findContact` with one parameter -- `name` of type `String`. Use it to search your dictionary for a contact. If it finds it, it should print "<contact name> can be called at <contact phone number>.". If the contact does not exist, it should print "<contact name> is not in your phone book!".
1. Create a function called `updateContact` with two parameters -- `name` of type `String` and `phoneNumber` of type `String`. Use it to add a new phone number to your dictionary with a key of `name`. If the contact exists in your phone book, it should print "<contact name> has been updated in your phone book." If the contact does not exist, it should print "<contact name> did not exist. It has now been added to your phone book."
1. Create a function called `deleteContact` with one parameter -- `name` of type `String`. Use it to delete a phone number from your dictionary. If the contact exists in your phone book, it should print "<contact name> has been deleted from your phone book." If the contact does not exist, it should print "<contact name> did not exist."
1. Test your code out! Add a few contacts. Try finding a few contacts (including some you know are not in your phone book). Update some contacts (including some you know are not in your phone book). Delete a few contacts (including some you know are not in your phone book).
1. Create a function called `allContacts`. It should iterate through each contact and print it out as "<contact name> can be called at <contact phone number>.". Can you reuse another function here? For an added challenge, try printing them in alphabetical order. This will likely require extensive Googling!
- note: Why are we using functions for all of this? You can consider these functions as "helper functions". When coding larger applications, it's important to "encapsulate" your code. The rest of your application does not need to know you are using a dictionary as the core data structure here. It only needs to know how to interact with the data!
*/
var contactBook = [String:String]()
func addContact(name:String, phoneNumber:String) {
print("\(name) has been added to your phone book.")
return contactBook[name] = phoneNumber
}
func findContact(name:String) {
if let contact = contactBook[name] {
print("\(name) can be called at \(contact).")
} else {
print("\(name) is not in your phone book!")
}
}
func updateContact(name: String, updatePhoneNumber: String) {
if contactBook[name] != nil {
print("\(name) has been updated in your phone book.")
contactBook[name] = updatePhoneNumber
} else {
print("\(name) did not exist. It has now been added to your phone book.")
addContact(name: name, phoneNumber: updatePhoneNumber)
}
}
func deleteContact(name: String) {
if contactBook[name] != nil {
contactBook[name] = nil
print("\(name) has been deleted from your phone book.")
} else {
print("\(name) did not exist.")
}
}
print("Challenge Test")
addContact(name: "Bob", phoneNumber: "6267281923")
print(contactBook)
updateContact(name: "Bob", updatePhoneNumber: "9999999999")
findContact(name:"Annie")
updateContact(name: "Annie", updatePhoneNumber: "18008888888")
print(contactBook)
deleteContact(name: "Annie")
print(contactBook)
addContact(name: "Oscar", phoneNumber: "6262447029")
addContact(name: "tsmc", phoneNumber: "85218234134123")
func allContacts() {
//var order = [String]()
for person in contactBook {
/*
var alpha: String = person.key
var firstletterprep = person.key
var firstletter = firstletterprep
if person.key > alpha {
order += alpha
} if person.key == alpha {
}
*/
print("\(person.key) can be called at \(person.value).")
}
}
print(contactBook)
allContacts()
/*
For an added challenge, try printing them in alphabetical order. This will likely require extensive Googling!
*/
/*:
[Previous](@prev) | [Next](@next)
*/
| mit | 26dd4efb0ab8c9268dcf0de7d6b93110 | 48.505263 | 434 | 0.70657 | 4.147266 | false | false | false | false |
EugeneVegner/sit-autolifestory-vapor-server | Sources/App/Middleware/ClientMiddleware.swift | 1 | 1858 | //
// ClientMiddleware.swift
// Server
//
// Created by Eugene Vegner on 11.04.17.
//
//
import HTTP
import Vapor
import Polymorphic
import Sessions
public struct Client {
var version: Double?
var platform: String?
var sys: String?
init(values: [Polymorphic]) {
guard let version = values[0].double, let platform = values[1].string, let sys = values[2].string else {
return
}
self.version = version
self.platform = platform
self.sys = sys
}
func isValid() -> Bool {
return true
}
}
final class ClientMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
if let val = request.headers["Client"]?.string {
let values = val.characters
.split(separator: "/")
.map { String($0) }
.map { $0.trim() }
.map { $0 as Polymorphic }
if values.count != 3 {
let error = Server.Error.headers(.client)
return try Server.failure(errors: [error]).makeResponse()
}
let cl = Client(values: values)
if cl.isValid() == false {
let status: Status = .serviceUnavailable
let err = Server.Error.new(code: 5, info: status.reasonPhrase, message: "Current client not supported", type: "client")
return try Server.failure(status, errors: [err]).makeResponse()
}
request.client = cl
let response = try next.respond(to: request)
return response
}
else {
return try Server.failure(errors: [Server.Error.unknown]).makeResponse()
}
}
}
| mit | d82984c0ebbad73a8967d56df620a426 | 26.731343 | 135 | 0.525834 | 4.668342 | false | false | false | false |
Caiflower/SwiftWeiBo | 花菜微博/花菜微博/Classes/Tools(工具)/Other/CFNetworker.swift | 1 | 4468 | //
// CFNetworker.swift
// 花菜微博
//
// Created by 花菜ChrisCai on 2016/12/12.
// Copyright © 2016年 花菜ChrisCai. All rights reserved.
//
import UIKit
import AFNetworking
import SVProgressHUD
enum HTTPMethod {
case GET
case POST
}
class CFNetworker: AFHTTPSessionManager {
// 用户信息
lazy var userAccount = CFAccount()
static let shared : CFNetworker = {
// 实例化对象
let instance = CFNetworker()
// 设置响应反序列化支持的数据类型
instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
// 返回对象
return instance
}()
var authorizeUrlString: String {
return "https://api.weibo.com/oauth2/authorize" + "?" + "client_id=\(SinaAppKey)" + "&" + "redirect_uri=\(SinaRedirectURI)"
}
var userLogon: Bool {
return userAccount.access_token != nil
}
func tokenRequest(method: HTTPMethod = .GET, URLString: String, parameters: [String : AnyObject]? ,name: String? = nil, data: Data? = nil, completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool) -> ()) -> () {
// 处理token
guard let token = userAccount.access_token else {
print("token 为 nil!, 请重新登录")
// 发送通知,提示用户登录
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUserShoudLoginNotification), object: "bad token")
completion(nil, false)
return
}
// 判断parameters是否有值
var parameters = parameters
if parameters == nil {
parameters = [String : AnyObject]()
}
// 此处parameters一定有值
parameters!["access_token"] = token as AnyObject?
// 判断是否是上传请求
if let name = name, let data = data {
upload(URLString: URLString, parameters: parameters, name: name, data: data, completion: completion)
}
else {
request(method: method, URLString: URLString, parameters: parameters, completion: completion)
}
}
func upload(URLString: String, parameters: [String : AnyObject]? ,name: String, data: Data, completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool) -> ()) {
post(URLString, parameters: parameters, constructingBodyWith: { (formData) in
// 拼接上传参数
formData.appendPart(withFileData: data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
}, progress: nil, success: { (_, json) in
completion(json as AnyObject, true)
}) { (task, error) in
// 针对403处理用户token过期
if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
print("token 已过期")
// 发送通知,提示用户重新登录(本方法不知道谁被调用,谁接手通知,谁处理)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUserShoudLoginNotification), object: "bad token")
}
print("错误信息 == \(error)")
completion(nil, false)
}
}
func request(method: HTTPMethod = .GET, URLString: String, parameters: [String : AnyObject]? ,completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool) -> ()) -> (){
// 成功回调
let success = { (task: URLSessionDataTask, json: Any?)->() in
completion(json as AnyObject, true)
}
// 失败回调
let failure = { (task: URLSessionDataTask?, error: Error) -> () in
// 针对403处理用户token过期
if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
print("token 已过期")
// 发送通知,提示用户重新登录(本方法不知道谁被调用,谁接手通知,谁处理)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUserShoudLoginNotification), object: "bad token")
}
print("错误信息 == \(error)")
completion(nil, false)
}
if method == .GET {
get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
}
else {
post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
}
}
}
| apache-2.0 | a3e4e675a5d444afafc748c7bfd2af27 | 37.027778 | 219 | 0.583881 | 4.425647 | false | false | false | false |
NigelJu/bloodDonatedTW | BloodDonated/BloodDonated/Class/Extension/JsonCodable.swift | 1 | 5680 | //
// JsonCodable.swift
//
//
import Foundation
func printLog<T>(message: T,
file: String = #file,
method: String = #function,
line: Int = #line) {
print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
}
public protocol JsonCodable: Codable {
static func dateFormatter() -> DateFormatter?
}
extension Array : JsonCodable {
}
extension Array where Element : JsonCodable {
func jsonArrayString(_ outputFormatter: JSONEncoder.OutputFormatting = []) -> String {
return Element.encode(outputFormatter, dateFormatter: Element.dateFormatter(), value: self).string()!
}
init?(data: Data) {
guard let s = data.decode([Element].self) else { return nil }
self = s
}
init?(string: String) {
guard let s = string.data()?.decode([Element].self) else { return nil }
self = s
}
init?(json: [Dictionary<String, Any?>]) {
guard let s = json.data()?.decode([Element].self) else { return nil }
self = s
}
}
public extension JsonCodable {
public static func dateFormatter() -> DateFormatter? {
return nil
}
init?(json: Dictionary<String, Any?>) {
guard let s = json.data()?.decode(Self.self) else { return nil }
self = s
}
static func arrayFrom(json: [Dictionary<String, Any?>]) -> [Self]? {
return json.data()?.decode([Self].self)
}
init?(data: Data) {
guard let s = data.decode(Self.self) else { return nil }
self = s
}
static func arrayFrom( data: Data) -> [Self]? {
return data.decode([Self].self)
}
init?(string: String) {
guard let s = string.data()?.decode(Self.self) else { return nil }
self = s
}
static func arrayFrom(string: String) -> [Self]? {
return string.data()?.decode([Self].self)
}
func data(_ outputFormatter: JSONEncoder.OutputFormatting = [], dateFormatter : DateFormatter? = nil) -> Data {
return Self.encode(outputFormatter, dateFormatter: dateFormatter, value: self)
}
func jsonString(_ outputFormatter: JSONEncoder.OutputFormatting = [], dateFormatter : DateFormatter? = nil) -> String {
return data([.prettyPrinted], dateFormatter: dateFormatter).string()!
}
static func encode<T>(_ outputFormatter: JSONEncoder.OutputFormatting = [], dateFormatter : DateFormatter? = nil, value: T) -> Data where T : Encodable {
let encoder = JSONEncoder()
encoder.outputFormatting = outputFormatter
if let dateFormatter = Self.dateFormatter() {
encoder.dateEncodingStrategy = .formatted(dateFormatter)
}
return try! encoder.encode(value)
}
}
extension JSONEncoder {
func outputFormat(_ formatter: JSONEncoder.OutputFormatting) -> Self {
outputFormatting = formatter
return self
}
}
extension Data {
func string() -> String? {
return String(data: self, encoding: .utf8)
}
func json() -> [String: Any?]? {
do {
let json = try JSONSerialization.jsonObject(with: self, options: .allowFragments) as! [String: Any?]
return json
}
catch {
return nil
}
}
func jsonArray() -> [[String: Any?]]? {
do {
let json = try JSONSerialization.jsonObject(with: self, options: .allowFragments) as! [[String: Any?]]
return json
}
catch {
printLog(message: error.localizedDescription)
printLog(message: error.localizedDescription)
return nil
}
}
func decode<T>(_ type: [T].Type) -> [T]? where T : JsonCodable {
return Data.decode(type, from: self)
}
func decode<T>(_ type: T.Type) -> T? where T : JsonCodable {
return Data.decode(type, from: self)
}
static func decode<T>(_ type: T.Type, from data: Data) -> T? where T : JsonCodable {
let decoder = JSONDecoder()
if let dateFormatter = T.dateFormatter() {
decoder.dateDecodingStrategy = .formatted(dateFormatter)
}
do {
return try decoder.decode(type, from: data)
}
catch {
printLog(message: error)
}
return nil
}
}
extension Data {
init?(obj: Any, options: JSONSerialization.WritingOptions = []) {
var data: Data
do {
data = try JSONSerialization.data(withJSONObject: obj, options:options)
} catch {
printLog(message: error.localizedDescription)
return nil
}
self = data
}
}
extension Dictionary {
func data(_ options: JSONSerialization.WritingOptions = []) -> Data? {
return Data(obj: self, options: options)
}
func string() -> String? {
return data(.prettyPrinted)?.string()
}
}
extension Array where Element == [String: Any?] {
func data(_ options: JSONSerialization.WritingOptions = []) -> Data? {
return Data(obj: self, options: options)
}
func string() -> String? {
return data(.prettyPrinted)?.string()
}
}
extension String {
func data() -> Data? {
return data(using: .utf8)
}
func json() -> [String: Any?]? {
return data()?.json()
}
func jsonArray() -> [[String: Any?]]? {
return data()?.jsonArray()
}
}
| mit | 8d0e7c0e8ed24df90e529ffa7bb091ef | 24.936073 | 157 | 0.557042 | 4.595469 | false | false | false | false |
Appsaurus/Infinity | InfinitySample/AddSamplesTableViewController.swift | 1 | 7126 | //
// SamplesTableViewController.swift
// InfiniteSample
//
// Created by Danis on 15/12/22.
// Copyright © 2015年 danis. All rights reserved.
//
import UIKit
import Infinity
class AddSamplesTableViewController: UITableViewController {
var type:AnimatorType = .Default
var items = 5
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "refresh", style: .plain, target: self, action: #selector(startRefreshing(sender:)))
view.backgroundColor = .white
title = type.description
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "SampleCell")
automaticallyAdjustsScrollViewInsets = false
tableView.contentInset = UIEdgeInsets(top: navigationController!.navigationBar.bounds.height, left: 0, bottom: 0, right: 0)
addPullToRefresh(type: type)
addInfiniteScroll(type: type)
// tableView.isPullToRefreshEnabled = false
// tableView.isInfiniteScrollEnabled = false
}
deinit {
tableView.fty.clear()
}
func startRefreshing(sender: AnyObject) {
tableView.fty.pullToRefresh.begin()
}
// MARK: - Add PullToRefresh
func addPullToRefresh(type: AnimatorType) {
switch type {
case .Default:
let animator = DefaultRefreshAnimator(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
addPullToRefreshWithAnimator(animator: animator)
case .GIF:
let animator = GIFRefreshAnimator(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
// Add Images for Animator
var refreshImages = [UIImage]()
for index in 0..<22 {
let image = UIImage(named: "hud_\(index)")
if let image = image {
refreshImages.append(image)
}
}
var animatedImages = [UIImage]()
for index in 21..<30 {
let image = UIImage(named: "hud_\(index)")
if let image = image {
animatedImages.append(image)
}
}
for index in 0..<22 {
let image = UIImage(named: "hud_\(index)")
if let image = image {
animatedImages.append(image)
}
}
animator.refreshImages = refreshImages
animator.animatedImages = animatedImages
addPullToRefreshWithAnimator(animator: animator)
case .Circle:
let animator = CircleRefreshAnimator(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
addPullToRefreshWithAnimator(animator: animator)
case .Arrow:
let animator = ArrowRefreshAnimator(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
animator.color = .red
addPullToRefreshWithAnimator(animator: animator)
case .Snake:
let animator = SnakeRefreshAnimator(frame: CGRect(x: 0, y: 0, width: 30, height: 18))
addPullToRefreshWithAnimator(animator: animator)
case .Spark:
let animator = SparkRefreshAnimator(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
addPullToRefreshWithAnimator(animator: animator)
default:
break
}
}
func addPullToRefreshWithAnimator(animator: CustomPullToRefreshAnimator) {
tableView.fty.pullToRefresh.add(animator: animator) { [unowned self] in
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
print("end refreshing")
self.items += 3
self.tableView.reloadData()
self.tableView.fty.pullToRefresh.end()
if self.items < 12 {
self.tableView.fty.infiniteScroll.isEnabled = false
} else {
self.tableView.fty.infiniteScroll.isEnabled = true
}
}
}
tableView.fty.pullToRefresh.animatorOffset = UIOffset(horizontal: 100, vertical: 0)
}
// MARK: - Add InfiniteScroll
func addInfiniteScroll(type: AnimatorType) {
switch type {
case .Default:
let animator = DefaultInfiniteAnimator(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
addInfiniteScrollWithAnimator(animator: animator)
case .GIF:
let animator = GIFInfiniteAnimator(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
var animatedImages = [UIImage]()
for index in 0..<30 {
let image = UIImage(named: "hud_\(index)")
if let image = image {
animatedImages.append(image)
}
}
animator.animatedImages = animatedImages
addInfiniteScrollWithAnimator(animator: animator)
case .Circle:
let animator = CircleInfiniteAnimator(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
addInfiniteScrollWithAnimator(animator: animator)
case .Snake:
let animator = SnakeInfiniteAnimator(frame: CGRect(x: 0, y: 0, width: 30, height: 18))
addInfiniteScrollWithAnimator(animator: animator)
default:
break
}
}
func addInfiniteScrollWithAnimator(animator: CustomInfiniteScrollAnimator) {
tableView.fty.infiniteScroll.add(animator: animator) { [unowned self] in
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
self.items += 15
self.tableView.reloadData()
self.tableView.fty.infiniteScroll.end()
}
}
tableView.fty.infiniteScroll.isEnabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SampleCell", for: indexPath)
cell.textLabel?.text = "Cell"
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let newVC = UIViewController()
newVC.view.backgroundColor = .red
show(newVC, sender: self)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 920f20cf7d9ab17a9330294373a3f7bc | 36.293194 | 151 | 0.595255 | 4.949965 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | Classes/Vendor/Alamofire/Result.swift | 1 | 10952 | //
// Result.swift
//
// Copyright (c) 2014 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 Foundation
/// Used to represent whether a request was successful or encountered an error.
///
/// - success: The request and all post processing operations were successful resulting in the serialization of the
/// provided associated value.
///
/// - failure: The request encountered an error resulting in a failure. The associated values are the original data
/// provided by the server as well as the error that caused the failure.
enum Result<Value> {
case success(Value)
case failure(Error)
/// Returns `true` if the result is a success, `false` otherwise.
var isSuccess: Bool {
switch self {
case .success:
return true
case .failure:
return false
}
}
/// Returns `true` if the result is a failure, `false` otherwise.
var isFailure: Bool {
return !isSuccess
}
/// Returns the associated value if the result is a success, `nil` otherwise.
var value: Value? {
switch self {
case .success(let value):
return value
case .failure:
return nil
}
}
/// Returns the associated error value if the result is a failure, `nil` otherwise.
var error: Error? {
switch self {
case .success:
return nil
case .failure(let error):
return error
}
}
}
// MARK: - CustomStringConvertible
extension Result: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
var description: String {
switch self {
case .success:
return "SUCCESS"
case .failure:
return "FAILURE"
}
}
}
// MARK: - CustomDebugStringConvertible
extension Result: CustomDebugStringConvertible {
/// The debug textual representation used when written to an output stream, which includes whether the result was a
/// success or failure in addition to the value or error.
var debugDescription: String {
switch self {
case .success(let value):
return "SUCCESS: \(value)"
case .failure(let error):
return "FAILURE: \(error)"
}
}
}
// MARK: - Functional APIs
extension Result {
/// Creates a `Result` instance from the result of a closure.
///
/// A failure result is created when the closure throws, and a success result is created when the closure
/// succeeds without throwing an error.
///
/// func someString() throws -> String { ... }
///
/// let result = Result(value: {
/// return try someString()
/// })
///
/// // The type of result is Result<String>
///
/// The trailing closure syntax is also supported:
///
/// let result = Result { try someString() }
///
/// - parameter value: The closure to execute and create the result for.
init(value: () throws -> Value) {
do {
self = try .success(value())
} catch {
self = .failure(error)
}
}
/// Returns the success value, or throws the failure error.
///
/// let possibleString: Result<String> = .success("success")
/// try print(possibleString.unwrap())
/// // Prints "success"
///
/// let noString: Result<String> = .failure(error)
/// try print(noString.unwrap())
/// // Throws error
func unwrap() throws -> Value {
switch self {
case .success(let value):
return value
case .failure(let error):
throw error
}
}
/// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter.
///
/// Use the `map` method with a closure that does not throw. For example:
///
/// let possibleData: Result<Data> = .success(Data())
/// let possibleInt = possibleData.map { $0.count }
/// try print(possibleInt.unwrap())
/// // Prints "0"
///
/// let noData: Result<Data> = .failure(error)
/// let noInt = noData.map { $0.count }
/// try print(noInt.unwrap())
/// // Throws error
///
/// - parameter transform: A closure that takes the success value of the `Result` instance.
///
/// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the
/// same failure.
func map<T>(_ transform: (Value) -> T) -> Result<T> {
switch self {
case .success(let value):
return .success(transform(value))
case .failure(let error):
return .failure(error)
}
}
/// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter.
///
/// Use the `flatMap` method with a closure that may throw an error. For example:
///
/// let possibleData: Result<Data> = .success(Data(...))
/// let possibleObject = possibleData.flatMap {
/// try JSONSerialization.jsonObject(with: $0)
/// }
///
/// - parameter transform: A closure that takes the success value of the instance.
///
/// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the
/// same failure.
func flatMap<T>(_ transform: (Value) throws -> T) -> Result<T> {
switch self {
case .success(let value):
do {
return try .success(transform(value))
} catch {
return .failure(error)
}
case .failure(let error):
return .failure(error)
}
}
/// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `mapError` function with a closure that does not throw. For example:
///
/// let possibleData: Result<Data> = .failure(someError)
/// let withMyError: Result<Data> = possibleData.mapError { MyError.error($0) }
///
/// - Parameter transform: A closure that takes the error of the instance.
/// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns
/// the same instance.
func mapError<T: Error>(_ transform: (Error) -> T) -> Result {
switch self {
case .failure(let error):
return .failure(transform(error))
case .success:
return self
}
}
/// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `flatMapError` function with a closure that may throw an error. For example:
///
/// let possibleData: Result<Data> = .success(Data(...))
/// let possibleObject = possibleData.flatMapError {
/// try someFailableFunction(taking: $0)
/// }
///
/// - Parameter transform: A throwing closure that takes the error of the instance.
///
/// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns
/// the same instance.
func flatMapError<T: Error>(_ transform: (Error) throws -> T) -> Result {
switch self {
case .failure(let error):
do {
return try .failure(transform(error))
} catch {
return .failure(error)
}
case .success:
return self
}
}
/// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter.
///
/// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance.
///
/// - Parameter closure: A closure that takes the success value of this instance.
/// - Returns: This `Result` instance, unmodified.
@discardableResult
func withValue(_ closure: (Value) throws -> Void) rethrows -> Result {
if case let .success(value) = self { try closure(value) }
return self
}
/// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance.
///
/// - Parameter closure: A closure that takes the success value of this instance.
/// - Returns: This `Result` instance, unmodified.
@discardableResult
func withError(_ closure: (Error) throws -> Void) rethrows -> Result {
if case let .failure(error) = self { try closure(error) }
return self
}
/// Evaluates the specified closure when the `Result` is a success.
///
/// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance.
///
/// - Parameter closure: A `Void` closure.
/// - Returns: This `Result` instance, unmodified.
@discardableResult
func ifSuccess(_ closure: () throws -> Void) rethrows -> Result {
if isSuccess { try closure() }
return self
}
/// Evaluates the specified closure when the `Result` is a failure.
///
/// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance.
///
/// - Parameter closure: A `Void` closure.
/// - Returns: This `Result` instance, unmodified.
@discardableResult
func ifFailure(_ closure: () throws -> Void) rethrows -> Result {
if isFailure { try closure() }
return self
}
}
| apache-2.0 | b220b891518b221298da7428e6145a7e | 35.506667 | 119 | 0.610665 | 4.59396 | false | false | false | false |
ello/ello-ios | Sources/Model/Watch.swift | 1 | 1789 | ////
/// Watch.swift
//
import SwiftyJSON
let WatchVersion: Int = 1
@objc(Watch)
final class Watch: Model, PostActionable {
let id: String
let postId: String
let userId: String
var post: Post? { return getLinkObject("post") }
var user: User? { return getLinkObject("user") }
init(
id: String,
postId: String,
userId: String
) {
self.id = id
self.postId = postId
self.userId = userId
super.init(version: WatchVersion)
addLinkObject("post", id: postId, type: .postsType)
addLinkObject("user", id: userId, type: .usersType)
}
required init(coder: NSCoder) {
let decoder = Coder(coder)
self.id = decoder.decodeKey("id")
self.postId = decoder.decodeKey("postId")
self.userId = decoder.decodeKey("userId")
super.init(coder: coder)
}
override func encode(with encoder: NSCoder) {
let coder = Coder(encoder)
coder.encodeObject(id, forKey: "id")
coder.encodeObject(postId, forKey: "postId")
coder.encodeObject(userId, forKey: "userId")
super.encode(with: coder.coder)
}
class func fromJSON(_ data: [String: Any]) -> Watch {
let json = JSON(data)
let watch = Watch(
id: json["id"].idValue,
postId: json["post_id"].stringValue,
userId: json["user_id"].stringValue
)
watch.mergeLinks(data["links"] as? [String: Any])
watch.addLinkObject("post", id: watch.postId, type: .postsType)
watch.addLinkObject("user", id: watch.userId, type: .usersType)
return watch
}
}
extension Watch: JSONSaveable {
var uniqueId: String? { return "Watch-\(id)" }
var tableId: String? { return id }
}
| mit | 8aa91b4168b88574c12447db15a7fedf | 24.927536 | 71 | 0.59251 | 3.914661 | false | false | false | false |
fanyu/EDCPhotoBrowser | EDCPhotoBrowser/EDCPhotoBrowser.swift | 1 | 22158 | //
// EDCPhotoBrowser.swift
// EDCPhotoBrowser
//
// Created by FanYu on 26/10/2015.
// Copyright © 2015 FanYu. All rights reserved.
//
import UIKit
class EDCPhotoBrowser: UIViewController {
// device property
var screenWidth: CGFloat { return UIScreen.mainScreen().bounds.width }
var screenHeight: CGFloat { return UIScreen.mainScreen().bounds.height }
// scroll view
var horizontalScrollView: UIScrollView!
var applicationWindow: UIWindow!
// paging
let pageIndexTagOffset = 520
var currentPageIndex: Int = 0
var visiblePages: Set<EDCZoomingScrollView> = Set()
// status check
var isViewActive: Bool = false
var isPerformingLayout: Bool = false
// var photos
var photos = [UIImage]()
var numberOfPhotos: Int {
return photos.count
}
// sender view's property
var originCells: [UIView]?
var startIndex: Int?
// animation property
let animationDuration: Double = 0.35
var animationImageView: UIImageView = UIImageView()
var useSpringEffect = false
// tool bar
var toolBar: UIToolbar!
var toolCounterLabel: UILabel!
var toolCounterButton: UIBarButtonItem!
var toolPreviousButton: UIBarButtonItem!
var toolNextButton: UIBarButtonItem!
var displayToolbar = false
var displayArrowButton = false
var displayCounterLabel = false
// MARK: - LifeCycle
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nil, bundle: nil)
setup()
}
convenience init(startIndex:Int, allOrginCells: [CollectionViewCell], showToolBar: Bool, showArrowButton: Bool, showCuounterLabel: Bool, springEffect: Bool) {
self.init(nibName: nil, bundle: nil)
self.useSpringEffect = springEffect
self.displayToolbar = showToolBar
self.displayArrowButton = showArrowButton
self.displayCounterLabel = showCuounterLabel
self.originCells = allOrginCells
self.startIndex = startIndex
self.currentPageIndex = startIndex
for cell in allOrginCells{
self.photos.append(cell.imageView.image!)
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
isPerformingLayout = true
horizontalScrollView.frame = frameForhorizontalScrollView()
horizontalScrollView.contentSize = contentSizeForhorizontalScrollView()
horizontalScrollView.contentOffset = contentOffsetForPageAtIndex(currentPageIndex)
isPerformingLayout = false
}
// load the first page
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
performLayout()
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
isViewActive = true
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(true)
horizontalScrollView = nil
visiblePages = Set()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
// MARK: - Setup View
//
extension EDCPhotoBrowser {
func setup() {
applicationWindow = (UIApplication.sharedApplication().delegate?.window)!
modalPresentationStyle = UIModalPresentationStyle.Custom
modalPresentationCapturesStatusBarAppearance = true
modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
}
func setupView() {
// bottom view
view.backgroundColor = UIColor.blackColor()
view.clipsToBounds = true
// scroll view
let horizontalScrollViewFrame = frameForhorizontalScrollView()
horizontalScrollView = UIScrollView(frame: horizontalScrollViewFrame)
horizontalScrollView.pagingEnabled = true
horizontalScrollView.delegate = self
horizontalScrollView.showsHorizontalScrollIndicator = true
horizontalScrollView.showsVerticalScrollIndicator = true
horizontalScrollView.backgroundColor = UIColor.blackColor()
horizontalScrollView.contentSize = contentSizeForhorizontalScrollView()
view.addSubview(horizontalScrollView)
// toolbar
toolBar = UIToolbar(frame: frameForToolbar())
toolBar.backgroundColor = UIColor.clearColor()
toolBar.clipsToBounds = true
toolBar.translucent = true
toolBar.setBackgroundImage(UIImage(), forToolbarPosition: .Bottom, barMetrics: .Default)
view.addSubview(toolBar)
if displayToolbar {
toolBar.hidden = false
} else {
toolBar.hidden = true
}
// prvious arrow
let previousButton = UIButton(type: .Custom)
previousButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
previousButton.imageEdgeInsets = UIEdgeInsets(top: 13.25, left: 17.25, bottom: 13.25, right: 17.25)
previousButton.setImage(UIImage(named: "btn_previous"), forState: .Normal)
previousButton.addTarget(self, action: "handleGoPrevious", forControlEvents: .TouchUpInside)
previousButton.contentMode = .Center
self.toolPreviousButton = UIBarButtonItem(customView: previousButton)
// next arrow
let nextButton = UIButton(type: .Custom)
nextButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
nextButton.imageEdgeInsets = UIEdgeInsets(top: 13.25, left: 17.25, bottom: 13.25, right: 17.25)
nextButton.setImage(UIImage(named: "btn_next"), forState: .Normal)
nextButton.addTarget(self, action: "handleGoNext", forControlEvents: .TouchUpInside)
nextButton.contentMode = .Center
self.toolNextButton = UIBarButtonItem(customView: nextButton)
// counter label
toolCounterLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 95, height: 40))
toolCounterLabel.textAlignment = .Center
toolCounterLabel.backgroundColor = UIColor.clearColor()
toolCounterLabel.font = UIFont.systemFontOfSize(16)
toolCounterLabel.textColor = UIColor.whiteColor()
toolCounterLabel.shadowColor = UIColor.darkTextColor()
toolCounterLabel.shadowOffset = CGSize(width: 0, height: 1)
self.toolCounterButton = UIBarButtonItem(customView: toolCounterLabel)
// tap gesture
let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: nil)
doubleTapRecognizer.numberOfTapsRequired = 2
doubleTapRecognizer.numberOfTouchesRequired = 1 // fingures
self.view.addGestureRecognizer(doubleTapRecognizer)
let singleTapRecognizer = UITapGestureRecognizer(target: self, action: "handleSingleTap:")
singleTapRecognizer.numberOfTapsRequired = 1
singleTapRecognizer.numberOfTouchesRequired = 1
self.view.addGestureRecognizer(singleTapRecognizer)
singleTapRecognizer.requireGestureRecognizerToFail(doubleTapRecognizer)
// pan gesture
let panRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
panRecognizer.minimumNumberOfTouches = 1
panRecognizer.maximumNumberOfTouches = 1
self.view.addGestureRecognizer(panRecognizer)
// transition, must be last call of view did load
performPresentAnimation()
}
func performLayout() {
isPerformingLayout = true
// tool bar
let flexSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
var items = [UIBarButtonItem]()
items.append(flexSpace)
if numberOfPhotos > 1 && displayArrowButton {
items.append(toolPreviousButton)
}
if displayCounterLabel {
items.append(flexSpace)
items.append(toolCounterButton)
items.append(flexSpace)
} else {
items.append(flexSpace)
}
if numberOfPhotos > 1 && displayArrowButton {
items.append(toolNextButton)
}
items.append(flexSpace)
toolBar.setItems(items, animated: false)
updateToolbar()
// reset local cache
visiblePages.removeAll()
// set content offset
horizontalScrollView.contentOffset = contentOffsetForPageAtIndex(currentPageIndex)
// add page
addPages()
isPerformingLayout = false
view.setNeedsLayout()
}
}
// MARK: - ToolBar
//
extension EDCPhotoBrowser {
func updateToolbar() {
if numberOfPhotos > 1 {
toolCounterLabel.text = "\(currentPageIndex + 1) / \(numberOfPhotos)"
} else {
toolCounterLabel.text = nil
}
toolPreviousButton.enabled = (currentPageIndex > 0)
toolNextButton.enabled = (currentPageIndex < numberOfPhotos - 1)
}
}
// MARK: - Action
//
extension EDCPhotoBrowser {
func handleSingleTap(sender: UITapGestureRecognizer) {
performCloseAnimationWithScrollView()
}
func panFrameAnimation(scrollView: EDCZoomingScrollView, duration: NSTimeInterval, finalY: CGFloat, dimissVC: Bool) {
UIView.animateWithDuration(duration, animations: { () -> Void in
if dimissVC {
scrollView.frame.origin.y = finalY
self.view.alpha = 0.0
} else {
scrollView.center.y = self.screenHeight / 2
self.view.alpha = 1
}
}) { (dismissVC) -> Void in
if dimissVC {
self.dismissViewControllerAnimated(false, completion: nil)
}
}
}
func handlePan(sender: UIPanGestureRecognizer) {
let zoomingScrollView = pageDisplayedAtIndex(currentPageIndex)
let translationPoint = sender.translationInView(self.view)
if sender.state == .Began {
zoomingScrollView.backgroundColor = UIColor.clearColor()
zoomingScrollView.imageView.backgroundColor = UIColor.blackColor()
self.horizontalScrollView.backgroundColor = UIColor.clearColor()
self.view.backgroundColor = UIColor.blackColor()
self.view.alpha = 1.0
} else if sender.state == .Changed {
let deltaY = 1 - fabs(translationPoint.y) / screenHeight
zoomingScrollView.frame.origin.y = translationPoint.y
self.view.alpha = deltaY
} else if sender.state == .Ended || sender.state == .Failed || sender.state == .Cancelled {
let velocityY = sender.velocityInView(self.view).y
let finalY = translationPoint.y > 0 ? screenHeight : -screenHeight
if velocityY < -500 { // Up Disappear
panFrameAnimation(zoomingScrollView, duration: 0.25, finalY: finalY, dimissVC: true)
} else if velocityY > 500 { // Down Disappear
panFrameAnimation(zoomingScrollView, duration: 0.25, finalY: finalY, dimissVC: true)
} else if zoomingScrollView.center.y < 10 || zoomingScrollView.center.y > screenHeight - 10 {
panFrameAnimation(zoomingScrollView, duration: 0.25, finalY: finalY, dimissVC: true)
} else { // 回到原位置
panFrameAnimation(zoomingScrollView, duration: 0.25, finalY: finalY, dimissVC: false)
}
}
}
func handleGoPrevious() {
jumpToPageAtIndex(currentPageIndex - 1)
}
func handleGoNext() {
jumpToPageAtIndex(currentPageIndex + 1)
}
}
// MARK: - Paging
//
extension EDCPhotoBrowser {
func jumpToPageAtIndex(index:Int){ // set content offset
if index < numberOfPhotos {
let pageFrame = frameForPageAtIndex(index)
horizontalScrollView.setContentOffset(CGPointMake(pageFrame.origin.x - 10, 0), animated: true)
updateToolbar()
}
}
func photoAtIndex(index: Int) ->UIImage {
return photos[index]
}
func addPages() {
let visibleBounds = horizontalScrollView.bounds // not content size
var firstIndex = Int(floor((CGRectGetMinX(visibleBounds) + 10 * 2) / CGRectGetWidth(visibleBounds)))
var lastIndex = Int(floor((CGRectGetMaxX(visibleBounds) - 10 * 2 - 1) / CGRectGetWidth(visibleBounds)))
if firstIndex < 0 {
firstIndex = 0
}
if firstIndex > numberOfPhotos - 1 {
firstIndex = numberOfPhotos - 1
}
if lastIndex < 0 {
lastIndex = 0
}
if lastIndex > numberOfPhotos - 1 {
lastIndex = numberOfPhotos - 1
}
for index in firstIndex ... lastIndex {
if !isDisplayingPageAtIndex(index){ // don't add current displayed page
// init the new page
let page = EDCZoomingScrollView(frame: view.frame)
page.frame = frameForPageAtIndex(index)
page.tag = index + pageIndexTagOffset
page.photo = photoAtIndex(index)
page.edcDelegate = self
visiblePages.insert(page)
horizontalScrollView.addSubview(page)
}
}
}
func isDisplayingPageAtIndex(index: Int) -> Bool{
for page in visiblePages{
if (page.tag - pageIndexTagOffset) == index {
return true
}
}
return false
}
func contentOffsetForPageAtIndex(index:Int) -> CGPoint{
let pageWidth = horizontalScrollView.bounds.size.width
let newOffset = CGFloat(index) * pageWidth
return CGPointMake(newOffset, 0)
}
func pageDisplayedAtIndex(index: Int) ->EDCZoomingScrollView {
var thePage = EDCZoomingScrollView()
for page in visiblePages {
if page.tag - pageIndexTagOffset == index {
thePage = page
break
}
}
return thePage
}
}
//MARK: - Frame and size
//
extension EDCPhotoBrowser {
func frameForhorizontalScrollView() ->CGRect {
var frame = self.view.bounds
frame.origin.x -= 10
frame.size.width += (2 * 10)
return frame
}
func contentSizeForhorizontalScrollView() ->CGSize {
let bounds = horizontalScrollView.bounds
let width = bounds.size.width * CGFloat(numberOfPhotos)
let height = bounds.size.height
return CGSize(width: width, height: height)
}
func frameForPageAtIndex(index: Int) -> CGRect {
let bounds = horizontalScrollView.bounds
var pageFrame = bounds
pageFrame.size.width -= (2 * 10)
pageFrame.origin.x = (bounds.size.width * CGFloat(index)) + 10
return pageFrame
}
func frameForToolbar() ->CGRect {
return CGRect(x: 0, y: view.bounds.size.height - 44, width: view.bounds.size.width, height: 44)
}
}
// MARK: - Animation
//
extension EDCPhotoBrowser {
func getScaledImageFrame(sender: UIImage) ->CGRect{
var finalImageViewFrame = CGRect.zero
var scaleFactor: CGFloat = 0
var scaledImageWidth: CGFloat = 0
var scaledImageHeight: CGFloat = 0
if sender.size.height / sender.size.width > screenHeight / screenWidth { // long photo
scaleFactor = sender.size.height / screenHeight
scaledImageWidth = sender.size.width / scaleFactor
finalImageViewFrame = CGRect(x: screenWidth / 2 - scaledImageWidth / 2 , y: 0, width: scaledImageWidth, height: screenHeight)
} else { // wide photo
scaleFactor = sender.size.width / screenWidth
scaledImageHeight = sender.size.height / scaleFactor
finalImageViewFrame = CGRect(x: 0, y: (screenHeight/2) - (scaledImageHeight/2), width: screenWidth, height: scaledImageHeight)
}
return finalImageViewFrame
}
func performPresentAnimation() {
// get the view be transparence
horizontalScrollView.alpha = 0.0
let fadeView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))
fadeView.backgroundColor = UIColor.clearColor()
applicationWindow.addSubview(fadeView)
// converts to window base coordinates
let startCell = originCells![startIndex!]
let frameFromStartView = startCell.superview?.convertRect(startCell.frame, toView: nil)
animationImageView = UIImageView(image: photoAtIndex(startIndex!))
animationImageView.frame = frameFromStartView!
animationImageView.clipsToBounds = true
animationImageView.contentMode = .ScaleAspectFill
applicationWindow.addSubview(animationImageView)
startCell.hidden = true
let scaledImageViewFrame = getScaledImageFrame(photoAtIndex(startIndex!))
// animation
if useSpringEffect {
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 20, options: .CurveEaseOut, animations: { () -> Void in
self.animationImageView.layer.frame = scaledImageViewFrame
fadeView.alpha = 1
}) { (Bool) -> Void in
self.horizontalScrollView.alpha = 1.0
self.animationImageView.removeFromSuperview()
fadeView.removeFromSuperview()
startCell.hidden = false
}
} else {
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
self.animationImageView.layer.frame = scaledImageViewFrame
}, completion: { (Bool) -> Void in
self.horizontalScrollView.alpha = 1.0
self.animationImageView.removeFromSuperview()
fadeView.removeFromSuperview()
startCell.hidden = false
})
}
}
func performCloseAnimationWithScrollView() {
let fadeView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))
fadeView.backgroundColor = UIColor.blackColor()
fadeView.alpha = 1.0
applicationWindow.addSubview(fadeView)
let lastCell = originCells![currentPageIndex]
let frameFromLastView = lastCell.superview?.convertRect(lastCell.frame, toView: self.view)
let scaledLastViewFrame = getScaledImageFrame(photoAtIndex(currentPageIndex))
animationImageView = UIImageView(image: photoAtIndex(currentPageIndex))
animationImageView.frame = scaledLastViewFrame
animationImageView.alpha = 1.0
animationImageView.backgroundColor = UIColor.greenColor()
animationImageView.clipsToBounds = true
animationImageView.contentMode = .ScaleAspectFill
applicationWindow.addSubview(animationImageView)
lastCell.hidden = true
view.hidden = true
if useSpringEffect {
UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 20, options: .CurveEaseOut, animations: { () -> Void in
fadeView.alpha = 0.0
self.animationImageView.layer.frame = frameFromLastView!
}, completion: { (Bool) -> Void in
self.animationImageView.removeFromSuperview()
fadeView.removeFromSuperview()
self.dismissViewControllerAnimated(true, completion: nil)
lastCell.hidden = false
})
} else {
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
fadeView.alpha = 0.0
self.animationImageView.layer.frame = frameFromLastView!
}) { (Bool) -> Void in
self.animationImageView.removeFromSuperview()
fadeView.removeFromSuperview()
self.dismissViewControllerAnimated(true, completion: nil)
lastCell.hidden = false
}
}
}
}
// MARK: - Scroll View Delegate
//
extension EDCPhotoBrowser: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
if !isViewActive {
return
}
if isPerformingLayout {
return
}
// add page
addPages()
// Calculate current page ???
let visibleBounds = horizontalScrollView.bounds
var index = Int(floor(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds)))
if index < 0 {
index = 0
}
if index > numberOfPhotos - 1 {
index = numberOfPhotos
}
let previousPageIndex = currentPageIndex
currentPageIndex = index
if currentPageIndex != previousPageIndex {
updateToolbar()
}
}
}
extension EDCPhotoBrowser: EDCZoomingScrollViewDelegate {
func didZoomInOut(zoom: String) {
if zoom == "ZoomIn" && displayToolbar{
toolBar.hidden = true
} else if zoom == "ZoomOut" && displayToolbar {
toolBar.hidden = false
}
}
}
| mit | 0c621529fed6e8262a06df2d047d7338 | 33.496885 | 162 | 0.613447 | 5.416239 | false | false | false | false |
AboutObjectsTraining/swift-comp-reston-2017-01 | lab exercises/Coolness/Coolness/CoolViewController.swift | 1 | 2381 | import UIKit
class CoolViewController: UIViewController
{
var contentView: UIView?
var textField: UITextField!
func addCoolViewCell() {
let newCell = CoolViewCell()
newCell.text = textField.text
newCell.sizeToFit()
contentView?.addSubview(newCell)
}
override func loadView() {
view = UIView(frame: UIScreen.main.bounds)
let (accessoryRect, contentRect) = UIScreen.main.bounds.divided(atDistance: 90, from: .minYEdge)
contentView = UIView(frame: contentRect)
let accessoryView = UIView(frame: accessoryRect)
let subview1 = CoolViewCell(frame: CGRect(x: 20, y: 30, width: 80, height: 30))
let subview2 = CoolViewCell(frame: CGRect(x: 40, y: 80, width: 80, height: 30))
contentView?.clipsToBounds = true
view.addSubview(accessoryView)
view.addSubview(contentView!)
contentView?.addSubview(subview1)
contentView?.addSubview(subview2)
// Controls
textField = UITextField(frame: CGRect(x: 8, y: 40, width: 240, height: 30))
accessoryView.addSubview(textField)
textField.placeholder = "Enter some text"
textField.borderStyle = .roundedRect
textField.delegate = self
let button = UIButton(type: .system)
accessoryView.addSubview(button)
button.setTitle("Add", for: .normal)
button.sizeToFit()
button.frame = button.frame.offsetBy(dx: 260, dy: 40)
button.addTarget(self, action: #selector(addCoolViewCell), for: .touchUpInside)
// Cool View Cells
subview1.text = "CoolViewCells Rock!"
subview2.text = "Now on the App Store!"
subview1.sizeToFit()
subview2.sizeToFit()
view.backgroundColor = UIColor.brown
accessoryView.backgroundColor = UIColor(white: 1, alpha: 0.8)
contentView?.backgroundColor = UIColor(white: 1, alpha: 0.7)
subview1.backgroundColor = UIColor.purple
subview2.backgroundColor = UIColor.orange
}
}
extension CoolViewController: UITextFieldDelegate
{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | 6f5b51d92e0340d5026312b812b3abd0 | 29.922078 | 104 | 0.614868 | 4.879098 | false | false | false | false |
phatblat/3DTouchDemo | 3DTouchDemo/TouchCanvas/TouchCanvas/CanvasView.swift | 1 | 10385 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `CanvasView` tracks `UITouch`es and represents them as a series of `Line`s.
*/
import UIKit
@available(iOS 9.1, *)
class CanvasView: UIView {
// MARK: Properties
let isPredictionEnabled = UIDevice.currentDevice().userInterfaceIdiom == .Pad
let isTouchUpdatingEnabled = true
var usePreciseLocations = false
var isDebuggingEnabled = false
/// Array containing all line objects that need to be drawn in `drawRect(_:)`.
var lines = [Line]()
/**
Holds a map of `UITouch` objects to `Line` objects whose touch has not ended yet.
Use `NSMapTable` to handle association as `UITouch` doesn't conform to `NSCopying`.
*/
let activeLines = NSMapTable.strongToStrongObjectsMapTable()
/**
Holds a map of `UITouch` objects to `Line` objects whose touch has ended but still has points awaiting
updates.
Use `NSMapTable` to handle association as `UITouch` doesn't conform to `NSCopying`.
*/
let pendingLines = NSMapTable.strongToStrongObjectsMapTable()
/// A `CGContext` for drawing the last representation of lines no longer receiving updates into.
lazy var frozenContext: CGContext = {
let scale = self.window!.screen.scale
var size = self.bounds.size
size.width *= scale
size.height *= scale
let colorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGBitmapContextCreate(nil, Int(size.width), Int(size.height), 8, 0, colorSpace, CGImageAlphaInfo.PremultipliedLast.rawValue)
CGContextSetLineCap(context, .Round)
let transform = CGAffineTransformMakeScale(scale, scale)
CGContextConcatCTM(context, transform)
return context!
}()
/// An optional `CGImage` containing the last representation of lines no longer receiving updates.
var frozenImage: CGImage?
// MARK: Drawing
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()!
CGContextSetLineCap(context, .Round)
frozenImage = frozenImage ?? CGBitmapContextCreateImage(frozenContext)
if let frozenImage = frozenImage {
CGContextDrawImage(context, bounds, frozenImage)
}
for line in lines {
line.drawInContext(context, isDebuggingEnabled: isDebuggingEnabled, usePreciseLocation: usePreciseLocations)
}
}
// MARK: Actions
func clear() {
activeLines.removeAllObjects()
pendingLines.removeAllObjects()
lines.removeAll()
frozenImage = nil
CGContextClearRect(frozenContext, bounds)
setNeedsDisplay()
}
// MARK: Convenience
func drawTouches(touches: Set<UITouch>, withEvent event: UIEvent?) {
var updateRect = CGRect.null
for touch in touches {
// Retrieve a line from `activeLines`. If no line exists, create one.
let line = activeLines.objectForKey(touch) as? Line ?? addActiveLineForTouch(touch)
/*
Remove prior predicted points and update the `updateRect` based on the removals. The touches
used to create these points are predictions provided to offer additional data. They are stale
by the time of the next event for this touch.
*/
updateRect.unionInPlace(line.removePointsWithType(.Predicted))
/*
Incorporate coalesced touch data. The data in the last touch in the returned array will match
the data of the touch supplied to `coalescedTouchesForTouch(_:)`
*/
let coalescedTouches = event?.coalescedTouchesForTouch(touch) ?? []
let coalescedRect = addPointsOfType(.Coalesced, forTouches: coalescedTouches, toLine: line, currentUpdateRect: updateRect)
updateRect.unionInPlace(coalescedRect)
/*
Incorporate predicted touch data. This sample draws predicted touches differently; however,
you may want to use them as inputs to smoothing algorithms rather than directly drawing them.
Points derived from predicted touches should be removed from the line at the next event for
this touch.
*/
if isPredictionEnabled {
let predictedTouches = event?.predictedTouchesForTouch(touch) ?? []
let predictedRect = addPointsOfType(.Predicted, forTouches: predictedTouches, toLine: line, currentUpdateRect: updateRect)
updateRect.unionInPlace(predictedRect)
}
}
setNeedsDisplayInRect(updateRect)
}
func addActiveLineForTouch(touch: UITouch) -> Line {
let newLine = Line()
activeLines.setObject(newLine, forKey: touch)
lines.append(newLine)
return newLine
}
func addPointsOfType(var type: LinePoint.PointType, forTouches touches: [UITouch], toLine line: Line, currentUpdateRect updateRect: CGRect) -> CGRect {
var accumulatedRect = CGRect.null
for (idx, touch) in touches.enumerate() {
let isStylus = touch.type == .Stylus
// The visualization displays non-`.Stylus` touches differently.
if !isStylus {
type.unionInPlace(.Finger)
}
// Touches with estimated properties require updates; add this information to the `PointType`.
if isTouchUpdatingEnabled && !touch.estimatedProperties.isEmpty {
type.unionInPlace(.NeedsUpdate)
}
// The last touch in a set of `.Coalesced` touches is the originating touch. Track it differently.
if type.contains(.Coalesced) && idx == touches.count - 1 {
type.subtractInPlace(.Coalesced)
type.unionInPlace(.Standard)
}
let force = isStylus || touch.force > 0 ? touch.force : 1.0
let touchRect = line.addPointAtLocation(touch.locationInView(self), preciseLocation: touch.preciseLocationInView(self), force: force, timestamp: touch.timestamp, type: type)
accumulatedRect.unionInPlace(touchRect)
commitLine(line)
}
return updateRect.union(accumulatedRect)
}
func endTouches(touches: Set<UITouch>, cancel: Bool) {
var updateRect = CGRect.null
for touch in touches {
// Skip over touches that do not correspond to an active line.
guard let line = activeLines.objectForKey(touch) as? Line else { continue }
// If this is a touch cancellation, cancel the associated line.
if cancel { updateRect.unionInPlace(line.cancel()) }
// If the line is complete (no points needing updates) or updating isn't enabled, move the line to the `frozenImage`.
if line.isComplete || !isTouchUpdatingEnabled {
finishLine(line)
}
// Otherwise, add the line to our map of touches to lines pending update.
else {
pendingLines.setObject(line, forKey: touch)
}
// This touch is ending, remove the line corresponding to it from `activeLines`.
activeLines.removeObjectForKey(touch)
}
setNeedsDisplayInRect(updateRect)
}
func updateEstimatedPropertiesForTouches(touches: Set<NSObject>) {
guard isTouchUpdatingEnabled, let touches = touches as? Set<UITouch> else { return }
var updateRect = CGRect.null
for touch in touches {
var isPending = false
// Look to retrieve a line from `activeLines`. If no line exists, look it up in `pendingLines`.
let possibleLine: Line? = activeLines.objectForKey(touch) as? Line ?? {
let pendingLine = pendingLines.objectForKey(touch) as? Line
isPending = pendingLine != nil
return pendingLine
}()
// If no line is related to the touch, return as there is no additional work to do.
guard let line = possibleLine else { return }
let updateEstimatedRect = line.updatePointLocation(touch.locationInView(self), preciseLocation: touch.preciseLocationInView(self), force: touch.force, forTimestamp: touch.timestamp)
updateRect.unionInPlace(updateEstimatedRect)
// If this update updated the last point requiring an update, move the line to the `frozenImage`.
if isPending && line.isComplete {
finishLine(line)
pendingLines.removeObjectForKey(touch)
}
// Otherwise, have the line add any points no longer requiring updates to the `frozenImage`.
else {
commitLine(line)
}
setNeedsDisplayInRect(updateRect)
}
}
func commitLine(line: Line) {
// Have the line draw any segments between points no longer being updated into the `frozenContext` and remove them from the line.
line.drawFixedPointsInContext(frozenContext, isDebuggingEnabled: isDebuggingEnabled, usePreciseLocation: usePreciseLocations)
// Force the `frozenImage` to be regenerated from the `frozenContext` during the next `drawRect(_:)` call.
frozenImage = nil
}
func finishLine(line: Line) {
// Have the line draw any remaining segments into the `frozenContext`.
line.drawInContext(frozenContext, isDebuggingEnabled: isDebuggingEnabled, usePreciseLocation: usePreciseLocations)
// Force the `frozenImage` to be regenerated from the `frozenContext` during the next `drawRect(_:)` call.
frozenImage = nil
// Cease tracking this line now that it is finished.
lines.removeAtIndex(lines.indexOf(line)!)
}
}
| mit | 699ce0d7775d2d591f557a5b91063c9e | 40.366534 | 193 | 0.619282 | 5.259878 | false | false | false | false |
worchyld/EYPlayground | Payout.playground/Pages/orders-and-sales.xcplaygroundpage/Contents.swift | 1 | 1760 | //: [Previous](@previous)
import Foundation
struct Factory {
var orders:[Int] = [Int]()
var completedOrders:[Int] = [Int]()
}
struct Book {
struct Orders {
var values: [Int] = [Int]()
}
struct Sales {
var values: [Int] = [Int]()
}
var orders: Orders = Orders.init()
var sales: Sales = Sales.init()
}
var book = Book.init()
book.orders.values.append(contentsOf: [3,5,2])
print (book.orders)
print (book.sales)
protocol OrderBookProtocol {
var values: [Int] { get set }
var entryType: OrderState { get set }
}
enum OrderState {
case outstandingOrder // order to be fulfilled
case completedOrder // AKA filled orders
}
struct OrderBook: OrderBookProtocol {
internal mutating func changeState(toState:OrderState) {
// move an order -> sale (completed order) and vice versa
self.entryType = toState
}
var entryType: OrderState = .outstandingOrder
var values: [Int] = [Int]()
public static func addOrders(values:[Int]) -> OrderBook {
let jb = OrderBook.init(entryType: .outstandingOrder, values: values)
return jb
}
}
class ABCFactory {
var name: String = ""
var books: [OrderBook] = [OrderBook]()
var orders: [Int] {
return books.filter({ (j:OrderBook) -> Bool in
return (j.entryType == .outstandingOrder)
}).flatMap({$0.values})
}
var completedOrders: [Int] {
return books.filter({ (j:OrderBook) -> Bool in
return (j.entryType == .completedOrder)
}).flatMap({$0.values})
}
}
let abc = ABCFactory.init()
abc.name = "ABC LTD"
let jb: OrderBook = OrderBook.addOrders(values: [3,5,2])
abc.books.append(jb)
print (abc.orders)
print (abc.completedOrders)
| gpl-3.0 | 65faba942907a98cf29da752c4f8bdf4 | 22.466667 | 77 | 0.624432 | 3.52 | false | false | false | false |
victorpimentel/MarvelAPI | MarvelAPI.playground/Sources/Requests/GetCharacters.swift | 1 | 594 | import Foundation
public struct GetCharacters: APIRequest {
public typealias Response = [ComicCharacter]
public var resourceName: String {
return "characters"
}
// Parameters
public let name: String?
public let nameStartsWith: String?
public let limit: Int?
public let offset: Int?
// Note that nil parameters will not be used
public init(name: String? = nil,
nameStartsWith: String? = nil,
limit: Int? = nil,
offset: Int? = nil) {
self.name = name
self.nameStartsWith = nameStartsWith
self.limit = limit
self.offset = offset
}
}
| apache-2.0 | a770232e4d4b801b6643d246bdb937c9 | 21.846154 | 45 | 0.675084 | 3.644172 | false | false | false | false |
xu6148152/binea_project_for_ios | ListerforAppleWatchiOSandOSX/Swift/Lister/AppDelegate.swift | 1 | 15828 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The application delegate.
*/
import UIKit
import ListerKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
// MARK: Types
struct MainStoryboard {
static let name = "Main"
struct Identifiers {
static let emptyViewController = "emptyViewController"
}
}
// MARK: Properties
var window: UIWindow!
var listsController: ListsController!
/**
A private, local queue used to ensure serialized access to Cloud containers during application
startup.
*/
let appDelegateQueue = dispatch_queue_create("com.example.apple-samplecode.lister.appdelegate", DISPATCH_QUEUE_SERIAL)
// MARK: View Controller Accessor Convenience
/**
The root view controller of the window will always be a `UISplitViewController`. This is set up
in the main storyboard.
*/
var splitViewController: UISplitViewController {
return window.rootViewController as UISplitViewController
}
/// The primary view controller of the split view controller defined in the main storyboard.
var primaryViewController: UINavigationController {
return splitViewController.viewControllers.first as UINavigationController
}
/**
The view controller that displays the list of documents. If it's not visible, then this value
is `nil`.
*/
var listDocumentsViewController: ListDocumentsViewController? {
return primaryViewController.viewControllers.first as? ListDocumentsViewController
}
// MARK: UIApplicationDelegate
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let appConfiguration = AppConfiguration.sharedConfiguration
if appConfiguration.isCloudAvailable {
/*
Ensure the app sandbox is extended to include the default container. Perform this action on the
`AppDelegate`'s serial queue so that actions dependent on the extension always follow it.
*/
dispatch_async(appDelegateQueue) {
// The initial call extends the sandbox. No need to capture the URL.
NSFileManager.defaultManager().URLForUbiquityContainerIdentifier(nil)
return
}
}
return true
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Observe changes to the user's iCloud account status (account changed, logged out, etc...).
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleUbiquityIdentityDidChangeNotification:", name: NSUbiquityIdentityDidChangeNotification, object: nil)
// Provide default lists from the app's bundle on first launch.
AppConfiguration.sharedConfiguration.runHandlerOnFirstLaunch {
ListUtilities.copyInitialLists()
}
splitViewController.delegate = self
splitViewController.preferredDisplayMode = .AllVisible
// Configure the detail controller in the `UISplitViewController` at the root of the view hierarchy.
let navigationController = splitViewController.viewControllers.last as UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
navigationController.topViewController.navigationItem.leftItemsSupplementBackButton = true
return true
}
func applicationDidBecomeActive(application: UIApplication) {
// Make sure that user storage preferences are set up after the app sandbox is extended. See `application(_:, willFinishLaunchingWithOptions:)` above.
dispatch_async(appDelegateQueue) {
self.setupUserStoragePreferences()
}
}
func application(_: UIApplication, continueUserActivity: NSUserActivity, restorationHandler: [AnyObject] -> Void) -> Bool {
// Lister only supports a single user activity type; if you support more than one the type is available from the `continueUserActivity` parameter.
if let listDocumentsViewController = listDocumentsViewController {
// Make sure that user activity continuation occurs after the app sandbox is extended. See `application(_:, willFinishLaunchingWithOptions:)` above.
dispatch_async(appDelegateQueue) {
restorationHandler([listDocumentsViewController])
}
return true
}
return false
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
// Lister currently only opens URLs of the Lister scheme type.
if url.scheme == AppConfiguration.ListerScheme.name {
// Obtain an app launch context from the provided lister:// URL and configure the view controller with it.
let launchContext = AppLaunchContext(listerURL: url)
if let listDocumentsViewController = listDocumentsViewController {
// Make sure that URL opening is handled after the app sandbox is extended. See `application(_:, willFinishLaunchingWithOptions:)` above.
dispatch_async(appDelegateQueue) {
listDocumentsViewController.configureViewControllerWithLaunchContext(launchContext)
}
return true
}
}
return false
}
// MARK: UISplitViewControllerDelegate
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController _: UIViewController) -> Bool {
/*
In a regular width size class, Lister displays a split view controller with a navigation controller
displayed in both the master and detail areas.
If there's a list that's currently selected, it should be on top of the stack when collapsed.
Ensuring that the navigation bar takes on the appearance of the selected list requires the
transfer of the configuration of the navigation controller that was shown in the detail area.
*/
if secondaryViewController is UINavigationController && (secondaryViewController as UINavigationController).topViewController is ListViewController {
// Obtain a reference to the navigation controller currently displayed in the detail area.
let secondaryNavigationController = secondaryViewController as UINavigationController
// Transfer the settings for the `navigationBar` and the `toolbar` to the main navigation controller.
primaryViewController.navigationBar.titleTextAttributes = secondaryNavigationController.navigationBar.titleTextAttributes
primaryViewController.navigationBar.tintColor = secondaryNavigationController.navigationBar.tintColor
primaryViewController.toolbar?.tintColor = secondaryNavigationController.toolbar?.tintColor
return false
}
return true
}
func splitViewController(splitViewController: UISplitViewController, separateSecondaryViewControllerFromPrimaryViewController _: UIViewController) -> UIViewController? {
/*
In this delegate method, the reverse of the collapsing procedure described above needs to be
carried out if a list is being displayed. The appropriate controller to display in the detail area
should be returned. If not, the standard behavior is obtained by returning nil.
*/
if primaryViewController.topViewController is UINavigationController && (primaryViewController.topViewController as UINavigationController).topViewController is ListViewController {
// Obtain a reference to the navigation controller containing the list controller to be separated.
let secondaryViewController = primaryViewController.popViewControllerAnimated(false) as UINavigationController
let listViewController = secondaryViewController.topViewController as ListViewController
// Obtain the `textAttributes` and `tintColor` to setup the separated navigation controller.
let textAttributes = listViewController.textAttributes
let tintColor = listViewController.listPresenter.color.colorValue
// Transfer the settings for the `navigationBar` and the `toolbar` to the detail navigation controller.
secondaryViewController.navigationBar.titleTextAttributes = textAttributes
secondaryViewController.navigationBar.tintColor = tintColor
secondaryViewController.toolbar?.tintColor = tintColor
// Display a bar button on the left to allow the user to expand or collapse the main area, similar to Mail.
secondaryViewController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
return secondaryViewController
}
return nil
}
// MARK: Notifications
func handleUbiquityIdentityDidChangeNotification(notification: NSNotification) {
primaryViewController.popToRootViewControllerAnimated(true)
setupUserStoragePreferences()
}
// MARK: User Storage Preferences
func setupUserStoragePreferences() {
let storageState = AppConfiguration.sharedConfiguration.storageState
/*
Check to see if the account has changed since the last time the method was called. If it has, let
the user know that their documents have changed. If they've already chosen local storage (i.e. not
iCloud), don't notify them since there's no impact.
*/
if storageState.accountDidChange && storageState.storageOption == .Cloud {
notifyUserOfAccountChange(storageState)
// Return early. State resolution will take place after the user acknowledges the change.
return
}
resolveStateForUserStorageState(storageState)
}
func resolveStateForUserStorageState(storageState: StorageState) {
if storageState.cloudAvailable {
if storageState.storageOption == .NotSet || (storageState.storageOption == .Local && storageState.accountDidChange) {
// iCloud is available, but we need to ask the user what they prefer.
promptUserForStorageOption()
}
else {
/*
The user has already selected a specific storage option. Set up the lists controller to use
that storage option.
*/
configureListsController(accountChanged: storageState.accountDidChange)
}
}
else {
/*
iCloud is not available, so we'll reset the storage option and configure the list controller.
The next time that the user signs in with an iCloud account, he or she can change provide their
desired storage option.
*/
if storageState.storageOption != .NotSet {
AppConfiguration.sharedConfiguration.storageOption = .NotSet
}
configureListsController(accountChanged: storageState.accountDidChange)
}
}
// MARK: Alerts
func notifyUserOfAccountChange(storageState: StorageState) {
/*
Copy a 'Today' list from the bundle to the local documents directory if a 'Today' list doesn't exist.
This provides more context for the user than no lists and ensures the user always has a 'Today' list (a
design choice made in Lister).
*/
if !storageState.cloudAvailable {
ListUtilities.copyTodayList()
}
let title = NSLocalizedString("Sign Out of iCloud", comment: "")
let message = NSLocalizedString("You have signed out of the iCloud account previously used to store documents. Sign back in with that account to access those documents.", comment: "")
let okActionTitle = NSLocalizedString("OK", comment: "")
let signedOutController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let action = UIAlertAction(title: okActionTitle, style: .Cancel) { _ in
self.resolveStateForUserStorageState(storageState)
}
signedOutController.addAction(action)
listDocumentsViewController?.presentViewController(signedOutController, animated: true, completion: nil)
}
func promptUserForStorageOption() {
let title = NSLocalizedString("Choose Storage Option", comment: "")
let message = NSLocalizedString("Do you want to store documents in iCloud or only on this device?", comment: "")
let localOnlyActionTitle = NSLocalizedString("Local Only", comment: "")
let cloudActionTitle = NSLocalizedString("iCloud", comment: "")
let storageController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let localOption = UIAlertAction(title: localOnlyActionTitle, style: .Default) { localAction in
AppConfiguration.sharedConfiguration.storageOption = .Local
self.configureListsController(accountChanged: true)
}
storageController.addAction(localOption)
let cloudOption = UIAlertAction(title: cloudActionTitle, style: .Default) { cloudAction in
AppConfiguration.sharedConfiguration.storageOption = .Cloud
self.configureListsController(accountChanged: true) {
ListUtilities.migrateLocalListsToCloud()
}
}
storageController.addAction(cloudOption)
listDocumentsViewController?.presentViewController(storageController, animated: true, completion: nil)
}
// MARK: Convenience
func configureListsController(#accountChanged: Bool, storageOptionChangeHandler: (Void -> Void)? = nil) {
if listsController != nil && !accountChanged {
// The current controller is correct. There is no need to reconfigure it.
return
}
if listsController == nil {
// There is currently no lists controller. Configure an appropriate one for the current configuration.
listsController = AppConfiguration.sharedConfiguration.listsControllerForCurrentConfigurationWithPathExtension(AppConfiguration.listerFileExtension, firstQueryHandler: storageOptionChangeHandler)
// Ensure that this controller is passed along to the `ListDocumentsViewController`.
listDocumentsViewController?.listsController = listsController
listsController.startSearching()
}
else if accountChanged {
// A lists controller is configured; however, it needs to have its coordinator updated based on the account change.
listsController.listCoordinator = AppConfiguration.sharedConfiguration.listCoordinatorForCurrentConfigurationWithLastPathComponent(AppConfiguration.listerFileExtension, firstQueryHandler: storageOptionChangeHandler)
}
}
}
| mit | 50e813eeedd87b6b84486e39cfaaf3de | 47.845679 | 227 | 0.685012 | 6.42289 | false | true | false | false |
NikKovIos/NKVPhonePicker | Sources/Helpers/NKVSourcesHelper.swift | 1 | 2849 | //
// Be happy and free :)
//
// Nik Kov
// nik-kov.com
//
#if os(iOS)
import Foundation
import UIKit
struct NKVSourcesHelper {
/// Gives the flag image, if it exists in bundle.
///
/// - Parameter source: Any of the source, look **NKVSourceType**
/// - Returns: The flag image or nil, if there are not such image for this country code.
public static func flag(`for` source: NKVSource) -> UIImage? {
var countryCode: String = ""
switch source {
case .country(let country):
countryCode = country.countryCode
case .code(let code):
countryCode = code.code
case .phoneExtension:
guard let country = Country.country(for: source) else {
return nil
}
countryCode = country.countryCode
}
let imageName = "Countries.bundle/Images/\(countryCode.uppercased())"
let flagImage = UIImage(named: imageName,
in: Bundle(for: NKVPhonePickerTextField.self),
compatibleWith: nil)
return flagImage
}
/// - Parameter code: Country code like 'ru' or 'RU' independed of the letter case.
/// - Returns: True of false dependenly if the image of the flag exists in the bundle.
public static func isFlagExists(`for` source: NKVSource) -> Bool {
return self.flag(for: source) != nil
}
/// The array of all countries in the bundle
public private(set) static var countries: [Country] = {
var countries: [Country] = []
do {
if let file = Bundle(for: NKVPhonePickerTextField.self).url(forResource: "Countries.bundle/Data/countryCodes", withExtension: "json") {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let array = json as? Array<[String: String]> {
for object in array {
guard let code = object["code"],
let phoneExtension = object["dial_code"],
let formatPattern = object["format"] else {
fatalError("Must be valid json.")
}
countries.append(Country(countryCode: code,
phoneExtension: phoneExtension,
formatPattern: formatPattern))
}
}
} else {
print("NKVPhonePickerTextField >>> Can't find a bundle for the countries")
}
} catch {
print("NKVPhonePickerTextField >>> \(error.localizedDescription)")
}
return countries
}()
}
#endif
| mit | 9025554020c097415f44519e0438916c | 36.486842 | 147 | 0.532468 | 5.151899 | false | false | false | false |
kousun12/RxSwift | RxSwift/Observables/Observable+Time.swift | 4 | 8377 | //
// Observable+Time.swift
// Rx
//
// Created by Krunoslav Zaher on 3/22/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// MARK: throttle
extension ObservableType {
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
`throttle` and `debounce` are synonyms.
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers and send events on.
- returns: The throttled sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func throttle<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S)
-> Observable<E> {
return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
`throttle` and `debounce` are synonyms.
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers and send events on.
- returns: The throttled sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func debounce<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S)
-> Observable<E> {
return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
// MARK: sample
extension ObservableType {
/**
Samples the source observable sequence using a samper observable sequence producing sampling ticks.
Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence.
**In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.**
- parameter sampler: Sampling tick sequence.
- returns: Sampled observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func sample<O: ObservableType>(sampler: O)
-> Observable<E> {
return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: true)
}
/**
Samples the source observable sequence using a samper observable sequence producing sampling ticks.
Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence.
**In case there were no new elements between sampler ticks, last produced element is always sent to the resulting sequence.**
- parameter sampler: Sampling tick sequence.
- returns: Sampled observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func sampleLatest<O: ObservableType>(sampler: O)
-> Observable<E> {
return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: false)
}
}
// MARK: interval
/**
Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages.
- parameter period: Period for producing the values in the resulting sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence that produces a value after each period.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func interval<S: SchedulerType>(period: S.TimeInterval, _ scheduler: S)
-> Observable<Int64> {
return Timer(dueTime: period,
period: period,
scheduler: scheduler
)
}
// MARK: timer
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- parameter dueTime: Relative time at which to produce the first value.
- parameter period: Period to produce subsequent values.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func timer<S: SchedulerType>(dueTime: S.TimeInterval, _ period: S.TimeInterval, _ scheduler: S)
-> Observable<Int64> {
return Timer(
dueTime: dueTime,
period: period,
scheduler: scheduler
)
}
/**
Returns an observable sequence that produces a single value at the specified absolute due time, using the specified scheduler to run the timer.
- parameter dueTime: Time interval after which to produce the value.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence that produces a value at due time.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func timer<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S)
-> Observable<Int64> {
return Timer(
dueTime: dueTime,
period: nil,
scheduler: scheduler
)
}
// MARK: take
extension ObservableType {
/**
Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func take<S: SchedulerType>(duration: S.TimeInterval, _ scheduler: S)
-> Observable<E> {
return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// MARK: skip
extension ObservableType {
/**
Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- parameter duration: Duration for skipping elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func skip<S: SchedulerType>(duration: S.TimeInterval, _ scheduler: S)
-> Observable<E> {
return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// MARK: delaySubscription
extension ObservableType {
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func delaySubscription<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S)
-> Observable<E> {
return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
// MARK: buffer
extension ObservableType {
/**
Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers.
A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first.
- parameter timeSpan: Maximum time length of a buffer.
- parameter count: Maximum element count of a buffer.
- parameter scheduler: Scheduler to run buffering timers on.
- returns: An observable sequence of buffers.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func buffer<S: SchedulerType>(timeSpan timeSpan: S.TimeInterval, count: Int, scheduler: S)
-> Observable<[E]> {
return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
| mit | e56bc1cbbc883205d3bbd3e9acb45954 | 38.701422 | 187 | 0.714695 | 4.60022 | false | false | false | false |
mrmacete/Morte | Morte/Robot/UgoRobot.swift | 1 | 9476 | //
// UgoRobot.swift
// Morte
//
// Created by ftamagni on 18/03/15.
// Copyright (c) 2015 morte. All rights reserved.
//
import SpriteKit
private let dismemberingDuration = 0.5
protocol UgoRobotDelegate: class {
func robotDead(robot: UgoRobot);
func robotDidFly(robot: UgoRobot, flyTime: Double);
}
class UgoRobot: NSObject {
var sensitivity: CGFloat = 3.0
var root: SKNode
var torso: SKNode!
var arm_hand_right: SKNode!
var arm_root_right: SKNode!
var arm_hand_left: SKNode!
var arm_root_left: SKNode!
var leg_root_right: SKNode!
var leg_foot_right: SKNode!
var leg_root_left: SKNode!
var leg_foot_left: SKNode!
var skate: SKNode!
var left_foot_socket: SKNode!
var right_foot_socket: SKNode!
var startPosition = CGPoint.zero
var startSkatePosition = CGPoint.zero
var dismembering = false
weak var delegate: UgoRobotDelegate?
var flying = false
var flyingStartTime: NSDate?
var flyTotalTime = 0.0
var autoStopTimer: Timer?
var t = 0.0
required init(fileName: String) {
if let ugoScene = GameScene.unarchiveFromFile(file: fileName as NSString) {
root = (ugoScene.children[0] ).copy() as! SKNode
for arm in root["//arm*"] {
(arm as SKNode).reachConstraints?.lowerAngleLimit = -90.0
(arm as SKNode).reachConstraints?.upperAngleLimit = 90.0
if arm.name == "arm_hand_right" {
arm_hand_right = arm
}
else if arm.name == "arm_root_right" {
arm_root_right = arm
}
else if arm.name == "arm_leg_root_right" {
leg_root_right = arm
}
else if arm.name == "arm_foot_right" {
leg_foot_right = arm
}
else if arm.name == "arm_leg_root_left" {
leg_root_left = arm
}
else if arm.name == "arm_foot_left" {
leg_foot_left = arm
} else if arm.name == "arm_hand_left" {
arm_hand_left = arm
}
else if arm.name == "arm_root_left" {
arm_root_left = arm
}
}
skate = root.childNode(withName: "skate")
skate.physicsBody!.usesPreciseCollisionDetection = true
torso = root.childNode(withName: "torso")
left_foot_socket = skate.childNode(withName: "left_foot_socket")
right_foot_socket = skate.childNode(withName: "right_foot_socket")
skate.constraints = [SKConstraint.zRotation(SKRange(lowerLimit: -1.0, upperLimit: 1.0))]
} else {
root = SKNode()
}
super.init()
addGroove()
}
func addGroove()
{
addGrooveTo(arm: arm_hand_right, root: arm_root_right )
addGrooveTo(arm: arm_hand_left, root: arm_root_left )
}
private var grooving = false
private let grooveAmplitude = CGPoint(x:10.0, y:10.0)
private let grooveFreq = CGPoint(x:10.0, y:10.0)
private let grooveSampling = 0.2
func addGrooveTo(arm: SKNode, root: SKNode) {
if let rnode = self.root.scene {
grooving = true
let delta = CGPoint(x:cos(CGFloat(t) * grooveFreq.x) * grooveAmplitude.x , y: sin(CGFloat(t) * grooveFreq.y) * grooveAmplitude.y )
var pos = arm.convert(CGPoint.zero, to: rnode);
pos.x += delta.x
pos.y += delta.y
arm.run(SKAction.reach(to: pos, rootNode: root, duration: grooveSampling), completion: {
self.addGrooveTo(arm: arm, root: root)
})
}
}
var grabbing = false
func grabPosition(position: CGPoint) {
arm_hand_left?.removeAllActions()
arm_hand_right?.removeAllActions()
grooving = false
grabbing = true
arm_hand_right?.run(SKAction.reach(to: position, rootNode: arm_root_right, duration: 0.1))
arm_hand_left?.run(SKAction.reach(to: position, rootNode: arm_root_left, duration: 0.1), completion: {
if !self.grooving {
self.addGroove()
}
self.grabbing = false
})
//dismember()
}
func startMoving(position: CGPoint) {
startPosition = position
startSkatePosition = skate.position
skate.physicsBody?.affectedByGravity = false
if let ast = autoStopTimer {
ast.invalidate()
autoStopTimer = nil
}
autoStopTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(stopMoving), userInfo: nil, repeats: false)
}
func stopMoving() {
if let ast = autoStopTimer {
ast.invalidate()
autoStopTimer = nil
}
skate.physicsBody?.affectedByGravity = true
}
func move(position: CGPoint) {
let dx = (position.x - startPosition.x) * sensitivity
let dy = (position.y - startPosition.y) * sensitivity
let to = CGPoint(x:startSkatePosition.x + dx, y: startSkatePosition.y + dy)
skate?.run(SKAction.move(to: to, duration: 0.2))
}
func update(currentTime: CFTimeInterval) {
t = currentTime
if !grooving && !grabbing {
addGroove()
}
if !dismembering {
torso.position = CGPoint(x:skate.position.x - tan(skate.zRotation)*50, y: skate.position.y + 150 * cos(skate.zRotation) )
torso.zRotation = skate.zRotation * 0.3
if let rootParent = root.parent {
if let rootParentParent = rootParent.parent {
leg_foot_right?.run(SKAction.reach(to: right_foot_socket.convert(CGPoint.zero, to: rootParentParent), rootNode: leg_root_right, duration: 0.01))
leg_foot_left?.run(SKAction.reach(to: left_foot_socket.convert(CGPoint.zero, to: rootParentParent), rootNode: leg_root_left, duration: 0.01))
}
}
let torsoFrame = torso.calculateAccumulatedFrame()
let torsoOrigin = root.scene!.convert(torsoFrame.origin, from: torso.parent!)
let torsoGlobalFrame = CGRect(x:torsoOrigin.x, y:torsoOrigin.y, width:torsoFrame.width, height: torsoFrame.height)
if !torsoGlobalFrame.intersects(root.scene!.frame) {
skate?.run(SKAction.move(to: CGPoint.zero, duration: 0.5))
dismember()
Timer.scheduledTimer(timeInterval: dismemberingDuration * 5, target: self, selector: #selector(UgoRobot.notifyDeath), userInfo: nil, repeats: false)
}
if root.scene!.convert(skate.position, from: skate.parent!).y > 50.0 {
if !flying {
flying = true
flyingStartTime = NSDate()
}
} else {
if flying && flyingStartTime != nil {
flying = false
let elapsed = Date().timeIntervalSince(flyingStartTime! as Date)
flyTotalTime += elapsed
delegate?.robotDidFly(robot: self, flyTime: elapsed)
}
}
}
}
func dismember() {
dismembering = true
let sw = UInt32(root.scene!.size.width)
let sh = UInt32(root.scene!.size.width)
for arm in torso["*"] {
explodeNode(arm: arm, horizExtent: sw, vertExtent: sh)
}
explodeNode(arm: torso, horizExtent: sw, vertExtent: sh)
}
func explodeNode(arm: SKNode, horizExtent: UInt32, vertExtent: UInt32) {
if let node = arm as? SKSpriteNode {
if node == skate {
return
}
node.physicsBody = SKPhysicsBody(rectangleOf: node.size, center: node.anchorPoint)
node.physicsBody?.mass = 0.1
let dx = CGFloat(arc4random() % horizExtent) - CGFloat(horizExtent/2)
let dy = CGFloat(arc4random() % vertExtent) - CGFloat(vertExtent/2)
let endPoint = CGPoint(x:dx, y:dy)
node.run(SKAction.move(to: endPoint, duration: dismemberingDuration))
}
}
func notifyDeath() {
delegate?.robotDead(robot: self)
}
}
| mit | 703e0232801e8c8650979dc6c13fa1d5 | 28.337461 | 164 | 0.498945 | 4.453008 | false | false | false | false |
DDSwift/SwiftDemos | Day01-LoadingADView/LoadingADView/LoadingADView/Class/Extension/UIDevice + Extension.swift | 1 | 711 | //
// UIDevice + Extension.swift
//
import UIKit
extension UIDevice {
// MARK: - 获取当前屏幕尺寸
class func currentDeviceScreenMeasurement() -> CGFloat {
var deviceScree: CGFloat = 3.5
if ((568 == ScreenHeight && 320 == ScreenWidth) || (1136 == ScreenHeight && 640 == ScreenWidth)) {
deviceScree = 4.0;
} else if ((667 == ScreenHeight && 375 == ScreenWidth) || (1334 == ScreenHeight && 750 == ScreenWidth)) {
deviceScree = 4.7;
} else if ((736 == ScreenHeight && 414 == ScreenWidth) || (2208 == ScreenHeight && 1242 == ScreenWidth)) {
deviceScree = 5.5;
}
return deviceScree
}
} | gpl-3.0 | c3151ef9c87ab828b649010dd34149b3 | 29.26087 | 114 | 0.545324 | 4.398734 | false | false | false | false |
TG908/iOS | TUM Campus App/News.swift | 1 | 1192 | //
// News.swift
// TUM Campus App
//
// Created by Mathias Quintero on 7/21/16.
// Copyright © 2016 LS1 TUM. All rights reserved.
//
import UIKit
class News: ImageDownloader, DataElement {
let id: String
let date: Date
let title: String
let link: String
init(id: String, date: Date, title: String, link: String, image: String? = nil) {
self.id = id
self.date = date
self.title = title
self.link = link
super.init()
if let image = image?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed) {
getImage(image)
}
}
var text: String {
get {
return title
}
}
func getCellIdentifier() -> String {
return "news"
}
func open() {
if let url = URL(string: link) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
extension News: CardDisplayable {
var cardKey: CardKey {
return .news
}
}
extension News: Equatable {
static func == (lhs: News, rhs: News) -> Bool {
return lhs.id == rhs.id
}
}
| gpl-3.0 | 7d0d1b470f19b9472e12453e0deddfd9 | 19.186441 | 109 | 0.554156 | 4.078767 | false | false | false | false |
kzaher/RxSwift | RxCocoa/iOS/UIBarButtonItem+Rx.swift | 1 | 1819 | //
// UIBarButtonItem+Rx.swift
// RxCocoa
//
// Created by Daniel Tartaglia on 5/31/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
import RxSwift
private var rx_tap_key: UInt8 = 0
extension Reactive where Base: UIBarButtonItem {
/// Reactive wrapper for target action pattern on `self`.
public var tap: ControlEvent<Void> {
let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<()> in
Observable.create { [weak control = self.base] observer in
guard let control = control else {
observer.on(.completed)
return Disposables.create()
}
let target = BarButtonItemTarget(barButtonItem: control) {
observer.on(.next(()))
}
return target
}
.take(until: self.deallocated)
.share()
}
return ControlEvent(events: source)
}
}
@objc
final class BarButtonItemTarget: RxTarget {
typealias Callback = () -> Void
weak var barButtonItem: UIBarButtonItem?
var callback: Callback!
init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) {
self.barButtonItem = barButtonItem
self.callback = callback
super.init()
barButtonItem.target = self
barButtonItem.action = #selector(BarButtonItemTarget.action(_:))
}
override func dispose() {
super.dispose()
#if DEBUG
MainScheduler.ensureRunningOnMainThread()
#endif
barButtonItem?.target = nil
barButtonItem?.action = nil
callback = nil
}
@objc func action(_ sender: AnyObject) {
callback()
}
}
#endif
| mit | 65ee5cf0551adce9b9af29c6c1888b3e | 24.25 | 82 | 0.579758 | 4.860963 | false | false | false | false |
inamiy/Await | Demo/AwaitDemoTests/AwaitDemoTests.swift | 1 | 4825 | //
// AwaitDemoTests.swift
// AwaitDemoTests
//
// Created by Yasuhiro Inami on 2014/06/30.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import XCTest
//import PromiseKit
class AwaitDemoTests: XCTestCase {
let request = NSURLRequest(URL: NSURL(string:"https://github.com"))
var response: NSData?
override func setUp()
{
super.setUp()
println("\n\n\n\n\n")
}
override func tearDown()
{
println("\n\n\n\n\n")
super.tearDown()
}
func testAwait()
{
self.response = await { NSURLConnection.sendSynchronousRequest(self.request, returningResponse:nil, error: nil) }
XCTAssertNotNil(self.response, "Should GET html data.")
}
func testAwaitTuple()
{
let result: (value: Int?, error: NSError?)? = await {
usleep(100_000);
return (nil, NSError(domain: "AwaitDemoTest", code: -1, userInfo: nil))
}
XCTAssertNil(result!.value, "Should not return value.")
XCTAssertNotNil(result!.error, "Should return error.")
}
func testAwaitWithUntil()
{
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
var shouldStop = false
self.response = await(until: shouldStop) {
dispatch_async(queue) {
usleep(100_000)
shouldStop = true
}
return NSData() // dummy
}
XCTAssertNotNil(self.response, "Should await for data.")
}
func testAwaitWithTimeout()
{
let timeout = 0.2 // 200ms
self.response = await(timeout: timeout) {
usleep(300_000) // 300ms, sleep well to demonstrate timeout error
return NSData() // dummy
}
XCTAssertNil(self.response, "Should time out and return nil.")
self.response = await(timeout: timeout) {
usleep(100_000) // 100ms
return NSData()
}
XCTAssertNotNil(self.response, "Should GET html data within \(timeout) seconds.")
}
// func testAwaitWithPromiseKit()
// {
// let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
//// let queue = dispatch_get_main_queue()
//
// let promise = Promise<NSData> { [weak self] (fulfiller, rejecter) in
// dispatch_async(queue) {
// let data = NSURLConnection.sendSynchronousRequest(self!.request, returningResponse:nil, error: nil)
// fulfiller(data)
// }
// }.then(onQueue: queue) { (data: NSData) -> NSData in
// return data
// }
//
//// self.response = await({ promise.value }, until: { !promise.pending })
// self.response = await(promise)
//
// XCTAssertNotNil(self.response, "Should GET html data.")
// }
func testAwaitWithNSOperation()
{
let operation = NSBlockOperation(block: { usleep(100_000); return })
operation.completionBlock = { println("operation finished.") }
self.response = await(until: operation.finished) {
operation.start()
return NSData() // dummy
}
XCTAssertNotNil(self.response, "Should await for data.")
}
func testAwaitWithNSOperationQueue()
{
let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 1
for i in 0 ..< 3 {
let operation = NSBlockOperation(block: { usleep(100_000); return })
operation.completionBlock = { println("operation[\(i)] finished.") }
operationQueue.addOperation(operation)
}
self.response = await(until: operationQueue.operationCount == 0) {
return NSData() // dummy
}
XCTAssertNotNil(self.response, "Should await for data.")
}
func testAwaitFinishable()
{
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
self.response = await { finish in
dispatch_async(queue) {
usleep(100_000)
finish(NSData()) // dummy
}
}
XCTAssertNotNil(self.response, "Should await for data.")
}
func testAwaitFinishableNoReturn()
{
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
await { finish in
dispatch_async(queue) {
usleep(100_000)
self.response = NSData() // dummy
finish()
}
}
XCTAssertNotNil(self.response, "Should await for data.")
}
}
| mit | f95d402a4b9253a38ed4c7311c9e6eb6 | 28.771605 | 121 | 0.55339 | 4.615311 | false | true | false | false |
zoeyzhong520/InformationTechnology | InformationTechnology/InformationTechnology/Classes/Recommend推荐/Science科技/View/CellDetailView.swift | 1 | 2415 | //
// CellDetailView.swift
// InformationTechnology
//
// Created by qianfeng on 16/11/15.
// Copyright © 2016年 zzj. All rights reserved.
//
import UIKit
class CellDetailView: UIView {
//定义Cell详情页面的布局类型
enum ScienceDetailCellType:String {
case doc = "doc"
case slide = "slides"
}
//数据
var model:CellDetailModel? {
didSet {
tableView?.reloadData()
}
}
//表格
private var tableView:UITableView?
//重新实现初始化方法
override init(frame: CGRect) {
super.init(frame: frame)
//创建表格视图
tableView = UITableView(frame: CGRectZero, style: .Plain)
tableView?.delegate = self
tableView?.dataSource = self
addSubview(tableView!)
//约束
tableView?.snp_makeConstraints(closure: { (make) in
make.edges.equalTo(self)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:UITableView的代理方法
extension CellDetailView:UITableViewDataSource,UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var row = 0
if model?.body != nil {
row = 1
}
return row
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return kScreenHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
if model?.meta?.type == ScienceDetailCellType.slide.rawValue {
let cell = HasSlideDetailCell.createSlidesForCell(tableView, atIndexPath: indexPath, slideArray: model?.body?.slides)
cell.selectionStyle = .None
return cell
}else{
let cell = DetailCell.ceateCellFor(tableView, atIndexPath: indexPath, bodyModel: model?.body)
//设置选中样式
cell.selectionStyle = .None
return cell
}
}
return UITableViewCell()
}
}
| mit | 3677f92fe2e7ba7f269c8bdd6cd64138 | 20.943396 | 133 | 0.55675 | 5.203579 | false | false | false | false |
narner/AudioKit | Examples/macOS/AudioUnitManager/AudioUnitManager/Extensions.swift | 1 | 3476 | //
// Extensions.swift
// AudioUnitManager
//
// Created by Ryan Francesconi on 7/14/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
import Cocoa
extension String {
var digits: String {
return components(separatedBy: CharacterSet.decimalDigits.inverted)
.joined()
}
func index(from: Int) -> Index {
return self.index(startIndex, offsetBy: from)
}
func indexOf(string: String) -> String.Index? {
return self.range( of:string, options: .literal, range: nil, locale: nil)?.lowerBound
}
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
func toCGFloat() -> CGFloat {
if let n = NumberFormatter().number(from: self) {
let f = CGFloat(truncating: n)
return f
}
return 0.0
}
func toInt() -> Int {
if let n = NumberFormatter().number(from: self) {
let f = Int(truncating: n)
return f
}
return 0
}
func toDouble() -> Double {
if let n = NumberFormatter().number(from: self) {
let f = Double(truncating: n)
return f
}
return 0.0
}
func startsWith(string: String) -> Bool {
guard let range = self.range( of: string, options:[.anchored, .caseInsensitive]) else {
return false
}
return range.lowerBound == startIndex
}
func removeSpecial() -> String {
let okayChars = "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-_"
return self.filter {okayChars.contains($0) }
}
func asciiValue() -> [UInt8] {
var retVal = [UInt8]()
for val in self.unicodeScalars where val.isASCII {
retVal.append(UInt8(val.value))
}
return retVal
}
}
extension String.Index {
func successor(in string: String) -> String.Index {
return string.index(after: self)
}
func predecessor(in string: String) -> String.Index {
return string.index(before: self)
}
func advance(_ offset: Int, `for` string: String) -> String.Index {
return string.index(self, offsetBy: offset)
}
}
extension NSLayoutConstraint {
public static func simpleVisualConstraints( view: NSView, direction: NSString = "H", padding1: Int = 0, padding2: Int = 0 ) -> [NSLayoutConstraint] {
view.translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint.constraints(withVisualFormat: "\(direction):|-\(padding1)-[view]-\(padding2)-|",
options: NSLayoutConstraint.FormatOptions(rawValue: 0),
metrics: nil,
views: ["view": view])
return constraint
}
public static func activateConstraintsEqualToSuperview( child: NSView ) {
if child.superview == nil {
Swift.print("NSLayoutConstraint.fillSuperview() superview of child is nil")
return
}
child.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate( [
child.leadingAnchor.constraint( equalTo: child.superview!.leadingAnchor ),
child.trailingAnchor.constraint( equalTo: child.superview!.trailingAnchor ),
child.topAnchor.constraint( equalTo: child.superview!.topAnchor ),
child.bottomAnchor.constraint( equalTo: child.superview!.bottomAnchor )
])
}
}
| mit | 9c7c118d00cfea21b7c1fa342fdd78ab | 28.201681 | 153 | 0.614964 | 4.639519 | false | false | false | false |
smud/Smud | Sources/Smud/Data/Creature+Find.swift | 1 | 7098 | //
// Creature+Find.swift
//
// This source file is part of the SMUD open source project
//
// Copyright (c) 2016 SMUD project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SMUD project authors
//
import Foundation
public extension Creature {
public enum FindResult {
case creature(Creature)
case item(Item)
case room(Room)
}
public struct SearchEntityTypes: OptionSet {
public let rawValue: Int
public static let creature = SearchEntityTypes(rawValue: 1 << 0)
public static let item = SearchEntityTypes(rawValue: 1 << 1)
public static let room = SearchEntityTypes(rawValue: 1 << 2)
public init(rawValue: Int) { self.rawValue = rawValue }
}
public struct SearchLocations: OptionSet {
public let rawValue: Int
public static let world = SearchLocations(rawValue: 1 << 0)
public static let room = SearchLocations(rawValue: 1 << 1)
public static let inventory = SearchLocations(rawValue: 1 << 2)
public static let equipment = SearchLocations(rawValue: 1 << 3)
public init(rawValue: Int) { self.rawValue = rawValue }
}
public func findCreature(selector: EntitySelector, locations: SearchLocations) -> Creature? {
let result = find(selector: selector, entityTypes: .creature, locations: locations)
guard let first = result.first,
case .creature(let creature) = first else {
return nil
}
return creature
}
public func findOne(selector: EntitySelector, entityTypes: SearchEntityTypes, locations: SearchLocations) -> FindResult? {
guard selector.startingIndex == 1 && selector.count == 1 else {
return nil
}
let results = find(selector: selector, entityTypes: entityTypes, locations: locations)
assert(0...1 ~= results.count)
return results.first
}
public func find(selector: EntitySelector, entityTypes: SearchEntityTypes, locations: SearchLocations) -> [FindResult] {
guard selector.startingIndex > 0 && selector.count > 0 else { return [] }
// Search What | Search Where | Search Locations (any of them should be set)
// Creature | Self | Room or World
if entityTypes.contains(.creature), locations.contains(.room) || locations.contains(.world) {
if case .pattern(let pattern) = selector.type,
selector.startingIndex == 1,
selector.count == 1,
let keyword = pattern.keywords.first,
keyword.isEqual(toOneOf: ["i", "me", "self"], caseInsensitive: true) {
return [.creature(self)]
}
}
var result: [FindResult] = []
var currentIndex = 1
// Returns true if should continue matching
let matchAndAppendCreature: (Creature) -> Bool = { creature in
if selector.matches(creature: creature) {
if currentIndex >= selector.startingIndex {
result.append(.creature(creature))
guard result.count < selector.count else { return false } // finished
}
currentIndex += 1
}
return true // need more
}
// Returns true if should continue matching
let matchAndAppendRoom: (Room) -> Bool = { room in
if selector.matches(room: room) {
if currentIndex >= selector.startingIndex {
result.append(.room(room))
guard result.count < selector.count else { return false } // finished
}
currentIndex += 1
}
return true // need more
}
// Item | Equipment | Equipment or World
// Item | Inventory | Inventory or World
// Creature | Room && !Self | Room or World
if entityTypes.contains(.creature), locations.contains(.room) || locations.contains(.world) {
if let room = room {
for creature in room.creatures {
guard self != creature else { continue }
guard matchAndAppendCreature(creature) else { return result }
}
}
}
// Item | Room | Room or World
// Creature | Instance && !Room && !Self | World
if entityTypes.contains(.creature), locations.contains(.world) {
if let areaInstance = room?.areaInstance {
for (_, currentRoom) in areaInstance.roomsById {
guard currentRoom != room else { continue }
for creature in currentRoom.creatures {
guard self != creature else { continue }
guard matchAndAppendCreature(creature) else { return result }
}
}
}
}
// Item | Instance && !Room | World
// Room | Instance | World
if entityTypes.contains(.room), locations.contains(.world) {
if let areaInstance = room?.areaInstance {
for (_, currentRoom) in areaInstance.roomsById {
guard matchAndAppendRoom(currentRoom) else { return result }
}
}
}
// Creature | World && !Instance && !Room && !Self | World
if entityTypes.contains(.creature), locations.contains(.world) {
for creature in world.creatures {
// If self isn't in any instance, then iterate everybody in world.
// Otherwise, exclude creatures in self's instance from search because they were accounted for already.
guard room?.areaInstance == nil || creature.room?.areaInstance != room?.areaInstance else { continue }
// Instance is taken from room, so we've already excluded room
// This one is probably not neccessary as well, but to be safe:
guard self != creature else { continue }
guard matchAndAppendCreature(creature) else { return result }
}
}
// Item | World && !Room && !Inventory && !Equipment | World
// Room | World && !Instance | World
if entityTypes.contains(.room), locations.contains(.world) {
for (_, currentArea) in world.areasById {
for (_, currentInstance) in currentArea.instancesByIndex {
guard currentInstance != room?.areaInstance else { return result }
for (_, currentRoom) in currentInstance.roomsById {
guard matchAndAppendRoom(currentRoom) else { return result }
}
}
}
}
return result
}
}
| apache-2.0 | 26d2eeb7bfe0bf2b04af64722d7bb25f | 38.653631 | 126 | 0.559031 | 5.12491 | false | false | false | false |
southfox/jfwindguru | JFWindguru/Classes/Model/WForecast.swift | 1 | 15900 | //
// WForecast.swift
// Pods
//
// Created by javierfuchs on 7/17/17.
//
//
import Foundation
/*
* WForecast
*
* Discussion:
* Model object representing forecast information, temperature, cloud cover (total, high,
* middle and lower), relative humidity, wind gusts, sea level pressure, feezing level,
* precipitations, wind (speed and direction)
*
* {
* "initstamp": 1444197600,
* "TMP": [ ],
* "TCDC": [ ],
* "HCDC": [ ],
* "MCDC": [ ],
* "LCDC": [ ],
* "RH": [ ],
* "GUST": [ ],
* "SLP": [ ],
* "FLHGT": [ ],
* "APCP": [ ],
* "WINDSPD": [ ],
* "WINDDIR": [ ],
* "SMERN": [ ], ????
* "WINDIRNAME": [ ],
* "TMPE": [ ],
* "initdate": "2015-10-07 06:00:00",
* "model_name": "GFS 27 km"
* }
*/
public class WForecast: Object, Mappable {
var TMP = [Float]() // TMP: temperature
var TCDC = [Int]() // TCDC: Cloud cover (%) Total
var HCDC = [Int]() // HCDC: Cloud cover (%) High
var MCDC = [Int]() // MCDC: Cloud cover (%) Mid
var LCDC = [Int]() // LCDC: Cloud cover (%) Low
var RH = [Int]() // RH: Relative humidity: relative humidity in percent
var GUST = [Float]() // GUST: Wind gusts (knots)
var SLP = [Int]() // SLP: sea level pressure
var FLHGT = [Int]() // FLHGT: Freezing Level height in meters (0 degree isoterm)
var APCP = [Int]() // APCP: Precip. (mm/3h)
var WINDSPD = [Float]() // WINDSPD: Wind speed (knots)
var WINDDIR = [Int]() // WINDDIR: Wind direction
var SMERN = [Int]()
var SMER = [Int]()
var TMPE = [Float]() // TMPE: temperature in 2 meters above ground with correction to real altitude of the spot.
var PCPT = [Int]()
var HTSGW = [Float]() // HTSGW: Significant Wave Height (Significant Height of Combined Wind Waves and Swell)
var WVHGT = [Float]() // WVHG: Wave height
var WVPER = [Float]() // WVPER: Mean wave period [s]
var WVDIR = [Float]() // WVDIR: Mean wave direction [°]
var SWELL1 = [Float]() // SWELL1: Swell height (m)
var SWPER1 = [Float]() // SWPER1: Swell period
var SWDIR1 = [Float]() // SWDIR1: Swell direction
var SWELL2 = [Float]() // SWELL2: Swell height (m)
var SWPER2 = [Float]() // SWPER2: Swell period
var SWDIR2 = [Float]() // SWDIR2: Swell direction
var PERPW = [Float]() // PERPW: Peak wave period
var DIRPW = [Float]() // DIRPW: Peak wave direction [°]
var hr_weekday = [Int]()
var hr_h = [String]()
var hr_d = [String]()
var hours = [Int]()
var img_param = [String]()
var img_var_map = [String]()
var initDate: String? = nil
var init_d: String? = nil
var init_dm: String? = nil
var init_h: String? = nil
var initstr: String? = nil
var model_name: String? = nil
var model_longname: String? = nil
var id_model: String? = nil
var update_last: String? = nil
var update_next: String? = nil
var initstamp = 0 // initstamp
required public convenience init?(map: [String:Any]) {
self.init()
mapping(map: map)
}
public func mapping(map: [String:Any]) {
TMP = map["TMP"] as? [Float] ?? []
TCDC = map["TCDC"] as? [Int] ?? []
HCDC = map["HCDC"] as? [Int] ?? []
MCDC = map["MCDC"] as? [Int] ?? []
LCDC = map["LCDC"] as? [Int] ?? []
RH = map["RH"] as? [Int] ?? []
GUST = map["GUST"] as? [Float] ?? []
SLP = map["SLP"] as? [Int] ?? []
FLHGT = map["FLHGT"] as? [Int] ?? []
APCP = map["APCP"] as? [Int] ?? []
WINDSPD = map["WINDSPD"] as? [Float] ?? []
WINDDIR = map["WINDDIR"] as? [Int] ?? []
SMERN = map["SMERN"] as? [Int] ?? []
SMER = map["SMER"] as? [Int] ?? []
TMPE = map["TMPE"] as? [Float] ?? []
PCPT = map["PCPT"] as? [Int] ?? []
HTSGW = map["HTSGW"] as? [Float] ?? []
WVHGT = map["WVHGT"] as? [Float] ?? []
WVPER = map["WVPER"] as? [Float] ?? []
WVDIR = map["WVDIR"] as? [Float] ?? []
SWELL1 = map["SWELL1"] as? [Float] ?? []
SWPER1 = map["SWPER1"] as? [Float] ?? []
SWDIR1 = map["SWDIR1"] as? [Float] ?? []
SWELL2 = map["SWELL2"] as? [Float] ?? []
SWPER2 = map["SWPER2"] as? [Float] ?? []
SWDIR2 = map["SWDIR2"] as? [Float] ?? []
PERPW = map["PERPW"] as? [Float] ?? []
DIRPW = map["DIRPW"] as? [Float] ?? []
hr_weekday = map["hr_weekday"] as? [Int] ?? []
hr_h = map["hr_h"] as? [String] ?? []
hr_d = map["hr_d"] as? [String] ?? []
hours = map["hours"] as? [Int] ?? []
img_param = map["img_param"] as? [String] ?? []
img_var_map = map["img_var_map"] as? [String] ?? []
initDate = map["initdate"] as? String
init_d = map["init_d"] as? String
init_dm = map["init_dm"] as? String
init_h = map["init_h"] as? String
initstr = map["initstr"] as? String
model_name = map["model_name"] as? String
model_longname = map["model_longname"] as? String
id_model = map["id_model"] as? String
update_last = map["update_last"] as? String
update_next = map["update_next"] as? String
initstamp = map["initstamp"] as? Int ?? 0
}
public var description : String {
var aux : String = "\(type(of:self)): "
aux += "initstamp: \(initstamp)\n"
aux += "TCDC = Cloud cover Total: \(TCDC)\n"
aux += "HCDC = Cloud cover High: \(HCDC)\n"
aux += "MCDC = Cloud cover Mid: \(MCDC)\n"
aux += "LCDC = Cloud cover Low: \(LCDC)\n"
aux += "RH = Humidity: \(RH)\n"
aux += "SLP = Sea Level pressure: \(SLP)\n"
aux += "FLHGT = Freezing level: \(FLHGT)\n"
aux += "APCP = Precipitation: \(APCP)\n"
aux += "GUST = Wind gust: \(GUST)\n"
aux += "WINDSPD = Wind speed: \(WINDSPD)\n"
aux += "WINDDIR = Wind direccion: \(WINDDIR)\n"
aux += "SMERN: \(SMERN)\n"
aux += "SMER: \(SMER)\n"
aux += "TMP = Temp: \(TMP)\n"
aux += "TMPE = Temp real: \(TMPE)\n"
aux += "PCPT: \(PCPT)\n"
aux += "HTSGW: \(HTSGW)\n"
aux += "WVHGT: \(WVHGT)\n"
aux += "WVPER: \(WVPER)\n"
aux += "WVDIR: \(WVDIR)\n"
aux += "SWELL1: \(SWELL1)\n"
aux += "SWPER1: \(SWPER1)\n"
aux += "SWDIR1: \(SWDIR1)\n"
aux += "SWELL2: \(SWELL2)\n"
aux += "SWPER2: \(SWPER2)\n"
aux += "SWDIR2: \(SWDIR2)\n"
aux += "PERPW: \(PERPW)\n"
aux += "DIRPW: \(DIRPW)\n"
aux += "hr_weekday: \(hr_weekday)\n"
aux += "hr_h: \(hr_h)\n"
aux += "hr_d: \(hr_d)\n"
aux += "hours: \(hours)\n"
aux += "img_param: \(img_param), "
aux += "img_var_map: \(img_var_map).\n"
aux += "initDate: \(initDate ?? ""), "
aux += "init_d: \(init_d ?? ""), "
aux += "init_dm: \(init_dm ?? ""), "
aux += "init_h: \(init_h ?? ""), "
aux += "initstr: \(initstr ?? "")\n"
aux += "modelName: \(model_name ?? ""), "
aux += "model_longname: \(model_longname ?? ""), "
aux += "id_model: \(id_model ?? "")\n"
aux += "update_last: \(update_last ?? ""), "
aux += "update_next: \(update_next ?? "")\n"
return aux
}
}
extension WForecast {
// Thanks: https://www.campbellsci.com/blog/convert-wind-directions
static public func windDirectionName(direction: Int) -> String? {
let compass = ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW","N"]
let module = Double(direction % 360)
let index = Int(module / 22.5) + 1 // degrees for each sector
if index >= 0 && index < compass.count {
return compass[index]
}
return nil
}
public func numberOfHours() -> Int {
return hours.count
}
public func hour24(hour: Int) -> String? {
if hr_h.count > 0 && hour < hr_h.count {
return hr_h[hour]
}
return nil
}
public func day(hour: Int) -> String? {
if hr_d.count > 0 && hour < hr_d.count {
return hr_d[hour]
}
return nil
}
public func weekday(hour: Int) -> String? {
if hr_weekday.count > 0 && hour < hr_weekday.count {
let w = hr_weekday[hour]
switch w {
case 0: return "Sunday"
case 1: return "Monday"
case 2: return "Tuesday"
case 3: return "Wednesday"
case 4: return "Thursday"
case 5: return "Friday"
case 6: return "Saturday"
default:
return nil
}
}
return nil
}
public func temperature(hour: Int) -> Float? {
if TMP.count > 0 && hour < TMP.count {
return TMP[hour]
}
return nil
}
public func temperatureReal(hour: Int) -> Float? {
if TMPE.count > 0 && hour < TMPE.count {
return TMPE[hour]
}
return nil
}
public func relativeHumidity(hour: Int) -> Int? {
if RH.count > 0 && hour < RH.count {
return RH[hour]
}
return nil
}
public func smern(hour: Int) -> Int? {
if SMERN.count > 0 && hour < SMERN.count {
return SMERN[hour]
}
return nil
}
public func smer(hour: Int) -> Int? {
if SMER.count > 0 && hour < SMERN.count {
return SMER[hour]
}
return nil
}
private func windSpeed(hour: Int) -> Float? {
if WINDSPD.count > 0 && hour < WINDSPD.count {
return WINDSPD[hour]
}
return nil
}
public func windSpeedKnots(hour: Int) -> Float? {
return windSpeed(hour:hour)
}
public func windSpeedKmh(hour: Int) -> Float? {
if let knots = windSpeed(hour:hour) {
var knotsBft = Knots.init(value: knots)
return knotsBft.kmh()
}
return nil
}
public func windSpeedMph(hour: Int) -> Float? {
if let knots = windSpeed(hour:hour) {
var knotsBft = Knots.init(value: knots)
return knotsBft.mph()
}
return nil
}
public func windSpeedMps(hour: Int) -> Float? {
if let knots = windSpeed(hour:hour) {
var knotsBft = Knots.init(value: knots)
return knotsBft.mps()
}
return nil
}
public func windSpeedBft(hour: Int) -> Int? {
if let knots = windSpeed(hour:hour) {
var knotsBft = Knots.init(value: knots)
return knotsBft.bft()
}
return nil
}
public func windSpeedBftEffect(hour: Int) -> String? {
if let knots = windSpeed(hour:hour) {
var knotsBft = Knots.init(value: knots)
return knotsBft.effect()
}
return nil
}
public func windSpeedBftEffectOnSea(hour: Int) -> String? {
if let knots = windSpeed(hour:hour) {
var knotsBft = Knots.init(value: knots)
return knotsBft.effectOnSea()
}
return nil
}
public func windSpeedBftEffectOnLand(hour: Int) -> String? {
if let knots = windSpeed(hour:hour) {
var knotsBft = Knots.init(value: knots)
return knotsBft.effectOnLand()
}
return nil
}
public func windDirection(hour: Int) -> Int? {
if WINDDIR.count > 0 && hour < WINDDIR.count {
return WINDDIR[hour]
}
return nil
}
public func windDirectionName(hour: Int) -> String? {
if let direction = windDirection(hour: hour) {
return WForecast.windDirectionName(direction:direction)
}
return nil
}
public func windGust(hour: Int) -> Float? {
if GUST.count > 0 && hour < GUST.count {
return GUST[hour]
}
return nil
}
public func perpw(hour: Int) -> Float? {
if PERPW.count > 0 && hour < PERPW.count {
return PERPW[hour]
}
return nil
}
public func wvhgt(hour: Int) -> Float? {
if WVHGT.count > 0 && hour < WVHGT.count {
return WVHGT[hour]
}
return nil
}
public func wvper(hour: Int) -> Float? {
if WVPER.count > 0 && hour < WVPER.count {
return WVPER[hour]
}
return nil
}
public func wvdir(hour: Int) -> Float? {
if WVDIR.count > 0 && hour < WVDIR.count {
return WVDIR[hour]
}
return nil
}
public func swell1(hour: Int) -> Float? {
if SWELL1.count > 0 && hour < SWELL1.count {
return SWELL1[hour]
}
return nil
}
public func swper1(hour: Int) -> Float? {
if SWPER1.count > 0 && hour < SWPER1.count {
return SWPER1[hour]
}
return nil
}
public func swdir1(hour: Int) -> Float? {
if SWDIR1.count > 0 && hour < SWDIR1.count {
return SWDIR1[hour]
}
return nil
}
public func swell2(hour: Int) -> Float? {
if SWELL2.count > 0 && hour < SWELL2.count {
return SWELL2[hour]
}
return nil
}
public func swper2(hour: Int) -> Float? {
if SWPER2.count > 0 && hour < SWPER2.count {
return SWPER2[hour]
}
return nil
}
public func swdir2(hour: Int) -> Float? {
if SWDIR2.count > 0 && hour < SWDIR2.count {
return SWDIR2[hour]
}
return nil
}
public func dirpw(hour: Int) -> Float? {
if DIRPW.count > 0 && hour < DIRPW.count {
return DIRPW[hour]
}
return nil
}
public func htsgw(hour: Int) -> Float? {
if HTSGW.count > 0 && hour < HTSGW.count {
return HTSGW[hour]
}
return nil
}
public func cloudCoverTotal(hour: Int) -> Int? {
if TCDC.count > 0 && hour < TCDC.count {
return TCDC[hour]
}
return nil
}
public func cloudCoverHigh(hour: Int) -> Int? {
if HCDC.count > 0 && hour < HCDC.count {
return HCDC[hour]
}
return nil
}
public func cloudCoverMid(hour: Int) -> Int? {
if MCDC.count > 0 && hour < MCDC.count {
return MCDC[hour]
}
return nil
}
public func cloudCoverLow(hour: Int) -> Int? {
if LCDC.count > 0 && hour < LCDC.count {
return LCDC[hour]
}
return nil
}
public func precipitation(hour: Int) -> Int? {
if APCP.count > 0 && hour < APCP.count {
return APCP[hour]
}
return nil
}
public func pcpt(hour: Int) -> Int? {
if PCPT.count > 0 && hour < PCPT.count {
return PCPT[hour]
}
return nil
}
public func seaLevelPressure(hour: Int) -> Int? {
if SLP.count > 0 && hour < SLP.count {
return SLP[hour]
}
return nil
}
public func freezingLevel(hour: Int) -> Int? {
if FLHGT.count > 0 && hour < FLHGT.count {
return FLHGT[hour]
}
return nil
}
public func lastUpdate() -> String? {
return update_last
}
}
| mit | e11ba247ee7ad83e149fa3e514d951c3 | 30.111546 | 123 | 0.483457 | 3.453834 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Home/Pocket/StoryProvider.swift | 2 | 2413 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
class StoryProvider: FeatureFlaggable {
private let numberOfPocketStories: Int
private let sponsoredIndices: [Int]
init(
pocketAPI: PocketStoriesProviding,
pocketSponsoredAPI: PocketSponsoredStoriesProviding,
numberOfPocketStories: Int = 11,
sponsoredIndices: [Int] = [1, 9]
) {
self.pocketAPI = pocketAPI
self.pocketSponsoredAPI = pocketSponsoredAPI
self.numberOfPocketStories = numberOfPocketStories
self.sponsoredIndices = sponsoredIndices
}
private let pocketAPI: PocketStoriesProviding
private let pocketSponsoredAPI: PocketSponsoredStoriesProviding
private func insert(
sponsoredStories: [PocketStory],
into globalFeed: [PocketStory],
indices: [Int]
) -> [PocketStory] {
var global = globalFeed
var sponsored = sponsoredStories
for index in indices {
// Making sure we insert a sponsored story at a valid index
let normalisedIndex = min(index, global.endIndex)
if let first = sponsored.first {
global.insert(first, at: normalisedIndex)
sponsored.removeAll(where: { $0 == first })
}
}
return global
}
func fetchPocketStories() async -> [PocketStory] {
let global = (try? await pocketAPI.fetchStories(items: numberOfPocketStories)) ?? []
// Convert global feed to PocketStory
var globalTemp = global.map(PocketStory.init)
if featureFlags.isFeatureEnabled(.sponsoredPocket, checking: .buildAndUser),
let sponsored = try? await pocketSponsoredAPI.fetchSponsoredStories() {
// Convert sponsored feed to PocketStory, take the desired number of sponsored stories
let sponsoredTemp = Array(sponsored.map(PocketStory.init).prefix(sponsoredIndices.count))
globalTemp = Array(globalTemp.prefix(numberOfPocketStories - sponsoredIndices.count))
globalTemp = insert(
sponsoredStories: sponsoredTemp,
into: globalTemp,
indices: sponsoredIndices
)
}
return globalTemp
}
}
| mpl-2.0 | 68f0b2eb967f763abb317f902e2088c2 | 36.703125 | 101 | 0.655615 | 4.622605 | false | false | false | false |
kwonye/restr | Restr/Calculator/HarrisBenedictCalculator.swift | 1 | 1355 |
//
// HarrisBenedictCalculator.swift
// Restr
//
// Created by Will Kwon on 2/4/15.
// Copyright (c) 2015 Ourly. All rights reserved.
//
import Foundation
import HealthKit
class HarrisBenedictCalculator: NSObject {
let healthKitStore: HKHealthStore = HKHealthStore()
func dailyRestingRate() {
// let sex = try? healthKitStore.biologicalSexWithError()
// let age = self.ageOfPerson(birthday: try! healthKitStore.dateOfBirthWithError())
// let weight = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
}
func dailyRestingRate(sex: HKBiologicalSexObject, age: NSInteger, weightInKilograms: Double, heightInCentimeters: NSInteger) {
}
func ageOfPerson(birthday birthday: NSDate) -> NSInteger {
let ageComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.Year, fromDate: birthday, toDate: NSDate(), options: NSCalendarOptions.WrapComponents)
return ageComponents.year;
}
func weightOfPerson() -> Double {
// let weightType: HKQuantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
// self.healthKitStore.aa
//
// return weight.doubleValueForUnit(HKUnit.gramUnitWithMetricPrefix(HKMetricPrefix.Kilo))
return 1.0
}
} | mit | e404fcf20c6c5fad18727930eb64d4bf | 31.285714 | 169 | 0.701107 | 4.531773 | false | false | false | false |
yusayusa/PlaceholderTextView | PlaceholderTextView/PlaceholderTextView.swift | 1 | 2174 | //
// PlaceholderTextView.swift
// PlaceholderTextView
//
// Created by KazukiYusa on 2017/02/06.
// Copyright © 2017年 KazukiYusa. All rights reserved.
//
import UIKit
extension UITextView {
// MARK: - Properties
private struct StoredProperties {
static var placeholderLabel: Void?
}
private var placeholderLabel: UILabel? {
get {
let value = objc_getAssociatedObject(self, &StoredProperties.placeholderLabel) as? UILabel
return value
}
set {
objc_setAssociatedObject(self,
&StoredProperties.placeholderLabel,
newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Functions
public func setPlaceholder(attribute: NSAttributedString) {
guard placeholderLabel == nil else {
return
}
configurePlaceholder(attribute: attribute)
NotificationCenter.default
.addObserver(forName: NSNotification.Name.UITextViewTextDidChange,
object: nil,
queue: nil,
using: { [weak self] _ in
guard let `self` = self else { return }
self.placeholderLabel?.isHidden = !self.text.isEmpty
})
}
private func configurePlaceholder(attribute: NSAttributedString) {
guard placeholderLabel == nil else {
return
}
let label: UILabel = .init()
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
label.isHidden = !text.isEmpty
label.attributedText = attribute
addSubview(label)
label.topAnchor
.constraint(equalTo: layoutMarginsGuide.topAnchor)
.isActive = true
label.leadingAnchor
.constraint(equalTo: layoutMarginsGuide.leadingAnchor)
.isActive = true
label.trailingAnchor
.constraint(equalTo: layoutMarginsGuide.trailingAnchor)
.isActive = true
label.bottomAnchor
.constraint(lessThanOrEqualTo: layoutMarginsGuide.bottomAnchor)
.isActive = true
placeholderLabel = label
}
}
| mit | d9bf4e4dfed52638958ed2ce032909fb | 25.47561 | 96 | 0.627821 | 5.468514 | false | false | false | false |
daniel-barros/ExtendedUIKit | Sources/common/Extensions/String.swift | 2 | 2316 | //
// String.swift
// ExtendedUIKit
//
// Created by Daniel Barros López on 11/5/16.
//
// Copyright (c) 2016 - 2017 Daniel Barros López
//
// 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 ExtendedFoundation
import UIKit
public extension String {
/// Use one or more parameters to create an attributed string with certain properties.
///
/// A nil parameter will be ignored.
func with(font: UIFont? = nil,
color: UIColor? = nil,
lineSpacing: CGFloat? = nil,
paragraphSpacing: CGFloat? = nil,
lineBreakMode: NSLineBreakMode? = nil) -> NSAttributedString {
var attributes: [NSAttributedStringKey: Any] = [:]
attributes[.font] =? font
attributes[.foregroundColor] =? color
if lineSpacing != nil || paragraphSpacing != nil || lineBreakMode != nil {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing =? paragraphSpacing
paragraphStyle.lineBreakMode =? lineBreakMode
paragraphStyle.lineSpacing =? lineSpacing
attributes[.paragraphStyle] = paragraphStyle
}
return NSAttributedString(string: self, attributes: attributes)
}
}
| mit | b2a797c51c5f26e670fe9ac83de7ef76 | 41.072727 | 90 | 0.687554 | 4.902542 | false | false | false | false |
priyax/TextToSpeech | textToTableViewController/textToTableViewController/RegisterViewController.swift | 1 | 4951 | //
// RegisterViewController.swift
// textToTableViewController
//
// Created by Priya Xavier on 10/6/16.
// Copyright © 2016 Guild/SA. All rights reserved.
//
import UIKit
class RegisterViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailFieldReg: UITextField!
@IBOutlet weak var passwordFieldReg: UITextField!
@IBOutlet weak var confirmPasswordField: UITextField!
@IBAction func cancelBtn(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
@IBOutlet weak var regBtn: UIButton!
@IBAction func register(_ sender: UIButton) {
if !Utility.isValidEmail(emailAddress: emailFieldReg.text!) {
Utility.showAlert(viewController: self, title: "Registration Error", message: "Please enter a valid email address.")
return
}
if passwordFieldReg.text != confirmPasswordField.text {
Utility.showAlert(viewController: self, title: "Registration Error", message: "Password confirmation failed. Plase enter your password try again.")
return
}
//spinner.startAnimating()
let email = emailFieldReg.text!
let password = passwordFieldReg.text!
BackendlessManager.sharedInstance.registerUser(email: email, password: password,
completion: {
BackendlessManager.sharedInstance.loginUser(email: email, password: password,
completion: {
// self.spinner.stopAnimating()
self.performSegue(withIdentifier: "gotoSavedRecipesFromRegister", sender: sender)
},
error: { message in
// self.spinner.stopAnimating()
Utility.showAlert(viewController: self, title: "Login Error", message: message)
})
},
error: { message in
// self.spinner.stopAnimating()
Utility.showAlert(viewController: self, title: "Register Error", message: message)
})
}
override func viewDidLoad() {
super.viewDidLoad()
emailFieldReg.addTarget(self, action: #selector(textFieldChanged(textField:)), for: UIControlEvents.editingChanged)
passwordFieldReg.addTarget(self, action: #selector(textFieldChanged(textField:)), for: UIControlEvents.editingChanged)
confirmPasswordField.addTarget(self, action: #selector(textFieldChanged(textField:)), for: UIControlEvents.editingChanged)
self.emailFieldReg.delegate = self
self.passwordFieldReg.delegate = self
self.confirmPasswordField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//facebook and twitter login
@IBAction func loginViaFacebook(_ sender: UIButton) {
BackendlessManager.sharedInstance.loginViaFacebook(completion: {
}, error: { message in
Utility.showAlert(viewController: self, title: "Login Error", message: message)
})
}
@IBAction func loginViaTwitter(_ sender: UIButton) {
BackendlessManager.sharedInstance.loginViaTwitter(completion: {
}, error: { message in
Utility.showAlert(viewController: self, title: "Login Error", message: message)
})
}
//Hide Keyboard when user touches outside keyboard
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
//Presses return key to exit keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return (true)
}
func textFieldChanged(textField: UITextField) {
if emailFieldReg.text == "" || passwordFieldReg.text == "" || confirmPasswordField.text == "" {
regBtn.isEnabled = false
} else {
regBtn.isEnabled = true
}
}
// UITextFieldDelegate, called when editing session begins, or when keyboard displayed
func textFieldDidBeginEditing(_ textField: UITextField) {
// Create padding for textFields
let paddingView = UIView(frame:CGRect(x: 0, y: 0, width: 20, height: 20))
textField.leftView = paddingView
textField.leftViewMode = UITextFieldViewMode.always
if textField == emailFieldReg {
emailFieldReg.placeholder = "Email"
} else if textField == passwordFieldReg {
passwordFieldReg.placeholder = "Password"
} else {
confirmPasswordField.placeholder = "Confirm password"}
}
}
| mit | 8654db39c9d95220d55c5b8255d9baf0 | 35.397059 | 159 | 0.613333 | 5.568054 | false | false | false | false |
AkshayNG/iSwift | iSwift/UI Components/UILabel/UIMoreTextLabel.swift | 1 | 5324 | //
// UIMoreTextLabel.swift
// iSwift
//
// Created by Akshay Gajarlawar on 24/03/19.
// Copyright © 2019 yantrana. All rights reserved.
//
import UIKit
class UIMoreTextLabel: UILabel, UIGestureRecognizerDelegate {
var onTapMoreText: (() -> Void)?
private var rangeOfMoreText:NSRange?
private var isAddedMoreText = false
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func set(moreText text:String, withAction action:(() -> Void)?) {
self.addMoreText(moreText: text)
self.onTapMoreText = action
}
func visibleText()-> String?
{
guard let fullText = text else { return nil }
var textVisible = fullText
let sizeConstraint = CGSize.init(width: frame.size.width, height: CGFloat.greatestFiniteMagnitude)
for i in 1...(fullText.count - 1) {
let subStr = (fullText as NSString).substring(to: i)
let attributedText = NSAttributedString.init(string: subStr, attributes: [NSAttributedStringKey.font : font])
let boundingRect = attributedText.boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, context: nil)
if boundingRect.height > frame.size.height {
break
}
textVisible = subStr
}
return textVisible
}
private func addMoreText(moreText:String)
{
if isAddedMoreText { return }
guard let textVisible = self.visibleText() else { return }
let appendText = "... \(moreText)"
let range = NSRange.init(location: textVisible.count - (appendText.count+2), length: appendText.count+2)
if range.location == NSNotFound { return }
let newText = (textVisible as NSString).replacingCharacters(in: range, with: appendText)
let moreRange = NSRange.init(location: newText.count - moreText.count, length: moreText.count)
let attrText = NSMutableAttributedString.init(string: newText)
attrText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.colorFromHexString(hex:"4286f4"), range: moreRange)
self.attributedText = attrText
rangeOfMoreText = moreRange
isAddedMoreText = true
self.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer.init(target: self, action: #selector(labelTapped(tapGesture:)))
tap.numberOfTapsRequired = 1
tap.delegate = self
self.addGestureRecognizer(tap)
}
@objc private func labelTapped(tapGesture:UITapGestureRecognizer)
{
if(didTapMoreText(gesture: tapGesture)) {
if let callback = self.onTapMoreText {
callback()
}
}
}
private func didTapMoreText(gesture:UITapGestureRecognizer) -> Bool
{
guard let targetRange = rangeOfMoreText else { return false }
guard let attrString = self.attributedText else { return false }
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: .zero)
let textStorage = NSTextStorage(attributedString: attrString)
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
textContainer.lineFragmentPadding = 0
textContainer.lineBreakMode = self.lineBreakMode
textContainer.maximumNumberOfLines = self.numberOfLines
let labelSize = self.bounds.size
textContainer.size = labelSize
let locationOfTouchInLabel = gesture.location(in: self)
let textBoundingBox = layoutManager.usedRect(for: textContainer)
let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
let inRange = NSLocationInRange(indexOfCharacter, targetRange)
if inRange {
let attributedString = NSMutableAttributedString(attributedString: attrString)
attributedString.addAttributes([.backgroundColor: UIColor.lightGray.withAlphaComponent(0.5)], range: targetRange)
attributedText = attributedString
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.indicateState(attributedString)
self.setNeedsDisplay()
}
}
return inRange
}
private func indicateState(_ attributedString: NSMutableAttributedString) {
guard let targetRange = rangeOfMoreText else { return }
attributedString.addAttributes([.backgroundColor: UIColor.clear], range: targetRange)
attributedText = attributedString
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| mit | 4d495d4b50c4c2d721e930f2e259abdb | 41.246032 | 211 | 0.671426 | 5.218627 | false | false | false | false |
bolshedvorsky/swift-corelibs-foundation | Foundation/CharacterSet.swift | 4 | 20812 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
private func _utfRangeToNSRange(_ inRange : Range<UnicodeScalar>) -> NSRange {
return NSRange(location: Int(inRange.lowerBound.value), length: Int(inRange.upperBound.value - inRange.lowerBound.value))
}
private func _utfRangeToNSRange(_ inRange : ClosedRange<UnicodeScalar>) -> NSRange {
return NSRange(location: Int(inRange.lowerBound.value), length: Int(inRange.upperBound.value - inRange.lowerBound.value + 1))
}
internal final class _SwiftNSCharacterSet : NSCharacterSet, _SwiftNativeFoundationType {
internal typealias ImmutableType = NSCharacterSet
internal typealias MutableType = NSMutableCharacterSet
var __wrapped : _MutableUnmanagedWrapper<ImmutableType, MutableType>
init(immutableObject: AnyObject) {
// Take ownership.
__wrapped = .Immutable(Unmanaged.passRetained(_unsafeReferenceCast(immutableObject, to: ImmutableType.self)))
super.init()
}
init(mutableObject: AnyObject) {
// Take ownership.
__wrapped = .Mutable(Unmanaged.passRetained(_unsafeReferenceCast(mutableObject, to: MutableType.self)))
super.init()
}
internal required init(unmanagedImmutableObject: Unmanaged<ImmutableType>) {
// Take ownership.
__wrapped = .Immutable(unmanagedImmutableObject)
super.init()
}
internal required init(unmanagedMutableObject: Unmanaged<MutableType>) {
// Take ownership.
__wrapped = .Mutable(unmanagedMutableObject)
super.init()
}
convenience required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
releaseWrappedObject()
}
override func copy(with zone: NSZone? = nil) -> Any {
return _mapUnmanaged { $0.copy(with: zone) }
}
override func mutableCopy(with zone: NSZone? = nil) -> Any {
return _mapUnmanaged { $0.mutableCopy(with: zone) }
}
public override var classForCoder: AnyClass {
return NSCharacterSet.self
}
override var bitmapRepresentation: Data {
return _mapUnmanaged { $0.bitmapRepresentation }
}
override var inverted : CharacterSet {
return _mapUnmanaged { $0.inverted }
}
override func hasMemberInPlane(_ thePlane: UInt8) -> Bool {
return _mapUnmanaged {$0.hasMemberInPlane(thePlane) }
}
override func characterIsMember(_ member: unichar) -> Bool {
return _mapUnmanaged { $0.characterIsMember(member) }
}
override func longCharacterIsMember(_ member: UInt32) -> Bool {
return _mapUnmanaged { $0.longCharacterIsMember(member) }
}
override func isSuperset(of other: CharacterSet) -> Bool {
return _mapUnmanaged { $0.isSuperset(of: other) }
}
override var _cfObject: CFType {
// We cannot inherit super's unsafeBitCast(self, to: CFType.self) here, because layout of _SwiftNSCharacterSet
// is not compatible with CFCharacterSet. We need to bitcast the underlying NSCharacterSet instead.
return _mapUnmanaged { unsafeBitCast($0, to: CFType.self) }
}
}
/**
A `CharacterSet` represents a set of Unicode-compliant characters. Foundation types use `CharacterSet` to group characters together for searching operations, so that they can find any of a particular set of characters during a search.
This type provides "copy-on-write" behavior, and is also bridged to the Objective-C `NSCharacterSet` class.
*/
public struct CharacterSet : ReferenceConvertible, Equatable, Hashable, SetAlgebra, _MutablePairBoxing {
public typealias ReferenceType = NSCharacterSet
internal typealias SwiftNSWrapping = _SwiftNSCharacterSet
internal typealias ImmutableType = SwiftNSWrapping.ImmutableType
internal typealias MutableType = SwiftNSWrapping.MutableType
internal var _wrapped : _SwiftNSCharacterSet
// MARK: Init methods
internal init(_bridged characterSet: NSCharacterSet) {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
_wrapped = _SwiftNSCharacterSet(immutableObject: characterSet.copy() as! NSObject)
}
/// Initialize an empty instance.
public init() {
_wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet())
}
/// Initialize with a range of integers.
///
/// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired.
public init(charactersIn range: Range<UnicodeScalar>) {
_wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(range: _utfRangeToNSRange(range)))
}
/// Initialize with a closed range of integers.
///
/// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired.
public init(charactersIn range: ClosedRange<UnicodeScalar>) {
_wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(range: _utfRangeToNSRange(range)))
}
/// Initialize with the characters in the given string.
///
/// - parameter string: The string content to inspect for characters.
public init(charactersIn string: String) {
_wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(charactersIn: string))
}
/// Initialize with a bitmap representation.
///
/// This method is useful for creating a character set object with data from a file or other external data source.
/// - parameter data: The bitmap representation.
public init(bitmapRepresentation data: Data) {
_wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(bitmapRepresentation: data))
}
/// Initialize with the contents of a file.
///
/// Returns `nil` if there was an error reading the file.
/// - parameter file: The file to read.
public init?(contentsOfFile file: String) {
if let interior = NSCharacterSet(contentsOfFile: file) {
_wrapped = _SwiftNSCharacterSet(immutableObject: interior)
} else {
return nil
}
}
public var hashValue: Int {
return _mapUnmanaged { $0.hashValue }
}
public var description: String {
return _mapUnmanaged { $0.description }
}
public var debugDescription: String {
return _mapUnmanaged { $0.debugDescription }
}
private init(reference: NSCharacterSet) {
_wrapped = _SwiftNSCharacterSet(immutableObject: reference)
}
// MARK: Static functions
/// Returns a character set containing the characters in Unicode General Category Cc and Cf.
public static var controlCharacters : CharacterSet {
return NSCharacterSet.controlCharacters
}
/// Returns a character set containing the characters in Unicode General Category Zs and `CHARACTER TABULATION (U+0009)`.
public static var whitespaces : CharacterSet {
return NSCharacterSet.whitespaces
}
/// Returns a character set containing characters in Unicode General Category Z*, `U+000A ~ U+000D`, and `U+0085`.
public static var whitespacesAndNewlines : CharacterSet {
return NSCharacterSet.whitespacesAndNewlines
}
/// Returns a character set containing the characters in the category of Decimal Numbers.
public static var decimalDigits : CharacterSet {
return NSCharacterSet.decimalDigits
}
/// Returns a character set containing the characters in Unicode General Category L* & M*.
public static var letters : CharacterSet {
return NSCharacterSet.letters
}
/// Returns a character set containing the characters in Unicode General Category Ll.
public static var lowercaseLetters : CharacterSet {
return NSCharacterSet.lowercaseLetters
}
/// Returns a character set containing the characters in Unicode General Category Lu and Lt.
public static var uppercaseLetters : CharacterSet {
return NSCharacterSet.uppercaseLetters
}
/// Returns a character set containing the characters in Unicode General Category M*.
public static var nonBaseCharacters : CharacterSet {
return NSCharacterSet.nonBaseCharacters
}
/// Returns a character set containing the characters in Unicode General Categories L*, M*, and N*.
public static var alphanumerics : CharacterSet {
return NSCharacterSet.alphanumerics
}
/// Returns a character set containing individual Unicode characters that can also be represented as composed character sequences (such as for letters with accents), by the definition of "standard decomposition" in version 3.2 of the Unicode character encoding standard.
public static var decomposables : CharacterSet {
return NSCharacterSet.decomposables
}
/// Returns a character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard.
public static var illegalCharacters : CharacterSet {
return NSCharacterSet.illegalCharacters
}
/// Returns a character set containing the characters in Unicode General Category P*.
public static var punctuationCharacters : CharacterSet {
return NSCharacterSet.punctuationCharacters
}
/// Returns a character set containing the characters in Unicode General Category Lt.
public static var capitalizedLetters : CharacterSet {
return NSCharacterSet.capitalizedLetters
}
/// Returns a character set containing the characters in Unicode General Category S*.
public static var symbols : CharacterSet {
return NSCharacterSet.symbols
}
/// Returns a character set containing the newline characters (`U+000A ~ U+000D`, `U+0085`, `U+2028`, and `U+2029`).
public static var newlines : CharacterSet {
return NSCharacterSet.newlines
}
// MARK: Static functions, from NSURL
/// Returns the character set for characters allowed in a user URL subcomponent.
public static var urlUserAllowed : CharacterSet {
return NSCharacterSet.urlUserAllowed
}
/// Returns the character set for characters allowed in a password URL subcomponent.
public static var urlPasswordAllowed : CharacterSet {
return NSCharacterSet.urlPasswordAllowed
}
/// Returns the character set for characters allowed in a host URL subcomponent.
public static var urlHostAllowed : CharacterSet {
return NSCharacterSet.urlHostAllowed
}
/// Returns the character set for characters allowed in a path URL component.
public static var urlPathAllowed : CharacterSet {
return NSCharacterSet.urlPathAllowed
}
/// Returns the character set for characters allowed in a query URL component.
public static var urlQueryAllowed : CharacterSet {
return NSCharacterSet.urlQueryAllowed
}
/// Returns the character set for characters allowed in a fragment URL component.
public static var urlFragmentAllowed : CharacterSet {
return NSCharacterSet.urlFragmentAllowed
}
// MARK: Immutable functions
/// Returns a representation of the `CharacterSet` in binary format.
public var bitmapRepresentation: Data {
return _mapUnmanaged { $0.bitmapRepresentation }
}
/// Returns an inverted copy of the receiver.
public var inverted : CharacterSet {
return _mapUnmanaged { $0.inverted }
}
/// Returns true if the `CharacterSet` has a member in the specified plane.
///
/// This method makes it easier to find the plane containing the members of the current character set. The Basic Multilingual Plane (BMP) is plane 0.
public func hasMember(inPlane plane: UInt8) -> Bool {
return _mapUnmanaged { $0.hasMemberInPlane(plane) }
}
// MARK: Mutable functions
/// Insert a range of integer values in the `CharacterSet`.
///
/// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired.
public mutating func insert(charactersIn range: Range<UnicodeScalar>) {
let nsRange = _utfRangeToNSRange(range)
_applyUnmanagedMutation {
$0.addCharacters(in: nsRange)
}
}
/// Insert a closed range of integer values in the `CharacterSet`.
///
/// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired.
public mutating func insert(charactersIn range: ClosedRange<UnicodeScalar>) {
let nsRange = _utfRangeToNSRange(range)
_applyUnmanagedMutation {
$0.addCharacters(in: nsRange)
}
}
/// Remove a range of integer values from the `CharacterSet`.
public mutating func remove(charactersIn range: Range<UnicodeScalar>) {
let nsRange = _utfRangeToNSRange(range)
_applyUnmanagedMutation {
$0.removeCharacters(in: nsRange)
}
}
/// Remove a closed range of integer values from the `CharacterSet`.
public mutating func remove(charactersIn range: ClosedRange<UnicodeScalar>) {
let nsRange = _utfRangeToNSRange(range)
_applyUnmanagedMutation {
$0.removeCharacters(in: nsRange)
}
}
/// Insert the values from the specified string into the `CharacterSet`.
public mutating func insert(charactersIn string: String) {
_applyUnmanagedMutation {
$0.addCharacters(in: string)
}
}
/// Remove the values from the specified string from the `CharacterSet`.
public mutating func remove(charactersIn string: String) {
_applyUnmanagedMutation {
$0.removeCharacters(in: string)
}
}
/// Invert the contents of the `CharacterSet`.
public mutating func invert() {
_applyUnmanagedMutation { $0.invert() }
}
// -----
// MARK: -
// MARK: SetAlgebraType
/// Insert a `UnicodeScalar` representation of a character into the `CharacterSet`.
///
/// `UnicodeScalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func insert(_ character: UnicodeScalar) -> (inserted: Bool, memberAfterInsert: UnicodeScalar) {
let nsRange = NSRange(location: Int(character.value), length: 1)
_applyUnmanagedMutation {
$0.addCharacters(in: nsRange)
}
// TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet
return (true, character)
}
/// Insert a `UnicodeScalar` representation of a character into the `CharacterSet`.
///
/// `UnicodeScalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func update(with character: UnicodeScalar) -> UnicodeScalar? {
let nsRange = NSRange(location: Int(character.value), length: 1)
_applyUnmanagedMutation {
$0.addCharacters(in: nsRange)
}
// TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet
return character
}
/// Remove a `UnicodeScalar` representation of a character from the `CharacterSet`.
///
/// `UnicodeScalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func remove(_ character: UnicodeScalar) -> UnicodeScalar? {
// TODO: Add method to NSCharacterSet to do this in one call
let result : UnicodeScalar? = contains(character) ? character : nil
let r = NSRange(location: Int(character.value), length: 1)
_applyUnmanagedMutation {
$0.removeCharacters(in: r)
}
return result
}
/// Test for membership of a particular `UnicodeScalar` in the `CharacterSet`.
public func contains(_ member: UnicodeScalar) -> Bool {
return _mapUnmanaged { $0.longCharacterIsMember(member.value) }
}
/// Returns a union of the `CharacterSet` with another `CharacterSet`.
public func union(_ other: CharacterSet) -> CharacterSet {
// The underlying collection does not have a method to return new CharacterSets with changes applied, so we will copy and apply here
var result = self
result.formUnion(other)
return result
}
/// Sets the value to a union of the `CharacterSet` with another `CharacterSet`.
public mutating func formUnion(_ other: CharacterSet) {
_applyUnmanagedMutation { $0.formUnion(with: other) }
}
/// Returns an intersection of the `CharacterSet` with another `CharacterSet`.
public func intersection(_ other: CharacterSet) -> CharacterSet {
// The underlying collection does not have a method to return new CharacterSets with changes applied, so we will copy and apply here
var result = self
result.formIntersection(other)
return result
}
/// Sets the value to an intersection of the `CharacterSet` with another `CharacterSet`.
public mutating func formIntersection(_ other: CharacterSet) {
_applyUnmanagedMutation {
$0.formIntersection(with: other)
}
}
/// Returns a `CharacterSet` created by removing elements in `other` from `self`.
public func subtracting(_ other: CharacterSet) -> CharacterSet {
return intersection(other.inverted)
}
/// Sets the value to a `CharacterSet` created by removing elements in `other` from `self`.
public mutating func subtract(_ other: CharacterSet) {
self = subtracting(other)
}
/// Returns an exclusive or of the `CharacterSet` with another `CharacterSet`.
public func symmetricDifference(_ other: CharacterSet) -> CharacterSet {
return union(other).subtracting(intersection(other))
}
/// Sets the value to an exclusive or of the `CharacterSet` with another `CharacterSet`.
public mutating func formSymmetricDifference(_ other: CharacterSet) {
self = symmetricDifference(other)
}
/// Returns true if `self` is a superset of `other`.
public func isSuperset(of other: CharacterSet) -> Bool {
return _mapUnmanaged { $0.isSuperset(of: other) }
}
/// Returns true if the two `CharacterSet`s are equal.
public static func ==(lhs : CharacterSet, rhs: CharacterSet) -> Bool {
return lhs._mapUnmanaged { $0.isEqual(rhs) }
}
}
// MARK: Objective-C Bridging
extension CharacterSet : _ObjectTypeBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSCharacterSet.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSCharacterSet {
return _wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) {
result = CharacterSet(_bridged: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) -> Bool {
result = CharacterSet(_bridged: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSCharacterSet?) -> CharacterSet {
return CharacterSet(_bridged: source!)
}
}
extension CharacterSet : Codable {
private enum CodingKeys : Int, CodingKey {
case bitmap
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let bitmap = try container.decode(Data.self, forKey: .bitmap)
self.init(bitmapRepresentation: bitmap)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.bitmapRepresentation, forKey: .bitmap)
}
}
| apache-2.0 | 2c3712d1a2981cb2f643b1277dd11f9c | 38.416667 | 274 | 0.674563 | 5.242317 | false | false | false | false |
slightair/SwiftUtilities | SwiftUtilities Tests/DispatchDataTest.swift | 2 | 3888 | //
// DispatchDataTest.swift
// SwiftUtilities
//
// Created by Jonathan Wight on 7/1/15.
//
// Copyright (c) 2014, Jonathan Wight
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 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 XCTest
import SwiftUtilities
let deadbeef: UInt32 = 0xDEADBEEF
class DispatchDataTest: XCTestCase {
func testBasic1() {
let data = DispatchData <Void> (value: UInt32(deadbeef).bigEndian)
XCTAssertEqual(data.elementSize, 1)
XCTAssertEqual(data.count, 4)
XCTAssertEqual(data.length, 4)
XCTAssertEqual(data.startIndex, 0)
XCTAssertEqual(data.endIndex, 4)
}
func testDefaulInit() {
let data = DispatchData <Void> ()
XCTAssertEqual(data.elementSize, 1)
XCTAssertEqual(data.count, 0)
XCTAssertEqual(data.length, 0)
XCTAssertEqual(data.startIndex, 0)
XCTAssertEqual(data.endIndex, 0)
}
// func testConcat() {
// let data1 = DispatchData <Void> (value: UInt16(0xDEAD).bigEndian)
// let data2 = DispatchData <Void> (value: UInt16(0xBEEF).bigEndian)
// let result = data1 + data2
// let expectedResult = DispatchData <Void> (value: UInt32(deadbeef).bigEndian)
// XCTAssertTrue(result == expectedResult)
// }
func testSplit() {
let data = DispatchData <Void> (value: UInt32(deadbeef).bigEndian)
let (lhs, rhs) = data.split(2)
XCTAssertTrue(lhs == DispatchData <Void> (value: UInt16(0xDEAD).bigEndian))
XCTAssertTrue(rhs == DispatchData <Void> (value: UInt16(0xBEEF).bigEndian))
}
func testInset() {
let data = DispatchData <Void> (value: UInt32(deadbeef).bigEndian)
let insettedData = data.inset(startInset: 1, endInset: 1)
let expectedResult = DispatchData <Void> (value: UInt16(0xADBE).bigEndian)
XCTAssertEqual(insettedData, expectedResult)
}
// func testNonByteSized() {
// let data = DispatchData <UInt16> (array: [ 1, 2, 3, 4 ])
// XCTAssertEqual(data.subBuffer(1 ..< 3), DispatchData <UInt16> (array: [ 2, 3 ]))
// XCTAssertEqual(data.subBuffer(startIndex: 1, count: 2), DispatchData <UInt16> (array: [ 2, 3 ]))
// XCTAssertEqual(data[1 ..< 3], DispatchData <UInt16> (array: [ 2, 3 ]))
//// XCTAssertEqual(data.subBuffer(startIndex: 1, length: 2 * sizeof(UInt16)), DispatchData <UInt16> (array: [ 2, 3 ]))
// }
}
extension DispatchData {
init(array: Array <Element>) {
let data: DispatchData = array.withUnsafeBufferPointer() {
return DispatchData(buffer: $0)
}
self = data
}
}
| bsd-2-clause | b237458029790b0db1dcec676d7d1e11 | 39.5 | 126 | 0.679527 | 4.088328 | false | true | false | false |
Arty-Maly/Volna | Volna/RepeatingTimer.swift | 1 | 1155 | class RepeatingTimer {
private var deadline: Int
private var interval: DispatchTimeInterval!
init(deadline: Int, interval: Int) {
self.deadline = deadline
self.interval = .seconds(interval)
}
private lazy var timer: DispatchSourceTimer = {
let t = DispatchSource.makeTimerSource()
let d = self.deadline
t.scheduleRepeating(deadline: .now() + .seconds(d), interval: self.interval)
t.setEventHandler(handler: { [weak self] in
self?.eventHandler?()
})
return t
}()
var eventHandler: (() -> Void)?
private enum State {
case suspended
case resumed
}
private var state: State = .suspended
deinit {
timer.setEventHandler {}
timer.cancel()
resume()
eventHandler = nil
}
func resume() {
if state == .resumed {
return
}
state = .resumed
timer.resume()
}
func suspend() {
if state == .suspended {
return
}
state = .suspended
timer.suspend()
}
}
| gpl-3.0 | 28100785b1814ac92f49a7113e190c89 | 21.211538 | 84 | 0.527273 | 5.043668 | false | false | false | false |
googlearchive/abelana | iOS/Abelana_v2/AbelanaClientCache.swift | 1 | 3561 | //
// Copyright 2015 Google Inc. 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
class AbelanaClientCache {
// The phone's preferences storage.
private let prefs = NSUserDefaults.standardUserDefaults()
// The array used to cache the photo lists retrieved from the server.
internal var photoLists = [PhotoListType: [Photo]]()
// The array used to cache the next pages of the photo lists that we can retrieve from the server.
internal var photoListsNextPage = [PhotoListType: NSNumber]()
//
// Constructor.
//
init() {
photoLists = [PhotoListType: [Photo]]()
photoListsNextPage = [PhotoListType: NSNumber]()
if !restore() {
photoLists.updateValue([Photo](), forKey: PhotoListType.Stream)
photoLists.updateValue([Photo](), forKey: PhotoListType.Likes)
photoLists.updateValue([Photo](), forKey: PhotoListType.Mine)
photoListsNextPage.updateValue(0, forKey: PhotoListType.Stream)
photoListsNextPage.updateValue(0, forKey: PhotoListType.Likes)
photoListsNextPage.updateValue(0, forKey: PhotoListType.Mine)
}
}
//
// Backs up the cache content to the phone disk.
//
internal func backup() {
prefs.setObject(photoLists[PhotoListType.Stream], forKey: "photoLists_Stream")
prefs.setObject(photoLists[PhotoListType.Likes], forKey: "photoLists_Likes")
prefs.setObject(photoLists[PhotoListType.Mine], forKey: "photoLists_Mine")
prefs.setObject(photoListsNextPage[PhotoListType.Stream],
forKey: "photoListsNextPage_Stream")
prefs.setObject(photoListsNextPage[PhotoListType.Likes],
forKey: "photoListsNextPage_Likes")
prefs.setObject(photoListsNextPage[PhotoListType.Mine],
forKey: "photoListsNextPage_Mine")
self.prefs.synchronize()
}
//
// Restores the cache content from the phone disk.
//
private func restore() -> Bool {
if prefs.objectForKey("photoLists_Stream") != nil
&& prefs.objectForKey("photoLists_Likes") != nil
&& prefs.objectForKey("photoLists_Mine") != nil
&& prefs.objectForKey("photoListsNextPage_Stream") != nil
&& prefs.objectForKey("photoListsNextPage_Likes") != nil
&& prefs.objectForKey("photoListsNextPage_Mine") != nil {
photoLists.updateValue((prefs.objectForKey("photoLists_Stream") as? [Photo])!,
forKey: PhotoListType.Stream)
photoLists.updateValue((prefs.objectForKey("photoLists_Likes") as? [Photo])!,
forKey: PhotoListType.Likes)
photoLists.updateValue((prefs.objectForKey("photoLists_Mine") as? [Photo])!,
forKey: PhotoListType.Mine)
photoListsNextPage.updateValue((prefs.objectForKey("photoListsNextPage_Stream") as? NSNumber)!,
forKey: PhotoListType.Stream)
photoListsNextPage.updateValue((prefs.objectForKey("photoListsNextPage_Likes") as? NSNumber)!,
forKey: PhotoListType.Likes)
photoListsNextPage.updateValue((prefs.objectForKey("photoListsNextPage_Mine") as? NSNumber)!,
forKey: PhotoListType.Mine)
return true
}
return false
}
}
| apache-2.0 | 50b779c2214fdf37d3fcea6737986cec | 40.406977 | 100 | 0.721988 | 4.285199 | false | false | false | false |
radu-costea/ATests | ATests/ATests/UI/CustomViews/KeyboardPlaceholderView.swift | 1 | 2407 | //
// KeyboardPlaceholderView.swift
// ATests
//
// Created by Radu Costea on 19/04/16.
// Copyright © 2016 Radu Costea. All rights reserved.
//
import UIKit
import Parse
class KeyboardPlaceholderView: UIView {
var heightConstraint: NSLayoutConstraint!
private func setup() {
heightConstraint = heightAnchor.constraintEqualToConstant(0.0)
heightConstraint.priority = 900
heightConstraint.active = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
deinit {
if let observer = keyboardObserver {
notificationCenter.removeObserver(observer)
}
}
var keyboardObserver: NSObjectProtocol?
lazy var notificationCenter = NSNotificationCenter.defaultCenter()
override func didMoveToWindow() {
if let _ = window {
let callback = { [unowned self] (notification: NSNotification) in
let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue ?? 0.0
let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey]?.integerValue ?? 0
let option = UIViewAnimationOptions(rawValue: UInt(curve) << 16)
var value: CGFloat = 0.0
if let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]?.CGRectValue,
let keyboardFrameToSuperview = self.superview?.convertRect(keyboardFrame, fromView: nil) {
let minY = CGRectGetMinY(keyboardFrameToSuperview)
let maxY = CGRectGetMaxY(self.frame)
if minY < maxY {
value = maxY - minY
}
}
let animation = { [unowned self] in
self.heightConstraint.constant = value
self.superview?.layoutIfNeeded()
}
UIView.animateWithDuration(duration, delay: 0.0, options: option, animations: animation, completion: nil)
}
keyboardObserver = notificationCenter.addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: nil, usingBlock: callback)
} else if let observer = keyboardObserver {
notificationCenter.removeObserver(observer)
}
}
}
| mit | 3f890371b8b1e7fa45c57ef4e89e705b | 37.806452 | 154 | 0.612635 | 6.030075 | false | false | false | false |
zq54zquan/SwiftDoubanFM | iDoubanFm/iDoubanFm/tools/DMCollectionRequestModule.swift | 1 | 1317 | //
// DMCollectionRequestModule.swift
// iDoubanFm
//
// Created by zhou quan on 7/10/14.
// Copyright (c) 2014 zquan. All rights reserved.
//
import Foundation
class DMCollectionRequestModule:DMBaseRequestModuel {
var handleCollections:((_:Array<DMCollection>?)->Void)?
var handleError:((_:NSError)->Void)?
init() {
super.init(successHandle: {(result: AnyObject?) -> Void in
println(result)
// var cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(NSURL(string: FMDOMAIN))
// println(cookies)
if let resultDic = result as? NSDictionary {
if resultDic["status"] {
var collections : Array<DMCollection> = []
var data = resultDic["data"] as NSDictionary
for collectionDic in data["chls"] as Array<NSDictionary> {
var collection = DMCollection(initDic: collectionDic as NSDictionary)
collections.append(collection);
}
self.handleCollections!(collections);
}
}
}, errorHandler: {(error: NSError!) -> Void in
self.handleError!(error)
});
}
} | mit | c11bdd2829564c0366e5a74a4540a11e | 33.684211 | 112 | 0.544419 | 5.065385 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Classes/Home/Model/EventListModel.swift | 1 | 1092 | //
// EventListModel.swift
// OMS-DL
//
// Created by ___Gwy on 2017/7/28.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
class EventListModel: CommonPaseModel {
// var eventCode:String?
var eventOpDate:String?
// var eventReasonDesc:String?
var externalRemark1:String?
// var sOEventID:NSNumber?
var attachmentList:[[String:AnyObject]]?
// init(dict:[String:AnyObject]) {
// super.init()
// self.setValuesForKeys(dict)
// }
//
// override func setValue(_ value: Any?, forUndefinedKey key: String) {
//
// }
//
// override func setValue(_ value: Any?, forKey key: String) {
//
// if key == "attachmentList"{
// let info = value as! [[String:AnyObject]]
// MedLog(message: info)
//// var child = [AttachmentModel]()
//// for item in info{
//// child.append(AttachmentModel.init(dict: item))
//// }
//// self.attachmentList = child
// }
// super.setValue(value, forKey: key)
// }
}
| mit | b1aa8655da6cb7935e136e964c3b1732 | 25.560976 | 74 | 0.555556 | 3.61794 | false | false | false | false |
kesun421/firefox-ios | Providers/PocketFeed.swift | 1 | 5971 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Alamofire
import Shared
import Deferred
import Storage
private let PocketEnvAPIKey = "PocketEnvironmentAPIKey"
private let PocketGlobalFeed = "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs"
private let MaxCacheAge: Timestamp = OneMinuteInMilliseconds * 60 // 1 hour in milliseconds
private let SupportedLocales = ["en_US", "en_GB", "en_CA", "de_DE", "de_AT", "de_CH"]
/*s
The Pocket class is used to fetch stories from the Pocked API.
Right now this only supports the global feed
For a sample feed item check ClientTests/pocketglobalfeed.json
*/
struct PocketStory {
let url: URL
let title: String
let storyDescription: String
let imageURL: URL
let domain: String
let dedupeURL: URL
static func parseJSON(list: Array<[String: Any]>) -> [PocketStory] {
return list.flatMap({ (storyDict) -> PocketStory? in
guard let urlS = storyDict["url"] as? String, let domain = storyDict["domain"] as? String,
let dedupe_URL = storyDict["dedupe_url"] as? String,
let imageURLS = storyDict["image_src"] as? String,
let title = storyDict["title"] as? String,
let description = storyDict["excerpt"] as? String else {
return nil
}
guard let url = URL(string: urlS), let imageURL = URL(string: imageURLS), let dedupeURL = URL(string: dedupe_URL) else {
return nil
}
return PocketStory(url: url, title: title, storyDescription: description, imageURL: imageURL, domain: domain, dedupeURL: dedupeURL)
})
}
}
private class PocketError: MaybeErrorType {
var description = "Failed to load from API"
}
class Pocket {
private let pocketGlobalFeed: String
static let MoreStoriesURL = URL(string: "https://getpocket.cdn.mozilla.net/explore/trending?src=ff_ios")!
// Allow endPoint to be overriden for testing
init(endPoint: String = PocketGlobalFeed) {
self.pocketGlobalFeed = endPoint
}
lazy fileprivate var alamofire: SessionManager = {
let ua = UserAgent.defaultClientUserAgent
let configuration = URLSessionConfiguration.default
var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
defaultHeaders["User-Agent"] = ua
configuration.httpAdditionalHeaders = defaultHeaders
return SessionManager(configuration: configuration)
}()
private func findCachedResponse(for request: URLRequest) -> [String: Any]? {
let cachedResponse = URLCache.shared.cachedResponse(for: request)
guard let cachedAtTime = cachedResponse?.userInfo?["cache-time"] as? Timestamp, (Date.now() - cachedAtTime) < MaxCacheAge else {
return nil
}
guard let data = cachedResponse?.data, let json = try? JSONSerialization.jsonObject(with: data, options: []) else {
return nil
}
return json as? [String: Any]
}
private func cache(response: HTTPURLResponse?, for request: URLRequest, with data: Data?) {
guard let resp = response, let data = data else {
return
}
let metadata = ["cache-time": Date.now()]
let cachedResp = CachedURLResponse(response: resp, data: data, userInfo: metadata, storagePolicy: .allowed)
URLCache.shared.removeCachedResponse(for: request)
URLCache.shared.storeCachedResponse(cachedResp, for: request)
}
// Fetch items from the global pocket feed
func globalFeed(items: Int = 2) -> Deferred<Array<PocketStory>> {
let deferred = Deferred<Array<PocketStory>>()
guard let request = createGlobalFeedRequest(items: items) else {
deferred.fill([])
return deferred
}
if let cachedResponse = findCachedResponse(for: request), let items = cachedResponse["list"] as? Array<[String: Any]> {
deferred.fill(PocketStory.parseJSON(list: items))
return deferred
}
alamofire.request(request).validate(contentType: ["application/json"]).responseJSON { response in
guard response.error == nil, let result = response.result.value as? [String: Any] else {
return deferred.fill([])
}
self.cache(response: response.response, for: request, with: response.data)
guard let items = result["list"] as? Array<[String: Any]> else {
return deferred.fill([])
}
return deferred.fill(PocketStory.parseJSON(list: items))
}
return deferred
}
// Returns nil if the locale is not supported
static func IslocaleSupported(_ locale: String) -> Bool {
return SupportedLocales.contains(locale)
}
// Create the URL request to query the Pocket API. The max items that the query can return is 20
private func createGlobalFeedRequest(items: Int = 2) -> URLRequest? {
guard items > 0 && items <= 20 else {
return nil
}
let locale = Locale.current.identifier
let pocketLocale = locale.replacingOccurrences(of: "_", with: "-")
var params = [URLQueryItem(name: "count", value: String(items)), URLQueryItem(name: "locale_lang", value: pocketLocale)]
if let consumerKey = Bundle.main.object(forInfoDictionaryKey: PocketEnvAPIKey) as? String {
params.append(URLQueryItem(name: "consumer_key", value: consumerKey))
}
guard let feedURL = URL(string: pocketGlobalFeed)?.withQueryParams(params) else {
return nil
}
return URLRequest(url: feedURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 5)
}
}
| mpl-2.0 | d1bae09cbaf6d46ba078121436609b2a | 40.465278 | 143 | 0.654664 | 4.617943 | false | false | false | false |
aliceatlas/hexagen | Hexagen/Swift/Task/Channel.swift | 1 | 1998 | /*****\\\\
/ \\\\ Swift/Task/Channel.swift
/ /\ /\ \\\\ (part of Hexagen)
\ \_X_/ ////
\ //// Copyright © 2015 Alice Atlas (see LICENSE.md)
\*****////
public class Channel<T>: _SyncTarget {
private let bufferSize: Int
private lazy var bufferSpace: Int = self.bufferSize
private let buffer = SynchronizedQueue<T>()
private let waitingReceivers = SynchronizedQueue<T -> Void>()
private let waitingSenders = SynchronizedQueue<Void -> Void>()
public init(buffer: Int = 0) {
bufferSize = buffer
}
public func send(val: T) {
var suspender: (Void -> Void)?
sync {
if !waitingReceivers.isEmpty {
let recv = waitingReceivers.pull(sync: false)!
recv(val)
} else {
bufferSpace--
buffer.push(val, sync: false)
if bufferSpace < 0 {
suspender = TaskCtrl.suspender { resume in
waitingSenders.push(resume)
}
}
}
}
suspender?()
}
public func receive() -> T {
var suspender: (Void -> T)?
var ret: T?
sync {
if !buffer.isEmpty {
bufferSpace++
ret = buffer.pull(sync: false)!
if bufferSpace <= 0 {
let sender = waitingSenders.pull(sync: false)!
sender()
}
} else {
suspender = TaskCtrl.suspender { resume in
waitingReceivers.push(resume, sync: false)
}
}
}
return ret ?? suspender!()
}
}
extension Channel: Awaitable {
public func _await() -> T {
return receive()
}
public var _hasValue: Bool {
return !buffer.isEmpty
}
}
extension Channel: SendAwaitable {
public func _awaitSend(val: T) {
send(val)
}
} | mit | c71eb4742faddc58e4ae6d7bcee36f9c | 26 | 66 | 0.477216 | 4.341304 | false | false | false | false |
anilkumarbp/ringcentral-swift-v2 | RingCentral/Http/ApiResponse.swift | 1 | 3064 | //
// ApiResponse.swift
// RingCentral
//
// Created by Anil Kumar BP on 2/10/16.
// Copyright © 2016 Anil Kumar BP. All rights reserved.
//
import Foundation
public class ApiResponse {
// ApiResponse Constants
internal var multipartTransactions: AnyObject? = AnyObject?()
internal var request: NSMutableURLRequest?
internal var raw: AnyObject? = AnyObject?()
// Data Response Error Initialization
private var data: NSData?
private var response: NSURLResponse?
private var error: NSError?
private var dict: NSDictionary?
/// Constructor for the ApiResponse
///
/// @param: request NSMutableURLRequest
/// @param: data Instance of NSData
/// @param: response Instance of NSURLResponse
/// @param: error Instance of NSError
init(request: NSMutableURLRequest, status: Int = 200, data: NSData?, response: NSURLResponse?=nil, error: NSError?=nil) {
self.request = request
print("ApiRespsone Request is : ", self.request)
self.data = data
print("ApiRespsone data is : ", self.data)
self.response = response
print("ApiRespsone Response is : ", self.response)
self.error = error
print("ApiRespsone Error is : ", self.error)
}
public func getText() -> String {
if let check = data {
return check.description
} else {
return "No data."
}
}
public func getRaw() -> Any {
return raw
}
public func getMultipart() -> AnyObject? {
return self.multipartTransactions
}
public func isOK() -> Bool {
return ((self.response as! NSHTTPURLResponse).statusCode >= 200 && (self.response as! NSHTTPURLResponse).statusCode < 300)
}
public func getError() -> NSError? {
return error
}
public func getData() -> NSData? {
return self.data
}
public func getDict() -> Dictionary<String,NSObject> {
// let errors: NSError?
do {
self.dict = try NSJSONSerialization.JSONObjectWithData(self.data!, options: []) as? NSDictionary
} catch {
print("error")
}
return self.dict as! Dictionary<String, NSObject>
}
public func getRequest() -> NSMutableURLRequest? {
return request
}
public func getResponse() -> NSURLResponse? {
return response
}
public func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String {
let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0)
if NSJSONSerialization.isValidJSONObject(value) {
if let data = try? NSJSONSerialization.dataWithJSONObject(value, options: options) {
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string as String
}
}
}
return ""
}
}
| mit | 5563b55b09f220bce1c0de7779c09779 | 28.737864 | 130 | 0.595168 | 4.988599 | false | false | false | false |
gouyz/GYZBaking | baking/Classes/Mine/Controller/GYZMineConmentVC.swift | 1 | 6577 | //
// GYZMineConmentVC.swift
// baking
// 我的评价
// Created by gouyz on 2017/4/2.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
import MBProgressHUD
private let mineConmentCell = "mineConmentCell"
private let mineConmentHeader = "mineConmentHeader"
class GYZMineConmentVC: GYZBaseVC,UITableViewDelegate,UITableViewDataSource {
var currPage : Int = 1
var mineConmentModels: [GYZMineConmentModel] = [GYZMineConmentModel]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "我的评价"
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalTo(0)
}
requestConmentListData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// 懒加载UITableView
lazy var tableView : UITableView = {
let table = UITableView(frame: CGRect.zero, style: .grouped)
table.dataSource = self
table.delegate = self
table.tableFooterView = UIView()
table.separatorStyle = .none
// 设置大概高度
table.estimatedRowHeight = 60
// 设置行高为自动适配
table.rowHeight = UITableViewAutomaticDimension
table.register(GYZConmentCell.self, forCellReuseIdentifier: mineConmentCell)
table.register(GYZMineConmentHeaderView.self, forHeaderFooterViewReuseIdentifier: mineConmentHeader)
weak var weakSelf = self
///添加下拉刷新
GYZTool.addPullRefresh(scorllView: table, pullRefreshCallBack: {
weakSelf?.refresh()
})
///添加上拉加载更多
GYZTool.addLoadMore(scorllView: table, loadMoreCallBack: {
weakSelf?.loadMore()
})
return table
}()
///获取评论数据
func requestConmentListData(){
weak var weakSelf = self
showLoadingView()
GYZNetWork.requestNetwork("Order/commentList",parameters: ["p":currPage,"user_id":userDefaults.string(forKey: "userId") ?? ""], success: { (response) in
weakSelf?.hiddenLoadingView()
weakSelf?.closeRefresh()
// GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
let data = response["result"]
guard let info = data["info"].array else { return }
for item in info{
guard let itemInfo = item.dictionaryObject else { return }
let model = GYZMineConmentModel.init(dict: itemInfo)
weakSelf?.mineConmentModels.append(model)
}
if weakSelf?.mineConmentModels.count > 0{
weakSelf?.hiddenEmptyView()
weakSelf?.tableView.reloadData()
}else{
///显示空页面
weakSelf?.showEmptyView(content:"暂无评论信息")
}
}else{
MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue)
}
}, failture: { (error) in
weakSelf?.hiddenLoadingView()
weakSelf?.closeRefresh()
GYZLog(error)
if weakSelf?.currPage == 1{//第一次加载失败,显示加载错误页面
weakSelf?.showEmptyView(content: "加载失败,请点击重新加载", reload: {
weakSelf?.refresh()
})
}
})
}
// MARK: - 上拉加载更多/下拉刷新
/// 下拉刷新
func refresh(){
currPage = 1
requestConmentListData()
}
/// 上拉加载更多
func loadMore(){
currPage += 1
requestConmentListData()
}
/// 关闭上拉/下拉刷新
func closeRefresh(){
if tableView.mj_header.isRefreshing(){//下拉刷新
mineConmentModels.removeAll()
GYZTool.endRefresh(scorllView: tableView)
}else if tableView.mj_footer.isRefreshing(){//上拉加载更多
GYZTool.endLoadMore(scorllView: tableView)
}
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return mineConmentModels.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: mineConmentCell) as! GYZConmentCell
// if indexPath.section % 2 == 0 {
// cell.imageViews.isHidden = true
// cell.imageViews.snp.updateConstraints({ (make) in
// make.height.equalTo(0)
// })
// }else{
// cell.imageViews.isHidden = false
// cell.imageViews.imgViewFour.isHidden = true
// cell.imageViews.snp.updateConstraints({ (make) in
// make.height.equalTo(kBusinessImgHeight)
// })
// }
cell.dataModel = mineConmentModels[indexPath.section]
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: mineConmentHeader) as! GYZMineConmentHeaderView
headerView.dataModel = mineConmentModels[section]
headerView.tag = section
headerView.addOnClickListener(target: self, action: #selector(goBusinessDetail(sender:)))
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return kMargin
}
/// 店铺详情
func goBusinessDetail(sender: UITapGestureRecognizer){
let businessVC = GYZBusinessVC()
businessVC.shopId = (mineConmentModels[(sender.view?.tag)!].member_info?.member_id)!
navigationController?.pushViewController(businessVC, animated: true)
}
}
| mit | 524864b67daac5796ef1f7942b6baaa3 | 31.704663 | 161 | 0.585076 | 4.985782 | false | false | false | false |
zhugejunwei/LeetCode | 91. Decode Ways.swift | 1 | 1745 | import Darwin
// First Method:
func numDecodings(s: String) -> Int {
if s.isEmpty || s[s.startIndex] == "0" { return 0 }
if s.characters.count == 1 { return 1 }
var i = s.endIndex.predecessor()
var count = 1
while i > s.startIndex {
if s[i] == "0" && s[i.predecessor()] != "2" && s[i.predecessor()] != "1" {
return 0
}else if s[i] == "0" && i.predecessor() != s.startIndex {
i = i.predecessor().predecessor()
}else if s[i] == "0" && i.predecessor() == s.startIndex {
return count
}else if s[i.predecessor()] == "1" || (s[i.predecessor()] == "2" && s[i] <= "6") {
var tag = 2, ex = 1
i = i.predecessor()
print("out:\(tag)")
while i > s.startIndex && (s[i.predecessor()] == "1" || (s[i.predecessor()] == "2" && s[i] <= "6")) {
tag <<= 1
tag -= ex
if tag >= 5 { ex += 1 }
i = i.predecessor()
print(":\(tag)")
}
count *= tag
}else {
i = i.predecessor()
}
}
return count
}
// Second Method: DP
func numDecodings(s: String) -> Int {
if s.isEmpty || s[s.startIndex] == "0" { return 0 }
if s.characters.count == 1 { return 1 }
var count = 1, last = 1
var i = s.startIndex.successor()
while i < s.endIndex {
var cur = 0
if s[i] > "0" {
cur += count
}
if s[i.predecessor()] == "1" || (s[i.predecessor()] == "2" && s[i] <= "6") {
cur += last
}
last = count
count = cur
if last == 0 {
return 0
}
i = i.successor()
}
return count
}
| mit | 57c48651eeaa477513ad8652d789c38b | 27.606557 | 113 | 0.429799 | 3.462302 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/WordPressIntents/SitesDataProvider.swift | 1 | 2157 | import Intents
class SitesDataProvider {
private(set) var sites = [Site]()
init() {
initializeSites()
}
// MARK: - Init Support
private func initializeSites() {
guard let data = HomeWidgetTodayData.read() else {
sites = []
return
}
sites = data.map { (key: Int, data: HomeWidgetTodayData) -> Site in
// Note: the image for the site was being set through:
//
// icon(from: data)
//
// Unfortunately, this had to be turned off for now since images aren't working very well in the
// customizer as reported here: https://github.com/wordpress-mobile/WordPress-iOS/pull/15397#pullrequestreview-539474644
let siteDomain: String?
if let urlComponents = URLComponents(string: data.url),
let host = urlComponents.host {
siteDomain = host
} else {
siteDomain = nil
}
return Site(
identifier: String(key),
display: data.siteName,
subtitle: siteDomain,
image: nil)
}.sorted(by: { (firstSite, secondSite) -> Bool in
let firstTitle = firstSite.displayString.lowercased()
let secondTitle = secondSite.displayString.lowercased()
guard firstTitle != secondTitle else {
let firstSubtitle = firstSite.subtitleString?.lowercased() ?? ""
let secondSubtitle = secondSite.subtitleString?.lowercased() ?? ""
return firstSubtitle <= secondSubtitle
}
return firstTitle < secondTitle
})
}
// MARK: - Default Site
private var defaultSiteID: Int? {
return UserDefaults(suiteName: WPAppGroupName)?.object(forKey: WPStatsHomeWidgetsUserDefaultsSiteIdKey) as? Int
}
var defaultSite: Site? {
guard let defaultSiteID = self.defaultSiteID else {
return nil
}
return sites.first { site in
return site.identifier == String(defaultSiteID)
}
}
}
| gpl-2.0 | a4962040861a712f9ca87a608e17fc8c | 28.148649 | 132 | 0.563746 | 4.958621 | false | false | false | false |
HotCatLX/SwiftStudy | 03-LoginAnimation/LoginAnimation/LoginController.swift | 1 | 3380 | //
// LoginController.swift
// LoginAnimation
//
// Created by suckerl on 2017/5/11.
// Copyright © 2017年 suckerl. All rights reserved.
//
import UIKit
import SnapKit
class LoginController: UIViewController {
fileprivate lazy var userName : UITextField = {
let userName = UITextField()
userName.placeholder = "username"
userName.layer.cornerRadius = 5
userName.backgroundColor = UIColor.yellow
userName.alpha = 0.5
return userName
}()
fileprivate lazy var password : UITextField = {
let password = UITextField()
password.placeholder = "password"
password.layer.cornerRadius = 5
password.backgroundColor = UIColor.yellow
password.alpha = 0.5
return password
}()
fileprivate lazy var loginButton :UIButton = {
let loginButton = UIButton()
loginButton.setTitle("Login", for: .normal)
loginButton.backgroundColor = UIColor.darkGray
loginButton.alpha = 0.3
loginButton.layer.cornerRadius = 5
loginButton.addTarget(self, action: #selector(LoginController.buttonClick), for: .touchUpInside)
return loginButton
}()
override func viewDidLoad() {
super.viewDidLoad()
self.setupNav()
view.addSubview(userName)
view.addSubview(password)
view.addSubview(loginButton)
self.constructLayout()
}
}
////MARK:- setupNav
extension LoginController {
func setupNav() {
self.navigationItem.title = "Login"
let leftItem = UIBarButtonItem(image: UIImage.init(named: "back"), style: .plain, target: self, action: #selector(LoginController.back))
self.navigationItem.leftBarButtonItem = leftItem
}
func back() {
self .dismiss(animated: true, completion: nil)
}
}
extension LoginController {
func constructLayout() {
userName.snp.makeConstraints { (make) in
make.top.equalTo(self.view).offset(100)
make.left.equalTo(self.view).offset(50)
make.right.equalTo(self.view).offset(-50)
make.height.equalTo(20)
}
password.snp.makeConstraints { (make) in
make.top.equalTo(userName.snp.bottom).offset(20)
make.left.right.height.equalTo(userName)
}
loginButton.snp.makeConstraints { (make) in
make.top.equalTo(password.snp.bottom).offset(50)
make.left.equalTo(self.view).offset(100)
make.right.equalTo(self.view).offset(-100)
make.height.equalTo(30)
}
}
}
//MARK:- buttonClick
extension LoginController {
func buttonClick() {
var bounds = self.loginButton.bounds
if bounds.size.width > 300 {
bounds = CGRect(x: 0, y: 0, width: 175, height: 30)
self.loginButton.alpha = 0.5
}
// dampingRatio(阻尼系数)
// velocity (弹性速率)
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 10, options: .curveLinear, animations: {
self.loginButton.alpha += 0.2
self.loginButton.bounds = CGRect(x: bounds.origin.x - 20, y: bounds.origin.y, width: bounds.size.width + 80, height: bounds.size.height)
}, completion: nil)
}
}
| mit | 395994aa4a25057d3f516dbc95f02905 | 28.955357 | 144 | 0.618182 | 4.426121 | false | false | false | false |
AliSoftware/SwiftGen | SwiftGen.playground/Pages/XCAssets-Demo.xcplaygroundpage/Contents.swift | 1 | 4883 | //: #### Other pages
//:
//: * [Demo for `colors` parser](Colors-Demo)
//: * [Demo for `coredata` parser](CoreData-Demo)
//: * [Demo for `files` parser](Files-Demo)
//: * [Demo for `fonts` parser](Fonts-Demo)
//: * [Demo for `ib` parser](InterfaceBuilder-Demo)
//: * [Demo for `json` parser](JSON-Demo)
//: * [Demo for `plist` parser](Plist-Demo)
//: * [Demo for `strings` parser](Strings-Demo)
//: * Demo for `xcassets` parser
//: * [Demo for `yaml` parser](YAML-Demo)
// setup code to make this work in playground
// swiftlint:disable convenience_type
private final class BundleToken {
static let bundle: Bundle = {
#if SWIFT_PACKAGE
return Bundle.module
#else
return Bundle(for: BundleToken.self)
#endif
}()
}
// swiftlint:enable convenience_type
bundle = BundleToken.bundle
//: #### Example of code generated by `xcassets` parser with "swift5" template
#if os(macOS)
import AppKit
#elseif os(iOS)
import ARKit
import UIKit
#elseif os(tvOS) || os(watchOS)
import UIKit
#endif
import PlaygroundSupport
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// MARK: - Asset Catalogs
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum Asset {
internal enum Files {
internal static let data = DataAsset(name: "Data")
internal enum Json {
internal static let data = DataAsset(name: "Json/Data")
}
internal static let readme = DataAsset(name: "README")
}
internal enum Food {
internal enum Exotic {
internal static let banana = ImageAsset(name: "Exotic/Banana")
internal static let mango = ImageAsset(name: "Exotic/Mango")
}
internal enum Round {
internal static let apricot = ImageAsset(name: "Round/Apricot")
internal static let apple = ImageAsset(name: "Round/Apple")
internal enum Double {
internal static let cherry = ImageAsset(name: "Round/Double/Cherry")
}
internal static let tomato = ImageAsset(name: "Round/Tomato")
}
internal static let `private` = ImageAsset(name: "private")
}
internal enum Styles {
internal enum _24Vision {
internal static let background = ColorAsset(name: "24Vision/Background")
internal static let primary = ColorAsset(name: "24Vision/Primary")
}
internal static let orange = ImageAsset(name: "Orange")
internal enum Vengo {
internal static let primary = ColorAsset(name: "Vengo/Primary")
internal static let tint = ColorAsset(name: "Vengo/Tint")
}
}
internal enum Symbols {
internal static let exclamationMark = SymbolAsset(name: "Exclamation Mark")
internal static let plus = SymbolAsset(name: "Plus")
}
internal enum Targets {
internal static let bottles = ARResourceGroupAsset(name: "Bottles")
internal static let paintings = ARResourceGroupAsset(name: "Paintings")
internal static let posters = ARResourceGroupAsset(name: "Posters")
}
}
// swiftlint:enable identifier_name line_length nesting type_body_length type_name
//: #### Usage Example
// images
// Tip: Use "Show Result" box on the right to display the images inline in playground
let image1 = UIImage(asset: Asset.Food.Exotic.banana)
let image2 = Asset.Food.Round.tomato.image
// Show fruits animated in the playground's liveView
PlaygroundPage.current.liveView = {
let assets = [
Asset.Food.Exotic.banana,
Asset.Food.Exotic.mango,
Asset.Food.Round.apricot,
Asset.Food.Round.apple,
Asset.Food.Round.tomato,
Asset.Food.Round.Double.cherry
]
let iv = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
iv.animationImages = assets.map(\.image)
iv.animationDuration = TimeInterval(assets.count)/2 // 0.5s per image
iv.startAnimating()
return iv
}()
// colors
let color1 = UIColor(asset: Asset.Styles.Vengo.primary)
let color2 = Asset.Styles.Vengo.tint.color
/* Colors support variations for different interface styles (light/dark mode) */ _ = {
let vc = UIViewController()
vc.overrideUserInterfaceStyle = .dark
vc.view.backgroundColor = Asset.Styles.Vengo.primary.color
vc.view // Use "Show Result" box on the right to display contextualized color inline in playground
vc.overrideUserInterfaceStyle = .light
vc.view // Use "Show Result" box on the right to display contextualized color inline in playground
}()
// data
let dataAsset1 = NSDataAsset(asset: Asset.Files.data)
let dataAsset2 = Asset.Files.readme.data
let readmeText = String(data: dataAsset2.data, encoding: .utf8) ?? "-"
print(readmeText)
// AR resources
let paintingReferenceImages = Asset.Targets.paintings.referenceImages
let bottleReferenceObjects = Asset.Targets.bottles.referenceObjects
// symbols
let plus = Asset.Symbols.plus.image
let style = UIImage.SymbolConfiguration(textStyle: .headline)
let styled = Asset.Symbols.exclamationMark.image(with: style)
| mit | 8ddf60ad5aa6d87837bc76cc0577af4d | 32.675862 | 100 | 0.71411 | 3.918941 | false | false | false | false |
AliSoftware/SwiftGen | Tests/SwiftGenKitTests/CoreDataTests.swift | 1 | 1240 | //
// SwiftGenKit UnitTests
// Copyright © 2020 SwiftGen
// MIT Licence
//
@testable import SwiftGenKit
import TestUtils
import XCTest
final class CoreDataTests: XCTestCase {
func testEmpty() throws {
let parser = try CoreData.Parser()
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "empty", sub: .coreData)
}
func testDefaults() throws {
let parser = try CoreData.Parser()
do {
try parser.searchAndParse(path: Fixtures.resource(for: "Model.xcdatamodeld", sub: .coreData))
} catch {
print("Error: \(error.localizedDescription)")
}
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "defaults", sub: .coreData)
}
// MARK: - Custom options
func testUnknownOption() throws {
do {
_ = try CoreData.Parser(options: ["SomeOptionThatDoesntExist": "foo"])
XCTFail("Parser successfully created with an invalid option")
} catch ParserOptionList.Error.unknownOption(let key, _) {
// That's the expected exception we want to happen
XCTAssertEqual(key, "SomeOptionThatDoesntExist", "Failed for unexpected option \(key)")
} catch let error {
XCTFail("Unexpected error occured: \(error)")
}
}
}
| mit | 90c40725e655b28d551283fb1420899c | 27.159091 | 99 | 0.682809 | 4.393617 | false | true | false | false |
GMSLabs/Hyber-SDK-iOS | Example/Hyber/LocalPush.swift | 1 | 12213 | //
// LocalPush.swift
// Hyber
//
// Created by Taras Markevych on 3/23/17.
// Copyright © 2017 Incuube. All rights reserved.
//
import UIKit
open class LocalNotificationView: UIToolbar {
// MARK: - Properties
open static var sharedNotification = LocalNotificationView()
open var titleFont = NotificationName.titleFont {
didSet {
titleLabel.font = titleFont
}
}
open var titleTextColor = UIColor.white {
didSet {
titleLabel.textColor = titleTextColor
}
}
open var subtitleFont = NotificationName.subtitleFont {
didSet {
subtitleLabel.font = subtitleFont
}
}
open var subtitleTextColor = UIColor.white {
didSet {
subtitleLabel.textColor = subtitleTextColor
}
}
open var duration: TimeInterval = NotificationName.exhibitionDuration
open fileprivate(set) var isAnimating = false
open fileprivate(set) var isDragging = false
fileprivate var dismissTimer: Timer? {
didSet {
if oldValue?.isValid == true {
oldValue?.invalidate()
}
}
}
fileprivate var tapAction: (() -> ())?
fileprivate lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = 3
imageView.contentMode = UIViewContentMode.scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
fileprivate lazy var titleLabel: UILabel = { [unowned self] in
let titleLabel = UILabel()
titleLabel.backgroundColor = UIColor.clear
titleLabel.textAlignment = .left
titleLabel.numberOfLines = 1
titleLabel.font = self.titleFont
titleLabel.textColor = self.titleTextColor
return titleLabel
}()
fileprivate lazy var subtitleLabel: UILabel = { [unowned self] in
let subtitleLabel = UILabel()
subtitleLabel.backgroundColor = UIColor.clear
subtitleLabel.textAlignment = .left
subtitleLabel.numberOfLines = 2
subtitleLabel.font = self.subtitleFont
subtitleLabel.textColor = self.subtitleTextColor
return subtitleLabel
}()
fileprivate lazy var dragView: UIView = { [unowned self] in
let dragView = UIView()
dragView.backgroundColor = UIColor(white: 1.0, alpha: 0.35)
dragView.layer.cornerRadius = NotificationLayout.dragViewHeight / 2
return dragView
}()
fileprivate var imageViewFrame: CGRect {
return CGRect(x: 15.0, y: 8.0, width: 20.0, height: 20.0)
}
fileprivate var dragViewFrame: CGRect {
let width: CGFloat = 40
return CGRect(x: (NotificationLayout.width - width) / 2,
y: NotificationLayout.height - 5,
width: width,
height: NotificationLayout.dragViewHeight)
}
fileprivate var titleLabelFrame: CGRect {
if self.imageView.image == nil {
return CGRect(x: 5.0, y: 3.0, width: NotificationLayout.width - 5.0, height: 26.0)
}
return CGRect(x: 45.0, y: 3.0, width: NotificationLayout.width - 45.0, height: 26.0)
}
fileprivate var messageLabelFrame: CGRect {
if self.imageView.image == nil {
return CGRect(x: 5, y: 25, width: NotificationLayout.width - 5, height: NotificationLayout.labelMessageHeight)
}
return CGRect(x: 45, y: 25, width: NotificationLayout.width - 45.0, height: NotificationLayout.labelMessageHeight)
}
// MARK: - Initialization
deinit {
NotificationCenter.default.removeObserver(self)
}
public init() {
super.init(frame: CGRect(x: 0, y: 0, width: NotificationLayout.width, height: NotificationLayout.height))
startNotificationObservers()
setupUI()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Override Toolbar
open override func layoutSubviews() {
super.layoutSubviews()
setupFrames()
}
open override var intrinsicContentSize: CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: NotificationLayout.height)
}
// MARK: - Observers
fileprivate func startNotificationObservers() {
/// Enable orientation tracking
if !UIDevice.current.isGeneratingDeviceOrientationNotifications {
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
}
/// Add Orientation notification
NotificationCenter.default.addObserver(self, selector: #selector(LocalNotificationView.orientationStatusDidChange(_:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
// MARK: - Orientation Observer
@objc fileprivate func orientationStatusDidChange(_ notification: Foundation.Notification) {
setupUI()
}
// MARK: - Setups
fileprivate func setupFrames() {
var frame = self.frame
frame.size.width = NotificationLayout.width
self.frame = frame
self.titleLabel.frame = self.titleLabelFrame
self.imageView.frame = self.imageViewFrame
self.subtitleLabel.frame = self.messageLabelFrame
self.dragView.frame = self.dragViewFrame
fixLabelMessageSize()
}
fileprivate func setupUI() {
translatesAutoresizingMaskIntoConstraints = false
// Bar style
self.barTintColor = nil
self.isTranslucent = true
self.barStyle = UIBarStyle.black
self.tintColor = UIColor(red: 5, green: 31, blue: 75, alpha: 1)
self.layer.zPosition = CGFloat.greatestFiniteMagnitude - 1
self.backgroundColor = UIColor.clear
self.isMultipleTouchEnabled = false
self.isExclusiveTouch = true
self.frame = CGRect(x: 0, y: 0, width: NotificationLayout.width, height: NotificationLayout.height)
self.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleTopMargin, UIViewAutoresizing.flexibleRightMargin, UIViewAutoresizing.flexibleLeftMargin]
// Add subviews
self.addSubview(self.titleLabel)
self.addSubview(self.subtitleLabel)
self.addSubview(self.imageView)
self.addSubview(self.dragView)
// Gestures
let tap = UITapGestureRecognizer(target: self, action: #selector(LocalNotificationView.didTap(_:)))
self.addGestureRecognizer(tap)
let pan = UIPanGestureRecognizer(target: self, action: #selector(LocalNotificationView.didPan(_:)))
self.addGestureRecognizer(pan)
// Setup frames
self.setupFrames()
}
// MARK: - Helper
fileprivate func fixLabelMessageSize() {
let size = self.subtitleLabel.sizeThatFits(CGSize(width: NotificationLayout.width - NotificationLayout.labelPadding, height: CGFloat.greatestFiniteMagnitude))
var frame = self.subtitleLabel.frame
frame.size.height = size.height > NotificationLayout.labelMessageHeight ? NotificationLayout.labelMessageHeight : size.height
self.subtitleLabel.frame = frame;
}
// MARK: - Actions
@objc fileprivate func scheduledDismiss() {
self.hide(completion: nil)
}
// MARK: - Tap gestures
@objc fileprivate func didTap(_ gesture: UIGestureRecognizer) {
self.isUserInteractionEnabled = false
self.tapAction?()
self.hide(completion: nil)
}
@objc fileprivate func didPan(_ gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .ended:
self.isDragging = false
if frame.origin.y < 0 || self.duration <= 0 {
self.hide(completion: nil)
}
break
case .began:
self.isDragging = true
break
case .changed:
guard let superview = self.superview else {
return
}
guard let gestureView = gesture.view else {
return
}
let translation = gesture.translation(in: superview)
// Figure out where the user is trying to drag the view.
let newCenter = CGPoint(x: superview.bounds.size.width / 2,
y: gestureView.center.y + translation.y)
// See if the new position is in bounds.
if (newCenter.y >= (-1 * NotificationLayout.height / 2) && newCenter.y <= NotificationLayout.height / 2) {
gestureView.center = newCenter
gesture.setTranslation(CGPoint.zero, in: superview)
}
break
default:
break
}
}
}
public extension LocalNotificationView {
// MARK: - Public Methods
public func show(withImage image: UIImage?, title: String?, message: String?, duration: TimeInterval = NotificationName.exhibitionDuration, onTap: (() -> ())?) {
/// Invalidate dismissTimer
self.dismissTimer = nil
self.tapAction = onTap
self.duration = duration
self.imageView.image = image
self.titleLabel.text = title
self.subtitleLabel.text = message
var frame = self.frame
frame.origin.y = -frame.size.height
self.frame = frame
self.setupFrames()
self.isUserInteractionEnabled = true
self.isAnimating = true
if let window = UIApplication.shared.delegate?.window {
window?.windowLevel = UIWindowLevelStatusBar
window?.addSubview(self)
}
UIView.animate(withDuration: NotificationName.animationDuration, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
var frame = self.frame
frame.origin.y += frame.size.height
self.frame = frame
}) { (finished) in
self.isAnimating = false
}
if self.duration > 0 {
let time = self.duration + NotificationName.animationDuration
self.dismissTimer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(LocalNotificationView.scheduledDismiss), userInfo: nil, repeats: false)
}
}
public func hide(completion: (() -> ())?) {
guard !self.isDragging else {
self.dismissTimer = nil
return
}
if self.superview == nil {
isAnimating = false
return
}
if (isAnimating) {
return
}
isAnimating = true
self.dismissTimer = nil
UIView.animate(withDuration: NotificationName.animationDuration, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
var frame = self.frame
frame.origin.y -= frame.size.height
self.frame = frame
}) { (finished) in
self.removeFromSuperview()
UIApplication.shared.delegate?.window??.windowLevel = UIWindowLevelNormal
self.isAnimating = false
completion?()
}
}
public static func show(withImage image: UIImage?, title: String?, message: String?, duration: TimeInterval = NotificationName.exhibitionDuration, onTap: (() -> ())? = nil) {
self.sharedNotification.show(withImage: image, title: title, message: message, duration: duration, onTap: onTap)
}
public static func hide(completion: (() -> ())? = nil) {
self.sharedNotification.hide(completion: completion)
}
}
| apache-2.0 | 3a5282748c63cc3dd3ea4821cd496f8a | 31.052493 | 196 | 0.597281 | 5.377367 | false | false | false | false |
nikrad/ios | FiveCalls/FiveCalls/CallScriptViewController.swift | 1 | 11544 | //
// CallScriptViewController.swift
// FiveCalls
//
// Created by Patrick McCarron on 2/3/17.
//
import UIKit
import CoreLocation
import Crashlytics
class CallScriptViewController : UIViewController, IssueShareable {
var issuesManager: IssuesManager!
var issue: Issue!
var contactIndex = 0
var contact: Contact!
var logs = ContactLogs.load()
var lastPhoneDialed: String?
var isLastContactForIssue: Bool {
let contactIndex = issue.contacts.index(of: contact)
return contactIndex == issue.contacts.count - 1
}
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var resultInstructionsLabel: UILabel!
@IBOutlet weak var resultUnavailableButton: BlueButton!
@IBOutlet weak var resultVoicemailButton: BlueButton!
@IBOutlet weak var resultContactedButton: BlueButton!
@IBOutlet weak var resultSkipButton: BlueButton!
@IBOutlet weak var checkboxView: CheckboxView!
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(IssueDetailViewController.shareButtonPressed(_ :)))
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
if self.presentingViewController != nil {
self.navigationItem.leftBarButtonItem = self.iPadDoneButton
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let issue = issue, let contactIndex = issue.contacts.index(of: contact) else {
return
}
Answers.logCustomEvent(withName:"Action: Issue Call Script", customAttributes: ["issue_id":issue.id])
self.contactIndex = contactIndex
title = "Contact \(contactIndex+1) of \(issue.contacts.count)"
let method = logs.methodOfContact(to: contact.id, forIssue: issue.id)
self.resultContactedButton.isSelected = method == .contacted
self.resultUnavailableButton.isSelected = method == .unavailable
self.resultVoicemailButton.isSelected = method == .voicemail
}
func back() {
_ = navigationController?.popViewController(animated: true)
}
func dismissCallScript() {
self.dismiss(animated: true, completion: nil)
}
var iPadDoneButton: UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissCallScript))
}
func callButtonPressed(_ button: UIButton) {
Answers.logCustomEvent(withName:"Action: Dialed Number", customAttributes: ["contact_id":contact.id])
callNumber(contact.phone)
}
fileprivate func callNumber(_ number: String) {
self.lastPhoneDialed = number
let defaults = UserDefaults.standard
let firstCallInstructionsKey = UserDefaultsKeys.hasSeenFirstCallInstructions.rawValue
let callErrorCompletion: (Bool) -> Void = { [weak self] successful in
if !successful {
DispatchQueue.main.async {
self?.showCallFailedAlert()
}
}
}
if defaults.bool(forKey: firstCallInstructionsKey) {
guard let dialURL = URL(string: "telprompt:\(number)") else { return }
UIApplication.shared.fvc_open(dialURL, completion: callErrorCompletion)
} else {
let alertController = UIAlertController(title: R.string.localizable.firstCallAlertTitle(),
message: R.string.localizable.firstCallAlertMessage(),
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: R.string.localizable.cancelButtonTitle(),
style: .cancel) { _ in
alertController.dismiss(animated: true, completion: nil)
}
let callAction = UIAlertAction(title: R.string.localizable.firstCallAlertCall(),
style: .default) { _ in
alertController.dismiss(animated: true, completion: nil)
guard let dialURL = URL(string: "tel:\(number)") else { return }
UIApplication.shared.fvc_open(dialURL, completion: callErrorCompletion)
defaults.set(true, forKey: firstCallInstructionsKey)
}
alertController.addAction(cancelAction)
alertController.addAction(callAction)
present(alertController, animated: true, completion: nil)
}
}
func reportCallOutcome(_ log: ContactLog) {
logs.add(log: log)
let operation = ReportOutcomeOperation(log:log)
#if !debug // don't report stats in debug builds
OperationQueue.main.addOperation(operation)
#endif
}
func hideResultButtons(animated: Bool) {
let duration = animated ? 0.5 : 0
let hideDuration = duration * 0.6
UIView.animate(withDuration: hideDuration) {
for button in [self.resultContactedButton, self.resultVoicemailButton, self.resultUnavailableButton, self.resultSkipButton] {
button?.alpha = 0
}
self.resultInstructionsLabel.alpha = 0
}
checkboxView.alpha = 0
checkboxView.transform = checkboxView.transform.scaledBy(x: 0.2, y: 0.2)
checkboxView.isHidden = false
UIView.animate(withDuration: duration, delay: duration * 0.75, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: {
self.checkboxView.alpha = 1
self.checkboxView.transform = .identity
}, completion: nil)
}
func handleCallOutcome(outcome: ContactOutcome) {
// save & send log entry
let contactedPhone = lastPhoneDialed ?? contact.phone
let log = ContactLog(issueId: issue.id, contactId: contact.id, phone: contactedPhone, outcome: outcome, date: Date())
reportCallOutcome(log)
}
@IBAction func resultButtonPressed(_ button: UIButton) {
Answers.logCustomEvent(withName:"Action: Button \(button.titleLabel)", customAttributes: ["contact_id":contact.id])
switch button {
case resultContactedButton: handleCallOutcome(outcome: .contacted)
case resultVoicemailButton: handleCallOutcome(outcome: .voicemail)
case resultUnavailableButton: handleCallOutcome(outcome: .unavailable)
case resultSkipButton: break
default:
print("unknown button pressed")
}
if isLastContactForIssue {
hideResultButtons(animated: true)
} else {
let nextContact = issue.contacts[contactIndex + 1]
showNextContact(nextContact)
}
}
func showNextContact(_ contact: Contact) {
let newController = R.storyboard.main.callScriptController()!
newController.issuesManager = issuesManager
newController.issue = issue
newController.contact = contact
navigationController?.replaceTopViewController(with: newController, animated: true)
}
func shareButtonPressed(_ button: UIBarButtonItem) {
shareIssue(from: button)
}
private func showCallFailedAlert() {
let alertController = UIAlertController(title: R.string.localizable.placeCallFailedTitle(),
message: R.string.localizable.placeCallFailedMessage(),
preferredStyle: .alert)
let okAction = UIAlertAction(title: R.string.localizable.okButtonTitle(),
style: .default) { _ in
alertController.dismiss(animated: true, completion: nil)
}
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
}
enum CallScriptRows : Int {
case contact
case script
case count
}
extension CallScriptViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return CallScriptRows.count.rawValue
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case CallScriptRows.contact.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.contactDetailCell, for: indexPath)!
cell.callButton.setTitle("☎️ " + contact.phone, for: .normal)
cell.callButton.addTarget(self, action: #selector(callButtonPressed(_:)), for: .touchUpInside)
cell.nameLabel.text = contact.name
cell.callingReasonLabel.text = contact.reason
if let photoURL = contact.photoURL {
cell.avatarImageView.setRemoteImage(url: photoURL)
} else {
cell.avatarImageView.image = cell.avatarImageView.defaultImage
}
cell.moreNumbersButton.isHidden = contact.fieldOffices.isEmpty
cell.moreNumbersButton.addTarget(self, action: #selector(CallScriptViewController.moreNumbersTapped), for: .touchUpInside)
// This helps both resizing labels we have actually display correctly
cell.layoutIfNeeded()
return cell
case CallScriptRows.script.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.scriptCell, for: indexPath)!
cell.scriptTextView.text = issue.script
return cell
default:
return UITableViewCell()
}
}
func moreNumbersTapped() {
Answers.logCustomEvent(withName:"Action: Opened More Numbers", customAttributes: ["contact_id":contact.id])
if contact.fieldOffices.count > 0 {
let contactID = contact.id
let sheet = UIAlertController(title: R.string.localizable.chooseANumber(), message: nil, preferredStyle: .actionSheet)
for office in contact.fieldOffices {
let title = office.city.isEmpty ? "\(office.phone)" : "\(office.city): \(office.phone)"
sheet.addAction(UIAlertAction(title: title, style: .default, handler: { [weak self] action in
Answers.logCustomEvent(withName:"Action: Dialed Alternate Number", customAttributes: ["contact_id":contactID])
self?.callNumber(office.phone)
}))
}
sheet.addAction(UIAlertAction(title: R.string.localizable.cancelButtonTitle(), style: .cancel, handler: { [weak self] action in
self?.dismiss(animated: true, completion: nil)
}))
self.present(sheet, animated: true, completion: nil)
}
}
}
extension IssueDetailViewController : UITableViewDelegate {
}
| mit | 00facac410b82bbd21cdca64652f59c4 | 40.811594 | 173 | 0.617504 | 5.267001 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Rule/Rule+AutomaticFacetFilters.swift | 1 | 1234 | //
// Rule+AutomaticFacetFilters.swift
//
//
// Created by Vladislav Fitc on 05/05/2020.
//
import Foundation
extension Rule {
public struct AutomaticFacetFilters: Codable {
/// Attribute to filter on. This must match Pattern.Facet.attribute.
public let attribute: Attribute
/// Score for the filter. Typically used for optional or disjunctive filters.
public let score: Int?
/**
Whether the filter is disjunctive (true) or conjunctive (false).
If the filter applies multiple times, e.g.
because the query string contains multiple values of the same facet, the multiple occurrences are combined
with an AND operator by default (conjunctive mode). If the filter is specified as disjunctive,
however, multiple occurrences are combined with an OR operator instead.
*/
public let isDisjunctive: Bool?
public init(attribute: Attribute, score: Int? = nil, isDisjunctive: Bool? = nil) {
self.attribute = attribute
self.score = score
self.isDisjunctive = isDisjunctive
}
}
}
extension Rule.AutomaticFacetFilters {
enum CodingKeys: String, CodingKey {
case attribute = "facet"
case score
case isDisjunctive = "disjunctive"
}
}
| mit | 421642c6aab5fd94b5bb8ffa3031dc1d | 24.708333 | 110 | 0.703404 | 4.391459 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/API/Types/Inline/InlineQueryResult/InlineResultPhoto.swift | 1 | 1963 | //
// InlineResultPhoto.swift
// Pelican
//
// Created by Takanu Kyriako on 20/12/2017.
//
import Foundation
/**
Represents either a link to a photo that's stored on the Telegram servers, or an external URL link to one.
By default, this photo will be sent by the user with an optional caption. Alternatively, you can use the `content` property to send a message with the specified content instead of the file.
*/
public struct InlineResultPhoto: InlineResult {
/// A metatype, used to Encode and Decode itself as part of the InlineResult protocol.
public var metatype: InlineResultType = .photo
/// Type of the result being given.
public var type: String = "photo"
/// Unique Identifier for the result, 1-64 bytes.
public var id: String
/// Content of the message to be sent.
public var content: InputMessageContent?
/// Inline keyboard attached to the message
public var markup: MarkupInline?
/// A valid URL of the photo. Photo must be in jpeg format. Photo size must not exceed 5MB
public var url: String?
/// A valid file identifier of the photo.
public var fileID: String?
/// The title of the inline result.
public var title: String?
/// A short description of the inline result.
public var description: String?
/// A caption for the photo to be sent, 200 characters maximum.
public var caption: String?
/// URL of the thumbnail to use for the result.
public var thumbURL: String?
/// Thumbnail width.
public var thumbWidth: Int?
/// Thumbnail height.
public var thumbHeight: Int?
/// Coding keys to map values when Encoding and Decoding.
enum CodingKeys: String, CodingKey {
case type
case id
case content = "input_message_content"
case markup = "reply_markup"
case url = "photo_url"
case fileID = "photo_file_id"
case caption
case title
case description
case thumbURL = "thumb_url"
case thumbWidth = "thumb_width"
case thumbHeight = "thumb_height"
}
}
| mit | 92b4665e99c7ac95eb01629f4d733c9c | 24.166667 | 189 | 0.714722 | 3.841487 | false | false | false | false |
lfarah/mynz | App/MYNZ/Trap.swift | 1 | 911 | //
// Trap.swift
// MYNZ
//
// Created by Lucas Farah on 4/9/16.
// Copyright © 2016 Lucas Farah. All rights reserved.
//
import UIKit
import CoreLocation
import Parse
class Trap: AnyObject {
//MARK: - Variables
enum TrapType {
case Mine
}
var location: CLLocation
var type: TrapType
var userId: String
var objectId: String
//MARK: - Methods
init(location: CLLocation, type: TrapType, userId: String, objectId: String) {
self.location = location
self.type = type
self.userId = userId
self.objectId = objectId
}
// When bomb explodes user, bomb is deleted
func remove() {
let query = PFQuery(className: "Mine")
query.whereKey("objectId", equalTo: self.objectId)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if error == nil && objects?.count > 0 {
let obj = objects?.first
obj?.deleteInBackground()
}
}
}
}
| mit | f555978a347fb431f4d97a1eee96c9dd | 18.782609 | 80 | 0.659341 | 3.625498 | false | false | false | false |
Yalantis/ColorMatchTabs | ColorMatchTabs/Classes/Views/MenuView.swift | 1 | 4385 | //
// MenuView.swift
// ColorMatchTabs
//
// Created by Serhii Butenko on 27/6/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
class MenuView: UIView {
private(set) var navigationBar: UIView!
private(set) var tabs: ColorTabs!
private(set) var scrollMenu: ScrollMenu!
private(set) var circleMenuButton: UIButton!
private var shadowView: VerticalGradientView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
layoutIfNeeded()
}
func setCircleMenuButtonHidden(_ hidden: Bool) {
circleMenuButton.isHidden = hidden
shadowView.isHidden = hidden
}
}
// Init
private extension MenuView {
func commonInit() {
backgroundColor = .white
createSubviews()
layoutNavigationBar()
layoutTabs()
layoutScrollMenu()
layoutShadowView()
layoutCircleMenu()
}
func createSubviews() {
scrollMenu = ScrollMenu()
scrollMenu.showsHorizontalScrollIndicator = false
addSubview(scrollMenu)
navigationBar = ExtendedNavigationBar()
navigationBar.backgroundColor = .white
addSubview(navigationBar)
tabs = ColorTabs()
tabs.isUserInteractionEnabled = true
navigationBar.addSubview(tabs)
shadowView = VerticalGradientView()
shadowView.isHidden = true
shadowView.topColor = UIColor(white: 1, alpha: 0)
shadowView.bottomColor = UIColor(white: 1, alpha: 1)
addSubview(shadowView)
circleMenuButton = UIButton()
circleMenuButton.isHidden = true
circleMenuButton.setImage(UIImage(namedInCurrentBundle: "circle_menu"), for: UIControl.State())
circleMenuButton.adjustsImageWhenHighlighted = false
addSubview(circleMenuButton)
}
}
// Layout
private extension MenuView {
func layoutNavigationBar() {
navigationBar.translatesAutoresizingMaskIntoConstraints = false
navigationBar.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
navigationBar.topAnchor.constraint(equalTo: topAnchor).isActive = true
navigationBar.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
navigationBar.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
func layoutTabs() {
tabs.translatesAutoresizingMaskIntoConstraints = false
tabs.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor).isActive = true
tabs.topAnchor.constraint(equalTo: navigationBar.topAnchor).isActive = true
tabs.trailingAnchor.constraint(equalTo: navigationBar.trailingAnchor).isActive = true
tabs.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: -6).isActive = true
}
func layoutScrollMenu() {
scrollMenu.translatesAutoresizingMaskIntoConstraints = false
scrollMenu.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
scrollMenu.topAnchor.constraint(equalTo: navigationBar.bottomAnchor).isActive = true
scrollMenu.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
scrollMenu.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
func layoutShadowView() {
shadowView.translatesAutoresizingMaskIntoConstraints = false
shadowView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
shadowView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
shadowView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
shadowView.heightAnchor.constraint(equalToConstant: 80).isActive = true
}
func layoutCircleMenu() {
circleMenuButton.translatesAutoresizingMaskIntoConstraints = false
circleMenuButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: PlusButtonButtonOffset).isActive = true
circleMenuButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
}
| mit | d3ce8c58a7d6d9ada2c487da8871ac0d | 33.25 | 121 | 0.690237 | 5.584713 | false | false | false | false |
ErAbhishekChandani/ACFloatingTextfield | ACFloatingTextField-Swift/ACFloatingTextField/ViewController.swift | 1 | 3593 | //
// ViewController.swift
// ACFloatingTextField
//
// Created by Er Abhishek Chandani on 31/07/16.
// Copyright © 2016 Abhishek. All rights reserved.
//
import UIKit
class ViewController: UIViewController ,UITextFieldDelegate {
let aTextField = ACFloatingTextfield()
@IBOutlet weak var tf1: ACFloatingTextfield!
@IBOutlet weak var tf2: ACFloatingTextfield!
@IBOutlet weak var tf3: ACFloatingTextfield!
// @IBOutlet weak var textFieldUsername: ACFloatingTextfield!
override func viewDidLoad() {
super.viewDidLoad()
aTextField.frame = CGRect(x:20, y:300, width:UIScreen.main.bounds.width-40, height:45)
aTextField.delegate = self
aTextField.placeholder = "Pasggsword"
aTextField.text = "Abhishk22580"
aTextField.lineColor = UIColor.brown
aTextField.selectedLineColor = UIColor.brown
aTextField.placeHolderColor = UIColor.cyan
aTextField.selectedPlaceHolderColor = UIColor.orange
self.view.addSubview(aTextField)
}
@IBAction func hideError(_ sender: Any) {
tf1.hideError()
tf2.hideError()
tf3.hideError()
aTextField.hideError()
}
@IBAction func showError(_ sender: AnyObject) {
tf1.showErrorWithText(errorText: "Enter Valhhggggggid Text")
tf2.showErrorWithText(errorText: "Enter Valhhggggggid Text")
tf3.showErrorWithText(errorText: "Enter Valhhggggggid Text")
aTextField.showErrorWithText(errorText: "Enter Valhhggggggid Text")
}
@IBAction func changeErrorColor(_ sender: Any) {
tf1.errorTextColor = getRandomColor()
tf2.errorTextColor = getRandomColor()
tf3.errorTextColor = getRandomColor()
aTextField.errorTextColor = getRandomColor()
tf1.errorLineColor = getRandomColor()
tf2.errorLineColor = getRandomColor()
tf3.errorLineColor = getRandomColor()
aTextField.errorLineColor = getRandomColor()
}
@IBAction func chanagePlacecholderColor(_ sender: Any) {
tf1.placeHolderColor = getRandomColor()
tf2.placeHolderColor = getRandomColor()
tf3.placeHolderColor = getRandomColor()
aTextField.placeHolderColor = getRandomColor()
tf1.selectedPlaceHolderColor = getRandomColor()
tf2.selectedPlaceHolderColor = getRandomColor()
tf3.selectedPlaceHolderColor = getRandomColor()
aTextField.selectedPlaceHolderColor = getRandomColor()
}
@IBAction func changeLineColor(_ sender: Any) {
tf1.lineColor = getRandomColor()
tf2.lineColor = getRandomColor()
tf3.lineColor = getRandomColor()
aTextField.lineColor = getRandomColor()
tf1.selectedLineColor = getRandomColor()
tf2.selectedLineColor = getRandomColor()
tf3.selectedLineColor = getRandomColor()
aTextField.selectedLineColor = getRandomColor()
}
func getRandomColor() -> UIColor{
let randomRed:CGFloat = CGFloat(drand48())
let randomGreen:CGFloat = CGFloat(drand48())
let randomBlue:CGFloat = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | b985eaea859062c0949f0821a64f589f | 32.570093 | 94 | 0.672327 | 4.776596 | false | false | false | false |
fabiomassimo/eidolon | KioskTests/Bid Fulfillment/RegistrationPasswordViewModelTests.swift | 1 | 8100 | import Quick
import Nimble
import ReactiveCocoa
import Swift_RAC_Macros
import Kiosk
import Moya
let testPassword = "password"
let testEmail = "[email protected]"
class RegistrationPasswordViewModelTests: QuickSpec {
typealias Check = (() -> ())?
func stubProvider(#emailExists: Bool, emailCheck: Check, loginSucceeds: Bool, loginCheck: Check, passwordRequestSucceeds: Bool, passwordCheck: Check) {
let endpointsClosure = { (target: ArtsyAPI) -> Endpoint<ArtsyAPI> in
switch target {
case ArtsyAPI.FindExistingEmailRegistration(let email):
emailCheck?()
expect(email) == testEmail
return Endpoint<ArtsyAPI>(URL: url(target), sampleResponse: .Success(emailExists ? 200 : 404, {NSData()}), method: target.method, parameters: target.parameters)
case ArtsyAPI.LostPasswordNotification(let email):
passwordCheck?()
expect(email) == testEmail
return Endpoint<ArtsyAPI>(URL: url(target), sampleResponse: .Success(passwordRequestSucceeds ? 200 : 404, {NSData()}), method: target.method, parameters: target.parameters)
case ArtsyAPI.XAuth(let email, let password):
loginCheck?()
expect(email) == testEmail
expect(password) == testPassword
// Fail auth (wrong password maybe)
return Endpoint<ArtsyAPI>(URL: url(target), sampleResponse: .Success(loginSucceeds ? 200 : 403, {NSData()}), method: target.method, parameters: target.parameters)
case .XApp:
// Any XApp requests are incidental; ignore.
return Endpoint<ArtsyAPI>(URL: url(target), sampleResponse: .Success(200, {NSData()}), method: target.method, parameters: target.parameters)
default:
// Fail on all other cases
expect(true) == false
return Endpoint<ArtsyAPI>(URL: url(target), sampleResponse: .Success(200, {NSData()}), method: target.method, parameters: target.parameters)
}
}
Provider.sharedProvider = ArtsyProvider(endpointsClosure: endpointsClosure, stubResponses: true, onlineSignal: { RACSignal.empty() })
}
func testSubject(passwordSubject: RACSignal = RACSignal.`return`(testPassword), invocationSignal: RACSignal = RACSubject(), finishedSubject: RACSubject = RACSubject()) -> RegistrationPasswordViewModel {
return RegistrationPasswordViewModel(passwordSignal: passwordSubject, manualInvocationSignal: invocationSignal, finishedSubject: finishedSubject, email: testEmail)
}
override func spec() {
// Just so providers form individual tests don't bleed into one another
setupProviderForSuite(Provider.StubbingProvider())
defaults = NSUserDefaults.standardUserDefaults()
it("enables the command only when the password is valid") {
let passwordSubject = RACSubject()
let subject = self.testSubject(passwordSubject: passwordSubject)
passwordSubject.sendNext("nope")
expect((subject.command.enabled.first() as! Bool)).toEventually( beFalse() )
passwordSubject.sendNext("validpassword")
expect((subject.command.enabled.first() as! Bool)).toEventually( beTrue() )
passwordSubject.sendNext("")
expect((subject.command.enabled.first() as! Bool)).toEventually( beFalse() )
}
it("checks for an email when executing the command") {
var checked = false
self.stubProvider(emailExists: false, emailCheck: { () -> () in
checked = true
}, loginSucceeds: true, loginCheck: nil, passwordRequestSucceeds: true, passwordCheck: nil)
let subject = self.testSubject()
subject.command.execute(nil)
expect(checked).toEventually( beTrue() )
}
it("sends true on emailExistsSignal if email exists") {
var exists = false
self.stubProvider(emailExists: true, emailCheck: { () -> () in
exists = true
}, loginSucceeds: true, loginCheck: nil, passwordRequestSucceeds: true, passwordCheck: nil)
let subject = self.testSubject()
subject.emailExistsSignal.subscribeNext { (object) -> Void in
exists = object as? Bool ?? false
}
subject.command.execute(nil)
expect(exists).toEventually( beTrue() )
}
it("sends false on emailExistsSignal if email does not exist") {
var exists: Bool?
self.stubProvider(emailExists: false, emailCheck: { () -> () in
exists = true
}, loginSucceeds: true, loginCheck: nil, passwordRequestSucceeds: true, passwordCheck: nil)
let subject = self.testSubject()
subject.emailExistsSignal.subscribeNext { (object) -> Void in
exists = object as? Bool
}
subject.command.execute(nil)
expect(exists).toEventuallyNot( beNil() )
expect(exists).toEventually( beFalse() )
}
it("checks for authorization if the email exists") {
var checked = false
var authed = false
self.stubProvider(emailExists: true, emailCheck: {
checked = true
}, loginSucceeds: true, loginCheck: {
authed = true
}, passwordRequestSucceeds: true, passwordCheck: nil)
let subject = self.testSubject()
subject.command.execute(nil)
expect(checked).toEventually( beTrue() )
expect(authed).toEventually( beTrue() )
}
it("sends an error on the command if the authorization fails") {
self.stubProvider(emailExists: true, emailCheck: nil, loginSucceeds: false, loginCheck: nil, passwordRequestSucceeds: true, passwordCheck: nil)
let subject = self.testSubject()
var errored = false
subject.command.errors.subscribeNext { _ -> Void in
errored = true
}
subject.command.execute(nil)
expect(errored).toEventually( beTrue() )
}
it("executes command when manual signal sends") {
self.stubProvider(emailExists: false, emailCheck: nil, loginSucceeds: false, loginCheck: nil, passwordRequestSucceeds: true, passwordCheck: nil)
let invocationSignal = RACSubject()
let subject = self.testSubject(invocationSignal: invocationSignal)
var completed = false
subject.command.executing.take(1).subscribeNext { _ -> Void in
completed = true
}
invocationSignal.sendNext(nil)
expect(completed).toEventually( beTrue() )
}
it("sends completed on finishedSubject when command is executed") {
let invocationSignal = RACSubject()
let finishedSubject = RACSubject()
var completed = false
finishedSubject.subscribeCompleted { () -> Void in
completed = true
}
let subject = self.testSubject(invocationSignal:invocationSignal, finishedSubject: finishedSubject)
subject.command.execute(nil)
expect(completed).toEventually( beTrue() )
}
it("handles password reminders") {
var sent = false
self.stubProvider(emailExists: false, emailCheck: nil, loginSucceeds: false, loginCheck: nil, passwordRequestSucceeds: true, passwordCheck: {
sent = true
})
let subject = self.testSubject()
subject.userForgotPasswordSignal().subscribeNext { _ -> Void in
// do nothing – we subscribe just to force the signal to execute.
}
expect(sent).toEventually( beTrue() )
Provider.sharedProvider = Provider.StubbingProvider()
}
}
}
| mit | adf8bfe0b101f813ac3e45765b19c35c | 37.932692 | 206 | 0.611509 | 5.148125 | false | true | false | false |
hari-tw/WWDC | SFParties WatchKit Extension/WDCGlanceInterfaceController.swift | 1 | 2422 | //
// WDCGlanceInterfaceController.swift
// SFParties
//
// Created by Genady Okrain on 3/5/15.
// Copyright (c) 2015 Sugar So Studio. All rights reserved.
//
import WatchKit
class WDCGlanceInterfaceController: WKInterfaceController {
@IBOutlet weak var titleLabel: WKInterfaceLabel!
@IBOutlet weak var emptyLabel: WKInterfaceLabel!
@IBOutlet weak var iconImage: WKInterfaceImage!
@IBOutlet weak var timer: WKInterfaceTimer!
var refreshTimer:NSTimer?
override func awakeWithContext(context: AnyObject!) {
// Initialize variables here.
super.awakeWithContext(context)
// analytics
let userDefaults = NSUserDefaults(suiteName: "group.so.sugar.SFParties")!
userDefaults.setInteger(userDefaults.integerForKey("glanceRuns")+1, forKey: "glanceRuns")
userDefaults.synchronize()
loadData()
}
func loadData() {
let parties = WDCParties.sharedInstance().glanceParties
if (parties.count == 0) {
iconImage.setHidden(true)
titleLabel.setHidden(true)
timer.setHidden(true)
emptyLabel.setHidden(false)
} else {
iconImage.setHidden(false)
titleLabel.setHidden(false)
timer.setHidden(false)
emptyLabel.setHidden(true)
let party = parties[0] as! WDCParty // TBD
if WKInterfaceDevice().cachedImages[party.objectId] != nil {
iconImage.setImageNamed(party.objectId)
} else if party.watchIcon != nil {
if WKInterfaceDevice().addCachedImage(party.watchIcon, name: party.objectId) {
iconImage.setImageNamed(party.objectId)
} else {
iconImage.setImage(party.watchIcon)
}
}
titleLabel.setText(party.title)
timer.setDate(party.startDate)
timer.start()
// Handoff
updateUserActivity("so.sugar.SFParties.view", userInfo: ["objectId": party.objectId], webpageURL: NSURL(string: party.url))
}
}
override func willActivate() {
super.willActivate()
refreshTimer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "loadData", userInfo: nil, repeats: true)
}
override func didDeactivate() {
super.didDeactivate()
refreshTimer?.invalidate()
}
}
| mit | 382bccf7d9d055bbe347a7c3dacdd8b7 | 32.178082 | 135 | 0.627993 | 4.873239 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/RequestJoinMemberListController.swift | 1 | 19565 | //
// RequestJoinMemberListController.swift
// Telegram
//
// Created by Mikhail Filimonov on 01.10.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Foundation
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
import Postbox
private final class Arguments {
let context: AccountContext
let add:(PeerId)->Void
let dismiss:(PeerId)->Void
let openInfo:(PeerId)->Void
let openInviteLinks:()->Void
init(context: AccountContext, add:@escaping(PeerId)->Void, dismiss:@escaping(PeerId)->Void, openInfo:@escaping(PeerId)->Void, openInviteLinks:@escaping()->Void) {
self.context = context
self.add = add
self.dismiss = dismiss
self.openInfo = openInfo
self.openInviteLinks = openInviteLinks
}
}
struct PeerRequestChatJoinData : Equatable {
let peer: PeerEquatable
let about: String?
let timeInterval: TimeInterval
let added: Bool
let adding: Bool
let dismissing: Bool
let dismissed: Bool
}
private struct State : Equatable {
struct SearchResult : Equatable {
var isLoading: Bool
var result: PeerInvitationImportersState?
}
var peer: PeerEquatable?
var state:PeerInvitationImportersState?
var added:Set<PeerId> = Set()
var dismissed:Set<PeerId> = Set()
var searchState: SearchState?
var empty: Bool {
if let state = state {
return state.importers.isEmpty
}
return true
}
var searchResult: SearchResult?
}
private func entries(_ state: State, arguments: Arguments) -> [InputDataEntry] {
var entries:[InputDataEntry] = []
var sectionId:Int32 = 0
var index: Int32 = 0
if let peer = state.peer?.peer {
if !state.empty {
if let searchState = state.searchState {
switch searchState.state {
case .Focus:
entries.append(.sectionId(sectionId, type: .customModern(80)))
sectionId += 1
default:
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
}
} else {
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
}
if state.searchResult == nil {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("header"), equatable: nil, comparable: nil, item: { initialSize, stableId in
let text: String = strings().requestJoinListDescription
let attr = parseMarkdownIntoAttributedString(text, attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: .normal(.text), textColor: theme.colors.listGrayText), bold: MarkdownAttributeSet(font: .bold(.text), textColor: theme.colors.listGrayText), link: MarkdownAttributeSet(font: .normal(.text), textColor: theme.colors.accent), linkAttribute: { contents in
return (NSAttributedString.Key.link.rawValue, inAppLink.callback(contents, {_ in
arguments.openInviteLinks()
}))
}))
return AnimatedStickerHeaderItem(initialSize, stableId: stableId, context: arguments.context, sticker: LocalAnimatedSticker.request_join_link, text: attr)
}))
index += 1
}
let isChannel = peer.isChannel
let effectiveImporterState: PeerInvitationImportersState?
if let searchResult = state.searchResult {
effectiveImporterState = searchResult.result
if searchResult.isLoading {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("searching"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return GeneralLoadingRowItem(initialSize, stableId: stableId, viewType: .singleItem)
}))
index += 1
} else if let result = searchResult.result, result.count == 0, let request = state.searchState?.request {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("dynamic_top"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return DynamicHeightRowItem(initialSize, stableId: stableId, side: .top)
}))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("empty_header"), equatable: nil, comparable: nil, item: { initialSize, stableId in
let text: String = strings().requestJoinListSearchEmpty(request)
let attr = NSMutableAttributedString()
_ = attr.append(string: strings().requestJoinListSearchEmptyHeader, color: theme.colors.text, font: .medium(.header))
_ = attr.append(string: "\n", color: theme.colors.grayText, font: .normal(.title))
_ = attr.append(string: text, color: theme.colors.grayText, font: .normal(.title))
attr.detectBoldColorInString(with: .medium(.title))
return AnimatedStickerHeaderItem(initialSize, stableId: stableId, context: arguments.context, sticker: LocalAnimatedSticker.zoom, text: attr)
}))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("dynamic_bottom"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return DynamicHeightRowItem(initialSize, stableId: stableId, side: .bottom)
}))
index += 1
//
// entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("search_empty"), equatable: nil, comparable: nil, item: { initialSize, stableId in
// return GeneralBlockTextRowItem.init(initialSize, stableId: stableId, viewType: .singleItem, text: strings().requestJoinListSearchEmpty(request), font: .normal(.text), color: theme.colors.text, header: .init(text: strings().requestJoinListSearchEmptyHeader, icon: nil))
// }))
// index += 1
}
} else {
effectiveImporterState = state.state
}
if let importerState = effectiveImporterState {
let importers = importerState.importers.filter { $0.approvedBy == nil && !state.added.contains($0.peer.peerId) && !state.dismissed.contains($0.peer.peerId) }
if !importers.isEmpty {
if state.searchResult == nil {
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().requestJoinListListHeaderCountable(importers.count)), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
}
for (i, importer) in importers.enumerated() {
let data: PeerRequestChatJoinData = .init(peer: PeerEquatable(importer.peer.peer!), about: importer.about, timeInterval: TimeInterval(importer.date), added: state.added.contains(importer.peer.peerId), adding: false, dismissing: false, dismissed: state.dismissed.contains(importer.peer.peerId))
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("peer_id_\(importer.peer.peerId)"), equatable: .init(data), comparable: nil, item: { initialSize, stableId in
return PeerRequestJoinRowItem(initialSize, stableId: stableId, context: arguments.context, isChannel: isChannel, data: data, add: arguments.add, dismiss: arguments.dismiss, openInfo: arguments.openInfo, viewType: bestGeneralViewType(importers, for: i))
}))
index += 1
}
}
}
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
} else if let _ = state.state {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("dynamic_top"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return DynamicHeightRowItem(initialSize, stableId: stableId, side: .top)
}))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("center"), equatable: nil, comparable: nil, item: { initialSize, stableId in
let attr = NSMutableAttributedString()
_ = attr.append(string: strings().requestJoinListEmpty1, color: theme.colors.text, font: .medium(.header))
_ = attr.append(string: "\n", color: theme.colors.text, font: .medium(.header))
_ = attr.append(string: peer.isChannel ? strings().requestJoinListEmpty2Channel : strings().requestJoinListEmpty2Group, color: theme.colors.listGrayText, font: .normal(.text))
return AnimatedStickerHeaderItem(initialSize, stableId: stableId, context: arguments.context, sticker: LocalAnimatedSticker.thumbsup, text: attr)
}))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("dynamic_bottom"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return DynamicHeightRowItem(initialSize, stableId: stableId, side: .bottom)
}))
index += 1
} else {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("dynamic_top"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return DynamicHeightRowItem(initialSize, stableId: stableId, side: .top)
}))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("progress"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return LoadingTableItem(initialSize, height: 100, stableId: stableId)
}))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("dynamic_bottom"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return DynamicHeightRowItem(initialSize, stableId: stableId, side: .bottom)
}))
index += 1
}
}
return entries
}
func RequestJoinMemberListController(context: AccountContext, peerId: PeerId, manager: PeerInvitationImportersContext, openInviteLinks: @escaping()->Void) -> InputDataController {
let actionsDisposable = DisposableSet()
let initialState = State(peer: nil, state: nil, added: Set(), dismissed: Set(), searchState: SearchState(state: .None, request: nil))
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((State) -> State) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
let searchStatePromise = ValuePromise(SearchState(state: .None, request: nil), ignoreRepeated: true)
let searchStateValue = Atomic(value: SearchState(state: .None, request: nil))
let updateSearchState: ((SearchState) -> SearchState) -> Void = { f in
searchStatePromise.set(searchStateValue.modify (f))
}
var getController:(()->InputDataController?)? = nil
let arguments = Arguments(context: context, add: { [weak manager] userId in
updateState { current in
var current = current
current.added.insert(userId)
return current
}
let attr = NSMutableAttributedString()
let text: String
let isChannel = stateValue.with { $0.peer?.peer.isChannel == true }
let peer = stateValue.with { $0.state?.importers.first(where: { $0.peer.peerId == userId })}
if isChannel {
text = strings().requestJoinListTooltipApprovedChannel(peer?.peer.peer?.displayTitle ?? "")
} else {
text = strings().requestJoinListTooltipApprovedGroup(peer?.peer.peer?.displayTitle ?? "")
}
_ = attr.append(string: text, color: theme.colors.text, font: .normal(.text))
attr.detectBoldColorInString(with: .medium(.text))
getController?()?.show(toaster: ControllerToaster(text: attr))
manager?.update(userId, action: .approve)
}, dismiss: { [weak manager] userId in
updateState { current in
var current = current
current.added.insert(userId)
return current
}
manager?.update(userId, action: .deny)
}, openInfo: { peerId in
context.bindings.rootNavigation().push(PeerInfoController(context: context, peerId: peerId))
}, openInviteLinks: openInviteLinks)
let peerSignal = context.engine.data.subscribe(TelegramEngine.EngineData.Item.Peer.Peer(id: peerId))
actionsDisposable.add(peerSignal.start(next: { peer in
updateState { current in
var current = current
if let peer = peer?._asPeer() {
current.peer = .init(peer)
} else {
current.peer = nil
}
return current
}
}))
actionsDisposable.add(manager.state.start(next: { state in
updateState { current in
var current = current
current.state = state
return current
}
}))
var searchManager: PeerInvitationImportersContext?
let searchResultDisposable = MetaDisposable()
actionsDisposable.add(searchStatePromise.get().start(next: { state in
let result: State.SearchResult?
if !state.request.isEmpty {
result = .init(isLoading: true, result: nil)
} else {
result = nil
}
updateState { current in
var current = current
current.searchState = state
current.searchResult = result
return current
}
if result != nil {
let manager = context.engine.peers.peerInvitationImporters(peerId: peerId, subject: .requests(query: state.request))
manager.loadMore()
searchManager = manager
searchResultDisposable.set(manager.state.start(next: { state in
updateState { current in
var current = current
if !state.isLoadingMore {
current.searchResult = .init(isLoading: false, result: state)
}
return current
}
}))
} else {
searchManager = nil
searchResultDisposable.set(nil)
}
}))
let searchValue:Atomic<TableSearchViewState> = Atomic(value: .none({ searchState in
updateSearchState { _ in
return searchState
}
}))
let searchPromise: ValuePromise<TableSearchViewState> = ValuePromise(.none({ searchState in
updateSearchState { _ in
return searchState
}
}), ignoreRepeated: true)
let updateSearchValue:((TableSearchViewState)->TableSearchViewState)->Void = { f in
searchPromise.set(searchValue.modify(f))
}
let searchData = TableSearchVisibleData(cancelImage: theme.icons.chatSearchCancel, cancel: {
updateSearchValue { _ in
return .none({ searchState in
updateSearchState { _ in
return searchState
}
})
}
}, updateState: { searchState in
updateSearchState { _ in
return searchState
}
})
let signal = combineLatest(statePromise.get(), searchPromise.get()) |> deliverOnPrepareQueue |> map { state, searchData in
return InputDataSignalValue(entries: entries(state, arguments: arguments), searchState: searchData)
}
var updateBarIsHidden:((Bool)->Void)? = nil
let controller = InputDataController(dataSignal: signal, title: strings().requestJoinListTitle, removeAfterDisappear: false, customRightButton: { controller in
let bar = ImageBarView(controller: controller, theme.icons.chatSearch)
bar.button.set(handler: { _ in
updateSearchValue { current in
switch current {
case .none:
return .visible(searchData)
case .visible:
return .none({ searchState in
updateState { current in
var current = current
current.searchState = searchState
return current
}
})
}
}
}, for: .Click)
bar.button.autohighlight = false
bar.button.scaleOnClick = true
updateBarIsHidden = { [weak bar] isHidden in
bar?.button.alphaValue = isHidden ? 0 : 1
}
return bar
})
controller.onDeinit = {
actionsDisposable.dispose()
searchResultDisposable.dispose()
searchManager = nil
}
controller.searchKeyInvocation = {
updateSearchValue { current in
switch current {
case .none:
return .visible(searchData)
case .visible:
return .none({ searchState in
updateState { current in
var current = current
current.searchState = searchState
return current
}
})
}
}
return .invoked
}
controller.didLoaded = { [weak manager] controller, _ in
controller.tableView.setScrollHandler { position in
switch position.direction {
case .bottom:
manager?.loadMore()
default:
break
}
}
}
controller.afterTransaction = { controller in
updateBarIsHidden?(stateValue.with { $0.state?.importers.filter { $0.approvedBy == nil}.count == 0 })
}
getController = { [weak controller] in
return controller
}
return controller
}
| gpl-2.0 | 61d89a2734796fca4b1b4f2c38c495af | 40.982833 | 386 | 0.572736 | 5.199043 | false | false | false | false |
zhangao0086/DKPhotoGallery | DKPhotoGallery/DKPhotoGalleryContentVC.swift | 2 | 17434 | //
// DKPhotoGalleryContentVC.swift
// DKPhotoGallery
//
// Created by ZhangAo on 16/6/23.
// Copyright © 2016年 ZhangAo. All rights reserved.
//
import UIKit
fileprivate class DKPhotoGalleryContentFooterViewContainer : UIView {
private var footerView: UIView
private var backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
init(footerView: UIView) {
self.footerView = footerView
super.init(frame: CGRect.zero)
self.addSubview(self.backgroundView)
self.backgroundView.contentView.addSubview(footerView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.backgroundView.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height)
self.footerView.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.footerView.bounds.height)
}
}
////////////////////////////////////////////////////////////
internal protocol DKPhotoGalleryContentDataSource: class {
func item(for index: Int) -> DKPhotoGalleryItem
func numberOfItems() -> Int
func hasIncrementalDataForLeft() -> Bool
func incrementalItemsForLeft(resultHandler: @escaping ((_ count: Int) -> Void))
func hasIncrementalDataForRight() -> Bool
func incrementalItemsForRight(resultHandler: @escaping ((_ count: Int) -> Void))
}
internal protocol DKPhotoGalleryContentDelegate: class {
func contentVCCanScrollToPreviousOrNext(_ contentVC: DKPhotoGalleryContentVC) -> Bool
}
////////////////////////////////////////////////////////////
@objc
open class DKPhotoGalleryContentVC: UIViewController, UIScrollViewDelegate {
internal weak var dataSource: DKPhotoGalleryContentDataSource!
internal weak var delegate: DKPhotoGalleryContentDelegate?
public var pageChangeBlock: ((_ index: Int) -> Void)?
public var prepareToShow: ((_ previewVC: DKPhotoBasePreviewVC) -> Void)?
open var currentIndex = 0 {
didSet {
self.pageChangeBlock?(self.currentIndex)
}
}
public var currentVC: DKPhotoBasePreviewVC {
get { return self.visibleVCs[self.dataSource.item(for: self.currentIndex)]! }
}
public var currentContentView: UIView {
get { return self.currentVC.contentView }
}
private let mainView = DKPhotoGalleryScrollView()
private var reuseableVCs: [ObjectIdentifier : [DKPhotoBasePreviewVC] ] = [:] // DKPhotoBasePreviewVC.Type : [DKPhotoBasePreviewVC]
private var visibleVCs: [DKPhotoGalleryItem : DKPhotoBasePreviewVC] = [:]
open var footerView: UIView? {
didSet {
self.updateFooterView()
if let footerViewContainer = self.footerViewContainer {
footerViewContainer.alpha = 0
self.setFooterViewHidden(false, animated: true)
}
}
}
private var footerViewContainer: DKPhotoGalleryContentFooterViewContainer?
private var leftIncrementalIndicator: DKPhotoIncrementalIndicator?
private var rightIncrementalIndicator: DKPhotoIncrementalIndicator?
open override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.view.backgroundColor = UIColor.clear
self.mainView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
self.mainView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.mainView.delegate = self
#if swift(>=4.2)
self.mainView.decelerationRate = UIScrollView.DecelerationRate.fast
#else
self.mainView.decelerationRate = UIScrollViewDecelerationRateFast
#endif
self.mainView.set(totalCount: self.dataSource.numberOfItems())
self.view.addSubview(self.mainView)
self.updateVisibleViews(index: self.currentIndex, scrollToIndex: true, indexOnly: true)
self.updateFooterView()
if self.dataSource.hasIncrementalDataForLeft() {
self.leftIncrementalIndicator = DKPhotoIncrementalIndicator.indicator(with: .left) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.dataSource.incrementalItemsForLeft { [weak self] (count) in
guard let strongSelf = self, let leftIncrementalIndicator = strongSelf.leftIncrementalIndicator else { return }
let scrollView = strongSelf.mainView
let canScrollToPreviousOrNext = strongSelf.delegate?.contentVCCanScrollToPreviousOrNext(strongSelf) ?? true
let shouldScrollToPrevious = canScrollToPreviousOrNext && !scrollView.isDragging &&
scrollView.contentOffset.x == -leftIncrementalIndicator.pullDistance
if count > 0 {
strongSelf.currentIndex += count
strongSelf.mainView.insertBefore(totalCount: count)
strongSelf.updateVisibleViews(index: strongSelf.currentIndex, scrollToIndex: false)
}
UIView.animate(withDuration: 0.4, animations: {
if shouldScrollToPrevious {
strongSelf.scrollToPrevious()
} else if !scrollView.isDragging {
strongSelf.scrollToCurrentPage()
}
}, completion: { finished in
leftIncrementalIndicator.isEnabled = strongSelf.dataSource.hasIncrementalDataForLeft()
})
leftIncrementalIndicator.endRefreshing()
}
}
self.mainView.addSubview(self.leftIncrementalIndicator!)
}
if self.dataSource.hasIncrementalDataForRight() {
self.rightIncrementalIndicator = DKPhotoIncrementalIndicator.indicator(with: .right) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.dataSource.incrementalItemsForRight { [weak self] (count) in
guard let strongSelf = self, let rightIncrementalIndicator = strongSelf.rightIncrementalIndicator else { return }
let scrollView = strongSelf.mainView
let canScrollToPreviousOrNext = strongSelf.delegate?.contentVCCanScrollToPreviousOrNext(strongSelf) ?? true
let shouldScrollToNext = canScrollToPreviousOrNext && !scrollView.isDragging &&
scrollView.contentSize.width == scrollView.contentOffset.x + scrollView.bounds.width - rightIncrementalIndicator.pullDistance
if count > 0 {
strongSelf.mainView.insertAfter(totalCount: count)
strongSelf.updateVisibleViews(index: strongSelf.currentIndex, scrollToIndex: false)
}
rightIncrementalIndicator.endRefreshing()
UIView.animate(withDuration: 0.4, animations: {
if shouldScrollToNext {
strongSelf.scrollToNext()
} else if !scrollView.isDragging {
strongSelf.scrollToCurrentPage()
}
}, completion: { finished in
rightIncrementalIndicator.isEnabled = strongSelf.dataSource.hasIncrementalDataForRight()
})
}
}
self.mainView.addSubview(self.rightIncrementalIndicator!)
}
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.prefillingReuseQueue()
}
internal func filterVisibleVCs<T>(with className: T.Type) -> [T]? {
var filtered = [T]()
for (_, value) in self.visibleVCs {
if let value = value as? T {
filtered.append(value)
}
}
return filtered
}
internal func setFooterViewHidden(_ hidden: Bool, animated: Bool, completeBlock: (() -> Void)? = nil) {
guard let footerView = self.footerViewContainer else { return }
let alpha = CGFloat(hidden ? 0 : 1)
if footerView.alpha != alpha {
let footerViewAnimationBlock = {
footerView.alpha = alpha
}
if animated {
UIView.animate(withDuration: 0.2, animations: footerViewAnimationBlock) { finished in
completeBlock?()
}
} else {
footerViewAnimationBlock()
}
}
}
// MARK: - Private
private func updateFooterView() {
guard self.isViewLoaded else { return }
if let footerView = self.footerView {
self.footerViewContainer = DKPhotoGalleryContentFooterViewContainer(footerView: footerView)
let footerViewHeight = footerView.bounds.height + (DKPhotoBasePreviewVC.isIphoneX() ? 34 : 0)
self.footerViewContainer!.frame = CGRect(x: 0, y: self.view.bounds.height - footerViewHeight,
width: self.view.bounds.width, height: footerViewHeight)
self.view.addSubview(self.footerViewContainer!)
} else if let footerViewContainer = self.footerViewContainer {
self.setFooterViewHidden(true, animated: true) {
footerViewContainer.removeFromSuperview()
}
self.footerViewContainer = nil
}
}
private func updateVisibleViews(index: Int, scrollToIndex need: Bool, animated: Bool = false, indexOnly: Bool = false) {
if need {
self.mainView.scroll(to: index, animated: animated)
}
if indexOnly {
self.showViewIfNeeded(at: index)
} else {
var visibleItems = [DKPhotoGalleryItem : Int]()
for visibleIndex in max(index - 1, 0) ... min(index + 1, self.dataSource.numberOfItems() - 1) {
let item = self.dataSource.item(for: visibleIndex)
visibleItems[item] = visibleIndex
}
let currentItem = self.dataSource.item(for: index)
for (visibleItem, visibleVC) in self.visibleVCs {
if visibleItems[visibleItem] == nil {
visibleVC.photoPreviewWillDisappear()
self.addToReuseQueueFromVisibleQueueIfNeeded(item: visibleItem)
} else if (visibleItem != currentItem) {
visibleVC.photoPreviewWillDisappear()
}
}
UIView.performWithoutAnimation {
for (_, index) in visibleItems {
self.showViewIfNeeded(at: index)
}
self.currentIndex = index
}
}
}
private func showViewIfNeeded(at index: Int) {
let item = self.dataSource.item(for: index)
if self.visibleVCs[item] == nil {
let vc = self.previewVC(for: item)
if vc.parent != self {
#if swift(>=4.2)
self.addChild(vc)
#else
self.addChildViewController(vc)
#endif
}
self.mainView.set(vc: vc, item: item, atIndex: index)
}
}
private func previewVC(for item: DKPhotoGalleryItem) -> DKPhotoBasePreviewVC {
if let vc = self.visibleVCs[item] {
return vc
}
let previewVCClass = DKPhotoBasePreviewVC.photoPreviewClass(with: item)
var previewVC: DKPhotoBasePreviewVC! = self.findPreviewVC(for: previewVCClass)
if previewVC == nil {
previewVC = previewVCClass.init()
} else {
previewVC.prepareForReuse()
}
self.prepareToShow?(previewVC)
previewVC.item = item
self.visibleVCs[item] = previewVC
return previewVC
}
private func findPreviewVC(for vcClass: DKPhotoBasePreviewVC.Type) -> DKPhotoBasePreviewVC? {
let classKey = ObjectIdentifier(vcClass)
return self.reuseableVCs[classKey]?.popLast()
}
private func addToReuseQueueFromVisibleQueueIfNeeded(item: DKPhotoGalleryItem) {
if let vc = self.visibleVCs[item] {
self.addToReuseQueue(vc: vc)
self.mainView.remove(vc: vc, item: item)
self.visibleVCs.removeValue(forKey: item)
}
}
private func addToReuseQueue(vc: DKPhotoBasePreviewVC) {
let classKey = ObjectIdentifier(type(of: vc))
var queue = self.reuseableVCs[classKey] ?? []
queue.append(vc)
self.reuseableVCs[classKey] = queue
}
private var isFilled = false
private func prefillingReuseQueue() {
guard !self.isFilled else { return }
self.isFilled = true
[DKPhotoImagePreviewVC(),
DKPhotoImagePreviewVC(),
DKPhotoPlayerPreviewVC(),
DKPhotoPlayerPreviewVC(),
self.currentVC.previewType == .photo ? DKPhotoPlayerPreviewVC() : DKPhotoImagePreviewVC()]
.forEach { (previewVC) in
previewVC.view.isHidden = true
self.mainView.addSubview(previewVC.view)
self.addToReuseQueue(vc: previewVC)
}
self.updateVisibleViews(index: self.currentIndex, scrollToIndex: false)
}
private func isScrollViewBouncing() -> Bool {
if self.mainView.contentOffset.x < -(self.mainView.contentInset.left) {
return true
} else if self.mainView.contentOffset.x > self.mainView.contentSize.width - self.mainView.bounds.width + self.mainView.contentInset.right {
return true
} else {
return false
}
}
private func resetScaleForVisibleVCs() {
if self.currentIndex > 0 {
self.visibleVCs[self.dataSource.item(for: self.currentIndex - 1)]?.resetScale()
} else if self.currentIndex < self.dataSource.numberOfItems() - 1 {
self.visibleVCs[self.dataSource.item(for: self.currentIndex + 1)]?.resetScale()
}
}
private func scrollToPrevious() {
guard self.currentIndex > 0 else { return }
self.updateVisibleViews(index: self.currentIndex - 1, scrollToIndex: true)
}
private func scrollToNext() {
guard self.currentIndex < self.dataSource.numberOfItems() - 1 else { return }
self.updateVisibleViews(index: self.currentIndex + 1, scrollToIndex: true)
}
private func scrollToCurrentPage() {
guard self.currentIndex >= 0 && self.currentIndex <= self.dataSource.numberOfItems() - 1 else { return }
self.updateVisibleViews(index: self.currentIndex, scrollToIndex: true)
}
// MARK: - Orientations & Status Bar
open override var shouldAutorotate: Bool {
return false
}
open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
// MARK: - UIScrollViewDelegate
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
guard !self.isScrollViewBouncing() else { return }
let halfPageWidth = self.mainView.pageWidth() * 0.5
var newIndex = self.currentIndex
// Check which way to move
let movedX = targetContentOffset.pointee.x - self.mainView.cellOrigin(for: self.currentIndex).x
if movedX < -halfPageWidth {
newIndex = self.currentIndex - 1 // Move left
} else if movedX > halfPageWidth {
newIndex = self.currentIndex + 1 // Move right
} else if abs(velocity.x) >= 0.25 {
newIndex = (velocity.x > 0) ? self.currentIndex + 1 : self.currentIndex - 1
}
newIndex = max(0, min(self.dataSource.numberOfItems() - 1, newIndex))
if newIndex != self.currentIndex {
self.updateVisibleViews(index: newIndex, scrollToIndex: false)
}
targetContentOffset.pointee.x = self.mainView.cellOrigin(for: self.currentIndex).x
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard !self.isScrollViewBouncing() else { return }
let position = self.mainView.positionFromContentOffset()
let offset = abs(CGFloat(self.currentIndex) - position)
if 1 - offset < 0.1 {
let index = Int(position.rounded())
if index != self.currentIndex {
self.updateVisibleViews(index: index, scrollToIndex: false)
}
}
}
}
| mit | 36e01b52398cdccc9a9ef40b892ccf44 | 37.479029 | 155 | 0.591762 | 5.266163 | false | false | false | false |
lstn-ltd/lstn-sdk-ios | Example/Lstn/ArticlesController.swift | 1 | 2309 | //
// ArticlesController.swift
// Lstn
//
// Created by Dan Halliday on 10/13/2016.
// Copyright (c) 2016 Dan Halliday. All rights reserved.
//
import UIKit
import Lstn
class ArticlesController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let store = ArticleStore()
var articles: [Article] = []
let publisher = ProcessInfo.processInfo.environment["LSTN_EXAMPLE_PUBLISHER"]!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
self.navigationItem.prompt = "Loading articles..."
self.store.fetch { articles in
DispatchQueue.main.async { self.loadingDidFinish(articles: articles) }
}
}
func loadingDidFinish(articles: [Article]?) {
guard let articles = articles else {
self.navigationItem.prompt = "Failed to fetch articles!"
return
}
self.articles = articles
self.navigationItem.prompt = nil
self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
}
func titleForRow(index: Int) -> String {
return self.articles[index].title
}
func detailForRow(index: Int) -> String {
return self.articles[index].summary
}
}
// MARK: - Table View Data Source
extension ArticlesController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.articles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath)
cell.textLabel?.text = self.titleForRow(index: indexPath.row)
cell.detailTextLabel?.text = self.detailForRow(index: indexPath.row)
return cell
}
}
// MARK: - Table View Delegate
extension ArticlesController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let article = self.articles[indexPath.row]
Lstn.shared.player.load(article: article.id, publisher: self.publisher) {
success in if success { Lstn.shared.player.play() }
}
}
}
| mit | ac62920cf9cfd4f6fb402e944b39d6be | 23.305263 | 100 | 0.663058 | 4.492218 | false | false | false | false |
Josscii/iOS-Demos | TableViewIssueDemo/TableViewDemo/estimatedRowHeight/ViewController.swift | 1 | 3323 | //
// ViewController.swift
// TableViewDemo
//
// Created by josscii on 2018/2/7.
// Copyright © 2018年 josscii. All rights reserved.
//
import UIKit
/*
测试 tableView 算高、加载 cell 和 estimatedRowHeight 的关系
*/
class ViewController: UIViewController {
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView = UITableView(frame: view.bounds)
tableView.delegate = self
tableView.dataSource = self
tableView.register(TableViewCell.self, forCellReuseIdentifier: "cell")
view.addSubview(tableView)
tableView.estimatedRowHeight = 44
tableView.rowHeight = 100
print(UITableViewAutomaticDimension)
/*
iOS 11
-1 用默认值 44 来计算高度和预加载 cell,默认
0 计算所有 cell 高度,只加载屏幕内 cell
>0 用 estimatedRowHeight 来计算高度和预加载 cell
< iOS 11
<= 0 计算所有 cell 高度,只加载屏幕内 cell,默认
>0 用 estimatedRowHeight 来计算高度和预加载 cell
*/
}
@IBAction func reload(_ sender: Any) {
/*
Call this method to reload all the data that is used to construct the table, including cells, section headers and footers, index arrays,
and so on. For efficiency, the table view redisplays only those rows that are visible. It adjusts offsets if the table shrinks as a result
of the reload. The table view’s delegate or data source calls this method when it wants the table view to completely reload its data. It
should not be called in the methods that insert or delete rows, especially within an animation block implemented with calls to
beginUpdates() and endUpdates().
*/
tableView.reloadData()
}
var addArr: [String] = []
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1000
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let cellAdd = cell.pointerString
if addArr.contains(cellAdd) {
cell.textLabel?.textColor = .red
} else {
cell.textLabel?.textColor = .black
addArr.append(cellAdd)
}
cell.textLabel?.text = "row \(indexPath.row) add \(cellAdd)"
print("cell row \(indexPath.row)")
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
print("height row \(indexPath.row)")
return 100
}
// func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// return 100;//CGFloat(arc4random_uniform(50) + 200)
// }
}
public extension NSObject {
public var pointerString: String {
return String(format: "%p", self)
}
}
| mit | c770c0cadf028d562a16ca419de92f65 | 30.039216 | 147 | 0.626342 | 4.863287 | false | false | false | false |
PJayRushton/TeacherTools | TeacherTools/StudentListViewController.swift | 1 | 17364 | //
// StudentListViewController.swift
// TeacherTools
//
// Created by Parker Rushton on 10/31/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import UIKit
import BetterSegmentedControl
class StudentListViewController: UIViewController, AutoStoryboardInitializable {
@IBOutlet var noGroupsView: UIView!
@IBOutlet var emptyGroupView: UIView!
@IBOutlet var emptyStateImages: [UIImageView]!
@IBOutlet var emptyStateLabels: [UILabel]!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var navBarButton: NavBarButton!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tableSortHeader: UIView!
@IBOutlet weak var newEntryView: UIView!
@IBOutlet weak var newStudentTextField: UITextField!
@IBOutlet weak var segmentedControl: BetterSegmentedControl!
var core = App.core
var group: Group?
var students = [Student]()
var absentStudents = [Student]()
fileprivate var plusBarButton = UIBarButtonItem()
fileprivate var pasteBarButton = UIBarButtonItem()
fileprivate var saveBarButton = UIBarButtonItem()
fileprivate var cancelBarButton = UIBarButtonItem()
fileprivate var doneBarButton = UIBarButtonItem()
fileprivate var editBarButton = UIBarButtonItem()
var currentSortType: SortType = App.core.state.currentUser?.lastFirst == true ? .last : .first {
didSet {
students = currentSortType.sort(students)
tableView.reloadData()
isAdding = false
}
}
var isAdding = false {
didSet {
toggleEntryView(hidden: !isAdding)
}
}
override func viewDidLoad() {
super.viewDidLoad()
newEntryView.isHidden = true
setUp()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
core.add(subscriber: self)
if !navBarButton.isPointingDown {
animateArrow(up: false)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
core.remove(subscriber: self)
}
@IBAction func newStudentTextFieldChanged(_ sender: UITextField) {
updateRightBarButton()
}
@IBAction func segmentedControlValueChanged(_ sender: BetterSegmentedControl) {
guard let selectedSortType = SortType(rawValue: Int(sender.index)) else { return }
currentSortType = selectedSortType
}
@IBAction func pasteViewTapped(_ sender: UITapGestureRecognizer) {
pasteButtonPressed()
}
@IBAction func addViewTapped(_ sender: UITapGestureRecognizer) {
startEditing()
}
@objc func editButtonPressed(_ sender: UIBarButtonItem) {
tableView.isEditing = !tableView.isEditing
tableView.reloadData()
navigationItem.leftBarButtonItem = tableView.isEditing ? doneBarButton : editBarButton
}
}
// MARK: - Subscriber
extension StudentListViewController: Subscriber {
func update(with state: AppState) {
newStudentTextField.text = ""
updateUI(with: state.theme)
tableView.tableHeaderView = state.selectedGroup == nil ? nil : tableSortHeader
tableView.backgroundView = nil
if state.groups.isEmpty {
tableView.backgroundView = noGroupsView
} else if let selectedGroup = state.selectedGroup, selectedGroup.studentIds.isEmpty {
tableView.backgroundView = emptyGroupView
}
navBarButton.update(with: state.selectedGroup)
guard let group = state.selectedGroup else { return }
self.group = group
absentStudents = state.absentStudents
students = currentSortType.sort(state.currentStudents)
let shouldShowEmptyView = core.state.groupsAreLoaded && students.isEmpty
tableView.backgroundView = shouldShowEmptyView ? emptyGroupView : nil
tableView.reloadData()
}
}
// MARK: - FilePrivate
extension StudentListViewController {
func setUp() {
plusBarButton = UIBarButtonItem(image: UIImage(named: "plus"), style: .plain, target: self, action: #selector(startEditing))
plusBarButton.setTitleTextAttributes([NSAttributedString.Key.font: core.state.theme.font(withSize: core.state.theme.plusButtonSize)], for: .normal)
pasteBarButton = UIBarButtonItem(image: UIImage(named: "lines"), style: .plain, target: self, action: #selector(pasteButtonPressed))
saveBarButton = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveNewStudent))
cancelBarButton = UIBarButtonItem(image: UIImage(named: "x"), style: .plain, target: self, action: #selector(saveNewStudent))
editBarButton = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editButtonPressed(_:)))
doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(editButtonPressed(_:)))
navigationItem.setLeftBarButton(editBarButton, animated: true)
navigationItem.setRightBarButton(plusBarButton, animated: true)
newEntryView.isHidden = true
let nib = UINib(nibName: String(describing: StudentTableViewCell.self), bundle: nil)
tableView.register(nib, forCellReuseIdentifier: StudentTableViewCell.reuseIdentifier)
tableView.rowHeight = Platform.isPad ? 60 : 45.0
resetAllCells()
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidHide), name: UIResponder.keyboardDidHideNotification, object: nil)
}
@objc func handleKeyboardDidShow(notification: NSNotification) {
var keyboardHeight: CGFloat = 216
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
keyboardHeight = keyboardSize.height
}
let insets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
tableView.contentInset = insets
}
@objc func handleKeyboardDidHide() {
tableView.contentInset = UIEdgeInsets.zero
}
func toggleEntryView(hidden: Bool) {
UIView.animate(withDuration: 0.5, animations: {
self.newEntryView.isHidden = hidden
self.newEntryView.alpha = hidden ? 0 : 1
DispatchQueue.main.async {
if hidden {
self.newStudentTextField.resignFirstResponder()
} else {
self.newStudentTextField.becomeFirstResponder()
}
}
}) { _ in
self.newStudentTextField.text = ""
self.updateRightBarButton()
}
}
@objc func pasteButtonPressed() {
let addStudentsVC = AddStudentsViewController.initializeFromStoryboard()
navigationController?.pushViewController(addStudentsVC, animated: true)
}
@objc func saveNewStudent() {
if newStudentTextField.text!.isEmpty { isAdding = false; return }
if let newStudentName = newStudentTextField.text, newStudentName.isEmpty == false {
guard newStudentName.isValidName else {
core.fire(event: ErrorEvent(error: nil, message: "Unaccepted name format"))
return
}
let newStudent = Student(name: newStudentName)
core.fire(command: CreateStudent(student: newStudent))
} else {
isAdding = false
}
}
func updateUI(with theme: Theme) {
for label in emptyStateLabels {
label.textColor = theme.textColor
label.font = theme.font(withSize: 18)
}
for image in emptyStateImages {
image.tintColor = theme.tintColor
}
backgroundImageView.image = theme.mainImage.image
let borderImage = theme.borderImage.image.stretchableImage(withLeftCapWidth: 0, topCapHeight: 0)
navigationController?.navigationBar.setBackgroundImage(borderImage, for: .default)
for barButton in [plusBarButton, pasteBarButton, saveBarButton, cancelBarButton, editBarButton] {
barButton.tintColor = theme.textColor
barButton.setTitleTextAttributes([NSAttributedString.Key.font: theme.font(withSize: 20)], for: .normal)
}
plusBarButton.setTitleTextAttributes([NSAttributedString.Key.font: theme.font(withSize: theme.plusButtonSize)], for: .normal)
navBarButton.tintColor = theme.textColor
navBarButton.update(with: theme)
updateRightBarButton()
updateSegmentedControl(theme: theme)
newStudentTextField.font = theme.font(withSize: 20)
newStudentTextField.textColor = theme.textColor
}
@objc func startEditing() {
isAdding = true
}
func resetAllCells() {
guard let visibleStudentCells = tableView.visibleCells as? [StudentTableViewCell] else { return }
for cell in visibleStudentCells {
cell.isEditing = false
}
}
}
// MARK: - TableView
extension StudentListViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return absentStudents.isEmpty ? 1 : 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? students.count : absentStudents.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: StudentTableViewCell.reuseIdentifier) as! StudentTableViewCell
let student = indexPath.section == 1 ? absentStudents[indexPath.row] : students[indexPath.row]
cell.update(with: student, theme: core.state.theme, isEditing: tableView.isEditing)
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.isEditing == false {
editButtonPressed(editBarButton)
guard let cell = tableView.cellForRow(at: indexPath) as? StudentTableViewCell else { return }
cell.textField.becomeFirstResponder()
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 1 ? "Absent" : nil
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete", handler: { action, indexPath in
let studentToX = indexPath.section == 0 ? self.students[indexPath.row] : self.absentStudents[indexPath.row]
self.core.fire(command: DeleteStudent(student: studentToX))
})
guard let currentUser = core.state.currentUser else { return [deleteAction] }
let absentAction = UITableViewRowAction(style: .normal, title: "Absent", handler: { action, indexPath in
if currentUser.isPro {
self.core.fire(event: MarkStudentAbsent(student: self.students[indexPath.row]))
} else {
self.goPro()
}
})
let presentAction = UITableViewRowAction(style: .normal, title: "Present", handler: { action, indexPath in
if currentUser.isPro {
self.core.fire(event: MarkStudentPresent(student: self.absentStudents[indexPath.row]))
} else {
self.goPro()
}
})
switch indexPath.section {
case 0:
return [deleteAction, absentAction]
case 1:
return [deleteAction, presentAction]
default:
return [deleteAction]
}
}
func goPro() {
let proVC = ProViewController.initializeFromStoryboard().embededInNavigationController
proVC.modalPresentationStyle = .popover
proVC.popoverPresentationController?.sourceView = navBarButton
proVC.popoverPresentationController?.sourceRect = navBarButton.bounds
present(proVC, animated: true, completion: nil)
}
}
// MARK: - TextField Delegate
extension StudentListViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
updateRightBarButton()
}
func textFieldDidEndEditing(_ textField: UITextField) {
updateRightBarButton()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
saveNewStudent()
return true
}
func updateRightBarButton() {
if isAdding {
if let name = newStudentTextField.text, name.isEmpty == false {
navigationItem.setRightBarButton(saveBarButton, animated: false)
} else {
navigationItem.setRightBarButton(cancelBarButton, animated: false)
}
} else {
navigationItem.setRightBarButtonItems([plusBarButton, pasteBarButton], animated: true)
}
}
}
// MARK: - SegmentedControl
extension StudentListViewController {
enum SortType: Int {
case first
case last
case random
var buttonTitle: String {
switch self {
case .first:
return "First"
case .last:
return "Last"
case .random:
return "Random"
}
}
var sort: (([Student]) -> [Student]) {
switch self {
case .first:
return { students in
return students.sorted(by: { $0.firstName < $1.firstName })
}
case .last:
return { students in
return students.sorted(by: { ($0.lastName ?? $0.firstName) < ($1.lastName ?? $1.firstName) })
}
case .random:
return { students in
return students.shuffled()
}
}
}
static let allValues = [SortType.first, .last, .random]
}
func updateSegmentedControl(theme: Theme) {
let titles = SortType.allValues.map { $0.buttonTitle }
segmentedControl?.segments = LabelSegment.segments(withTitles: titles,
normalBackgroundColor: .clear,
normalFont: theme.font(withSize: 16),
normalTextColor: theme.textColor,
selectedBackgroundColor: .clear,
selectedFont: theme.font(withSize: 18),
selectedTextColor: .white)
segmentedControl?.backgroundColor = .clear
segmentedControl?.indicatorViewBackgroundColor = theme.tintColor
segmentedControl?.cornerRadius = 5
}
}
extension StudentListViewController: StudentCellDelegate {
func saveStudentName(_ name: FullName, forCell cell: StudentTableViewCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
var updatedStudent = students[indexPath.row]
updatedStudent.firstName = name.first
updatedStudent.lastName = name.last
core.fire(command: CreateStudent(student: updatedStudent))
}
}
extension StudentListViewController: SegueHandling {
enum SegueIdentifier: String {
case showGroupSwitcher
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segueIdentifier(for: segue) {
case .showGroupSwitcher:
guard let groupSwitcherNav = segue.destination as? UINavigationController, let groupSwitcher = groupSwitcherNav.viewControllers.first as? GroupListViewController else { return }
groupSwitcher.proCompletion = {
let proViewController = ProViewController.initializeFromStoryboard().embededInNavigationController
self.present(proViewController, animated: true, completion: nil)
}
groupSwitcher.arrowCompletion = { up in
self.animateArrow(up: up)
}
}
}
fileprivate func animateArrow(up: Bool = true) {
UIView.animate(withDuration: 0.25) {
let transform = up ? CGAffineTransform(rotationAngle: -CGFloat.pi) : CGAffineTransform(rotationAngle: CGFloat.pi * 2)
self.navBarButton.icon.transform = transform
}
}
}
extension StudentListViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
}
| mit | 4503d57f71c530ee3ac2d65056730327 | 36.745652 | 189 | 0.638772 | 5.367233 | false | false | false | false |
mobgeek/swift | Swift em 4 Semanas/Desafios/Desafios Semana 1.playground/Contents.swift | 2 | 2172 | // Playground - noun: a place where people can play
import UIKit
/*
__ __
__ \ / __
/ \ | / \
\|/ Mobgeek
_,.---v---._
/\__/\ / \ Curso Swift em 4 semanas
\_ _/ / \
\ \_| @ __|
\ \_
\ ,__/ /
~~~`~~~~~~~~~~~~~~/~~~~
*/
/*:
# **Exercícios práticos - Semana 1:**
1 - Constantes e variáveis devem ser declaradas antes de ser usadas. Para ter certeza que tipo de valor pode ser armazenado, você pode especificar o tipo escrevendo ": tipoEscolhido" após a variável.
Veja o seguinte exemplo:
*/
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
/*:
**Desafio 1:** Crie uma constante com um tipo explícito de Float e um valor de 6.
Resposta:
*/
/*:
---
2 - Falhando no Playground.
**Desafio 2:** Tente remover a conversão para String da última linha de código. Qual é o erro que é gerado? Comente a sua resposta.
*/
let label = "The width is "
let width = 74
let widthLabel = label + String(width)
//:Resposta:
/*:
---
3 - Há uma maneira bem mais simples de incluir valores em strings: escrevendo o valor em parênteses, e escrevendo uma barra invertida ‘ \ ‘ antes do parêntese.
*/
let nome = "André"
var saldo = 0.47
var deposito = 50
/*:
**Desafio** 3: Use \( ) para comunicar o saldo da conta bancária do André após o depósito de R$50 com a função `println()`. Você precisará incluir um cálculo em uma String e, também incluir o nome do cliente junto com a saudação Olá.
Resposta:
*/
/*:
---
4 - Para essa tarefa você irá precisar dos conhecimentos sobre Switch e do operador Range.
**Desafio 4:** Classifique o tamanho de diversos Strings imprimindo a sua categoria segundo essa regra sugerida:
Clarificando, imprima na tela:
* "Pequenos" para frases (Strings) com até dez caracteres;
* "Médios" para frases que tenham entre 11 e 25 caracteres;
* "Grandes" para frases que possuem de 26 a 50 caracteres;
* "Grandes pra caramba!"para as que tenham mais de 50 caracteres.
Resposta:
*/
| mit | c0d9594548de347dcbbb45c84fdbb31f | 21.239583 | 233 | 0.620141 | 2.961165 | false | false | false | false |
polymr/polymyr-api | Sources/App/Stripe/Models/Account/Account.swift | 1 | 10902 | //
// Account.swift
// Stripe
//
// Created by Hakon Hanesand on 1/2/17.
//
//
import Node
import Vapor
import Foundation
public final class DeclineChargeRules: NodeConvertible {
public let avs_failure: Bool
public let cvc_failure: Bool
public required init(node: Node) throws {
avs_failure = try node.extract("avs_failure")
cvc_failure = try node.extract("cvc_failure")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"avs_failure" : .bool(avs_failure),
"cvc_failure" : .bool(cvc_failure)
] as [String : Node])
}
}
public final class Document: NodeConvertible {
public let id: String
public let created: Date
public let size: Int
public required init(node: Node) throws {
id = try node.extract("id")
created = try node.extract("created")
size = try node.extract("size")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"id" : .string(id),
"created" : try created.makeNode(in: context),
"size" : .number(.int(size))
] as [String : Node])
}
}
public final class DateOfBirth: NodeConvertible {
public let day: Int?
public let month: Int?
public let year: Int?
public required init(node: Node) throws {
day = try? node.extract("day")
month = try? node.extract("month")
year = try? node.extract("year")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node.object([:]).add(objects: [
"day" : day,
"month" : month,
"year" : year
])
}
}
public final class TermsOfServiceAgreement: NodeConvertible {
public let date: Date?
public let ip: String?
public let user_agent: String?
public required init(node: Node) throws {
date = try? node.extract("date")
ip = try? node.extract("ip")
user_agent = try? node.extract("user_agent")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node.object([:]).add(objects: [
"date" : date,
"ip" : ip,
"user_agent" : user_agent
])
}
}
public final class TransferSchedule: NodeConvertible {
public let delay_days: Int
public let interval: Interval
public required init(node: Node) throws {
delay_days = try node.extract("delay_days")
interval = try node.extract("interval")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"delay_days" : .number(.int(delay_days)),
"interval" : try interval.makeNode(in: context)
] as [String : Node])
}
}
public final class Keys: NodeConvertible {
public let secret: String
public let publishable: String
public required init(node: Node) throws {
secret = try node.extract("secret")
publishable = try node.extract("publishable")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"secret" : .string(secret),
"publishable" : .string(publishable)
] as [String : Node])
}
}
extension Sequence where Iterator.Element == (key: String, value: Node) {
func group(with separator: String = ".") throws -> Node {
guard let dictionary = self as? [String : Node] else {
throw Abort.custom(status: .internalServerError, message: "Unable to cast to [String: Node].")
}
var result = Node.object([:])
dictionary.forEach { result[$0.components(separatedBy: separator)] = $1 }
return result
}
}
public final class StripeAccount: NodeConvertible {
static let type = "account"
public let id: String
public let business_logo: String?
public let business_name: String?
public let business_url: String?
public let charges_enabled: Bool
public let country: CountryType
public let debit_negative_balances: Bool
public let decline_charge_on: DeclineChargeRules
public let default_currency: Currency
public let details_submitted: Bool
public let display_name: String?
public let email: String
public let external_accounts: [ExternalAccount]
public let legal_entity: LegalEntity
public let managed: Bool
public let product_description: String?
public let statement_descriptor: String?
public let support_email: String?
public let support_phone: String?
public let timezone: String
public let tos_acceptance: TermsOfServiceAgreement
public let transfer_schedule: TransferSchedule
public let transfer_statement_descriptor: String?
public let transfers_enabled: Bool
public let verification: IdentityVerification
public let keys: Keys?
public let metadata: Node
public required init(node: Node) throws {
guard try node.extract("object") == StripeAccount.type else {
throw NodeError.unableToConvert(input: node, expectation: StripeAccount.type, path: ["object"])
}
id = try node.extract("id")
business_logo = try? node.extract("business_logo")
business_name = try? node.extract("business_name")
business_url = try? node.extract("business_url")
charges_enabled = try node.extract("charges_enabled")
country = try node.extract("country")
debit_negative_balances = try node.extract("debit_negative_balances")
decline_charge_on = try node.extract("decline_charge_on")
default_currency = try node.extract("default_currency")
details_submitted = try node.extract("details_submitted")
display_name = try? node.extract("display_name")
email = try node.extract("email")
external_accounts = try node.extractList("external_accounts")
legal_entity = try node.extract("legal_entity")
managed = try node.extract("managed")
product_description = try? node.extract("product_description")
statement_descriptor = try? node.extract("statement_descriptor")
support_email = try? node.extract("support_email")
support_phone = try? node.extract("support_phone")
timezone = try node.extract("timezone")
tos_acceptance = try node.extract("tos_acceptance")
transfer_schedule = try node.extract("transfer_schedule")
transfer_statement_descriptor = try? node.extract("transfer_statement_descriptor")
transfers_enabled = try node.extract("transfers_enabled")
verification = try node.extract("verification")
keys = try? node.extract("keys")
metadata = try node.extract("metadata")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"id" : .string(id),
"charges_enabled" : .bool(charges_enabled),
"country" : try country.makeNode(in: context),
"debit_negative_balances" : .bool(debit_negative_balances),
"decline_charge_on" : try decline_charge_on.makeNode(in: context),
"default_currency" : try default_currency.makeNode(in: context),
"details_submitted" : .bool(details_submitted),
"email" : .string(email),
"external_accounts" : try .array(external_accounts.map { try $0.makeNode(in: context) }),
"legal_entity" : try legal_entity.makeNode(in: context),
"managed" : .bool(managed),
"timezone" : .string(timezone),
"tos_acceptance" : try tos_acceptance.makeNode(in: context),
"transfer_schedule" : try transfer_schedule.makeNode(in: context),
"transfers_enabled" : .bool(transfers_enabled),
"verification" : try verification.makeNode(in: context),
"metadata" : metadata
] as [String : Node]).add(objects: [
"business_logo" : business_logo,
"business_name" : business_name,
"business_url" : business_url,
"product_description" : product_description,
"statement_descriptor" : statement_descriptor,
"support_email" : support_email,
"support_phone" : support_phone,
"transfer_statement_descriptor" : transfer_statement_descriptor,
"display_name" : display_name,
"keys" : keys
])
}
public func filteredNeededFieldsWithCombinedDateOfBirth(filtering prefix: String = "tos_acceptance") -> [String] {
var fieldsNeeded = verification.fields_needed.filter { !$0.hasPrefix(prefix) }
if fieldsNeeded.contains(where: { $0.contains("dob") }) {
let keysToRemove = ["legal_entity.dob.day", "legal_entity.dob.month", "legal_entity.dob.year"]
fieldsNeeded = fieldsNeeded.filter { !keysToRemove.contains($0) }
fieldsNeeded.append("legal_entity.dob")
}
if let index = fieldsNeeded.index(of: "external_account") {
fieldsNeeded.remove(at: index)
let accountFields = ["external_account.routing_number", "external_account.account_number", "external_account.country", "external_account.currency"]
fieldsNeeded.append(contentsOf: accountFields)
}
return fieldsNeeded
}
public func descriptionsForNeededFields() throws -> Node {
var descriptions: [Node] = []
try filteredNeededFieldsWithCombinedDateOfBirth().forEach {
descriptions.append(contentsOf: try description(for: $0))
}
return .array(descriptions)
}
private func description(for field: String) throws -> [Node] {
switch field {
case let field where field.hasPrefix("external_account"):
return [.object(ExternalAccount.descriptionsForNeededFields(in: country, for: field))]
case let field where field.hasPrefix("legal_entity"):
return [.object(LegalEntity.descriptionForNeededFields(in: country, for: field))]
case "tos_acceptance.date": fallthrough
case "tos_acceptance.ip": fallthrough
default:
return [.string(field)]
}
}
var requiresIdentityVerification: Bool {
let triggers = ["legal_entity.verification.document",
"legal_entity.additional_owners.0.verification.document",
"legal_entity.additional_owners.1.verification.document",
"legal_entity.additional_owners.2.verification.document",
"legal_entity.additional_owners.3.verification.document"]
return triggers.map { verification.fields_needed.contains($0) }.reduce(false) { $0 || $1 }
}
}
| mit | 12c659caff22f5f585cfead9fab55c7e | 35.831081 | 159 | 0.62117 | 4.310795 | false | false | false | false |
goyuanfang/SXSwiftWeibo | 103 - swiftWeibo/103 - swiftWeibo/Classes/UI/Main/SXMainTabBar.swift | 1 | 2219 | //
// SXMainTabBar.swift
// 103 - swiftWeibo
//
// Created by 董 尚先 on 15/3/5.
// Copyright (c) 2015年 shangxianDante. All rights reserved.
//
import UIKit
class SXMainTabBar: UITabBar {
var composedButtonClicked:(()->())?
override func awakeFromNib() {
self.addSubview(composeBtn!)
self.backgroundColor = UIColor(patternImage: UIImage(named: "tabbar_background")!)
}
override func layoutSubviews() {
super.layoutSubviews()
/// 设置按钮位置
setButtonFrame()
}
func setButtonFrame(){
let buttonCount = 5
let w = self.bounds.width/CGFloat(buttonCount)
let h = self.bounds.height
var index = 0
for view in self.subviews as![UIView]{
if view is UIControl && !(view is UIButton){
let r = CGRectMake(CGFloat(index) * w, 0, w, h)
view.frame = r
/// 如果是后两个 就往右边靠
index++
if index == 2 {
index++
}
// println(index)
}
}
composeBtn!.frame = CGRectMake(0, 0, w, h)
composeBtn!.center = CGPointMake(self.center.x, h * 0.5)
}
/// 创建撰写微博按钮
lazy var composeBtn: UIButton? = {
let btn = UIButton()
btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
// 添加按钮的监听方法
btn.addTarget(self, action: "clickCompose", forControlEvents: .TouchUpInside)
return btn
}()
func clickCompose(){
println("发微博")
if composedButtonClicked != nil{
composedButtonClicked!()
}
}
}
| mit | c7fb54efae20f04e7ffa4988e08e5036 | 27.118421 | 121 | 0.55124 | 4.635575 | false | false | false | false |
StefanKruger/WiLibrary | Pod/Classes/ImageLoader/Core/ImageProcessor.swift | 1 | 4110 | // The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import Foundation
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
// MARK: - ImageProcessing
public protocol ImageProcessing {
func processImage(image: Image) -> Image?
func isEquivalentToProcessor(other: ImageProcessing) -> Bool
}
public extension ImageProcessing {
public func isEquivalentToProcessor(other: ImageProcessing) -> Bool {
return other is Self
}
}
public extension ImageProcessing where Self: Equatable {
public func isEquivalentToProcessor(other: ImageProcessing) -> Bool {
return (other as? Self) == self
}
}
public func equivalentProcessors(lhs: ImageProcessing?, rhs: ImageProcessing?) -> Bool {
switch (lhs, rhs) {
case (.Some(let lhs), .Some(let rhs)): return lhs.isEquivalentToProcessor(rhs)
case (.None, .None): return true
default: return false
}
}
// MARK: - ImageProcessorComposition
public class ImageProcessorComposition: ImageProcessing, Equatable {
public let processors: [ImageProcessing]
public init(processors: [ImageProcessing]) {
self.processors = processors
}
public func processImage(input: Image) -> Image? {
return processors.reduce(input) { image, processor in
return image != nil ? processor.processImage(image!) : nil
}
}
}
public func ==(lhs: ImageProcessorComposition, rhs: ImageProcessorComposition) -> Bool {
guard lhs.processors.count == rhs.processors.count else {
return false
}
for (lhs, rhs) in zip(lhs.processors, rhs.processors) {
if !lhs.isEquivalentToProcessor(rhs) {
return false
}
}
return true
}
#if !os(OSX)
// MARK: - ImageDecompressor
public class ImageDecompressor: ImageProcessing, Equatable {
public let targetSize: CGSize
public let contentMode: ImageContentMode
public init(targetSize: CGSize = ImageMaximumSize, contentMode: ImageContentMode = .AspectFill) {
self.targetSize = targetSize
self.contentMode = contentMode
}
public func processImage(image: Image) -> Image? {
return decompressImage(image, targetSize: self.targetSize, contentMode: self.contentMode)
}
}
public func ==(lhs: ImageDecompressor, rhs: ImageDecompressor) -> Bool {
return lhs.targetSize == rhs.targetSize && lhs.contentMode == rhs.contentMode
}
// MARK: - Misc
private func decompressImage(image: UIImage, targetSize: CGSize, contentMode: ImageContentMode) -> UIImage {
let bitmapSize = CGSize(width: CGImageGetWidth(image.CGImage), height: CGImageGetHeight(image.CGImage))
let scaleWidth = targetSize.width / bitmapSize.width
let scaleHeight = targetSize.height / bitmapSize.height
let scale = contentMode == .AspectFill ? max(scaleWidth, scaleHeight) : min(scaleWidth, scaleHeight)
return decompressImage(image, scale: Double(scale))
}
private func decompressImage(image: UIImage, scale: Double) -> UIImage {
let imageRef = image.CGImage
var imageSize = CGSize(width: CGImageGetWidth(imageRef), height: CGImageGetHeight(imageRef))
if scale < 1.0 {
imageSize = CGSize(width: Double(imageSize.width) * scale, height: Double(imageSize.height) * scale)
}
// See Quartz 2D Programming Guide and https://github.com/kean/Nuke/issues/35 for more info
guard let contextRef = CGBitmapContextCreate(nil, Int(imageSize.width), Int(imageSize.height), 8, 0, CGColorSpaceCreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast.rawValue) else {
return image
}
CGContextDrawImage(contextRef, CGRect(origin: CGPointZero, size: imageSize), imageRef)
guard let decompressedImageRef = CGBitmapContextCreateImage(contextRef) else {
return image
}
return UIImage(CGImage: decompressedImageRef, scale: image.scale, orientation: image.imageOrientation)
}
#endif
| mit | 0dd5dd865df7865364154919a9e98680 | 34.431034 | 191 | 0.676886 | 4.740484 | false | false | false | false |
HassanEskandari/Eureka | Source/Rows/Common/FieldRow.swift | 3 | 18734 | // FieldRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public protocol InputTypeInitiable {
init?(string stringValue: String)
}
public protocol FieldRowConformance : FormatterConformance {
var titlePercentage : CGFloat? { get set }
var placeholder : String? { get set }
var placeholderColor : UIColor? { get set }
}
extension Int: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue, radix: 10)
}
}
extension Float: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
extension String: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
extension URL: InputTypeInitiable {}
extension Double: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
open class FormatteableRow<Cell: CellType>: Row<Cell>, FormatterConformance where Cell: BaseCell, Cell: TextInputCell {
/// A formatter to be used to format the user's input
open var formatter: Formatter?
/// If the formatter should be used while the user is editing the text.
open var useFormatterDuringInput = false
open var useFormatterOnDidBeginEditing: Bool?
public required init(tag: String?) {
super.init(tag: tag)
displayValueFor = { [unowned self] value in
guard let v = value else { return nil }
guard let formatter = self.formatter else { return String(describing: v) }
if (self.cell.textInput as? UIView)?.isFirstResponder == true {
return self.useFormatterDuringInput ? formatter.editingString(for: v) : String(describing: v)
}
return formatter.string(for: v)
}
}
}
open class FieldRow<Cell: CellType>: FormatteableRow<Cell>, FieldRowConformance, KeyboardReturnHandler where Cell: BaseCell, Cell: TextFieldCell {
/// Configuration for the keyboardReturnType of this row
open var keyboardReturnType: KeyboardReturnTypeConfiguration?
/// The percentage of the cell that should be occupied by the textField
@available (*, deprecated, message: "Use titleLabelPercentage instead")
open var textFieldPercentage : CGFloat? {
get {
return titlePercentage.map { 1 - $0 }
}
set {
titlePercentage = newValue.map { 1 - $0 }
}
}
/// The percentage of the cell that should be occupied by the title (i.e. the titleLabel and optional imageView combined)
open var titlePercentage: CGFloat?
/// The placeholder for the textField
open var placeholder: String?
/// The textColor for the textField's placeholder
open var placeholderColor: UIColor?
public required init(tag: String?) {
super.init(tag: tag)
}
}
/**
* Protocol for cells that contain a UITextField
*/
public protocol TextInputCell {
var textInput: UITextInput { get }
}
public protocol TextFieldCell: TextInputCell {
var textField: UITextField! { get }
}
extension TextFieldCell {
public var textInput: UITextInput {
return textField
}
}
open class _FieldCell<T> : Cell<T>, UITextFieldDelegate, TextFieldCell where T: Equatable, T: InputTypeInitiable {
@IBOutlet public weak var textField: UITextField!
@IBOutlet public weak var titleLabel: UILabel?
fileprivate var observingTitleText = false
private var awakeFromNibCalled = false
open var dynamicConstraints = [NSLayoutConstraint]()
private var calculatedTitlePercentage: CGFloat = 0.7
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
let textField = UITextField()
self.textField = textField
textField.translatesAutoresizingMaskIntoConstraints = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel = self.textLabel
titleLabel?.translatesAutoresizingMaskIntoConstraints = false
titleLabel?.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal)
titleLabel?.setContentCompressionResistancePriority(UILayoutPriority(1000), for: .horizontal)
contentView.addSubview(titleLabel!)
contentView.addSubview(textField)
NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationWillResignActive, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard me.observingTitleText else { return }
me.titleLabel?.removeObserver(me, forKeyPath: "text")
me.observingTitleText = false
}
NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard !me.observingTitleText else { return }
me.titleLabel?.addObserver(me, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
me.observingTitleText = true
}
NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil) { [weak self] _ in
self?.titleLabel = self?.textLabel
self?.setNeedsUpdateConstraints()
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
awakeFromNibCalled = true
}
deinit {
textField?.delegate = nil
textField?.removeTarget(self, action: nil, for: .allEvents)
guard !awakeFromNibCalled else { return }
if observingTitleText {
titleLabel?.removeObserver(self, forKeyPath: "text")
}
imageView?.removeObserver(self, forKeyPath: "image")
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil)
}
open override func setup() {
super.setup()
selectionStyle = .none
if !awakeFromNibCalled {
titleLabel?.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
observingTitleText = true
imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
}
textField.addTarget(self, action: #selector(_FieldCell.textFieldDidChange(_:)), for: .editingChanged)
}
open override func update() {
super.update()
detailTextLabel?.text = nil
if !awakeFromNibCalled {
if let title = row.title {
textField.textAlignment = title.isEmpty ? .left : .right
textField.clearButtonMode = title.isEmpty ? .whileEditing : .never
} else {
textField.textAlignment = .left
textField.clearButtonMode = .whileEditing
}
}
textField.delegate = self
textField.text = row.displayValueFor?(row.value)
textField.isEnabled = !row.isDisabled
textField.textColor = row.isDisabled ? .gray : .black
textField.font = .preferredFont(forTextStyle: .body)
if let placeholder = (row as? FieldRowConformance)?.placeholder {
if let color = (row as? FieldRowConformance)?.placeholderColor {
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedStringKey.foregroundColor: color])
} else {
textField.placeholder = (row as? FieldRowConformance)?.placeholder
}
}
if row.isHighlighted {
textLabel?.textColor = tintColor
}
}
open override func cellCanBecomeFirstResponder() -> Bool {
return !row.isDisabled && textField?.canBecomeFirstResponder == true
}
open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool {
return textField?.becomeFirstResponder() ?? false
}
open override func cellResignFirstResponder() -> Bool {
return textField?.resignFirstResponder() ?? true
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let obj = object as AnyObject?
if let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey],
((obj === titleLabel && keyPathValue == "text") || (obj === imageView && keyPathValue == "image")) &&
(changeType as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
// MARK: Helpers
open func customConstraints() {
guard !awakeFromNibCalled else { return }
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
var views: [String: AnyObject] = ["textField": textField]
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[textField]-11-|", options: .alignAllLastBaseline, metrics: nil, views: views)
if let label = titleLabel, let text = label.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[titleLabel]-11-|", options: .alignAllLastBaseline, metrics: nil, views: ["titleLabel": label])
dynamicConstraints.append(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: textField, attribute: .centerY, multiplier: 1, constant: 0))
}
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["label"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[label]-[textField]-|", options: NSLayoutFormatOptions(), metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .width,
relatedBy: (row as? FieldRowConformance)?.titlePercentage != nil ? .equal : .lessThanOrEqual,
toItem: contentView,
attribute: .width,
multiplier: calculatedTitlePercentage,
constant: 0.0))
}
else{
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views)
}
}
else{
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["label"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]-[textField]-|", options: [], metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .width,
relatedBy: (row as? FieldRowConformance)?.titlePercentage != nil ? .equal : .lessThanOrEqual,
toItem: contentView,
attribute: .width,
multiplier: calculatedTitlePercentage,
constant: 0.0))
}
else{
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: .alignAllLeft, metrics: nil, views: views)
}
}
contentView.addConstraints(dynamicConstraints)
}
open override func updateConstraints() {
customConstraints()
super.updateConstraints()
}
@objc open func textFieldDidChange(_ textField: UITextField) {
guard let textValue = textField.text else {
row.value = nil
return
}
guard let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
return
}
if fieldRow.useFormatterDuringInput {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
guard var selStartPos = textField.selectedTextRange?.start else { return }
let oldVal = textField.text
textField.text = row.displayValueFor?(row.value)
selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(forPosition: selStartPos, inTextInput: textField, oldValue: oldVal, newValue: textField.text) ?? selStartPos
textField.selectedTextRange = textField.textRange(from: selStartPos, to: selStartPos)
return
}
} else {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
} else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
}
}
}
// MARK: Helpers
private func displayValue(useFormatter: Bool) -> String? {
guard let v = row.value else { return nil }
if let formatter = (row as? FormatterConformance)?.formatter, useFormatter {
return textField?.isFirstResponder == true ? formatter.editingString(for: v) : formatter.string(for: v)
}
return String(describing: v)
}
// MARK: TextFieldDelegate
open func textFieldDidBeginEditing(_ textField: UITextField) {
formViewController()?.beginEditing(of: self)
formViewController()?.textInputDidBeginEditing(textField, cell: self)
if let fieldRowConformance = row as? FormatterConformance, let _ = fieldRowConformance.formatter, fieldRowConformance.useFormatterOnDidBeginEditing ?? fieldRowConformance.useFormatterDuringInput {
textField.text = displayValue(useFormatter: true)
} else {
textField.text = displayValue(useFormatter: false)
}
}
open func textFieldDidEndEditing(_ textField: UITextField) {
formViewController()?.endEditing(of: self)
formViewController()?.textInputDidEndEditing(textField, cell: self)
textFieldDidChange(textField)
textField.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil)
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldReturn(textField, cell: self) ?? true
}
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return formViewController()?.textInput(textField, shouldChangeCharactersInRange:range, replacementString:string, cell: self) ?? true
}
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}
open func textFieldShouldClear(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldClear(textField, cell: self) ?? true
}
open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldEndEditing(textField, cell: self) ?? true
}
open override func layoutSubviews() {
super.layoutSubviews()
guard let row = (row as? FieldRowConformance) else { return }
guard let titlePercentage = row.titlePercentage else { return }
var targetTitleWidth = bounds.size.width * titlePercentage
if let imageView = imageView, let _ = imageView.image, let titleLabel = titleLabel {
var extraWidthToSubtract = titleLabel.frame.minX - imageView.frame.minX // Left-to-right interface layout
if #available(iOS 9.0, *) {
if UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) == .rightToLeft {
extraWidthToSubtract = imageView.frame.maxX - titleLabel.frame.maxX
}
}
targetTitleWidth -= extraWidthToSubtract
}
let targetTitlePercentage = targetTitleWidth / contentView.bounds.size.width
if calculatedTitlePercentage != targetTitlePercentage {
calculatedTitlePercentage = targetTitlePercentage
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
}
| mit | 8f863f7397abbc5b9a222720d88770c0 | 43.183962 | 204 | 0.664087 | 5.277183 | false | false | false | false |
davidahouse/chute | chute/Output/ChuteOutput.swift | 1 | 1591 | //
// ChuteOutput.swift
// chute
//
// Created by David House on 10/20/17.
// Copyright © 2017 David House. All rights reserved.
//
import Foundation
protocol HTMLRenderable {
func renderSummary() -> String
func renderDetail() -> String
}
protocol ChuteOutputRenderable {
func render(dataCapture: DataCapture) -> String
}
protocol ChuteOutputDifferenceRenderable {
func render(difference: DataCaptureDifference) -> String
}
class ChuteOutput {
let outputFolder: ChuteOutputFolder
init(into outputFolder: ChuteOutputFolder) {
self.outputFolder = outputFolder
}
func createReports(with dataCapture: DataCapture, and difference: DataCaptureDifference?) {
let mainReport = CaptureReport()
print("Creating chute.html")
outputFolder.saveOutputFile(fileName: "chute.html", contents: mainReport.render(dataCapture: dataCapture))
let jsonReport = CaptureJSONReport()
print("Creating chute.json")
outputFolder.saveOutputFile(fileName: "chute.json", contents: jsonReport.render(dataCapture: dataCapture))
let cqReport = CaptureCQReport()
print("Creating cq.json")
outputFolder.saveOutputFile(fileName: "cq.json", contents: cqReport.render(dataCapture: dataCapture))
if let difference = difference {
let differenceReport = DifferenceReport()
print("Creating chute_difference.html")
outputFolder.saveOutputFile(fileName: "chute_difference.html", contents: differenceReport.render(difference: difference))
}
}
}
| mit | daeac0baaf116bc9d949d584e71e0628 | 29.576923 | 133 | 0.701887 | 4.392265 | false | false | false | false |
Yummypets/YPImagePicker | Source/Helpers/YPLoadingView.swift | 1 | 1300 | //
// YPLoadingView.swift
// YPImagePicker
//
// Created by Sacha DSO on 24/04/2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
import Stevia
class YPLoadingView: UIView {
let spinner = UIActivityIndicatorView(style: .whiteLarge)
let processingLabel = UILabel()
convenience init() {
self.init(frame: .zero)
// View Hiearachy
let stack = UIStackView(arrangedSubviews: [spinner, processingLabel])
stack.axis = .vertical
stack.spacing = 20
subviews(
stack
)
// Layout
stack.centerInContainer()
processingLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 751), for: .horizontal)
// Style
backgroundColor = UIColor.ypLabel.withAlphaComponent(0.8)
processingLabel.textColor = .ypSystemBackground
spinner.hidesWhenStopped = true
// Content
processingLabel.text = YPConfig.wordings.processing
spinner.startAnimating()
}
func toggleLoading() {
if !spinner.isAnimating {
spinner.startAnimating()
alpha = 1
} else {
spinner.stopAnimating()
alpha = 0
}
}
}
| mit | 73f935e93bbd87653312df28a2069c40 | 23.980769 | 114 | 0.596613 | 5.034884 | false | false | false | false |
nguyenantinhbk77/practice-swift | Games/SwiftTetris/SwiftTetris/GameViewController.swift | 3 | 5759 | import UIKit
import SpriteKit
class GameViewController: UIViewController, SwiftrisDelegate, UIGestureRecognizerDelegate {
var scene: GameScene!
var swiftris:SwifTris!
@IBOutlet weak var scoreLbl: UILabel!
@IBOutlet weak var levelLbl: UILabel!
/// It keeps track of the last point on the screen at which a shape movement occurred or where a pan begins.
var panPointReference:CGPoint?
override func viewDidLoad() {
super.viewDidLoad()
// Configure the view.
let skView = view as SKView
skView.multipleTouchEnabled = false
// Create and configure the scene.
self.scene = GameScene(size: skView.bounds.size)
self.scene.scaleMode = .AspectFill
self.scene.tick = didTick
swiftris = SwifTris()
swiftris.delegate = self
swiftris.beginGame()
// Present the scene.
skView.presentScene(scene)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
/// It lowers the falling shape by one row and then asks GameScene to redraw the shape at its new location.
func didTick() {
swiftris.letShapeFall()
}
func nextShape() {
let newShapes = swiftris.newShape()
if let fallingShape = newShapes.fallingShape {
self.scene.addPreviewShapeToScene(newShapes.nextShape!) {}
self.scene.movePreviewShape(fallingShape) {
self.view.userInteractionEnabled = true
self.scene.startTicking()
}
}
}
@IBAction func didPan(sender: UIPanGestureRecognizer) {
let currentPoint = sender.translationInView(self.view)
if let originalPoint = panPointReference {
if abs(currentPoint.x - originalPoint.x) > (BlockSize * 0.9) {
if sender.velocityInView(self.view).x > CGFloat(0) {
swiftris.moveShapeRight()
panPointReference = currentPoint
} else {
swiftris.moveShapeLeft()
panPointReference = currentPoint
}
}
} else if sender.state == .Began {
panPointReference = currentPoint
}
}
@IBAction func didTap(sender: UITapGestureRecognizer) {
swiftris.rotateShape()
}
@IBAction func didSwipe(sender: UISwipeGestureRecognizer) {
swiftris.dropShape()
}
/// Optional delegate method found in UIGestureRecognizerDelegate which will allow each gesture recognizer to work in tandem with the others. However, at times a gesture recognizer may collide with another.
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer!, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer!) -> Bool {
return true
}
/// Pan gesture recognizer take precedence over the swipe gesture and the tap to do likewise over the pan.
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer!, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer!) -> Bool {
if let swipeRec = gestureRecognizer as? UISwipeGestureRecognizer {
if let panRec = otherGestureRecognizer as? UIPanGestureRecognizer {
return true
}
} else if let panRec = gestureRecognizer as? UIPanGestureRecognizer {
if let tapRec = otherGestureRecognizer as? UITapGestureRecognizer {
return true
}
}
return false
}
func gameDidBegin(swiftris: SwifTris) {
// The following is false when restarting a new game
levelLbl.text = "\(swiftris.level)"
scoreLbl.text = "\(swiftris.score)"
scene.tickLengthMillis = TickLengthLevelOne
if swiftris.nextShape != nil && swiftris.nextShape!.blocks[0].sprite == nil {
scene.addPreviewShapeToScene(swiftris.nextShape!) {
self.nextShape()
}
} else {
nextShape()
}
}
func gameDidEnd(swiftris: SwifTris) {
view.userInteractionEnabled = false
scene.stopTicking()
scene.playSound("gameover.mp3")
scene.animateCollapsingLines(swiftris.removeAllBlocks(), fallenBlocks: Array<Array<Block>>()) {
swiftris.beginGame()
}
}
func gameDidLevelUp(swiftris: SwifTris) {
levelLbl.text = "\(swiftris.level)"
if scene.tickLengthMillis >= 100 {
scene.tickLengthMillis -= 100
} else if scene.tickLengthMillis > 50 {
scene.tickLengthMillis -= 50
}
scene.playSound("levelup.mp3")
}
func gameShapeDidDrop(swiftris: SwifTris) {
scene.stopTicking()
scene.redrawShape(swiftris.fallingShape!) {
swiftris.letShapeFall()
}
scene.playSound("drop.mp3")
}
func gameShapeDidLand(swiftris: SwifTris) {
scene.stopTicking()
self.view.userInteractionEnabled = false
let removedLines = swiftris.removeCompletedLines()
if removedLines.linesRemoved.count > 0 {
self.scoreLbl.text = "\(swiftris.score)"
scene.animateCollapsingLines(removedLines.linesRemoved, fallenBlocks:removedLines.fallenBlocks) {
self.gameShapeDidLand(swiftris)
}
scene.playSound("bomb.mp3")
} else {
nextShape()
}
}
func gameShapeDidMove(swiftris: SwifTris) {
scene.redrawShape(swiftris.fallingShape!) {}
}
}
| mit | 3899b873db4d01b0aa4c0d242ba0b62e | 33.279762 | 210 | 0.61278 | 5.09646 | false | false | false | false |
Jaspion/Kilza | spec/res/swift/hash/Obj.swift | 1 | 3212 | //
// Obj.swift
//
// Created on <%= Time.now.strftime("%Y-%m-%d") %>
// Copyright (c) <%= Time.now.strftime("%Y") %>. All rights reserved.
// Generated by Kilza https://github.com/Jaspion/Kilza
//
import Foundation
public class Obj: NSObject, NSCoding {
// Original names
static let kObjStr: String = "str"
static let kObjNum: String = "num"
static let kObjFlo: String = "flo"
static let kObjBoo: String = "boo"
public var str: String?
public var num: Int?
public var flo: Double?
public var boo: Bool?
public class func model(obj: AnyObject) -> Obj? {
var instance: Obj?
if (obj is String) {
instance = Obj.init(str: obj as! String)
} else if (obj is Dictionary<String, AnyObject>) {
instance = Obj.init(dict: obj as! Dictionary)
}
return instance
}
public convenience init?(str: String) {
if let data = str.dataUsingEncoding(NSUTF8StringEncoding) {
do {
let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
self.init(dict: object as! Dictionary)
} catch _ as NSError {
self.init(dict: Dictionary())
}
} else {
self.init(dict: Dictionary())
}
}
public init?(dict: Dictionary<String, AnyObject>) {
super.init()
self.str = objectOrNil(forKey: Obj.kObjStr, fromDictionary:dict) as? String
self.num = objectOrNil(forKey: Obj.kObjNum, fromDictionary:dict) as? Int
self.flo = objectOrNil(forKey: Obj.kObjFlo, fromDictionary:dict) as? Double
self.boo = objectOrNil(forKey: Obj.kObjBoo, fromDictionary:dict) as? Bool
}
public func dictionaryRepresentation() -> Dictionary<String, AnyObject> {
var mutableDict: Dictionary = [String: AnyObject]()
mutableDict[Obj.kObjStr] = self.str
mutableDict[Obj.kObjNum] = self.num
mutableDict[Obj.kObjFlo] = self.flo
mutableDict[Obj.kObjBoo] = self.boo
return NSDictionary.init(dictionary: mutableDict) as! Dictionary<String, AnyObject>
}
public func objectOrNil(forKey key: String, fromDictionary dict: Dictionary<String, AnyObject>) -> AnyObject?
{
if let object: AnyObject = dict[key] {
if !(object is NSNull) {
return object
}
}
return nil
}
required public init(coder aDecoder: NSCoder) {
self.str = aDecoder.decodeObjectForKey(Obj.kObjStr)! as? String
self.num = aDecoder.decodeObjectForKey(Obj.kObjNum)! as? Int
self.flo = aDecoder.decodeObjectForKey(Obj.kObjFlo)! as? Double
self.boo = aDecoder.decodeObjectForKey(Obj.kObjBoo)! as? Bool
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(str, forKey:Obj.kObjStr)
aCoder.encodeObject(num, forKey:Obj.kObjNum)
aCoder.encodeObject(flo, forKey:Obj.kObjFlo)
aCoder.encodeObject(boo, forKey:Obj.kObjBoo)
}
override public var description: String {
get {
return "\(dictionaryRepresentation())"
}
}
}
| mit | d8dfd09b72453e5e791a30c018261660 | 33.913043 | 134 | 0.623288 | 4.076142 | false | false | false | false |
gottesmm/swift | test/Reflection/typeref_decoding.swift | 5 | 23950 | // REQUIRES: no_asan
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/libTypesToReflect.%target-dylib-extension
// RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension | %FileCheck %s
// CHECK: FIELDS:
// CHECK: =======
// CHECK: TypesToReflect.Box
// CHECK: ------------------
// CHECK: item: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.C
// CHECK: ----------------
// CHECK: aClass: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: aStruct: TypesToReflect.S
// CHECK: (struct TypesToReflect.S)
// CHECK: anEnum: TypesToReflect.E
// CHECK: (enum TypesToReflect.E)
// CHECK: aTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int))
// CHECK: aTupleWithLabels: (a : TypesToReflect.C, s : TypesToReflect.S, e : TypesToReflect.E)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E))
// CHECK: aMetatype: TypesToReflect.C.Type
// CHECK: (metatype
// CHECK: (class TypesToReflect.C))
// CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int
// CHECK: (function
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (struct Swift.Int))
// CHECK: aFunctionWithVarArgs: (TypesToReflect.C, Swift.Array<TypesToReflect.S>...) -> ()
// CHECK: (function
// CHECK: (class TypesToReflect.C)
// CHECK: (bound_generic_struct Swift.Array
// CHECK: (struct TypesToReflect.S))
// CHECK: (tuple))
// CHECK: TypesToReflect.S.NestedS
// CHECK: ------------------------
// CHECK: aField: Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: TypesToReflect.S
// CHECK: ----------------
// CHECK: aClass: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (struct TypesToReflect.S))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (enum TypesToReflect.E))
// CHECK: aTuple: (TypesToReflect.C, TypesToReflect.Box<TypesToReflect.S>, TypesToReflect.Box<TypesToReflect.E>, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (struct TypesToReflect.S))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (enum TypesToReflect.E))
// CHECK: (struct Swift.Int))
// CHECK: aMetatype: TypesToReflect.C.Type
// CHECK: (metatype
// CHECK: (class TypesToReflect.C))
// CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int
// CHECK: (function
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (struct Swift.Int))
// CHECK: aFunctionWithThinRepresentation: @convention(thin) () -> ()
// CHECK: (function convention=thin
// CHECK: (tuple))
// CHECK: aFunctionWithCRepresentation: @convention(c) () -> ()
// CHECK: (function convention=c
// CHECK: (tuple))
// CHECK: TypesToReflect.E
// CHECK: ----------------
// CHECK: Class: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: Struct: TypesToReflect.S
// CHECK: (struct TypesToReflect.S)
// CHECK: Enum: TypesToReflect.E
// CHECK: (enum TypesToReflect.E)
// CHECK: Function: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> ()
// CHECK: (function
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (tuple))
// CHECK: Tuple: (TypesToReflect.C, TypesToReflect.S, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (struct Swift.Int))
// CHECK: IndirectTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int))
// CHECK: NestedStruct: TypesToReflect.S.NestedS
// CHECK: (struct TypesToReflect.S.NestedS
// CHECK: (struct TypesToReflect.S))
// CHECK: Metatype
// CHECK: EmptyCase
// CHECK: TypesToReflect.References
// CHECK: -------------------------
// CHECK: strongRef: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: weakRef: weak Swift.Optional<TypesToReflect.C>
// CHECK: (weak_storage
// CHECK: (bound_generic_enum Swift.Optional
// CHECK: (class TypesToReflect.C)))
// CHECK: unownedRef: unowned TypesToReflect.C
// CHECK: (unowned_storage
// CHECK: (class TypesToReflect.C))
// CHECK: unownedUnsafeRef: unowned(unsafe) TypesToReflect.C
// CHECK: (unmanaged_storage
// CHECK: (class TypesToReflect.C))
// CHECK: TypesToReflect.C1
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, TypesToReflect.E1<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: dependentMember: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.C2
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, TypesToReflect.E2<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: TypesToReflect.C3
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S3<A>
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E3<A>
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int
// CHECK: (function
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, TypesToReflect.E3<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Outer
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: dependentMember2: A.Outer.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.C4
// CHECK: -----------------
// CHECK: TypesToReflect.S1
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S1<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E1<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.Box<TypesToReflect.S1<A>>, TypesToReflect.Box<TypesToReflect.E1<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.S2
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C2<A>
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S2<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E2<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C2<A>) -> (TypesToReflect.S2<A>) -> (TypesToReflect.E2<A>) -> Swift.Int
// CHECK: (function
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.Box<TypesToReflect.S2<A>>, TypesToReflect.Box<TypesToReflect.E2<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: TypesToReflect.S3
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S3<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E3<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int
// CHECK: (function
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (function
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.Box<TypesToReflect.S3<A>>, TypesToReflect.Box<TypesToReflect.E3<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Outer
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: dependentMember2: A.Outer.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.S4
// CHECK: -----------------
// CHECK: TypesToReflect.E1
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Int: Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: Function: (A) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: Metatype: A.Type
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: TypesToReflect.E2
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C2<A>
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S2<A>
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E2<A>
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Function: (A.Type) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: DependentMemberInner: A.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: ExistentialMetatype: A.Type
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: TypesToReflect.E3
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S3<A>
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E3<A>
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Function: (A.Type.Type) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (metatype
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: DependentMemberOuter: A.Outer
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: DependentMemberInner: A.Outer.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.E4
// CHECK: -----------------
// CHECK: TypesToReflect.P1
// CHECK: -----------------
// CHECK: TypesToReflect.P2
// CHECK: -----------------
// CHECK: TypesToReflect.P3
// CHECK: -----------------
// CHECK: TypesToReflect.P4
// CHECK: -----------------
// CHECK: TypesToReflect.ClassBoundP
// CHECK: --------------------------
// CHECK: ASSOCIATED TYPES:
// CHECK: =================
// CHECK: - TypesToReflect.C1 : TypesToReflect.ClassBoundP
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.C4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.C4 : TypesToReflect.P2
// CHECK: typealias Outer = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.S4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.S4 : TypesToReflect.P2
// CHECK: typealias Outer = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P2
// CHECK: typealias Outer = B
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P3
// CHECK: typealias First = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: typealias Second = B
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: - TypesToReflect.S : TypesToReflect.P4
// CHECK: typealias Result = Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: BUILTIN TYPES:
// CHECK: ==============
// CHECK: CAPTURE DESCRIPTORS:
// CHECK: ====================
// CHECK: - Capture types:
// CHECK: (sil_box
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: - Metadata sources:
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (closure_binding index=0)
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: (closure_binding index=1)
// CHECK: - Capture types:
// CHECK: (struct Swift.Int)
// CHECK: - Metadata sources:
// CHECK: - Capture types:
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=1))
// CHECK: - Metadata sources:
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (closure_binding index=0)
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: (generic_argument index=0
// CHECK: (reference_capture index=0))
| apache-2.0 | 0c8573166e8237e17baa82f1c55c94ca | 35.846154 | 285 | 0.681628 | 3.319013 | false | false | false | false |
WeHUD/app | weHub-ios/Gzone_App/Gzone_App/User.swift | 1 | 1586 | //
// User.swift
// GZone
//
// Created by Lyes Atek on 01/06/2017.
// Copyright © 2017 Lyes Atek. All rights reserved.
//
import Foundation
open class User : NSObject{
var _id : String = ""
var dateOfBirth : String
var email : String
var username : String
var reply : String
var password : String
var avatar : String? = "https://s3.ca-central-1.amazonaws.com/g-zone/images/profile01.png"
var datetimeRegister : String?
var longitude : Double?
var latitude : Double?
var followedUsers : [String]?
var followedGames : [String]?
var score : Int?
var connected : Bool?
init(id : String,dateOfBirth : String,email : String,username : String,reply : String,password : String,avatar : String,datetimeRegister : String,longitude : Double,latitude : Double,followedUsers : [String],followedGames : [String],score : Int,connected : Bool){
self.dateOfBirth = dateOfBirth
self.email = email
self.username = username
self.password = password
self.avatar = avatar
self.datetimeRegister = datetimeRegister
self._id = id
self.reply = reply
self.followedGames = followedGames
self.followedUsers = followedUsers
self.score = score
self.connected = connected
self.longitude = longitude
self.latitude = latitude
}
override init(){
self.dateOfBirth = " "
self.email = " "
self.username = " "
self.reply = " "
self.password = " "
}
}
| bsd-3-clause | 3036c1d375792d2391256ddf90e3dbeb | 27.818182 | 267 | 0.611356 | 4.24933 | false | false | false | false |
csontosgabor/Twitter_Post | Twitter_Post/ViewController.swift | 1 | 3232 | //
// ViewController.swift
// Twitter_Post
//
// Created by Gabor Csontos on 12/15/16.
// Copyright © 2016 GaborMajorszki. All rights reserved.
//
/*
THANKS FOR DOWNLOADING AND USING TWITTER_POST CONTROLLER.
GITHUB:
https://github.com/csontosgabor
Dribbble:
https://dribbble.com/gaborcsontos
*/
/*
Don't forget to add these lines into your Info.plist !!!
Privacy - Location When in Use Usage Description ------ We need to access your location.
Privacy - Camera Usage Description ------ We need to access your camera.
Privacy - Photo Library Usage Description ----- We need to access your photos.
*/
import UIKit
internal var greetingsText: String = "Thanks for using TWITTER_POST. \n github: \n https://github.com/csontosgabor"
class ViewController: UIViewController {
let label: UITextView = {
let label = UITextView()
label.text = greetingsText
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 14)
label.textAlignment = .center
label.isScrollEnabled = false
label.isEditable = false
label.dataDetectorTypes = .link
return label
}()
lazy var postBtn: UIButton = {
let button = UIButton(type: .system)
let imageView = UIImageView()
imageView.image = UIImage(named: "ic_post")!.withRenderingMode(.alwaysOriginal)
button.setImage(imageView.image, for: .normal)
button.tintColor = UIColor.clear
button.contentHorizontalAlignment = .center
button.addTarget(self, action: #selector(_openpostController(_:)), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
func _openpostController(_ sender: UIButton) {
let nav = UINavigationController(rootViewController: PostViewController())
self.present(nav, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
//label x,y,w,h
if !label.isDescendant(of: self.view) { self.view.addSubview(label) }
label.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
label.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -100).isActive = true
label.heightAnchor.constraint(equalToConstant: 150).isActive = true
//postBtn x,y,w,h
if !postBtn.isDescendant(of: self.view) { self.view.addSubview(postBtn) }
postBtn.widthAnchor.constraint(equalToConstant: 50).isActive = true
postBtn.heightAnchor.constraint(equalToConstant: 50).isActive = true
postBtn.topAnchor.constraint(equalTo: self.label.bottomAnchor,constant: 12).isActive = true
postBtn.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
}
}
| mit | c393b3afb7faa9783020e159dd2e6fa9 | 27.59292 | 116 | 0.653668 | 4.662338 | false | false | false | false |
VivaReal/Compose | Compose/Classes/Views/CollectionViewCell/CollectionStackContainerCollectionViewCell.swift | 1 | 2494 | //
// CollectionStackContainerCollectionViewCell.swift
// Compose
//
// Created by Bruno Bilescky on 26/10/16.
// Copyright © 2016 VivaReal. All rights reserved.
//
import UIKit
class CollectionStackContainerCollectionViewCell: UICollectionViewCell {
private var currentConstraints: [NSLayoutConstraint] = []
public private(set) var innerView: ComposingCollectionView
private var widthConstraint: NSLayoutConstraint!
private var heightConstraint: NSLayoutConstraint!
private var leadingConstraint: NSLayoutConstraint!
private var topConstraint: NSLayoutConstraint!
var containerSize: CGSize {
get {
return CGSize(width: widthConstraint.constant, height: heightConstraint.constant)
}
set {
widthConstraint.constant = newValue.width
heightConstraint.constant = newValue.height
}
}
override public init(frame: CGRect) {
var innerFrame = frame
innerFrame.origin = .zero
self.innerView = ComposingCollectionView(frame: innerFrame)
super.init(frame: frame)
commonInit(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported.")
}
private func commonInit(frame: CGRect) {
self.isOpaque = false
self.backgroundColor = .clear
self.innerView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(innerView)
self.addConstraints()
}
private func addConstraints() {
let toView = self
let itemView = self.innerView
leadingConstraint = NSLayoutConstraint(item: itemView, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1, constant: 0)
topConstraint = NSLayoutConstraint(item: itemView, attribute: .top, relatedBy: .equal, toItem: toView, attribute: .top, multiplier: 1, constant: 0)
widthConstraint = NSLayoutConstraint(item: self.innerView, attribute: .width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: .width, multiplier: 1, constant: 0)
heightConstraint = NSLayoutConstraint(item: self.innerView, attribute: .height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: .height, multiplier: 1, constant: 0)
toView.addConstraints([leadingConstraint, topConstraint])
self.innerView.addConstraints([widthConstraint, heightConstraint])
}
}
| mit | 7f6f862a16ea642996c9b88d689700d6 | 38.571429 | 183 | 0.696751 | 5.12963 | false | false | false | false |
svyatoslav-zubrin/CustomSolutions | CustomSolutions/UniversalRefreshControl/UniversalRefreshControl.swift | 1 | 13019 | //
// UniversalRefreshControl.swift
// CustomSolutions
//
// Created by Slava Zubrin on 9/20/17.
// Copyright © 2017 Slava Zubrin. All rights reserved.
//
import UIKit
protocol UniversalRefreshControlDelegate: class {
func startedLoading(_ sender: UniversalRefreshControl)
}
/// Universal refresh control that can be used even with simple UIView. The component tested with UIScrollView only for now 😉
class UniversalRefreshControl: UIView {
weak var delegate: UniversalRefreshControlDelegate? = nil
// views
fileprivate weak var pan: UIPanGestureRecognizer! = nil
fileprivate weak var refresh: FRYMoonActivityIndicator! = nil
fileprivate weak var contentView: UIView! = nil
private var _content: UIView? = nil
var content: UIView? {
get {
return _content
}
set {
guard let newContent = newValue else {
_content?.removeFromSuperview()
_content = nil
return
}
_content?.removeFromSuperview()
newContent.frame = contentView.bounds
newContent.translatesAutoresizingMaskIntoConstraints = true
newContent.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.addSubview(newContent)
_content = newContent
}
}
// internal helpers
private var gestureShift: CGFloat = 0
private var contentOffsetAtGestureStart: CGFloat = 0
// refresh logic
private let moonSize: CGFloat = 50
private let limitToTriggerRefresh: CGFloat = 90;
private let topMarginAtLoadingTime: CGFloat = 70
private enum RefreshState {
case normal
case pullingBeforeLimitReached
case pullingAfterLimitReached
case droppedBeforeLimitReached
case droppedAfterLimitReached
case loading
case loadingAndScrolled
var string: String {
switch self {
case .normal: return "normal"
case .pullingBeforeLimitReached: return "pullingBefore"
case .pullingAfterLimitReached: return "pullingAfter"
case .droppedBeforeLimitReached: return "droppedBefore"
case .droppedAfterLimitReached: return "droppedAfter"
case .loading: return "loading"
case .loadingAndScrolled: return "loadingAndScrolled"
}
}
}
private var refreshState: RefreshState = .normal {
didSet {
switch refreshState {
case .normal:
refresh.animating = false
pan.isEnabled = false
pan.isEnabled = true
// animate back
UIView.animate(withDuration: 0.3, animations: { [unowned self] in
var frame = self.contentView.frame
frame.origin = CGPoint(x: frame.origin.x, y: 0)
self.contentView.frame = frame
})
case .droppedBeforeLimitReached:
UIView.animate(withDuration: 0.3, animations: { [unowned self] in
var frame = self.contentView.frame
frame.origin = CGPoint(x: frame.origin.x, y: 0)
self.contentView.frame = frame
}, completion: { [unowned self] _ in
self.refreshState = .normal
})
case .droppedAfterLimitReached:
UIView.animate(withDuration: 0.3, animations: { [unowned self] in
var frame = self.contentView.frame
frame.origin = CGPoint(x: frame.origin.x, y: self.topMarginAtLoadingTime)
self.contentView.frame = frame
}, completion: { [unowned self] _ in
self.refreshState = .loading
})
case .loading:
UIView.animate(withDuration: 0.3, animations: { [unowned self] in
var frame = self.contentView.frame
frame.origin = CGPoint(x: frame.origin.x, y: self.topMarginAtLoadingTime)
self.contentView.frame = frame
}, completion: { [unowned self] _ in
self.delegate?.startedLoading(self)
})
refresh.animating = true
case .loadingAndScrolled:
guard isScrolledBelowRefresh else {
break
}
UIView.animate(withDuration: 0.3, animations: { [unowned self] in
var frame = self.contentView.frame
frame.origin = CGPoint(x: frame.origin.x, y: self.topMarginAtLoadingTime)
self.contentView.frame = frame
})
default: break
}
//print("state set to: \(refreshState.string)")
}
}
// MARK: Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: User actions
func handlePan(_ gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .began:
if let content = content as? UIScrollView {
contentOffsetAtGestureStart = content.contentOffset.y
}
fallthrough
case .changed:
let shift = gesture.translation(in: self).y
let delta = shift - gestureShift
gestureShift = shift
var topCellToContentViewDistance = contentView.frame.minY
if let content = content as? UIScrollView {
topCellToContentViewDistance -= content.contentOffset.y
}
// scroll up happend
if delta < 0 {
let shouldHandleScrollUp = topCellToContentViewDistance > 0
if shouldHandleScrollUp {
if contentView.frame.minY > 0 {
if let content = content as? UIScrollView {
var frame = contentView.frame
frame.origin = CGPoint(x: frame.origin.x, y: max(0, frame.origin.y + delta))
contentView.frame = frame
content.contentOffset = .zero
refresh.alpha = contentView.frame.minY / limitToTriggerRefresh
}
}
break
}
}
// scroll down happend
let shouldHandleScrollDown = topCellToContentViewDistance >= 0
if shouldHandleScrollDown {
let expectedShift = contentView.frame.origin.y + delta
let limitedShift = max(0, min(160, expectedShift))
var frame = contentView.frame
frame.origin = CGPoint(x: frame.origin.x, y: contentOffsetAtGestureStart + limitedShift)
contentView.frame = frame
refresh.alpha = contentView.frame.minY / limitToTriggerRefresh
}
if refreshState == .normal {
if topCellToContentViewDistance > 0 {
if topCellToContentViewDistance < limitToTriggerRefresh {
refreshState = .pullingBeforeLimitReached
} else {
refreshState = .pullingAfterLimitReached
}
}
} else if refreshState == .pullingBeforeLimitReached {
if topCellToContentViewDistance >= limitToTriggerRefresh {
refreshState = .pullingAfterLimitReached
}
} else if refreshState == .pullingAfterLimitReached {
if topCellToContentViewDistance < limitToTriggerRefresh {
refreshState = .pullingBeforeLimitReached
}
}
case .ended, .cancelled:
if refreshState == .pullingAfterLimitReached {
refreshState = .droppedAfterLimitReached
} else if refreshState == .pullingBeforeLimitReached {
refreshState = .droppedBeforeLimitReached
} else if refreshState == .loading {
if contentView.frame.minY != topMarginAtLoadingTime {
refreshState = .loadingAndScrolled
}
if let _ = content as? UIScrollView {
if isScrolledAboveRefresh {
reset()
break
}
}
UIView.animate(withDuration: 0.3, animations: { [unowned self] in
var frame = self.contentView.frame
frame.origin = CGPoint(x: frame.origin.x, y: self.topMarginAtLoadingTime)
self.contentView.frame = frame
})
} else if refreshState == .loadingAndScrolled {
if let _ = content as? UIScrollView {
if isScrolledAboveRefresh {
reset()
break
}
}
UIView.animate(withDuration: 0.3, animations: { [unowned self] in
var frame = self.contentView.frame
frame.origin = CGPoint(x: frame.origin.x, y: self.topMarginAtLoadingTime)
self.contentView.frame = frame
})
}
reset()
case .failed:
reset()
default: break
}
}
// MARK: Public
func finish() {
guard refreshState == .loading || refreshState == .loadingAndScrolled else {
return
}
refreshState = .normal
}
// MARK: Private
private func setup() {
// views
let cv = UIView(frame: bounds)
cv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cv.backgroundColor = .yellow
addSubview(cv)
contentView = cv
var frame = CGRect(origin: .zero, size: CGSize(width: bounds.size.width, height: topMarginAtLoadingTime))
let refreshContainer = UIView(frame: frame)
refreshContainer.autoresizingMask = [.flexibleBottomMargin, .flexibleWidth]
addSubview(refreshContainer)
sendSubview(toBack: refreshContainer)
frame = CGRect(x: (bounds.size.width - moonSize) / 2,
y: (topMarginAtLoadingTime - moonSize) / 2,
width: moonSize,
height: moonSize)
let mai = FRYMoonActivityIndicator(frame: frame)
mai.autoresizingMask = [.flexibleBottomMargin, .flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin]
refreshContainer.addSubview(mai)
refresh = mai
// gestures
let p = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)));
p.delegate = self
addGestureRecognizer(p)
pan = p
}
private func reset() {
gestureShift = 0
}
private var isScrolledAboveRefresh: Bool {
guard refreshState == .loading || refreshState == .loadingAndScrolled else {
return false
}
if let _ = content as? UIScrollView {
// TODO: is that correct, shouldn't we take into account contentOffset of the scroll?
return contentView.frame.minY < topMarginAtLoadingTime
} else {
return contentView.frame.minY < topMarginAtLoadingTime
}
}
private var isScrolledBelowRefresh: Bool {
guard refreshState == .loading || refreshState == .loadingAndScrolled else {
return false
}
if let _ = content as? UIScrollView {
// TODO: is that correct, shouldn't we take into account contentOffset of the scroll?s
return contentView.frame.minY > topMarginAtLoadingTime
} else {
return contentView.frame.minY > topMarginAtLoadingTime
}
}
}
extension UniversalRefreshControl: UIGestureRecognizerDelegate {
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard pan == gestureRecognizer else {
return false
}
if let content = content as? UIScrollView, content.contentOffset.y > 0 {
return false
}
let should = contentView.frame.minY > 0 || (contentView.frame.minY == 0 && pan.translation(in: self).y > 0)
return should
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
guard let content = content as? UIScrollView else {
return false
}
return otherGestureRecognizer == content.panGestureRecognizer
}
}
| mit | 8cac7b405eb30fa4f53b3f55d8677041 | 34.953039 | 125 | 0.558509 | 5.554844 | false | false | false | false |
ben-ng/swift | benchmark/single-source/StringInterpolation.swift | 1 | 1457 | //===--- StringInterpolation.swift ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
class RefTypePrintable : CustomStringConvertible {
var description: String {
return "01234567890123456789012345678901234567890123456789"
}
}
@inline(never)
public func run_StringInterpolation(_ N: Int) {
let reps = 100
let refResult = reps
let anInt: Int64 = 0x1234567812345678
let aRefCountedObject = RefTypePrintable()
for _ in 1...100*N {
var result = 0
for _ in 1...reps {
let s = "\(anInt) abcdefdhijklmn \(aRefCountedObject) abcdefdhijklmn \u{01}"
let utf16 = s.utf16
// FIXME: if String is not stored as UTF-16 on this platform, then the
// following operation has a non-trivial cost and needs to be replaced
// with an operation on the native storage type.
result = result &+ Int(utf16[utf16.index(before: utf16.endIndex)])
}
CheckResults(result == refResult, "IncorrectResults in StringInterpolation: \(result) != \(refResult)")
}
}
| apache-2.0 | 6af071b36b5d61d6f7c3ed119222f553 | 33.690476 | 107 | 0.645161 | 4.428571 | false | false | false | false |
genedelisa/MusicSequenceAUGraph | MusicSequenceAUGraph/ViewController.swift | 1 | 5196 | //
// ViewController.swift
// MusicSequenceAUGraph
//
// Created by Gene De Lisa on 9/9/14.
// Copyright (c) 2014 Gene De Lisa. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var picker: UIPickerView!
@IBOutlet var loopSlider: UISlider!
var gen = SoundGenerator()
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
picker.dataSource = self
let len = gen.getTrackLength()
loopSlider.maximumValue = Float(len)
loopSlider.value = Float(len)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func play(sender: AnyObject) {
gen.play()
}
@IBAction func stopPlaying(sender: AnyObject) {
gen.stop()
}
@IBAction func loopSliderChanged(sender: AnyObject) {
print("slider vlaue \(loopSlider.value)")
gen.setTrackLoopDuration(loopSlider.value)
}
var GMDict:[String:UInt8] = [
"Acoustic Grand Piano" : 0,
"Bright Acoustic Piano" : 1,
"Electric Grand Piano" : 2,
"Honky-tonk Piano" : 3,
"Electric Piano 1" : 4,
"Electric Piano 2" : 5,
"Harpsichord" : 6,
"Clavi" : 7,
"Celesta" : 8,
"Glockenspiel" : 9,
"Music Box" : 10,
"Vibraphone" : 11,
"Marimba" : 12,
"Xylophone" : 13,
"Tubular Bells" : 14,
"Dulcimer" : 15,
"Drawbar Organ" : 16,
"Percussive Organ" : 17,
"Rock Organ" : 18,
"ChurchPipe" : 19,
"Positive" : 20,
"Accordion" : 21,
"Harmonica" : 22,
"Tango Accordion" : 23,
"Classic Guitar" : 24,
"Acoustic Guitar" : 25,
"Jazz Guitar" : 26,
"Clean Guitar" : 27,
"Muted Guitar" : 28,
"Overdriven Guitar" : 29,
"Distortion Guitar" : 30,
"Guitar harmonics" : 31,
"JazzBass" : 32,
"DeepBass" : 33,
"PickBass" : 34,
"FretLess" : 35,
"SlapBass1" : 36,
"SlapBass2" : 37,
"SynthBass1" : 38,
"SynthBass2" : 39,
"Violin" : 40,
"Viola" : 41,
"Cello" : 42,
"ContraBass" : 43,
"TremoloStr" : 44,
"Pizzicato" : 45,
"Harp" : 46,
"Timpani" : 47,
"String Ensemble 1" : 48,
"String Ensemble 2" : 49,
"SynthStrings 1" : 50,
"SynthStrings 2" : 51,
"Choir" : 52,
"DooVoice" : 53,
"Voices" : 54,
"OrchHit" : 55,
"Trumpet" : 56,
"Trombone" : 57,
"Tuba" : 58,
"MutedTrumpet" : 59,
"FrenchHorn" : 60,
"Brass" : 61,
"SynBrass1" : 62,
"SynBrass2" : 63,
"SopranoSax" : 64,
"AltoSax" : 65,
"TenorSax" : 66,
"BariSax" : 67,
"Oboe" : 68,
"EnglishHorn" : 69,
"Bassoon" : 70,
"Clarinet" : 71,
"Piccolo" : 72,
"Flute" : 73,
"Recorder" : 74,
"PanFlute" : 75,
"Bottle" : 76,
"Shakuhachi" : 77,
"Whistle" : 78,
"Ocarina" : 79,
"SquareWave" : 80,
"SawWave" : 81,
"Calliope" : 82,
"SynChiff" : 83,
"Charang" : 84,
"AirChorus" : 85,
"fifths" : 86,
"BassLead" : 87,
"New Age" : 88,
"WarmPad" : 89,
"PolyPad" : 90,
"GhostPad" : 91,
"BowedGlas" : 92,
"MetalPad" : 93,
"HaloPad" : 94,
"Sweep" : 95,
"IceRain" : 96,
"SoundTrack" : 97,
"Crystal" : 98,
"Atmosphere" : 99,
"Brightness" : 100,
"Goblin" : 101,
"EchoDrop" : 102,
"SciFi effect" : 103,
"Sitar" : 104,
"Banjo" : 105,
"Shamisen" : 106,
"Koto" : 107,
"Kalimba" : 108,
"Scotland" : 109,
"Fiddle" : 110,
"Shanai" : 111,
"MetalBell" : 112,
"Agogo" : 113,
"SteelDrums" : 114,
"Woodblock" : 115,
"Taiko" : 116,
"Tom" : 117,
"SynthTom" : 118,
"RevCymbal" : 119,
"FretNoise" : 120,
"NoiseChiff" : 121,
"Seashore" : 122,
"Birds" : 123,
"Telephone" : 124,
"Helicopter" : 125,
"Stadium" : 126,
"GunShot" : 127
]
}
extension ViewController: UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 128
}
}
extension ViewController: UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
//var u = UInt8(row)
for (k,v) in GMDict {
if v == UInt8(row) {
return k
}
}
return nil
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
gen.loadSF2Preset(UInt8(row))
}
}
| mit | cada57b0be337d670bd0de8da7f06fd9 | 23.742857 | 109 | 0.488645 | 3.436508 | false | false | false | false |
khizkhiz/swift | test/expr/closure/default_args.swift | 3 | 908 | // RUN: %target-parse-verify-swift
func simple_default_args() {
// <rdar://problem/22753605> QoI: bad diagnostic when closure has default argument
let _ : (Int) -> Int = {(x : Int = 1) in x+1} // expected-error{{default arguments are not allowed in closures}} {{36-39=}}
let _ : () -> Int = {(x : Int = 1) in x+1} // expected-error{{cannot convert value of type '(Int) -> Int' to specified type '() -> Int'}} expected-error {{default arguments are not allowed in closures}} {{33-36=}}
let _ : () -> Int = {(x : Int) in x+1} // expected-error{{cannot convert value of type '(Int) -> Int' to specified type '() -> Int'}}
}
func func_default_args() {
func has_default_args(x x: Int = 1) -> Int { return x+1 }
var _ : (Int) -> Int = has_default_args // okay
var _ : () -> Int = has_default_args // expected-error{{cannot convert value of type '(x: Int) -> Int' to specified type '() -> Int'}}
}
| apache-2.0 | 0741df58c377ba0e75a2db51e944d864 | 59.533333 | 215 | 0.610132 | 3.301818 | false | false | false | false |
CodeEagle/SSPageViewController | SSPageViewController/Source/SSPageViewController.swift | 1 | 18259 | //
// SSPageViewController.swift
// SSPageViewController
//
// Created by LawLincoln on 16/3/11.
// Copyright © 2016年 Luoo. All rights reserved.
//
import UIKit
#if !PACKING_FOR_APPSTORE
import HMSegmentedControl_CodeEagle
import SnapKit
#endif
//MARK:- SSPageViewController
/// SSPageViewController
public final class SSPageViewController < Template: SSPageViewContentProtocol, Delegate: SSPageViewDelegate>: UIViewController, UIScrollViewDelegate where Template == Delegate.Template {
public typealias TemplateConfigurationClosure = (_ display: Template, _ backup: Template) -> Void
// MARK:- Public
public fileprivate(set) lazy var indicator: UIPageControl = UIPageControl()
public fileprivate(set) lazy var scrollView = UIScrollView()
public fileprivate(set) lazy var segment: HMSegmentedControl_CodeEagle = HMSegmentedControl_CodeEagle()
public var itemLength: CGFloat {
let size = view.bounds.size
return _isHorizontal ? size.width : size.height
}
public weak var ss_delegate: Delegate?
public var initializeTemplateConfiguration: TemplateConfigurationClosure? {
didSet {
initializeTemplateConfiguration?(_display, _backup)
}
}
public var configurationBlock: TemplateConfigurationClosure? {
didSet {
configurationBlock?(_display, _backup)
customConfigurationDone()
}
}
public var indicatorAlignStyle: NSTextAlignment = .center {
didSet {
configureIndicator()
}
}
public var loopInterval: TimeInterval = 0 {
didSet {
addDisplayNextTask()
}
}
public var showsSegment = false {
didSet {
segment.snp.remakeConstraints { (make) -> Void in
make.top.left.right.equalTo(view)
make.height.equalTo(showsSegment ? 44 : 0)
}
}
}
public var showsIndicator: Bool = false {
didSet { indicator.isHidden = !showsIndicator }
}
public var currentOffset: ((CGFloat) -> ())?
// MARK:- Private
fileprivate var _display: Template!
fileprivate var _backup: Template!
fileprivate var _direction: UIPageViewControllerNavigationOrientation!
fileprivate var _task: SSCancelableTask?
fileprivate var _isHorizontal: Bool { return _direction == .horizontal }
fileprivate var _displayView: UIView! { return _display.ss_content }
fileprivate var _backupView: UIView! { return _backup.ss_content }
fileprivate var _boundsWidth: CGFloat { return view.bounds.width }
fileprivate var _boundsHeight: CGFloat { return view.bounds.height }
// MARK:- LifeCycle
deinit {
_display = nil
_backup = nil
scrollView.delegate = nil
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public convenience init(scrollDirection: UIPageViewControllerNavigationOrientation = .horizontal) {
self.init(nibName: nil, bundle: nil)
_direction = scrollDirection
_display = Template()
_backup = Template()
automaticallyAdjustsScrollViewInsets = false
setup()
}
fileprivate var _ignoreScroll = false
public func scrollTo(_ template: (Template) -> Template, direction: UIPageViewControllerNavigationDirection) {
_backup = template(_backup)
_ignoreScroll = true
let hasNextAfterBackup = _backup.ss_nextId != nil
if direction == .forward {
_displayView.snp.remakeConstraints({ (make) -> Void in
if _isHorizontal {
make.left.equalTo(scrollView).offset(_displayView.frame.origin.x)
make.top.bottom.equalTo(scrollView)
} else {
make.top.equalTo(scrollView).offset(_displayView.frame.origin.y)
make.left.right.equalTo(scrollView)
}
make.width.height.equalTo(scrollView)
})
_backupView.snp.remakeConstraints({ (make) -> Void in
if _isHorizontal {
make.left.equalTo(_displayView.snp.right)
make.right.equalTo(scrollView).offset(hasNextAfterBackup ? -_boundsWidth : 0)
make.top.bottom.equalTo(scrollView)
} else {
make.top.equalTo(_displayView.snp.bottom)
make.bottom.equalTo(scrollView).offset(hasNextAfterBackup ? -_boundsHeight : 0)
make.left.right.equalTo(scrollView)
}
make.width.height.equalTo(scrollView)
})
} else {
let offset = _isHorizontal ? (_displayView.frame.origin.x - _boundsWidth) : (_displayView.frame.origin.y - _boundsHeight)
_backupView.snp.remakeConstraints({ (make) -> Void in
if _isHorizontal {
make.left.equalTo(scrollView).offset(offset)
make.top.bottom.equalTo(scrollView)
} else {
make.top.equalTo(scrollView).offset(offset)
make.left.right.equalTo(scrollView)
}
make.width.height.equalTo(scrollView)
})
_displayView.snp.remakeConstraints({ (make) -> Void in
if _isHorizontal {
make.left.equalTo(_backupView.snp.right)
make.right.equalTo(scrollView)
make.top.bottom.equalTo(scrollView)
} else {
make.top.equalTo(_backupView.snp.bottom)
make.bottom.equalTo(scrollView)
make.left.right.equalTo(scrollView)
}
make.width.height.equalTo(scrollView)
})
}
var point = scrollView.contentOffset
if direction == .forward {
if _isHorizontal {
point.x += _boundsWidth
} else {
point.y += _boundsHeight
}
} else {
if _isHorizontal {
point.x -= _boundsWidth
} else {
point.y -= _boundsHeight
}
}
scrollView.setNeedsLayout()
scrollView.setContentOffset(point, animated: true)
}
// MARK:- UIScrollViewDelegate
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
dealScroll(scrollView)
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
dealEnd(scrollView)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
dealEnd(scrollView)
}
fileprivate func dealScroll(_ scrollView: UIScrollView) {
SSCancelableTaskManager.cancel(_task)
let offset = scrollView.contentOffset
let standarValue = _isHorizontal ? offset.x : offset.y
currentOffset?(standarValue)
if _ignoreScroll { return }
let backupPoint = _isHorizontal ? _backupView.frame.origin.x : _backupView.frame.origin.y
let displayPoint = _isHorizontal ? _displayView.frame.origin.x : _displayView.frame.origin.y
let displayLen = _isHorizontal ? _displayView.frame.size.width : _displayView.frame.size.height
if displayPoint - standarValue > 0 {
let targetBackupPoint = displayPoint - displayLen
if let preId = _display.ss_previousId {
if _backup.ss_identifer != preId || _backup.ss_identifer == "" {
ss_delegate?.pageView(self, configureForView: _backup, beforeView: _display)
}
if backupPoint != targetBackupPoint {
_backupView.snp.remakeConstraints({ (make) -> Void in
if _isHorizontal {
make.left.equalTo(scrollView)
make.top.bottom.equalTo(scrollView)
} else {
make.top.equalTo(scrollView)
make.left.right.equalTo(scrollView)
}
make.width.height.equalTo(scrollView)
})
_displayView.snp.remakeConstraints({ (make) -> Void in
if _isHorizontal {
make.right.equalTo(scrollView).offset(-_boundsWidth)
make.left.equalTo(_backupView.snp.right)
make.top.bottom.equalTo(scrollView)
} else {
make.top.equalTo(_backupView.snp.bottom)
make.left.right.equalTo(scrollView)
make.bottom.equalTo(scrollView).offset(-_boundsHeight)
}
make.width.height.equalTo(scrollView)
})
}
}
} else {
let targetBackupPoint = displayPoint + displayLen
if let nextId = _display.ss_nextId {
if _backup.ss_identifer != nextId || _backup.ss_identifer == "" {
ss_delegate?.pageView(self, configureForView: _backup, afterView: _display)
}
if backupPoint != targetBackupPoint {
_displayView.snp.remakeConstraints({ (make) -> Void in
if _isHorizontal {
make.left.equalTo(scrollView).offset(_boundsWidth)
make.top.bottom.equalTo(scrollView)
} else {
make.top.equalTo(scrollView).offset(_boundsHeight)
make.left.right.equalTo(scrollView)
}
make.width.height.equalTo(scrollView)
})
_backupView.snp.remakeConstraints({ (make) -> Void in
if _isHorizontal {
make.right.equalTo(scrollView).offset(-_boundsWidth)
make.left.equalTo(_displayView.snp.right)
make.top.bottom.equalTo(scrollView)
} else {
make.top.equalTo(_displayView.snp.bottom)
make.left.right.equalTo(scrollView)
make.bottom.equalTo(scrollView).offset(-_boundsHeight)
}
make.width.height.equalTo(scrollView)
})
}
}
}
scrollView.setNeedsLayout()
}
fileprivate func dealEnd(_ scrollView: UIScrollView) {
_ignoreScroll = false
let lastPoint = scrollView.contentOffset
let displayPoint = _isHorizontal ? _displayView.frame.origin.x : _displayView.frame.origin.y
let backupPoint = _isHorizontal ? _backupView.frame.origin.x : _backupView.frame.origin.y
let standar = _isHorizontal ? lastPoint.x : lastPoint.y
let b = abs(backupPoint - standar)
let s = abs(displayPoint - standar)
if b < s { swap(&_display, &_backup) }
let reachHeader = _isHorizontal ? (lastPoint.x == 0) : (lastPoint.y == 0)
let reachFooter = _isHorizontal ? (lastPoint.x == scrollView.bounds.size.width * 2) : (lastPoint.y == scrollView.bounds.size.height * 2)
var target: CGFloat = 0
if reachHeader {
if _display?.ss_previousId != nil {
target = _isHorizontal ? _boundsWidth : _boundsHeight
}
let point = CGPoint(x: _isHorizontal ? target : 0, y: _isHorizontal ? 0 : target)
scrollView.setContentOffset(point, animated: false)
} else if reachFooter {
target = _isHorizontal ? _boundsWidth * 2: _boundsHeight * 2
if _display?.ss_nextId != nil {
target = _isHorizontal ? _boundsWidth : _boundsHeight
}
let point = CGPoint(x: _isHorizontal ? target : 0, y: _isHorizontal ? 0 : target)
scrollView.setContentOffset(point, animated: false)
} else {
target = _isHorizontal ? _boundsWidth : _boundsHeight
let point = CGPoint(x: _isHorizontal ? target : 0, y: _isHorizontal ? 0 : target)
scrollView.setContentOffset(point, animated: false)
}
_displayView.snp.remakeConstraints({ (make) -> Void in
if _isHorizontal {
if target == _boundsWidth * 2 {
make.right.equalTo(scrollView)
} else {
make.left.equalTo(scrollView).offset(target)
}
make.top.bottom.equalTo(scrollView)
} else {
if target == _boundsHeight * 2 {
make.top.equalTo(scrollView).offset(_boundsHeight)
} else {
make.top.equalTo(scrollView).offset(target)
}
make.left.right.equalTo(scrollView)
}
make.width.height.equalTo(scrollView)
})
_backupView.snp.remakeConstraints({ (make) -> Void in
if _isHorizontal {
if target == _boundsWidth * 2 {
make.right.equalTo(_displayView.snp.left)
make.left.equalTo(scrollView).offset(_boundsWidth)
} else {
make.left.equalTo(_displayView.snp.right)
make.right.equalTo(scrollView)
}
make.top.bottom.equalTo(scrollView)
} else {
make.top.equalTo(_displayView.snp.bottom)
make.left.right.equalTo(scrollView)
make.bottom.equalTo(scrollView).offset(-target)
}
make.width.height.equalTo(scrollView)
})
scrollView.setNeedsLayout()
ss_delegate?.pageView(self, didScrollToView: _display)
addDisplayNextTask()
}
}
//MARK:- Private Function
private extension SSPageViewController {
func setup() {
view.backgroundColor = UIColor.white
initializeSegment()
initializeScrollview()
initializeIndicator()
}
func initializeScrollview() {
view.addSubview(scrollView)
scrollView.addSubview(_displayView)
scrollView.addSubview(_backupView)
_displayView.snp.makeConstraints { (make) -> Void in
make.top.left.bottom.height.width.equalTo(scrollView)
}
_backupView.snp.makeConstraints { (make) -> Void in
make.width.height.equalTo(scrollView)
if _isHorizontal {
make.top.bottom.equalTo(scrollView)
make.left.equalTo(_displayView.snp.right)
make.right.equalTo(scrollView).offset(-_boundsWidth)
} else {
make.left.right.equalTo(scrollView)
make.top.equalTo(_displayView.snp.bottom)
make.bottom.equalTo(scrollView).offset(-_boundsHeight)
}
}
scrollView.snp.makeConstraints { (make) -> Void in
make.top.equalTo(segment.snp.bottom)
make.left.bottom.right.equalTo(view)
}
_isHorizontal ? (scrollView.alwaysBounceHorizontal = true) : (scrollView.alwaysBounceVertical = true)
let factorX: CGFloat = _isHorizontal ? 3 : 1
let factorY: CGFloat = _isHorizontal ? 1 : 3
scrollView.contentSize = CGSize(width: _boundsWidth * factorX, height: _boundsHeight * factorY)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.backgroundColor = UIColor.white
scrollView.isPagingEnabled = true
scrollView.delegate = self
}
func initializeSegment() {
view.addSubview(segment)
segment.snp.makeConstraints { (make) -> Void in
make.top.left.right.equalTo(view)
make.height.equalTo(0)
}
}
func initializeIndicator() {
view.addSubview(indicator)
indicator.isHidden = true
configureIndicator()
}
func configureIndicator() {
if !_isHorizontal {
indicator.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI * 90 / 180.0))
}
indicator.sizeToFit()
var inset = UIEdgeInsets.zero
switch indicatorAlignStyle {
case .left: _isHorizontal ? (inset.left = 10) : (inset.top = 10)
case .right: _isHorizontal ? (inset.right = 10) : (inset.bottom = 10)
default: break
}
if _isHorizontal { inset.bottom = 10 }
else { inset.right = 10 }
indicator.snp.removeConstraints()
indicator.snp.makeConstraints { (make) -> Void in
if _isHorizontal {
make.bottom.equalTo(inset.bottom)
if inset.left != 0 { make.left.equalTo(inset.left) }
if inset.right != 0 { make.right.equalTo(inset.right) }
if indicatorAlignStyle == .center {
make.right.left.equalTo(indicator.superview!)
}
} else {
make.right.equalTo(inset.right)
if inset.top != 0 { make.top.equalTo(inset.top) }
if inset.bottom != 0 { make.bottom.equalTo(inset.bottom) }
if indicatorAlignStyle == .center {
make.top.bottom.equalTo(indicator.superview!)
}
}
}
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.view.setNeedsLayout()
})
}
func customConfigurationDone() {
let hideAndStall = !(_display.ss_nextId == nil && _display.ss_previousId == nil)
if showsIndicator { indicator.isHidden = hideAndStall }
scrollView.isScrollEnabled = hideAndStall
_displayView.snp.removeConstraints()
_backupView.snp.removeConstraints()
let hasPrevious = _display.ss_previousId != nil
_displayView.snp.remakeConstraints { (make) -> Void in
if hasPrevious {
if _isHorizontal {
make.top.bottom.equalTo(scrollView)
make.left.equalTo(scrollView).offset(_boundsWidth)
} else {
make.top.equalTo(scrollView).offset(_boundsHeight)
make.left.right.equalTo(scrollView)
}
make.width.height.equalTo(scrollView)
} else {
make.top.left.bottom.height.width.equalTo(scrollView)
}
}
_backupView.snp.remakeConstraints { (make) -> Void in
make.width.height.equalTo(scrollView)
if _isHorizontal {
make.top.bottom.equalTo(scrollView)
make.left.equalTo(_displayView.snp.right)
make.right.equalTo(scrollView).offset(hasPrevious ? 0 : -_boundsWidth)
} else {
make.left.right.equalTo(scrollView)
make.top.equalTo(_displayView.snp.bottom)
make.bottom.equalTo(scrollView).offset(hasPrevious ? 0 : -_boundsHeight)
}
}
let point = hasPrevious ? CGPoint(x: _isHorizontal ? _boundsWidth : 0, y: _isHorizontal ? 0 : _boundsHeight) : CGPoint.zero
scrollView.setContentOffset(point, animated: false)
view.setNeedsLayout()
}
func addDisplayNextTask() {
SSCancelableTaskManager.cancel(_task)
if loopInterval == 0 || (_display.ss_nextId == nil && _display.ss_previousId == nil) { return }
_task = SSCancelableTaskManager.delay(loopInterval, work: { [weak self]() -> Void in
guard let sself = self else { return }
let x = sself._isHorizontal ? sself.scrollView.contentOffset.x + sself._boundsWidth: 0
let y = sself._isHorizontal ? 0 : sself.scrollView.contentOffset.y + sself._boundsHeight
sself.scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true)
})
}
}
//MARK:-
//MARK:- SSPageViewContentProtocol
/// SSPageViewContentProtocol
public protocol SSPageViewContentProtocol {
var ss_identifer: String { get }
var ss_previousId: String? { get }
var ss_nextId: String? { get }
var ss_content: UIView { get }
init()
}
private func == (lhs: SSPageViewContentProtocol, rhs: SSPageViewContentProtocol) -> Bool {
return lhs.ss_identifer == rhs.ss_identifer
}
//MARK:-
//MARK:- SSPageViewDelegateProtocol
/// SSPageViewDelegateProtocol
public protocol SSPageViewDelegate: class {
associatedtype Template: SSPageViewContentProtocol
func pageView(_ pageView: SSPageViewController<Template, Self>, configureForView view: Template, afterView: Template)
func pageView(_ pageView: SSPageViewController<Template, Self>, configureForView view: Template, beforeView: Template)
func pageView(_ pageView: SSPageViewController<Template, Self>, didScrollToView view: Template)
}
//MARK:- Help
private extension NSRange {
func contain(_ number: CGFloat) -> Bool {
let target = Int(number)
return location <= target && target <= length
}
}
//MARK:- CancelableTaskManager
typealias SSCancelableTask = (_ cancel: Bool) -> Void
struct SSCancelableTaskManager {
static func delay(_ time: TimeInterval, work: @escaping ()->()) -> SSCancelableTask? {
var finalTask: SSCancelableTask?
let cancelableTask: SSCancelableTask = { cancel in
if cancel {
finalTask = nil // key
} else {
DispatchQueue.main.async(execute: work)
}
}
finalTask = cancelableTask
DispatchQueue.main.asyncAfter(deadline: .now() + time ) {
if let task = finalTask { task(false) }
}
return finalTask
}
static func cancel(_ cancelableTask: SSCancelableTask?) {
cancelableTask?(true)
}
}
| mit | 127362e61e20a0da22d687a601d11309 | 31.084359 | 187 | 0.704262 | 3.662187 | false | false | false | false |
marty-suzuki/FluxCapacitor | Examples/Flux+MVVM/FluxCapacitorSample/Sources/UI/Favorite/FavoriteViewModel.swift | 1 | 1939 | //
// FavoriteViewModel.swift
// FluxCapacitorSample
//
// Created by marty-suzuki on 2017/08/20.
// Copyright © 2017年 marty-suzuki. All rights reserved.
//
import Foundation
import RxSwift
import FluxCapacitor
import GithubKit
final class FavoriteViewModel {
private let action: RepositoryAction
private let store: RepositoryStore
private let disposeBag = DisposeBag()
let reloadData: Observable<Void>
private let _reloadData = PublishSubject<Void>()
let showRepository: Observable<Void>
private let _showRepository = PublishSubject<Void>()
let favorites: Constant<[Repository]>
init(action: RepositoryAction = .init(),
store: RepositoryStore = .instantiate(),
viewDidAppear: Observable<Void>,
viewDidDisappear: Observable<Void>,
selectRepositoryRowAt: Observable<IndexPath>) {
self.store = store
self.action = action
self.favorites = store.favorites
self.reloadData = _reloadData
self.showRepository = _showRepository
let selectedRepository = store.selectedRepository.asObservable()
.filter { $0 != nil }
.map { _ in }
Observable.merge(viewDidAppear.map { _ in true },
viewDidDisappear.map { _ in false })
.flatMapLatest { $0 ? selectedRepository : .empty() }
.bind(to: _showRepository)
.disposed(by: disposeBag)
selectRepositoryRowAt
.withLatestFrom(store.favorites.asObservable()) { $1[$0.row] }
.subscribe(onNext: { [weak self] in
self?.action.invoke(.selectedRepository($0))
})
.disposed(by: disposeBag)
store.favorites.asObservable()
.map { _ in }
.bind(to: _reloadData)
.disposed(by: disposeBag)
}
deinit {
store.clear()
}
}
| mit | f96b4bdc62d2efde9b78dc6acb54ed63 | 29.730159 | 74 | 0.606405 | 4.84 | false | false | false | false |
C4Framework/C4iOS | C4/UI/Movie.swift | 2 | 9439 | // Copyright © 2014 C4
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import UIKit
import AVFoundation
///This document describes the Movie class. You use a Movie object to implement the playback of video files, it encapulates an AVQueuePlayer object which handles the loading and control of assets.
///
///The Movie class is meant to simplify the addition of videos to your application. It is also a subclass of View, and so has all the common animation, interaction and notification capabilities.
///
///A C4Movie’s resizing behaviour is to map itself to the edges of its visible frame. This functionality implicitly uses AVLayerVideoGravityResize as its layer’s default gravity. You can change the frame of the movie from an arbitrary shape back to its original proportion by using its originalSize, originalRatio, or by independently setting either its width or height properties.
public class Movie: View {
var filename: String!
var player: AVQueuePlayer?
var currentItem: AVPlayerItem?
var reachedEndAction: (() -> Void)?
/// Assigning a value of true to this property will cause the receiver to loop at the end of playback.
///
/// The default value of this property is `true`.
public var loops: Bool = true
/// Mute/Unmute the audio track.
///
/// The default value of this property is `false`.
public var muted: Bool {
get {
guard let p = player else {
return false
}
return p.isMuted
}
set {
player?.isMuted = newValue
}
}
/// A variable that provides access to the width of the receiver. Animatable.
/// The default value of this property is defined by the movie being created.
/// Assigning a value to this property causes the receiver to change the width of its frame. If the receiver's
/// `contrainsProportions` variable is set to `true` the receiver's height will change to match the new width.
public override var width: Double {
get {
return Double(view.frame.size.width)
} set(val) {
var newSize = Size(val, height)
if constrainsProportions {
newSize.height = val * height / width
}
var rect = self.frame
rect.size = newSize
self.frame = rect
}
}
/// A variable that provides access to the height of the receiver. Animatable.
/// The default value of this property is defined by the movie being created.
/// Assigning a value to this property causes the receiver to change the height of its frame. If the receiver's
/// `contrainsProportions` variable is set to `true` the receiver's width will change to match the new height.
public override var height: Double {
get {
return Double(view.frame.size.height)
} set(val) {
var newSize = Size(Double(view.frame.size.width), val)
if constrainsProportions {
let ratio = Double(self.size.width / self.size.height)
newSize.width = val * ratio
}
var rect = self.frame
rect.size = newSize
self.frame = rect
}
}
/// Assigning a value of true to this property will cause the receiver to scale its entire frame whenever its `width` or
/// `height` variables are set.
/// The default value of this property is `true`.
public var constrainsProportions: Bool = true
/// The original size of the receiver when it was initialized.
public internal(set) var originalSize: Size = Size(1, 1)
/// The original width/height ratio of the receiver when it was initialized.
public var originalRatio: Double {
return originalSize.width / originalSize.height
}
var movieLayer: PlayerLayer {
return self.movieView.movieLayer
}
var movieView: MovieView {
return self.view as! MovieView // swiftlint:disable:this force_cast
}
public var playing: Bool {
return player?.rate != 0.0
}
class MovieView: UIView {
var movieLayer: PlayerLayer {
return self.layer as! PlayerLayer // swiftlint:disable:this force_cast
}
override class var layerClass: AnyClass {
return PlayerLayer.self
}
}
/// The current rotation value of the view. Animatable.
/// - returns: A Double value representing the cumulative rotation of the view, measured in Radians.
public override var rotation: Double {
get {
if let number = movieLayer.value(forKeyPath: Layer.rotationKey) as? NSNumber {
return number.doubleValue
}
return 0.0
}
set {
movieLayer.setValue(newValue, forKeyPath: Layer.rotationKey)
}
}
/// Initializes a new Movie using the specified filename from the bundle (i.e. your project).
///
/// - parameter filename: The name of the movie file included in your project.
public convenience init?(_ filename: String) {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print("Couldn't set up AVAudioSession")
}
guard let url = Bundle.main.url(forResource: filename, withExtension: nil) else {
print("Couldn't retrieve url for: \(filename)")
return nil
}
let asset = AVAsset(url: url)
let tracks = asset.tracks(withMediaType: AVMediaType.video)
let movieTrack = tracks[0]
self.init(frame: Rect(0, 0, Double(movieTrack.naturalSize.width), Double(movieTrack.naturalSize.height)))
self.filename = filename
//initialize player with item
let newPlayer = AVQueuePlayer(playerItem: AVPlayerItem(asset: asset))
newPlayer.actionAtItemEnd = .pause
currentItem = newPlayer.currentItem
player = newPlayer
//runs an overrideable method for handling the end of the movie
on(event: NSNotification.Name.AVPlayerItemDidPlayToEndTime) {
self.handleReachedEnd()
}
//movie view's player
movieLayer.player = player
movieLayer.videoGravity = AVLayerVideoGravity.resize
originalSize = self.size
// unmute
muted = false
}
/// Initializes a new Movie using the specified frame.
///
/// - parameter frame: The frame of the new movie object.
public override init(frame: Rect) {
super.init()
self.view = MovieView(frame: CGRect(frame))
}
public convenience init?(copy original: Movie) {
self.init(original.filename)
self.frame = original.frame
copyViewStyle(original)
}
/// Begins playback of the current item.
///
/// This is the same as setting rate to 1.0.
public func play() {
guard let p = player else {
print("The current movie's player is not properly initialized")
return
}
p.play()
}
/// Pauses playback.
///
/// This is the same as setting rate to 0.0.
public func pause() {
guard let p = player else {
print("The current movie's player is not properly initialized")
return
}
p.pause()
}
/// Stops playback.
///
/// This is the same as setting rate to 0.0 and resetting the current time to 0.
public func stop() {
guard let p = player else {
print("The current movie's player is not properly initialized")
return
}
p.seek(to: CMTimeMake(0, 1))
p.pause()
}
/// The action to perform at the end of playback.
///
/// - parameter action: A block of code to execute at the end of playback.
public func reachedEnd(_ action: (() -> Void)?) {
reachedEndAction = action
}
/// Called at the end of playback (i.e. when the movie reaches its end).
///
/// You can override this function to add your own custom actions.
///
/// By default, the movie should loop then the method calls `stop()` and `play()`.
func handleReachedEnd() {
if self.loops {
self.stop()
self.play()
}
reachedEndAction?()
}
}
| mit | 33273d3ac2ae99b9e4e61ec7558d311a | 36.585657 | 381 | 0.641615 | 4.757438 | false | false | false | false |
shorlander/firefox-ios | Account/FirefoxAccountConfiguration.swift | 3 | 7899 | /* 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
public enum FirefoxAccountConfigurationLabel: String {
case latestDev = "LatestDev"
case stableDev = "StableDev"
case stage = "Stage"
case production = "Production"
case chinaEdition = "ChinaEdition"
public func toConfiguration() -> FirefoxAccountConfiguration {
switch self {
case .latestDev: return LatestDevFirefoxAccountConfiguration()
case .stableDev: return StableDevFirefoxAccountConfiguration()
case .stage: return StageFirefoxAccountConfiguration()
case .production: return ProductionFirefoxAccountConfiguration()
case .chinaEdition: return ChinaEditionFirefoxAccountConfiguration()
}
}
}
/**
* In the URLs below, service=sync ensures that we always get the keys with signin messages,
* and context=fx_ios_v1 opts us in to the Desktop Sync postMessage interface.
*/
public protocol FirefoxAccountConfiguration {
init()
var label: FirefoxAccountConfigurationLabel { get }
/// A Firefox Account exists on a particular server. The auth endpoint should speak the protocol documented at
/// https://github.com/mozilla/fxa-auth-server/blob/02f88502700b0c5ef5a4768a8adf332f062ad9bf/docs/api.md
var authEndpointURL: URL { get }
/// The associated oauth server should speak the protocol documented at
/// https://github.com/mozilla/fxa-oauth-server/blob/6cc91e285fc51045a365dbacb3617ef29093dbc3/docs/api.md
var oauthEndpointURL: URL { get }
var profileEndpointURL: URL { get }
/// The associated content server should speak the protocol implemented (but not yet documented) at
/// https://github.com/mozilla/fxa-content-server/blob/161bff2d2b50bac86ec46c507e597441c8575189/app/scripts/models/auth_brokers/fx-desktop.js
var signInURL: URL { get }
var settingsURL: URL { get }
var forceAuthURL: URL { get }
var sync15Configuration: Sync15Configuration { get }
var pushConfiguration: PushConfiguration { get }
}
public struct LatestDevFirefoxAccountConfiguration: FirefoxAccountConfiguration {
public init() {
}
public let label = FirefoxAccountConfigurationLabel.latestDev
public let authEndpointURL = URL(string: "https://latest.dev.lcip.org/auth/v1")!
public let oauthEndpointURL = URL(string: "https://oauth-latest.dev.lcip.org")!
public let profileEndpointURL = URL(string: "https://latest.dev.lcip.org/profile")!
public let signInURL = URL(string: "https://latest.dev.lcip.org/signin?service=sync&context=fx_ios_v1")!
public let settingsURL = URL(string: "https://latest.dev.lcip.org/settings?context=fx_ios_v1")!
public let forceAuthURL = URL(string: "https://latest.dev.lcip.org/force_auth?service=sync&context=fx_ios_v1")!
public let sync15Configuration: Sync15Configuration = StageSync15Configuration()
public let pushConfiguration: PushConfiguration = FennecPushConfiguration()
}
public struct StableDevFirefoxAccountConfiguration: FirefoxAccountConfiguration {
public init() {
}
public let label = FirefoxAccountConfigurationLabel.stableDev
public let authEndpointURL = URL(string: "https://stable.dev.lcip.org/auth/v1")!
public let oauthEndpointURL = URL(string: "https://oauth-stable.dev.lcip.org")!
public let profileEndpointURL = URL(string: "https://stable.dev.lcip.org/profile")!
public let signInURL = URL(string: "https://stable.dev.lcip.org/signin?service=sync&context=fx_ios_v1")!
public let settingsURL = URL(string: "https://stable.dev.lcip.org/settings?context=fx_ios_v1")!
public let forceAuthURL = URL(string: "https://stable.dev.lcip.org/force_auth?service=sync&context=fx_ios_v1")!
public let sync15Configuration: Sync15Configuration = StageSync15Configuration()
public let pushConfiguration: PushConfiguration = FennecPushConfiguration()
}
public struct StageFirefoxAccountConfiguration: FirefoxAccountConfiguration {
public init() {
}
public let label = FirefoxAccountConfigurationLabel.stage
public let authEndpointURL = URL(string: "https://api-accounts.stage.mozaws.net/v1")!
public let oauthEndpointURL = URL(string: "https://oauth.stage.mozaws.net/v1")!
public let profileEndpointURL = URL(string: "https://profile.stage.mozaws.net/v1")!
public let signInURL = URL(string: "https://accounts.stage.mozaws.net/signin?service=sync&context=fx_ios_v1")!
public let settingsURL = URL(string: "https://accounts.stage.mozaws.net/settings?context=fx_ios_v1")!
public let forceAuthURL = URL(string: "https://accounts.stage.mozaws.net/force_auth?service=sync&context=fx_ios_v1")!
public let sync15Configuration: Sync15Configuration = StageSync15Configuration()
public var pushConfiguration: PushConfiguration {
get {
#if MOZ_CHANNEL_RELEASE
return FirefoxStagingPushConfiguration()
#elseif MOZ_CHANNEL_BETA
return FirefoxBetaStagingPushConfiguration()
#elseif MOZ_CHANNEL_FENNEC
return FennecStagingPushConfiguration()
#endif
}
}
}
public struct ProductionFirefoxAccountConfiguration: FirefoxAccountConfiguration {
public init() {
}
public let label = FirefoxAccountConfigurationLabel.production
public let authEndpointURL = URL(string: "https://api.accounts.firefox.com/v1")!
public let oauthEndpointURL = URL(string: "https://oauth.accounts.firefox.com/v1")!
public let profileEndpointURL = URL(string: "https://profile.accounts.firefox.com/v1")!
public let signInURL = URL(string: "https://accounts.firefox.com/signin?service=sync&context=fx_ios_v1")!
public let settingsURL = URL(string: "https://accounts.firefox.com/settings?context=fx_ios_v1")!
public let forceAuthURL = URL(string: "https://accounts.firefox.com/force_auth?service=sync&context=fx_ios_v1")!
public let sync15Configuration: Sync15Configuration = ProductionSync15Configuration()
public let pushConfiguration: PushConfiguration = FirefoxPushConfiguration()
}
public struct ChinaEditionFirefoxAccountConfiguration: FirefoxAccountConfiguration {
public init() {
}
public let label = FirefoxAccountConfigurationLabel.chinaEdition
public let authEndpointURL = URL(string: "https://api-accounts.firefox.com.cn/v1")!
public let oauthEndpointURL = URL(string: "https://oauth.firefox.com.cn/v1")!
public let profileEndpointURL = URL(string: "https://profile.firefox.com.cn/v1")!
public let signInURL = URL(string: "https://accounts.firefox.com.cn/signin?service=sync&context=fx_ios_v1")!
public let settingsURL = URL(string: "https://accounts.firefox.com.cn/settings?context=fx_ios_v1")!
public let forceAuthURL = URL(string: "https://accounts.firefox.com.cn/force_auth?service=sync&context=fx_ios_v1")!
public let sync15Configuration: Sync15Configuration = ChinaEditionSync15Configuration()
public let pushConfiguration: PushConfiguration = FirefoxPushConfiguration()
}
public struct ChinaEditionSync15Configuration: Sync15Configuration {
public init() {
}
public let tokenServerEndpointURL = URL(string: "https://sync.firefox.com.cn/token/1.0/sync/1.5")!
}
public protocol Sync15Configuration {
init()
var tokenServerEndpointURL: URL { get }
}
public struct ProductionSync15Configuration: Sync15Configuration {
public init() {
}
public let tokenServerEndpointURL = URL(string: "https://token.services.mozilla.com/1.0/sync/1.5")!
}
public struct StageSync15Configuration: Sync15Configuration {
public init() {
}
public let tokenServerEndpointURL = URL(string: "https://token.stage.mozaws.net/1.0/sync/1.5")!
}
| mpl-2.0 | bfd780b91d2f8eeebc94b63913a5803d | 41.929348 | 145 | 0.737055 | 4.063272 | false | true | false | false |
jindulys/EbloVaporServer | Sources/App/Services/BlogCrawling/BlogCrawlingService.swift | 1 | 6718 | //
// BlogCrawlingService.swift
// EbloVaporServer
//
// Created by yansong li on 2017-04-28.
//
//
import Foundation
/// The service to start a blog crawling.
class BlogCrawlingService {
/// The crawledblogs.
var crawledBlog: [Blog] = []
/// The blogParsers.
private var blogParsers: [BlogParser] = []
/// Whether or not automatically save crawled blog when crawling finishes.
private var automaticallySaveWhenCrawlingFinished = false
/// Whether or not blog crawling has finished.
var crawlingFinished: Bool = false {
didSet {
if (crawlingFinished && !oldValue) && automaticallySaveWhenCrawlingFinished {
// Add in a test yelp blog
// let testBlog = Blog(title: "Hoooooool lllll",
// urlString: "http://yelp.com/test",
// companyName: "Yelp")
// testBlog.publishDate = "May, 27, 2017"
// testBlog.publishDateInterval = Date().timeIntervalSince1970
// self.crawledBlog.append(testBlog)
self.saveCrawledBlog()
}
}
}
/// Start service
func startService(automaticallySaveWhenCrawlingFinished: Bool) {
crawlingFinished = false
var url: URL? = nil
#if os(OSX)
// NOTE: If you want to use local file, you need to add in `SupportingFiles`
// Folder to your workspace, and add in `company.json`, `newCompany.json`
// You also need to add them to `Copy Files` build phases of `App` target.
if EnviromentManager.local {
let resourceName = EnviromentManager.newCompany ? "newCompany" : "company"
let urlPath = Bundle.main.path(forResource: resourceName, ofType: "json")
url = NSURL.fileURL(withPath: urlPath!)
}
#endif
if url == nil {
url = URL(string: "https://api.myjson.com/bins/ztmnh")
}
self.automaticallySaveWhenCrawlingFinished = automaticallySaveWhenCrawlingFinished
guard let data = try? Data(contentsOf: url!) else {
print("\(self) can not load data from URL \(url!)")
return
}
do {
let json =
try JSONSerialization.jsonObject(with: data,
options: [.mutableContainers, .allowFragments])
guard let jsonData = json as? [String: Any],
let companies = jsonData["company"] as? [[String: Any]] else {
return
}
/// The current existed companies.
var existingCompaniesDict: [String : Company] = [:]
do {
let existingCompanies = try Company.all()
existingCompanies.forEach { company in
existingCompaniesDict[company.string()] = company
}
} catch {
print("Can not load Company from data base.")
}
for companyInfo in companies {
// Create blog parsers.
if let titlePath = companyInfo["title"] as? String,
let href = companyInfo["href"] as? String,
let baseURL = companyInfo["baseURL"] as? String,
let basedOnBase = companyInfo["basedOnBase"] as? Bool,
let companyName = companyInfo["name"] as? String {
// Create company instance.
var company = Company(companyName: companyName, companyUrlString: baseURL)
var newCompany = false
// Check whether this company exist or not, set company to correct value.
if let exist = existingCompaniesDict[company.string()],
company.companyUrlString == exist.companyUrlString {
company = exist
} else {
newCompany = true
// Use the new information of a company.
var toSave = company
if let exist = existingCompaniesDict[company.string()] {
// If we already have existing one, update existing one's info.
exist.companyUrlString = company.companyUrlString
toSave = exist
}
do {
try toSave.save()
existingCompaniesDict[toSave.string()] = toSave
company = toSave
} catch {
print("Some Error \(error)")
}
}
let articleInfo = ArticleInfoPath(title: titlePath,
href: href,
authorName: companyInfo["author"] as? String,
authorAvatar: companyInfo["authorAvatar"] as? String,
publishDate: companyInfo["date"] as? String)
let metaInfo = BlogMetaInfo(nextPageXPath: companyInfo["nextPage"] as? String,
needRemoveExtraBlog: companyInfo["needRemoveRepeatBlog"] as? Bool,
needRemoveEndSlash: companyInfo["needRemoveEndSlash"] as? Bool)
if let _ = company.id {
//print("--- create valid parser for company: \(company.companyName) id: \(validCompanyID).")
let companyParser = BlogParser(baseURLString: baseURL,
articlePath: articleInfo,
metaData: metaInfo,
companyName: companyName,
basedOnBaseURL: basedOnBase,
company: company,
fetchAllBlogs: newCompany)
self.blogParsers.append(companyParser)
}
}
}
self.blogParsers.forEach { parser in
parser.parse { finished in
self.crawledBlog.append(contentsOf: parser.blogs)
self.checkCrawlingStatus()
}
}
} catch {
print(error)
}
}
/// Save crawled blogs.
func saveCrawledBlog() {
if self.crawlingFinished {
do {
let existingBlogs = try Blog.all()
let existingIdentifiers = existingBlogs.map { blog in
return blog.string()
}
self.crawledBlog.forEach { blog in
if existingIdentifiers.contains(blog.string()) {
return
}
print("This blog does not exist in our data base\(blog.string())")
var toSave = blog
do {
try toSave.save()
} catch {
print("Some Error \(error)")
}
}
} catch {
print("Can not load Blogs from data base.")
}
} else {
print("BlogCrawlingService not finish yet.")
}
self.automaticallySaveWhenCrawlingFinished = false
}
private func checkCrawlingStatus() {
self.crawlingFinished =
self.blogParsers.filter { $0.finished == false }.count == 0
}
}
| mit | d45c772544f0a12e00e145f1a2786a1d | 35.313514 | 105 | 0.560286 | 4.704482 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Models/Notifications/Actions/ApproveComment.swift | 1 | 1969 | /// Encapsulates logic to approve a comment
class ApproveComment: DefaultNotificationActionCommand {
enum TitleStrings {
static let approve = NSLocalizedString("Approve Comment", comment: "Approves a Comment")
static let unapprove = NSLocalizedString("Unapprove Comment", comment: "Unapproves a Comment")
}
enum TitleHints {
static let approve = NSLocalizedString("Approves the Comment.", comment: "VoiceOver accessibility hint, informing the user the button can be used to approve a comment")
static let unapprove = NSLocalizedString("Unapproves the Comment.", comment: "VoiceOver accessibility hint, informing the user the button can be used to unapprove a comment")
}
override var actionTitle: String {
return on ? TitleStrings.unapprove : TitleStrings.approve
}
override var actionColor: UIColor {
return on ? .neutral(.shade30) : .primary
}
override func execute<ObjectType: FormattableContent>(context: ActionContext<ObjectType>) {
guard let block = context.block as? FormattableCommentContent else {
super.execute(context: context)
return
}
if on {
unApprove(block: block)
} else {
approve(block: block)
}
}
private func unApprove(block: FormattableCommentContent) {
ReachabilityUtils.onAvailableInternetConnectionDo {
actionsService?.unapproveCommentWithBlock(block, completion: { [weak self] success in
if success {
self?.on.toggle()
}
})
}
}
private func approve(block: FormattableCommentContent) {
ReachabilityUtils.onAvailableInternetConnectionDo {
actionsService?.approveCommentWithBlock(block, completion: { [weak self] success in
if success {
self?.on.toggle()
}
})
}
}
}
| gpl-2.0 | 46d38684f7e6ae70dbbe0daf9c0f4571 | 36.865385 | 182 | 0.637887 | 5.336043 | false | false | false | false |
acrocat/EverLayout | Source/Resolvers/UIView+PropertyMappable.swift | 1 | 4559 | // EverLayout
//
// Copyright (c) 2017 Dale Webster
//
// 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
/*
Behaviour of UIView when properties are mapped to from it
*/
extension UIView : FrameMappable {
@objc func mapFrame(_ frame: String) {
self.frame = CGRectFromString(frame)
}
@objc func getMappedFrame() -> String? {
return NSStringFromCGRect(self.frame) as String
}
}
extension UIView : BackgroundColorMappable {
@objc func mapBackgroundColor(_ color: String) {
self.backgroundColor = UIColor.color(fromName: color) ?? UIColor(hex: color) ?? .clear
}
@objc func getMappedBackgroundColor() -> String? {
return UIColor.name(ofColor: self.backgroundColor ?? .clear)
}
}
extension UIView : HiddenMappable {
@objc func mapHidden(_ hidden: String) {
self.isHidden = (hidden.lowercased() == "true")
}
@objc func getMappedHidden() -> String? {
return self.isHidden ? "true" : "false"
}
}
extension UIView : CornerRadiusMappable {
@objc func mapCornerRadius(_ cornerRadius: String) {
self.layer.cornerRadius = cornerRadius.toCGFloat() ?? 0
}
@objc func getMappedCornerRadius() -> String? {
return self.layer.cornerRadius.description
}
}
extension UIView : BorderWidthMappable {
@objc func mapBorderWidth(_ borderWidth: String) {
self.layer.borderWidth = borderWidth.toCGFloat() ?? 0
}
@objc func getMappedBorderWidth() -> String? {
return self.layer.borderWidth.description
}
}
extension UIView : BorderColorMappable {
@objc func mapBorderColor(_ borderColor: String) {
self.layer.borderColor = UIColor.color(fromName: borderColor)?.cgColor ?? UIColor(hex: borderColor)?.cgColor
}
@objc func getMappedBorderColor() -> String? {
guard let borderColor = self.layer.borderColor else { return nil }
return UIColor.name(ofColor: UIColor(cgColor: borderColor))
}
}
extension UIView : AlphaMappable {
@objc func mapAlpha(_ alpha: String) {
self.alpha = alpha.toCGFloat() ?? 1
}
@objc func getMappedAlpha() -> String? {
return self.alpha.description
}
}
extension UIView : ClipBoundsMappable {
@objc func mapClipToBounds(_ clipToBounds: String) {
self.clipsToBounds = (clipToBounds.lowercased() == "true")
}
@objc func getMappedClipToBounds() -> String? {
return self.clipsToBounds ? "true" : "false"
}
}
extension UIView : ContentModeMappable {
internal var contentModes : [String : UIViewContentMode] {
return [
"scaleToFill" : .scaleToFill,
"scaleAspectFit" : .scaleAspectFit,
"scaleAspectFill" : .scaleAspectFill,
"redraw" : .redraw,
"center" : .center,
"top" : .top,
"bottom" : .bottom,
"left" : .left,
"right" : .right,
"topLeft" : .topLeft,
"topRight" : .topRight,
"bottomLeft" : .bottomLeft,
"bottomRight" : .bottomRight
]
}
@objc func mapContentMode(_ contentMode: String) {
if let contentMode = self.contentModes[contentMode] {
self.contentMode = contentMode
}
}
@objc func getMappedContentMode() -> String? {
return self.contentModes.filter { (key , value) -> Bool in
return value == self.contentMode
}.first?.key
}
}
| mit | c6107431dbc5c51066216c7ab5260d91 | 33.022388 | 116 | 0.646852 | 4.452148 | false | false | false | false |
khoren93/SwiftHub | SwiftHub/Networking/GraphQL/Apollo+Rx.swift | 1 | 3539 | //
// Apollo+Rx.swift
// SwiftHub
//
// Created by Sygnoos9 on 3/9/19.
// Copyright © 2019 Khoren Markosyan. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Apollo
enum RxApolloError: Error {
case graphQLErrors([GraphQLError])
}
extension ApolloClient: ReactiveCompatible {}
extension Reactive where Base: ApolloClient {
func fetch<Query: GraphQLQuery>(query: Query,
cachePolicy: CachePolicy = .returnCacheDataElseFetch,
queue: DispatchQueue = DispatchQueue.main) -> Single<Query.Data> {
return Single.create { [weak base] single in
let cancellableToken = base?.fetch(query: query, cachePolicy: cachePolicy, contextIdentifier: nil, queue: queue, resultHandler: { (result) in
switch result {
case .success(let graphQLResult):
if let data = graphQLResult.data {
single(.success(data))
} else if let errors = graphQLResult.errors {
// GraphQL errors
single(.failure(RxApolloError.graphQLErrors(errors)))
}
case .failure(let error):
// Network or response format errors
single(.failure(error))
}
})
return Disposables.create {
cancellableToken?.cancel()
}
}
}
func watch<Query: GraphQLQuery>(query: Query,
cachePolicy: CachePolicy = .returnCacheDataElseFetch) -> Single<Query.Data> {
return Single.create { [weak base] single in
let cancellableToken = base?.watch(query: query, cachePolicy: cachePolicy, resultHandler: { (result) in
switch result {
case .success(let graphQLResult):
if let data = graphQLResult.data {
single(.success(data))
} else if let errors = graphQLResult.errors {
// GraphQL errors
single(.failure(RxApolloError.graphQLErrors(errors)))
}
case .failure(let error):
// Network or response format errors
single(.failure(error))
}
})
return Disposables.create {
cancellableToken?.cancel()
}
}
}
func perform<Mutation: GraphQLMutation>(mutation: Mutation,
queue: DispatchQueue = DispatchQueue.main) -> Single<Mutation.Data> {
return Single.create { [weak base] single in
let cancellableToken = base?.perform(mutation: mutation, queue: queue, resultHandler: { (result) in
switch result {
case .success(let graphQLResult):
if let data = graphQLResult.data {
single(.success(data))
} else if let errors = graphQLResult.errors {
// GraphQL errors
single(.failure(RxApolloError.graphQLErrors(errors)))
}
case .failure(let error):
// Network or response format errors
single(.failure(error))
}
})
return Disposables.create {
cancellableToken?.cancel()
}
}
}
}
| mit | 24b7a9d289ef43c919b5650706a97537 | 37.879121 | 153 | 0.516959 | 5.580442 | false | false | false | false |
balitm/Sherpany | Sherpany/AsyncDataProvider.swift | 1 | 2525 | //
// AsyncDataProvider.swift
// Sherpany
//
// Created by Balázs Kilvády on 3/4/16.
// Copyright © 2016 kil-dev. All rights reserved.
//
import Foundation
class AsyncDataProvider: DataProviderBase, DataProviderProtocol {
var indicatorDelegate: ModelNetworkIndicatorDelegate! = nil
private var _pendingTasks = 0
func setup(urls: DataURLs) {
URLRouter.setup(urls)
}
private func _processData<T>(url: NSURL, checkStatus: Bool = true, function: (data: NSData) -> T, finished: (data: T) -> Void) {
if checkStatus && status != Status.kNetFinished && status != Status.kNetNoop {
return
}
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
status = Status.kNetExecuting
assert(_pendingTasks >= 0)
if _pendingTasks == 0 {
indicatorDelegate?.show()
}
_pendingTasks += 1
print("> pending: \(_pendingTasks)")
dispatch_async(dispatch_get_global_queue(priority, 0), {
if let data = NSData(contentsOfURL: url) {
let result = function(data: data)
dispatch_sync(dispatch_get_main_queue()) {
finished(data: result)
self.status = Status.kNetFinished
self._pendingTasks -= 1
print("< pending: \(self._pendingTasks)")
assert(self._pendingTasks >= 0)
if self._pendingTasks == 0 {
self.indicatorDelegate?.hide()
}
}
} else {
self.status = Status.kNetNoHost
}
})
}
func processUsers(finished: (data: [UserData]?) -> Void) {
_processData(URLRouter.Users.url, function: self.dataProcessor.processUsers, finished: finished)
}
func processAlbums(finished: (data: [AlbumData]?) -> Void) {
_processData(URLRouter.Albums.url, function: self.dataProcessor.processAlbums, finished: finished)
}
func processPhotos(finished: (data: [PhotoData]?) -> Void) {
_processData(URLRouter.Photos.url, function: self.dataProcessor.processPhotos, finished: finished)
}
func processPicture(url: NSURL, finished: (data: NSData?) -> Void, progress: (Float) -> Void) {
_processData(url, checkStatus: false, function: self.dataProcessor.processPictureData, finished: finished)
}
func hasPendingTask() -> Bool {
assert(_pendingTasks >= 0)
return _pendingTasks > 0
}
} | mit | 243548d4c164c1a27687cd4dd4f69378 | 34.535211 | 132 | 0.591594 | 4.355786 | false | false | false | false |
radvansky-tomas/NutriFacts | nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Data/BubbleChartDataEntry.swift | 6 | 1224 | //
// BubbleDataEntry.swift
// Charts
//
// Bubble chart implementation:
// Copyright 2015 Pierre-Marc Airoldi
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class BubbleChartDataEntry: ChartDataEntry
{
/// The size of the bubble.
public var size = CGFloat(0.0)
/// :xIndex: The index on the x-axis.
/// :val: The value on the y-axis.
/// :size: The size of the bubble.
public init(xIndex: Int, value: Float, size: CGFloat)
{
super.init(value: value, xIndex: xIndex)
self.size = size
}
/// :xIndex: The index on the x-axis.
/// :val: The value on the y-axis.
/// :size: The size of the bubble.
/// :data: Spot for additional data this Entry represents.
public init(xIndex: Int, value: Float, size: CGFloat, data: AnyObject?)
{
super.init(value: value, xIndex: xIndex, data: data)
self.size = size
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = super.copyWithZone(zone) as! BubbleChartDataEntry;
copy.size = size;
return copy;
}
} | gpl-2.0 | f1d0806780fefed80ec61e447ed0db86 | 24.520833 | 75 | 0.607026 | 3.923077 | false | false | false | false |
piars777/TheMovieDatabaseSwiftWrapper | Sources/Models/TVMDB.swift | 1 | 9787 | //
// TVMDB.swift
// MDBSwiftWrapper
//
// Created by George on 2016-02-12.
// Copyright © 2016 GeorgeKye. All rights reserved.
//
//TODO: - tanslations
//
import Foundation
extension TVMDB{
///Get the primary information about a TV series by id.
public class func tv(api_key: String!, tvShowID: Int!, language: String?, completion: (clientReturn: ClientReturn, data: TVDetailedMDB?) -> ()) -> (){
Client.TV("\(tvShowID)", api_key: api_key, page: nil, language: language, timezone: nil){
apiReturn in
var data: TVDetailedMDB?
if(apiReturn.error == nil){
data = TVDetailedMDB.init(results: apiReturn.json!)
}
completion(clientReturn: apiReturn, data: data)
}
}
///Get the alternative titles for a specific show ID.
public class func alternativeTitles(api_key: String!, tvShowID: Int!, completion: (clientReturn: ClientReturn, data: Alternative_TitlesMDB?) -> ()) -> (){
Client.TV("\(tvShowID)/alternative_titles", api_key: api_key, page: nil, language: nil, timezone: nil){
apiReturn in
var data: Alternative_TitlesMDB?
if(apiReturn.error == nil){
data = Alternative_TitlesMDB.init(results: apiReturn.json!)
}
completion(clientReturn: apiReturn, data: data)
}
}
///Get the content ratings for a specific TV show id.
public class func content_ratings(api_key: String, tvShowID: Int, completion: (clientReturn: ClientReturn, data: [Content_RatingsMDB]?) -> ()) -> (){
Client.TV("\(tvShowID)/content_ratings", api_key: api_key, page: nil, language: nil, timezone: nil){
apiReturn in
var data: [Content_RatingsMDB]?
if(apiReturn.error == nil){
data = Content_RatingsMDB.initialize(json: apiReturn.json!["results"])
}
completion(clientReturn: apiReturn, data: data)
}
}
///Get the cast & crew information about a TV series. Just like the website, this information from the last season of the series.
public class func credits(api_key: String!, tvShowID: Int!, completion: (clientResult: ClientReturn, data: TVCreditsMDB?) -> ()) -> (){
Client.TV("\(tvShowID)/credits", api_key: api_key, page: nil, language: nil, timezone: nil){
apiReturn in
var data: TVCreditsMDB?
if(apiReturn.error == nil){
data = TVCreditsMDB.init(results: apiReturn.json!)
}
completion(clientResult: apiReturn, data: data)
}
}
//Get the external ids that we have stored for a TV series.
public class func externalIDS(api_key: String!, tvShowID: Int!, language: String, completion: (clientResult: ClientReturn, data: ExternalIdsMDB?) -> ()) -> (){
Client.TV("\(tvShowID)/external_ids", api_key: api_key, page: nil, language: language, timezone: nil){
apiReturn in
var data: ExternalIdsMDB?
if(apiReturn.error == nil){
data = ExternalIdsMDB.init(results: apiReturn.json!)
}
completion(clientResult: apiReturn, data: data)
}
}
///Get the images (posters and backdrops) for a TV series.
public class func images(api_key: String!, tvShowID: Int!, language: String?, completion: (clientResult: ClientReturn, data: ImagesMDB?) -> ()) -> (){
Client.TV("\(tvShowID)/images", api_key: api_key, page: nil, language: language, timezone: nil){
apiReturn in
var data: ImagesMDB?
if(apiReturn.error == nil){
data = ImagesMDB.init(results: apiReturn.json!)
}
completion(clientResult: apiReturn, data: data)
}
}
///Get the plot keywords for a specific TV show id.
public class func keywords(api_key: String, tvShowID: Int!, completion: (clientResult: ClientReturn, data: [KeywordsMDB]?) -> ()) -> (){
Client.TV("\(tvShowID)/keywords", api_key: api_key, page: nil, language: nil, timezone: nil){
apiReturn in
var data: [KeywordsMDB]?
if(apiReturn.error == nil){
data = KeywordsMDB.initialize(json: apiReturn.json!["results"])
}
completion(clientResult: apiReturn, data: data)
}
}
///Get the similar TV shows for a specific tv id.
public class func similar(api_key: String!, tvShowID: Int!, page: Int?, language: String?, completion: (clientResult: ClientReturn, data: [TVMDB]?) -> ()) -> (){
Client.TV("\(tvShowID)/similar", api_key: api_key, page: page, language: language, timezone: nil){
apiReturn in
var data: [TVMDB]?
if(apiReturn.error == nil){
if(apiReturn.json!["results"].count > 0){
data = TVMDB.initialize(json: apiReturn.json!["results"])
}
}
completion(clientResult: apiReturn, data: data)
}
}
///Get the list of translations that exist for a TV series. These translations cascade down to the episode level.
public class func translations(api_key: String!, tvShowID: Int!, completion: (clientReturn: ClientReturn, data: [TranslationsMDB]?) -> ()) -> (){
Client.TV("\(tvShowID)/translations", api_key: api_key, page: nil, language: nil, timezone: nil){
apiReturn in
var data: [TranslationsMDB]?
if(apiReturn.error == nil){
data = TranslationsMDB.initialize(json: apiReturn.json!["translations"])
}
completion(clientReturn: apiReturn, data: data)
}
}
///Get the videos that have been added to a TV series (trailers, opening credits, etc...)
public class func videos(api_key: String!, tvShowID: Int!, language: String?, completion: (clientReturn: ClientReturn, data: [VideosMDB]?) -> ()) -> (){
Client.TV("\(tvShowID)/videos", api_key: api_key, page: nil, language: language, timezone: nil){
apiReturn in
var data: [VideosMDB]?
if(apiReturn.error == nil){
data = VideosMDB.initialize(json: apiReturn.json!["results"])
}
completion(clientReturn: apiReturn, data: data)
}
}
///Get the latest TV show id.
public class func latest(api_key: String!, completion: (clientReturn: ClientReturn, data: TVDetailedMDB?) -> ()) -> (){
Client.TV("latest", api_key: api_key, page: nil, language: nil, timezone: nil){
apiReturn in
var data: TVDetailedMDB?
if(apiReturn.error == nil){
data = TVDetailedMDB.init(results: apiReturn.json!)
}
completion(clientReturn: apiReturn, data: data)
}
}
///Get the list of TV shows that are currently on the air. This query looks for any TV show that has an episode with an air date in the next 7 days.
public class func ontheair(api_key: String!, page: Int?, language: String?, completion: (clientResult: ClientReturn, data: [TVMDB]?) -> ()) -> (){
Client.TV("on_the_air", api_key: api_key, page: page, language: language, timezone: nil){
apiReturn in
var data: [TVMDB]?
if(apiReturn.error == nil){
if(apiReturn.json!["results"].count > 0){
data = TVMDB.initialize(json: apiReturn.json!["results"])
}
}
completion(clientResult: apiReturn, data: data)
}
}
///Get the list of TV shows that air today. Without a specified timezone, this query defaults to EST (Eastern Time UTC-05:00).
public class func airingtoday(api_key: String!, page: Int?, language: String?, timezone: String?, completion: (clientResult: ClientReturn, data: [TVMDB]?) -> ()) -> (){
Client.TV("airing_today", api_key: api_key, page: page, language: language, timezone: timezone){
apiReturn in
var data: [TVMDB]?
if(apiReturn.error == nil){
if(apiReturn.json!["results"].count > 0){
data = TVMDB.initialize(json: apiReturn.json!["results"])
}
}
completion(clientResult: apiReturn, data: data)
}
}
///Get the list of top rated TV shows. By default, this list will only include TV shows that have 2 or more votes. This list refreshes every day.
public class func toprated(api_key: String!, page: Int?, language: String?, completion: (clientResult: ClientReturn, data: [TVMDB]?) -> ()) -> (){
Client.TV("top_rated", api_key: api_key, page: page, language: language, timezone: nil){
apiReturn in
var data: [TVMDB]?
if(apiReturn.error == nil){
if(apiReturn.json!["results"].count > 0){
data = TVMDB.initialize(json: apiReturn.json!["results"])
}
}
completion(clientResult: apiReturn, data: data)
}
}
///Get the list of popular TV shows. This list refreshes every day.
public class func popular(api_key: String!, page: Int?, language: String?, completion: (clientResult: ClientReturn, data: [TVMDB]?) -> ()) -> (){
Client.TV("popular", api_key: api_key, page: page, language: language, timezone: nil){
apiReturn in
var data: [TVMDB]?
if(apiReturn.error == nil){
if(apiReturn.json!["results"].count > 0){
data = TVMDB.initialize(json: apiReturn.json!["results"])
}
}
completion(clientResult: apiReturn, data: data)
}
}
} | mit | 62ff9ac797806da8909f855b3444ec4c | 46.509709 | 172 | 0.584611 | 4.269634 | false | false | false | false |
MatthiasU/TimeKeeper | TimeKeeperTests/TimeKeeperModelTests.swift | 1 | 2050 | //
// TimeKeeperModelTests.swift
// TimeKeeper
//
// Created by Matthias Uttendorfer on 11/06/16.
// Copyright © 2016 Matthias Uttendorfer. All rights reserved.
//
import XCTest
@testable import TimeKeeper
class TimeKeeperModelTests: XCTestCase {
func testInit() {
// setup
let model: TimeKeeperModel
// execute
model = TimeKeeperModel(breakTimeInMinutes: 45)
// verify
XCTAssertEqual(model.breakTimeInMinutes, 45)
}
func testUpdateTime() {
// setup
let model = TimeKeeperModel()
// stub
let calendar = Calendar.current()
let startDate = calendar.startOfDay(for: Date())
model.startTime = startDate
model.currentTime = startDate.addingTimeInterval(2 * 3600) // adding two hours to start time
// execute
let time = model.timeDifference()
// verify
XCTAssertEqual(time.hours, 2)
XCTAssertEqual(time.minutes, 0)
}
func testUpdateTimeWithBreak() {
// setup
let model = TimeKeeperModel(breakTimeInMinutes: 30)
// stub
let calendar = Calendar.current()
let startDate = calendar.startOfDay(for: Date())
model.startTime = startDate
model.currentTime = startDate.addingTimeInterval(2 * 3600) // adding two hours to start time
// execute
let time = model.timeDifference()
// verify
XCTAssertEqual(time.hours, 1)
XCTAssertEqual(time.minutes, 30)
}
func testUpdateTimeWithBreakWhenBreakTimeWouldGetANegativeTime() {
// setup
let model = TimeKeeperModel(breakTimeInMinutes: 30)
// stub
let calendar = Calendar.current()
let startDate = calendar.startOfDay(for: Date())
model.startTime = startDate
model.currentTime = startDate.addingTimeInterval(15 * 60) // adding two hours to start time
// execute
let time = model.timeDifference()
// verify
XCTAssertEqual(time.hours, 0)
XCTAssertEqual(time.minutes, 0)
}
}
| gpl-3.0 | aeebe35966ddd0df168686c88a4a5f19 | 18.701923 | 96 | 0.638848 | 4.604494 | false | true | false | false |
johnno1962/eidolon | Kiosk/Observable+Operators.swift | 1 | 4310 | import RxSwift
extension Observable where Element: Equatable {
func ignore(value: Element) -> Observable<Element> {
return filter { (e) -> Bool in
return value != e
}
}
}
extension Observable {
// OK, so the idea is that I have a Variable that exposes an Observable and I want
// to switch to the latest without mapping.
//
// viewModel.flatMap { saleArtworkViewModel in return saleArtworkViewModel.lotNumber }
//
// Becomes...
//
// viewModel.flatMapTo(SaleArtworkViewModel.lotNumber)
//
// Still not sure if this is a good idea.
func flatMapTo<R>(selector: Element -> () -> Observable<R>) -> Observable<R> {
return self.map { (s) -> Observable<R> in
return selector(s)()
}.switchLatest()
}
}
protocol OptionalType {
typealias Wrapped
var value: Wrapped? { get }
}
extension Optional: OptionalType {
var value: Wrapped? {
return self
}
}
extension Observable where Element: OptionalType {
func filterNil() -> Observable<Element.Wrapped> {
return flatMap { (element) -> Observable<Element.Wrapped> in
if let value = element.value {
return .just(value)
} else {
return .empty()
}
}
}
func replaceNilWith(nilValue: Element.Wrapped) -> Observable<Element.Wrapped> {
return flatMap { (element) -> Observable<Element.Wrapped> in
if let value = element.value {
return .just(value)
} else {
return .just(nilValue)
}
}
}
}
extension Observable {
func doOnNext(closure: Element -> Void) -> Observable<Element> {
return doOn { (event: Event) in
switch event {
case .Next(let value):
closure(value)
default: break
}
}
}
func doOnCompleted(closure: () -> Void) -> Observable<Element> {
return doOn { (event: Event) in
switch event {
case .Completed:
closure()
default: break
}
}
}
func doOnError(closure: ErrorType -> Void) -> Observable<Element> {
return doOn { (event: Event) in
switch event {
case .Error(let error):
closure(error)
default: break
}
}
}
}
private let backgroundScheduler = SerialDispatchQueueScheduler(globalConcurrentQueueQOS: .Default)
extension Observable {
func mapReplace<T>(value: T) -> Observable<T> {
return map { _ -> T in
return value
}
}
func dispatchAsyncMainScheduler() -> Observable<E> {
return self.observeOn(backgroundScheduler).observeOn(MainScheduler.instance)
}
}
// Maps true to false and vice versa
extension Observable where Element: BooleanType {
func not() -> Observable<Bool> {
return self.map { input in
return !input.boolValue
}
}
}
extension CollectionType where Generator.Element: ObservableType, Generator.Element.E: BooleanType {
func combineLatestAnd() -> Observable<Bool> {
return combineLatest { bools -> Bool in
bools.reduce(true, combine: { (memo, element) in
return memo && element.boolValue
})
}
}
func combineLatestOr() -> Observable<Bool> {
return combineLatest { bools in
bools.reduce(false, combine: { (memo, element) in
return memo || element.boolValue
})
}
}
}
extension ObservableType {
func then(closure: () -> Observable<E>?) -> Observable<E> {
return then(closure() ?? .empty())
}
func then(@autoclosure(escaping) closure: () -> Observable<E>) -> Observable<E> {
let next = Observable.deferred {
return closure() ?? .empty()
}
return self
.ignoreElements()
.concat(next)
}
}
extension Observable {
func mapToOptional() -> Observable<Optional<Element>> {
return map { Optional($0) }
}
}
func sendDispatchCompleted<T>(observer: AnyObserver<T>) {
dispatch_async(dispatch_get_main_queue()) {
observer.onCompleted()
}
}
| mit | 8df5561fe23d7da977f9f8be552715e1 | 25.121212 | 100 | 0.568677 | 4.589989 | false | false | false | false |
kyouko-taiga/LogicKit | Sources/LogicKit/EDSL.swift | 1 | 3856 | infix operator ~=~: ComparisonPrecedence
infix operator => : AssignmentPrecedence
infix operator |- : AssignmentPrecedence
infix operator ⊢ : AssignmentPrecedence
infix operator ∧ : LogicalConjunctionPrecedence
infix operator ∨ : LogicalDisjunctionPrecedence
extension Term {
public static func lit<T>(_ value: T) -> Term where T: Hashable {
return .val(AnyHashable(value))
}
public func extractValue<T>(ofType type: T.Type) -> T? {
guard case .val(let v) = self
else { return nil }
return v as? T
}
public func extractValue() -> Any? {
guard case .val(let v) = self
else { return nil }
return v
}
public static func fact(_ name: String, _ arguments: Term...) -> Term {
return ._term(name: name, arguments: arguments)
}
public subscript(terms: Term...) -> Term {
guard case ._term(let name, let subterms) = self, subterms.isEmpty
else { fatalError("Cannot coerce '\(self)' into a functor") }
return ._term(name: name, arguments: terms)
}
public static func rule(_ name: String, _ arguments: Term..., body: () -> Term) -> Term {
return ._rule(name: name, arguments: arguments, body: body())
}
public static func =>(lhs: Term, rhs: Term) -> Term {
guard case ._term(let name, let args) = rhs
else { fatalError("Cannot use '\(self)' as a rule head.") }
return ._rule(name: name, arguments: args, body: lhs)
}
public static func |-(lhs: Term, rhs: Term) -> Term {
guard case ._term(let name, let args) = lhs
else { fatalError("Cannot use '\(self)' as a rule head.") }
return ._rule(name: name, arguments: args, body: rhs)
}
public static func ⊢(lhs: Term, rhs: Term) -> Term {
guard case ._term(let name, let args) = lhs
else { fatalError("Cannot use '\(self)' as a rule head.") }
return ._rule(name: name, arguments: args, body: rhs)
}
public static func &&(lhs: Term, rhs: Term) -> Term {
return .conjunction(lhs, rhs)
}
public static func ∧(lhs: Term, rhs: Term) -> Term {
return .conjunction(lhs, rhs)
}
public static func ||(lhs: Term, rhs: Term) -> Term {
return .disjunction(lhs, rhs)
}
public static func ∨(lhs: Term, rhs: Term) -> Term {
return .disjunction(lhs, rhs)
}
public static func ~=~(lhs: Term, rhs: Term) -> Term {
return ._term(name: "lk.~=~", arguments: [lhs, rhs])
}
}
protocol PredicateConvertible {
var name: String { get }
var arguments: [PredicateConvertible] { get }
}
extension PredicateConvertible {
var predicateValue: Term {
return ._term(name: name, arguments: arguments.map({ $0.predicateValue }))
}
}
extension Term: PredicateConvertible {
var name: String {
guard case ._term(let name, _) = self
else { fatalError() }
return name
}
var arguments: [PredicateConvertible] {
guard case ._term(_, let arguments) = self
else { fatalError() }
return arguments
}
}
extension Term: ExpressibleByStringLiteral {
public init(stringLiteral : String) {
self = .fact(stringLiteral)
}
}
@dynamicCallable
public struct Functor {
public let name: String
public let arity: Int
public func dynamicallyCall(withArguments args: [Term]) -> Term {
assert(args.count == arity)
return ._term(name: name, arguments: args)
}
public func dynamicallyCall(withArguments args: [Any]) -> Term {
assert(args.count == arity)
return ._term(
name: name,
arguments: args.map({ (arg: Any) -> Term in
switch arg {
case let term as Term:
return term
case let value as AnyHashable:
return .lit(value)
default:
fatalError("'\(arg)' is not a valid term argument")
}
}))
}
}
public func / (name: String, arity: Int) -> Functor {
return Functor(name: name, arity: arity)
}
| mit | ffae1fb6046d11e1555152ba185f7d04 | 24.626667 | 91 | 0.628512 | 3.824876 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.