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
qmathe/Confetti
Event/Operator/MapTouchesToIndexes.swift
1
1909
/** Copyright (C) 2017 Quentin Mathe Date: November 2017 License: MIT */ import Foundation import RxSwift public extension Observable where Element == [Touch] { /// Computes selection indexes from touches inside the given item, then combines it with /// current selection indexes, according to `Touch.modifiers`. /// /// Can be used when one or more elements in a row or column are tapped or targeted by a /// selection request. For example, when tapping the elements or choosing _Select All_ in _Edit_ /// menu. /// /// By default, touches other than the first one are ignored. public func mapToIndexes(in item: Item, combinedWith oldIndexes: Observable<IndexSet>) -> Observable<IndexSet> { return withLatestFrom(oldIndexes) { ($0, $1) }.flatMap { (pair: ([Touch], IndexSet)) -> Observable<IndexSet> in let touches = pair.0 let oldIndexes = pair.1 guard let (newIndexes, modifiers) = self.select(with: touches, in: item) else { return .empty() } switch modifiers { case [.command]: return .just(oldIndexes.symmetricDifference(newIndexes)) default: return .just(newIndexes) } } } public func mapToIndexes(in item: Item, combinedWithSelectionFrom state: SelectionState) -> Observable<IndexSet> { return mapToIndexes(in: item, combinedWith: state.selectionIndexes) } private func select(with touches: [Touch], in item: Item) -> (IndexSet, Modifiers)? { guard let touch = touches.first, let point = touch.location(in: item), let touchedItem = item.item(at: point), let index = item.items?.index(of: touchedItem) else { return nil } return (IndexSet(integer: index), touch.modifiers) } }
mit
f81b843a31b252d7f9612a662608a8ca
35.018868
119
0.618649
4.534442
false
false
false
false
TurfDb/Turf
Turf/Observable/MiniRx/RxScheduler.swift
1
767
import Foundation public protocol RxScheduler { func schedule(action: @escaping () -> Disposable) -> Disposable } open class QueueScheduler: RxScheduler { private let queue: DispatchQueue private let requiresScheduling: () -> Bool public init(queue: DispatchQueue, requiresScheduling: @escaping () -> Bool) { self.queue = queue self.requiresScheduling = requiresScheduling } open func schedule(action: @escaping () -> Disposable) -> Disposable { let disposable = AssignableDisposable() if requiresScheduling() { queue.async { disposable.disposable = action() } } else { disposable.disposable = action() } return disposable } }
mit
870531785bac879dbb124e141ac230e2
28.5
81
0.623207
5.147651
false
false
false
false
wl879/SwiftyCss
Example/Example/Views/TestBasic.swift
1
1270
import UIKit import SwiftyCss class TestBasic: UIViewController { override func loadView() { super.loadView() self.view.backgroundColor = .white let css = [ "#test-basic .box {background:#aaa;}", "" ] Css.load(text: css.joined(separator: "\n") ) self.view.css(insert: ".body#test-basic", " CALayer.box[style=top:10;left:5%;width:43%;height:100]", " CALayer.box[style=top:10;right:5%;width:43%;height:100]", " CALayer[style=top:10; left:[50%-5]; width:10; height:10; background:#f00]", " CALayer.box[style=top:130;left:5%;right:5%;bottom:10]", " CATextLayer[style=float:center;autoSize:auto;fontSize:16;color:#fff;][content=The center of the universe]", "UIScrollView.footer > CATextLayer" ) if let text = self.view.layer.css(query: ".footer > CATextLayer") as? CATextLayer { text.string = css.joined(separator: "\n") + "\n------------------------------------------\n" + Css.debugPrint(self.view, noprint: true) } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() Css.refresh(self.view) } }
mit
dda27a8ba478ba2a1b2d233c6da45d56
37.484848
147
0.551181
3.883792
false
true
false
false
dehesa/apple-utilites
Sources/Apple/Visuals/Segues/ModalSegue.swift
2
7712
#if os(iOS) import UIKit /// Segue that displays modally the destination controller with the preferred content size. /// - note: If the `preferredContentSize` is too big, a minium variable of the screen size minus inset is taken. public final class ModalSegue: UIStoryboardSegue, Unwindable { /// The identifier for the unwind segue. /// /// This is used when a tap is recognized outside the presentedVC frame. public var unwindSegueIdentifier: String? = nil public override func perform() { var delegate: UIViewControllerTransitioningDelegate? = ModalTransitioningDelegate(withUnwindSegueIdentifier: unwindSegueIdentifier) if !destination.isViewLoaded { // sourceVC is the presentingVC destination.modalPresentationStyle = .custom destination.transitioningDelegate = delegate source.present(destination, animated: true) { delegate = nil } } else { // sourceVC is the presentedVC source.modalPresentationStyle = .custom source.transitioningDelegate = delegate source.dismiss(animated: true) { delegate = nil } } } } public final class ModalTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate, Unwindable { public var unwindSegueIdentifier: String? = nil init(withUnwindSegueIdentifier segueID: String?) { unwindSegueIdentifier = segueID } public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { let controller = ModalPresentationController(presentedViewController: presented, presenting: presenting) controller.unwindSegueIdentifier = unwindSegueIdentifier return controller } public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return ModalAnimationPresenter() } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return ModalAnimationDissmiser() } } final class ModalPresentationController: UIPresentationController, UIGestureRecognizerDelegate, Unwindable { fileprivate let inset = CGFloat(15.0) fileprivate let blurView: UIVisualEffectView fileprivate(set) var tapGR: UITapGestureRecognizer! var unwindSegueIdentifier: String? = nil // MARK: UIPresentationController override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { blurView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) super.init(presentedViewController: presentedViewController, presenting: presentingViewController) tapGR = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) tapGR.delegate = self } override var frameOfPresentedViewInContainerView : CGRect { let containerBounds = CGRect(origin: CGPoint.zero, size: containerView!.bounds.size) let preferredSize = presentedViewController.preferredContentSize var size = containerBounds.insetBy(dx: inset, dy: inset).size size.width = min(size.width, preferredSize.width) size.height = min(size.height, preferredSize.height) return CGRect(x: 0.5*containerBounds.width-0.5*size.width, y: 0.5*containerBounds.height-0.5*size.height, width: size.width, height: size.height) } override func presentationTransitionWillBegin() { blurView.frame = containerView!.bounds containerView!.addSubview(blurView) let presentedView = presentedViewController.view presentedView?.frame = frameOfPresentedViewInContainerView containerView!.addSubview(presentedView!) presentingViewController.view.isUserInteractionEnabled = false super.presentationTransitionWillBegin() } override func presentationTransitionDidEnd(_ completed: Bool) { containerView!.addGestureRecognizer(tapGR) super.presentationTransitionDidEnd(completed) } override func containerViewWillLayoutSubviews() { let presentedView = presentedViewController.view presentedView?.frame = frameOfPresentedViewInContainerView blurView.frame = containerView!.bounds let layer = presentedView?.layer layer?.shadowOpacity = 0.8 layer?.shadowPath = CGPath(rect: (layer?.bounds)!, transform: nil) layer?.shadowOffset = CGSize.zero layer?.shadowRadius = 5 super.containerViewWillLayoutSubviews() } override func dismissalTransitionWillBegin() { containerView!.removeGestureRecognizer(tapGR) super.dismissalTransitionWillBegin() } override func dismissalTransitionDidEnd(_ completed: Bool) { presentedViewController.view.removeFromSuperview() blurView.removeFromSuperview() presentingViewController.view.isUserInteractionEnabled = true super.dismissalTransitionDidEnd(completed) } // MARK: UIGestureRecognizerDelegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { let view = presentedViewController.view let location = touch.location(in: view) return !view!.point(inside: location, with: nil) } func handleTap(_ sender: UITapGestureRecognizer) { guard case .ended = sender.state else { return } if let segueID = unwindSegueIdentifier { presentedViewController.performSegue(withIdentifier: segueID, sender: sender) } else { var delegate: UIViewControllerTransitioningDelegate? = ModalTransitioningDelegate(withUnwindSegueIdentifier: nil) presentedViewController.modalPresentationStyle = .custom presentedViewController.transitioningDelegate = delegate presentedViewController.dismiss(animated: true) { delegate = nil } } } } internal final class ModalAnimationPresenter: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView guard let blurView: UIVisualEffectView = containerView.subviews.find(), let presentedView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)?.view else { return } blurView.alpha = 0 presentedView.center = CGPoint(x: containerView.center.x, y: containerView.bounds.height + 0.5*presentedView.bounds.height) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { blurView.alpha = 1 presentedView.center = containerView.center }, completion: { transitionContext.completeTransition($0) }) } } internal final class ModalAnimationDissmiser: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView guard let blurView: UIVisualEffectView = containerView.subviews.find(), let presentedView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)?.view else { return } UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: { blurView.alpha = 0 presentedView.center = CGPoint(x: containerView.center.x, y: containerView.bounds.height + 0.5*presentedView.bounds.height) }, completion: { transitionContext.completeTransition($0) }) } } #endif
mit
bc2d5ab75d2aa6498f1d2787f9f4d6d7
42.570621
174
0.767635
5.488968
false
false
false
false
zneak/swift-chess
chess/PlaySession.swift
1
2302
// // main.swift // chess // // Created by Félix on 16-02-12. // Copyright © 2016 Félix Cloutier. All rights reserved. // import Foundation private let codePoints: [Piece: Int] = [ .Pawn: 0x2659, .Rook: 0x2656, .Knight: 0x2658, .Bishop: 0x2657, .Queen: 0x2655, .King: 0x2654, ] private func pieceChar(player: Player, piece: Piece) -> Character { let codePoint = codePoints[piece]! + (player == .Black ? 6 : 0) return Character(UnicodeScalar(codePoint)) } private func tileBackground(loc: Locator) -> Int { return (loc.rank % 2 + loc.file) % 2 == 0 ? 42 : 47 } enum SpecialStatus { case None case Check(Player) case Checkmate(Player) } enum InterpretationResult { case Success(SpecialStatus) case SelfCheck case ParseError case Illegal case Ambiguous } class PlaySession { var board = Board() var history = [(Locator, Locator)]() var turn: Player { return history.count % 2 == 0 ? .White : .Black } func interpret(move: String) -> InterpretationResult { do { let player = turn let move = try parseAlgebraic(board, player: player, move: move) let copy = board.move(move.0, to: move.1) if copy.isCheck(player) { return .SelfCheck } board = copy history.append(move) let opponent = player.opponent if copy.isCheck(opponent) { if copy.isCheckmate(opponent) { return .Success(.Checkmate(opponent)) } return .Success(.Check(opponent)) } return .Success(.None) } catch AlgebraicError.Ambiguous { return .Ambiguous } catch AlgebraicError.Illegal { return .Illegal } catch { return .ParseError } } func xtermPrint() { let rankOrder: [UInt8] if turn == .Black { rankOrder = Array(0..<8) } else { rankOrder = Array((0..<8).reverse()) } let escape = Character(UnicodeScalar(0x1b)) for rank in rankOrder { print("\(rank+1) ", terminator: "") for file in UInt8(0)..<UInt8(8) { let loc = Locator.fromCoords(file, rank: rank)! print("\(escape)[\(tileBackground(loc))m", terminator: "") if case .Occupied(let player, let piece) = board[loc] { print("\(pieceChar(player, piece: piece))", terminator: "") } else { print(" ", terminator: "") } print(" ", terminator: "") } print("\(escape)[0m") } print(" a b c d e f g h") } }
gpl-3.0
2f2297aecaf0fff112021c7a8bb6cb72
21.105769
67
0.638973
3.021025
false
false
false
false
furuya02/ARKitFurnitureArrangementSample
ARKitFurnitureArrangementSample/ViewController.swift
1
7432
// // ViewController.swift // ARKitFurnitureArrangementSample // // Created by SIN on 2017/09/05. // Copyright © 2017年 js.ne.sapporoworks. All rights reserved. // import UIKit import SceneKit import ARKit class ViewController: UIViewController, ScrollViewDelegate, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! @IBOutlet weak var controlView: UIView! @IBOutlet weak var menuButton: UIButton! @IBOutlet weak var menuView: UIView! var isMenuOpen = true @IBOutlet weak var scrollView: TouchScrollView! var recordingButto: RecordingButton! var planeNodes:[PlaneNode] = [] var sofaNode: SCNNode? let movement:Float = 0.05 override func viewDidLoad() { super.viewDidLoad() scrollView.Delegate = self // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true // Create a new scene let scene = SCNScene() // Set the scene to the view sceneView.scene = scene sceneView.autoenablesDefaultLighting = true menuView.translatesAutoresizingMaskIntoConstraints = true toggleMenu() initializeMenu() self.recordingButto = RecordingButton(self) // 録画ボタン controlView.backgroundColor = UIColor(white: 0, alpha: 0) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = .horizontal // 平面の検出を有効化する sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) sceneView.session.pause() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } // MARK; - Control @IBAction func moveUp(_ sender: Any) { sofaNode?.position = SCNVector3((sofaNode?.position.x)!, (sofaNode?.position.y)!, (sofaNode?.position.z)! - movement) } @IBAction func moveDown(_ sender: Any) { sofaNode?.position = SCNVector3((sofaNode?.position.x)!, (sofaNode?.position.y)!, (sofaNode?.position.z)! + movement) } @IBAction func moveRight(_ sender: Any) { sofaNode?.position = SCNVector3((sofaNode?.position.x)! + movement, (sofaNode?.position.y)!, (sofaNode?.position.z)! ) } @IBAction func moveLeft(_ sender: Any) { sofaNode?.position = SCNVector3((sofaNode?.position.x)! - movement, (sofaNode?.position.y)!, (sofaNode?.position.z)! ) } @IBAction func rotation(_ sender: Any) { sofaNode?.physicsBody?.applyTorque(SCNVector4(0, 10, 0, -1.0), asImpulse:false) } // MARK: - ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { if let planeAnchor = anchor as? ARPlaneAnchor { // 平面を表現するノードを追加する let panelNode = PlaneNode(anchor: planeAnchor) panelNode.isDisplay = true node.addChildNode(panelNode) self.planeNodes.append(panelNode) } } } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { if let planeAnchor = anchor as? ARPlaneAnchor, let planeNode = node.childNodes[0] as? PlaneNode { // ノードの位置及び形状を修正する planeNode.update(anchor: planeAnchor) } } } // MAEK: - Menu View @IBAction func menuButtonTapperd(_ sender: UIButton) { toggleMenu() } func toggleMenu() { if isMenuOpen { controlView.isHidden = false isMenuOpen = false menuButton.setImage(UIImage(named:"open"), for: .normal) UIView.animate(withDuration: 0.5, animations: { self.menuView.frame.origin.y = UIScreen.main.bounds.height - 50 }) } else { controlView.isHidden = true for imageView in scrollView.subviews { imageView.layer.borderWidth = 0 } isMenuOpen = true menuButton.setImage(UIImage(named:"close"), for: .normal) UIView.animate(withDuration: 0.5, animations: { self.menuView.frame.origin.y = UIScreen.main.bounds.height - 300 }) } } func initializeMenu() { let imageWidth = 250 let imageHeight = 200 let margin = 20 let imageNames = ["sofa_001","sofa_002","sofa_003","sofa_004"] scrollView.contentSize = CGSize(width: (imageWidth + margin) * imageNames.count , height: imageHeight) scrollView.isUserInteractionEnabled = true for i:Int in 0 ..< imageNames.count { let imageView = UIImageView(image: UIImage(named: imageNames[i])) imageView.tag = i + 1 imageView.isUserInteractionEnabled = true imageView.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.7) imageView.layer.borderColor = UIColor.white.cgColor imageView.layer.borderWidth = 0 imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 10 let offSet = i * (imageWidth + margin) imageView.frame = CGRect(x: offSet, y: 0, width: imageWidth, height: imageHeight) scrollView.addSubview(imageView) } menuView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) } // MAEK: - append Sofa Node func scrollViewTapped(tag: Int) { let imageView = scrollView.subviews[tag-1] imageView.layer.borderWidth = 10 self.toggleMenu() if sofaNode != nil { sofaNode?.removeFromParentNode() } let hitTestResult = sceneView.hitTest(sceneView.center, types: .existingPlaneUsingExtent) if !hitTestResult.isEmpty { if let hitResult = hitTestResult.first { let sceneName = ["sofa001","sofa002","sofa003","sofa004"] let assetsName = "art.scnassets" let sofaWidth:[CGFloat] = [1.7, 1.7, 0.8, 1.0] sofaNode = Furniture.create(sceneName: "\(assetsName)/\(sceneName[tag-1]).scn", width: sofaWidth[tag-1]) sofaNode?.physicsBody = SCNPhysicsBody(type: .dynamic, shape: nil) sofaNode?.physicsBody?.categoryBitMask = 1 sofaNode?.physicsBody?.restitution = 0// 弾み具合 0:弾まない 3:弾みすぎ sofaNode?.physicsBody?.damping = 1 // 空気の摩擦抵抗 1でゆっくり落ちる sofaNode?.position = SCNVector3(hitResult.worldTransform.columns.3.x, hitResult.worldTransform.columns.3.y + Float(0.1), hitResult.worldTransform.columns.3.z) sceneView.scene.rootNode.addChildNode(sofaNode!) } } } }
mit
bfb8b333a224ae81900e50a5c7494d7f
34.866995
174
0.600467
4.661332
false
false
false
false
NunoAlexandre/broccoli_mobile
ios/broccoli/DayFormVC.swift
1
1797
import UIKit import Eureka import Alamofire class DayFormVC : FormViewController { override func viewDidLoad() { super.viewDidLoad() form +++ Section("Your day") <<< DateRow("day") { $0.title = "Day" $0.add(rule: RuleRequired()) $0.maximumDate = Date() $0.value = Date() } <<< ActionSheetRow<String>("level") { $0.title = "Level" $0.selectorTitle = "The higher, the better your day was. " $0.options = ["7","6","5","4","3","2","1"] $0.add(rule: RuleRequired()) } <<< TextAreaRow("note") { $0.title = "Note" $0.add(rule: RuleMaxLength(maxLength: 400)) } <<< ButtonRow() { $0.title = "Save" $0.cell.height = {90} } .onCellSelection { _, _ in BroccoliAPI().saveDay(self.userDay(from: self.form), onSuccess: {self.present(Feedback.dayAdded())}, onDuplicateDay: {self.present(Feedback.duplicatedDay())}, onUnauthorized: self.performExplainedLogout) } } func userDay(from form: Form) -> Parameters { return ["user_day" : ["day" : self.asString(self.form.values()["day"] as! Date), "level" : self.form.values()["level"] as? String, "note" : self.form.values()["note"] as? String]] } private func asString(_ date : Date) -> String { let styled = DateFormatter() styled.dateFormat = "yyyy-MM-dd" return styled.string(from: date) } }
mit
d20dd03f4cc8a680fcd2eed8a6e5b50d
33.557692
88
0.459655
4.470149
false
false
false
false
rob-brown/SwiftRedux
Source/Action.swift
1
696
// // Action.swift // SwiftRedux // // Created by Robert Brown on 10/28/15. // Copyright © 2015 Robert Brown. All rights reserved. // import Foundation public protocol Action { var type: String { get } var payload: AnyObject? { get } var meta: AnyObject? { get } var error: Bool { get } } public struct BasicAction: Action { public let type: String public let payload: AnyObject? public let meta: AnyObject? public let error: Bool public init(type: String, payload: AnyObject? = nil, meta: AnyObject? = nil, error: Bool = false) { self.type = type self.payload = payload self.meta = meta self.error = error } }
mit
247c2cab4459e24e55587eab00087d91
22.166667
103
0.627338
3.818681
false
false
false
false
Loveswift/BookReview
BookReview/BookReview/HeaderView.swift
1
2568
// // HeaderView.swift // BookReview // // Created by xjc on 16/5/7. // Copyright © 2016年 xjc. All rights reserved. // import UIKit class HeaderView: UIView { //var lineView:LineView! var View_Width:CGFloat! var View_Height:CGFloat! var userName:UILabel? var shareButton:UIButton? var settingButton:UIButton? var userImageBtn:UIButton? var imageBackground:UIImageView? /** 初始化view */ override init(frame: CGRect) { super.init(frame: frame) self.View_Width = frame.size.width self.View_Height = frame.size.height self.backgroundColor = UIColor.whiteColor() self.imageBackground = UIImageView(frame: CGRectMake(0, 0, View_Width, View_Height)) self.imageBackground?.image = UIImage(named: "bg") self.imageBackground?.userInteractionEnabled = true //imageBackground可交互 self.addSubview(self.imageBackground!) self.userImageBtn = UIButton(frame: CGRectMake(View_Width/2-70/2,View_Height-150,75,75)) self.userImageBtn?.layer.cornerRadius = 75/2 self.userImageBtn?.layer.masksToBounds = true //self.userImageBtn?.backgroundColor = UIColor.greenColor() self.userImageBtn?.setImage(UIImage(named: "Avatar"), forState: .Normal) self.imageBackground?.addSubview(self.userImageBtn!) self.shareButton = UIButton(frame: CGRectMake(30,View_Height-80,50,50)) self.shareButton?.setImage(UIImage(named: "pic_myqrcode_share_img"), forState: .Normal) self.imageBackground?.addSubview(self.shareButton!) self.userName = UILabel(frame: CGRectMake(View_Width/2-50,View_Height-70,100,30)) self.userName?.text = "jinhui" self.userName?.textAlignment = .Center self.userName?.textColor = UIColor.blackColor() self.imageBackground?.addSubview(self.userName!) self.settingButton = UIButton(frame: CGRectMake(View_Width-65,View_Height-80,50,50)) self.settingButton?.setImage(UIImage(named: "ic_love_action"), forState: .Normal) self.imageBackground?.addSubview(self.settingButton!) //self.lineView = LineView(frame: CGRectMake(0,View_Height-38,View_Width,38)) //self.imageBackground?.addSubview(self.lineView!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { } }
apache-2.0
d5a0fd37ba3025820cf6ff7c4946b918
32.155844
96
0.64904
4.262104
false
false
false
false
sprint84/CalculatorKeyboard
CalculatorKeyboard/CalculatorProcessor.swift
2
5153
// // CalculatorProcessor.swift // Pods // // Created by Guilherme Moura on 8/17/15. // // import UIKit class CalculatorProcessor { var automaticDecimal = false { didSet { if automaticDecimal { previousOperand = resetOperand() currentOperand = resetOperand() } } } var previousOperand: String = "0" var currentOperand: String = "0" var storedOperator: CalculatorKey? var decimalDigit = 0 func storeOperand(_ value: Int) -> String { let operand = "\(value)" if currentOperand == "0" { currentOperand = operand } else { currentOperand += operand } if storedOperator == .equal { if automaticDecimal { currentOperand = previousOperand + operand } else { currentOperand = operand } storedOperator = nil } if automaticDecimal { currentOperand = currentOperand.replacingOccurrences(of: decimalSymbol(), with: "") if currentOperand[currentOperand.startIndex] == "0" { currentOperand.remove(at: currentOperand.startIndex) } let char = decimalSymbol()[decimalSymbol().startIndex] currentOperand.insert(char, at: currentOperand.characters.index(currentOperand.endIndex, offsetBy: -2)) } return currentOperand } func deleteLastDigit() -> String { if currentOperand.characters.count > 1 { currentOperand.remove(at: currentOperand.characters.index(before: currentOperand.endIndex)) if automaticDecimal { currentOperand = currentOperand.replacingOccurrences(of: decimalSymbol(), with: "") if currentOperand.characters.count < 3 { currentOperand.insert("0", at: currentOperand.startIndex) } let char = decimalSymbol()[decimalSymbol().startIndex] currentOperand.insert(char, at: currentOperand.characters.index(currentOperand.endIndex, offsetBy: -2)) } } else { currentOperand = resetOperand() } return currentOperand } func addDecimal() -> String { if currentOperand.range(of: decimalSymbol()) == nil { currentOperand += decimalSymbol() } return currentOperand } func storeOperator(_ rawValue: Int) -> String { if storedOperator != nil && storedOperator != .equal { previousOperand = computeFinalValue() } else if storedOperator == .equal && rawValue == CalculatorKey.equal.rawValue { return currentOperand } else { previousOperand = currentOperand } currentOperand = resetOperand() storedOperator = CalculatorKey(rawValue: rawValue)! return previousOperand } func computeFinalValue() -> String { let value1 = (previousOperand as NSString).doubleValue let value2 = (currentOperand as NSString).doubleValue if let oper = storedOperator { var output = 0.0 switch oper { case .multiply: output = value1 * value2 case .divide: output = value1 / value2 case .subtract: output = value1 - value2 case .add: output = value1 + value2 case .equal: return currentOperand default: break } currentOperand = formatValue(output) } previousOperand = resetOperand() storedOperator = .equal return currentOperand } func clearAll() -> String { storedOperator = nil currentOperand = resetOperand() previousOperand = resetOperand() return currentOperand } fileprivate func decimalSymbol() -> String { return "." } fileprivate func resetOperand() -> String { var operand = "0" if automaticDecimal { operand = convertOperandToDecimals(operand) } return operand } fileprivate func convertOperandToDecimals(_ operand: String) -> String { return operand + ".00" } fileprivate func formatValue(_ value: Double) -> String { var raw = "\(value)" if automaticDecimal { raw = String(format: "%.2f", value) return raw } else { var end = raw.characters.index(before: raw.endIndex) var foundDecimal = false while end != raw.startIndex && (raw[end] == "0" || isDecimal(raw[end])) && !foundDecimal { foundDecimal = isDecimal(raw[end]) raw.remove(at: end) end = raw.characters.index(before: end) } return raw } } fileprivate func isDecimal(_ char: Character) -> Bool { return String(char) == decimalSymbol() } }
mit
509259a62429ef9cc76a8a50c8b82350
30.613497
119
0.551912
5.61329
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Requests/Groups/EditGroupRequest.swift
1
2370
// // EditGroupRequest.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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 class EditGroupRequest: Request { override var method: RequestMethod { return .put } override var parameters: Dictionary<String, AnyObject> { return prepareParameters() } override var endpoint: String { return "groups/\(identifier)" } fileprivate let data: EditGroupData fileprivate let identifier: String init(identifier: String, data: EditGroupData) { self.identifier = identifier self.data = data } fileprivate func prepareParameters() -> Dictionary<String, AnyObject> { var dataDict = Dictionary<String, AnyObject>() var attributesDict = Dictionary<String, AnyObject>() var relationshipsDict = Dictionary<String, AnyObject>() dataDict["type"] = "groups" as AnyObject? if let value = data.name { attributesDict["name"] = value as AnyObject? } if let value = data.avatarCreationIdentifier { relationshipsDict["avatar_creation"] = ["data": ["id": value]] as AnyObject? } dataDict["attributes"] = attributesDict as AnyObject? dataDict["relationships"] = relationshipsDict as AnyObject? return ["data": dataDict as AnyObject] } }
mit
009f416ea397c945e83b38a59c0bc309
42.090909
133
0.716878
4.674556
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00172-swift-archetypebuilder-inferrequirementswalker-walktotypepost.swift
1
7912
// 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 // RUN: not %target-swift-frontend %s -typecheck protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } <c b: func b<c { enum b { func b var _ = b func b((Any, e))(e: (Any) -> <d>(()-> d) -> f func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c k) func c<i>() -> (i, i -> i) -> i { k b k.i = { } { i) { k } } protocol c { class func i() } class k: c{ class func i { protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { typealias g } func b(c) -> <d>(() -> d) { } import Foundation class d<c>: NSObject { var b: c init(b: c) { self.b = b } } struct c<e> { let d: i h } func f(h: b) -> <e>(()-> e c j) func c<k>() -> (k, > k) -> k { d h d.f 1, k(j, i))) class k { typealias h = h func C<D, E: A where D.C == E> { } func prefix(with: String) -> <T>(() -> T) -> String { { g in "\(withing } clasnintln(some(xs)) func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) protocol f { k g d { k d k k } j j<l : d> : d { k , d> } class f: f { } class B : l { } k l = B class f<i : f () { g g h g } } func e(i: d) -> <f>(() -> f)> func h<j>() -> (j, j -> j) -> j { var f: ({ (c: e, f: e -> e) -> return f(c) }(k, i) let o: e = { c, g return f(c) }(l) -> m) -> p>, e> } class n<j : n> protocol A { func c() -> String } class B { func d() -> String { return "" } } class C: B, A { override func d() -> String { return "" } func c() -> String { return "" } } func e<T where T: A, T: B>(t: T) { t.c() } struct c<d: Sequence, b where Optional<b> == d.Iterator.Element> func f<e>() -> (e, e -> e) -> e { e b e.c = {} { e) { f } } protocol f { class func c() } class e: f { class func c } } struct c<d : Sequence> { var b: d } func a<d>() -> [c<d>] { return [] } protocol b { class func e() } struct c { var d: b.Type func e() { d.e() } } func a<T>() { enum b { case c } } func r<t>() { f f { i i } } struct i<o : u> { o f: o } func r<o>() -> [i<o>] { p [] } class g<t : g> { } class g: g { } class n : h { } typealias h = n protocol g { func i() -> l func o() -> m { q"" } } func j<t k t: g, t: n>(s: t) { s.i() } protocol r { } protocol f : r { } protocol i : r { } j ) func n<w>() -> (w, w -> w) -> w { o m o.q = { } { w) { k } } protocol n { class func q() } class o: n{ class func q {} func p(e: Int = x) { } let c = p c() func r<o: y, s q n<s> ==(r(t)) protocol p : p { } protocol p { class func c() } class e: p { class func c() { } } (e() u p).v.c() k e.w == l> { } func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) { } class i { func d((h: (Any, AnyObject)) { d(h) } } d h) func d<i>() -> (i, i -> i) -> i { i j i.f = { } protocol d { class func f() } class i: d{ class func f {} struct d<f : e, g: e where g.h == f.h> { } protocol e { typealias h } func a(b: Int = 0) { } let c = a c() protocol a : a { } } } class b<i : b> i: g{ func c {} e g { : g { h func i() -> } struct c<e> { let d: [( h } func b(g: f) -> <e>(()-> e) -> i func ^(a: Boolean, Bool) -> Bool { return !(a) } func d() -> String { return 1 k f { typealias c } class g<i{ } d(j i) class h { typealias i = i } func o() as o).m.k() func p(k: b) -> <i>(() -> i) -> b { n { o f "\(k): \(o())" } } struct d<d : n, o:j n { l p } protocol o : o { } func o< import Foundation class k<f>: NSObject { d e: f g(e: f) { j h.g() } } d protocol i : d { func d i struct l<e : Sequence> { l g: e } func h<e>() -> [l<e>] { f [] } func i(e: g) -> <j>(() -> j) -> k func i(c: () -> ()) { } class a { var _ = i() { } } ) var d = b =b as c=b o } class f<p : k, p : k where p.n == p> : n { } class f<p, p> { } protocol k { typealias n } o: i where k.j == f> {l func k() { } } (f() as n).m.k() func k<o { enum k { func o var _ = protocol g { typealias f typealias e } struct c<h : g> : g { typealias f = h typealias e = a<c<h>, f> import Foundation class m<j>k i<g : g, e : f k(f: l) { } i(()) class h { typealias g = g } class p { u _ = q() { } } u l = r u s: k -> k = { n $h: m.j) { } } o l() { ({}) } struct m<t> { let p: [(t, () -> ())] = [] } protocol p : p { } protocol m { o u() -> String } class j { o m() -> String { n "" } } class h: j, m { q o m() -> String { n "" } o u() -> S, q> { } protocol u { typealias u } class p { typealias u = u } func ^(r: l, k) -> k { ? { h (s : t?) q u { g let d = s { p d } } e} let u : [Int?] = [n{ c v: j t.v == m>(n: o<t>) { } } class r { typealias n = n func c<e>() -> (e -> e) -> e { e, e -> e) ->)func d(f: b) -> <e>(() -> e) -> b { return { g in} protocol p { class func g() } class h: p { class func g() { } } (h() as p).dynamicType.g() protocol p { } protocol h : p { } protocol g : p { } protocol n { o t = p } struct h : n { t : n q m.t == m> (h: m) { } func q<t : n q t.t == g> (h: t) { } q(h()) func r(g: m) -> <s>(() -> s) -> n b protocol d : b { func b func d(e: = { (g: h, f: h -> h) -> h in return f(g) } func f<T : Boolean>(b: T) { } f(true as Boolean) class k { func l((Any, k))(m } } func j<f: l: e -> e = { { l) { m } } protocol k { class func j() } class e: k{ class func j func f(c: i, l: i) -> (((i, i) -> i) -> i) { b { (h -> i) d $k } let e: Int = 1, 1) class g<j :g func a<T>() -> (T, T -> T) -> T { var b: ((T, T -> T) -> T)! return b } func ^(d: e, Bool) -> Bool {g !(d) } protocol d { f func g() f e: d { f func g() { } } (e() h d).i() e protocol g : e { func e >) } struct n : C { class p { typealias n = n } l l) func l<u>() -> (u, u -> u) -> u { n j n.q = { } { u) { h } } protocol l { class { func n() -> q { return "" } } class C: s, l { t) { return { (s: (t, t) -> t) -> t o return s(c, u) -> Any) -> Any l k s(j, t) } } func b(s: (((Any, Any) -> Any) -> Any) func m<u>() -> (u, u -> u) -> u { p o p.s = { } { u) { o } } s m { class func s() } class p: m{ class func s {} s p { func m() -> String } class n { func p() -> String { q "" } } class e: n, p { v func> String { q "" } { r m = m } func s<o : m, o : p o o.m == o> (m: o) { } func s<v : p o v.m == m> (u: String) -> <t>(() -> t) - protocol A { func c()l k { func l() -> g { m "" } } class C: k, A { j func l()q c() -> g { m "" } } func e<r where r: A, r: k>(n: r) { n.c() } protocol A { typealias h } c k<r : A> { p f: r p p: r.h } protocol C l.e() } } class o { typealias l = l f g } struct d<i : b> : b { typealias b = i typealias g = a<d<i>i) { } let d = a d() a=d g a=d protocol a : a { } class a { typealias b = b func m(c: b) -> <h>(() -> h) -> b { f) -> j) -> > j { l i !(k) } d l) func d<m>-> (m, m -
apache-2.0
a71e0a1ec0ea8d91d6a212ccae4cab49
12.954145
79
0.41595
2.357569
false
false
false
false
ShatteredPhoenix/ItunesPreviewPlayer
SwiftApiExample/APIController.swift
1
3804
// // APIController.swift // WeatherApp // // Created by Humza Ahmed on 31/08/2015. // Copyright (c) 2015 Humza Ahmed. All rights reserved. // /*********************************************************************** ItunesPreviewPlayer - Simple application that uses Swift with Itunes Search API to allow the user to search for any album and prieview the tracks within it. Copyright (C) 2015 Humza Ahmed This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************/ import Foundation // Add a Protocol that the View Controller can Adhere Too. protocol APIControllerProtocol { func didReceiveAPIResults(results: NSArray) } class APIController { //Constructor to intitlise the delegate init(delegate: APIControllerProtocol) { self.delegate = delegate } // Non Optional Everyday Delegate var delegate: APIControllerProtocol //Function to Send Request and get data back in JSon func Get(path: String) { let url = NSURL(string: path) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in println("Task completed") if(error != nil) { // If there is an error in the web request, print it to the console println(error.localizedDescription) } var err: NSError? if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary { if(err != nil) { // If there is an error parsing JSON, print it to the console println("JSON Error \(err!.localizedDescription)") } if let results: NSArray = jsonResult["results"] as? NSArray { self.delegate.didReceiveAPIResults(results) } } }) // The task is just an object with all these properties set // In order to actually make the web request, I need to "resume" the task task.resume() } //Function to Search ITunes for an Album func SearchItunesFor(searchTerm: String) { // The iTunes API wants multiple terms separated by + symbols, replace spaces with + signs let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) // Now escape anything else that isn't URL-friendly if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music&entity=album" Get(urlPath) //Call Get Function with urlPath as Path } } //Takes ID and Uses GET function to get track information func lookupAlbum(collectionId: Int) { Get("https://itunes.apple.com/lookup?id=\(collectionId)&entity=song") } }
gpl-3.0
3b0fa2b8e7700a4017a3c124a8410f7a
37.434343
167
0.628812
5.246897
false
false
false
false
zhubch/DropDownMenu
ZHDropDownMenu/ZHDropDownMenu.swift
1
9010
// // ZHDropDownMenu.swift // // Created by zhubch on 3/8/16. // // Copyright (c) 2016 zhubch <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public protocol ZHDropDownMenuDelegate: NSObjectProtocol { func dropDownMenu(_ menu:ZHDropDownMenu, didEdit text:String) func dropDownMenu(_ menu:ZHDropDownMenu, didSelect index:Int) } @IBDesignable public class ZHDropDownMenu: UIView { public weak var delegate: ZHDropDownMenuDelegate? public var didEditHandler: ((_ text: String) -> Void)? public var didSelectHandler: ((_ index: Int) -> Void)? public var options = [String]() {//菜单项数据,设置后自动刷新列表 didSet { reload() } } public var rowHeight: CGFloat { //菜单项的每一行行高,默认和本控件一样高,如果为0则和本空间初始高度一样 get{ if _rowHeight == 0 { return frame.size.height } return _rowHeight } set{ _rowHeight = newValue reload() } } public var menuHeight: CGFloat {// 菜单展开的最大高度,当它为0时全部展开 get { if _menuMaxHeight == 0 { return CGFloat(options.count) * rowHeight } return min(_menuMaxHeight, CGFloat(options.count) * rowHeight) } set { _menuMaxHeight = newValue reload() } } @IBInspectable public var editable = false { //是否允许用户编辑, 默认不允许 didSet { contentTextField.isEnabled = editable } } @IBInspectable public var buttonImage: UIImage? { //下拉按钮的图片 didSet { pullDownButton.setImage(buttonImage, for: UIControlState()) } } @IBInspectable public var placeholder: String? { //占位符 didSet { contentTextField.placeholder = placeholder } } @IBInspectable public var defaultValue: String? { //默认值 didSet { contentTextField.text = defaultValue } } @IBInspectable public var textColor: UIColor?{ //输入框和下拉列表项中文本颜色 didSet { contentTextField.textColor = textColor } } public var font: UIFont?{ //输入框和下拉列表项中字体 didSet { contentTextField.font = font } } public var showBorder = true { //是否显示边框,默认显示 didSet { if showBorder { layer.borderColor = UIColor.lightGray.cgColor layer.borderWidth = 0.5 layer.masksToBounds = true layer.cornerRadius = 2.5 }else { layer.borderColor = UIColor.clear.cgColor layer.masksToBounds = false layer.cornerRadius = 0 layer.borderWidth = 0 } } } private lazy var optionsList: UITableView = { //下拉列表 let frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y + self.frame.size.height, width: self.frame.size.width, height: 0) let table = UITableView(frame: frame, style: .plain) table.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0) table.dataSource = self table.delegate = self table.layer.borderColor = UIColor.lightGray.cgColor table.layer.borderWidth = 0.5 self.superview?.addSubview(table) return table }() public var contentTextField: UITextField! private var pullDownButton: UIButton! private var isShown = false private var _rowHeight = CGFloat(0) private var _menuMaxHeight = CGFloat(0) override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { contentTextField = UITextField(frame: CGRect.zero) contentTextField.delegate = self contentTextField.isEnabled = false addSubview(contentTextField) pullDownButton = UIButton(type: .custom) pullDownButton.addTarget(self, action: #selector(ZHDropDownMenu.showOrHide), for: .touchUpInside) pullDownButton.setImage(UIImage(named: "default_down"), for: .normal) addSubview(pullDownButton) showBorder = true textColor = .darkGray font = UIFont.systemFont(ofSize: 16) } @objc func showOrHide() { if isShown { UIView.animate(withDuration: 0.3, animations: { self.pullDownButton.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi*2)) self.optionsList.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y + self.frame.size.height-0.5, width: self.frame.size.width, height: 0) }, completion: { _ in self.pullDownButton.transform = CGAffineTransform(rotationAngle: 0.0) self.isShown = false }) } else { contentTextField.resignFirstResponder() optionsList.reloadData() UIView.animate(withDuration: 0.3, animations: { self.pullDownButton.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) self.optionsList.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y + self.frame.size.height-0.5, width: self.frame.size.width, height:self.menuHeight) }, completion: { _ in self.isShown = true }) } } func reload() { guard self.isShown else { return } optionsList.reloadData() UIView.animate(withDuration: 0.3) { self.pullDownButton.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) self.optionsList.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y + self.frame.size.height-0.5, width: self.frame.size.width, height:self.menuHeight) } } override open func layoutSubviews() { super.layoutSubviews() contentTextField.frame = CGRect(x: 15, y: 5, width: frame.size.width - 50, height: frame.size.height - 10) pullDownButton.frame = CGRect(x: frame.size.width - 35, y: 5, width: 30, height: 30) } } extension ZHDropDownMenu: UITextFieldDelegate { open func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() if let text = textField.text { self.delegate?.dropDownMenu(self, didEdit: text) self.didEditHandler?(text) } return true } } extension ZHDropDownMenu: UITableViewDelegate, UITableViewDataSource { open func numberOfSections(in tableView: UITableView) -> Int { return 1 } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: "") cell.textLabel?.text = options[indexPath.row] cell.textLabel?.font = font cell.textLabel?.textColor = textColor return cell } open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.rowHeight } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { contentTextField.text = options[indexPath.row] delegate?.dropDownMenu(self, didSelect:indexPath.row) didSelectHandler?(indexPath.row) showOrHide() } }
mit
b21271c1a8cdcffba7cd30cd6e41f4f4
33.55336
178
0.620682
4.613193
false
false
false
false
opalorange/OpalImagePicker
OpalImagePicker/Source/OpalImagePickerController.swift
1
6821
// // OpalImagePickerController.swift // OpalImagePicker // // Created by Kris Katsanevas on 1/15/17. // Copyright © 2017 Opal Orange LLC. All rights reserved. // import UIKit import Photos /// Image Picker Controller Delegate. Notifies when images are selected or image picker is cancelled. @objc public protocol OpalImagePickerControllerDelegate: class { /// Image Picker did finish picking images. Provides an array of `PHAsset` selected. /// /// - Parameters: /// - picker: the `OpalImagePickerController` /// - assets: the array of `PHAsset` @objc optional func imagePicker(_ picker: OpalImagePickerController, didFinishPickingAssets assets: [PHAsset]) /// Image Picker did cancel. /// /// - Parameter picker: the `OpalImagePickerController` @objc optional func imagePickerDidCancel(_ picker: OpalImagePickerController) /// Image Picker Number of External items. Optional use to provide items from external /// sources e.g. (Facebook, Twitter, or Instagram). /// /// - Parameter picker: the `OpalImagePickerController` /// - Returns: an `Int` describing the number of available external image `URL` @objc optional func imagePickerNumberOfExternalItems(_ picker: OpalImagePickerController) -> Int /// Image Picker returns the `URL` for an image at an `Int` index. Optional use to provide items from external /// sources e.g. (Facebook, Twitter, or Instagram). /// /// - Parameters: /// - picker: the `OpalImagePickerController` /// - index: the `Int` index for the image /// - Returns: the `URL` @objc optional func imagePicker(_ picker: OpalImagePickerController, imageURLforExternalItemAtIndex index: Int) -> URL? /// Image Picker external title. This will appear in the `UISegmentedControl`. Make sure to provide a Localized String. /// /// - Parameter picker: the `OpalImagePickerController` /// - Returns: the `String`. This should be a Localized String. @objc optional func imagePickerTitleForExternalItems(_ picker: OpalImagePickerController) -> String /// Image Picker did finish picking external images. Provides an array of `URL` selected. /// /// - Parameters: /// - picker: the `OpalImagePickerController` /// - urls: the array of `URL` @objc optional func imagePicker(_ picker: OpalImagePickerController, didFinishPickingExternalURLs urls: [URL]) } /// Image Picker Controller. Displays images from the Photo Library. Must check Photo Library permissions before attempting to display this controller. open class OpalImagePickerController: UINavigationController { /// Image Picker Delegate. Notifies when images are selected or image picker is cancelled. @objc open weak var imagePickerDelegate: OpalImagePickerControllerDelegate? { didSet { let rootVC = viewControllers.first as? OpalImagePickerRootViewController rootVC?.delegate = imagePickerDelegate } } /// Configuration to change Localized Strings @objc open var configuration: OpalImagePickerConfiguration? { didSet { let rootVC = viewControllers.first as? OpalImagePickerRootViewController rootVC?.configuration = configuration } } /// Custom Tint Color for overlay of selected images. @objc open var selectionTintColor: UIColor? { didSet { let rootVC = viewControllers.first as? OpalImagePickerRootViewController rootVC?.selectionTintColor = selectionTintColor } } /// Custom Tint Color for selection image (checkmark). @objc open var selectionImageTintColor: UIColor? { didSet { let rootVC = viewControllers.first as? OpalImagePickerRootViewController rootVC?.selectionImageTintColor = selectionImageTintColor } } /// Custom selection image (checkmark). @objc open var selectionImage: UIImage? { didSet { let rootVC = viewControllers.first as? OpalImagePickerRootViewController rootVC?.selectionImage = selectionImage } } /// Maximum photo selections allowed in picker (zero or fewer means unlimited). @objc open var maximumSelectionsAllowed: Int = -1 { didSet { let rootVC = viewControllers.first as? OpalImagePickerRootViewController rootVC?.maximumSelectionsAllowed = maximumSelectionsAllowed } } /// Allowed Media Types that can be fetched. See `PHAssetMediaType` open var allowedMediaTypes: Set<PHAssetMediaType>? { didSet { let rootVC = viewControllers.first as? OpalImagePickerRootViewController rootVC?.allowedMediaTypes = allowedMediaTypes } } /// Allowed MediaSubtype that can be fetched. Can be applied as `OptionSet`. See `PHAssetMediaSubtype` open var allowedMediaSubtypes: PHAssetMediaSubtype? { didSet { let rootVC = viewControllers.first as? OpalImagePickerRootViewController rootVC?.allowedMediaSubtypes = allowedMediaSubtypes } } /// Status Bar Preference (defaults to `default`) @objc open var statusBarPreference = UIStatusBarStyle.default /// External `UIToolbar` barTintColor. @objc open var externalToolbarBarTintColor: UIColor? { didSet { let rootVC = viewControllers.first as? OpalImagePickerRootViewController rootVC?.toolbar.barTintColor = externalToolbarBarTintColor } } /// External `UIToolbar` and `UISegmentedControl` tint color. @objc open var externalToolbarTintColor: UIColor? { didSet { let rootVC = viewControllers.first as? OpalImagePickerRootViewController rootVC?.toolbar.tintColor = externalToolbarTintColor rootVC?.tabSegmentedControl.tintColor = externalToolbarTintColor } } /// Initializer public required init() { super.init(rootViewController: OpalImagePickerRootViewController()) } /// Initializer (Do not use this controller in Interface Builder) /// /// - Parameters: /// - nibNameOrNil: the nib name /// - nibBundleOrNil: the nib `Bundle` public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } /// Initializer (Do not use this controller in Interface Builder) public required init?(coder aDecoder: NSCoder) { fatalError("Cannot init \(String(describing: OpalImagePickerController.self)) from Interface Builder") } open override var preferredStatusBarStyle: UIStatusBarStyle { return statusBarPreference } }
mit
69b141b81aae3950a1d1e41c4e728cde
40.084337
151
0.684897
5.636364
false
false
false
false
luanlzsn/pos
pos/Classes/Common/LanguageManager.swift
1
1001
// // LanguageManager.swift // Traber // // Created by luan on 2017/4/29. // Copyright © 2017年 luan. All rights reserved. // import UIKit let LanguageSaveKey = "CurrentLanguageKey" class LanguageManager: NSObject { class func setupCurrentLanguage() { var currentLanguage = UserDefaults.standard.object(forKey: LanguageSaveKey) if currentLanguage == nil { currentLanguage = "en" UserDefaults.standard.set(currentLanguage, forKey: LanguageSaveKey) UserDefaults.standard.synchronize() } Bundle.setLanguage(currentLanguage as! String) } class func currentLanguageString() -> String { return UserDefaults.standard.object(forKey: LanguageSaveKey) as! String } class func saveLanguage(languageString: String) { UserDefaults.standard.set(languageString, forKey: LanguageSaveKey) UserDefaults.standard.synchronize() Bundle.setLanguage(languageString) } }
mit
6f2b163dc416860d96d2b90a8ef219ef
26.722222
83
0.678357
4.707547
false
false
false
false
artsy/eigen
ios/ArtsyTests/View_Controller_Tests/Live_Auction/BiddingIncrementSpecs.swift
1
1865
import Quick import Nimble @testable import Artsy class BiddingIncrementSpecs: QuickSpec { class func spec() { it("should return the bid parameter if the list is empty") { let subject: [BidIncrementStrategy] = [] expect(subject.minimumNextBidCentsIncrement(100)) == 100 } describe("actual increments") { let subject: [BidIncrementStrategy] = [ BidIncrementStrategy(json: ["from": 0, "amount": 25]), BidIncrementStrategy(json: ["from": 100, "amount": 50]), BidIncrementStrategy(json: ["from": 1_000, "amount": 500]) ] it("works with the smallest increment") { expect(subject.minimumNextBidCentsIncrement(50)) == 75 } it("works with the medium increment") { expect(subject.minimumNextBidCentsIncrement(500)) == 550 } it("works with the largest increment") { expect(subject.minimumNextBidCentsIncrement(5_000)) == 5_500 } it("works with an absurdly large number increment") { expect(subject.minimumNextBidCentsIncrement(5_000_000_000)) == 5_000_000_500 } } describe("out of order increments") { let subject: [BidIncrementStrategy] = [ BidIncrementStrategy(json: ["from": 0, "amount": 25]), BidIncrementStrategy(json: ["from": 1_000, "amount": 500]), BidIncrementStrategy(json: ["from": 100, "amount": 50]) ] // It is the salesperson's job to sort these. it("gives incorrect output when array is not sorted, following principle of garbage-in-garbage-out") { expect(subject.minimumNextBidCentsIncrement(500)) != 550 } } } }
mit
6c8b7f760d0eb8d535668e87548335ad
34.865385
114
0.564075
4.986631
false
false
false
false
SnipDog/ETV
ETV/Moudel/Game/GameViewController.swift
1
2267
// // GameViewController.swift // ETV // // Created by Heisenbean on 16/9/29. // Copyright © 2016年 Heisenbean. All rights reserved. // import UIKit import Alamofire class GameViewController: UIViewController { // MARK:Init Properties @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var layout: UICollectionViewFlowLayout! var models = [[String : AnyObject]]() let kRequestUrl = "http://api.m.panda.tv/index.php?method=category.list&type=game&__version=2.0.1.1339&__plat=ios&__channel=appstore&pt_sign=f8802801e9daf1d0f0e09027aac27c6a&pt_time=1476504216" let margin = CGFloat(5) // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() loadData() configLayout() // Do any additional setup after loading the view. } func configLayout() { layout.itemSize = CGSize(width: (UIScreen.main.bounds.width - margin * 4) / 3, height: 202) collectionView.contentInset = UIEdgeInsetsMake(5, 4, 4, 4) layout.minimumLineSpacing = 5 layout.minimumInteritemSpacing = 5 } func loadData() { Alamofire.request(kRequestUrl).responseJSON { response in if let json = response.result.value { let jsonData = json as! [String:AnyObject] for data in jsonData["data"] as! [[String : AnyObject]]{ self.models.append(data) } self.collectionView.reloadData() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension GameViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! GameCell cell.model = models[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.models.count } }
mit
c8bd9d767e8499faecfc1fb8f6d56de8
30.013699
197
0.651943
4.697095
false
false
false
false
gobetti/Swift
GestureLongPress/GestureLongPress/ViewController.swift
1
1413
// // ViewController.swift // GestureLongPress // // Created by Carlos Butron on 01/12/14. // Copyright (c) 2015 Carlos Butron. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var image: UIImageView! override func viewDidLoad() { let longPressGesture = UILongPressGestureRecognizer(target: self, action: "action:") longPressGesture.minimumPressDuration = 2.0; image.addGestureRecognizer(longPressGesture) super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func action(gestureRecognizer:UIGestureRecognizer) { if (gestureRecognizer.state == UIGestureRecognizerState.Began){ let alertController = UIAlertController(title: "Alert", message: "Long Press gesture", preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true) { } } } }
mit
9ba8bf3884bb70e12daea5d37f288591
26.173077
122
0.607219
5.790984
false
false
false
false
akoi/healthkit-poc
healthkit-poc/Controllers/DetailViewController.swift
1
1754
// // DetailViewController.swift // healthkit-poc // import UIKit import HealthKit class DetailViewController: UIViewController { let healthStore = HealthStoreProvider.sharedInstance.healthStore var item: HealthItem? @IBOutlet weak var sampleSizeLbl: UILabel! @IBOutlet weak var queryIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() loadSamples() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func loadSamples() { if let i = item? { let name = i.name let sample = HKSampleType.quantityTypeForIdentifier(i.hkIdentifier) let query = HKSampleQuery(sampleType: sample, predicate: nil, limit: Int(HKObjectQueryNoLimit), sortDescriptors: nil) { query, results, error in if error != nil { // Perform proper error handling here... println("An error occured while fetching \(name) samples. \(error.localizedDescription)") self.sampleSizeLbl.text = "0" self.queryIndicator.stopAnimating() self.sampleSizeLbl.hidden = false } else { dispatch_async(dispatch_get_main_queue()) { println("Found \(results.count) samples for \(name)") self.sampleSizeLbl.text = String(results.count) self.queryIndicator.stopAnimating() self.sampleSizeLbl.hidden = false } } } self.healthStore!.executeQuery(query) } } }
unlicense
44c97bf38468118088afaf905f10725f
32.09434
131
0.565564
5.621795
false
false
false
false
tkremenek/swift
test/decl/protocol/special/DistributedActor.swift
2
876
// RUN: %target-typecheck-verify-swift -enable-experimental-distributed // REQUIRES: concurrency // REQUIRES: distributed import _Distributed // Synthesis of distributed actors. @available(SwiftStdlib 5.5, *) distributed actor D1 { var x: Int = 17 } @available(SwiftStdlib 5.5, *) distributed actor D2 { let actorTransport: String // expected-error{{invalid redeclaration of synthesized implementation for protocol requirement 'actorTransport'}} let id: String // expected-error{{invalid redeclaration of synthesized implementation for protocol requirement 'id'}} } // ==== Tests ------------------------------------------------------------------ // Make sure the conformances actually happen. @available(SwiftStdlib 5.5, *) func acceptActor<Act: DistributedActor>(_: Act.Type) { } @available(SwiftStdlib 5.5, *) func testConformance() { acceptActor(D1.self) }
apache-2.0
c40abb46ea0682baeb4f56ae8eb1c580
29.206897
143
0.692922
4.40201
false
true
false
false
Eonil/Editor
Editor4/DialogueUtility.swift
1
2035
//// //// DialogueUtility.swift //// Editor4 //// //// Created by Hoon H. on 2016/05/16. //// Copyright © 2016 Eonil. All rights reserved. //// // //import Foundation.NSURL //import AppKit //import BoltsSwift // ///// - TODO: Remake as a separated service. //struct DialogueUtility { // static func runFolderSaveDialogue() -> Task<NSURL> { // assertMainThread() // let c = SavePanelController() // let t = c.completionSource.task.continueWithTask { [c] (task: Task<NSURL>) -> Task<NSURL> in //// c.savePanel.close() // return task // } // switch c.savePanel.runModal() { // case NSFileHandlingPanelOKButton: // if let u = c.savePanel.URL { // c.completionSource.trySetResult(u) // return t // } // default: // break // } // c.completionSource.tryCancel() // return t // } // static func runFolderOpenDialogue() -> Task<NSURL> { // assertMainThread() // let c = OpenPanelController() // let t = c.completionSource.task.continueWithTask { [c] (task: Task<NSURL>) -> Task<NSURL> in // return task // } // switch c.openPanel.runModal() { // case NSFileHandlingPanelOKButton: // if let u = c.openPanel.URL { // c.completionSource.trySetResult(u) // return t // } // default: // break // } // c.completionSource.tryCancel() // return t // } //} // //private final class SavePanelController: NSObject, NSOpenSavePanelDelegate { // let savePanel = NSSavePanel() // let completionSource = TaskCompletionSource<NSURL>() //} //private final class OpenPanelController: NSObject { // let openPanel = NSOpenPanel() // let completionSource = TaskCompletionSource<NSURL>() // override init() { // super.init() // openPanel.canChooseFiles = false // openPanel.canChooseDirectories = true // } //}
mit
ac346304e00021509a8aa28acbbaa796
29.818182
102
0.564897
3.996071
false
false
false
false
xwu/swift
test/Generics/sr10752.swift
1
481
// RUN: %target-typecheck-verify-swift -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s // CHECK: sr10752.(file).P@ // CHECK-NEXT: Requirement signature: <Self where Self.A : P, Self.A == Self.A.A> protocol P { associatedtype A : P where A.A == A } // CHECK: sr10752.(file).Q@ // CHECK-NEXT: Requirement signature: <Self where Self.A == Self.C.A, Self.C : P> protocol Q { associatedtype A : P associatedtype C : P where A == C.A }
apache-2.0
0e35da9f2543f31285d7757ef6bd4ba3
33.357143
129
0.679834
3.063694
false
false
false
false
Jasdev/JDSActivityVC
JDSActivityViewController.swift
1
2135
import UIKit public class JDSActivityViewController: UIActivityViewController { private let defaultMargin: CGFloat = 16 private let maxURLHeight: CGFloat = 100 private let linkLabelInset: CGFloat = 10 private let linkViewBottomSpace: CGFloat = 10 private let animationDuration = 0.3 private let linkBlue = UIColor(red: 0.05, green: 0.39, blue: 1.0, alpha: 1.0) private var linkView: UIView! public var link: NSURL? = nil override public func viewDidLoad() { super.viewDidLoad() if let url = link { linkView = UIView() linkView.backgroundColor = .whiteColor() linkView.layer.cornerRadius = 3 linkView.alpha = 0 let linkLabel = UILabel() linkLabel.textAlignment = .Center linkLabel.textColor = linkBlue linkLabel.numberOfLines = 4 linkLabel.text = url.absoluteString linkLabel.font = linkLabel.font.fontWithSize(15) let finalLinkSize = linkLabel.sizeThatFits(CGSize(width: view.frame.width - defaultMargin - 2*linkLabelInset, height: maxURLHeight)) linkView.frame = CGRect(x: 0, y: -(linkViewBottomSpace + finalLinkSize.height + 2*linkLabelInset), width: view.frame.width - defaultMargin, height: finalLinkSize.height + 2*linkLabelInset) linkLabel.frame = CGRectInset(linkView.bounds, linkLabelInset, linkLabelInset) linkView.addSubview(linkLabel) view.addSubview(linkView) } } override public func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if let _ = link { UIView.animateWithDuration(animationDuration, animations: { [unowned self] () -> Void in self.linkView.alpha = 0.9 }) } } override public func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if let _ = link { UIView.animateWithDuration(animationDuration, animations: { [unowned self] () -> Void in self.linkView.alpha = 0 }) } } }
mit
e28aa619705d339b9b5782f3d38ebb77
32.359375
200
0.633255
4.919355
false
false
false
false
nikita-leonov/boss-client
BoSS/Services/ServiceLocator.swift
1
1243
// // ServiceLocator.swift // BoSS // // Created by Emanuele Rudel on 28/02/15. // Copyright (c) 2015 Bureau of Street Services. All rights reserved. // import Foundation private class BaseServiceContainer { } private class ServiceContainer<T> : BaseServiceContainer { let service: T init(_ s: T) { service = s } } class ServiceLocator { private var services = [String: BaseServiceContainer]() // MARK: - Registering and Accessing Services internal class func registerService<T>(service: T) { let key = "\(T.self)" ServiceLocator.sharedInstance.services[key] = ServiceContainer<T>(service) } internal class func getService<T>() -> T { let key = "\(T.self)" var result = ServiceLocator.sharedInstance.services[key] as? ServiceContainer<T> if result == nil { assertionFailure("WARNING: no service \(key) found") } return result!.service } // MARK: - Getting the Singleton private class var sharedInstance: ServiceLocator { struct Static { static let instance : ServiceLocator = ServiceLocator() } return Static.instance } }
mit
634e2fb9b2ac190d4a422a56df55010d
22.471698
88
0.612228
4.569853
false
false
false
false
shohei/firefox-ios
Client/Frontend/Browser/BrowserToolbar.swift
1
10400
/* 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 UIKit import SnapKit @objc protocol BrowserToolbarProtocol { weak var browserToolbarDelegate: BrowserToolbarDelegate? { get set } var shareButton: UIButton { get } var bookmarkButton: UIButton { get } var forwardButton: UIButton { get } var backButton: UIButton { get } var stopReloadButton: UIButton { get } func updateBackStatus(canGoBack: Bool) func updateForwardStatus(canGoForward: Bool) func updateBookmarkStatus(isBookmarked: Bool) func updateReloadStatus(isLoading: Bool) func updatePageStatus(#isWebPage: Bool) } @objc protocol BrowserToolbarDelegate: class { func browserToolbarDidPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidLongPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidLongPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressReload(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressStop(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidLongPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressShare(browserToolbar: BrowserToolbarProtocol, button: UIButton) } @objc public class BrowserToolbarHelper: NSObject { let toolbar: BrowserToolbarProtocol let ImageReload = UIImage(named: "reload") let ImageReloadPressed = UIImage(named: "reloadPressed") let ImageStop = UIImage(named: "stop") let ImageStopPressed = UIImage(named: "stopPressed") var loading: Bool = false { didSet { if loading { toolbar.stopReloadButton.setImage(ImageStop, forState: .Normal) toolbar.stopReloadButton.setImage(ImageStopPressed, forState: .Highlighted) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Stop", comment: "Accessibility Label for the browser toolbar Stop button") toolbar.stopReloadButton.accessibilityHint = NSLocalizedString("Tap to stop loading the page", comment: "") } else { toolbar.stopReloadButton.setImage(ImageReload, forState: .Normal) toolbar.stopReloadButton.setImage(ImageReloadPressed, forState: .Highlighted) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the browser toolbar Reload button") toolbar.stopReloadButton.accessibilityHint = NSLocalizedString("Tap to reload the page", comment: "") } } } init(toolbar: BrowserToolbarProtocol) { self.toolbar = toolbar super.init() toolbar.backButton.setImage(UIImage(named: "back"), forState: .Normal) toolbar.backButton.setImage(UIImage(named: "backPressed"), forState: .Highlighted) toolbar.backButton.accessibilityLabel = NSLocalizedString("Back", comment: "Accessibility Label for the browser toolbar Back button") //toolbar.backButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "") var longPressGestureBackButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressBack:") toolbar.backButton.addGestureRecognizer(longPressGestureBackButton) toolbar.backButton.addTarget(self, action: "SELdidClickBack", forControlEvents: UIControlEvents.TouchUpInside) toolbar.forwardButton.setImage(UIImage(named: "forward"), forState: .Normal) toolbar.forwardButton.setImage(UIImage(named: "forwardPressed"), forState: .Highlighted) toolbar.forwardButton.accessibilityLabel = NSLocalizedString("Forward", comment: "Accessibility Label for the browser toolbar Forward button") //toolbar.forwardButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "") var longPressGestureForwardButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressForward:") toolbar.forwardButton.addGestureRecognizer(longPressGestureForwardButton) toolbar.forwardButton.addTarget(self, action: "SELdidClickForward", forControlEvents: UIControlEvents.TouchUpInside) toolbar.stopReloadButton.setImage(UIImage(named: "reload"), forState: .Normal) toolbar.stopReloadButton.setImage(UIImage(named: "reloadPressed"), forState: .Highlighted) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the browser toolbar Reload button") toolbar.stopReloadButton.accessibilityHint = NSLocalizedString("Tap to reload page", comment: "") toolbar.stopReloadButton.addTarget(self, action: "SELdidClickStopReload", forControlEvents: UIControlEvents.TouchUpInside) toolbar.shareButton.setImage(UIImage(named: "send"), forState: .Normal) toolbar.shareButton.setImage(UIImage(named: "sendPressed"), forState: .Highlighted) toolbar.shareButton.accessibilityLabel = NSLocalizedString("Share", comment: "Accessibility Label for the browser toolbar Share button") toolbar.shareButton.addTarget(self, action: "SELdidClickShare", forControlEvents: UIControlEvents.TouchUpInside) toolbar.bookmarkButton.contentMode = UIViewContentMode.Center toolbar.bookmarkButton.setImage(UIImage(named: "bookmark"), forState: .Normal) toolbar.bookmarkButton.setImage(UIImage(named: "bookmarked"), forState: UIControlState.Selected) toolbar.bookmarkButton.accessibilityLabel = NSLocalizedString("Bookmark", comment: "Accessibility Label for the browser toolbar Bookmark button") var longPressGestureBookmarkButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressBookmark:") toolbar.bookmarkButton.addGestureRecognizer(longPressGestureBookmarkButton) toolbar.bookmarkButton.addTarget(self, action: "SELdidClickBookmark", forControlEvents: UIControlEvents.TouchUpInside) } func SELdidClickBack() { toolbar.browserToolbarDelegate?.browserToolbarDidPressBack(toolbar, button: toolbar.backButton) } func SELdidLongPressBack(recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { toolbar.browserToolbarDelegate?.browserToolbarDidLongPressBack(toolbar, button: toolbar.backButton) } } func SELdidClickShare() { toolbar.browserToolbarDelegate?.browserToolbarDidPressShare(toolbar, button: toolbar.shareButton) } func SELdidClickForward() { toolbar.browserToolbarDelegate?.browserToolbarDidPressForward(toolbar, button: toolbar.forwardButton) } func SELdidLongPressForward(recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { toolbar.browserToolbarDelegate?.browserToolbarDidLongPressForward(toolbar, button: toolbar.forwardButton) } } func SELdidClickBookmark() { toolbar.browserToolbarDelegate?.browserToolbarDidPressBookmark(toolbar, button: toolbar.bookmarkButton) } func SELdidLongPressBookmark(recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { toolbar.browserToolbarDelegate?.browserToolbarDidLongPressBookmark(toolbar, button: toolbar.bookmarkButton) } } func SELdidClickStopReload() { if loading { toolbar.browserToolbarDelegate?.browserToolbarDidPressStop(toolbar, button: toolbar.stopReloadButton) } else { toolbar.browserToolbarDelegate?.browserToolbarDidPressReload(toolbar, button: toolbar.stopReloadButton) } } func updateReloadStatus(isLoading: Bool) { loading = isLoading } } class BrowserToolbar: Toolbar, BrowserToolbarProtocol { weak var browserToolbarDelegate: BrowserToolbarDelegate? let shareButton: UIButton let bookmarkButton: UIButton let forwardButton: UIButton let backButton: UIButton let stopReloadButton: UIButton var helper: BrowserToolbarHelper? // This has to be here since init() calls it private override init(frame: CGRect) { // And these have to be initialized in here or the compiler will get angry backButton = UIButton() forwardButton = UIButton() stopReloadButton = UIButton() shareButton = UIButton() bookmarkButton = UIButton() super.init(frame: frame) self.helper = BrowserToolbarHelper(toolbar: self) addButtons(backButton, forwardButton, stopReloadButton, shareButton, bookmarkButton) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateBackStatus(canGoBack: Bool) { backButton.enabled = canGoBack } func updateForwardStatus(canGoForward: Bool) { forwardButton.enabled = canGoForward } func updateBookmarkStatus(isBookmarked: Bool) { bookmarkButton.selected = isBookmarked } func updateReloadStatus(isLoading: Bool) { helper?.updateReloadStatus(isLoading) } func updatePageStatus(#isWebPage: Bool) { bookmarkButton.enabled = isWebPage stopReloadButton.enabled = isWebPage shareButton.enabled = isWebPage } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() drawLine(context, start: CGPoint(x: 0, y: 0), end: CGPoint(x: frame.width, y: 0)) } private func drawLine(context: CGContextRef, start: CGPoint, end: CGPoint) { CGContextSetStrokeColorWithColor(context, UIColor.blackColor().colorWithAlphaComponent(0.05).CGColor) CGContextSetLineWidth(context, 2) CGContextMoveToPoint(context, start.x, start.y) CGContextAddLineToPoint(context, end.x, end.y) CGContextStrokePath(context) } }
mpl-2.0
1daf423577452ce16b6de2538c709fbe
46.926267
159
0.740577
5.739514
false
false
false
false
3pillarlabs/ios-audio-player
Framework/iOSAudioPlayer/iOSAudioPlayer/TPGAudioPlayer.swift
1
8413
// // TPGAudioPlayer.swift // swiftAudioPlayer // // Created by 3Pillar Global on 9/23/15. // Copyright © 2015 3PillarGlobal. All rights reserved. // import UIKit import AVFoundation /// Used in skipDirection: method. public enum SkipDirection: Double { case backward = -1, forward = 1 } public class TPGAudioPlayer: NSObject { static let internalInstance = TPGAudioPlayer() let player = AVPlayer() var playerDuration: Double? var currentPlayingItem: String? public var isPlaying: Bool { get { if player.rate == 0.0 { return false } return true } set { if newValue == true { player.play() if let _ = self.currentPlayingItem { SpringboardData().updateLockScreenCurrentTime(currentTime: currentTimeInSeconds) } } else { player.pause() } } } private var timeRangesObservation: Any? // MARK: PUBLIC METHODS /// Method used to return the total duration of the player item. public var durationInSeconds: Double { get { return playerDuration ?? kCMTimeZero.seconds } } public class func sharedInstance() -> TPGAudioPlayer { return self.internalInstance } /// Current time in seconds of the current player item. public var currentTimeInSeconds: Double { get { return player.currentTime().seconds } } public override init() { super.init() self.setupNotifications() } /// Method to be called whenever play or pause functionality is needed. /// /// __springboardInfo__ may contain the following keys: /// - kTitleKey: holds value of title String object /// - kAuthorKey - key for holding the author information /// - kDurationKey - length of the certain player item /// - kListScreenTitleKey - secondary information to be displayed on springboard in sleep mode /// - kImagePathKey - key to be used for holding the path of image to be displayed /// /// *springboardInfo* is an optional parameter, it can be set to nil if the feature of playing in background while /// the device is in sleep mode is desired to be ignored. /// /// - Parameters: /// - audioUrl: The resource that need to be processed. /// - springboardInfo: dictionary that contains useful information to be displayed when device is in sleep mode /// - startTime: Offset from where the certain processing should start /// - completion: Completion block. public func playPauseMediaFile(audioUrl: NSURL, springboardInfo: Dictionary <String, AnyObject>, startTime: Double, completion: @escaping (_ previousItem: String?, _ stopTime: Double) -> ()) { let stopTime = self.currentTimeInSeconds if audioUrl.absoluteString == self.currentPlayingItem { // Current episode playing self.isPlaying = !self.isPlaying completion(nil, stopTime) return } // Other episode to load // Load new episode DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { let options = [AVURLAssetReferenceRestrictionsKey : 0] let playerAsset = AVURLAsset(url: audioUrl as URL, options: options) self.playerDuration = playerAsset.duration.seconds DispatchQueue.main.async(execute: { //Episode Loaded self.prepareAndPlay(playerAsset: playerAsset, startTime: startTime, completion: { () -> Void in //Ready to play let previousPlayingItem = self.currentPlayingItem self.currentPlayingItem = audioUrl.absoluteString completion(previousPlayingItem, stopTime) SpringboardData().setupLockScreenElementsWithDictionary( infoDictionary: springboardInfo as NSDictionary ) }) }) } } /* Method used for skiping a certain time interval from an audio resourse */ public func skipDirection(skipDirection: SkipDirection, timeInterval: Double, offset: Double) { let skipPercentage = timeInterval / self.durationInSeconds let newTime = CMTimeMakeWithSeconds(offset + ((skipDirection.rawValue * skipPercentage) * 2000.0), 100) player.seek(to: newTime) { (finished) -> Void in SpringboardData().updateLockScreenCurrentTime(currentTime: self.currentTimeInSeconds) } } /* Set the current player to a certain time from an input value */ public func seekPlayerToTime(value: Double, completion: (() -> Void)!) { let newTime = CMTimeMakeWithSeconds(value, 100) player.seek(to: newTime, completionHandler: { (finished) -> Void in if completion != nil { DispatchQueue.main.async(execute: { () -> Void in completion() }) } }) } /*************************************/ // MARK: NOTIFICATION METHODS /*************************************/ @objc func playingStalled(_ notification: NSNotification) { NotificationCenter.default.post(name: .playerStalled, object: player.currentItem) } @objc func playerDidReachEnd(_ notification: NSNotification) { self.player.seek(to: kCMTimeZero) NotificationCenter.default.post(name: .playerDidReachEnd, object: nil) } @objc func playerItemTimeJumpedNotification(_ notification: NSNotification) { NotificationCenter.default.post(name: .playerTimeDidChange, object: NSNumber(value: self.currentTimeInSeconds)) } /*************************************/ // MARK: PRIVATE METHODS /*************************************/ func setupNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(TPGAudioPlayer.playerDidReachEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(TPGAudioPlayer.playingStalled(_:)), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: player.currentItem) NotificationCenter.default.addObserver(self, selector: #selector(TPGAudioPlayer.playerItemTimeJumpedNotification(_:)), name: NSNotification.Name.AVPlayerItemTimeJumped, object: nil) } func prepareAndPlay(playerAsset: AVURLAsset, startTime: Double, completion: @escaping (() -> Void)) { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) UIApplication.shared.beginReceivingRemoteControlEvents() } catch { // Code to be added in case of audio session setup error print(error) } self.player.pause() // remove kvo for current item timeRangesObservation = nil // load new asset let newPlayerItem = AVPlayerItem(asset: playerAsset) // replace current item with new player item self.player.replaceCurrentItem(with: newPlayerItem) if let _ = self.player.currentItem { timeRangesObservation = player.currentItem?.observe(\.loadedTimeRanges, changeHandler: { (playerItem, change) in guard let timeRanges = change.newValue else { return } guard let firstTimeRange = timeRanges.first else { return } let timeRange = firstTimeRange.timeRangeValue let loadedAmout = timeRange.start.seconds + timeRange.duration.seconds let loadedPercentage = (loadedAmout * 100.0) / self.durationInSeconds NotificationCenter.default.post(name: .mediaLoadProgress, object: NSNumber(value: loadedPercentage)) }) } // seek player to offset self.seekPlayerToTime(value: startTime, completion: { [unowned self] in self.player.play() completion() }) } }
mit
8eb9af8fea9dc93b7dfbd30f202bfd6a
36.553571
196
0.606277
5.469441
false
false
false
false
Lyokone/flutterlocation
packages/location_ios/ios/Classes/SwiftLocationPlugin.swift
1
9512
import Flutter import UIKit import SwiftLocation import CoreLocation @UIApplicationMain public class SwiftLocationPlugin: NSObject, FlutterPlugin, LocationHostApi, UIApplicationDelegate { var globalPigeonLocationSettings: PigeonLocationSettings? var streamHandler: StreamHandler? init(_ messenger: FlutterBinaryMessenger, _ registrar: FlutterPluginRegistrar) { super.init() let eventChannel = FlutterEventChannel(name: "lyokone/location_stream", binaryMessenger: messenger) self.streamHandler = StreamHandler() eventChannel.setStreamHandler(self.streamHandler) registrar.addApplicationDelegate(self) } public func getLocationSettings(_ settings: PigeonLocationSettings?, completion: @escaping (PigeonLocationData?, FlutterError?) -> Void) { if !CLLocationManager.locationServicesEnabled() { UIApplication.shared.open(URL(string:UIApplication.openSettingsURLString)!) return completion(nil, FlutterError(code: "LOCATION_SERVICE_DISABLED", message: "The user have deactivated the location service, the settings page has been opened", details: nil)) } let currentSettings = SwiftLocationPlugin.locationSettingsToGPSLocationOptions(settings ?? globalPigeonLocationSettings) if globalPigeonLocationSettings?.ignoreLastKnownPosition == false { let lastKnownPosition = SwiftLocation.lastKnownGPSLocation if (lastKnownPosition != nil) { completion(SwiftLocationPlugin.locationToData(lastKnownPosition!), nil) return; } } SwiftLocation.gpsLocationWith(currentSettings ?? getDefaultGPSLocationOptions()).then { result in // you can attach one or more subscriptions via `then`. switch result { case .success(let location): completion(SwiftLocationPlugin.locationToData(location), nil) case .failure(let error): completion(nil, FlutterError(code: "LOCATION_ERROR", message: error.localizedDescription, details: error.recoverySuggestion)) } } } static public func locationToData(_ location: CLLocation) -> PigeonLocationData { if #available(iOS 13.4, *) { return PigeonLocationData.make( withLatitude: NSNumber(value: location.coordinate.latitude), longitude: NSNumber(value: location.coordinate.longitude), accuracy: NSNumber(value: location.horizontalAccuracy), altitude: NSNumber(value: location.altitude), bearing: NSNumber(value: location.course), bearingAccuracyDegrees: NSNumber(value: location.courseAccuracy), elaspedRealTimeNanos: nil, elaspedRealTimeUncertaintyNanos: nil, satellites: nil, speed: NSNumber(value: location.speed), speedAccuracy: NSNumber(value: location.speedAccuracy), time: NSNumber(value: location.timestamp.timeIntervalSince1970), verticalAccuracy: NSNumber(value: location.verticalAccuracy), isMock: false) } return PigeonLocationData.make( withLatitude: NSNumber(value: location.coordinate.latitude), longitude: NSNumber(value: location.coordinate.longitude), accuracy: NSNumber(value: location.horizontalAccuracy), altitude: NSNumber(value: location.altitude), bearing: NSNumber(value: location.course), bearingAccuracyDegrees: nil, elaspedRealTimeNanos: nil, elaspedRealTimeUncertaintyNanos: nil, satellites: nil, speed: NSNumber(value: location.speed), speedAccuracy: NSNumber(value: location.speedAccuracy), time: NSNumber(value: location.timestamp.timeIntervalSince1970), verticalAccuracy: NSNumber(value: location.verticalAccuracy), isMock: false) } public func getDefaultGPSLocationOptions() -> GPSLocationOptions { let defaultOption = GPSLocationOptions() defaultOption.minTimeInterval = 2 defaultOption.subscription = .single return defaultOption } static private func mapAccuracy (_ accuracy: PigeonLocationAccuracy) -> GPSLocationOptions.Accuracy { switch (accuracy) { case .powerSave: return GPSLocationOptions.Accuracy.city case .low: return GPSLocationOptions.Accuracy.block case .balanced: return GPSLocationOptions.Accuracy.house case .high: return GPSLocationOptions.Accuracy.room case .navigation: return GPSLocationOptions.Accuracy.room @unknown default: return GPSLocationOptions.Accuracy.room } } static public func locationSettingsToGPSLocationOptions(_ settings: PigeonLocationSettings?) -> GPSLocationOptions? { if (settings == nil) { return nil } let options = GPSLocationOptions() let minTimeInterval = settings?.interval let accuracy = settings?.accuracy let askForPermission = settings?.askForPermission let minDistance = settings?.smallestDisplacement options.activityType = .automotiveNavigation options.subscription = .single if (minTimeInterval != nil) { options.minTimeInterval = Double(Int(truncating: minTimeInterval!) / 1000) } if (accuracy != nil) { options.accuracy = mapAccuracy(accuracy!) } if (askForPermission == false) { options.avoidRequestAuthorization = true } if (minDistance != nil) { options.minDistance = Double(truncating: minDistance!) } return options } public func setLocationSettingsSettings(_ settings: PigeonLocationSettings, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) -> NSNumber? { globalPigeonLocationSettings = settings; return NSNumber(true) } static public func getPermissionNumber() -> NSNumber { let currentStatus = SwiftLocation.authorizationStatus switch currentStatus { case .notDetermined: return 0 case .restricted: return 1 case .denied: return 2 case .authorizedAlways: return 3 case .authorizedWhenInUse: return 4 case .authorized: return 3 @unknown default: return 5 } } public func getPermissionStatusWithError(_ error: AutoreleasingUnsafeMutablePointer<FlutterError?>) -> NSNumber? { return SwiftLocationPlugin.getPermissionNumber() } public func requestPermission(completion: @escaping (NSNumber?, FlutterError?) -> Void) { SwiftLocation.requestAuthorization(.onlyInUse) { newStatus in switch newStatus { case .notDetermined: completion(0, nil) case .restricted: completion(1, nil) case .denied: completion(2, nil) case .authorizedAlways: completion(3, nil) case .authorizedWhenInUse: completion(4, nil) case .authorized: completion(3, nil) @unknown default: completion(5, nil) } } } public func isGPSEnabledWithError(_ error: AutoreleasingUnsafeMutablePointer<FlutterError?>) -> NSNumber? { if CLLocationManager.locationServicesEnabled() { return NSNumber(true) } return NSNumber(false) } public func isNetworkEnabledWithError(_ error: AutoreleasingUnsafeMutablePointer<FlutterError?>) -> NSNumber? { if CLLocationManager.locationServicesEnabled() { return NSNumber(true) } return NSNumber(false) } // Not applicable to iOS public func changeNotificationSettingsSettings(_ settings: PigeonNotificationSettings, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) -> NSNumber? { return NSNumber(true) } public func setBackgroundActivatedActivated(_ activated: NSNumber, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) -> NSNumber? { SwiftLocation.allowsBackgroundLocationUpdates = activated.boolValue return NSNumber(true) } public static func register(with registrar: FlutterPluginRegistrar) { let messenger : FlutterBinaryMessenger = registrar.messenger() let api : LocationHostApi & NSObjectProtocol = SwiftLocationPlugin.init(messenger, registrar) LocationHostApiSetup(messenger, api); } @nonobjc public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [AnyHashable : Any] = [:]) -> Bool { return true } }
mit
3fc8f8e29dab15588c8576e667572a25
37.82449
162
0.617641
6.09353
false
false
false
false
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/SettingsFeature/SettingsFeatureCore.swift
1
3759
import ComposableArchitecture import FileClient import Helpers import SharedModels import UIApplicationClient import UIKit.UIInterface public struct SettingsFeature: ReducerProtocol { public init() {} // MARK: State @Dependency(\.fileClient) public var fileClient @Dependency(\.mainQueue) public var mainQueue @Dependency(\.uiApplicationClient) public var uiApplicationClient public struct State: Equatable { public var userSettings: UserSettings public init( userSettings: UserSettings = UserSettings() ) { self.userSettings = userSettings } var versionNumber: String { "Critical Maps \(Bundle.main.versionNumber)" } var buildNumber: String { "Build \(Bundle.main.buildNumber)" } var acknowledgementsPlistPath: String? { guard let path = Bundle.module.path(forResource: "Acknowledgements", ofType: "plist") else { return nil } return path } } // MARK: Actions public enum Action: Equatable { case onAppear case binding(BindingAction<State>) case supportSectionRowTapped(SettingsFeature.State.SupportSectionRow) case infoSectionRowTapped(SettingsFeature.State.InfoSectionRow) case setObservationMode(Bool) case openURL(URL) case appearance(AppearanceSettingsFeature.Action) case rideevent(RideEventsSettingsFeature.Action) } // MARK: Reducer public var body: some ReducerProtocol<State, Action> { Scope( state: \.userSettings.appearanceSettings, action: /SettingsFeature.Action.appearance ) { AppearanceSettingsFeature() } Scope(state: \.userSettings.rideEventSettings, action: /SettingsFeature.Action.rideevent) { RideEventsSettingsFeature() } Reduce<State, Action> { state, action in switch action { case .onAppear: state.userSettings.appearanceSettings.appIcon = uiApplicationClient.alternateIconName() .flatMap(AppIcon.init(rawValue:)) ?? .appIcon2 return .none case let .infoSectionRowTapped(row): return Effect(value: .openURL(row.url)) case let .supportSectionRowTapped(row): return Effect(value: .openURL(row.url)) case let .openURL(url): return .fireAndForget { await uiApplicationClient.open(url, [:]) } case let .setObservationMode(value): state.userSettings.enableObservationMode = value return .none case .binding: return .none case .appearance, .rideevent: enum SaveDebounceId {} let userSettings = state.userSettings return .fireAndForget { try await withTaskCancellation(id: SaveDebounceId.self, cancelInFlight: true) { try await mainQueue.sleep(for: .seconds(0.3)) try await fileClient.saveUserSettings(userSettings: userSettings) } } } } } } // MARK: Helper public extension SettingsFeature.State { enum InfoSectionRow: Equatable { case website, twitter, privacy public var url: URL { switch self { case .website: return URL(string: "https://www.criticalmaps.net")! case .twitter: return URL(string: "https://twitter.com/criticalmaps/")! case .privacy: return URL(string: "https://www.criticalmaps.net/info")! } } } enum SupportSectionRow: Equatable { case github, criticalMassDotIn, crowdin public var url: URL { switch self { case .github: return URL(string: "https://github.com/criticalmaps/criticalmaps-ios")! case .criticalMassDotIn: return URL(string: "https://criticalmass.in")! case .crowdin: return URL(string: "https://crowdin.com/project/critical-maps")! } } } }
mit
f3af4cd8908ec3e9203dcea01e3f2c93
26.639706
98
0.671987
4.61227
false
false
false
false
wireapp/wire-ios-data-model
Source/Model/Conversation/ZMConversation+Role.swift
1
1886
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation public enum UpdateRoleError: Error { case unknown } public class UpdateRoleAction: EntityAction { public var resultHandler: ResultHandler? public typealias Result = Void public typealias Failure = UpdateRoleError public let userID: NSManagedObjectID public let conversationID: NSManagedObjectID public let roleID: NSManagedObjectID public required init(user: ZMUser, conversation: ZMConversation, role: Role) { userID = user.objectID conversationID = conversation.objectID roleID = role.objectID } } extension ZMConversation { public func updateRole(of participant: UserType, to newRole: Role, completion: @escaping UpdateRoleAction.ResultHandler) { guard let context = managedObjectContext, let user = participant as? ZMUser else { return completion(.failure(UpdateRoleError.unknown)) } var action = UpdateRoleAction(user: user, conversation: self, role: newRole) action.onResult(resultHandler: completion) action.send(in: context.notificationContext) } }
gpl-3.0
dd85dd042f3cf76b9139c93312b22aca
32.087719
84
0.697243
4.950131
false
false
false
false
bsmith11/ScoreReporter
ScoreReporterCore/ScoreReporterCore/Extensions/Date+Extensions.swift
1
1447
// // Date+Extensions.swift // ScoreReporter // // Created by Bradley Smith on 7/19/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation public extension Date { static func date(fromDate date: Date?, time: Date?) -> Date? { guard let date = date, let time = time else { return nil } guard let timeZone = TimeZone(abbreviation: "UTC") else { print("Failed to initialize UTC timezone") return nil } var calendar = Calendar.current calendar.timeZone = timeZone var dateComponents = calendar.dateComponents([.day, .month, .year], from: date) let timeComponents = calendar.dateComponents([.hour, .minute], from: time) dateComponents.hour = timeComponents.hour dateComponents.minute = timeComponents.minute return calendar.date(from: dateComponents) } static var enclosingDatesForCurrentWeek: (Date, Date) { var calendar = Calendar.current calendar.firstWeekday = 2 var startDate: NSDate? = nil var interval: TimeInterval = 0.0 (calendar as NSCalendar).range(of: .weekOfYear, start: &startDate, interval: &interval, for: Date()) let endDate = startDate?.addingTimeInterval(interval) let start = startDate as? Date ?? Date() let end = endDate as? Date ?? Date() return (start, end) } }
mit
168908182fa5fad5f5974a1a41ee1cc3
27.92
108
0.623098
4.634615
false
false
false
false
bignerdranch/Deferred
Tests/TaskTests/TaskCompositionTests.swift
1
8903
// // TaskCompositionTests.swift // Deferred // // Created by Zachary Waldowski on 4/12/20. // Copyright © 2020 Big Nerd Ranch. Licensed under MIT. // import XCTest #if SWIFT_PACKAGE import Deferred import Task #else import Deferred #endif class TaskCompositionTests: CustomExecutorTestCase { struct Type1 {} struct Type2 {} struct Type3 {} struct Type4 {} struct Type5 {} struct Type6 {} struct Type7 {} struct Type8 {} func testAndSuccess() { let toBeCombined1 = Task<Type1>.Promise() let toBeCombined2 = Task<Type2>.Promise() let combined = toBeCombined1.andSuccess(of: toBeCombined2) let expect = expectation(description: "Combined task delivered its result once") combined.uponSuccess { _ in expect.fulfill() } XCTAssertFalse(combined.isFilled) toBeCombined1.succeed(with: Type1()) XCTAssertFalse(combined.isFilled) toBeCombined2.succeed(with: Type2()) wait(for: [ expect ], timeout: shortTimeout) XCTAssertTrue(combined.isFilled) } func testAndSuccess3() { let toBeCombined1 = Task<Type1>.Promise() let toBeCombined2 = Task<Type2>.Promise() let toBeCombined3 = Task<Type3>.Promise() let combined = toBeCombined1.andSuccess(of: toBeCombined2, toBeCombined3) let expect = expectation(description: "Combined task delivered its result once") combined.uponSuccess { _ in expect.fulfill() } XCTAssertFalse(combined.isFilled) toBeCombined1.succeed(with: Type1()) XCTAssertFalse(combined.isFilled) toBeCombined2.succeed(with: Type2()) XCTAssertFalse(combined.isFilled) toBeCombined3.succeed(with: Type3()) wait(for: [ expect ], timeout: shortTimeout) XCTAssertTrue(combined.isFilled) } func testAndSuccess4() { let toBeCombined1 = Task<Type1>.Promise() let toBeCombined2 = Task<Type2>.Promise() let toBeCombined3 = Task<Type3>.Promise() let toBeCombined4 = Task<Type4>.Promise() let combined = toBeCombined1.andSuccess(of: toBeCombined2, toBeCombined3, toBeCombined4) let expect = expectation(description: "Combined task delivered its result once") combined.uponSuccess { _ in expect.fulfill() } XCTAssertFalse(combined.isFilled) toBeCombined1.succeed(with: Type1()) XCTAssertFalse(combined.isFilled) toBeCombined2.succeed(with: Type2()) XCTAssertFalse(combined.isFilled) toBeCombined3.succeed(with: Type3()) XCTAssertFalse(combined.isFilled) toBeCombined4.succeed(with: Type4()) wait(for: [ expect ], timeout: shortTimeout) XCTAssertTrue(combined.isFilled) } func testAndSuccess5() { let toBeCombined1 = Task<Type1>.Promise() let toBeCombined2 = Task<Type2>.Promise() let toBeCombined3 = Task<Type3>.Promise() let toBeCombined4 = Task<Type4>.Promise() let toBeCombined5 = Task<Type5>.Promise() let combined = toBeCombined1.andSuccess(of: toBeCombined2, toBeCombined3, toBeCombined4, toBeCombined5) let expect = expectation(description: "Combined task delivered its result once") combined.uponSuccess { _ in expect.fulfill() } XCTAssertFalse(combined.isFilled) toBeCombined1.succeed(with: Type1()) XCTAssertFalse(combined.isFilled) toBeCombined2.succeed(with: Type2()) XCTAssertFalse(combined.isFilled) toBeCombined3.succeed(with: Type3()) XCTAssertFalse(combined.isFilled) toBeCombined4.succeed(with: Type4()) XCTAssertFalse(combined.isFilled) toBeCombined5.succeed(with: Type5()) wait(for: [ expect ], timeout: shortTimeout) XCTAssertTrue(combined.isFilled) } func testAndSuccess6() { let toBeCombined1 = Task<Type1>.Promise() let toBeCombined2 = Task<Type2>.Promise() let toBeCombined3 = Task<Type3>.Promise() let toBeCombined4 = Task<Type4>.Promise() let toBeCombined5 = Task<Type5>.Promise() let toBeCombined6 = Task<Type6>.Promise() let combined = toBeCombined1.andSuccess(of: toBeCombined2, toBeCombined3, toBeCombined4, toBeCombined5, toBeCombined6) let expect = expectation(description: "Combined task delivered its result once") combined.uponSuccess { _ in expect.fulfill() } XCTAssertFalse(combined.isFilled) toBeCombined1.succeed(with: Type1()) XCTAssertFalse(combined.isFilled) toBeCombined2.succeed(with: Type2()) XCTAssertFalse(combined.isFilled) toBeCombined3.succeed(with: Type3()) XCTAssertFalse(combined.isFilled) toBeCombined4.succeed(with: Type4()) XCTAssertFalse(combined.isFilled) toBeCombined5.succeed(with: Type5()) XCTAssertFalse(combined.isFilled) toBeCombined6.succeed(with: Type6()) wait(for: [ expect ], timeout: shortTimeout) XCTAssertTrue(combined.isFilled) } func testAndSuccess7() { let toBeCombined1 = Task<Type1>.Promise() let toBeCombined2 = Task<Type2>.Promise() let toBeCombined3 = Task<Type3>.Promise() let toBeCombined4 = Task<Type4>.Promise() let toBeCombined5 = Task<Type5>.Promise() let toBeCombined6 = Task<Type6>.Promise() let toBeCombined7 = Task<Type7>.Promise() let combined = toBeCombined1.andSuccess(of: toBeCombined2, toBeCombined3, toBeCombined4, toBeCombined5, toBeCombined6, toBeCombined7) let expect = expectation(description: "Combined task delivered its result once") combined.uponSuccess { _ in expect.fulfill() } XCTAssertFalse(combined.isFilled) toBeCombined1.succeed(with: Type1()) XCTAssertFalse(combined.isFilled) toBeCombined2.succeed(with: Type2()) XCTAssertFalse(combined.isFilled) toBeCombined3.succeed(with: Type3()) XCTAssertFalse(combined.isFilled) toBeCombined4.succeed(with: Type4()) XCTAssertFalse(combined.isFilled) toBeCombined5.succeed(with: Type5()) XCTAssertFalse(combined.isFilled) toBeCombined6.succeed(with: Type6()) XCTAssertFalse(combined.isFilled) toBeCombined7.succeed(with: Type7()) wait(for: [ expect ], timeout: shortTimeout) XCTAssertTrue(combined.isFilled) } func testAndSuccess8() { let toBeCombined1 = Task<Type1>.Promise() let toBeCombined2 = Task<Type2>.Promise() let toBeCombined3 = Task<Type3>.Promise() let toBeCombined4 = Task<Type4>.Promise() let toBeCombined5 = Task<Type5>.Promise() let toBeCombined6 = Task<Type6>.Promise() let toBeCombined7 = Task<Type7>.Promise() let toBeCombined8 = Task<Type8>.Promise() let combined = toBeCombined1.andSuccess(of: toBeCombined2, toBeCombined3, toBeCombined4, toBeCombined5, toBeCombined6, toBeCombined7, toBeCombined8) let expect = expectation(description: "Combined task delivered its result once") combined.uponSuccess { _ in expect.fulfill() } XCTAssertFalse(combined.isFilled) toBeCombined1.succeed(with: Type1()) XCTAssertFalse(combined.isFilled) toBeCombined2.succeed(with: Type2()) XCTAssertFalse(combined.isFilled) toBeCombined3.succeed(with: Type3()) XCTAssertFalse(combined.isFilled) toBeCombined4.succeed(with: Type4()) XCTAssertFalse(combined.isFilled) toBeCombined5.succeed(with: Type5()) XCTAssertFalse(combined.isFilled) toBeCombined6.succeed(with: Type6()) XCTAssertFalse(combined.isFilled) toBeCombined7.succeed(with: Type7()) XCTAssertFalse(combined.isFilled) toBeCombined8.succeed(with: Type8()) wait(for: [ expect ], timeout: shortTimeout) XCTAssertTrue(combined.isFilled) } func testAndSuccessFailure() { let toBeCombined1 = Task<Type1>.Promise() let toBeCombined2 = Task<Type2>.Promise() let combined = toBeCombined1.andSuccess(of: toBeCombined2) let expect = expectation(description: "Combined task delivered a failure once") combined.uponFailure { error in expect.fulfill() XCTAssertEqual(error as? TestError, .fourth) } XCTAssertFalse(combined.isFilled) toBeCombined2.fail(with: TestError.fourth) wait(for: [ expect ], timeout: shortTimeout) XCTAssertTrue(combined.isFilled) } }
mit
8a9a5694e0007c6d2a73c1f6da732819
30.792857
88
0.648281
4.757883
false
false
false
false
younata/RSSClient
TethysAppSpecs/UI/Feeds/FeedDetailViewSpec.swift
1
17754
import Quick import Nimble import Tethys class FakeFeedDetailViewDelegate: FeedDetailViewDelegate { var urlDidChangeCallCount = 0 private var urlDidChangeArgs: [(FeedDetailView, URL)] = [] func urlDidChangeArgsForCall(_ callIndex: Int) -> (FeedDetailView, URL) { return self.urlDidChangeArgs[callIndex] } func feedDetailView(_ feedDetailView: FeedDetailView, urlDidChange url: URL) { self.urlDidChangeArgs.append((feedDetailView, url)) self.urlDidChangeCallCount += 1 } var tagsDidChangeCallCount = 0 private var tagsDidChangeArgs: [(FeedDetailView, [String])] = [] func tagsDidChangeArgsForCall(_ callIndex: Int) -> (FeedDetailView, [String]) { return self.tagsDidChangeArgs[callIndex] } func feedDetailView(_ feedDetailView: FeedDetailView, tagsDidChange tags: [String]) { self.tagsDidChangeCallCount += 1 self.tagsDidChangeArgs.append((feedDetailView, tags)) } var editTagCallCount = 0 private var editTagArgs: [(FeedDetailView, String?, (String) -> (Void))] = [] func editTagArgsForCall(_ callIndex: Int) -> (FeedDetailView, String?, (String) -> (Void)) { return self.editTagArgs[callIndex] } func feedDetailView(_ feedDetailView: FeedDetailView, editTag tag: String?, completion: @escaping (String) -> (Void)) { self.editTagCallCount += 1 self.editTagArgs.append((feedDetailView, tag, completion)) } } class FeedDetailViewSpec: QuickSpec { override func spec() { var subject: FeedDetailView! var delegate: FakeFeedDetailViewDelegate! var tableView: UITableView! beforeEach { delegate = FakeFeedDetailViewDelegate() subject = FeedDetailView(forAutoLayout: ()) subject.delegate = delegate tableView = subject.tagsList.tableView } describe("the theme") { it("sets the background color") { expect(subject.backgroundColor).to(equal(Theme.backgroundColor)) } it("sets the titleLabel text color") { expect(subject.titleLabel.textColor).to(equal(Theme.textColor)) } it("sets the summaryLabel's text color") { expect(subject.summaryLabel.textColor).to(equal(Theme.textColor)) } it("sets the addTagButton's title color") { expect(subject.addTagButton.titleColor(for: .normal)).to(equal(Theme.highlightColor)) } } it("is configured for accessibility") { expect(subject.isAccessibilityElement).to(beFalse()) expect(subject.titleLabel.isAccessibilityElement).to(beTrue()) expect(subject.urlField.isAccessibilityElement).to(beTrue()) expect(subject.summaryLabel.isAccessibilityElement).to(beTrue()) expect(subject.addTagButton.isAccessibilityElement).to(beTrue()) expect(subject.titleLabel.accessibilityTraits).to(equal([.staticText])) expect(subject.summaryLabel.accessibilityTraits).to(equal([.staticText])) expect(subject.addTagButton.accessibilityTraits).to(equal([.button])) expect(subject.addTagButton.accessibilityLabel).to(equal("Add Tag")) } describe("configure(title:url:summary:tags:)") { let tags = ["hello", "goodbye"] beforeEach { subject.configure(title: "title", url: URL(string: "https://example.com")!, summary: "summary", tags: tags) } it("sets the titleLabel's text") { expect(subject.titleLabel.text).to(equal("title")) expect(subject.titleLabel.accessibilityLabel).to(equal("Feed title")) expect(subject.titleLabel.accessibilityValue).to(equal("title")) } it("sets the urlField's text") { expect(subject.urlField.text).to(equal("https://example.com")) expect(subject.urlField.accessibilityLabel).to(equal("Feed URL")) expect(subject.urlField.accessibilityValue).to(equal("https://example.com")) } it("sets the summaryLabel's text") { expect(subject.summaryLabel.text).to(equal("summary")) expect(subject.summaryLabel.accessibilityLabel).to(equal("Feed summary")) expect(subject.summaryLabel.accessibilityValue).to(equal("summary")) } it("sets the tagsList's cells") { expect(tableView.numberOfRows(inSection: 0)) == tags.count for (idx, tag) in tags.enumerated() { let indexPath = IndexPath(row: idx, section: 0) let cell = tableView.dataSource?.tableView(tableView, cellForRowAt: indexPath) expect(cell?.textLabel?.text) == tag } } it("doesn't call the delegate over the url field text changing") { expect(delegate.urlDidChangeCallCount) == 0 } } describe("the urlField's delegate") { it("calls the delegate whenever the characters change and produce a valid url") { _ = subject.urlField.delegate?.textField?(subject.urlField, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: "https://example.com") expect(delegate.urlDidChangeCallCount) == 1 guard delegate.urlDidChangeCallCount == 1 else { return } let args = delegate.urlDidChangeArgsForCall(0) expect(args.0) === subject expect(args.1) == URL(string: "https://example.com") } it("doesn't call the delegate if the characters produce an invalid url") { _ = subject.urlField.delegate?.textField?(subject.urlField, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: "hello") expect(delegate.urlDidChangeCallCount) == 0 } } describe("the tagsList") { let tags = ["hello", "goodbye"] beforeEach { subject.configure(title: "", url: URL(string: "https://example.com")!, summary: "", tags: tags) } it("has a cell for each tag") { expect(tableView.numberOfRows(inSection: 0)) == tags.count } describe("a cell") { let indexPath = IndexPath(row: 0, section: 0) var cell: TableViewCell? beforeEach { cell = tableView.cellForRow(at: indexPath) as? TableViewCell } it("titles the cell for the tag") { expect(cell?.textLabel?.text).to(equal("hello")) } it("configures the cell for accessibility") { expect(cell?.isAccessibilityElement).to(beTrue()) expect(cell?.accessibilityTraits).to(equal([.button])) expect(cell?.accessibilityLabel).to(equal("Tag")) expect(cell?.accessibilityValue).to(equal("hello")) } describe("the contextual actions") { var swipeActions: UISwipeActionsConfiguration? = nil var completionHandlerCalls: [Bool] = [] beforeEach { completionHandlerCalls = [] swipeActions = tableView.delegate?.tableView?(tableView, trailingSwipeActionsConfigurationForRowAt: indexPath) } it("automatically performs the first action if full swipe") { expect(swipeActions?.performsFirstActionWithFullSwipe).to(beTrue()) } it("has two actions") { expect(swipeActions?.actions).to(haveCount(2)) } describe("the first action") { var action: UIContextualAction? beforeEach { action = swipeActions?.actions.first } it("is titled 'Delete'") { expect(action?.title) == "Delete" } describe("when tapped") { beforeEach { action?.handler(action!, subject, { completionHandlerCalls.append($0) }) } it("deletes the cell from the tags list") { expect(tableView.numberOfRows(inSection: 0)) == (tags.count - 1) let newCell = tableView.dataSource?.tableView(tableView, cellForRowAt: indexPath) expect(newCell?.textLabel?.text) == tags[1] } it("informs the delegate that the tags changed") { expect(delegate.tagsDidChangeCallCount) == 1 guard delegate.tagsDidChangeCallCount == 1 else { return } let args = delegate.tagsDidChangeArgsForCall(0) expect(args.0) === subject expect(args.1) == ["goodbye"] } it("calls the completion handler") { expect(completionHandlerCalls).to(equal([true])) } } } describe("the second edit action") { var action: UIContextualAction? beforeEach { action = swipeActions?.actions.last } it("is titled 'Edit'") { expect(action?.title) == "Edit" } describe("when tapped") { beforeEach { action?.handler(action!, subject, { completionHandlerCalls.append($0) }) } it("informs its delegate when tapped") { expect(delegate.editTagCallCount) == 1 guard delegate.editTagCallCount == 1 else { return } let args = delegate.editTagArgsForCall(0) expect(args.0) === subject expect(args.1) == tags[0] } it("does not yet call the completion handler") { expect(completionHandlerCalls).to(beEmpty()) } describe("when the delegate calls the callback") { beforeEach { guard delegate.editTagCallCount == 1 else { fail("delegate not called") return } let callback = delegate.editTagArgsForCall(0).2 callback("callback string") } it("replaces the text of the cell with the text the user gave") { expect(tableView.numberOfRows(inSection: 0)) == 2 let newCell = tableView.dataSource?.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 0)) expect(newCell?.textLabel?.text) == "callback string" let oldCell = tableView.dataSource?.tableView(tableView, cellForRowAt: IndexPath(row: 1, section: 0)) expect(oldCell?.textLabel?.text) == "goodbye" } it("calls the delegate to inform it that the user changed the tags") { expect(delegate.tagsDidChangeCallCount) == 1 guard delegate.tagsDidChangeCallCount == 1 else { return } let args = delegate.tagsDidChangeArgsForCall(0) expect(args.0) === subject expect(args.1) == ["callback string", "goodbye"] } it("calls the completion handler") { expect(completionHandlerCalls).to(equal([true])) } } } } } describe("tapping the cell") { beforeEach { tableView.delegate?.tableView?(tableView, didSelectRowAt: indexPath) } it("informs the delegate that the user wants to edit a tag") { expect(delegate.editTagCallCount) == 1 guard delegate.editTagCallCount == 1 else { return } let args = delegate.editTagArgsForCall(0) expect(args.0) === subject expect(args.1) == tags[0] } describe("when the delegate calls the callback") { beforeEach { guard delegate.editTagCallCount == 1 else { fail("delegate not called") return } let callback = delegate.editTagArgsForCall(0).2 callback("callback string") } it("replaces the text of the cell with the text the user gave") { expect(tableView.numberOfRows(inSection: 0)) == 2 let newCell = tableView.dataSource?.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 0)) expect(newCell?.textLabel?.text) == "callback string" let oldCell = tableView.dataSource?.tableView(tableView, cellForRowAt: IndexPath(row: 1, section: 0)) expect(oldCell?.textLabel?.text) == "goodbye" } it("calls the delegate to inform it that the user changed the tags") { expect(delegate.tagsDidChangeCallCount) == 1 guard delegate.tagsDidChangeCallCount == 1 else { return } let args = delegate.tagsDidChangeArgsForCall(0) expect(args.0) === subject expect(args.1) == ["callback string", "goodbye"] } } } } } describe("the add tag button") { let tags = ["hello", "goodbye"] beforeEach { subject.configure(title: "", url: URL(string: "https://example.com")!, summary: "", tags: tags) } it("is titled 'Add Tag'") { expect(subject.addTagButton.title(for: .normal)) == "Add Tag" } describe("tapping it") { beforeEach { subject.addTagButton.sendActions(for: .touchUpInside) } it("informs the delegate to create a new tag") { expect(delegate.editTagCallCount) == 1 guard delegate.editTagCallCount == 1 else { return } let args = delegate.editTagArgsForCall(0) expect(args.0) === subject expect(args.1).to(beNil()) } describe("when the delegate calls the callback") { beforeEach { guard delegate.editTagCallCount == 1 else { fail("delegate not called") return } let callback = delegate.editTagArgsForCall(0).2 callback("callback string") } it("adds another cell to the tags list") { expect(tableView.numberOfRows(inSection: 0)) == 3 guard tableView.numberOfRows(inSection: 0) == 3 else { return } let newCell = tableView.dataSource?.tableView(tableView, cellForRowAt: IndexPath(row: 2, section: 0)) expect(newCell?.textLabel?.text) == "callback string" } it("calls the delegate to inform that the user added a tag") { expect(delegate.tagsDidChangeCallCount) == 1 guard delegate.tagsDidChangeCallCount == 1 else { return } let args = delegate.tagsDidChangeArgsForCall(0) expect(args.0) === subject expect(args.1) == ["hello", "goodbye", "callback string"] } } } } } }
mit
2edb282ebedd51907386bffa893e23c5
43.385
137
0.486144
6.109429
false
false
false
false
AshuMishra/iAppStreetDemo
iAppStreet App/Third Party/PKHUD/HUDAssets.swift
5
1293
// // PKHUD.Assets.swift // PKHUD // // Created by Philip Kluz on 6/18/14. // Copyright (c) 2014 NSExceptional. All rights reserved. // import UIKit /// Provides a set of default assets, like images, that can be supplied to the PKHUD's contentViews. public struct HUDAssets { public static let rotationLockImage = HUDAssets.bundledImage(named: "rotation_lock") public static let rotationUnlockedImage = HUDAssets.bundledImage(named: "rotation_unlocked") public static let volumeImage = HUDAssets.bundledImage(named: "volume") public static let volumeMutedImage = HUDAssets.bundledImage(named: "volume_muted") public static let ringerImage = HUDAssets.bundledImage(named: "ringer") public static let ringerMutedImage = HUDAssets.bundledImage(named: "ringer_muted") public static let crossImage = HUDAssets.bundledImage(named: "cross") public static let checkmarkImage = HUDAssets.bundledImage(named: "checkmark") public static let progressImage = HUDAssets.bundledImage(named: "progress") internal static func bundledImage(named name: String) -> UIImage { let bundleIdentifier = "com.NSExceptional.PKHUD" return UIImage(named: name, inBundle: NSBundle(identifier: bundleIdentifier), compatibleWithTraitCollection: nil)! } }
mit
cb38226310bc51a853cdf8aee108d0dd
46.925926
122
0.750193
4.505226
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/TableviewCells/AchievementCell.swift
1
6657
// // AchievementCell.swift // Habitica // // Created by Phillip Thelen on 11.07.19. // Copyright © 2019 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class AchievementCell: UICollectionViewCell { var isHeightCalculated: Bool = false var isGridLayout = false { didSet { if isGridLayout && !isQuestAchievement { titleLabel.backgroundColor = ThemeService.shared.theme.offsetBackgroundColor titleLabel.textAlignment = .center titleLabel.numberOfLines = 3 descriptionlabel.isHidden = true contentBackgroundView.backgroundColor = ThemeService.shared.theme.windowBackgroundColor contentBackgroundView.isHidden = false } else { titleLabel.backgroundColor = ThemeService.shared.theme.contentBackgroundColor titleLabel.textAlignment = .natural titleLabel.numberOfLines = 3 descriptionlabel.isHidden = false contentBackgroundView.isHidden = true } } } private var contentBackgroundView: UIView = UIView() private var titleLabel: UILabel = { let label = UILabel() label.font = CustomFontMetrics.scaledSystemFont(ofSize: 14, ofWeight: .medium) label.cornerRadius = 6 if #available(iOS 11.0, *) { label.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] } return label }() private var descriptionlabel: UILabel = { let label = UILabel() label.font = CustomFontMetrics.scaledSystemFont(ofSize: 12) label.numberOfLines = 0 return label }() private var iconView: NetworkImageView = { let view = NetworkImageView() view.contentMode = .center return view }() private var countBadge = BadgeView() private var isQuestAchievement: Bool = false { didSet { if isQuestAchievement { countBadge.font = CustomFontMetrics.scaledSystemFont(ofSize: 14, ofWeight: .medium) } else { countBadge.font = CustomFontMetrics.scaledSystemFont(ofSize: 13) } } } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func setup() { contentView.addSubview(contentBackgroundView) contentView.addSubview(titleLabel) contentView.addSubview(descriptionlabel) contentView.addSubview(iconView) contentView.addSubview(countBadge) cornerRadius = 6 } override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { var newFrame = layoutAttributes.frame if isGridLayout && !isQuestAchievement { newFrame.size.width = 156 newFrame.size.height = 106 } else { let totalWidth = superview?.frame.size.width ?? 100 newFrame.size.width = totalWidth frame.size.width = totalWidth newFrame.size.height = heightForWidth(totalWidth) } layoutAttributes.frame = newFrame return layoutAttributes } override func layoutSubviews() { super.layoutSubviews() layout() } private func layout() { if isGridLayout && !isQuestAchievement { iconView.pin.start(4).top(4).end(4).height(66) titleLabel.pin.start(4).below(of: iconView).bottom().end(4) countBadge.pin.start().top().sizeToFit() contentBackgroundView.pin.top(to: iconView.edge.top).start(4).end(4).bottom(to: titleLabel.edge.bottom) } else { iconView.pin.start(16).width(48).height(52).vCenter() countBadge.pin.start(12).top(to: iconView.edge.top).marginTop(-4).sizeToFit() titleLabel.pin.after(of: iconView).marginStart(16).end(16).sizeToFit(.width) descriptionlabel.pin.after(of: iconView).marginStart(16).below(of: titleLabel).marginTop(4).end(16).sizeToFit(.width) let offset = (frame.size.height - (titleLabel.frame.size.height + descriptionlabel.frame.size.height)) / 2 titleLabel.pin.top(offset) descriptionlabel.pin.below(of: titleLabel) } if isQuestAchievement { countBadge.pin.size(40).start(20).vCenter() } } func heightForWidth(_ width: CGFloat) -> CGFloat { if isGridLayout && !isQuestAchievement { return 106 } else { var height = titleLabel.sizeThatFits(CGSize(width: width - 84, height: 200)).height height += descriptionlabel.sizeThatFits(CGSize(width: width - 84, height: 200)).height if isQuestAchievement { return max(height + 16, 60) } else { return max(height + 16, 80) } } } func configure(achievement: AchievementProtocol) { titleLabel.text = achievement.title titleLabel.textColor = ThemeService.shared.theme.primaryTextColor descriptionlabel.text = achievement.text descriptionlabel.textColor = ThemeService.shared.theme.secondaryTextColor if !achievement.isQuestAchievement { if achievement.earned { iconView.setImagewith(name: (achievement.icon ?? "") + "2x") } else { iconView.setImagewith(name: "achievement-unearned2x") } iconView.isHidden = false countBadge.backgroundColor = ThemeService.shared.theme.secondaryBadgeColor countBadge.textColor = ThemeService.shared.theme.lightTextColor } else { iconView.isHidden = true countBadge.backgroundColor = ThemeService.shared.theme.offsetBackgroundColor countBadge.textColor = ThemeService.shared.theme.secondaryTextColor } if achievement.optionalCount > 0 { countBadge.number = achievement.optionalCount countBadge.isHidden = false } else { countBadge.isHidden = true } isQuestAchievement = achievement.isQuestAchievement setNeedsLayout() } func configure(achievement: AchievementProtocol, quest: QuestProtocol) { configure(achievement: achievement) titleLabel.text = quest.text } }
gpl-3.0
c587d2c1727876f64888da62a4dcbb23
36.818182
142
0.615685
5.350482
false
false
false
false
PureSwift/Silica
Sources/Silica/CGContext.swift
1
28516
// // Context.swift // Silica // // Created by Alsey Coleman Miller on 5/8/16. // Copyright © 2016 PureSwift. All rights reserved. // #if os(macOS) import Darwin.C.math #elseif os(Linux) import Glibc #endif import Cairo import CCairo import Foundation public final class CGContext { // MARK: - Properties public let surface: Cairo.Surface public let size: CGSize public var textMatrix = CGAffineTransform.identity // MARK: - Private Properties private let internalContext: Cairo.Context private var internalState: State = State() // MARK: - Initialization public init(surface: Cairo.Surface, size: CGSize) throws { let context = Cairo.Context(surface: surface) if let error = context.status.toError() { throw error } // Cairo defaults to line width 2.0 context.lineWidth = 1.0 self.size = size self.internalContext = context self.surface = surface } // MARK: - Accessors /// Returns the current transformation matrix. public var currentTransform: CGAffineTransform { return CGAffineTransform(cairo: internalContext.matrix) } public var currentPoint: CGPoint? { guard let point = internalContext.currentPoint else { return nil } return CGPoint(x: CGFloat(point.x), y: CGFloat(point.y)) } public var shouldAntialias: Bool { get { return internalContext.antialias != CAIRO_ANTIALIAS_NONE } set { internalContext.antialias = newValue ? CAIRO_ANTIALIAS_DEFAULT : CAIRO_ANTIALIAS_NONE } } public var lineWidth: CGFloat { get { return CGFloat(internalContext.lineWidth) } set { internalContext.lineWidth = Double(newValue) } } public var lineJoin: CGLineJoin { get { return CGLineJoin(cairo: internalContext.lineJoin) } set { internalContext.lineJoin = newValue.toCairo() } } public var lineCap: CGLineCap { get { return CGLineCap(cairo: internalContext.lineCap) } set { internalContext.lineCap = newValue.toCairo() } } public var miterLimit: CGFloat { get { return CGFloat(internalContext.miterLimit) } set { internalContext.miterLimit = Double(newValue) } } public var lineDash: (phase: CGFloat, lengths: [CGFloat]) { get { let cairoValue = internalContext.lineDash return (CGFloat(cairoValue.phase), cairoValue.lengths.map({ CGFloat($0) })) } set { internalContext.lineDash = (Double(newValue.phase), newValue.lengths.map({ Double($0) })) } } @inline(__always) public func setLineDash(phase: CGFloat, lengths: [CGFloat]) { self.lineDash = (phase, lengths) } public var tolerance: CGFloat { get { return CGFloat(internalContext.tolerance) } set { internalContext.tolerance = Double(newValue) } } /// Returns a `Path` built from the current path information in the graphics context. public var path: CGPath { var path = CGPath() let cairoPath = internalContext.copyPath() var index = 0 while index < cairoPath.count { let header = cairoPath[index].header let length = Int(header.length) let data = Array(cairoPath.data[index + 1 ..< length]) let element: PathElement switch header.type { case CAIRO_PATH_MOVE_TO: let point = CGPoint(x: CGFloat(data[0].point.x), y: CGFloat(data[0].point.y)) element = PathElement.moveToPoint(point) case CAIRO_PATH_LINE_TO: let point = CGPoint(x: CGFloat(data[0].point.x), y: CGFloat(data[0].point.y)) element = PathElement.addLineToPoint(point) case CAIRO_PATH_CURVE_TO: let control1 = CGPoint(x: CGFloat(data[0].point.x), y: CGFloat(data[0].point.y)) let control2 = CGPoint(x: CGFloat(data[1].point.x), y: CGFloat(data[1].point.y)) let destination = CGPoint(x: CGFloat(data[2].point.x), y: CGFloat(data[2].point.y)) element = PathElement.addCurveToPoint(control1, control2, destination) case CAIRO_PATH_CLOSE_PATH: element = PathElement.closeSubpath default: fatalError("Unknown Cairo Path data: \(header.type.rawValue)") } path.elements.append(element) // increment index += length } return path } public var fillColor: CGColor { get { return internalState.fill?.color ?? CGColor.black } set { internalState.fill = (newValue, Cairo.Pattern(color: newValue)) } } public var strokeColor: CGColor { get { return internalState.stroke?.color ?? CGColor.black } set { internalState.stroke = (newValue, Cairo.Pattern(color: newValue)) } } @inline(__always) public func setAlpha(_ alpha: CGFloat) { self.alpha = alpha } public var alpha: CGFloat { get { return CGFloat(internalState.alpha) } set { // store new value internalState.alpha = newValue // update stroke if var stroke = internalState.stroke { stroke.color.alpha = newValue stroke.pattern = Pattern(color: stroke.color) internalState.stroke = stroke } // update fill if var fill = internalState.fill { fill.color.alpha = newValue fill.pattern = Pattern(color: fill.color) internalState.fill = fill } } } public var fontSize: CGFloat { get { return internalState.fontSize } set { internalState.fontSize = newValue } } public var characterSpacing: CGFloat { get { return internalState.characterSpacing } set { internalState.characterSpacing = newValue } } @inline(__always) public func setTextDrawingMode(_ newValue: CGTextDrawingMode) { self.textDrawingMode = newValue } public var textDrawingMode: CGTextDrawingMode { get { return internalState.textMode } set { internalState.textMode = newValue } } public var textPosition: CGPoint { get { return CGPoint(x: textMatrix.tx, y: textMatrix.ty) } set { textMatrix.tx = newValue.x textMatrix.ty = newValue.y } } // MARK: - Methods // MARK: Defining Pages public func beginPage() { internalContext.copyPage() } public func endPage() { internalContext.showPage() } // MARK: Transforming the Coordinate Space public func scaleBy(x: CGFloat, y: CGFloat) { internalContext.scale(x: Double(x), y: Double(y)) } public func translateBy(x: CGFloat, y: CGFloat) { internalContext.translate(x: Double(x), y: Double(y)) } public func rotateBy(_ angle: CGFloat) { internalContext.rotate(Double(angle)) } /// Transforms the user coordinate system in a context using a specified matrix. public func concatenate(_ transform: CGAffineTransform) { internalContext.transform(transform.toCairo()) } // MARK: Saving and Restoring the Graphics State public func save() throws { internalContext.save() if let error = internalContext.status.toError() { throw error } let newState = internalState.copy newState.next = internalState internalState = newState } @inline(__always) public func saveGState() { try! save() } public func restore() throws { guard let restoredState = internalState.next else { throw CAIRO_STATUS_INVALID_RESTORE.toError()! } internalContext.restore() if let error = internalContext.status.toError() { throw error } // success internalState = restoredState } @inline(__always) public func restoreGState() { try! restore() } // MARK: Setting Graphics State Attributes public func setShadow(offset: CGSize, radius: CGFloat, color: CGColor) { let colorPattern = Pattern(color: color) internalState.shadow = (offset: offset, radius: radius, color: color, pattern: colorPattern) } // MARK: Constructing Paths /// Creates a new empty path in a graphics context. public func beginPath() { internalContext.newPath() } /// Closes and terminates the current path’s subpath. public func closePath() { internalContext.closePath() } /// Begins a new subpath at the specified point. public func move(to point: CGPoint) { internalContext.move(to: (x: Double(point.x), y: Double(point.y))) } /// Appends a straight line segment from the current point to the specified point. public func addLine(to point: CGPoint) { internalContext.line(to: (x: Double(point.x), y: Double(point.y))) } /// Adds a cubic Bézier curve to the current path, with the specified end point and control points. func addCurve(to end: CGPoint, control1: CGPoint, control2: CGPoint) { internalContext.curve(to: ((x: Double(control1.x), y: Double(control1.y)), (x: Double(control2.x), y: Double(control2.y)), (x: Double(end.x), y: Double(end.y)))) } /// Adds a quadratic Bézier curve to the current path, with the specified end point and control point. public func addQuadCurve(to end: CGPoint, control point: CGPoint) { let currentPoint = self.currentPoint ?? CGPoint() let first = CGPoint(x: (currentPoint.x / 3.0) + (2.0 * point.x / 3.0), y: (currentPoint.y / 3.0) + (2.0 * point.y / 3.0)) let second = CGPoint(x: (2.0 * currentPoint.x / 3.0) + (end.x / 3.0), y: (2.0 * currentPoint.y / 3.0) + (end.y / 3.0)) addCurve(to: end, control1: first, control2: second) } /// Adds an arc of a circle to the current path, specified with a radius and angles. public func addArc(center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) { internalContext.addArc(center: (x: Double(center.x), y: Double(center.y)), radius: Double(radius), angle: (Double(startAngle), Double(endAngle)), negative: clockwise) } /// Adds an arc of a circle to the current path, specified with a radius and two tangent lines. public func addArc(tangent1End: CGPoint, tangent2End: CGPoint, radius: CGFloat) { let points: (CGPoint, CGPoint) = (tangent1End, tangent2End) let currentPoint = self.currentPoint ?? CGPoint() // arguments let x0 = currentPoint.x.native let y0 = currentPoint.y.native let x1 = points.0.x.native let y1 = points.0.y.native let x2 = points.1.x.native let y2 = points.1.y.native // calculated let dx0 = x0 - x1 let dy0 = y0 - y1 let dx2 = x2 - x1 let dy2 = y2 - y1 let xl0 = sqrt((dx0 * dx0) + (dy0 * dy0)) guard xl0 != 0 else { return } let xl2 = sqrt((dx2 * dx2) + (dy2 * dy2)) let san = (dx2 * dy0) - (dx0 * dy2) guard san != 0 else { addLine(to: points.0) return } let n0x: CGFloat.NativeType let n0y: CGFloat.NativeType let n2x: CGFloat.NativeType let n2y: CGFloat.NativeType if san < 0 { n0x = -dy0 / xl0 n0y = dx0 / xl0 n2x = dy2 / xl2 n2y = -dx2 / xl2 } else { n0x = dy0 / xl0 n0y = -dx0 / xl0 n2x = -dy2 / xl2 n2y = dx2 / xl2 } let t = (dx2*n2y - dx2*n0y - dy2*n2x + dy2*n0x) / san let center = CGPoint(x: CGFloat(x1 + radius.native * (t * dx0 + n0x)), y: CGFloat(y1 + radius.native * (t * dy0 + n0y))) let angle = (start: atan2(-n0y, -n0x), end: atan2(-n2y, -n2x)) self.addArc(center: center, radius: radius, startAngle: CGFloat(angle.start), endAngle: CGFloat(angle.end), clockwise: (san < 0)) } /// Adds a rectangular path to the current path. public func addRect(_ rect: CGRect) { internalContext.addRectangle(x: Double(rect.origin.x), y: Double(rect.origin.y), width: Double(rect.size.width), height: Double(rect.size.height)) } /// Adds a previously created path object to the current path in a graphics context. public func addPath(_ path: CGPath) { for element in path.elements { switch element { case let .moveToPoint(point): move(to: point) case let .addLineToPoint(point): addLine(to: point) case let .addQuadCurveToPoint(control, destination): addQuadCurve(to: destination, control: control) case let .addCurveToPoint(control1, control2, destination): addCurve(to: destination, control1: control1, control2: control2) case .closeSubpath: closePath() } } } // MARK: - Painting Paths /// Paints a line along the current path. public func strokePath() { if internalState.shadow != nil { startShadow() } internalContext.source = internalState.stroke?.pattern ?? DefaultPattern internalContext.stroke() if internalState.shadow != nil { endShadow() } } /// Paints the area within the current path, as determined by the specified fill rule. public func fillPath(using rule: CGPathFillRule = .winding) { let evenOdd: Bool switch rule { case .evenOdd: evenOdd = true case .winding: evenOdd = false } try! fillPath(evenOdd: evenOdd, preserve: false) } public func clear() { internalContext.source = internalState.fill?.pattern ?? DefaultPattern internalContext.clip() internalContext.clipPreserve() } public func drawPath(using mode: CGDrawingMode = CGDrawingMode()) { switch mode { case .fill: try! fillPath(evenOdd: false, preserve: false) case .evenOddFill: try! fillPath(evenOdd: true, preserve: false) case .fillStroke: try! fillPath(evenOdd: false, preserve: true) case .evenOddFillStroke: try! fillPath(evenOdd: true, preserve: true) case .stroke: strokePath() } } public func clip(evenOdd: Bool = false) { if evenOdd { internalContext.fillRule = CAIRO_FILL_RULE_EVEN_ODD } internalContext.clip() if evenOdd { internalContext.fillRule = CAIRO_FILL_RULE_WINDING } } @inline(__always) public func clip(to rect: CGRect) { beginPath() addRect(rect) clip() } // MARK: - Using Transparency Layers public func beginTransparencyLayer(in rect: CGRect? = nil, auxiliaryInfo: [String: Any]? = nil) { // in case we clip (for the rect) internalContext.save() if let rect = rect { internalContext.newPath() addRect(rect) internalContext.clip() } saveGState() alpha = 1.0 internalState.shadow = nil internalContext.pushGroup() } public func endTransparencyLayer() { let group = internalContext.popGroup() // undo change to alpha and shadow state restoreGState() // paint contents internalContext.source = group internalContext.paint(alpha: Double(internalState.alpha)) // undo clipping (if any) internalContext.restore() } // MARK: - Drawing an Image to a Graphics Context /// Draws an image into a graphics context. public func draw(_ image: CGImage, in rect: CGRect) { internalContext.save() let imageSurface = image.surface let sourceRect = CGRect(x: 0, y: 0, width: CGFloat(image.width), height: CGFloat(image.height)) let pattern = Pattern(surface: imageSurface) var patternMatrix = Matrix.identity patternMatrix.translate(x: Double(rect.origin.x), y: Double(rect.origin.y)) patternMatrix.scale(x: Double(rect.size.width / sourceRect.size.width), y: Double(rect.size.height / sourceRect.size.height)) patternMatrix.scale(x: 1, y: -1) patternMatrix.translate(x: 0, y: Double(-sourceRect.size.height)) patternMatrix.invert() pattern.matrix = patternMatrix pattern.extend = .pad internalContext.operator = CAIRO_OPERATOR_OVER internalContext.source = pattern internalContext.addRectangle(x: Double(rect.origin.x), y: Double(rect.origin.y), width: Double(rect.size.width), height: Double(rect.size.height)) internalContext.fill() internalContext.restore() } // MARK: - Drawing Text public func setFont(_ font: CGFont) { internalContext.fontFace = font.scaledFont.face internalState.font = font } /// Uses the Cairo toy text API. public func show(toyText text: String) { let oldPoint = internalContext.currentPoint internalContext.move(to: (0, 0)) // calculate text matrix var cairoTextMatrix = Matrix.identity cairoTextMatrix.scale(x: Double(fontSize), y: Double(fontSize)) cairoTextMatrix.multiply(a: cairoTextMatrix, b: textMatrix.toCairo()) internalContext.setFont(matrix: cairoTextMatrix) internalContext.source = internalState.fill?.pattern ?? DefaultPattern internalContext.show(text: text) let distance = internalContext.currentPoint ?? (0, 0) textPosition = CGPoint(x: textPosition.x + CGFloat(distance.x), y: textPosition.y + CGFloat(distance.y)) if let oldPoint = oldPoint { internalContext.move(to: oldPoint) } else { internalContext.newPath() } } public func show(text: String) { guard let font = internalState.font?.scaledFont, fontSize > 0.0 && text.isEmpty == false else { return } let glyphs = text.unicodeScalars.map { font[UInt($0.value)] } show(glyphs: glyphs) } public func show(glyphs: [FontIndex]) { guard let font = internalState.font, fontSize > 0.0 && glyphs.isEmpty == false else { return } let advances = font.advances(for: glyphs, fontSize: fontSize, textMatrix: textMatrix, characterSpacing: characterSpacing) show(glyphs: unsafeBitCast(glyphs.merge(advances), to: [(glyph: FontIndex, advance: CGSize)].self)) } public func show(glyphs glyphAdvances: [(glyph: FontIndex, advance: CGSize)]) { guard let font = internalState.font, fontSize > 0.0 && glyphAdvances.isEmpty == false else { return } let advances = glyphAdvances.map { $0.advance } let glyphs = glyphAdvances.map { $0.glyph } let positions = font.positions(for: advances, textMatrix: textMatrix) // render show(glyphs: unsafeBitCast(glyphs.merge(positions), to: [(glyph: FontIndex, position: CGPoint)].self)) // advance text position advances.forEach { textPosition.x += $0.width textPosition.y += $0.height } } public func show(glyphs glyphPositions: [(glyph: FontIndex, position: CGPoint)]) { guard let font = internalState.font?.scaledFont, fontSize > 0.0 && glyphPositions.isEmpty == false else { return } // actual rendering let cairoGlyphs: [cairo_glyph_t] = glyphPositions.indexedMap { (index, element) in var cairoGlyph = cairo_glyph_t() cairoGlyph.index = UInt(element.glyph) let userSpacePoint = element.position.applying(textMatrix) cairoGlyph.x = Double(userSpacePoint.x) cairoGlyph.y = Double(userSpacePoint.y) return cairoGlyph } var cairoTextMatrix = Matrix.identity cairoTextMatrix.scale(x: Double(fontSize), y: Double(fontSize)) let ascender = (Double(font.ascent) * Double(fontSize)) / Double(font.unitsPerEm) let silicaTextMatrix = Matrix(a: Double(textMatrix.a), b: Double(textMatrix.b), c: Double(textMatrix.c), d: Double(textMatrix.d), t: (0, ascender)) cairoTextMatrix.multiply(a: cairoTextMatrix, b: silicaTextMatrix) internalContext.setFont(matrix: cairoTextMatrix) internalContext.source = internalState.fill?.pattern ?? DefaultPattern // show glyphs cairoGlyphs.forEach { internalContext.show(glyph: $0) } } // MARK: - Private Functions private func fillPath(evenOdd: Bool, preserve: Bool) throws { if internalState.shadow != nil { startShadow() } internalContext.source = internalState.fill?.pattern ?? DefaultPattern internalContext.fillRule = evenOdd ? CAIRO_FILL_RULE_EVEN_ODD : CAIRO_FILL_RULE_WINDING internalContext.fillPreserve() if preserve == false { internalContext.newPath() } if internalState.shadow != nil { endShadow() } if let error = internalContext.status.toError() { throw error } } private func startShadow() { internalContext.pushGroup() } private func endShadow() { let pattern = internalContext.popGroup() internalContext.save() let radius = internalState.shadow!.radius let alphaSurface = try! Surface.Image(format: .a8, width: Int(ceil(size.width + 2 * radius)), height: Int(ceil(size.height + 2 * radius))) let alphaContext = Cairo.Context(surface: alphaSurface) alphaContext.source = pattern alphaContext.paint() alphaSurface.flush() internalContext.source = internalState.shadow!.pattern internalContext.mask(surface: alphaSurface, at: (Double(internalState.shadow!.offset.width), Double(internalState.shadow!.offset.height))) // draw content internalContext.source = pattern internalContext.paint() internalContext.restore() } } // MARK: - Private /// Default black pattern fileprivate let DefaultPattern = Cairo.Pattern(color: (red: 0, green: 0, blue: 0)) fileprivate extension Silica.CGContext { /// To save non-Cairo state variables fileprivate final class State { var next: State? var alpha: CGFloat = 1.0 var fill: (color: CGColor, pattern: Cairo.Pattern)? var stroke: (color: CGColor, pattern: Cairo.Pattern)? var shadow: (offset: CGSize, radius: CGFloat, color: CGColor, pattern: Cairo.Pattern)? var font: CGFont? var fontSize: CGFloat = 0.0 var characterSpacing: CGFloat = 0.0 var textMode = CGTextDrawingMode() init() { } var copy: State { let copy = State() copy.next = next copy.alpha = alpha copy.fill = fill copy.stroke = stroke copy.shadow = shadow copy.font = font copy.fontSize = fontSize copy.characterSpacing = characterSpacing copy.textMode = textMode return copy } } } // MARK: - Internal Extensions internal extension Collection { func indexedMap<T>(_ transform: (Index, Iterator.Element) throws -> T) rethrows -> [T] { let count: Int = numericCast(self.count) if count == 0 { return [] } var result = ContiguousArray<T>() result.reserveCapacity(count) var i = self.startIndex for _ in 0..<count { result.append(try transform(i, self[i])) formIndex(after: &i) } //_expectEnd(i, self) return Array(result) } @inline(__always) func merge<C: Collection, T> (_ other: C) -> [(Iterator.Element, T)] where C.Iterator.Element == T, C.IndexDistance == IndexDistance, C.Index == Index { precondition(self.count == other.count, "The collection to merge must be of the same size") return self.indexedMap { ($1, other[$0]) } } } #if os(macOS) && Xcode import Foundation import AppKit public extension Silica.CGContext { @objc(debugQuickLookObject) public var debugQuickLookObject: AnyObject { return surface.debugQuickLookObject } } #endif
mit
6d845d5ffe872873b3a517f37e2593b7
28.483971
137
0.52734
5.057832
false
false
false
false
omnypay/omnypay-sdk-ios
ExampleApp/OmnyPayAPIDemo/OmnyPayAPIDemo/ReceiptViewController.swift
1
4489
/** Copyright 2017 OmnyPay Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import OmnyPayAPI class ReceiptViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var receiptItems = [BasketItem]() var receipt: BasketReceiptNotification? @IBOutlet weak var itemsTableView: UITableView! @IBOutlet weak var lblDiscount: UILabel! @IBOutlet weak var lblTax: UILabel! @IBOutlet weak var lblSubTotal: UILabel! @IBOutlet weak var lblTotal: UILabel! override func viewDidLoad() { super.viewDidLoad() self.receiptItems = self.parseBasketForItems(receipt: self.receipt!) self.itemsTableView.delegate = self self.itemsTableView.dataSource = self self.itemsTableView.allowsSelection = false self.itemsTableView.separatorStyle = UITableViewCellSeparatorStyle.none title = Constants.appTitle self.navigationItem.hidesBackButton = true self.lblSubTotal.text = "$" + (Double(self.receipt!.summary?.total ?? 0)/100.0).format(f: "%03.2f") self.lblTax.text = "$" + (Double(self.receipt!.summary?.tax ?? 0)/100.0).format(f: "%03.2f") self.lblDiscount.text = "-$" + (Double(self.receipt!.summary?.discountCents ?? 0)/100.0).format(f: "%03.2f") self.lblTotal.text = "$" + (Double(self.receipt!.summary?.paymentTotal ?? 0)/100.0).format(f: "%03.2f") self.automaticallyAdjustsScrollViewInsets = false } func parseBasketForItems(receipt: BasketReceiptNotification) -> [BasketItem] { var allBasketItems = [BasketItem]() if let basketItems = receipt.items { for item in basketItems { let basketItem = BasketItem() basketItem.productId = item.sku basketItem.productDescription = item.name basketItem.productQuantity = item.qty! if let offers = receipt.offers { for offer in offers { if basketItem.productId == offer.sku { basketItem.offerDescription = offer.description break } } } if let reconciledTotal = receipt.reconciledTotal { for reconcile in reconciledTotal { if basketItem.productId == reconcile.sku { basketItem.productPrice = reconcile.total basketItem.offerAmount = reconcile.discountCents break } } } allBasketItems.append(basketItem) } } return allBasketItems } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.receiptItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.itemsTableView.dequeueReusableCell(withIdentifier: "receiptItemCell") as! ReceiptItemTableViewCell let index = indexPath.row cell.lblItemDescription.text = self.receiptItems[index].productDescription cell.lblItemQuantity.text = String(self.receiptItems[index].productQuantity!) cell.lblAmount.text = "$" + (Double(self.receiptItems[index].productPrice ?? 0)/100.0).format(f: "%03.2f") if self.receiptItems[index].offerDescription != nil && self.receiptItems[index].offerAmount! > 0 { cell.lblOfferDescription.text = self.receiptItems[index].offerDescription cell.lblOfferDiscount.text = "-$" + (Double(self.receiptItems[index].offerAmount ?? 0)/100.0).format(f: "%03.2f") cell.lblOfferDiscount.isHidden = false cell.lblOfferDescription.isHidden = false } else { cell.lblOfferDiscount.isHidden = true cell.lblOfferDescription.isHidden = true } return cell } @IBAction func goToHome(_ sender: UIButton) { print("home clicked") self.dismiss(animated: true, completion: {}) self.navigationController?.popToRootViewController(animated: true) } }
apache-2.0
193b5c59f9d7c788754919a8c58a69fb
37.367521
123
0.684339
4.552738
false
false
false
false
BradLarson/GPUImage2
framework/Source/Operations/TransformOperation.swift
1
1715
#if canImport(OpenGL) import OpenGL.GL3 #endif #if canImport(OpenGLES) import OpenGLES #endif #if canImport(COpenGLES) import COpenGLES.gles2 #endif #if canImport(COpenGL) import COpenGL #endif public class TransformOperation: BasicOperation { public var transform:Matrix4x4 = Matrix4x4.identity { didSet { uniformSettings["transformMatrix"] = transform } } var normalizedImageVertices:[GLfloat]! public init() { super.init(vertexShader:TransformVertexShader, fragmentShader:PassthroughFragmentShader, numberOfInputs:1) ({transform = Matrix4x4.identity})() } override func internalRenderFunction(_ inputFramebuffer:Framebuffer, textureProperties:[InputTextureProperties]) { renderQuadWithShader(shader, uniformSettings:uniformSettings, vertices:normalizedImageVertices, inputTextures:textureProperties) releaseIncomingFramebuffers() } override func configureFramebufferSpecificUniforms(_ inputFramebuffer:Framebuffer) { let outputRotation = overriddenOutputRotation ?? inputFramebuffer.orientation.rotationNeededForOrientation(.portrait) let aspectRatio = inputFramebuffer.aspectRatioForRotation(outputRotation) let orthoMatrix = orthographicMatrix(-1.0, right:1.0, bottom:-1.0 * aspectRatio, top:1.0 * aspectRatio, near:-1.0, far:1.0) normalizedImageVertices = normalizedImageVerticesForAspectRatio(aspectRatio) uniformSettings["orthographicMatrix"] = orthoMatrix } } func normalizedImageVerticesForAspectRatio(_ aspectRatio:Float) -> [GLfloat] { return [-1.0, GLfloat(-aspectRatio), 1.0, GLfloat(-aspectRatio), -1.0, GLfloat(aspectRatio), 1.0, GLfloat(aspectRatio)] }
bsd-3-clause
18c0e6511954e77a7845202cea86c9d2
37.111111
136
0.754519
4.635135
false
false
false
false
nathawes/swift
stdlib/public/core/StringInterpolation.swift
6
10050
//===--- StringInterpolation.swift - String Interpolation -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Represents a string literal with interpolations while it is being built up. /// /// Do not create an instance of this type directly. It is used by the compiler /// when you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." /// /// When implementing an `ExpressibleByStringInterpolation` conformance, /// set the `StringInterpolation` associated type to /// `DefaultStringInterpolation` to get the same interpolation behavior as /// Swift's built-in `String` type and construct a `String` with the results. /// If you don't want the default behavior or don't want to construct a /// `String`, use a custom type conforming to `StringInterpolationProtocol` /// instead. /// /// Extending default string interpolation behavior /// =============================================== /// /// Code outside the standard library can extend string interpolation on /// `String` and many other common types by extending /// `DefaultStringInterpolation` and adding an `appendInterpolation(...)` /// method. For example: /// /// extension DefaultStringInterpolation { /// fileprivate mutating func appendInterpolation( /// escaped value: String, asASCII forceASCII: Bool = false) { /// for char in value.unicodeScalars { /// appendInterpolation(char.escaped(asASCII: forceASCII)) /// } /// } /// } /// /// print("Escaped string: \(escaped: string)") /// /// See `StringInterpolationProtocol` for details on `appendInterpolation` /// methods. /// /// `DefaultStringInterpolation` extensions should add only `mutating` members /// and should not copy `self` or capture it in an escaping closure. @frozen public struct DefaultStringInterpolation: StringInterpolationProtocol { /// The string contents accumulated by this instance. @usableFromInline internal var _storage: String /// Creates a string interpolation with storage pre-sized for a literal /// with the indicated attributes. /// /// Do not call this initializer directly. It is used by the compiler when /// interpreting string interpolations. @inlinable public init(literalCapacity: Int, interpolationCount: Int) { let capacityPerInterpolation = 2 let initialCapacity = literalCapacity + interpolationCount * capacityPerInterpolation _storage = String._createEmpty(withInitialCapacity: initialCapacity) } /// Appends a literal segment of a string interpolation. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. @inlinable public mutating func appendLiteral(_ literal: String) { literal.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: TextOutputStreamable, T: CustomStringConvertible { value.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = "If one cookie costs \(price) dollars, " + /// "\(number) cookies cost \(price * number) dollars." /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: TextOutputStreamable { value.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: CustomStringConvertible { value.description.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) { _print_unlocked(value, &self) } @_alwaysEmitIntoClient public mutating func appendInterpolation(_ value: Any.Type) { _typeName(value, qualified: false).write(to: &self) } /// Creates a string from this instance, consuming the instance in the /// process. @inlinable internal __consuming func make() -> String { return _storage } } extension DefaultStringInterpolation: CustomStringConvertible { @inlinable public var description: String { return _storage } } extension DefaultStringInterpolation: TextOutputStream { @inlinable public mutating func write(_ string: String) { _storage.append(string) } public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) { _storage._guts.append(_StringGuts(buffer, isASCII: true)) } } // While not strictly necessary, declaring these is faster than using the // default implementation. extension String { /// Creates a new instance from an interpolated string literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable @_effects(readonly) public init(stringInterpolation: DefaultStringInterpolation) { self = stringInterpolation.make() } } extension Substring { /// Creates a new instance from an interpolated string literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable @_effects(readonly) public init(stringInterpolation: DefaultStringInterpolation) { self.init(stringInterpolation.make()) } }
apache-2.0
774bec5a6a7075054ce722c0b95a42bc
37.505747
80
0.638806
4.850386
false
false
false
false
TotalDigital/People-iOS
Pods/p2.OAuth2/Sources/Base/OAuth2Securable.swift
4
6597
// // OAuth2Requestable.swift // OAuth2 // // Created by Pascal Pfiffner on 6/2/15. // Copyright 2015 Pascal Pfiffner // // 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 /** Base class to add keychain storage functionality. */ open class OAuth2Securable: OAuth2Requestable { /// Server-side settings, as set upon initialization. final let settings: OAuth2JSON /// If set to `true` (the default) will use system keychain to store tokens. Use `"keychain": bool` in settings. public var useKeychain = true { didSet { if useKeychain { updateFromKeychain() } } } /// The keychain account to use to store tokens. Defaults to "currentTokens". open var keychainAccountForTokens = "currentTokens" { didSet { assert(!keychainAccountForTokens.isEmpty) updateFromKeychain() } } /// The keychain account name to use to store client credentials. Defaults to "clientCredentials". open var keychainAccountForClientCredentials = "clientCredentials" { didSet { assert(!keychainAccountForClientCredentials.isEmpty) } } /// Defaults to `kSecAttrAccessibleWhenUnlocked`. MUST be set via `keychain_access_group` init setting. open internal(set) var keychainAccessMode = kSecAttrAccessibleWhenUnlocked /// Keychain access group, none is set by default. MUST be set via `keychain_access_group` init setting. open internal(set) var keychainAccessGroup: String? /** Base initializer. Looks at the `verbose`, `keychain`, `keychain_access_mode`, `keychain_access_group` `keychain_account_for_client_credentials` and `keychain_account_for_tokens`. Everything else is handled by subclasses. */ public init(settings: OAuth2JSON) { self.settings = settings // keychain settings if let accountForClientCredentials = settings["keychain_account_for_client_credentials"] as? String { keychainAccountForClientCredentials = accountForClientCredentials } if let accountForTokens = settings["keychain_account_for_tokens"] as? String { keychainAccountForTokens = accountForTokens } if let keychain = settings["keychain"] as? Bool { useKeychain = keychain } if let accessMode = settings["keychain_access_mode"] as? String { keychainAccessMode = accessMode as CFString } if let accessGroup = settings["keychain_access_group"] as? String { keychainAccessGroup = accessGroup } // logging settings var verbose = false if let verb = settings["verbose"] as? Bool { verbose = verb } super.init(verbose: verbose) // init from keychain if useKeychain { updateFromKeychain() } } // MARK: - Keychain Integration /** The service key under which to store keychain items. Returns "http://localhost", subclasses override to return the authorize URL. */ open func keychainServiceName() -> String { return "http://localhost" } /** Queries the keychain for tokens stored for the receiver's authorize URL, and updates the token properties accordingly. */ private func updateFromKeychain() { logger?.debug("OAuth2", msg: "Looking for items in keychain") do { var creds = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForClientCredentials) let creds_data = try creds.fetchedFromKeychain() updateFromKeychainItems(creds_data) } catch { logger?.warn("OAuth2", msg: "Failed to load client credentials from keychain: \(error)") } do { var toks = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForTokens) let toks_data = try toks.fetchedFromKeychain() updateFromKeychainItems(toks_data) } catch { logger?.warn("OAuth2", msg: "Failed to load tokens from keychain: \(error)") } } /** Updates instance properties according to the items found in the given dictionary, which was found in the keychain. */ func updateFromKeychainItems(_ items: [String: Any]) { } /** Items that should be stored when storing client credentials. - returns: A dictionary with `String` keys and `Any` items */ open func storableCredentialItems() -> [String: Any]? { return nil } /** Stores our client credentials in the keychain. */ open func storeClientToKeychain() { if let items = storableCredentialItems() { logger?.debug("OAuth2", msg: "Storing client credentials to keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForClientCredentials, data: items) do { try keychain.saveInKeychain() } catch { logger?.warn("OAuth2", msg: "Failed to store client credentials to keychain: \(error)") } } } /** Items that should be stored when tokens are stored to the keychain. - returns: A dictionary with `String` keys and `Any` items */ open func storableTokenItems() -> [String: Any]? { return nil } /** Stores our current token(s) in the keychain. */ public func storeTokensToKeychain() { if let items = storableTokenItems() { logger?.debug("OAuth2", msg: "Storing tokens to keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForTokens, data: items) do { try keychain.saveInKeychain() } catch let error { logger?.warn("OAuth2", msg: "Failed to store tokens to keychain: \(error)") } } } /** Unsets the client credentials and deletes them from the keychain. */ open func forgetClient() { logger?.debug("OAuth2", msg: "Forgetting client credentials and removing them from keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForClientCredentials) do { try keychain.removeFromKeychain() } catch { logger?.warn("OAuth2", msg: "Failed to delete credentials from keychain: \(error)") } } /** Unsets the tokens and deletes them from the keychain. */ open func forgetTokens() { logger?.debug("OAuth2", msg: "Forgetting tokens and removing them from keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForTokens) do { try keychain.removeFromKeychain() } catch { logger?.warn("OAuth2", msg: "Failed to delete tokens from keychain: \(error)") } } }
apache-2.0
83bd50a08b850026822ef5bdbcac5506
30.869565
203
0.720327
3.955036
false
false
false
false
sorenmortensen/SymondsTimetable
Sources/SplashViewController.swift
1
6877
// // SplashViewController.swift // SymondsTimetable // // Created by Søren Mortensen on 07/10/2016. // Copyright © 2016 Soren Mortensen. All rights reserved. // import UIKit import Dispatch /// Displays a logo and a login button to the user. /// /// This is the first view controller that is presented to the user upon opening /// the app. class SplashViewController: UIViewController { // MARK: - IBOutlets /// A button that the user can tap to move on to the login screen. @IBOutlet weak var logInButton: UIButton! /// An indicator to show the user that a network request is ongoing. @IBOutlet weak var loginActivityIndicator: UIActivityIndicatorView! // MARK: - IBActions /// Initiates the login process by performing a segue to a /// LoginViewController. /// /// - Parameter sender: The sender of the IBAction. @IBAction func logIn(_ sender: UIButton) { // This method is called when the login button is tapped. // Hide the login button. logInButton.isHidden = true // Start animating the activity indicator. loginActivityIndicator.startAnimating() // Try to authenticate from details saved in Keychain. SymondsAPI.shared.authenticateFromSavedDetails { error in // Check if authentication was successful. if let _ = error { // Authentication was unsuccessful. DispatchQueue.main.async { // Show the view controller containing the web view for // login. self.performSegue( withIdentifier: "SplashToLogin", sender: nil) } } else { // Authentication was successful! DispatchQueue.main.async { // Show the timetable view controller. self.segueToTimetable() } } } } /// Called when the LoginViewController unwinds to this view controller. @IBAction func unwindToSplash(_ sender: UIStoryboardSegue) { loginActivityIndicator.stopAnimating() logInButton.isHidden = false } // MARK: - Functions /// Segues to the main timetable view, and stops the activity indicator /// from animating. func segueToTimetable() { // Get a reference to the animations queue. let animationsQueue = DispatchQueue(label: "Animations") // Send a block to the animations queue, so that it doesn't execute // before any other animations. animationsQueue.sync { [unowned self] in // Send the block from the animations queue to the main queue, // because this block performs UI updates and should not be // called from a background thread. DispatchQueue.main.async { // Segue to the main timetable view. self.performSegue( withIdentifier: "splash-to-timetable", sender: self) // Stop animating and hide the login activity indicator. self.loginActivityIndicator.stopAnimating() self.logInButton.isHidden = false } } } /// Displays an alert to the user to warn them that their login failed, and /// asks them to try again. func displayLoginFailedAlert() { // Get a reference to the animations queue. let animationsQueue = DispatchQueue(label: "Animations") // Add this operation to the animations queue. animationsQueue.sync { [unowned self] in // Send the block from the animations queue to the main queue when // the outer block executes, because it's performing UI updates. DispatchQueue.main.async { // Create an alert to warn the user. let alert = UIAlertController( title: "Login failed", message: "Please check your internet connection and try again.", preferredStyle: .alert) // Add an OK button. alert.addAction(UIAlertAction(title: "OK", style: .default)) // Present the alert. self.present(alert, animated: true) } } } // MARK: - UIViewController /// :nodoc: override func viewDidLoad() { super.viewDidLoad() // Get a reference to the application's instance of AppDelegate. let appDelegate = UIApplication.shared.delegate! as! AppDelegate // Set the completion handler that is called when AppDelegate is asked // to handle opening the Symonds Data Service redirect URL. This // occurs after an authorisation code has been received but before an // access token has been requested from the Data Service. appDelegate.symondsAPIURLCompletion = { // Get a reference to the animations queue. let animationsQueue = DispatchQueue(label: "Animations") // Send a block to the animations queue. animationsQueue.sync { // Dismiss the LoginViewController. self.dismiss(animated: true, completion: nil) } } // Set the completion handler that is called when the access token // request has finished. appDelegate.exchangeCompletion = { [unowned self] _, error in guard error == nil else { self.displayLoginFailedAlert() return } SymondsAPI.shared.getUserInfo { object in guard let object = object else { self.displayLoginFailedAlert() return } do { try PrimaryUser.shared.loadDetails(from: object) self.segueToTimetable() } catch { NSLog("Retrieval of user details failed!") if let error = error as? STError<PrimaryUser.Error> { NSLog("\(error.description)") } else { NSLog("Unexpected error \(error)") } self.displayLoginFailedAlert() } } } // Round the corners of the login button a little bit. logInButton.layer.cornerRadius = 5 // If this property isn't set to true, the button won't look right at // the rounded corners. logInButton.clipsToBounds = true } /// :nodoc: override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
mit
a5144234384d323f5a41a5d0443cf447
37.194444
84
0.570036
5.733945
false
false
false
false
practicalswift/swift
test/SILOptimizer/sil_combine_protocol_conf.swift
5
14790
// RUN: %target-swift-frontend %s -O -wmo -emit-sil -Xllvm -sil-disable-pass=DeadFunctionElimination -enforce-exclusivity=unchecked | %FileCheck %s // case 1: class protocol -- should optimize internal protocol SomeProtocol : class { func foo(x:SomeProtocol) -> Int func foo_internal() -> Int } internal class SomeClass: SomeProtocol { func foo_internal() ->Int { return 10 } func foo(x:SomeProtocol) -> Int { return x.foo_internal() } } // case 2: non-class protocol -- should optimize internal protocol SomeNonClassProtocol { func bar(x:SomeNonClassProtocol) -> Int func bar_internal() -> Int } internal class SomeNonClass: SomeNonClassProtocol { func bar_internal() -> Int { return 20 } func bar(x:SomeNonClassProtocol) -> Int { return x.bar_internal() } } // case 3: class conforming to protocol has a derived class -- should not optimize internal protocol DerivedProtocol { func foo() -> Int } internal class SomeDerivedClass: DerivedProtocol { func foo() -> Int { return 20 } } internal class SomeDerivedClassDerived: SomeDerivedClass { } // case 3: public protocol -- should not optimize public protocol PublicProtocol { func foo() -> Int } internal class SomePublicClass: PublicProtocol { func foo() -> Int { return 20 } } // case 4: Chain of protocols P1->P2->C -- optimize internal protocol MultiProtocolChain { func foo() -> Int } internal protocol RefinedMultiProtocolChain : MultiProtocolChain { func bar() -> Int } internal class SomeMultiClass: RefinedMultiProtocolChain { func foo() -> Int { return 20 } func bar() -> Int { return 30 } } // case 5: Generic conforming type -- should not optimize internal protocol GenericProtocol { func foo() -> Int } internal class GenericClass<T> : GenericProtocol { var items = [T]() func foo() -> Int { return items.count } } // case 6: two classes conforming to protocol internal protocol MultipleConformanceProtocol { func foo() -> Int } internal class Klass1: MultipleConformanceProtocol { func foo() -> Int { return 20 } } internal class Klass2: MultipleConformanceProtocol { func foo() -> Int { return 30 } } internal class Other { let x:SomeProtocol let y:SomeNonClassProtocol let z:DerivedProtocol let p:PublicProtocol let q:MultiProtocolChain let r:GenericProtocol let s:MultipleConformanceProtocol init(x:SomeProtocol, y:SomeNonClassProtocol, z:DerivedProtocol, p:PublicProtocol, q:MultiProtocolChain, r:GenericProtocol, s:MultipleConformanceProtocol) { self.x = x; self.y = y; self.z = z; self.p = p; self.q = q; self.r = r; self.s = s; } // CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf5OtherC11doWorkClassSiyF : $@convention(method) (@guaranteed Other) -> Int { // CHECK: bb0 // CHECK: debug_value // CHECK: integer_literal // CHECK: [[R1:%.*]] = ref_element_addr %0 : $Other, #Other.z // CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*DerivedProtocol to $*@opened("{{.*}}") DerivedProtocol // CHECK: [[W1:%.*]] = witness_method $@opened("{{.*}}") DerivedProtocol, #DerivedProtocol.foo!1 : <Self where Self : DerivedProtocol> (Self) -> () -> Int, [[O1]] : $*@opened("{{.*}}") DerivedProtocol : $@convention(witness_method: DerivedProtocol) <τ_0_0 where τ_0_0 : DerivedProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W1]]<@opened("{{.*}}") DerivedProtocol>([[O1]]) : $@convention(witness_method: DerivedProtocol) <τ_0_0 where τ_0_0 : DerivedProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R2:%.*]] = ref_element_addr %0 : $Other, #Other.p // CHECK: [[O2:%.*]] = open_existential_addr immutable_access [[R2]] : $*PublicProtocol to $*@opened("{{.*}}") PublicProtocol // CHECK: [[W2:%.*]] = witness_method $@opened("{{.*}}") PublicProtocol, #PublicProtocol.foo!1 : <Self where Self : PublicProtocol> (Self) -> () -> Int, [[O2]] : $*@opened("{{.*}}") PublicProtocol : $@convention(witness_method: PublicProtocol) <τ_0_0 where τ_0_0 : PublicProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W2]]<@opened("{{.*}}") PublicProtocol>([[O2]]) : $@convention(witness_method: PublicProtocol) <τ_0_0 where τ_0_0 : PublicProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R3:%.*]] = ref_element_addr %0 : $Other, #Other.r // CHECK: [[O3:%.*]] = open_existential_addr immutable_access [[R3]] : $*GenericProtocol to $*@opened("{{.*}}") GenericProtocol // CHECK: [[W3:%.*]] = witness_method $@opened("{{.*}}") GenericProtocol, #GenericProtocol.foo!1 : <Self where Self : GenericProtocol> (Self) -> () -> Int, [[O3]] : $*@opened("{{.*}}") GenericProtocol : $@convention(witness_method: GenericProtocol) <τ_0_0 where τ_0_0 : GenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W3]]<@opened("{{.*}}") GenericProtocol>([[O3]]) : $@convention(witness_method: GenericProtocol) <τ_0_0 where τ_0_0 : GenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R4:%.*]] = ref_element_addr %0 : $Other, #Other.s // CHECK: [[O4:%.*]] = open_existential_addr immutable_access %36 : $*MultipleConformanceProtocol to $*@opened("{{.*}}") MultipleConformanceProtocol // CHECK: [[W4:%.*]] = witness_method $@opened("{{.*}}") MultipleConformanceProtocol, #MultipleConformanceProtocol.foo!1 : <Self where Self : MultipleConformanceProtocol> (Self) -> () -> Int, %37 : $*@opened("{{.*}}") MultipleConformanceProtocol : $@convention(witness_method: MultipleConformanceProtocol) <τ_0_0 where τ_0_0 : MultipleConformanceProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W4]]<@opened("{{.*}}") MultipleConformanceProtocol>(%37) : $@convention(witness_method: MultipleConformanceProtocol) <τ_0_0 where τ_0_0 : MultipleConformanceProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: struct // CHECK: return // CHECK: } // end sil function '$s25sil_combine_protocol_conf5OtherC11doWorkClassSiyF' @inline(never) func doWorkClass () ->Int { return self.x.foo(x:self.x) // optimize + self.y.bar(x:self.y) // optimize + self.z.foo() // do not optimize + self.p.foo() // do not optimize + self.q.foo() // optimize + self.r.foo() // do not optimize + self.s.foo() // do not optimize } } // case 1: struct -- optimize internal protocol PropProtocol { var val: Int { get set } } internal struct PropClass: PropProtocol { var val: Int init(val: Int) { self.val = val } } // case 2: generic struct -- do not optimize internal protocol GenericPropProtocol { var val: Int { get set } } internal struct GenericPropClass<T>: GenericPropProtocol { var val: Int init(val: Int) { self.val = val } } // case 3: nested struct -- optimize internal protocol NestedPropProtocol { var val: Int { get } } struct Outer { struct Inner : NestedPropProtocol { var val: Int init(val: Int) { self.val = val } } } // case 4: generic nested struct -- do not optimize internal protocol GenericNestedPropProtocol { var val: Int { get } } struct GenericOuter<T> { struct GenericInner : GenericNestedPropProtocol { var val: Int init(val: Int) { self.val = val } } } internal class OtherClass { var arg1: PropProtocol var arg2: GenericPropProtocol var arg3: NestedPropProtocol var arg4: GenericNestedPropProtocol init(arg1:PropProtocol, arg2:GenericPropProtocol, arg3: NestedPropProtocol, arg4: GenericNestedPropProtocol) { self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 self.arg4 = arg4 } // CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf10OtherClassC12doWorkStructSiyF : $@convention(method) (@guaranteed OtherClass) -> Int { // CHECK: bb0 // CHECK: debug_value // CHECK: [[A1:%.*]] = alloc_stack $PropProtocol // CHECK: [[R1:%.*]] = ref_element_addr %0 : $OtherClass, #OtherClass.arg1 // CHECK: copy_addr [[R1]] to [initialization] [[A1]] : $*PropProtocol // CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[A1]] : $*PropProtocol to $*@opened("{{.*}}") PropProtocol // CHECK: [[U1:%.*]] = unchecked_addr_cast [[O1]] : $*@opened("{{.*}}") PropProtocol to $*PropClass // CHECK: [[S1:%.*]] = struct_element_addr [[U1]] : $*PropClass, #PropClass.val // CHECK: [[S11:%.*]] = struct_element_addr [[S1]] : $*Int, #Int._value // CHECK: load [[S11]] // CHECK: destroy_addr [[A1]] : $*PropProtocol // CHECK: [[A2:%.*]] = alloc_stack $GenericPropProtocol // CHECK: [[R2:%.*]] = ref_element_addr %0 : $OtherClass, #OtherClass.arg2 // CHECK: copy_addr [[R2]] to [initialization] [[A2]] : $*GenericPropProtocol // CHECK: [[O2:%.*]] = open_existential_addr immutable_access [[A2]] : $*GenericPropProtocol to $*@opened("{{.*}}") GenericPropProtocol // CHECK: [[W2:%.*]] = witness_method $@opened("{{.*}}") GenericPropProtocol, #GenericPropProtocol.val!getter.1 : <Self where Self : GenericPropProtocol> (Self) -> () -> Int, [[O2]] : $*@opened("{{.*}}") GenericPropProtocol : $@convention(witness_method: GenericPropProtocol) <τ_0_0 where τ_0_0 : GenericPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W2]]<@opened("{{.*}}") GenericPropProtocol>([[O2]]) : $@convention(witness_method: GenericPropProtocol) <τ_0_0 where τ_0_0 : GenericPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: destroy_addr [[A2]] : $*GenericPropProtocol // CHECK: struct_extract // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: dealloc_stack [[A2]] : $*GenericPropProtocol // CHECK: dealloc_stack [[A1]] : $*PropProtocol // CHECK: [[A4:%.*]] = alloc_stack $NestedPropProtocol // CHECK: [[R4:%.*]] = ref_element_addr %0 : $OtherClass, #OtherClass.arg3 // CHECK: copy_addr [[R4]] to [initialization] [[A4]] : $*NestedPropProtocol // CHECK: [[O4:%.*]] = open_existential_addr immutable_access [[A4]] : $*NestedPropProtocol to $*@opened("{{.*}}") NestedPropProtocol // CHECK: [[U4:%.*]] = unchecked_addr_cast [[O4]] : $*@opened("{{.*}}") NestedPropProtocol to $*Outer.Inner // CHECK: [[S4:%.*]] = struct_element_addr [[U4]] : $*Outer.Inner, #Outer.Inner.val // CHECK: [[S41:%.*]] = struct_element_addr [[S4]] : $*Int, #Int._value // CHECK: load [[S41]] // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: dealloc_stack [[A4]] : $*NestedPropProtocol // CHECK: [[A5:%.*]] = alloc_stack $GenericNestedPropProtocol // CHECK: [[R5:%.*]] = ref_element_addr %0 : $OtherClass, #OtherClass.arg4 // CHECK: copy_addr [[R5]] to [initialization] [[A5]] : $*GenericNestedPropProtocol // CHECK: [[O5:%.*]] = open_existential_addr immutable_access [[A5]] : $*GenericNestedPropProtocol to $*@opened("{{.*}}") GenericNestedPropProtocol // CHECK: [[W5:%.*]] = witness_method $@opened("{{.*}}") GenericNestedPropProtocol, #GenericNestedPropProtocol.val!getter.1 : <Self where Self : GenericNestedPropProtocol> (Self) -> () -> Int, [[O5:%.*]] : $*@opened("{{.*}}") GenericNestedPropProtocol : $@convention(witness_method: GenericNestedPropProtocol) <τ_0_0 where τ_0_0 : GenericNestedPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W5]]<@opened("{{.*}}") GenericNestedPropProtocol>([[O5]]) : $@convention(witness_method: GenericNestedPropProtocol) <τ_0_0 where τ_0_0 : GenericNestedPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: struct // CHECK: destroy_addr [[A5]] : $*GenericNestedPropProtocol // CHECK: dealloc_stack [[A5]] : $*GenericNestedPropProtocol // CHECK: return // CHECK: } // end sil function '$s25sil_combine_protocol_conf10OtherClassC12doWorkStructSiyF' @inline(never) func doWorkStruct () -> Int{ return self.arg1.val // optimize + self.arg2.val // do not optimize + self.arg3.val // optimize + self.arg4.val // do not optimize } } // case 1: enum -- optimize internal protocol AProtocol { var val: Int { get } } internal enum AnEnum : AProtocol { case avalue var val: Int { switch self { case .avalue: return 10 } } } // case 2: generic enum -- do not optimize internal protocol AGenericProtocol { var val: Int { get } } internal enum AGenericEnum<T> : AGenericProtocol { case avalue var val: Int { switch self { case .avalue: return 10 } } } internal class OtherKlass { var arg1: AProtocol var arg2: AGenericProtocol init(arg1:AProtocol, arg2:AGenericProtocol) { self.arg1 = arg1 self.arg2 = arg2 } // CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf10OtherKlassC10doWorkEnumSiyF : $@convention(method) (@guaranteed OtherKlass) -> Int { // CHECK: bb0 // CHECK: debug_value // CHECK: integer_literal // CHECK: [[A1:%.*]] = alloc_stack $AGenericProtocol // CHECK: [[R1:%.*]] = ref_element_addr %0 : $OtherKlass, #OtherKlass.arg2 // CHECK: copy_addr [[R1]] to [initialization] [[A1]] : $*AGenericProtocol // CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[A1]] : $*AGenericProtocol to $*@opened("{{.*}}") AGenericProtocol // CHECK: [[W1:%.*]] = witness_method $@opened("{{.*}}") AGenericProtocol, #AGenericProtocol.val!getter.1 : <Self where Self : AGenericProtocol> (Self) -> () -> Int, [[O1]] : $*@opened("{{.*}}") AGenericProtocol : $@convention(witness_method: AGenericProtocol) <τ_0_0 where τ_0_0 : AGenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W1]]<@opened("{{.*}}") AGenericProtocol>([[O1]]) : $@convention(witness_method: AGenericProtocol) <τ_0_0 where τ_0_0 : AGenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: struct // CHECK: destroy_addr [[A1]] : $*AGenericProtocol // CHECK: dealloc_stack [[A1]] : $*AGenericProtocol // CHECK: return // CHECK: } // end sil function '$s25sil_combine_protocol_conf10OtherKlassC10doWorkEnumSiyF' @inline(never) func doWorkEnum() -> Int { return self.arg1.val // optimize + self.arg2.val // do not optimize } }
apache-2.0
6f2a5b92397dc83e43328d2b5963fa15
39.516484
388
0.656903
3.713926
false
false
false
false
ascode/JF-IOS-Swift_demos
IOSDemos/Views/PlayVoiceFormNetView.swift
1
5569
// // PlayVoiceFormNetView.swift // IOSDemos // // Created by 金飞 on 28/12/2016. // Copyright © 2016 Enjia. All rights reserved. // import UIKit import AVFoundation class PlayVoiceFormNetView: UIView, AVAudioPlayerDelegate { var _delegate: PlayVoiceFormNetViewDelegate! let urlTextInput: UITextField = UITextField() var player: AVAudioPlayer!//不要把 AVAudioPlayer 当做局部变量,在局部声明不会发出声音 override init(frame: CGRect) { super.init(frame: frame) let kbtnBackW: CGFloat = 36 let kbtnBackH: CGFloat = kbtnBackW let kbtnBackX: CGFloat = 15 let kbtnBackY: CGFloat = 15 let btnBack: UIButton = UIButton() btnBack.frame = CGRect(x: kbtnBackX, y: kbtnBackY, width: kbtnBackW, height: kbtnBackH) btnBack.setImage(#imageLiteral(resourceName: "btnBack"), for: UIControlState.normal) self.addSubview(btnBack) btnBack.addTarget(self, action: #selector(PlayVoiceFormNetView.btnBackPressed(btnObj:)), for: UIControlEvents.touchUpInside) let kurlTextInputW: CGFloat = UIScreen.main.bounds.width let kurlTextInputH: CGFloat = 26 let kurlTextInputX: CGFloat = 0 let kurlTextInputY: CGFloat = UIScreen.main.bounds.height * 0.2 urlTextInput.frame = CGRect(x: kurlTextInputX, y: kurlTextInputY, width: kurlTextInputW, height: kurlTextInputH) //urlTextInput.text = "http://image.bgenius.cn/enjiafuture/voice/vocabulary_word_voice/100" urlTextInput.text = "http://image.bgenius.cn/enjiafuture/voice/stlc_content_voice/11255" urlTextInput.borderStyle = UITextBorderStyle.line self.addSubview(urlTextInput) let kbtnPlayW: CGFloat = 36 let kbtnPlayH: CGFloat = kbtnPlayW let kbtnPlayX: CGFloat = (UIScreen.main.bounds.width - kbtnPlayW) / 2 let kbtnPlayY: CGFloat = kurlTextInputY + kurlTextInputH + kbtnPlayW let btnPlay: UIButton = UIButton() btnPlay.frame = CGRect(x: kbtnPlayX, y: kbtnPlayY, width: kbtnPlayW, height: kbtnPlayH) btnPlay.setImage(#imageLiteral(resourceName: "btnPlay"), for: UIControlState.normal) btnPlay.addTarget(self, action: #selector(PlayVoiceFormNetView.btnPlayPressed(btnObj:)), for: UIControlEvents.touchUpInside) self.addSubview(btnPlay) let kbtnPlayLocalW: CGFloat = 280 let kbtnPlayLocalH: CGFloat = 150 let kbtnPlayLocalX: CGFloat = (UIScreen.main.bounds.width - kbtnPlayLocalW) / 2 let kbtnPlayLocalY: CGFloat = kbtnPlayY + kbtnPlayH + kbtnPlayLocalW let btnPlayLocal: UIButton = UIButton() btnPlayLocal.frame = CGRect(x: kbtnPlayLocalX, y: kbtnPlayLocalY, width: kbtnPlayLocalW, height: kbtnPlayLocalH) btnPlayLocal.setImage(#imageLiteral(resourceName: "btnPlay"), for: UIControlState.normal) btnPlayLocal.setTitle("播放本地音乐", for: UIControlState.normal) btnPlayLocal.setTitleColor(UIColor.black, for: UIControlState.normal) btnPlayLocal.addTarget(self, action: #selector(PlayVoiceFormNetView.btnPlayLocalPressed(btnObj:)), for: UIControlEvents.touchUpInside) self.addSubview(btnPlayLocal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { print("播放完毕") } func btnPlayPressed(btnObj: UIButton){ let session:AVAudioSession = AVAudioSession.sharedInstance() do { try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.defaultToSpeaker) try session.setActive(true) }catch let err as NSError { print(err.localizedDescription) } let voiceUrl: URL = URL(string: self.urlTextInput.text!)! do { let voiceData: NSData! = NSData(contentsOf: voiceUrl) if let voice: NSData = voiceData { player = try AVAudioPlayer(data: voice as Data, fileTypeHint: "AVFileTypeMPEGLayer3") // player = try AVAudioPlayer(contentsOf: voiceUrl) player.prepareToPlay() player.delegate = self player.play() } }catch let err as NSError { print(err.localizedDescription) } } func btnPlayLocalPressed(btnObj: UIButton){ let session:AVAudioSession = AVAudioSession.sharedInstance() do { try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.defaultToSpeaker) try session.setActive(true) }catch let err as NSError { print(err.localizedDescription) } let voiceUrl: URL = URL(fileURLWithPath: Bundle.main.path(forResource: "anjiexigongzhu", ofType: "mp3")!) do { player = try AVAudioPlayer(contentsOf: voiceUrl) player.prepareToPlay() player.delegate = self player.play() }catch let err as NSError { print(err.localizedDescription) } } func btnBackPressed(btnObj: UIButton){ self._delegate.btnBackPressed(btnObj: btnObj) } }
artistic-2.0
2dd917d5f41b75b4926dfb13d7da27c8
37.222222
142
0.639898
4.990027
false
false
false
false
tominated/Quake3BSPParser
Sources/Quake3BSPParser.swift
1
11112
// // Quake3BSPParser.swift // Quake3BSPParser // // Created by Thomas Brunoli on {TODAY}. // Copyright © 2017 Quake3BSPParser. All rights reserved. // import Foundation import simd // Directory: let ENTITIES_INDEX = 0; let TEXTURES_INDEX = 1; let PLANES_INDEX = 2; let NODES_INDEX = 3; let LEAVES_INDEX = 4; let LEAF_FACES_INDEX = 5; let LEAF_BRUSHES_INDEX = 6; let MODELS_INDEX = 7; let BRUSHES_INDEX = 8; let BRUSH_SIDES_INDEX = 9; let VERTICES_INDEX = 10; let MESH_VERTS_INDEX = 11; let EFFECTS_INDEX = 12; let FACES_INDEX = 13; let LIGHTMAPS_INDEX = 14; let LIGHT_VOLS_INDEX = 15; let VISDATA_INDEX = 16; func colorToFloat4(_ r: UInt8, _ g: UInt8, _ b: UInt8, _ a: UInt8) -> float4 { return float4( Float(r) / 255, Float(g) / 255, Float(b) / 255, Float(a) / 255 ) } public class Quake3BSPParser { let reader: BinaryReader; var directory: Array<Range<Int>> = []; var bsp = Quake3BSP(); public enum ParseError: Error { case invalidBSP(reason: String); } public init(bspData data: Data) throws { reader = BinaryReader(data); try parseHeader(); } public func parse() throws -> Quake3BSP { try parseEntities(); try parseTextures(); try parsePlanes(); try parseNodes(); try parseLeaves(); try parseLeafFaces(); try parseLeafBrushes(); try parseModels(); try parseBrushes(); try parseBrushSides(); try parseVertices(); try parseMeshVerts(); try parseEffects(); try parseFaces(); try parseLightmaps(); try parseLightVols(); try parseVisdata(); return bsp } // Parse the header of a Quake 3 BSP file and return the directory private func parseHeader() throws { // Ensure the 'magic' value is correct guard reader.getString(maxLength: 4) == "IBSP" else { throw ParseError.invalidBSP(reason: "Magic value not IBSP"); } // Ensure the version is correct let version: Int32 = reader.getNumber(); guard version == 0x2e else { throw ParseError.invalidBSP(reason: "Version not 0x2e"); } // Get the directory entry index/lengths (as ranges) for _ in 0 ..< 17 { let start: Int32 = reader.getNumber(); let size: Int32 = reader.getNumber(); directory.append(Int(start) ..< Int(start + size)); } } private func parseEntities() throws { let entry = directory[ENTITIES_INDEX]; reader.jump(to: entry.lowerBound); guard let entities = reader.getString(maxLength: entry.count) else { throw ParseError.invalidBSP(reason: "Error parsing entities"); }; bsp.entities = BSPEntities(entities: entities); } private func parseTextures() throws { bsp.textures = try readEntry(index: TEXTURES_INDEX, entryLength: 72) { reader in guard let name = reader.getString(maxLength: 64) else { throw ParseError.invalidBSP(reason: "Error parsing texture name"); } return BSPTexture( name: name, surfaceFlags: reader.getNumber(), contentFlags: reader.getNumber() ); } } private func parsePlanes() throws { bsp.planes = try readEntry(index: PLANES_INDEX, entryLength: 16) { reader in return BSPPlane( normal: reader.getFloat3(), distance: reader.getNumber() ); } } private func parseNodes() throws { bsp.nodes = try readEntry(index: NODES_INDEX, entryLength: 36) { reader in let planeIndex: Int32 = reader.getNumber(); let leftChildRaw: Int32 = reader.getNumber(); let rightChildRaw: Int32 = reader.getNumber(); let boundingBoxMin = reader.getInt3(); let boundingBoxMax = reader.getInt3(); let leftChild: BSPNode.NodeChild = leftChildRaw < 0 ? .leaf(-(Int(leftChildRaw) + 1)) : .node(Int(leftChildRaw)) let rightChild: BSPNode.NodeChild = rightChildRaw < 0 ? .leaf(-(Int(rightChildRaw) + 1)) : .node(Int(rightChildRaw)) return BSPNode( planeIndex: planeIndex, leftChild: leftChild, rightChild: rightChild, boundingBoxMin: boundingBoxMin, boundingBoxMax: boundingBoxMax ); } } private func parseLeaves() throws { bsp.leaves = try readEntry(index: LEAVES_INDEX, entryLength: 48) { reader in return BSPLeaf( cluster: reader.getNumber(), area: reader.getNumber(), boundingBoxMin: reader.getInt3(), boundingBoxMax: reader.getInt3(), leafFaceIndices: reader.getIndexRange(), leafBrushIndices: reader.getIndexRange() ); } } private func parseLeafFaces() throws { bsp.leafFaces = try readEntry(index: LEAF_FACES_INDEX, entryLength: 4) { reader in return BSPLeafFace(faceIndex: reader.getNumber()); } } private func parseLeafBrushes() throws { bsp.leafBrushes = try readEntry(index: LEAF_BRUSHES_INDEX, entryLength: 4) { reader in return BSPLeafBrush(brushIndex: reader.getNumber()); } } private func parseModels() throws { bsp.models = try readEntry(index: MODELS_INDEX, entryLength: 40) { reader in return BSPModel( boundingBoxMin: reader.getFloat3(), boundingBoxMax: reader.getFloat3(), faceIndices: reader.getIndexRange(), brushIndices: reader.getIndexRange() ); } } private func parseBrushes() throws { bsp.brushes = try readEntry(index: BRUSHES_INDEX, entryLength: 12) { reader in return BSPBrush( brushSideIndices: reader.getIndexRange(), textureIndex: reader.getNumber() ); } } private func parseBrushSides() throws { bsp.brushSides = try readEntry(index: BRUSH_SIDES_INDEX, entryLength: 8) { reader in return BSPBrushSide( planeIndex: reader.getNumber(), textureIndex: reader.getNumber() ); } } private func parseVertices() throws { bsp.vertices = try readEntry(index: VERTICES_INDEX, entryLength: 44) { reader in return BSPVertex( position: reader.getFloat3(), surfaceTextureCoord: reader.getFloat2(), lightmapTextureCoord: reader.getFloat2(), normal: reader.getFloat3(), color: colorToFloat4(reader.getNumber(), reader.getNumber(), reader.getNumber(), reader.getNumber()) ) } } private func parseMeshVerts() throws { bsp.meshVerts = try readEntry(index: MESH_VERTS_INDEX, entryLength: 4) { reader in return BSPMeshVert(vertexIndexOffset: reader.getNumber()); } } private func parseEffects() throws { bsp.effects = try readEntry(index: EFFECTS_INDEX, entryLength: 72) { reader in guard let name = reader.getString(maxLength: 64) else { throw ParseError.invalidBSP(reason: "Error parsing effect name"); } return BSPEffect( name: name, brushIndex: reader.getNumber() ); } } private func parseFaces() throws { bsp.faces = try readEntry(index: FACES_INDEX, entryLength: 104) { reader in let textureIndex: Int32 = reader.getNumber(); let effectIndex: Int32 = reader.getNumber(); guard let faceType = BSPFace.FaceType(rawValue: reader.getNumber()) else { throw ParseError.invalidBSP(reason: "Error parsing face type"); } return BSPFace( textureIndex: textureIndex, effectIndex: effectIndex >= 0 ? effectIndex : nil, type: faceType, vertexIndices: reader.getIndexRange(), meshVertIndices: reader.getIndexRange(), lightmapIndex: reader.getNumber(), lightmapStart: reader.getInt2(), lightmapSize: reader.getInt2(), lightmapOrigin: reader.getFloat3(), lightmapSVector: reader.getFloat3(), lightmapTVector: reader.getFloat3(), normal: reader.getFloat3(), size: reader.getInt2() ) } } private func parseLightmaps() throws { bsp.lightmaps = try readEntry(index: LIGHTMAPS_INDEX, entryLength: 128 * 128 * 3) { reader in var lightmap: Array<(UInt8, UInt8, UInt8)> = []; for _ in 0 ..< (128 * 128) { lightmap.append((reader.getNumber(), reader.getNumber(), reader.getNumber())) } return BSPLightmap(lightmap: lightmap); } } private func parseLightVols() throws { bsp.lightVols = try readEntry(index: LIGHT_VOLS_INDEX, entryLength: 8) { reader in return BSPLightVol( ambientColor: (reader.getNumber(), reader.getNumber(), reader.getNumber()), directionalColor: (reader.getNumber(), reader.getNumber(), reader.getNumber()), direction: (reader.getNumber(), reader.getNumber()) ) } } private func parseVisdata() throws { let entry = directory[VISDATA_INDEX]; guard entry.count > 0 else { print("No visdata") return } reader.jump(to: entry.lowerBound); let numVectors: Int32 = reader.getNumber(); let vectorSize: Int32 = reader.getNumber(); var visdata: Array<UInt8> = []; for _ in 0 ..< (numVectors * vectorSize) { visdata.append(reader.getNumber()) } bsp.visdata = BSPVisdata( numVectors: numVectors, vectorSize: vectorSize, vectors: visdata ) } // Parse an entry with a closure for each item in the entry private func readEntry<T>( index: Int, entryLength: Int, each: (BinaryReader) throws -> T? ) throws -> Array<T> { guard index < directory.count else { throw ParseError.invalidBSP(reason: "Directory entry not found"); } let entry = directory[index]; let subReader = reader.subdata(in: entry); let numItems = entry.count / entryLength; var accumulator: Array<T> = []; for i in 0 ..< numItems { subReader.jump(to: i * entryLength); if let value = try each(subReader) { accumulator.append(value); } } return accumulator; } }
mit
3563158157fa4e8412bc80fc517d1bf9
31.488304
116
0.568086
4.49656
false
false
false
false
lerigos/music-service
iOS_9/Pods/SwiftyVK/Source/SDK/Models/Media.swift
2
1168
import Foundation public struct Media : CustomStringConvertible { enum MediaType { case image case audio case video case document } public enum ImageType : String { case JPG case PNG case BMP case GIF } let data : NSData let mediaType : MediaType var imageType : ImageType = .JPG var documentType : String = "untitled" var type : String { switch mediaType { case .image: return imageType.rawValue case .document: return documentType case .audio: return "mp3" case .video: return "video" } } public var description: String { get { return "VK.Media with type \(type)" } } public init(imageData: NSData, type: ImageType) { mediaType = .image imageType = type data = imageData } public init(audioData: NSData) { mediaType = .audio data = audioData } public init(videoData: NSData) { mediaType = .video data = videoData } public init(documentData: NSData, type: String) { mediaType = .document documentType = type data = documentData } }
apache-2.0
65025542959109d08dd28b9bc60eaa77
14.168831
51
0.598459
4.509653
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeLoading/AwesomeLoading/Classes/Shimmer/ShimmerView.swift
1
3496
// // ShimmerView.swift // AwesomeLoading // // Created by Emmanuel on 21/06/2018. // import UIKit class ShimmerView: UIView, ShimmerEffect { override open static var layerClass: AnyClass { return CAGradientLayer.self } open var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } open var animationDuration: TimeInterval = 3 open var animationDelay: TimeInterval = 1.5 open var gradientHighlightRatio: Double = 0.3 @IBInspectable open var shimmerGradientTint: UIColor = .black @IBInspectable open var shimmerGradientHighlight: UIColor = .white } // MARK: - UIView Extension extension UIView { public func startShimmerAnimation(delay: Double = 0.2, tint: UIColor = UIColor.init(red: 35/255.0, green: 39/255.0, blue: 47/255.0, alpha: 0.2), highlight: UIColor = UIColor.init(red: 40/255.0, green: 45/255.0, blue: 53/255.0, alpha: 0.8), highlightRatio: Double = 0.8, widthRatio: CGFloat = 1, heightRatio: CGFloat = 1, alignment: NSTextAlignment = .center) { stopShimmerAnimation() let shimmerView = ShimmerView() //shimmerView.frame = CGRect(x: 0, y: 0, width: self.bounds.width*widthRatio, height: self.bounds.height*heightRatio) //shimmerView.center = CGPoint(x: self.bounds.width/2, y: self.bounds.height/2) shimmerView.backgroundColor = .clear shimmerView.shimmerGradientTint = tint shimmerView.shimmerGradientHighlight = highlight shimmerView.animationDelay = delay shimmerView.gradientHighlightRatio = highlightRatio shimmerView.addShimmerAnimation() self.addSubview(shimmerView) shimmerView.translatesAutoresizingMaskIntoConstraints = false switch alignment { case .left: self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)) break case .right: self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)) break default: self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) } self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: widthRatio, constant: 0)) self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: heightRatio, constant: 0)) } public func stopShimmerAnimation() { for subview in subviews { if let subview = subview as? ShimmerView { subview.removeShimmerAnimation() subview.removeFromSuperview() } } } }
mit
864eb45a761d98c68786034df4005c67
40.129412
176
0.624714
4.896359
false
false
false
false
iOSWizards/AwesomeMedia
AwesomeMedia/Classes/Views/AwesomeMediaView.swift
1
11514
// // AwesomeMediaView.swift // AwesomeMedia // // Created by Evandro Harrison Hoffmann on 4/5/18. // import UIKit import AVFoundation import AwesomeLoading import MediaPlayer // Typealiases public typealias FinishedPlayingCallback = () -> Void public class AwesomeMediaView: UIView { public var mediaParams = AwesomeMediaParams() public var controlView: AwesomeMediaVideoControlView? public var titleView: AwesomeMediaVideoTitleView? public var coverImageView: UIImageView? @IBInspectable public var canLoadCoverImage: Bool = true // Callbacks public var finishedPlayingCallback: FinishedPlayingCallback? public override func awakeFromNib() { super.awakeFromNib() addObservers() } public override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) AwesomeMediaPlayerLayer.shared.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height) } public func configure( withMediaParams mediaParams: AwesomeMediaParams, controls: AwesomeMediaVideoControls, states: AwesomeMediaVideoStates, trackingSource: AwesomeMediaTrackingSource, titleViewVisible: Bool = false) { self.mediaParams = mediaParams // remove player layer so that we can add it again when needed self.removePlayerLayer() // Control View configureControls(controls: controls, states: states, trackingSource: trackingSource) // Auto play media if the case applyParamKeys() // Title view if titleViewVisible { configureTitle() } // check for media playing if let item = sharedAVPlayer.currentItem(withParams: mediaParams) { controlView?.update(withItem: item) addPlayerLayer() } // set coverImage addCoverImage() // check for loading state stopLoadingAnimation() if AwesomeMediaManager.shared.mediaIsLoading(withParams: mediaParams) { startLoadingAnimation() } // update Speed speedRateChanged() } fileprivate func configureControls(controls: AwesomeMediaVideoControls, states: AwesomeMediaVideoStates = .standard, trackingSource: AwesomeMediaTrackingSource) { // Filter controls if needed var controls = controls if mediaParams.markers.count == 0 { controls.remove(.jumpto) } // Add controls controlView = superview?.addVideoControls(withControls: controls, states: states, trackingSource: trackingSource) // set time label controlView?.timeLabel?.text = mediaParams.duration.timeString.uppercased() // show progress from last play duration let progressDuration = (mediaParams.url?.url?.time ?? 0) / Float(mediaParams.duration) if progressDuration < 1 { controlView?.progressView.progress = (mediaParams.url?.url?.time ?? 0) / Float(mediaParams.duration) controlView?.progressView.transform = CGAffineTransform(scaleX: 1.0, y: 3.0) } else { // set progress to 0.0 controlView?.progressView.progress = 0.0 } controlView?.playCallback = { [weak self] (isPlaying) in guard let self = self else { return } if isPlaying { AwesomeMediaManager.shared.playMedia( withParams: self.mediaParams, inPlayerLayer: AwesomeMediaPlayerLayer.shared, viewController: self.parentViewController) // update caption button based on current item self.titleView?.updateCaptionButtonBasedOnCurrentItem() // adds player layer self.addPlayerLayer() } else { sharedAVPlayer.pause() } } controlView?.toggleViewCallback = { [weak self] (_) in self?.titleView?.toggleView() } // seek slider controlView?.timeSliderChangedCallback = { (time) in sharedAVPlayer.seek(toTime: time) } controlView?.timeSliderFinishedDraggingCallback = { (play) in if play { sharedAVPlayer.play() } } // Rewind controlView?.rewindCallback = { sharedAVPlayer.seekBackward() } // Speed controlView?.speedToggleCallback = { sharedAVPlayer.toggleSpeed() } } fileprivate func configureTitle() { titleView = superview?.addVideoTitle() titleView?.configure(withMediaParams: mediaParams) // show airplay menu titleView?.airplayCallback = { [weak self] in self?.showAirplayMenu() } // show captions menu titleView?.captionsCallback = { [weak self] in self?.parentViewController?.showCaptions { (caption) in let selected = sharedAVPlayer.currentItem?.selectSubtitle(caption) print("\(caption ?? "none") caption selected: \(selected ?? false)") } } } public func applyParamKeys() { var needDelay: Bool = false // Auto start media on time if let startOnTime = mediaParams.params[AwesomeMediaParamsKey.startOnTime.rawValue] as? Double { sharedAVPlayer.seek(toTime: startOnTime, pausing: false) needDelay = true } // Auto play media if the case if let autoPlay = mediaParams.params[AwesomeMediaParamsKey.autoplay.rawValue] as? Bool, autoPlay { DispatchQueue.main.asyncAfter(deadline: .now() + (needDelay ? 1 : 0)) { if !(self.controlView?.playButton.isSelected ?? false) { self.controlView?.playButtonPressed(self) } } } //mediaParams.params = [:] } } // MARK: - Observers extension AwesomeMediaView: AwesomeMediaEventObserver { public func addObservers() { AwesomeMediaNotificationCenter.addObservers([.basic, .timeUpdated, .speedRateChanged, .timedOut, .stopped], to: self) } public func removeObservers() { AwesomeMediaNotificationCenter.removeObservers(from: self) } public func startedPlaying() { guard sharedAVPlayer.isPlaying(withParams: mediaParams) else { // not this media, reset player resetPlayer() return } // adds player layer addPlayerLayer() // set play button selected controlView?.playButton.isSelected = true // hide coverImage showCoverImage(false) // update Control Center AwesomeMediaControlCenter.updateControlCenter(withParams: mediaParams) // remove media alert if present parentViewController?.removeAlertIfPresent() } public func pausedPlaying() { controlView?.playButton.isSelected = sharedAVPlayer.isPlaying(withParams: mediaParams) } public func stoppedPlaying() { pausedPlaying() stoppedBuffering() resetPlayer() // remove media alert if present parentViewController?.removeAlertIfPresent() } public func timeUpdated() { guard let item = sharedAVPlayer.currentItem(withParams: mediaParams) else { return } //AwesomeMedia.log("Current time updated: \(item.currentTime().seconds) of \(CMTimeGetSeconds(item.duration))") // update time controls controlView?.update(withItem: item) } public func startedBuffering() { guard !(controlView?.timerSliderIsSliding ?? false), AwesomeMedia.shouldLockControlsWhenBuffering, sharedAVPlayer.isCurrentItem(withParams: mediaParams) else { stoppedBuffering() return } startLoadingAnimation() if let controlView = controlView { // bring controlview to front as loading animation will be on top bringSubviewToFront(controlView) // lock state for controlView controlView.lock(true, animated: true) // cancels auto hide controlView.show() } } public func stoppedBuffering() { stopLoadingAnimation() // unlock controls controlView?.lock(false, animated: true) // setup auto hide controlView?.setupAutoHide() } public func finishedPlaying() { resetPlayer() // do something after finished playing finishedPlayingCallback?() } public func speedRateChanged() { controlView?.speedLabel?.text = AwesomeMediaSpeed.speedLabelForCurrentSpeed } public func timedOut() { parentViewController?.showMediaTimedOutAlert() } public func resetPlayer() { // reset controls controlView?.reset() // show cover image showCoverImage(true) } } // MARK: - Touches extension AwesomeMediaView { public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { controlView?.toggleViewIfPossible() } } // MARK: - Media Cover extension AwesomeMediaView { public func addCoverImage() { guard canLoadCoverImage else { return } // remove pre-existing cover images coverImageView?.removeFromSuperview() guard let coverImageUrl = mediaParams.coverUrl else { return } // set the cover image coverImageView = UIImageView(image: nil) coverImageView?.setImage(coverImageUrl) guard let coverImageView = coverImageView else { return } coverImageView.contentMode = .scaleAspectFill superview?.addSubview(coverImageView) superview?.sendSubviewToBack(coverImageView) coverImageView.translatesAutoresizingMaskIntoConstraints = false superview?.addConstraint(NSLayoutConstraint(item: coverImageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)) superview?.addConstraint(NSLayoutConstraint(item: coverImageView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)) superview?.addConstraint(NSLayoutConstraint(item: coverImageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)) superview?.addConstraint(NSLayoutConstraint(item: coverImageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)) // hide cover image in case is not playing current item showCoverImage(!sharedAVPlayer.isPlaying(withParams: mediaParams)) } public func showCoverImage(_ show: Bool) { coverImageView?.isHidden = !show } }
mit
2d46ca2435f45d061ac5e77acd4a2690
31.525424
179
0.604916
5.754123
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/Chart/ElapsedTimeFormatter.swift
1
3381
/* * Copyright 2019 Google LLC. 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 /// Formats a timestamp in milliseconds to a string representation: /// /// 01:30 - one minute, thirty seconds /// 9:00:45 - 9 hours, fourty-five seconds /// -15:25 - negative fifteen minutes, twenty-five seconds /// /// Defaults to only displays hours if the time is greater than or equal to one hour. /// Toggle alwaysDisplayHours to always display hours. /// Toggle shouldDisplayTenths to display tenths of a second. class ElapsedTimeFormatter: Formatter { let millisInSecond: Int64 = 1000 let minutesInHour: Int64 = 60 let secondsInMinute: Int64 = 60 let tenthsInSecond: Int64 = 10 /// If true displays tenths of a second. var shouldDisplayTenths = false /// If true displays the string with hours var alwaysDisplayHours = false override func string(for obj: Any?) -> String? { guard let timestamp = obj as? Int64 else { return nil } return string(fromTimestamp: timestamp) } /// Returns a string representation of the given timestamp. /// /// - Parameter timestamp: A timestamp in milliseconds. /// - Returns: A string. func string(fromTimestamp timestamp: Int64) -> String { // Calculate the format independent of sign. A minus sign is prepended if necessary. let isNegative = timestamp < 0 let absTimestamp = abs(timestamp) let secondsInHour = secondsInMinute * minutesInHour let hours = absTimestamp / millisInSecond / secondsInHour let secondsInTotalHours = hours * secondsInHour let minutes = (absTimestamp / millisInSecond - secondsInTotalHours) / secondsInMinute let seconds = absTimestamp / millisInSecond - secondsInTotalHours - minutes * secondsInMinute // This method of padding a leading zero is more performant than using // `String(format: "%02d", seconds)` and makes a difference when this is called rapidly (such as // when drawing TimeAxisView. var secondsFormatted = String(seconds) if seconds < 10 { secondsFormatted = "0" + secondsFormatted } var formatted: String if alwaysDisplayHours || hours > 0 { var minutesFormatted = String(minutes) if minutes < 10 { minutesFormatted = "0" + minutesFormatted } formatted = "\(hours):\(minutesFormatted):\(secondsFormatted)" } else { formatted = "\(minutes):\(secondsFormatted)" } if shouldDisplayTenths { let tenths = absTimestamp * tenthsInSecond / millisInSecond - secondsInTotalHours * tenthsInSecond - minutes * secondsInMinute * tenthsInSecond - seconds * tenthsInSecond formatted += "." + String(tenths) } // Prepend a minus sign if the number is negative. return isNegative ? "-" + formatted : formatted } }
apache-2.0
33d9fc10ea91cc80c05e895b2e00f30b
33.85567
100
0.696244
4.581301
false
false
false
false
clayellis/AudioRecorder
AudioRecorderFramework/Sources/TrackMerger.swift
1
3250
// // TrackMerger.swift // AudioRecorder // // Created by Clay on 5/19/17. // Copyright © 2017 Clay Ellis. All rights reserved. // import Foundation import AVFoundation internal class TrackMerger { enum Error: Swift.Error { case urlsNotUnique case invalidOptions case destinationTrackError case mergingTrackError case exportSessionError case failed(error: Swift.Error) case cancelled } func merge(trackAt activeURL: URL, intoTrackAt masterURL: URL, writeTo outputURL: URL? = nil, deleteMergingTrack: Bool = true, inputFileType: String = AVAssetExportPresetPassthrough, outputFileType: AVFileType = .mp4, completion: @escaping ((URL?, Error?) -> ())) { do { guard activeURL != masterURL else { throw Error.urlsNotUnique } let composition = AVMutableComposition() let compositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid) let masterAsset = AVURLAsset(url: masterURL) let activeAsset = AVURLAsset(url: activeURL) guard let masterTrack = masterAsset.tracks(withMediaType: AVMediaType.audio).first else { throw Error.destinationTrackError } guard let activeTrack = activeAsset.tracks(withMediaType: AVMediaType.audio).first else { throw Error.mergingTrackError } try compositionTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, masterAsset.duration), of: masterTrack, at: kCMTimeZero) try compositionTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, activeAsset.duration), of: activeTrack, at: masterAsset.duration) guard let exportSession = AVAssetExportSession(asset: composition, presetName: inputFileType) else { throw Error.exportSessionError } exportSession.outputFileType = outputFileType if let outputURL = outputURL { exportSession.outputURL = outputURL } else { deleteExistingFile(at: masterURL) exportSession.outputURL = masterURL } if deleteMergingTrack { deleteExistingFile(at: activeURL) } exportSession.exportAsynchronously { switch exportSession.status { case .completed: completion(exportSession.outputURL, nil) case .failed: let error = exportSession.error! completion(nil, .failed(error: error)) case .cancelled: completion(nil, .cancelled) default: break } } } catch (let error as Error) { completion(nil, error) } catch { completion(nil, .failed(error: error)) } } private func deleteExistingFile(at url: URL) { let filePath = url.path let manager = FileManager.default if manager.fileExists(atPath: filePath) { try? manager.removeItem(atPath: filePath) } } }
mit
c3ccd4b894387cfc374f79ee2c41d0c8
38.621951
269
0.605109
5.460504
false
false
false
false
Mirmeca/Mirmeca
Mirmeca/PostGateway.swift
1
1102
// // PostGateway.swift // Mirmeca // // Created by solal on 2/08/2015. // Copyright (c) 2015 Mirmeca. All rights reserved. // import Alamofire import ObjectMapper public struct PostGateway: GatewayProtocol { private var url: String? public init(endpoint: String, env: String?) { let env = MirmecaEnv.sharedInstance.getEnv(env) self.url = "\(env)/\(endpoint)" } public func request(completion: (value: AnyObject?, error: NSError?) -> Void) { Alamofire.request(.GET, self.url!).responseJSON { (_, _, JSON, _) in var value: Post? var error: NSError? if (JSON != nil) { if let mappedObject = Mapper<Post>().map(JSON) { value = mappedObject } else { error = NSError(domain: self.url!, code: 303, userInfo: nil) } } else { error = NSError(domain: self.url!, code: 302, userInfo: nil) } completion(value: value, error: error) } } }
mit
631d33187e9e10b13972d6cc9f9e363f
26.55
83
0.522686
4.355731
false
false
false
false
banxi1988/Staff
Pods/BXiOSUtils/Pod/Classes/TextFactory.swift
1
924
// // AttributedTextFactory.swift // Pods // // Created by Haizhen Lee on 15/12/23. // // import UIKit public struct AttributedText{ public var textColor:UIColor public var font:UIFont public private(set) var text:String public init(text:String,font:UIFont = UIFont.systemFontOfSize(15),textColor:UIColor = UIColor.darkTextColor()){ self.text = text self.font = font self.textColor = textColor } var attributedText:NSAttributedString{ return NSAttributedString(string: text, attributes: [NSFontAttributeName:font,NSForegroundColorAttributeName:textColor]) } } public struct TextFactory{ public static func createAttributedText(textAttributes:[AttributedText]) -> NSAttributedString{ let attributedText = NSMutableAttributedString() for attr in textAttributes{ attributedText.appendAttributedString(attr.attributedText) } return attributedText } }
mit
39b1933af857ca1c4c6e8b5ad4a1ab67
21.560976
124
0.744589
4.8125
false
false
false
false
manavgabhawala/swift
test/SILGen/complete_object_init.swift
1
2012
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -emit-silgen | %FileCheck %s struct X { } class A { // CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $A): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var A } // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*A // CHECK: store [[SELF_PARAM]] to [init] [[SELF]] : $*A // CHECK: [[SELFP:%[0-9]+]] = load [take] [[SELF]] : $*A // CHECK: [[INIT:%[0-9]+]] = class_method [[SELFP]] : $A, #A.init!initializer.1 : (A.Type) -> (X) -> A, $@convention(method) (X, @owned A) -> @owned A // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT]]([[X]], [[SELFP]]) : $@convention(method) (X, @owned A) -> @owned A // CHECK: store [[INIT_RESULT]] to [init] [[SELF]] : $*A // CHECK: [[RESULT:%[0-9]+]] = load [copy] [[SELF]] : $*A // CHECK: destroy_value [[SELF_BOX]] : ${ var A } // CHECK: return [[RESULT]] : $A // CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick A.Type) -> @owned A convenience init() { // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thick A.Type): // CHECK: [[SELF:%[0-9]+]] = alloc_ref_dynamic [[SELF_META]] : $@thick A.Type, $A // CHECK: [[OTHER_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A // CHECK: [[RESULT:%[0-9]+]] = apply [[OTHER_INIT]]([[SELF]]) : $@convention(method) (@owned A) -> @owned A // CHECK: return [[RESULT]] : $A self.init(x: X()) } init(x: X) { } }
apache-2.0
acc5bb037e7af7a92b0d43b5353303cb
56.485714
152
0.540755
2.779006
false
false
false
false
marcbaldwin/AutoLayoutBuilder
AutoLayoutBuilder/LayoutRelation.swift
1
2140
import UIKit public enum LayoutDirection { case Horizontal case LeadingToTrailing case Vertical } public class LayoutRelation { var views: [UIView] var margins: [CGFloat] public init(views: UIView...) { self.views = views self.margins = [0] } } // MARK: Operators infix operator ~ { associativity left precedence 100 } public func ~(lhs: LayoutDirection, rhs: LayoutRelation) -> [NSLayoutConstraint] { return makeLayoutConstraints(lhs, views: rhs.views, margins: rhs.margins) } public func ~(lhs: LayoutDirection, rhs: Group) -> [NSLayoutConstraint] { return makeLayoutConstraints(lhs, views: rhs.views, margins: nil) } public func |(lhs: UIView, rhs: UIView) -> LayoutRelation { return LayoutRelation(views: lhs, rhs) } public func |(lhs: LayoutRelation, rhs: UIView) -> LayoutRelation { lhs.views.append(rhs) if lhs.margins.count < lhs.views.count-1 { lhs.margins.append(0) } return lhs } public func |(lhs: LayoutRelation, rhs: CGFloat) -> LayoutRelation { lhs.margins.append(rhs) return lhs } public func |(lhs: UIView, rhs: CGFloat) -> LayoutRelation { let layoutRelation = LayoutRelation(views: lhs) layoutRelation.margins[layoutRelation.margins.count-1] = rhs return layoutRelation } // MARK: Internal internal func makeLayoutConstraints(direction: LayoutDirection, views: [UIView], margins: [CGFloat]?) -> [NSLayoutConstraint] { let safeMargins = margins == nil ? Array<CGFloat>(count:views.count, repeatedValue: 0) : margins! var constraints = [NSLayoutConstraint]() for i in 1 ..< views.count { switch direction { case .Horizontal: constraints.append(NSLayoutConstraint(views[i], .Left, .Equal, views[i-1], .Right, 1, safeMargins[i-1])) case .LeadingToTrailing: constraints.append(NSLayoutConstraint(views[i], .Leading, .Equal, views[i-1], .Trailing, 1, safeMargins[i-1])) case .Vertical: constraints.append(NSLayoutConstraint(views[i], .Top, .Equal, views[i-1], .Bottom, 1, safeMargins[i-1])) } } return constraints }
mit
89e2f8444e9331d32ae676fe2d71e20f
28.328767
127
0.676168
4.030132
false
false
false
false
AsyncNinja/AsyncNinja
Sources/AsyncNinja/NetworkReachability.swift
1
12012
// // Copyright (c) 2017 Anton Mironov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom // the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // #if os(macOS) || os(iOS) || os(tvOS) import Foundation import SystemConfiguration /// **internal use only** class NetworkReachabilityManager { typealias ProducerBox = WeakBox<Producer<SCNetworkReachabilityFlags, Void>> static let `default` = NetworkReachabilityManager() let internalQueue = DispatchQueue(label: "NetworkReachabilityManager", target: .global()) var locking = makeLocking() var producerBoxesByHostName = [String: ProducerBox]() var producerBoxesByAddress = [NetworkAddress: ProducerBox]() var producerBoxesByAddressPair = [NetworkAddressPair: ProducerBox]() init() { } func channel(addressPair: NetworkAddressPair) -> Channel<SCNetworkReachabilityFlags, Void> { func fetch() -> (mustSetup: Bool, producer: Producer<SCNetworkReachabilityFlags, Void>) { if let producer = producerBoxesByAddressPair[addressPair]?.value { return (false, producer) } else { let producer = Producer<SCNetworkReachabilityFlags, Void>() producerBoxesByAddressPair[addressPair] = WeakBox(producer) return (true, producer) } } func makeNetworkReachability() -> SCNetworkReachability? { return addressPair.localAddress?.data .withUnsafeBytes { (localAddress: UnsafeRawBufferPointer) -> SCNetworkReachability? in addressPair.remoteAddress?.data .withUnsafeBytes { (remoteAddress: UnsafeRawBufferPointer) -> SCNetworkReachability? in return SCNetworkReachabilityCreateWithAddressPair( nil, localAddress.bindMemory(to: sockaddr.self).baseAddress, remoteAddress.bindMemory(to: sockaddr.self).baseAddress ) } } } return channel(fetch: fetch, makeNetworkReachability: makeNetworkReachability) } func channelForInternetConnection() -> Channel<SCNetworkReachabilityFlags, Void> { var address = sockaddr_in() address.sin_len = __uint8_t(MemoryLayout<sockaddr_in>.size) address.sin_family = sa_family_t(AF_INET) address.sin_port = 0 return channel(address: NetworkAddress(sockaddr_in: &address)) } func channel(address: NetworkAddress) -> Channel<SCNetworkReachabilityFlags, Void> { func fetch() -> (mustSetup: Bool, producer: Producer<SCNetworkReachabilityFlags, Void>) { if let producer = producerBoxesByAddress[address]?.value { return (false, producer) } else { let producer = Producer<SCNetworkReachabilityFlags, Void>() producerBoxesByAddress[address] = WeakBox(producer) return (true, producer) } } func makeNetworkReachability() -> SCNetworkReachability? { return address.data.withUnsafeBytes { ($0.bindMemory(to: sockaddr.self).baseAddress) .flatMap { SCNetworkReachabilityCreateWithAddress(nil, $0) } } } return channel(fetch: fetch, makeNetworkReachability: makeNetworkReachability) } func channel(hostName: String) -> Channel<SCNetworkReachabilityFlags, Void> { func fetch() -> (mustSetup: Bool, producer: Producer<SCNetworkReachabilityFlags, Void>) { if let producer = producerBoxesByHostName[hostName]?.value { return (false, producer) } else { let producer = Producer<SCNetworkReachabilityFlags, Void>() producerBoxesByHostName[hostName] = WeakBox(producer) return (true, producer) } } func makeNetworkReachability() -> SCNetworkReachability? { return hostName.withCString { SCNetworkReachabilityCreateWithName(nil, $0) } } return channel(fetch: fetch, makeNetworkReachability: makeNetworkReachability) } private func channel( fetch: () -> (mustSetup: Bool, producer: Producer<SCNetworkReachabilityFlags, Void>), makeNetworkReachability: () -> SCNetworkReachability? ) -> Channel<SCNetworkReachabilityFlags, Void> { let (mustSetup, producer): (Bool, Producer<SCNetworkReachabilityFlags, Void>) = locking.locker(fetch) if mustSetup { if let networkReachability = makeNetworkReachability() { setup(producer: producer, networkReachability: networkReachability) } else { producer.fail(AsyncNinjaError.networkReachabilityDetectionFailed) } } return producer } private func setup( producer: Producer<SCNetworkReachabilityFlags, Void>, networkReachability: SCNetworkReachability) { let queue = internalQueue queue.async { var flags = SCNetworkReachabilityFlags() guard SCNetworkReachabilityGetFlags(networkReachability, &flags) else { producer.fail(AsyncNinjaError.networkReachabilityDetectionFailed) return } producer.update(flags) let unmanagedProducerBox = Unmanaged.passRetained(WeakBox(producer)) var context = SCNetworkReachabilityContext( version: 0, info: unmanagedProducerBox.toOpaque(), retain: { return UnsafeRawPointer(Unmanaged<ProducerBox>.fromOpaque($0).retain().toOpaque()) }, release: { Unmanaged<ProducerBox>.fromOpaque($0).release() }, copyDescription: nil) if SCNetworkReachabilitySetCallback(networkReachability, { (_, flags, info) in let unmanagedProducerBox = Unmanaged<ProducerBox>.fromOpaque(info!) unmanagedProducerBox.retain().takeUnretainedValue().value?.update(flags) unmanagedProducerBox.release() }, &context), SCNetworkReachabilitySetDispatchQueue(networkReachability, queue) { producer._asyncNinja_notifyFinalization { SCNetworkReachabilitySetCallback(networkReachability, nil, nil) } } else { producer.fail(AsyncNinjaError.networkReachabilityDetectionFailed) } unmanagedProducerBox.release() } } } // MARK: - /// Wraps sockaddr and it's derivetives into a convenient swift structure public struct NetworkAddress: Hashable { var data: Data /// Reference to a stored sockaddr public var sockaddrRef: UnsafePointer<sockaddr>? { return data.withUnsafeBytes { $0.bindMemory(to: sockaddr.self).baseAddress } } /// Initializes NetworkAddress with any sockaddr /// /// - Parameter sockaddr: to initialize NetworkAddress with public init(sockaddr: UnsafePointer<sockaddr>) { self.data = Data(bytes: sockaddr, count: Int(sockaddr.pointee.sa_len)) } /// Initializes NetworkAddress with any sockaddr_in /// /// - Parameter sockaddr_in: to initialize NetworkAddress with public init(sockaddr_in: UnsafePointer<sockaddr_in>) { self = sockaddr_in.withMemoryRebound(to: sockaddr.self, capacity: 1) { NetworkAddress.init(sockaddr: $0) } } /// is equal operator public static func == (lhs: NetworkAddress, rhs: NetworkAddress) -> Bool { return lhs.data == rhs.data } } // MARK: - /// **internal use only** struct NetworkAddressPair: Hashable { var localAddress: NetworkAddress? var remoteAddress: NetworkAddress? static func == (lhs: NetworkAddressPair, rhs: NetworkAddressPair) -> Bool { return lhs.localAddress == rhs.localAddress && lhs.remoteAddress == rhs.remoteAddress } } // MARK: - extension SCNetworkReachabilityFlags: CustomStringConvertible { /// Commonly known description of the flags written on Swift public var description: String { var spec = [(SCNetworkReachabilityFlags, String)]() #if os(iOS) spec.append((.isWWAN, "W")) #endif spec += [ (.reachable, "R"), (.transientConnection, "t"), (.connectionRequired, "c"), (.connectionOnTraffic, "C"), (.interventionRequired, "i"), (.connectionOnDemand, "D"), (.isLocalAddress, "l"), (.isDirect, "d") ] return spec .map { let (flag, description) = $0 return contains(flag) ? description : "-" } .joined() } /// Returns true if network is reachable unconditionally public var isReachable: Bool { return contains(.reachable) && !contains(.connectionRequired) } /// Returns true if network is not reachable but it is possible to esteblish connection public var isConditionallyReachable: Bool { return !contains(.reachable) && contains(.connectionRequired) && (contains(.connectionOnTraffic) || contains(.connectionOnDemand)) && !contains(.interventionRequired) } #if os(iOS) /// Returns true if network is reachable via WWAN public var isReachableViaWWAN: Bool { return contains(.isWWAN) } #endif } // MARK: - public functions /// Makes or returns cached channel that reports of reachability changes /// /// - Parameters: /// - localAddress: local address associated with a network connection. /// If nil, only the remote address is of interest /// - remoteAddress: remote address associated with a network connection. /// If nil, only the local address is of interest /// - Returns: channel that reports of reachability changes public func networkReachability( localAddress: NetworkAddress?, remoteAddress: NetworkAddress? ) -> Channel<SCNetworkReachabilityFlags, Void> { let addressPair = NetworkAddressPair(localAddress: localAddress, remoteAddress: remoteAddress) return NetworkReachabilityManager.default.channel(addressPair: addressPair) } /// Makes or returns cached channel that reports of reachability changes /// The channel will report of a internet connection availibility. /// /// - Returns: channel that reports of reachability changes public func networkReachabilityForInternetConnection() -> Channel<SCNetworkReachabilityFlags, Void> { return NetworkReachabilityManager.default.channelForInternetConnection() } /// Makes or returns cached channel that reports of reachability changes /// /// - Parameters: /// - address: associated with a network connection. /// - Returns: channel that reports of reachability changes public func networkReachability(address: NetworkAddress) -> Channel<SCNetworkReachabilityFlags, Void> { return NetworkReachabilityManager.default.channel(address: address) } /// Makes or returns cached channel that reports of reachability changes /// /// - Parameter hostName: associated with a network connection. /// - Returns: channel that reports of reachability changes public func networkReachability(hostName: String) -> Channel<SCNetworkReachabilityFlags, Void> { return NetworkReachabilityManager.default.channel(hostName: hostName) } #endif
mit
c8378d24896c99ddde7b3f3243ff43cc
37.623794
107
0.683899
5.345794
false
false
false
false
googlearchive/cannonball-ios
Cannonball/AboutViewController.swift
1
3287
// // Copyright (C) 2018 Google, Inc. and other contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Crashlytics import Firebase class AboutViewController: UIViewController { // MARK: References @IBOutlet weak var signOutButton: UIButton! var logoView: UIImageView! // MARK: View Life Cycle override func viewDidLoad() { // Add the logo view to the top (not in the navigation bar title to have it bigger). logoView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) logoView.image = UIImage(named: "Logo")?.withRenderingMode(.alwaysTemplate) logoView.tintColor = UIColor.cannonballGreenColor() logoView.frame.origin.x = (view.frame.size.width - logoView.frame.size.width) / 2 logoView.frame.origin.y = 8 // Add the logo view to the navigation controller and bring it to the front. navigationController?.view.addSubview(logoView) navigationController?.view.bringSubview(toFront: logoView) // Customize the navigation bar. let titleDict: NSDictionary = [NSAttributedStringKey.foregroundColor: UIColor.cannonballGreenColor()] navigationController?.navigationBar.titleTextAttributes = titleDict as? [NSAttributedStringKey : Any] navigationController?.navigationBar.tintColor = UIColor.cannonballGreenColor() navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) navigationController?.navigationBar.shadowImage = UIImage() // Log Analytics custom event. Analytics.logEvent(AnalyticsEventSelectContent, parameters: [AnalyticsParameterItemID: "about"]) } // MARK: IBActions @IBAction func dismiss(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } @IBAction func learnMore(_ sender: AnyObject) { UIApplication.shared.openURL(URL(string: "https://github.com/Firebase/cannonball-ios/")!) } @IBAction func signOut(_ sender: AnyObject) { // Remove any Firebase Phone Auth local sessions for this app. if Auth.auth().currentUser != nil { do { try Auth.auth().signOut() } catch let signOutError as NSError { print ("Error signing out: %@", signOutError) } } // Remove user information for any upcoming crashes in Crashlytics. Crashlytics.sharedInstance().setUserIdentifier(nil) Crashlytics.sharedInstance().setUserName(nil) // Log Analytics custom event. Analytics.logEvent("logout", parameters: nil) // Present the Sign In again. navigationController!.popToRootViewController(animated: true) } }
apache-2.0
e32eabe45d12ad5d280450dfb968f28a
37.22093
109
0.683298
5.010671
false
false
false
false
RedRoster/rr-ios
RedRoster/Model/Notification.swift
1
431
// // Notification.swift // RedRoster // // Created by Daniel Li on 5/30/16. // Copyright © 2016 dantheli. All rights reserved. // import Foundation import UIKit struct Notification { var content: String var image: UIImage? var action: String? init(content: String, image: UIImage? = nil, action: String? = nil) { self.content = content self.image = image self.action = action } }
apache-2.0
75ba0a2979605fb96ea79d74774af2a4
19.52381
73
0.637209
3.644068
false
false
false
false
teambox/RealmResultsController
Source/RealmNotification.swift
2
661
// // RealmNotification.swift // redbooth-ios-sdk // // Created by Pol Quintana on 4/8/15. // Copyright © 2015 Redbooth Inc. // import Foundation import RealmSwift class RealmNotification { static let sharedInstance = RealmNotification() var loggers: [RealmLogger] = [] static func logger(for realm: Realm) -> RealmLogger { let logger = RealmNotification.sharedInstance.loggers.filter {$0.realm == realm} if let log = logger.first { return log } let newLogger = RealmLogger(realm: realm) RealmNotification.sharedInstance.loggers.append(newLogger) return newLogger } }
mit
dc80365866deca776e502d54e31b857d
24.384615
88
0.657576
4.342105
false
false
false
false
tuanan94/FRadio-ios
SwiftRadio/Libraries/Spring/AsyncButton.swift
1
2103
// The MIT License (MIT) // // Copyright (c) 2015 James Tang ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class AsyncButton: UIButton { private var imageURL = [UInt:NSURL]() private var placeholderImage = [UInt:UIImage]() @objc public func setImageURL(url: NSURL?, placeholderImage placeholder:UIImage?, forState state:UIControlState) { imageURL[state.rawValue] = url placeholderImage[state.rawValue] = placeholder if let urlString = url?.absoluteString { ImageLoader.sharedLoader.imageForUrl(urlString: urlString) { [weak self] image, url in if let strongSelf = self { DispatchQueue.main.async(execute: { () -> Void in if strongSelf.imageURL[state.rawValue]?.absoluteString == url { strongSelf.setImage(image, for: state) } }) } } } } }
mit
b0a07e4ca6ed540607bdb9f3cec753d0
40.235294
118
0.654303
4.971631
false
false
false
false
likumb/DouBanBookSDK
DouBanBookSDK/DouBanBookSDK/DBAnnotation.swift
1
604
// // DBAnnotation.swift // DouBanBookSDK // // Created by  李俊 on 15/8/31. // Copyright (c) 2015年  李俊. All rights reserved. // import UIKit class DBAnnotation: NSObject { var content: String? var page: String? var chapter: String? var id: String? var bookId: String? convenience init(content: String, page: String?, chapter: String?,bookid: String? ,id: String?){ self.init() self.content = content self.page = page self.chapter = chapter self.bookId = bookid self.id = id } }
mit
2f98ac99d8814708c65c04a602b7beea
18.096774
100
0.574324
3.677019
false
false
false
false
ReiVerdugo/uikit-fundamentals
Click Counter/Click Counter/ViewController.swift
1
2796
// // ViewController.swift // Click Counter // // Created by devstn5 on 2016-09-28. // Copyright © 2016 Rverdugo. All rights reserved. // import UIKit class ViewController: UIViewController { var label : UILabel! var count = 0 override func viewDidLoad() { super.viewDidLoad() // Label let label = UILabel() label.frame = CGRect(x: Int(view.center.x), y: Int(view.center.y), width: 60, height: 60) label.textAlignment = .center label.center.x = view.center.x label.center.y = view.center.y label.text = "0" self.label = label view.addSubview(label) // Increment button let button = UIButton() button.frame = CGRect(x: Int(view.center.x), y: Int(view.center.y) + 40, width: 70, height: 60) button.center.x = view.center.x - 50 button.center.y = view.center.y + 40 button.setTitle("Up", for: .normal) button.setTitleColor(UIColor.blue, for: .normal) button.addTarget(self, action: #selector(ViewController.incrementCount), for: .touchUpInside) view.addSubview(button) // Decrement button let button2 = UIButton() button2.frame = CGRect(x: Int(view.center.x), y: Int(view.center.y) + 40, width: 70, height: 60) button2.center.x = view.center.x + 50 button2.center.y = button.center.y button2.setTitle("Down", for: .normal) button2.setTitleColor(UIColor.blue, for: .normal) button2.addTarget(self, action: #selector(ViewController.decrementCount), for: .touchUpInside) view.addSubview(button2) // Change background color button let button3 = UIButton() button3.frame = CGRect(x: Int(view.center.x), y: Int(view.center.y) + 40, width: 70, height: 60) button3.center.x = view.center.x button3.center.y = button.center.y + 50 button3.setTitle("Color!", for: .normal) button3.setTitleColor(UIColor.blue, for: .normal) button3.addTarget(self, action: #selector(ViewController.changeColor), for: .touchUpInside) view.addSubview(button3) } func incrementCount () { self.count += 1 self.label.text = "\(self.count)" } func decrementCount () { self.count -= 1 self.label.text = "\(self.count)" } func changeColor () { self.view.backgroundColor = 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) } }
mit
441558f9d115aa1614adb285e4f1bb7f
32.27381
104
0.606798
3.87656
false
false
false
false
lieonCX/Live
Live/View/Home/SearchHistoryCell.swift
1
1769
// // SearchHistoryCell.swift // Live // // Created by fanfans on 2017/7/18. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import UIKit class SearchHistoryCell: UITableViewCell, ViewNameReusable { fileprivate lazy var bgView: UIView = { let view: UIView = UIView() view.backgroundColor = .white return view }() lazy var nameLable: UILabel = { let nameLable: UILabel = UILabel() nameLable.textAlignment = .left nameLable.textColor = UIColor(hex: 0x222222) nameLable.font = UIFont.systemFont(ofSize: 14) return nameLable }() fileprivate lazy var line: UIView = { let line: UIView = UIView() line.backgroundColor = UIColor(hex: 0xe5e5e5) return line }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(bgView) contentView.addSubview(nameLable) bgView.addSubview(line) bgView.snp.makeConstraints { (maker) in maker.top.equalTo(0) maker.left.equalTo(0) maker.right.equalTo(0) maker.bottom.equalTo(0) } nameLable.snp.makeConstraints { (maker) in maker.left.equalTo(bgView.snp.left).offset(12) maker.centerY.equalTo(bgView.snp.centerY) } line.snp.makeConstraints { (maker) in maker.left.equalTo(nameLable.snp.left) maker.height.equalTo(0.5) maker.bottom.equalTo(0) maker.right.equalTo(0) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
4c5d3c2deb628a81438c8cde21863265
29.982456
74
0.61325
4.339066
false
false
false
false
SirWellington/sir-wellington-mall
SirWellingtonMall/SirWellingtonMall/Extensions.swift
1
5494
// // Extensions.swift // SirWellingtonMall // // Created by Juan Wellington Moreno on 5/14/16. // Copyright © 2016 Sir Wellington. All rights reserved. // import Foundation import MCSwipeTableViewCell import MobileCoreServices import UIKit extension Int { func isEven() -> Bool { return self % 2 == 0 } func isOdd() -> Bool { return !self.isEven() } static func random(from begin: Int, to end: Int) -> Int { guard begin != end else { return begin } guard begin < end else { return 0 } let difference = end - begin let random = arc4random_uniform(UInt32(difference)) let result = begin + Int(random) if result >= end { return end - 1 } else { return result } } } //MARK: UIViewController //Hides the Navigation Bar Lip extension UIViewController { func hideNavigationBarShadow() { let emptyImage = UIImage() self.navigationController?.navigationBar.shadowImage = emptyImage self.navigationController?.navigationBar.setBackgroundImage(emptyImage, forBarMetrics: UIBarMetrics.Default) } var isiPhone: Bool { return UI_USER_INTERFACE_IDIOM() == .Phone } var isiPad: Bool { return UI_USER_INTERFACE_IDIOM() == .Pad } } //MARK: String Operations public extension String { public var length: Int { return self.characters.count } public func toURL() -> NSURL? { return NSURL(string: self) } } //MARK: Arrays extension Array { func selectOne() -> Element? { guard count > 0 else { return nil } var index = Int.random(from: 0, to: count) if index >= count { index -= 1 } return self[index] } } // MARK: UILabel extension UILabel { func readjustLabelFontSize() { let rect = self.frame self.adjustFontSizeToFitRect(rect, minFontSize: 5, maxFontSize: 100) } func adjustFontSizeToFitRect(rect: CGRect, minFontSize: Int = 5, maxFontSize: Int = 200) { guard let text = self.text else { return } frame = rect var right = maxFontSize var left = minFontSize let constraintSize = CGSize(width: rect.width, height: CGFloat.max) while (left <= right) { let currentSize = (left + right) / 2 font = font.fontWithSize(CGFloat(currentSize)) let text = NSAttributedString(string: text, attributes: [NSFontAttributeName: font]) let textRect = text.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, context: nil) let labelSize = textRect.size if labelSize.height < frame.height && labelSize.height >= frame.height - 10 && labelSize.width < frame.width && labelSize.width >= frame.width - 10 { break } else if labelSize.height > frame.height || labelSize.width > frame.width { right = currentSize - 1 } else { left = currentSize + 1 } } } } //MARK: Add Image Picker Capability extension UIViewController { func prepareImagePicker() -> UIImagePickerController? { guard UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) else { return nil } let picker = UIImagePickerController() picker.sourceType = .PhotoLibrary picker.mediaTypes = [kUTTypeImage as String] picker.allowsEditing = true return picker } } //MARK: UITableView Controllers extension UITableViewController { func reloadSection(section: Int, animation: UITableViewRowAnimation = .Automatic) { let section = NSIndexSet(index: section) self.tableView?.reloadSections(section, withRowAnimation: animation) } } extension UITableViewController { var emptyCell: UITableViewCell { return UITableViewCell() } private var trashIcon: UIImage? { return UIImage(named: "Trash") } private var checkMarkIcon: UIImage? { return UIImage(named: "Checkmark") } typealias OnSwipe = (NSIndexPath) -> Void func addSwipeToDelete(toCell cell: MCSwipeTableViewCell, atIndexPath path: NSIndexPath, onSwipe: OnSwipe) { cell.defaultColor = Colors.PRIMARY let view = UIImageView() if let icon = trashIcon { view.image = icon } view.contentMode = .Center cell.setSwipeGestureWithView(view, color: UIColor.redColor(), mode: .Exit, state: .State3) { [weak self] cell, state, mode in guard let path = self?.tableView?.indexPathForCell(cell) else { return } onSwipe(path) } cell.firstTrigger = 0.35 } func addSwipeToToggle(toCell cell: MCSwipeTableViewCell, atIndexPath path: NSIndexPath, onSwipe: OnSwipe) { cell.defaultColor = Colors.PRIMARY let view = UIImageView() if let icon = checkMarkIcon { view.image = icon } view.contentMode = .Center cell.setSwipeGestureWithView(view, color: Colors.BLUE, mode: .Switch, state: .State1) { [weak self] cell, state, mode in guard let path = self?.tableView?.indexPathForCell(cell) else { return } onSwipe(path) } cell.firstTrigger = 0.35 } }
mit
110b3c08593b01a8fac939e8618ce9dc
24.910377
161
0.606954
4.719072
false
false
false
false
131e55/KKPlayerViewController
Sources/KKPlayerViewController.swift
1
19278
// // KKPlayerViewController.swift // KKPlayerViewController // // Created by Keisuke Kawamura a.k.a. 131e55 on 2016/08/23. // // The MIT License (MIT) // // Copyright (c) 2016 Keisuke Kawamura ( https://twitter.com/131e55 ) // // 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 AVFoundation import AVKit import MediaPlayer // MARK: Public enumerations /// PlayerStatus is a wrapper of [AVPlayerStatus](https://developer.apple.com/reference/avfoundation/avplayerstatus). @objc public enum PlayerStatus: Int, CustomStringConvertible { case unknown case readyToPlay case failed public var description: String { switch self { case .unknown: return "unknown" case .readyToPlay: return "readyToPlay" case .failed: return "failed" } } } /** PlaybackStatus indicates playback status of current item. unstarted: Not yet started playback or Not set any player item. playing: The current player item is playing. paused: The current player item is paused. ended: The current player item is ended. stalled: The player can not continue to playback because bufferred data is not enough. */ @objc public enum PlaybackStatus: Int, CustomStringConvertible { case unstarted case playing case paused case ended case stalled public var description: String { switch self { case .unstarted: return "unstarted" case .playing: return "playing" case .paused: return "paused" case .ended: return "ended" case .stalled: return "stalled" } } } // MARK: - Public KKPlayerViewControllerDelegate protocol @objc public protocol KKPlayerViewControllerDelegate: AVPlayerViewControllerDelegate { func playerViewController(_ playerViewController: KKPlayerViewController, didChangePlayerStatus status: PlayerStatus) func playerViewController(_ playerViewController: KKPlayerViewController, didChangePlaybackStatus status: PlaybackStatus) func playerViewControllerDidReadyForDisplay(_ playerViewController: KKPlayerViewController) @objc optional func playerViewController(_ playerViewController: KKPlayerViewController, didChangeCurrentTime time: Double) } // MARK: - Public KKPlayerViewController class open class KKPlayerViewController: UIViewController { // MARK: Public properties private(set) open var playerStatus: PlayerStatus = .unknown { didSet { if self.playerStatus != oldValue { self.delegate?.playerViewController(self, didChangePlayerStatus: self.playerStatus) } } } private(set) open var playbackStatus: PlaybackStatus = .unstarted { didSet { if self.playbackStatus != oldValue { self.delegate?.playerViewController(self, didChangePlaybackStatus: self.playbackStatus) } } } open var readyForDisplay: Bool { return self.playerView.playerLayer.isReadyForDisplay } open var videoRect: CGRect { return self.playerView.playerLayer.videoRect } open var videoGravity: String { get { return self.playerView.playerLayer.videoGravity } set { self.playerView.playerLayer.videoGravity = newValue } } open var videoNaturalSize: CGSize { let track = self.player?.currentItem?.asset.tracks(withMediaType: AVMediaTypeVideo).first return track?.naturalSize ?? CGSize.zero } open var duration: Double { let duration = CMTimeGetSeconds(self.player?.currentItem?.duration ?? kCMTimeZero) return duration.isFinite ? duration : 0 } open var currentTime: Double { let currentTime = CMTimeGetSeconds(self.player?.currentTime() ?? kCMTimeZero) return currentTime.isFinite ? currentTime : 0 } open var isMuted: Bool = false { didSet { self.player?.isMuted = self.isMuted } } open var volume: Float = 1.0 { didSet { self.player?.volume = self.volume } } /// Specifies whether the player automatically repeats if playback is ended. open var repeatPlayback: Bool = false open var allowsPictureInPicturePlayback = true open var minimumBufferDuration: Double = 5.0 /// The interval of calling playerViewControllerDidChangeCurrentTime delegate method. /// Specify the value as milliseconds. open var intervalOfTimeObservation: Int = 500 open weak var delegate: KKPlayerViewControllerDelegate? // MARK: Private properties private var asset: AVAsset? private var playerItem: AVPlayerItem? private var player: AVPlayer? { didSet { self.player?.isMuted = self.isMuted self.player?.volume = self.volume } } private var playerView: AVPlayerView { return self.view as! AVPlayerView } private var timeObserver: Any? private var _pictureInPictureController: AnyObject? @available(iOS 9.0, *) private var pictureInPictureController: AVPictureInPictureController? { get { return self._pictureInPictureController as? AVPictureInPictureController } set { self._pictureInPictureController = newValue } } private var observationContext = 0 // MARK: Initialization methods public convenience init() { self.init(nibName: nil, bundle: nil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.commonInit() } private func commonInit() { self.addApplicationNotificationObservers() } deinit { self.playerView.playerLayer.removeObserver( self, forKeyPath: playerLayerReadyForDisplayKey, context: &self.observationContext ) self.clear() self.removeApplicationNotificationObservers() } // MARK: UIViewController open override func loadView() { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: "\(type(of: self))", bundle: bundle) self.view = nib.instantiate(withOwner: self, options: nil).first as! AVPlayerView self.playerView.playerLayer.addObserver( self, forKeyPath: playerLayerReadyForDisplayKey, options: [.initial, .new], context: &self.observationContext ) } // MARK: Public methods open func clear() { self.asset?.cancelLoading() self.asset = nil if let playerItem = self.playerItem { playerItem.cancelPendingSeeks() self.removeObservers(from: playerItem) } self.playerItem = nil if let player = self.player { player.cancelPendingPrerolls() self.removeObservers(from: player) } self.playerView.player = nil self.player = nil if #available(iOS 9.0, *) { self.pictureInPictureController = nil } self.playerStatus = .unknown self.playbackStatus = .unstarted } open func load(url: URL, from seconds: Double = 0) { self.setupAsset(url: url, from: seconds) } open func play(from seconds: Double? = nil) { guard let player = self.player else { return } if let seconds = seconds { self.seek(to: seconds) } player.play() } open func pause() { guard let player = self.player else { return } player.pause() } open func seek(to seconds: Double) { guard let player = self.player else { return } let time = CMTimeMakeWithSeconds(seconds, 1) player.seek(to: time) } // MARK: Private methods private func setupAsset(url: URL, from seconds: Double = 0) { DispatchQueue.global().async { self.asset = AVURLAsset(url: url, options: nil) let keys = ["playable", "duration"] self.asset!.loadValuesAsynchronously( forKeys: keys, completionHandler: { [weak self] in guard let `self` = self, let asset = self.asset else { return } var error: NSError? let failed = keys.filter { asset.statusOfValue(forKey: $0, error: &error) == .failed } guard failed.isEmpty else { self.playerStatus = .failed return } self.setupPlayerItem(asset: asset, from: seconds) } ) } } private func setupPlayerItem(asset: AVAsset, from seconds: Double = 0) { DispatchQueue.main.async { if let playerItem = self.playerItem { self.removeObservers(from: playerItem) } self.playerItem = AVPlayerItem(asset: asset) let time = CMTimeMakeWithSeconds(seconds, 1) self.playerItem!.seek(to: time) self.addObservers(to: self.playerItem!) self.setupPlayer(playerItem: self.playerItem!) } } private func setupPlayer(playerItem: AVPlayerItem) { DispatchQueue.main.async { if let player = self.player { player.replaceCurrentItem(with: playerItem) } else { self.player = AVPlayer(playerItem: playerItem) self.addObservers(to: self.player!) self.playerView.player = self.player if #available(iOS 9.0, *) { self.setupPictureInPictureController(playerLayer: self.playerView.playerLayer) } } } } @available (iOS 9.0, *) private func setupPictureInPictureController(playerLayer: AVPlayerLayer) { guard AVPictureInPictureController.isPictureInPictureSupported() && self.allowsPictureInPicturePlayback else { return } self.pictureInPictureController = AVPictureInPictureController(playerLayer: playerLayer) } // MARK: KVO private func addObservers(to playerItem: AVPlayerItem) { playerItem.addObserver( self, forKeyPath: playerItemLoadedTimeRangesKey, options: ([.initial, .new]), context: &self.observationContext ) NotificationCenter.default.addObserver( self, selector: #selector(self.playerItemDidPlayToEndTime(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem ) NotificationCenter.default.addObserver( self, selector: #selector(self.playerItemPlaybackStalled(_:)), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: playerItem ) } private func removeObservers(from playerItem: AVPlayerItem) { playerItem.removeObserver( self, forKeyPath: playerItemLoadedTimeRangesKey, context: &self.observationContext ) NotificationCenter.default.removeObserver( self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem ) NotificationCenter.default.removeObserver( self, name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: playerItem ) } private func addObservers(to player: AVPlayer) { player.addObserver( self, forKeyPath: playerStatusKey, options: ([.initial, .new]), context: &self.observationContext ) player.addObserver( self, forKeyPath: playerRateKey, options: ([.initial, .new]), context: &self.observationContext ) let interval = CMTimeMake(1, 1000 / Int32(self.intervalOfTimeObservation)) self.timeObserver = player.addPeriodicTimeObserver( forInterval: interval, queue: DispatchQueue.main, using: { [weak self] time in guard let `self` = self else { return } let currentTime = CMTimeGetSeconds(time) self.delegate?.playerViewController?(self, didChangeCurrentTime: currentTime) } ) } private func removeObservers(from player: AVPlayer) { player.removeObserver( self, forKeyPath: playerStatusKey, context: &self.observationContext ) player.removeObserver( self, forKeyPath: playerRateKey, context: &self.observationContext ) player.removeTimeObserver(self.timeObserver!) self.timeObserver = nil } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &self.observationContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } guard let keyPath = keyPath else { fatalError() } switch keyPath { case playerItemLoadedTimeRangesKey: guard let playerItem = object as? AVPlayerItem, self.playerItem == playerItem else { fatalError() } if let timeRange = playerItem.loadedTimeRanges.first?.timeRangeValue { let duration = CMTimeGetSeconds(timeRange.duration) if self.playbackStatus == .stalled && duration >= self.minimumBufferDuration { self.play() } } case playerStatusKey: guard let player = object as? AVPlayer, self.player == player else { fatalError() } self.playerStatus = PlayerStatus(rawValue: player.status.rawValue)! case playerRateKey: guard let player = object as? AVPlayer, self.player == player else { fatalError() } if fabs(player.rate) > 0 { self.playbackStatus = .playing } else if let currentItem = player.currentItem, self.playbackStatus != .unstarted { if !currentItem.isPlaybackLikelyToKeepUp { // Do nothing. PlaybackStatus will be Stalled. } else if player.currentTime() < currentItem.duration { self.playbackStatus = .paused } else { // Do nothing. PlaybackStatus will be Ended. } } else { self.playbackStatus = .unstarted } case playerLayerReadyForDisplayKey: guard let playerLayer = object as? AVPlayerLayer, self.playerView.playerLayer == playerLayer else { fatalError() } if playerLayer.isReadyForDisplay { self.delegate?.playerViewControllerDidReadyForDisplay(self) } default: fatalError() } } // MARK: AVPlayerItem notifications open func playerItemDidPlayToEndTime(_ notification: Notification) { self.playbackStatus = .ended if self.repeatPlayback { self.play(from: 0) } } open func playerItemPlaybackStalled(_ notification: Notification) { self.playbackStatus = .stalled } // MARK: UIApplication notifications private func addApplicationNotificationObservers() { NotificationCenter.default.addObserver( self, selector: #selector(applicationDidEnterBackground(_:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(applicationWillEnterForeground(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil ) } private func removeApplicationNotificationObservers() { NotificationCenter.default.removeObserver( self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil ) NotificationCenter.default.removeObserver( self, name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil ) } func applicationDidEnterBackground(_ notification: Notification) { func remove() { self.playerView.player = nil } if #available(iOS 9.0, *) { if AVPictureInPictureController.isPictureInPictureSupported() && self.allowsPictureInPicturePlayback { // Do nothing. Keep the reference from AVPlayerViewController for Picture in Picture. } else { remove() } } else { remove() } } func applicationWillEnterForeground(_ notification: Notification) { // Refer again for case of background playback self.playerView.player = self.player } } // MARK: Private KVO keys private let playerItemLoadedTimeRangesKey = "loadedTimeRanges" private let playerStatusKey = "status" private let playerRateKey = "rate" private let playerLayerReadyForDisplayKey = "readyForDisplay"
mit
b78176d467649bb9327a5e4fa3afc1ae
25.228571
156
0.604731
5.511149
false
false
false
false
jingyaokuku/JYweibo05
JYSinaWeibo/JYSinaWeibo/Classse/Model/JYStatus.swift
1
7095
// // JYStatus.swift // JYSinaWeibo // // Created by apple on 15/11/2. // Copyright © 2015年 Jingyao. All rights reserved. // import UIKit import SDWebImage class JYStatus: NSObject { ///微博创建的时间 var created_at: String? /// 字符串型的微博ID var idstr: String? /// 微博信息内容 var text: String? /// 微博来源 var source: String? /// 微博的配图 var pic_urls: [[String: AnyObject]]?{ didSet { //// 当字典转模型,给pic_urls赋值的时候,将数组里面的url转成NSURL赋值给storePictureURLs //判断有没有图片 let count = pic_urls?.count ?? 0 //如果没有图片,直接返回 if count == 0 { return } //创建storePictureURLs storePictureURLs = [NSURL]() for dict in pic_urls!{ if let urlString = dict["thumbnail_pic"] as? String{ //有URL地址 storePictureURLs?.append(NSURL(string: urlString)!) } } } } ///返回微博的配图对应URL的数组 var storePictureURLs:[NSURL]? /// 如果是原创微博,就返回原创微博的图片,如果是转发微博就返回被转发微博的图片 /// 计算型属性, var pictureURLs: [NSURL]? { get { // 判断: // 1.原创微博: 返回 storePictureURLs // 2.转发微博: 返回 retweeted_status.storePictureURLs return retweeted_status == nil ? storePictureURLs : retweeted_status!.storePictureURLs } } /// 用户模型 var user: JYUser? /// 缓存行高 var rowHeight: CGFloat? ///被转发的微博 var retweeted_status:JYStatus? func cellID() -> String { // retweeted_status == nil表示原创微博 return retweeted_status == nil ? JYStatusCellIdentifier.NormalCell.rawValue : JYStatusCellIdentifier.ForwardCell.rawValue } /// 字典转模型 init(dict: [String: AnyObject]) { super.init() // 回调用 setValue(value: AnyObject?, forKey key: String) 赋值每个属性 setValuesForKeysWithDictionary(dict) } //kvc赋值每一个属性时都会调用 override func setValue(value: AnyObject?, forKey key: String) { //判断user赋值时,自己字典转模型 if key == "user"{ //使用值绑定转换字典类型 if let dict = value as?[String:AnyObject]{ //字典转模型 //赋值 user = JYUser(dict: dict) //一定要记得return return } }else if key == "retweeted_status"{ if let dict = value as? [String :AnyObject] { //字典装模型 //被转发的微博 retweeted_status = JYStatus (dict: dict ) } return } return super.setValue(value, forKey: key) } //字典的key在模型中找不到对应的属性时候 override func setValue(value: AnyObject?, forUndefinedKey key: String) {} override var description: String { let p = ["created_at", "idstr", "text", "source", "pic_urls", "user"] // 数组里面的每个元素,找到对应的value,拼接成字典 // \n 换行, \t table return "\n\t微博模型:\(dictionaryWithValuesForKeys(p))" } ///加载微博数据 ///没有模型对象就能加载数据 所以用类方法 class func loadStatus(finished:(statuses:[JYStatus]?,error:NSError?) ->()){ JYNetworkTools.sharedInstance.loadStautus {(result ,error) ->() in if error != nil { //通知调用者 finished(statuses: nil , error: error) return } if let array = result?["statuses"] as? [[String: AnyObject]] { // 有数据 // 创建模型数组 var statuses = [JYStatus]() for dict in array { // 字典转模型 statuses.append(JYStatus(dict: dict)) } // 字典转模型完成 // 缓存图片,通知调用者 // finished(statuses: statuses, error: nil) self.cacheWebImage(statuses, finished:finished) } else { // 没有数据,通知调用者 finished(statuses: nil, error: nil) } } } class func cacheWebImage(statuses:[JYStatus]?,finished:(statuses:[JYStatus]?,error:NSError?)->()){ //创建任务组 let group = dispatch_group_create() //判断是否有模型 guard let list = statuses else { //没有模型 return } //记录缓存图片的大小 var length = 0 //遍历模型 for status in list { //如果没有图片需要下载,接着遍历下一个 let count = status.pictureURLs?.count ?? 0 if count == 0 { //没有图片遍历下一个模型 continue } //判断是否有图片需要下载 if let urls = status.pictureURLs{ //有需要缓存的图片 if urls.count == 1{ let url = urls[0] //缓存图片 //在缓存之时放到任务组里面 dispatch_group_enter(group) SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil , completed: { (image , error , _ , _ ,_ ) -> Void in //离开组 dispatch_group_leave(group) //判断有没有错误 if error != nil { print("下载图片出错:\(url)") return } //没有出错 print("下载图片完成:\(url )") //记录下载图片的大小 if let data = UIImagePNGRepresentation(image){ length += data.length } }) } } } //所有图片下载完,再通知调用者 dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in //通知调用者,已经有数据了 finished(statuses: statuses, error: nil ) } } }
apache-2.0
db03319e3d4f065e766153c9ff4228b9
25.486957
183
0.453546
4.908944
false
false
false
false
eoger/firefox-ios
Shared/SentryIntegration.swift
2
6459
/* 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 Sentry public enum SentryTag: String { case swiftData = "SwiftData" case browserDB = "BrowserDB" case notificationService = "NotificationService" case unifiedTelemetry = "UnifiedTelemetry" case general = "General" case tabManager = "TabManager" case bookmarks = "Bookmarks" } public class Sentry { public static let shared = Sentry() public static var crashedLastLaunch: Bool { return Client.shared?.crashedLastLaunch() ?? false } private let SentryDSNKey = "SentryDSN" private let SentryDeviceAppHashKey = "SentryDeviceAppHash" private let DefaultDeviceAppHash = "0000000000000000000000000000000000000000" private let DeviceAppHashLength = UInt(20) private var enabled = false private var attributes: [String: Any] = [:] public func setup(sendUsageData: Bool) { assert(!enabled, "Sentry.setup() should only be called once") if DeviceInfo.isSimulator() { Logger.browserLogger.debug("Not enabling Sentry; Running in Simulator") return } if !sendUsageData { Logger.browserLogger.debug("Not enabling Sentry; Not enabled by user choice") return } guard let dsn = Bundle.main.object(forInfoDictionaryKey: SentryDSNKey) as? String, !dsn.isEmpty else { Logger.browserLogger.debug("Not enabling Sentry; Not configured in Info.plist") return } Logger.browserLogger.debug("Enabling Sentry crash handler") do { Client.shared = try Client(dsn: dsn) try Client.shared?.startCrashHandler() enabled = true // If we have not already for this install, generate a completely random identifier // for this device. It is stored in the app group so that the same value will // be used for both the main application and the app extensions. if let defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier), defaults.string(forKey: SentryDeviceAppHashKey) == nil { defaults.set(Bytes.generateRandomBytes(DeviceAppHashLength).hexEncodedString, forKey: SentryDeviceAppHashKey) defaults.synchronize() } // For all outgoing reports, override the default device identifier with our own random // version. Default to a blank (zero) identifier in case of errors. Client.shared?.beforeSerializeEvent = { event in let deviceAppHash = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)?.string(forKey: self.SentryDeviceAppHashKey) event.context?.appContext?["device_app_hash"] = deviceAppHash ?? self.DefaultDeviceAppHash var attributes = event.extra ?? [:] attributes.merge(with: self.attributes) event.extra = attributes } } catch let error { Logger.browserLogger.error("Failed to initialize Sentry: \(error)") } } public func crash() { Client.shared?.crash() } /* This is the behaviour we want for Sentry logging .info .error .severe Debug y y y Beta y y y Relase n n y */ private func shouldNotSendEventFor(_ severity: SentrySeverity) -> Bool { return !enabled || (AppConstants.BuildChannel == .release && severity != .fatal) } private func makeEvent(message: String, tag: String, severity: SentrySeverity, extra: [String: Any]?) -> Event { let event = Event(level: severity) event.message = message event.tags = ["tag": tag] if let extra = extra { event.extra = extra } return event } public func send(message: String, tag: SentryTag = .general, severity: SentrySeverity = .info, extra: [String: Any]? = nil, description: String? = nil, completion: SentryRequestFinished? = nil) { // Build the dictionary var extraEvents: [String: Any] = [:] if let paramEvents = extra { extraEvents.merge(with: paramEvents) } if let extraString = description { extraEvents.merge(with: ["errorDescription": extraString]) } printMessage(message: message, extra: extraEvents) // Only report fatal errors on release if shouldNotSendEventFor(severity) { completion?(nil) return } let event = makeEvent(message: message, tag: tag.rawValue, severity: severity, extra: extraEvents) Client.shared?.send(event: event, completion: completion) } public func sendWithStacktrace(message: String, tag: SentryTag = .general, severity: SentrySeverity = .info, extra: [String: Any]? = nil, description: String? = nil, completion: SentryRequestFinished? = nil) { var extraEvents: [String: Any] = [:] if let paramEvents = extra { extraEvents.merge(with: paramEvents) } if let extraString = description { extraEvents.merge(with: ["errorDescription": extraString]) } printMessage(message: message, extra: extraEvents) // Do not send messages to Sentry if disabled OR if we are not on beta and the severity isnt severe if shouldNotSendEventFor(severity) { completion?(nil) return } Client.shared?.snapshotStacktrace { let event = self.makeEvent(message: message, tag: tag.rawValue, severity: severity, extra: extraEvents) Client.shared?.appendStacktrace(to: event) event.debugMeta = nil Client.shared?.send(event: event, completion: completion) } } public func addAttributes(_ attributes: [String: Any]) { self.attributes.merge(with: attributes) } private func printMessage(message: String, extra: [String: Any]? = nil) { let string = extra?.reduce("") { (result: String, arg1) in let (key, value) = arg1 return "\(result), \(key): \(value)" } Logger.browserLogger.debug("Sentry: \(message) \(string ??? "")") } }
mpl-2.0
6227ec191a19edc82a5e3bb2da5dc238
38.625767
213
0.625948
4.896892
false
false
false
false
benlangmuir/swift
validation-test/compiler_crashers_2_fixed/0189-sr10033.swift
4
777
// RUN: %target-swift-frontend -emit-ir -verify %s // RUN: %target-swift-frontend -emit-ir -verify -disable-requirement-machine-concrete-contraction %s protocol P1 { associatedtype A2 : P2 where A2.A1 == Self } protocol P2 { associatedtype A1 : P1 where A1.A2 == Self var property: Int { get } } extension P2 { var property: Int { return 0 } } class C1 : P1 { // expected-warning@-1 {{non-final class 'C1' cannot safely conform to protocol 'P1', which requires that 'Self.A2.A1' is exactly equal to 'Self'; this is an error in Swift 6}} class A2 : P2 { // expected-warning@-1 {{non-final class 'C1.A2' cannot safely conform to protocol 'P2', which requires that 'Self.A1.A2' is exactly equal to 'Self'; this is an error in Swift 6}} typealias A1 = C1 } }
apache-2.0
267be38796c744e85bd7408c9127d3cc
32.782609
181
0.687259
3.071146
false
false
false
false
benlangmuir/swift
test/Generics/sr13226.swift
4
1406
// RUN: %target-typecheck-verify-swift // https://github.com/apple/swift/issues/55666 struct W<T> {} struct S<C1: Collection> { init(){} // expected-note@+2 {{where 'C1.Element' = 'String', 'W<C2.Element>' = 'Int'}} // expected-note@+1 {{where 'C1.Element' = 'C1', 'W<C2.Element>' = 'C2.Element'}} init<C2>(_ c2: W<C2>) where C2: Collection, C1.Element == W<C2.Element> {} // expected-note@+1 {{where 'C1.Element' = 'String', 'W<C2.Element>' = 'Int'}} static func f<C2>(_ c2: W<C2>) where C2: Collection, C1.Element == W<C2.Element> {} // expected-note@+1 {{where 'C1.Element' = 'String', 'W<C2.Element>' = 'Int'}} func instancef<C2>(_ c2: W<C2>) where C2: Collection, C1.Element == W<C2.Element> {} } let _ = S<[W<String>]>(W<[Int]>()) // expected-error{{initializer 'init(_:)' requires the types 'String' and 'Int' be equivalent}} let _ = S<[W<String>]>.f(W<[Int]>()) // expected-error{{static method 'f' requires the types 'String' and 'Int' be equivalent}} let _ = S<[W<String>]>().instancef(W<[Int]>()) // expected-error{{instance method 'instancef' requires the types 'String' and 'Int' be equivalent}} // Archetypes requirement failure func genericFunc<C1: Collection, C2: Collection>(_ c2: W<C2>, c1: C1.Type) where C1.Element == W<C2.Element> { let _ = S<[W<C1>]>(W<C2>()) // expected-error{{initializer 'init(_:)' requires the types 'C1' and 'C2.Element' be equivalent}} }
apache-2.0
49e8a8aef10ee347dbcf3f39f3e3a8b8
57.583333
147
0.630868
2.806387
false
false
false
false
zirinisp/SlackKit
SlackKit/Sources/TeamIcon.swift
1
2021
// // TeamIcon.swift // // Copyright © 2016 Peter Zignego. All rights reserved. // // 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. public struct TeamIcon { internal(set) public var image34: String? internal(set) public var image44: String? internal(set) public var image68: String? internal(set) public var image88: String? internal(set) public var image102: String? internal(set) public var image132: String? internal(set) public var imageOriginal: String? internal(set) public var imageDefault: Bool? internal init(icon: [String: Any]?) { image34 = icon?["image_34"] as? String image44 = icon?["image_44"] as? String image68 = icon?["image_68"] as? String image88 = icon?["image_88"] as? String image102 = icon?["image_102"] as? String image132 = icon?["image_132"] as? String imageOriginal = icon?["image_original"] as? String imageDefault = icon?["image_default"] as? Bool } }
mit
9a7ee3d7a04d7d0dc4a9002911186109
43.888889
80
0.709406
4.261603
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Post/Scheduling/SchedulingViewControllerPresenter.swift
1
4097
import Foundation import UIKit protocol PresentableSchedulingViewControllerProviding { static func viewController(sourceView: UIView?, sourceRect: CGRect?, viewModel: PublishSettingsViewModel, transitioningDelegate: UIViewControllerTransitioningDelegate?, updated: @escaping (Date?) -> Void, onDismiss: (() -> Void)?) -> UINavigationController } class PresentableSchedulingViewControllerProvider: PresentableSchedulingViewControllerProviding { static func viewController(sourceView: UIView?, sourceRect: CGRect?, viewModel: PublishSettingsViewModel, transitioningDelegate: UIViewControllerTransitioningDelegate?, updated: @escaping (Date?) -> Void, onDismiss: (() -> Void)?) -> UINavigationController { let schedulingViewController = schedulingViewController(with: viewModel, updated: updated) return wrappedSchedulingViewController(schedulingViewController, sourceView: sourceView, sourceRect: sourceRect, transitioningDelegate: transitioningDelegate, onDismiss: onDismiss) } static func wrappedSchedulingViewController(_ schedulingViewController: SchedulingViewControllerProtocol, sourceView: UIView?, sourceRect: CGRect?, transitioningDelegate: UIViewControllerTransitioningDelegate?, onDismiss: (() -> Void)?) -> SchedulingLightNavigationController { let vc = SchedulingLightNavigationController(rootViewController: schedulingViewController) vc.onDismiss = onDismiss if UIDevice.isPad() { vc.modalPresentationStyle = .popover } else { vc.modalPresentationStyle = .custom vc.transitioningDelegate = transitioningDelegate ?? schedulingViewController } if let popoverController = vc.popoverPresentationController, let sourceView = sourceView { popoverController.sourceView = sourceView popoverController.sourceRect = sourceRect ?? sourceView.frame } return vc } static func schedulingViewController(with viewModel: PublishSettingsViewModel, updated: @escaping (Date?) -> Void) -> SchedulingViewControllerProtocol { let schedulingViewController = SchedulingDatePickerViewController() schedulingViewController.coordinator = DateCoordinator(date: viewModel.date, timeZone: viewModel.timeZone, dateFormatter: viewModel.dateFormatter, dateTimeFormatter: viewModel.dateTimeFormatter, updated: updated) return schedulingViewController } } // FIXME: This protocol is redundant as of dropping iOS 13. // // It was used as a facade in between `SchedulingCalendarViewController` (iOS 13) and // `SchedulingDatePickerViewController` (iOS 14+). `SchedulingCalendarViewController` has been // deleted so we can remove this as well. protocol SchedulingViewControllerProtocol: UIViewController, UIViewControllerTransitioningDelegate, UIAdaptivePresentationControllerDelegate { var coordinator: DateCoordinator? { get set } } class SchedulingLightNavigationController: LightNavigationController { var onDismiss: (() -> Void)? override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) onDismiss?() } }
gpl-2.0
568b0b68a68ff4be285b7ba62e149370
51.525641
156
0.592141
8.210421
false
false
false
false
ianfelzer1/ifelzer-advprog
Last Year/IOS Development- J Term 2017/Stopwatch/Stopwatch/ViewController.swift
1
1633
// // ViewController.swift // Stopwatch // // Created by Programming on 1/18/17. // Copyright © 2017 Ian Felzer. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var timeLabel: UILabel! @IBOutlet var startButton: UIButton! @IBOutlet var stopButton: UIButton! @IBOutlet var resetButton: UIButton! let stopwatch = Stopwatch() @IBAction func startButtonTapped() { self.stopwatch.start() Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(ViewController.updateElapsedTimeLabel), userInfo: nil, repeats: true) } @IBAction func stopButtonTapped() { print(self.stopwatch.elapsedTime) self.stopwatch.stop() } override func viewDidLoad() { super.viewDidLoad() self.startButton.backgroundColor = UIColor.green self.startButton.layer.cornerRadius = 30 self.resetButton.backgroundColor = UIColor.black self.resetButton.layer.cornerRadius = 30 self.stopButton.backgroundColor = UIColor.red self.stopButton.layer.cornerRadius = 30 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func resetButtonTapped() { self.stopwatch.reset() self.timeLabel.text = self.stopwatch.formattedElapsedTime } func updateElapsedTimeLabel() { if self.stopwatch.isRunning { self.timeLabel.text = "\(stopwatch.formattedElapsedTime)" } } }
gpl-3.0
74e984d0c0d2ce20be812287565e9933
26.2
153
0.658701
4.915663
false
false
false
false
QuanXu/SwiftSimpleFramwork
SwiftDemo/AppDelegate.swift
3
3915
// // AppDelegate.swift // SwiftDemo // // Created by zhoutong on 16/11/11. // Copyright © 2016年 zhoutong. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //状态栏文字颜色 白色 UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.makeKeyAndVisible() let rootVC = RootTabBarController() self.window?.rootViewController = rootVC //播放启动画面动画 launchAnimation() return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } } //增加启动动画功能 extension AppDelegate{ //播放启动画面动画 fileprivate func launchAnimation() { let statusBarOrientation = UIApplication.shared.statusBarOrientation if let img = splashImageForOrientation(orientation: statusBarOrientation, size: (self.window?.bounds.size)!) { //获取启动图片 let launchImage = UIImage(named: img) let launchview = UIImageView(frame: UIScreen.main.bounds) launchview.image = launchImage //将图片添加到视图上 //self.view.addSubview(launchview) let delegate = UIApplication.shared.delegate let mainWindow = delegate?.window mainWindow!!.addSubview(launchview) //播放动画效果,完毕后将其移除 UIView.animate(withDuration: 1, delay: 1.5, options: .beginFromCurrentState, animations: { launchview.alpha = 0.0 launchview.layer.transform = CATransform3DScale(CATransform3DIdentity, 1.5, 1.5, 1.0) }) { (finished) in launchview.removeFromSuperview() } } } //获取启动图片名(根据设备方向和尺寸) func splashImageForOrientation(orientation: UIInterfaceOrientation, size: CGSize) -> String?{ //获取设备尺寸和方向 var viewSize = size var viewOrientation = "Portrait" if UIInterfaceOrientationIsLandscape(orientation) { viewSize = CGSize(width: size.height, height: size.width) viewOrientation = "Landscape" } //遍历资源库中的所有启动图片,找出符合条件的 if let imagesDict = Bundle.main.infoDictionary { if let imagesArray = imagesDict["UILaunchImages"] as? [[String: String]] { for dict in imagesArray { if let sizeString = dict["UILaunchImageSize"], let imageOrientation = dict["UILaunchImageOrientation"] { let imageSize = CGSizeFromString(sizeString) if imageSize.equalTo(viewSize) && viewOrientation == imageOrientation { if let imageName = dict["UILaunchImageName"] { return imageName } } } } } } return nil } }
mit
94d80265d5645ae5fd9f4943f1e7aec4
30.288136
144
0.569339
5.619482
false
false
false
false
enlarsen/Tesseract-Box-Editor
Tesseract-Box-Editor/Document.swift
1
4482
// // Document.swift // Tesseract-Box-Editor // // Created by Erik Larsen on 6/27/14. // // Copyright (c) 2014 Erik Larsen. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation import Cocoa import QuartzCore class Document: NSDocument { var pagesFromImage: [NSBitmapImageRep] = [] var boxes: [Box] = [] var pageIndex = Dictionary<Int, Int>() override var windowNibName: String { return "Document" } // TODO: This needs vastly improved error handling and value checking func readBoxFile(path: String) { var error: NSError? = nil var boxes: [Box] = [] let fileText: NSString? do { fileText = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) } catch var error1 as NSError { error = error1 fileText = nil } if let mError = error { NSLog("Error: \(mError.localizedDescription)") } fileText!.enumerateLinesUsingBlock({line, stop in let box = Box() var intValue: CInt = 0 var characterAsString: NSString? let scanner = NSScanner(string: line) scanner.caseSensitive = true scanner.charactersToBeSkipped = nil scanner.scanUpToString(" ", intoString: &characterAsString) if let character = characterAsString { box.character = character as String } scanner.charactersToBeSkipped = NSCharacterSet.whitespaceCharacterSet() box.x = self.getNextIntValue(scanner) box.y = self.getNextIntValue(scanner) box.x2 = self.getNextIntValue(scanner) box.y2 = self.getNextIntValue(scanner) box.page = self.getNextIntValue(scanner) boxes.append(box) }) self.boxes = boxes } func getNextIntValue(scanner: NSScanner) -> Int { var intValue: CInt = 0 scanner.scanInt(&intValue) return Int(intValue) } func createPageIndex() { pageIndex.removeAll(keepCapacity: true) var current = -1 for var i = 0; i < boxes.count; i++ { if current != boxes[i].page { current = boxes[i].page pageIndex[current] = i } } } override func readFromURL(url: NSURL, ofType typeName: String) throws { readBoxFile(url.path!) } override func writeToURL(url: NSURL, ofType typeName: String) throws { var outError: NSError! = NSError(domain: "Migrator", code: 0, userInfo: nil) var output = "" for box in boxes { output = output.stringByAppendingString(box.formatForWriting()) } do { try output.writeToFile(url.path!, atomically: true, encoding: NSUTF8StringEncoding) } catch var error as NSError { outError = error } // NSLog("\(outError.memory?.localizedDescription)") if outError == nil { return } else { throw outError } } override func makeWindowControllers() { let windowController = DocumentWindowController(windowNibName: self.windowNibName) addWindowController(windowController) } }
mit
871438847a860500a6e3df0ef1914642
27.547771
95
0.612896
4.752916
false
false
false
false
Yoseob/Trevi
Trevi/Source/Pipe.swift
1
2126
// // Pipe.swift // Trevi // // Created by JangTaehwan on 2016. 2. 29.. // Copyright © 2016년 LeeYoseob. All rights reserved. // import Libuv /** Provides interactive actions with file descriptors and Stream modules. */ public class Pipe : Stream { public let pipeHandle : uv_pipe_ptr public init(loop : uv_loop_ptr = uv_default_loop(), ipc : Int32 = 0){ self.pipeHandle = uv_pipe_ptr.alloc(1) uv_pipe_init(loop, self.pipeHandle, ipc) super.init(streamHandle: uv_stream_ptr(self.pipeHandle)) } deinit{ if isAlive { Handle.close(self.handle) self.pipeHandle.dealloc(1) isAlive = false } } } // Pipe static functions extension Pipe { public static func open(handle : uv_pipe_ptr, fd : uv_file) { let error = uv_pipe_open(handle, fd) if error != 0 { // Should handle error } } public static func bind(handle : uv_pipe_ptr, path : String) { let error = uv_pipe_bind(handle, path) if error != 0 { // Should handle error } } public static func connect(handle : uv_pipe_ptr, path : String) { let request : uv_connect_ptr = uv_connect_ptr.alloc(1) uv_pipe_connect(request, handle, path, Pipe.afterConnect) } public static func listen(handle : uv_pipe_ptr, backlog : Int32 = 50) { let error = uv_listen(uv_stream_ptr(handle), backlog, Pipe.onConnection) if error != 0 { // Should handle error } } } // Pipe static callbacks extension Pipe { public static var afterConnect : uv_connect_cb = { (request, status) in request.dealloc(1) } public static var onConnection : uv_connection_cb = { (handle, status) in var client = Pipe() if uv_accept(handle, client.streamHandle) != 0 { return } // Should add client callbacks } }
apache-2.0
3bf43d85357015e386ed90fad726077e
20.444444
80
0.540744
4.00566
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Tests/EurofurenceModelTests/Test Doubles/Notifications/CapturingRemoteNotificationsTokenRegistration.swift
2
1163
import EurofurenceModel import Foundation class CapturingRemoteNotificationsTokenRegistration: RemoteNotificationsTokenRegistration { private(set) var capturedRemoteNotificationsDeviceToken: Data? private(set) var capturedUserAuthenticationToken: String? private(set) var numberOfRegistrations = 0 private var completionHandler: ((Error?) -> Void)? private(set) var didRegisterNilPushTokenAndAuthToken = false func registerRemoteNotificationsDeviceToken(_ token: Data?, userAuthenticationToken: String?, completionHandler: @escaping (Error?) -> Void) { capturedRemoteNotificationsDeviceToken = token capturedUserAuthenticationToken = userAuthenticationToken numberOfRegistrations += 1 self.completionHandler = completionHandler didRegisterNilPushTokenAndAuthToken = token == nil && userAuthenticationToken == nil } func succeedLastRequest() { completionHandler?(nil) } struct SomeError: Error {} func failLastRequest() { completionHandler?(SomeError()) } }
mit
79c4514db09447a8aaf132040bbaaf97
36.516129
96
0.687876
6.461111
false
false
false
false
tfmalt/garage-door-opener-ble
iOS/GarageOpener/BTService.swift
1
5787
// // BTService.swift // GarageOpener // // Created by Thomas Malt on 11/01/15. // Copyright (c) 2015 Thomas Malt. All rights reserved. // import Foundation import CoreBluetooth class BTService : NSObject, CBPeripheralDelegate { var peripheral : CBPeripheral? var txCharacteristic : CBCharacteristic? var rxCharacteristic : CBCharacteristic? let btConst = BTConstants() private let nc = NSNotificationCenter.defaultCenter() init(initWithPeripheral peripheral: CBPeripheral) { super.init() self.peripheral = peripheral self.peripheral?.delegate = self } deinit { self.reset() } func reset() { if peripheral != nil { peripheral = nil } } func startDiscoveringServices() { println("Starting discover services") if let peri = self.peripheral { peri.discoverServices([CBUUID(string: btConst.SERVICE_UUID)]) } } func sendNotificationIsConnected(connected: Bool) { if let peripheral = self.peripheral { nc.postNotificationName( "btConnectionChangedNotification", object: self, userInfo: [ "isConnected": connected, "name": peripheral.name ] ) } } // // Implementation of CBPeripheralDelegate functions: // // Did Discover Characteristics for Service // // Adds the two characteristics to the object for easy retrival func peripheral(peripheral: CBPeripheral!, didDiscoverCharacteristicsForService service: CBService!, error: NSError!) { println("got did discover characteristics for service") for cha in service.characteristics { if cha.UUID == CBUUID(string: btConst.CHAR_TX_UUID) { self.txCharacteristic = (cha as CBCharacteristic) } else if cha.UUID == CBUUID(string: btConst.CHAR_RX_UUID) { self.rxCharacteristic = (cha as CBCharacteristic) } else { println(" Found unexpected characteristic: \(cha)") return } peripheral.setNotifyValue(true, forCharacteristic: cha as CBCharacteristic) } self.sendNotificationIsConnected(true) } func peripheral(peripheral: CBPeripheral!, didDiscoverDescriptorsForCharacteristic characteristic: CBCharacteristic!, error: NSError!) { println("got did discover descriptors for characteristic") } func peripheral(peripheral: CBPeripheral!, didDiscoverIncludedServicesForService service: CBService!, error: NSError!) { println("got did discover included services for service") } func peripheral(peripheral: CBPeripheral!, didDiscoverServices error: NSError!) { // array of the two available characteristics. let cUUIDs : [CBUUID] = [ CBUUID(string: btConst.CHAR_RX_UUID), CBUUID(string: btConst.CHAR_TX_UUID) ] if (error != nil) { println("got error: a surprise: \(error)") return } // Sometimes services has been reported as nil. testing for that. if ((peripheral.services == nil) || (peripheral.services.count == 0)) { println("Got no services!") return } for service in peripheral.services { if (service.UUID == CBUUID(string: btConst.SERVICE_UUID)) { peripheral.discoverCharacteristics(cUUIDs, forService: service as CBService) } } } func peripheral(peripheral: CBPeripheral!, didModifyServices invalidatedServices: [AnyObject]!) { println("got did modify services") } func peripheral(peripheral: CBPeripheral!, didReadRSSI RSSI: NSNumber!, error: NSError!) { // println("got did read rssi: \(RSSI)") if peripheral.state != CBPeripheralState.Connected { println(" Peripheral state says not connected.") return } nc.postNotificationName( "btRSSIUpdateNotification", object: peripheral, userInfo: ["rssi": RSSI] ) } func peripheral(peripheral: CBPeripheral!, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic!, error: NSError!) { println("got did update notification state for characteristic") } func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) { println("got did update value for characteristic") } func peripheral(peripheral: CBPeripheral!, didUpdateValueForDescriptor descriptor: CBDescriptor!, error: NSError!) { println("got did update value for descriptor") } func peripheral(peripheral: CBPeripheral!, didWriteValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) { println("got did write value for characteristic") } func peripheral(peripheral: CBPeripheral!, didWriteValueForDescriptor descriptor: CBDescriptor!, error: NSError!) { println("got did write value for descriptor") } func peripheralDidInvalidateServices(peripheral: CBPeripheral!) { println("got peripheral did invalidate services") } func peripheralDidUpdateName(peripheral: CBPeripheral!) { println("got peripheral did update name") } func peripheralDidUpdateRSSI(peripheral: CBPeripheral!, error: NSError!) { println("Got peripheral did update rssi") } }
mit
2d12478d346b41a7ee569781310736ad
32.450867
144
0.62243
5.662427
false
false
false
false
phimage/CryptoPrephirences
Sources/CryptoPrephirences.swift
1
4250
// // CryptoPrephirences.swift // CryptoPrephirences /* The MIT License (MIT) Copyright (c) 2015-2016 Eric Marchand (phimage) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import Prephirences import CryptoSwift open class CryptoPrephirences { open let preferences: PreferencesType open let cipher: Cipher open var returnNotDecrytable = false public init(preferences: PreferencesType, cipher: Cipher) { self.preferences = preferences self.cipher = cipher } } extension CryptoPrephirences: PreferencesType { public func object(forKey key: String) -> Any? { guard let value = self.preferences.object(forKey: key) else { return nil } guard let data = value as? Data, let decrypted = try? data.decrypt(cipher: cipher), let object = Prephirences.unarchive(decrypted) else { return self.returnNotDecrytable ? value : nil } return object } public func dictionary() -> [String : Any] { var result = [String : Any]() for (key, value) in self.preferences.dictionary() { guard let data = value as? Data, let decrypted = try? data.decrypt(cipher: cipher), let object = Prephirences.unarchive(decrypted) else { if self.returnNotDecrytable { result[key] = value } continue } result[key] = object } return result } } open class MutableCryptoPrephirences: CryptoPrephirences { public var mutablePreferences: MutablePreferencesType { return self.preferences as! MutablePreferencesType } public init(preferences: MutablePreferencesType, cipher: Cipher) { super.init(preferences: preferences, cipher: cipher) } } extension MutableCryptoPrephirences: MutablePreferencesType { public func set(_ value: Any?, forKey key: String) { guard let object = value else { self.removeObject(forKey: key) return } let data = Prephirences.archive(object) if let encrypted = try? data.encrypt(cipher: cipher) { self.mutablePreferences.set(encrypted, forKey: key) } } public func removeObject(forKey key: String) { self.mutablePreferences.removeObject(forKey: key) } } public extension MutablePreferencesType { public func set(_ value: Any?, forKey key: String, withCipher cipher: Cipher) { guard let object = value else { self.removeObject(forKey: key) return } let data = Prephirences.archive(object) if let encrypted = try? data.encrypt(cipher: cipher) { self.set(encrypted, forKey: key) } } } extension CryptoPrephirences { public func object(forKey key: String, withCipher cipher: Cipher) -> Any? { guard let value = self.preferences.object(forKey: key) else { return nil } guard let data = value as? Data, let decrypted = try? data.decrypt(cipher: cipher), let object = Prephirences.unarchive(decrypted) else { return self.returnNotDecrytable ? value : nil } return object } }
mit
97af98a8bfd2f4e689d58f60ee0e5036
30.716418
149
0.668706
4.753915
false
false
false
false
prochol/UIStoryboard-main
Foundation/TimeInterval+String.swift
1
1924
// // TimeInterval+String.swift // DaTracker // // Created by Pavel Kuzmin on 05.10.2018. // Copyright © 2018 Gaika Group. All rights reserved. // import Foundation.NSDate extension TimeInterval { func stringValue() -> String { let currentHours = self.isFinite ? Int(self / 3600) : 0 let currentMinutes = self.isFinite ? Int(self / 60) - currentHours * 60 : 0 let currentSeconds = self.isFinite ? Int(self) % 60 : 0 let currentTimeString = currentHours > 0 ? String.init(format: "%i:%02d:%02d", currentHours, currentMinutes, currentSeconds) : String.init(format: "%02d:%02d", currentMinutes, currentSeconds) return currentTimeString } func stringLongValue() -> String { let currentHours = self.isFinite ? Int(self / 3600) : 0 let currentMinutes = self.isFinite ? Int(self / 60) - currentHours * 60 : 0 let currentSeconds = self.isFinite ? Int(self) % 60 : 0 var currentTimeString = "0 sec" if currentHours > 0 { if currentMinutes > 0 { currentTimeString = currentSeconds > 0 ? String.init(format: "%i hours %02d min %02d sec", currentHours, currentMinutes, currentSeconds) : String.init(format: "%i hours %02d min ", currentHours, currentMinutes) } else { currentTimeString = currentSeconds > 0 ? String.init(format: "%i hours %02d sec", currentHours, currentSeconds) : String.init(format: "%i hours", currentHours) } } else { if currentMinutes > 0 { currentTimeString = currentSeconds > 0 ? String.init(format: "%02d min %02d sec", currentMinutes, currentSeconds) : String.init(format: "%02d min ", currentMinutes) } else { currentTimeString = String.init(format: "%02d sec", currentSeconds) } } return currentTimeString } }
mit
26d04fcc712dd8b33a67ce9c98437ceb
39.083333
226
0.617265
4.524706
false
false
false
false
SiddharthChopra/KahunaSocialMedia
KahunaSocialMedia/Classes/Twitter/TwitterPublicFeedsHandler.swift
1
5189
// // TwitterPublicFeedsHandler.swift // MyCity311 // // Created by Piyush on 6/13/16. // Copyright © 2016 Kahuna Systems. All rights reserved. // import UIKit @objc protocol TwitterFeedDelegate: class { @objc optional func twitterFeedFetchSuccess(_ feedArray: NSArray?) @objc optional func twitterFeedFetchError(_ errorType: NSError?) } class TwitterPublicFeedsHandler: NSObject { var tweetAccessToken: String! var tweetSecretKey: String! var tweetConsumerKey: String! var tweetConsumerSecret: String! var tweetOwnerSecretName: String! var tweetSlugName: String! var engine: FHSTwitterEngine! weak var twitterDelegate: TwitterFeedDelegate! static let sharedInstance = TwitterPublicFeedsHandler() override init() { } deinit { print("** TwitterPublicFeedsHandler deinit called **") } func getTwitterFeedListFromURL(_ stringURL: String) { autoreleasepool() { DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { let basePath = SocialOperationHandler.sharedInstance.serverBaseURL let paramString = basePath + stringURL let loadURL = URL(string: paramString) let request = URLRequest(url: loadURL!) let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.dataTask(with: request, completionHandler: { (data, response, error) in if error != nil { if self.twitterDelegate != nil { self.twitterDelegate?.twitterFeedFetchError!(error! as NSError?) } } else if data != nil { let parserArray = NSMutableArray() let jsonParser = TwitterJSONParser() var tweetsArray = NSMutableArray() DispatchQueue.main.async { tweetsArray = jsonParser.parseTwitterFeedData(data!, parserArray: parserArray) as NSMutableArray if tweetsArray.count > 0 { SocialOperationHandler.sharedInstance.socialDBStore.saveAllFetchedTwitterFeedsToDB(twitterFeedArray: tweetsArray) } if self.twitterDelegate != nil { self.twitterDelegate.twitterFeedFetchSuccess!(tweetsArray) } } } }) task.resume() } } } func getLatestTweetsFromServerWithURLString(_ stringURL: String) { autoreleasepool() { DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { // AccessToken self.tweetAccessToken = SocialOperationHandler.sharedInstance.tweetAccessToken // AccessToken Secret self.tweetSecretKey = SocialOperationHandler.sharedInstance.tweetSecretKey // TweetConsumerKey self.tweetConsumerKey = SocialOperationHandler.sharedInstance.tweetConsumerKey // ConsumerKeySecret self.tweetConsumerSecret = SocialOperationHandler.sharedInstance.tweetConsumerSecret // OwnerSecret self.tweetOwnerSecretName = SocialOperationHandler.sharedInstance.tweetOwnerSecretName // SlugName self.tweetSlugName = SocialOperationHandler.sharedInstance.tweetSlugName self.engine = FHSTwitterEngine.shared() self.engine.permanentlySetConsumerKey(self.tweetConsumerKey, andSecret: self.tweetConsumerSecret) let token = FHSToken() token.key = self.tweetAccessToken token.secret = self.tweetSecretKey self.engine.accessToken = token var tweetsArray = NSMutableArray() var isNoError = false if let tweets = self.engine.getTimelineForList(withID: self.tweetSlugName, self.tweetOwnerSecretName, count: 30, tweetURL: stringURL) as? NSArray { isNoError = true let jsonParser = TwitterJSONParser() DispatchQueue.main.async { tweetsArray = jsonParser.parseTwitterData(tweets) if tweetsArray.count > 0 { SocialOperationHandler.sharedInstance.socialDBStore.saveAllFetchedTwitterFeedsToDB(twitterFeedArray: tweetsArray) } if self.twitterDelegate != nil { self.twitterDelegate.twitterFeedFetchSuccess!(tweetsArray) } } } if !isNoError { DispatchQueue.main.async { if self.twitterDelegate != nil { self.twitterDelegate.twitterFeedFetchError!(nil) } } } } } } }
mit
30b64f5cc8265c09484ae630101a8caa
43.724138
163
0.574788
6.132388
false
false
false
false
marty-suzuki/FluxCapacitor
FluxCapacitor/Dispatcher.swift
1
1050
// // Dispatcher.swift // FluxCapacitor // // Created by marty-suzuki on 2017/07/29. // // import Foundation /// Represents Flux-Dispatcher. /// /// - seealso: [flux-concepts Dispatcher](https://github.com/facebook/flux/tree/master/examples/flux-concepts#dispatcher) public final class Dispatcher { let objectStore = ObjectStore() private init() {} func register<T: Storable>(_ object: T) { objectStore.insert(object) } func unregister<T: Storable>(_ object: T) { objectStore.remove(forType: T.self) } func dispatch<T: DispatchState>(_ dispatchState: T) { typealias U = T.RelatedStoreType.DispatchStateType guard let state = dispatchState as? U else { return } let store = T.RelatedStoreType.instantiate() store.reduce(with: state) } } extension Dispatcher { /// Represents single Dispatcher. public static let shared = Dispatcher() /// Unregister all Stores dispatching. public func unregisterAll() { objectStore.removeAll() } }
mit
ed4c9d04be9788b712972a0f6c3ef63e
22.863636
121
0.66
4.069767
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/ElasticTranscoder/ElasticTranscoder_Paginator.swift
1
11516
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension ElasticTranscoder { /// The ListJobsByPipeline operation gets a list of the jobs currently in a pipeline. Elastic Transcoder returns all of the jobs currently in the specified pipeline. The response body contains one element for each job that satisfies the search criteria. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listJobsByPipelinePaginator<Result>( _ input: ListJobsByPipelineRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListJobsByPipelineResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listJobsByPipeline, tokenKey: \ListJobsByPipelineResponse.nextPageToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listJobsByPipelinePaginator( _ input: ListJobsByPipelineRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListJobsByPipelineResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listJobsByPipeline, tokenKey: \ListJobsByPipelineResponse.nextPageToken, on: eventLoop, onPage: onPage ) } /// The ListJobsByStatus operation gets a list of jobs that have a specified status. The response body contains one element for each job that satisfies the search criteria. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listJobsByStatusPaginator<Result>( _ input: ListJobsByStatusRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListJobsByStatusResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listJobsByStatus, tokenKey: \ListJobsByStatusResponse.nextPageToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listJobsByStatusPaginator( _ input: ListJobsByStatusRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListJobsByStatusResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listJobsByStatus, tokenKey: \ListJobsByStatusResponse.nextPageToken, on: eventLoop, onPage: onPage ) } /// The ListPipelines operation gets a list of the pipelines associated with the current AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listPipelinesPaginator<Result>( _ input: ListPipelinesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPipelinesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPipelines, tokenKey: \ListPipelinesResponse.nextPageToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listPipelinesPaginator( _ input: ListPipelinesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPipelinesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPipelines, tokenKey: \ListPipelinesResponse.nextPageToken, on: eventLoop, onPage: onPage ) } /// The ListPresets operation gets a list of the default presets included with Elastic Transcoder and the presets that you've added in an AWS region. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listPresetsPaginator<Result>( _ input: ListPresetsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPresetsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPresets, tokenKey: \ListPresetsResponse.nextPageToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listPresetsPaginator( _ input: ListPresetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPresetsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPresets, tokenKey: \ListPresetsResponse.nextPageToken, on: eventLoop, onPage: onPage ) } } extension ElasticTranscoder.ListJobsByPipelineRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ElasticTranscoder.ListJobsByPipelineRequest { return .init( ascending: self.ascending, pageToken: token, pipelineId: self.pipelineId ) } } extension ElasticTranscoder.ListJobsByStatusRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ElasticTranscoder.ListJobsByStatusRequest { return .init( ascending: self.ascending, pageToken: token, status: self.status ) } } extension ElasticTranscoder.ListPipelinesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ElasticTranscoder.ListPipelinesRequest { return .init( ascending: self.ascending, pageToken: token ) } } extension ElasticTranscoder.ListPresetsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ElasticTranscoder.ListPresetsRequest { return .init( ascending: self.ascending, pageToken: token ) } }
apache-2.0
148bdaf9864ec3c4784e51172f8bdfb7
42.787072
258
0.6471
5.225045
false
false
false
false
xdliu002/TongjiAppleClubDeviceManagement
TAC-DM/AppDelegate.swift
1
6285
// // AppDelegate.swift // TAC-DM // // Created by FOWAFOLO on 15/7/24. // Copyright (c) 2015年 TAC. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.andy.CreateDB2" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("CreateDB2", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TAC-DM.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } catch { fatalError() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges { do { try moc.save() } catch let error1 as NSError { error = error1 // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } } }
mit
d904d3ee05a01dc4dac12f3bcb1d5b44
50.081301
290
0.690116
5.806839
false
false
false
false
jwelton/BreweryDB
BreweryDB/RequestManager.swift
1
2037
// // RequestManager.swift // BreweryDB // // Created by Jake Welton on 2016-07-21. // Copyright © 2016 Jake Welton. All rights reserved. // import Foundation public protocol BreweryDBRequest { var endpoint: RequestEndPoint { get } var rawParams: [String: String]? { get } var rawOrderBy: String? { get } var pageNumber: Int { get set } } public class RequestManager<Type: JSONParserEntity> { fileprivate let requestBuilder: RequestBuilder fileprivate var urlRequest: URLRequest public var request: BreweryDBRequest public var requestURL: URLRequest { return urlRequest } public var currentPageNumber: Int { return request.pageNumber } public init?(request: BreweryDBRequest) { requestBuilder = RequestBuilder(endPoint: request.endpoint) guard let url = requestBuilder.buildRequest(request) else { return nil } self.request = request urlRequest = url } public func fetch(using completionHandler: @escaping ([Type]?)->Void) { URLSession.shared.dataTask(with: urlRequest, completionHandler: { data, response, error in guard let returnedData = data, let response = response as? HTTPURLResponse , response.statusCode == 200 else { completionHandler(nil) return } let jsonParser = JSONParser<Type>(rawData: returnedData) jsonParser?.extractObjects(using: completionHandler) }) .resume() } public func fetchNextPage(using completionHandler: @escaping ([Type]?)->Void) { request.pageNumber += 1 guard let url = requestBuilder.buildRequest(request) else { completionHandler(nil) return } urlRequest = url fetch(using: completionHandler) } public func cancel() { URLSession.shared.invalidateAndCancel() } }
mit
baf9dc9ac0cff637f422d4cbcffd448d
28.085714
98
0.611493
5.400531
false
false
false
false
DeveloperLx/LxWaveLayer-swift
LxWaveLayerDemo/LxWaveLayerDemo/ViewController.swift
1
1298
// // ViewController.swift // LxWaveLayerDemo // // Created by DeveloperLx on 15/12/12. // Copyright © 2015年 DeveloperLx. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var _waveContainerView: UIView! let _waveLayer = LxWaveLayer() override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) _waveLayer.deployOnView(_waveContainerView) _waveLayer.beginWaveAnimation() } @IBAction func heightSliderValueChanged(sender: UISlider) { _waveLayer.waveHeight = CGFloat(sender.value) } @IBAction func amplitideSliderValueChanged(sender: UISlider) { _waveLayer.waveAmplitude = CGFloat(sender.value) } @IBAction func periodSliderValueChanged(sender: UISlider) { _waveLayer.wavePeriod = NSTimeInterval(sender.value) } @IBAction func speedSliderValueChanged(sender: UISlider) { _waveLayer.waveSpeed = CGFloat(sender.value) } @IBAction func startOrStopSwitchValueChanged(sender: UISwitch) { if sender.on { _waveLayer.beginWaveAnimation() } else { _waveLayer.stopWaveAnimation() } } }
mit
4ac9413542de1c226addee0dc15b40b7
22.545455
68
0.633205
4.778598
false
false
false
false
kousun12/RxSwift
RxSwift/Concurrency/Lock.swift
4
1620
// // Lock.swift // Rx // // Created by Krunoslav Zaher on 3/31/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation protocol Lock { func lock() func unlock() } /** Simple wrapper for spin lock. */ struct SpinLock { private var _lock = OS_SPINLOCK_INIT init() { } mutating func lock() { OSSpinLockLock(&_lock) } mutating func unlock() { OSSpinLockUnlock(&_lock) } mutating func performLocked(@noescape action: () -> Void) { OSSpinLockLock(&_lock) action() OSSpinLockUnlock(&_lock) } mutating func calculateLocked<T>(@noescape action: () -> T) -> T { OSSpinLockLock(&_lock) let result = action() OSSpinLockUnlock(&_lock) return result } mutating func calculateLockedOrFail<T>(@noescape action: () throws -> T) throws -> T { OSSpinLockLock(&_lock) defer { OSSpinLockUnlock(&_lock) } let result = try action() return result } } extension NSRecursiveLock : Lock { func performLocked(@noescape action: () -> Void) { self.lock() action() self.unlock() } func calculateLocked<T>(@noescape action: () -> T) -> T { self.lock() let result = action() self.unlock() return result } func calculateLockedOrFail<T>(@noescape action: () throws -> T) throws -> T { self.lock() defer { self.unlock() } let result = try action() return result } }
mit
aadbe734b0457c560f78745d01069dda
19.518987
90
0.54321
4.487535
false
false
false
false
caodong1991/SwiftStudyNote
Swift.playground/Pages/19 - NestedType.xcplaygroundpage/Contents.swift
1
1803
import Foundation // 嵌套类型 /* 枚举常用于为特定类或结构体实现某些功能。 类似地,枚举可以方便的定义工具类或结构体,从而为某个复杂的类型所使用。 为了实现这种功能,Swift允许你定义嵌套类型,可以在支持的类型中定义嵌套的枚举、类和结构体。 要在一个类型中嵌套另一个类型,将嵌套类型的定义写在其外部类型的{}内,而且可以根据需要定义多级嵌套。 */ // 嵌套类型实践 struct BlackjackCard { enum Suit: Character { case spades = "♠", hearts = "♡", diamonds = "♢", clubs = "♣" } enum Rank: Int { case two = 2, three, four, five, six, seven, eight, nine, ten case jack, queen, king, ace struct Values { let first: Int, second: Int? } var values: Values { switch self { case .ace: return Values(first: 1, second: 11) case .jack, .queen, .king: return Values(first: 10, second: nil) default: return Values(first: self.rawValue, second: nil) } } } let rank: Rank, suit: Suit var description: String { var output = "suit is \(suit.rawValue)," output += " value is \(rank.values.first)" if let second = rank.values.second { output += " or \(second)" } return output } } let theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades) print("theAceOfSpades: \(theAceOfSpades.description)") // 引用嵌套类型 /* 在外部引用嵌套类型时,在嵌套类型的类型名前加上其外部类型的类型名作为前缀。 */ let heartsSymbol = BlackjackCard.Suit.hearts.rawValue
mit
416e426b758f17646a566bff90e09439
24.907407
69
0.576841
3.34689
false
false
false
false
Charlisim/ios-collection-batch-safe-updates-swift
CSMCollectionBatchUpdates/CSMCollectionBatchUpdates/CSMCollectionUpdate.swift
1
11881
// // CSMCollectionUpdate.swift // CSMCollectionBatchUpdates // // Created by Carlos Simon Villas on 11/04/16. // Copyright © 2016 Charlisim. All rights reserved. // import Foundation public class CSMCollectionUpdate{ let type:CSMCollectionUpdateType var object:AnyObject? var itemUpdate:Bool { get{ return false } } var sectionUpdate:Bool{ get{ return false } } public init(withType type:CSMCollectionUpdateType, object:AnyObject){ self.type = type self.object = object } public static func calculateUpdatesFor( oldModel oldSections:[CSMUpdatableCollectionSection]?, newModel newSections:[CSMUpdatableCollectionSection], sectionsPriorityOrder:[String]?, eliminatesDuplicates:Bool, completion:(sections:[CSMUpdatableCollectionSection]?, updates:[CSMCollectionUpdate]?)->Void ){ autoreleasepool { // Define section updates: UICollectionView and UITableView cannot deal with simultaneous updates for both items and sections (internal exceptions are generated leading to inconsistent states), so once a section change is detected perform full content reload instead of batch updates. // Find insertedSections for newIndex in 0..<newSections.count{ let newSection:CSMUpdatableCollectionSection = newSections[newIndex] var oldIndex = NSNotFound if let oldSections = oldSections{ let matchedOldIndex = oldSections.indexOf({ (oldSection) -> Bool in return oldSection.uid == newSection.uid }) if matchedOldIndex == nil{ oldIndex = NSNotFound }else if let newOldIndex = matchedOldIndex { oldIndex = newOldIndex } if oldIndex == NSNotFound{ completion(sections: newSections, updates: nil) return } } } // Find deleted or moved sections if let oldSections = oldSections{ for oldIndex in 0..<oldSections.count{ let oldSection = oldSections[oldIndex] let newIndex = newSections.indexOf({ (newSection) -> Bool in return oldSection.uid == newSection.uid }) if oldIndex != newIndex{ completion(sections: newSections, updates: nil) return } } } // Calculate new sectionsProcessing order var newSectionsProcessingOrder:[Int] = [] // First add index of priority order if let sectionsPriorityOrder = sectionsPriorityOrder{ for sectionId in sectionsPriorityOrder{ let index = newSections.indexOf({ (newSection) -> Bool in return newSection.uid == sectionId }) if let index = index{ if !newSectionsProcessingOrder.contains(index){ newSectionsProcessingOrder.append(index) } } } } // Add the rest of index for sectionIndex in 0..<newSections.count{ if !newSectionsProcessingOrder.contains(sectionIndex){ newSectionsProcessingOrder.append(sectionIndex) } } // Guarantee items uniqueness var newItemsSet:Set<String> = Set() for sectionIndex in newSectionsProcessingOrder{ var newSection = newSections[sectionIndex] let notUniqueItemIndexes = NSMutableIndexSet() for (index, item) in newSection.items.enumerate(){ if newItemsSet.contains(item.uid){ notUniqueItemIndexes.addIndex(index) }else{ newItemsSet.insert(item.uid) } } var updatedItems = Array(newSection.items) for notUnique in notUniqueItemIndexes{ updatedItems.removeAtIndex(notUnique) } newSection.items = Array(updatedItems) if !eliminatesDuplicates{ newItemsSet.removeAll() } } // Pre-calculate new items indexPaths lookup table let newItemsLookupTable = NSMutableDictionary() for (section_index, newSection) in newSections.enumerate(){ let newItemsInSection:NSMutableDictionary if eliminatesDuplicates{ newItemsInSection = newItemsLookupTable }else{ newItemsInSection = NSMutableDictionary() newItemsLookupTable[newSection.uid] = newItemsInSection } for (item_index,item) in newSection.items.enumerate(){ newItemsInSection[item.uid] = NSIndexPath(forItem: item_index , inSection: section_index) } } // Pre-calculate old items indexPaths lookup table let oldItemsLookupTable = NSMutableDictionary() if let oldSections = oldSections{ for (section_index, oldSection) in oldSections.enumerate(){ let oldItemsInSection:NSMutableDictionary if eliminatesDuplicates{ oldItemsInSection = oldItemsLookupTable }else{ oldItemsInSection = NSMutableDictionary() newItemsLookupTable[oldSection.uid] = oldItemsInSection } for (item_index,item) in oldSection.items.enumerate(){ oldItemsInSection[item.uid] = NSIndexPath(forItem: item_index , inSection: section_index) } } } // Calculate updates var updates:[CSMCollectionUpdate] = [] // Calculate inserted items for (section_index, newSection) in newSections.enumerate(){ let lookupTable:NSDictionary if eliminatesDuplicates{ lookupTable = oldItemsLookupTable }else{ if let sectionData = oldItemsLookupTable[newSection.uid] as? NSDictionary{ lookupTable = sectionData }else{ lookupTable = NSDictionary() } } for (item_index, item) in newSection.items.enumerate(){ if let oldIndexPath:NSIndexPath? = lookupTable[item.uid] as? NSIndexPath{ if oldIndexPath == nil{ updates.append(CSMCollectionItemUpdate.updateWithType(.Insert, indexPath: nil, newIndexPath: NSIndexPath(forItem: item_index, inSection:section_index), object: item.uid)) } }else{ updates.append(CSMCollectionItemUpdate.updateWithType(.Insert, indexPath: nil, newIndexPath: NSIndexPath(forItem: item_index, inSection:section_index), object: item.uid)) } } } // Calculate deleted and moved items var indexPathsForDeletedItems:[NSIndexPath] = [] var indexPathsForMovedItems:[NSIndexPath] = [] if let oldSections = oldSections{ for (oldSection_index, oldSection) in oldSections.enumerate(){ let lookupTable:NSDictionary? if eliminatesDuplicates{ lookupTable = newItemsLookupTable }else{ lookupTable = newItemsLookupTable[oldSection.uid] as? NSDictionary } for (item_index, item) in oldSection.items.enumerate(){ if let newIndexPath = lookupTable?[item.uid] as? NSIndexPath{ let newSection:CSMUpdatableCollectionSection = newSections[newIndexPath.section] if newSection.uid == oldSection.uid && item_index == newIndexPath.item{ // Item remains at the same place continue } let oldIndexPath = NSIndexPath(forItem: item_index, inSection: oldSection_index) indexPathsForMovedItems.append(oldIndexPath) updates.append(CSMCollectionItemUpdate(withType: .Move, object: item.uid, indexPath: oldIndexPath, newIndexPath: newIndexPath)) }else{ let indexPath = NSIndexPath(forItem: item_index, inSection: oldSection_index) indexPathsForDeletedItems.append(indexPath) updates.append(CSMCollectionItemUpdate.updateWithType(.Delete, indexPath: nil, newIndexPath: indexPath, object: item.uid)) } } } } // Calculates items to be reload if let oldSections = oldSections{ for (section_index, oldSection) in oldSections.enumerate(){ let lookupTable:NSDictionary? if eliminatesDuplicates{ lookupTable = newItemsLookupTable }else{ lookupTable = newItemsLookupTable[oldSection.uid] as? NSDictionary } for (item_index, item) in oldSection.items.enumerate(){ // UITableView and UICollectionView have issues with updates for items which are being moved or deleted, so skip generation of such changes as according to tests moved items get updated during transition let indexPath = NSIndexPath(forItem: item_index, inSection: section_index) if indexPathsForDeletedItems.contains(indexPath) || indexPathsForMovedItems.contains(indexPath){ continue } if let newIndexPath = lookupTable?[item.uid] as? NSIndexPath{ let newSection:CSMUpdatableCollectionSection = newSections[newIndexPath.section] let newItem:CSMUpdatableCollectionItem = newSection.items[newIndexPath.item] if item.uid != newItem.uid{ updates.append(CSMCollectionItemUpdate.updateWithType(.Reload, indexPath: indexPath, newIndexPath: nil, object: item.uid)) } } } } } completion(sections: newSections, updates: updates) } } }
mit
b4be2820b00cc9ddbb228f945fe94610
43.003704
296
0.50766
6.980024
false
false
false
false
xxxAIRINxxx/Cmg
Sources/CIImage+Cmg.swift
1
1221
// // CIImage+Convert.swift // Cmg // // Created by xxxAIRINxxx on 2016/02/20. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit import CoreImage extension CIImage { static func generate(_ uiImage: UIImage) -> CIImage? { var ciImage: CIImage? = uiImage.ciImage if ciImage == nil { guard let _cgImage = uiImage.cgImage else { return nil } ciImage = CIImage(cgImage: _cgImage) } return ciImage } func generateUIImage() -> UIImage { let cgImage = Context.ciContext.createCGImage(self, from: self.extent) return UIImage(cgImage: cgImage!, scale: UIScreen.main.scale, orientation: .up) } func generateUIImage(_ originalImage: UIImage) -> UIImage { var extent = self.extent if extent.origin.x < 0.0 || extent.origin.y < 0.0 { extent = CGRect(x: 0, y: 0, width: originalImage.size.width, height: originalImage.size.height) } let cgImage = Context.ciContext.createCGImage(self, from: extent) return UIImage(cgImage: cgImage!, scale: originalImage.scale, orientation: originalImage.imageOrientation) } }
mit
c5470c1c8bdc49baef5b93a06ab6c8d4
30.282051
114
0.633607
4.326241
false
false
false
false
leoMehlig/Charts
ChartsRealm/Classes/Data/RealmPieDataSet.swift
3
1541
// // RealmPieDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import Charts import Realm import Realm.Dynamic public class RealmPieDataSet: RealmBaseDataSet, IPieChartDataSet { public override func initialize() { self.valueTextColor = NSUIColor.whiteColor() self.valueFont = NSUIFont.systemFontOfSize(13.0) } // MARK: - Styling functions and accessors private var _sliceSpace = CGFloat(0.0) /// the space in pixels between the pie-slices /// **default**: 0 /// **maximum**: 20 public var sliceSpace: CGFloat { get { return _sliceSpace } set { var space = newValue if (space > 20.0) { space = 20.0 } if (space < 0.0) { space = 0.0 } _sliceSpace = space } } /// indicates the selection distance of a pie slice public var selectionShift = CGFloat(18.0) // MARK: - NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! RealmPieDataSet copy._sliceSpace = _sliceSpace copy.selectionShift = selectionShift return copy } }
apache-2.0
217e6dd5eed7068b135a66b44981bca8
21.347826
64
0.571707
4.545723
false
false
false
false
eure/ReceptionApp
iOS/ReceptionApp/Services/User.swift
1
3857
// // User.swift // ReceptionApp // // Created by Hiroshi Kimura on 8/27/15. // Copyright © 2016 eureka, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import CoreStore import SwiftyJSON // MARK: - User @objc final class User: NSManagedObject, ImportableUniqueObject { // MARK: Internal @NSManaged dynamic var id: Int64 @NSManaged dynamic var imageURL: String! @NSManaged dynamic var nameEn: String! @NSManaged dynamic var nameJa: String! @NSManaged dynamic var slackID: String! @NSManaged dynamic var slackName: String! @NSManaged dynamic var removed: Bool func matches(query: String) -> Bool { let strings = [ self.nameEn.lowercaseString, self.nameJa, self.nameKatana, self.nameHiragana ].lazy return strings.contains { self.separateSpace($0).lazy.contains { $0.hasPrefix(query) } } } // MARK: ImportableUniqueObject static var uniqueIDKeyPath: String { return "id" } var uniqueIDValue: NSNumber { get { return NSNumber(longLong: self.id) } set { self.id = newValue.longLongValue } } static func uniqueIDFromImportSource(source: JSON, inTransaction transaction: BaseDataTransaction) throws -> NSNumber? { return source["id"].number } func updateFromImportSource(source: JSON, inTransaction transaction: BaseDataTransaction) throws { self.id = source["id"].int64Value self.imageURL = source["face_image_url"].stringValue self.nameEn = source["name_en"].stringValue self.nameJa = source["name_ja"].stringValue self.slackID = source["slack_account_id"].stringValue self.slackName = source["slack_account_name"].stringValue self.removed = source["deleted"].boolValue } static func shouldUpdateFromImportSource(source: JSON, inTransaction transaction: BaseDataTransaction) -> Bool { return true } static func shouldInsertFromImportSource(source: JSON, inTransaction transaction: BaseDataTransaction) -> Bool { return true } // MARK: Private private lazy var nameKatana: String = self .separateSpace(self.nameEn) .joinWithSeparator(" ") .stringByTransliteratingRomajiToKatakana() private lazy var nameHiragana: String = self .separateSpace(self.nameEn) .joinWithSeparator(" ") .stringByTransliteratingRomajiToHiragana() private func separateSpace(string: String) -> [String] { return string.characters.split(" ").reverse().map(String.init) } }
mit
edc47bdfafe0cc509783f3dd5db42697
31.403361
124
0.660788
4.760494
false
false
false
false
summertian4/Lotusoot
Lotusoot/LotusootCoordinator.swift
1
2081
// // LotusootCoordinator.swift // LPDBusiness // // Created by 周凌宇 on 2017/4/21. // Copyright © 2017年 LPD. All rights reserved. // import UIKit @objc public class LotusootCoordinator: NSObject { @objc public static let sharedInstance = LotusootCoordinator() // lotus(协议) 和 lotusoot(实现) 表 @objc var lotusootMap: Dictionary = Dictionary<String, Any>() @objc private override init() { } /// 注册 Lotus 和 Lotusoot /// /// - Parameters: /// - lotusoot: lotusoot 对象。自动注册的 lotusoot 都必须是集成 NSObject,手动注册不做限制 /// - lotusName: lotus 协议名 @objc public static func register(lotusoot: Any, lotusName: String) { sharedInstance.lotusootMap.updateValue(lotusoot, forKey: lotusName) } /// 通过 lotus 名称 获取 lotusoot 实例 /// /// - Parameter lotus: lotus 协议名 /// - Returns: lotusoot 对象 @objc public static func lotusoot(lotus: String) -> Any? { return sharedInstance.lotusootMap[lotus] } /// 注册所有的 lotusoot /// /// - Parameter serviceMap: 自定义传入的字典 @objc public static func registerAll(serviceMap: Dictionary<String, String>) { for (lotus, lotusootName) in serviceMap { let classStringName = lotusootName let classType = NSClassFromString(classStringName) as? NSObject.Type if let type = classType { let lotusoot = type.init() register(lotusoot: lotusoot, lotusName: lotus) } } } /// 注册所有的 lotusoot /// 使用默认生成的 Lotusoot.plist @objc public static func registerAll() { let lotusPlistPath = Bundle.main.path(forResource: "Lotusoot", ofType: "plist") if let lotusPlistPath = lotusPlistPath { let map = NSDictionary(contentsOfFile: lotusPlistPath) registerAll(serviceMap: map as! Dictionary<String, String>) } } }
mit
fa72d35a86aa558e7e8caaf0140500f5
29.935484
87
0.615746
4.31982
false
false
false
false
powerytg/Accented
Accented/UI/Details/DetailComposerViewController.swift
1
7386
// // DetailComposerViewController.swift // Accented // // Comment and reply composer // // Created by Tiangong You on 5/20/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit import KMPlaceholderTextView class DetailComposerViewController: UIViewController, Composer, UITextViewDelegate { @IBOutlet weak var composerView: UIView! @IBOutlet weak var titleView: UIView! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var sendButton: UIButton! @IBOutlet weak var textView: KMPlaceholderTextView! @IBOutlet weak var progressView: UIView! @IBOutlet weak var successView: UIView! @IBOutlet weak var errorView: UIView! @IBOutlet weak var progressIndicator: UIActivityIndicatorView! @IBOutlet weak var composerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var errorLabelView: UILabel! @IBOutlet weak var progressLabelView: UILabel! @IBOutlet weak var successLabelView: UILabel! private var photo : PhotoModel private let cornerRadius : CGFloat = 20 private let statusViewPaddingTop : CGFloat = 20 private let titleBarMaskLayer = CAShapeLayer() private let titleBarRectCorner = UIRectCorner([.topLeft, .topRight]) private let transitionController = ComposerPresentationController() private var currentStatusView : UIView? override var nibName: String? { return "DetailComposerViewController" } init(photo : PhotoModel) { self.photo = photo super.init(nibName: "DetailComposerViewController", bundle: nil) modalPresentationStyle = .custom transitioningDelegate = transitionController } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() composerView.backgroundColor = ThemeManager.sharedInstance.currentTheme.composerBackground textView.placeholderColor = ThemeManager.sharedInstance.currentTheme.composerPlaceholderTextColor textView.textColor = ThemeManager.sharedInstance.currentTheme.composerTextColor successLabelView.textColor = ThemeManager.sharedInstance.currentTheme.titleTextColor errorLabelView.textColor = ThemeManager.sharedInstance.currentTheme.titleTextColor progressLabelView.textColor = ThemeManager.sharedInstance.currentTheme.titleTextColor progressIndicator.activityIndicatorViewStyle = ThemeManager.sharedInstance.currentTheme.loadingSpinnerStyle composerView.alpha = 0 composerView.layer.cornerRadius = cornerRadius textView.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) textView.becomeFirstResponder() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() updateTitlebarCorners() } private func updateTitlebarCorners() { let path = UIBezierPath(roundedRect: titleView.bounds, byRoundingCorners: titleBarRectCorner, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)) titleBarMaskLayer.path = path.cgPath titleView.layer.mask = titleBarMaskLayer } @IBAction func backButtonDidTap(_ sender: Any) { self.presentingViewController?.dismiss(animated: true, completion: nil) } @IBAction func sendButtonDidTap(_ sender: Any) { textView.isEditable = false sendButton.isEnabled = false transitionToStatusView(progressView) APIService.sharedInstance.addComment(self.photo.photoId, content: textView.text!, success: { [weak self] in self?.commentDidPost() }) { [weak self] (error) in self?.commentFailedPost() } } private func commentDidPost() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { self.transitionToStatusView(self.successView) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.presentingViewController?.dismiss(animated: true, completion: nil) } } } private func commentFailedPost() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { self.transitionToStatusView(self.errorView) self.textView.isEditable = true self.sendButton.isEnabled = (self.textView.text.lengthOfBytes(using: String.Encoding.utf8) != 0) } } private func showStatusView(_ view : UIView) { var f = view.frame f.origin.x = composerView.frame.origin.x + 8 f.origin.y = composerView.frame.origin.y + composerView.frame.size.height + statusViewPaddingTop view.frame = f if view == progressView { progressIndicator.startAnimating() } else { progressIndicator.stopAnimating() } currentStatusView = view UIView.animate(withDuration: 0.2) { view.alpha = 1 } } private func transitionToStatusView(_ view : UIView) { guard let previousStatusView = currentStatusView else { showStatusView(view) return } let tx : CGFloat = 30 var f = view.frame f.origin.x = composerView.frame.origin.x + 8 f.origin.y = composerView.frame.origin.y + composerView.frame.size.height + statusViewPaddingTop view.frame = f view.alpha = 0 view.transform = CGAffineTransform(translationX: tx, y: 0) UIView.animateKeyframes(withDuration: 0.4, delay: 0, options: [.calculationModeCubic], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.4, animations: { previousStatusView.transform = CGAffineTransform(translationX: -tx, y: 0) previousStatusView.alpha = 0 }) UIView.addKeyframe(withRelativeStartTime: 0.3, relativeDuration: 1, animations: { view.transform = CGAffineTransform.identity view.alpha = 1 }) }) { [weak self] (finished) in previousStatusView.transform = CGAffineTransform.identity self?.currentStatusView = view } } // MARK: - EntranceAnimation func entranceAnimationWillBegin() { composerView.transform = CGAffineTransform(translationX: 0, y: -composerHeightConstraint.constant) } func performEntranceAnimation() { composerView.transform = CGAffineTransform.identity composerView.alpha = 1 } func entranceAnimationDidFinish() { // Ignore } // MARK: - ExitAnimation func exitAnimationWillBegin() { composerView.resignFirstResponder() } func performExitAnimation() { self.view.transform = CGAffineTransform(translationX: 0, y: -composerHeightConstraint.constant) self.view.alpha = 0 } func exitAnimationDidFinish() { // Ignore } // MARK: - UITextViewDelegate func textViewDidChange(_ textView: UITextView) { sendButton.isEnabled = (textView.text.lengthOfBytes(using: String.Encoding.utf8) != 0) } }
mit
038f1a88ddf4f6f2df809b0407a51f82
34.849515
115
0.657955
5.335983
false
false
false
false
wosheesh/uchatclient
uchat/Model/Parse/ParseClient.swift
1
2619
// // ParseClient.swift // On the Map // // Created by Wojtek Materka on 21/01/2016. // Copyright © 2016 Wojtek Materka. All rights reserved. // import Foundation class ParseClient: RESTClient { // MARK: Properties // Singleton static let sharedInstance = ParseClient() private init() {} /* Shared session */ var session: NSURLSession = NSURLSession.sharedSession() // MARK: taskForHTTPMethod /// This if a flexible method for running Parse API HTTP requests func taskForHTTPMethod(method: String, httpMethod: String, parameters: [String : AnyObject]?, jsonBody: [String:AnyObject]?, handler: CompletionHandlerType) -> NSURLSessionDataTask { /* 1. Build the URL */ var urlString = String() if let mutableParameters = parameters { urlString = Constants.BaseURLSecure + method + escapedParameters(mutableParameters) } else { urlString = Constants.BaseURLSecure + method } let url = NSURL(string: urlString)! let request = NSMutableURLRequest(URL: url) /* 2. Build the HTTP Headers */ // Values for the AppID and APIKey request.addValue(Constants.ParseAppID, forHTTPHeaderField: Constants.ParseAppIDHTTPHeader) request.addValue(Constants.ParseMasterKey, forHTTPHeaderField: Constants.ParseMasterKeyHTTPHeader) //TODO: Check if Parse doesn't need "GET" to be specified in HttpBody if httpMethod != "GET" { request.HTTPMethod = httpMethod } if let jsonBody = jsonBody { do { request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(jsonBody, options: .PrettyPrinted) } } /* 3. Make the request */ let task = session.dataTaskWithRequest(request) { (data, result, error) in /* GUARD: Was there an error? */ guard (error == nil) else { self.processRESTErrorWithHandler(error!, handler: handler) return } /* GUARD: Was there any data returned? */ guard let data = data else { handler(Result.Failure(APIError.NoDataReceived)) return } /* 4. Parse the data and use the data (happens in completion handler) */ self.parseJSONWithCompletionHandler(data, handler: handler) } /* 5. Start the request */ task.resume() return task } }
mit
43580bc075cd01ea81744f2726109374
30.939024
186
0.587471
5.331976
false
false
false
false
remirobert/RRLocationManager
example/RRGeoLoc/RRLocationViewController.swift
1
1670
// // RRLocationViewController.swift // RRGeoLoc // // Created by Remi Robert on 11/05/15. // Copyright (c) 2015 Remi Robert. All rights reserved. // import UIKit import CoreLocation import MapKit class RRLocationViewController: UIViewController { lazy var navigationBar: UINavigationBar! = { let navBar = UINavigationBar() navBar.frame.origin = CGPointZero navBar.frame.size = CGSizeMake(UIScreen.mainScreen().bounds.size.width, 64) let navigationItems = UINavigationItem(title: "RRLocationController") navigationItems.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: ""), UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Save, target: self, action: "")] navigationItems.leftBarButtonItems = [UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "")] navBar.pushNavigationItem(navigationItems, animated: true) return navBar }() lazy var mapView: MKMapView! = { let mapView = MKMapView() mapView.frame.origin = CGPointZero mapView.frame.size = UIScreen.mainScreen().bounds.size return mapView }() lazy var searchBarController: UISearchController! = { let searchBar = UISearchController() return searchBar }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.view.addSubview(self.navigationBar) self.presentViewController(self.searchBarController, animated: true, completion: nil) } }
mit
2b2aef69c7cd612121361e33ebc5c06b
33.081633
140
0.694611
5.21875
false
false
false
false
wangyuanou/Coastline
Coastline/UI/PageViewController.swift
1
3029
// // PageViewController.swift // Coastline // // Created by 王渊鸥 on 2016/10/22. // Copyright © 2016年 王渊鸥. All rights reserved. // import UIKit open class CLPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { var pages:[UIViewController] = [] open var cycleMode:Bool = false open var onSelectPage:(Int) -> () = { _ in } open var animated = true open var currentPage:Int = 0 open func gotoNext() { if currentPage >= pages.count - 1 { currentPage = -1 } gotoPage(index: currentPage + 1) onSelectPage(currentPage) } open func gotoPrev() { if currentPage < 0 { currentPage = pages.count } gotoPage(index: currentPage - 1) onSelectPage(currentPage) } open func setPages(pages:[UIViewController]) { self.dataSource = self self.delegate = self self.pages = pages self.setViewControllers([pages[0]], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil) currentPage = 0 } open func gotoPage(index:Int) { if pages.count < 2 { return } let direction = index > currentPage ? UIPageViewControllerNavigationDirection.forward : UIPageViewControllerNavigationDirection.reverse if index < pages.count { let page = pages[index] OperationQueue.main.addOperation { [weak self] in guard let vc = self else { return } vc.setViewControllers([page], direction: direction, animated: vc.animated, completion: nil) } currentPage = index } } open func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if pages.count < 2 { return nil } if let index = pages.index(of: viewController) { if index == pages.count - 1 { if cycleMode { currentPage = 0 } return self.cycleMode ? pages.first : nil } currentPage = index + 1 return pages[index+1] } return nil } open func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if pages.count < 2 { return nil } if let index = pages.index(of: viewController) { if index == 0 { if cycleMode { currentPage = pages.count - 1 } return self.cycleMode ? pages.last : nil } currentPage = index - 1 return pages[index-1] } return nil } // open func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { // if let curPage = pendingViewControllers.first { // if let index = pages.index(of: curPage) { // onSelectPage(index) // } // } // } public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if let curPage = viewControllers?.first { if let index = pages.index(of: curPage) { onSelectPage(index) } } } }
mit
79b254a1ca60c092c3760c2dc988f1db
26.907407
194
0.70637
3.965789
false
false
false
false
JeffJin/ios9_notification
twilio/Services/Models/ViewModel/SearchResultsItemViewModel.swift
2
1674
// // SearchResultsItemViewModel.swift // ReactiveSwiftFlickrSearch // // Created by Colin Eberhardt on 18/07/2014. // Copyright (c) 2014 Colin Eberhardt. All rights reserved. // import Foundation // A ViewModel that backs an individual photo in a search result view. @objc public class SearchResultsItemViewModel: NSObject { dynamic var isVisible: Bool let title: String let imageUrl: NSURL var id: Int64 var note: String private let services: ViewModelServices init(appointment: AppointmentDto, services: ViewModelServices) { self.services = services title = appointment.description as String imageUrl = NSURL(fileURLWithPath: appointment.imageLink as! String)! id = appointment.id isVisible = false note = appointment.note as String super.init() // a signal that emits events when visibility changes let visibleStateChanged = RACObserve(self, "isVisible").skip(1) // filtered into visible and hidden signals let visibleSignal = visibleStateChanged.filter { $0.boolValue } let hiddenSignal = visibleStateChanged.filter { !$0.boolValue } // a signal that emits when an item has been visible for 1 second let fetchMetadata = visibleSignal.delay(1).takeUntil(hiddenSignal) fetchMetadata.subscribeNext { (next: AnyObject!) -> () in self.services.appointmentService.searchAppointments(123456, keywords:"keywords").subscribeNextAs { (appts: [AppointmentDto]) -> () in } } } }
apache-2.0
bcc8e54a972f75ee38cdbbc92c5c658a
31.192308
110
0.643369
5.027027
false
false
false
false
hackstock/instagram_clone
Instagram Clone/Instagram Clone/UIMainViewController.swift
1
7866
// // ViewController.swift // Instagram Clone // // Created by Edward Pie on 26/01/2017. // Copyright © 2017 Hubtel. All rights reserved. // import UIKit class UIMainViewController: UIViewController { var backgroundGradientLayer: CAGradientLayer! let logoImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named : "instagram_logo") imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() let introLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Log in to see photos and videos from your friends" label.font = UIFont.boldSystemFont(ofSize: 12) label.textColor = UIColor.white label.textAlignment = .center return label }() let footerView: UIView = { let view = UIView() view.backgroundColor = UIColor(hexString: "#9844A4FF") view.layer.shadowColor = UIColor(hexString: "#9844A4FF")?.cgColor view.layer.shadowOpacity = 1 view.layer.shadowRadius = 5 view.layer.shadowOffset = CGSize.zero view.translatesAutoresizingMaskIntoConstraints = false return view }() let signUpButton: UIButton = { let button = UIButton() button.setTitle("SIGN UP", for: .normal) button.setTitleColor(UIColor.white, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12) button.translatesAutoresizingMaskIntoConstraints = false return button }() let loginButton: UIButton = { let button = UIButton() button.setTitle("LOG IN", for: .normal) button.setTitleColor(UIColor.white, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12) button.translatesAutoresizingMaskIntoConstraints = false return button }() override func viewDidLoad() { super.viewDidLoad() self.initializeViews() self.applyLayoutConstraints() self.registerEventHandlers() } func initializeViews(){ self.backgroundGradientLayer = CAGradientLayer() self.backgroundGradientLayer.frame = self.view.bounds self.backgroundGradientLayer.colors = [ UIColor(red: 151/255, green: 48/255, blue: 123/255, alpha: 1).cgColor, UIColor(red: 129/255, green: 63/255, blue: 153/255, alpha: 1).cgColor] self.backgroundGradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) self.backgroundGradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) self.view.layer.addSublayer(self.backgroundGradientLayer) } func applyLayoutConstraints(){ self.view.addSubview(self.logoImageView) self.view.addSubview(self.introLabel) self.view.addSubview(self.footerView) self.footerView.addSubview(self.signUpButton) self.footerView.addSubview(self.loginButton) self.view.addConstraint(NSLayoutConstraint(item: self.logoImageView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0.0)) self.view.addConstraint(NSLayoutConstraint(item: self.logoImageView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 150.0)) self.view.addConstraint(NSLayoutConstraint(item: self.logoImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 300.0)) self.view.addConstraint(NSLayoutConstraint(item: self.logoImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 150.0)) self.view.addConstraint(NSLayoutConstraint(item: self.introLabel, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0.0)) self.view.addConstraint(NSLayoutConstraint(item: self.introLabel, attribute: .top, relatedBy: .equal, toItem: self.logoImageView, attribute: .bottom, multiplier: 1.0, constant: 10.0)) self.view.addConstraint(NSLayoutConstraint(item: self.introLabel, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1.0, constant: -5.0)) self.view.addConstraint(NSLayoutConstraint(item: self.introLabel, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1.0, constant: 5.0)) self.view.addConstraint(NSLayoutConstraint(item: self.footerView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0.0)) self.view.addConstraint(NSLayoutConstraint(item: self.footerView, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1.0, constant: 0.0)) self.view.addConstraint(NSLayoutConstraint(item: self.footerView, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1.0, constant: 0.0)) self.view.addConstraint(NSLayoutConstraint(item: self.footerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 60.0)) self.footerView.addConstraint(NSLayoutConstraint(item: self.signUpButton, attribute: .centerY, relatedBy: .equal, toItem: self.footerView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) self.view.addConstraint(NSLayoutConstraint(item: self.signUpButton, attribute: .left, relatedBy: .equal, toItem: self.footerView, attribute: .left, multiplier: 1.0, constant: 5.0)) self.view.addConstraint(NSLayoutConstraint(item: self.signUpButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100.0)) self.view.addConstraint(NSLayoutConstraint(item: self.signUpButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50.0)) self.footerView.addConstraint(NSLayoutConstraint(item: self.loginButton, attribute: .centerY, relatedBy: .equal, toItem: self.footerView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) self.view.addConstraint(NSLayoutConstraint(item: self.loginButton, attribute: .right, relatedBy: .equal, toItem: self.footerView, attribute: .right, multiplier: 1.0, constant: -5.0)) self.view.addConstraint(NSLayoutConstraint(item: self.loginButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100.0)) self.view.addConstraint(NSLayoutConstraint(item: self.loginButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50.0)) } func registerEventHandlers(){ self.signUpButton.addTarget(self, action: #selector(self.onSignUpButtonTapped), for: .touchUpInside) self.loginButton.addTarget(self, action: #selector(self.onLoginButtonTapped), for: .touchUpInside) } func onLoginButtonTapped(){ let loginViewController = UILoginViewController() self.present(loginViewController, animated: true, completion: nil) } func onSignUpButtonTapped(){ let url = URL(string: "https://www.instagram.com/accounts/login/") if #available(iOS 10.0, *) { UIApplication.shared.open(url!, options: [:], completionHandler: nil) }else{ UIApplication.shared.open(url!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
540398bc10bbc81d9cee422afb5a2734
52.503401
200
0.689765
4.443503
false
false
false
false
danstorre/CookIt
CookIt/CookIt/ConstantsGeneral.swift
1
1902
// // ConstantsGeneral.swift // CookIt // // Created by Daniel Torres on 3/24/17. // Copyright © 2017 Danieltorres. All rights reserved. // import Foundation struct ConstantsGeneral { struct Messages{ static let messageError = "sorry, please try again" } enum Cuisine : String { case emptyString = "" case african, chinese, japanese, korean, vietnamese, thai, indian, british, irish, french, italian, mexican, spanish, jewish, american, cajun, southern, greek, german, nordic, caribbean case middleEastern = "middle eastern" case easternEuropean = "eastern european" case latinAmerican = "latin american" } enum Diet: String { case emptyString = "" case pescetarian, vegan, paleo, primal, vegetarian case lactoVegetarian = "lacto vegetarian" case ovoVegetarian = "ovo vegetarian" } enum Intolerances: String { case emptyString = "" case dairy, egg, gluten, peanut, sesame, seafood, shellfish, soy, sulfite, wheat case treeNut = "tree nut" } enum TypeDish: String { case emptyString = "" case dessert, appetizer, salad, bread, breakfast, soup, beverage, sauce, drink case mainCourse = "main course" case sideDish = "side dish" } enum ImageSize: String { case xxs = "90x90" case xs = "240x150" case s = "312x150" case m = "312x231" case l = "480x360" case xl = "556x370" case xxl = "636x393" } } //Helper standalone methods func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> { var i = 0 return AnyIterator { let next = withUnsafeBytes(of: &i) { $0.load(as: T.self) } if next.hashValue != i { return nil } i += 1 return next } }
mit
49262280cf5a773f598ceaa124d70524
24.346667
193
0.586007
3.712891
false
false
false
false
lazersly/GithubzToGo
GithubzToGo/Repository.swift
1
516
// // Repository.swift // GithubzToGo // // Created by Brandon Roberts on 4/13/15. // Copyright (c) 2015 BR World. All rights reserved. // import Foundation struct Repository { var id : String var name : String var author : String var description : String var htmlURL : String init(id: String, name: String, author: String, description: String, htmlURL: String) { self.id = id self.name = name self.author = author self.description = description self.htmlURL = htmlURL } }
mit
8fe26b38cb623c623556ee0c8f834942
19.64
88
0.668605
3.685714
false
false
false
false
DrewKiino/Pacific
Pods/Atlantis/Atlantis/Source/Atlantis.swift
1
16189
// // Atlantis.swift // Atlantis // // Created by Andrew Aquino on 9/29/15. // Copyright © 2015 Andrew Aquino. All rights reserved. // import Foundation import UIKit public struct Atlantis { public enum LogLevel: Int { case Verbose = 5 case Info = 4 case Warning = 3 case Debug = 2 case Error = 1 case None = 0 } public struct Configuration { // Reserved Variables private struct Reserved { private static let ESCAPE = "\u{001b}[" private static let RESET_FG = ESCAPE + "fg;" // Clear any foreground color private static let RESET_BG = ESCAPE + "bg;" // Clear any background color private static let RESET = ESCAPE + ";" // Clear any foreground or background color } // Color Configurations public struct logColors { private static var _verbose: XCodeColor = XCodeColor.purple public static var verbose: XCodeColor? { get { return _verbose } set { if let newValue = newValue { _verbose = newValue } else { _verbose = XCodeColor.purple } } } private static var _info: XCodeColor = XCodeColor.green public static var info: XCodeColor? { get { return _info } set { if let newValue = newValue { _info = newValue } else { _info = XCodeColor.green } } } private static var _warning: XCodeColor = XCodeColor.yellow public static var warning: XCodeColor? { get { return _warning } set { if let newValue = newValue { _warning = newValue } else { _warning = XCodeColor.yellow } } } private static var _debug: XCodeColor = XCodeColor.blue public static var debug: XCodeColor? { get { return _debug} set { if let newValue = newValue { _debug = newValue } else { _debug = XCodeColor.blue } } } private static var _error: XCodeColor = XCodeColor.red public static var error: XCodeColor? { get { return _error} set { if let newValue = newValue { _error = newValue } else { _error = XCodeColor.red } } } } // configured log level public static var logLevel: LogLevel = .Verbose public static var hasWhiteBackground: Bool = false public static var hasColoredLogs: Bool = false public static var showExtraInfo: Bool = true } private struct Singleton { private static let LogQueue = dispatch_queue_create("Atlantis.LogQueue", nil) } public struct XCodeColor { private static let escape = "\u{001b}[" private static let resetFg = "\u{001b}[fg;" private static let resetBg = "\u{001b}[bg;" private static let reset = "\u{001b}[;" private var fg: (Int, Int, Int)? = nil private var bg: (Int, Int, Int)? = nil private mutating func whiteBG() -> XCodeColor { if Configuration.hasWhiteBackground { bg = (255, 255, 255) } return self } private mutating func forceWhiteBG() -> XCodeColor { bg = (255, 255, 255) return self } private func format() -> String { var format = "" if fg == nil && bg == nil { // neither set, return reset value return XCodeColor.reset } if let fg = fg { format += "\(XCodeColor.escape)fg\(fg.0),\(fg.1),\(fg.2);" } else { format += XCodeColor.resetFg } if let bg = bg { format += "\(XCodeColor.escape)bg\(bg.0),\(bg.1),\(bg.2);" } else { format += XCodeColor.resetBg } return format } public init(fg: (Int, Int, Int)? = nil, bg: (Int, Int, Int)? = nil) { self.fg = fg self.bg = bg } #if os(iOS) public init(fg: UIColor, bg: UIColor? = nil) { var redComponent: CGFloat = 0 var greenComponent: CGFloat = 0 var blueComponent: CGFloat = 0 var alphaComponent: CGFloat = 0 fg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent) self.fg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255)) if let bg = bg { bg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent) self.bg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255)) } else { self.bg = nil } } #else public init(fg: NSColor, bg: NSColor? = nil) { if let fgColorSpaceCorrected = fg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) { self.fg = (Int(fgColorSpaceCorrected.redComponent * 255), Int(fgColorSpaceCorrected.greenComponent * 255), Int(fgColorSpaceCorrected.blueComponent * 255)) } else { self.fg = nil } if let bg = bg, let bgColorSpaceCorrected = bg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) { self.bg = (Int(bgColorSpaceCorrected.redComponent * 255), Int(bgColorSpaceCorrected.greenComponent * 255), Int(bgColorSpaceCorrected.blueComponent * 255)) } else { self.bg = nil } } #endif public static let red: XCodeColor = { return XCodeColor(fg: (255, 0, 0)) }() public static let green: XCodeColor = { return XCodeColor(fg: (0, 255, 0)) }() public static let blue: XCodeColor = { // actual blue is 0, 0, 255 // dodger blue return XCodeColor(fg: (30, 144, 255)) }() public static let black: XCodeColor = { return XCodeColor(fg: (0, 0, 0)) }() public static let white: XCodeColor = { return XCodeColor(fg: (255, 255, 255)) }() public static let lightGrey: XCodeColor = { return XCodeColor(fg: (211, 211, 211)) }() public static let darkGrey: XCodeColor = { return XCodeColor(fg: (169, 169, 169)) }() public static let orange: XCodeColor = { return XCodeColor(fg: (255, 165, 0)) }() public static let whiteOnRed: XCodeColor = { return XCodeColor(fg: (255, 255, 255), bg: (255, 0, 0)) }() public static let darkGreen: XCodeColor = { return XCodeColor(fg: (0, 128, 0)) }() public static let purple: XCodeColor = { return XCodeColor(fg: (160, 32, 240)) }() public static let yellow: XCodeColor = { return XCodeColor(fg: (255, 255, 0)) }() } public struct Logger { private let logQueue = Singleton.LogQueue private typealias closure = () -> Void private typealias void = Void private static var maxCharCount: Int = 0 public init() {} private struct LogSettings { private var logLevel: LogLevel private var functionName: String private var fileName: String private var lineNumber: Int init(logLevel: LogLevel, _ functionName: String, _ fileName: String, _ lineNumber: Int) { self.logLevel = logLevel self.functionName = functionName self.fileName = fileName self.lineNumber = lineNumber } private func sourceString() -> String { if Configuration.showExtraInfo { let array = fileName.componentsSeparatedByString("/") var name: String = "" if let string = array.last { name = string } let string = "[\(name)/\(functionName)/line:\(lineNumber)]" return string + "\t" } return "" } } private static func acceptableLogLevel(logSettings: Atlantis.Logger.LogSettings) -> Bool { return logSettings.logLevel.rawValue <= Configuration.logLevel.rawValue } public let tap = Tap() public struct Tap { public func verbose<T>(arg: T, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) -> T { dispatch_async(Singleton.LogQueue) { let logSettings = LogSettings(logLevel: .Verbose, functionName,fileName, lineNumber) if Logger.acceptableLogLevel(logSettings) { Logger.log(arg, logSettings) } } return arg } public func info<T>(arg: T, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) -> T { dispatch_async(Singleton.LogQueue) { let logSettings = LogSettings(logLevel: .Info, functionName,fileName, lineNumber) if Logger.acceptableLogLevel(logSettings) { Logger.log(arg, logSettings) } } return arg } public func warning<T>(arg: T, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) -> T { dispatch_async(Singleton.LogQueue) { let logSettings = LogSettings(logLevel: .Warning, functionName,fileName, lineNumber) if Logger.acceptableLogLevel(logSettings) { Logger.log(arg, logSettings) } } return arg } public func debug<T>(arg: T, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) -> T { dispatch_async(Singleton.LogQueue) { let logSettings = LogSettings(logLevel: .Debug, functionName,fileName, lineNumber) if Logger.acceptableLogLevel(logSettings) { Logger.log(arg, logSettings) } } return arg } public func error<T>(arg: T, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) -> T { dispatch_async(Singleton.LogQueue) { let logSettings = LogSettings(logLevel: .Error, functionName,fileName, lineNumber) if Logger.acceptableLogLevel(logSettings) { Logger.log(arg, logSettings) } } return arg } } public func verbose<T>(args: T?..., functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { dispatch_async(logQueue) { let logSettings = LogSettings(logLevel: .Verbose, functionName,fileName, lineNumber) if Logger.acceptableLogLevel(logSettings) { for arg in args { Logger.log(arg, logSettings) } } } } public func info<T>(args: T?..., functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { dispatch_async(logQueue) { let logSettings = LogSettings(logLevel: .Info, functionName,fileName, lineNumber) if Logger.acceptableLogLevel(logSettings) { for arg in args { Logger.log(arg, logSettings) } } } } public func warning<T>(args: T?..., functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { dispatch_async(logQueue) { let logSettings = LogSettings(logLevel: .Warning, functionName,fileName, lineNumber) if Logger.acceptableLogLevel(logSettings) { for arg in args { Logger.log(arg, logSettings) } } } } public func debug<T>(args: T?..., functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { dispatch_async(logQueue) { let logSettings = LogSettings(logLevel: .Debug, functionName,fileName, lineNumber) if Logger.acceptableLogLevel(logSettings) { for arg in args { Logger.log(arg, logSettings) } } } } public func error<T>(args: T?..., functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { dispatch_async(logQueue) { let logSettings = LogSettings(logLevel: .Error, functionName,fileName, lineNumber) if Logger.acceptableLogLevel(logSettings) { for arg in args { Logger.log(arg, logSettings) } } } } private static func getEscapeString() -> String { return Configuration.Reserved.ESCAPE } private static func getResetString() -> String { return Configuration.Reserved.RESET } private static func getRGBString(logLevel: LogLevel) -> String { if Configuration.hasColoredLogs { switch logLevel { case .Verbose: return Configuration.logColors._verbose.whiteBG().format() case .Info: return Configuration.logColors._info.whiteBG().format() case .Warning: return Configuration.logColors._warning.whiteBG().format() case .Debug: return Configuration.logColors._debug.whiteBG().format() case .Error: return Configuration.logColors._error.whiteBG().format() case .None: break } } return "" } private static func getLogLevelString(logLevel: LogLevel) -> String { let level: String = "\(logLevel)" let tab1: String = ": " let tab2: String = ": " let tab3: String = ": " switch logLevel { case .Verbose: return level + tab1 case .Info: return level + tab2 case .Warning: return level + tab1 case .Debug: return level + tab3 case .Error: return level + tab3 case .None: return level } } private static func toPrettyJSONString(object: AnyObject) -> String? { do { if NSJSONSerialization.isValidJSONObject(object) { let data = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted) if let string = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { return "\n" + string } } throw NSError(domain: "", code: 404, userInfo: nil) } catch { return nil } } private static func log<T>(x: T?, _ logSettings: LogSettings) { let logLevel = logSettings.logLevel var jsonString: String? = nil switch x { case .Some(is NSArray): jsonString = toPrettyJSONString(x as! NSArray) ?? "\n\(x!)"; break case .Some(is NSDictionary): jsonString = toPrettyJSONString(x as! NSDictionary) ?? "\n\(x!)"; break case .Some(is [String: AnyObject]): jsonString = toPrettyJSONString(x as! [String: AnyObject]) ?? "\n\(x!)"; break default: break } var unwrap: Any = x ?? "nil" unwrap = jsonString ?? addDash(unwrap) let color = getRGBString(logLevel) let reset = getResetString() let level = getLogLevelString(logLevel) let source = logSettings.sourceString() let string = "\(unwrap)" let coloredString: String = color + string + reset let log: String = "\(color)\(level)\(reset)\(source)" let prettyLog: String = calculateLegibleWhitespace(log, endString: coloredString, logLevel: logLevel) dispatch_async(dispatch_get_main_queue()) { print(prettyLog) } } private static func addDash(x: Any) -> String { let string = "\(x)" if Configuration.showExtraInfo { return "- " + string } return string } private static func calculateLegibleWhitespace(startString: String, endString: String, logLevel: LogLevel) -> String { let charCount = startString.characters.count maxCharCount = maxCharCount > charCount ? maxCharCount : charCount var whitespace: String = "" var i = 0 switch logLevel { case .Info: i = 3; break case .Error: i = 4; break default: break } for var j = i; j < maxCharCount - charCount; j++ { whitespace += " " } let string: String = startString + whitespace + endString return string } } }
mit
9bb1a629ff6f752f31e93ad2efaa8a16
30.311412
164
0.578391
4.617228
false
false
false
false
workinghard/Cube4Fun
Cube4Fun/src/AppDelegate.swift
1
7843
// // AppDelegate.swift // Cube4Fun // // Created by Nikolai Rinas on 27.03.15. // Copyright (c) 2015 Nikolai Rinas. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import Cocoa var _animationsWindow: NSWindow = NSWindow() var _cubeWindow: NSWindow = NSWindow() var _prefWindow: NSWindow = NSWindow() var __animations: Animations = Animations() var __prefData: Preferences = Preferences() @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSTextFieldDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var animationsWindow: NSWindow! @IBOutlet weak var preferencesWindow: NSWindow! @IBOutlet weak var myMenu: NSMenu! @IBOutlet weak var levelInd: NSProgressIndicator! @IBOutlet weak var ipAddr: NSTextField! @IBOutlet weak var port: NSTextField! @IBOutlet weak var passwd: NSTextField! @IBOutlet weak var waitAnim: NSProgressIndicator! func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application _animationsWindow = animationsWindow _cubeWindow = window _prefWindow = preferencesWindow //__animations.initialize() port.stringValue = String(__prefData.portNR()) ipAddr.stringValue = __prefData.ipAddr() passwd.stringValue = String(__prefData.passwdStr()) if CubeNetworkObj.connected() { showConnActive(true) }else{ showConnActive(false) } } func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply { CubeNetworkObj.closeConnection() return NSApplicationTerminateReply.TerminateNow } @IBAction func saveDocument(sender: AnyObject) { let mySavePanel: NSSavePanel = NSSavePanel() mySavePanel.allowedFileTypes = ["plist"] mySavePanel.beginWithCompletionHandler { (result: Int) -> Void in if result == NSFileHandlingPanelOKButton { let exportedFileURL = mySavePanel.URL // Save the data. What you do depends on your app. let myAnimArray: NSMutableArray = NSMutableArray() myAnimArray.addObjectsFromArray(__animations.getAnimations()) myAnimArray.writeToURL(exportedFileURL!, atomically: true) //let myAnimation: NSDictionary = NSDictionary(dictionary: __animations.getAnimations()) // Don't just paste this code in your app as your app // probably doesn't have a createPDF() method. self.createPDF(exportedFileURL) } } // End block print("save pressed") } @IBAction func openDocument(sender: AnyObject) { let myOpenPanel: NSOpenPanel = NSOpenPanel() myOpenPanel.allowedFileTypes = ["plist"] myOpenPanel.beginWithCompletionHandler { (result: Int) -> Void in if result == NSFileHandlingPanelOKButton { let importedFileURL = myOpenPanel.URL //let myAnimationsDict: NSMutableDictionary = NSMutableDictionary(contentsOfURL: importedFileURL!)! let myAnimArray: NSMutableArray = NSMutableArray(contentsOfURL: importedFileURL!)! __animations.loadAnimations(myAnimArray) } } // End block } @IBAction func openPreferences(send: AnyObject) { preferencesWindow.setIsVisible(true) } @IBAction func testIPConnection(send: AnyObject) { //println("TestIP Button clicked") if CubeNetworkObj.connected() { CubeNetworkObj.closeConnection() } if CubeNetworkObj.openConnection(__prefData.ipAddr(), port: UInt32(__prefData.portNR()), passwd: __prefData.passwdStr()) { showConnActive(true) }else{ showConnActive(false) } } func showConnActive(active: Bool) { if active { levelInd.doubleValue = 100.0 }else{ levelInd.doubleValue = 0.0 } } func validIPAddress(ipaddr: String) -> Bool { var valid: Bool = false let validIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" if ipaddr != "" { if (ipaddr.rangeOfString(validIpAddressRegex, options: .RegularExpressionSearch) != nil) { valid = true; } } return valid } func validPortNr(portNr: Int) -> Bool { var valid: Bool = false if portNr < 65536 && portNr > 0 { valid = true } return valid //^(6553[0-5]|655[0-2]\d|65[0-4]\d\d|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)$ } func validPasswdStr(myPasswd: String) -> Bool { var valid: Bool = false if myPasswd.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 8 { valid = true } return valid } override func controlTextDidChange(obj: NSNotification) { let myField: NSTextField = obj.object as! NSTextField if myField.identifier == "IPADDR_FIELD" { if validIPAddress(myField.stringValue) { __prefData.setIPAddr(myField.stringValue) print("Changing ip address field") } } if myField.identifier == "PORTNR_FIELD" { if validPortNr(myField.integerValue) { __prefData.setPortNr(myField.integerValue) print("Changing port number") } } if myField.identifier == "PASSWD_FIELD" { if validPasswdStr(myField.stringValue) { __prefData.setPasswd(myField.stringValue) print("Changing password") } } } @IBAction func cmdCopyPressed(send: AnyObject) { __animations.copyDisplayedFrame() } @IBAction func cmdPastePressed(send: AnyObject) { __animations.pasteDisplayedFrame() _gameView.updateLEDFrame() // Send updated frame __animations.sendFrame() } @IBAction func clearLEDs(send: AnyObject) { // Remove from Memory __animations.clearLEDColor() // Update visual _gameView.updateLEDFrame() // Update on a hardware __animations.sendFrame() } @IBAction func cmdInsertPressed(send: AnyObject) { // Insert one new frame at the current position __animations.insertDisplFrame() // Update visual _gameView.updateLEDFrame() _gameView.updateButtonVisibility() // Update on a hardware __animations.sendFrame() } @IBAction func cmdDeletePressed(send: AnyObject) { // Check if we have more than one frame if __animations.getAnimationFrameCount() > 1 { __animations.deleteDisplFrame() // Update visual _gameView.updateLEDFrame() _gameView.updateButtonVisibility() // Update on a hardware __animations.sendFrame() } } }
gpl-3.0
3582665a49c9bcbbea303478663a769f
34.977064
142
0.610991
4.741838
false
false
false
false