repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
TinyCrayon/TinyCrayon-iOS-SDK
TCMask/MaskViewWizard.swift
1
5738
// // MaskViewWizard.swift // TinyCrayon // // Created by Xin Zeng on 5/25/16. // // import UIKit class MaskViewWizard : NSObject { unowned var controller: MaskViewController var view: UIView init(controller: MaskViewController) { self.controller = controller self.view = UIView(frame: controller.view.frame) super.init() view.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] controller.view.addSubview(view) view.isHidden = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTapped(_:))) view.addGestureRecognizer(tapGesture) initMaskWizard() } func present() { view.alpha = 0 view.isHidden = false UIView.animate(withDuration: 0.5, animations:{ self.view.alpha = 1 }, completion: { success in }) } func makeTransition() { // if (status == nil) { // return // } // // switch status! { // case .mask: // break // case .hairBrush: // adjustHairBrushWizard() // break // } } func initMaskWizard() { view.backgroundColor = UIColor(white: 0, alpha: 0.75) let container = UIView(frame: view.bounds) let hints = [(controller.localized("Tips-Draw"), "gesture_tap"), (controller.localized("Tips-Zoom"), "gesture_pinch"), (controller.localized("Tips-Move"), "gesture_twofingertap")] var top: CGFloat = 0 for (text, imgName) in hints { let label = UILabel(frame: CGRect(x: 0, y: 0, width: container.width, height: 30)) label.center = container.center label.text = text label.top = top label.textAlignment = NSTextAlignment.center label.textColor = UIColor.white label.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth] container.addSubview(label) let image = UIImage(named: imgName, in: Bundle(for: type(of: self)), compatibleWith: nil)!.withRenderingMode(UIImage.RenderingMode.alwaysTemplate) let imageView = UIImageView(image: image) imageView.tintColor = UIColor.white imageView.center = container.center imageView.top = label.bottom imageView.autoresizingMask = [UIView.AutoresizingMask.flexibleLeftMargin, UIView.AutoresizingMask.flexibleRightMargin] container.addSubview(imageView) top = imageView.bottom + 20 } // let linkButton = UIButton(frame: CGRect(x: 0, y: 0, width: 150, height: 50)) // let linkButtonTitle = NSAttributedString(string:"view tutorial", attributes: // [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSForegroundColorAttributeName: UIColor(red: 0.5, green: 0.5, blue: 1, alpha: 1)]) // linkButton.setAttributedTitle(linkButtonTitle, for: UIControlState()) // linkButton.top = top // linkButton.left = (container.width - linkButton.width) / 2 // linkButton.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin] // linkButton.addTarget(self, action: #selector(MaskViewWizard.viewTutorialButtonTapped(_:)), for: UIControlEvents.touchUpInside) // container.addSubview(linkButton) container.height = container.subviews.last!.bottom container.center = view.center container.autoresizingMask = [UIView.AutoresizingMask.flexibleTopMargin, UIView.AutoresizingMask.flexibleBottomMargin, UIView.AutoresizingMask.flexibleWidth] self.view.addSubview(container) } func presentHairBrushWizard() { let title = UILabel(frame: CGRect(x: 0, y: self.view.height / 6, width: self.view.width, height: 30)) title.text = "Select hair and fur using hair brush" title.textAlignment = NSTextAlignment.center title.textColor = UIColor.white title.autoresizingMask = [UIView.AutoresizingMask.flexibleBottomMargin, UIView.AutoresizingMask.flexibleTopMargin, UIView.AutoresizingMask.flexibleWidth] view.addSubview(title) let paintHint = UILabel(frame: CGRect(x: 0, y: 0, width: 120, height: 50)) paintHint.text = "Paint on edges to make selections" view.addSubview(paintHint) let cleanHint = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 50)) cleanHint.text = "Draw on edges to clean unwanted region" view.addSubview(cleanHint) let autoHint = UILabel(frame: CGRect(x: 0, y: 0, width: 140, height: 50)) autoHint.text = "Color along edges to make auto selection" view.addSubview(autoHint) } @objc func viewTapped(_ sender: UITapGestureRecognizer) { UIView.animate(withDuration: 0.5, animations:{ self.view.alpha = 0 }, completion: { success -> () in self.view.isHidden = true }) } func viewTutorialButtonTapped(_ sender: UIButton) { // let urlString = self.status == MaskViewWizardType.mask ? "https://d2iufzlyjlomo7.cloudfront.net/tutorial_masking.html" : "https://d2iufzlyjlomo7.cloudfront.net/tutorial_hairbrush.html" // let webViewController = WebViewController(nibName: "WebViewController", bundle: nil) // webViewController.setup(urlString) // controller.present(webViewController, animated: true, completion: { // }) } }
mit
1500c6ac2a32c2de49633a56d0549bd6
41.191176
194
0.635239
4.594075
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/01121-swift-derivedconformance-deriveequatable.swift
11
600
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse private class B<C> { init(c: C) { extension NSSet { convenience init<T>(array: Array<T>) { } } var e: Int -> Int = { return $0t = { c, b in }(f, e) enum A : String { case b = "" } if c == .b { } clas }()
apache-2.0
d51de6700d1eba6ab9046394a3118514
25.086957
78
0.673333
3.191489
false
false
false
false
kylebshr/Linchi
Linchi/URLRouter/URLPattern.swift
2
2887
// // URLPattern.swift // Linchi // /** Describes a component of a `URLPattern`. Either raw text or regex. __Example:__ The url `"users/∆: [a-zA-Z]+/profile/"` will be represented as an array of these `URLPatternElement`: `[Text("users"), Regex("[a-zA-Z]+"), Text("profile")]` Because the urls are separated by "/", the regexes or raw strings CANNOT contain any "/". */ private enum URLPatternElement { case Text(String) case Parameter(name: String, pattern: RegEx) /// Returns true iff the given string matches the text or regex func matches(s: String) -> Bool { switch self { case .Text(let text) : return text == s case .Parameter(_, let regex): return regex.matches(s) } } } /** A URLPattern is a set of URL capable of capturing parameters. __Example__ `let urlPattern = URLPattern("users/∆: name=[a-zA-Z]+/profile")` `let match = urlPattern.matches("users/anna/profile")` `// match.0 == true; match.1 == ["name": "anna"]` __Rules for the initialization string:__ - Trailing or leading slashes don't matter - Between slashes, there is either: - raw text - a regex prefixed by "∆: " (with a trailing space!) - No slashes in the regex */ internal struct URLPattern { private let elements : [URLPatternElement] internal init?(str: String) { var tmpPattern = [URLPatternElement]() let components = str.split("/") for component in components { if component.hasPrefix("∆: ") { let withoutDelta = component.removeFirst(3) guard let (name, regexString) = withoutDelta.splitOnce("=") else { return nil } guard let reg = RegEx(regexString) else { return nil } tmpPattern.append(.Parameter(name: name, pattern: reg)) } else { tmpPattern.append(.Text(component)) } } self.elements = tmpPattern } /** Returns: `(true, params)` iff the given url matches the URLPattern `(false, nil)` otherwise */ internal func matches(url: String) -> (matches: Bool, params: [String: String]) { let split1 = url.splitOnce("?") let withoutGETParameters = split1 == nil ? url : split1!.0 let components = withoutGETParameters.split("/") guard components.count == elements.count else { return (false, [:]) } var params : [String: String] = [:] for i in 0 ..< components.count { let string = components[i] let pattern = elements[i] guard pattern.matches(string) else { return (false, [:]) } if case .Parameter(let name, _) = pattern { params[name] = string } } return (true, params) } }
mit
96237501fa82bdf923b3456086235666
25.657407
95
0.573463
4.136494
false
false
false
false
sgurnoor/FunFacts
FunFacts/ViewController.swift
1
1734
// // ViewController.swift // FunFacts // // Created by Gurnoor Singh on 11/11/15. // Copyright © 2015 Cyberician. All rights reserved. // Modified upon Teamtreehouse.org's iOS tutorial. // import UIKit class ViewController: UIViewController { // initialisation of Fact Book and Color Wheel let factBook = FactBook() let colorWheel = ColorWheel() // initialisation of storage to avoid duplication of color and facts. var colorStorage = UIColor(red: 90/255.0, green: 187/255.0, blue: 181/255.0, alpha: 1.0) var factStorage = "Hello! It's me" // Label and button outlets @IBOutlet weak var funFactLabel: UILabel! @IBOutlet weak var funFactButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // initial label funFactLabel.text = factBook.randomFact() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // action initiated on clicking the button @IBAction func showFunFact() { //choosing a random property var randomColor = colorWheel.randomColor() var randomFact = factBook.randomFact() //checking with storage while (colorStorage == randomColor) { randomColor = colorWheel.randomColor() } while (factStorage == randomFact) { randomFact = factBook.randomFact() } //apply properties to view view.backgroundColor = randomColor funFactButton.tintColor = randomColor funFactLabel.text = randomFact //update storage colorStorage = randomColor factStorage = randomFact } }
mit
a7ee5eea3cccdb6e0f7ed0f7622656c3
25.661538
92
0.627236
4.722071
false
false
false
false
chromium/chromium
ios/chrome/test/swift_interop/namespace/namespace_xctest.swift
7
1773
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Namespace import UIKit import XCTest class NamespaceTest: XCTestCase { func testNamespaceClass() throws { // Non-namespaced class. let goat = Goat() XCTAssertEqual(goat.GetValue(), 7, "Values don't match") // Namespaced class with the same type name, verify the namespaced one // is the one created. let spaceGoat = space.Goat() spaceGoat.DoNothing() XCTAssertEqual(spaceGoat.GetValue(), 42, "Values don't match") } func testNamespaceTypedEnum_noCompile() throws { // namespaced typed enum. // DOESN'T COMPILE: 'Vehicle' has no member 'boat' (it does). // let vehicle = space.Vehicle.boat } func testNamespaceClassEnum() throws { // Use a namespaced class enum. // Compiles ONLY with Swift greater than version 5.6 (Xcode 13.3). let animal = space.Animal.goat XCTAssertEqual(animal, space.Animal.goat, "values don't match") XCTAssertNotEqual(animal, space.Animal.dog, "values don't match") } func testNestedNamespace() throws { let goat = outer.inner.NestedGoat() XCTAssertEqual(goat.GetValue(), 50, "values don't match") } func testClassEnumInOutNamespace_crashes() throws { // Test the enum class not in a namespace. let food = SameNameEnum.watermelon XCTAssertNotEqual(food, SameNameEnum.orange, "something broke") // Test the enum class in a namespace. // CRASHES in XCTAssertNotEqual() // In progress CL: https://github.com/apple/swift/pull/42494. // let moreFood = sameName.SameNameEnum.watermelon; // XCTAssertNotEqual(moreFood, sameName.SameNameEnum.orange, "something broke") } }
bsd-3-clause
3e1ffb2ac461393b01b1905705662e38
31.833333
83
0.704456
4.047945
false
true
false
false
ephread/Instructions
Sources/Instructions/Helpers/Internal/Extensions/UIView+Layout.swift
2
2806
// Copyright (c) 2017-present Frédéric Maquin <[email protected]> and contributors. // Licensed under the terms of the MIT License. import UIKit internal extension UIView { var isOutOfSuperview: Bool { let insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) return isOutOfSuperview(consideringInsets: insets) } func isOutOfSuperview(consideringInsets insets: UIEdgeInsets) -> Bool { guard let superview = self.superview else { return true } let isInBounds = frame.origin.x >= insets.left && frame.origin.y >= insets.top && (frame.origin.x + frame.size.width) <= (superview.frame.size.width - insets.right) && (frame.origin.y + frame.size.height) <= (superview.frame.size.height - insets.bottom) return !isInBounds } func fillSuperview(insets: UIEdgeInsets) { guard let superview = superview else { print(ErrorMessage.Warning.noParent) return } NSLayoutConstraint.activate([ topAnchor.constraint(equalTo: superview.topAnchor, constant: insets.top), bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: -insets.bottom), leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: insets.left), trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: -insets.right) ]) } func fillSuperview() { fillSuperviewVertically() fillSuperviewHorizontally() } func fillSuperviewVertically() { NSLayoutConstraint.activate(makeConstraintToFillSuperviewVertically()) } func fillSuperviewHorizontally() { NSLayoutConstraint.activate(makeConstraintToFillSuperviewHorizontally()) } func makeConstraintToFillSuperviewVertically() -> [NSLayoutConstraint] { guard let superview = superview else { print(ErrorMessage.Warning.noParent) return [] } return [ topAnchor.constraint(equalTo: superview.topAnchor), bottomAnchor.constraint(equalTo: superview.bottomAnchor) ] } func makeConstraintToFillSuperviewHorizontally() -> [NSLayoutConstraint] { guard let superview = superview else { print(ErrorMessage.Warning.noParent) return [] } return [ leadingAnchor.constraint(equalTo: superview.leadingAnchor), trailingAnchor.constraint(equalTo: superview.trailingAnchor) ] } func preparedForAutoLayout() -> Self { translatesAutoresizingMaskIntoConstraints = false return self } }
mit
6cac17442bf5b3b4e10f447cb3b493ea
31.988235
97
0.626248
5.330798
false
false
false
false
khizkhiz/swift
stdlib/public/core/String.swift
1
33532
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // FIXME: complexity documentation for most of methods on String is ought to be // qualified with "amortized" at least, as Characters are variable-length. /// An arbitrary Unicode string value. /// /// Unicode-Correct /// =============== /// /// Swift strings are designed to be Unicode-correct. In particular, /// the APIs make it easy to write code that works correctly, and does /// not surprise end-users, regardless of where you venture in the /// Unicode character space. For example, the `==` operator checks /// for [Unicode canonical /// equivalence](http://www.unicode.org/glossary/#deterministic_comparison), /// so two different representations of the same string will always /// compare equal. /// /// Locale-Insensitive /// ================== /// /// The fundamental operations on Swift strings are not sensitive to /// locale settings. That's because, for example, the validity of a /// `Dictionary<String, T>` in a running program depends on a given /// string comparison having a single, stable result. Therefore, /// Swift always uses the default, /// un-[tailored](http://www.unicode.org/glossary/#tailorable) Unicode /// algorithms for basic string operations. /// /// Importing `Foundation` endows swift strings with the full power of /// the `NSString` API, which allows you to choose more complex /// locale-sensitive operations explicitly. /// /// Value Semantics /// =============== /// /// Each string variable, `let` binding, or stored property has an /// independent value, so mutations to the string are not observable /// through its copies: /// /// var a = "foo" /// var b = a /// b.append("bar") /// print("a=\(a), b=\(b)") // a=foo, b=foobar /// /// Strings use Copy-on-Write so that their data is only copied /// lazily, upon mutation, when more than one string instance is using /// the same buffer. Therefore, the first in any sequence of mutating /// operations may cost `O(N)` time and space, where `N` is the length /// of the string's (unspecified) underlying representation. /// /// Views /// ===== /// /// `String` is not itself a collection of anything. Instead, it has /// properties that present the string's contents as meaningful /// collections: /// /// - `characters`: a collection of `Character` ([extended grapheme /// cluster](http://www.unicode.org/glossary/#extended_grapheme_cluster)) /// elements, a unit of text that is meaningful to most humans. /// /// - `unicodeScalars`: a collection of `UnicodeScalar` ([Unicode /// scalar /// values](http://www.unicode.org/glossary/#unicode_scalar_value)) /// the 21-bit codes that are the basic unit of Unicode. These /// values are equivalent to UTF-32 code units. /// /// - `utf16`: a collection of `UTF16.CodeUnit`, the 16-bit /// elements of the string's UTF-16 encoding. /// /// - `utf8`: a collection of `UTF8.CodeUnit`, the 8-bit /// elements of the string's UTF-8 encoding. /// /// Growth and Capacity /// =================== /// /// When a string's contiguous storage fills up, new storage must be /// allocated and characters must be moved to the new storage. /// `String` uses an exponential growth strategy that makes `append` a /// constant time operation *when amortized over many invocations*. /// /// Objective-C Bridge /// ================== /// /// `String` is bridged to Objective-C as `NSString`, and a `String` /// that originated in Objective-C may store its characters in an /// `NSString`. Since any arbitrary subclass of `NSString` can /// become a `String`, there are no guarantees about representation or /// efficiency in this case. Since `NSString` is immutable, it is /// just as though the storage was shared by some copy: the first in /// any sequence of mutating operations causes elements to be copied /// into unique, contiguous storage which may cost `O(N)` time and /// space, where `N` is the length of the string representation (or /// more, if the underlying `NSString` has unusual performance /// characteristics). public struct String { /// An empty `String`. public init() { _core = _StringCore() } public // @testable init(_ _core: _StringCore) { self._core = _core } public // @testable var _core: _StringCore } extension String { @warn_unused_result public // @testable static func _fromWellFormedCodeUnitSequence< Encoding: UnicodeCodec, Input: Collection where Input.Iterator.Element == Encoding.CodeUnit >( encoding: Encoding.Type, input: Input ) -> String { return String._fromCodeUnitSequence(encoding, input: input)! } @warn_unused_result public // @testable static func _fromCodeUnitSequence< Encoding: UnicodeCodec, Input: Collection where Input.Iterator.Element == Encoding.CodeUnit >( encoding: Encoding.Type, input: Input ) -> String? { let (stringBufferOptional, _) = _StringBuffer.fromCodeUnits(input, encoding: encoding, repairIllFormedSequences: false) if let stringBuffer = stringBufferOptional { return String(_storage: stringBuffer) } else { return nil } } @warn_unused_result public // @testable static func _fromCodeUnitSequenceWithRepair< Encoding: UnicodeCodec, Input: Collection where Input.Iterator.Element == Encoding.CodeUnit >( encoding: Encoding.Type, input: Input ) -> (String, hadError: Bool) { let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits(input, encoding: encoding, repairIllFormedSequences: true) return (String(_storage: stringBuffer!), hadError) } } extension String : _BuiltinUnicodeScalarLiteralConvertible { @effects(readonly) public // @testable init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value))) } } extension String : UnicodeScalarLiteralConvertible { /// Create an instance initialized to `value`. public init(unicodeScalarLiteral value: String) { self = value } } extension String : _BuiltinExtendedGraphemeClusterLiteralConvertible { @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount))) } } extension String : ExtendedGraphemeClusterLiteralConvertible { /// Create an instance initialized to `value`. public init(extendedGraphemeClusterLiteral value: String) { self = value } } extension String : _BuiltinUTF16StringLiteralConvertible { @effects(readonly) @_semantics("string.makeUTF16") public init( _builtinUTF16StringLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { self = String( _StringCore( baseAddress: OpaquePointer(start), count: Int(utf16CodeUnitCount), elementShift: 1, hasCocoaBuffer: false, owner: nil)) } } extension String : _BuiltinStringLiteralConvertible { @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { if Bool(isASCII) { self = String( _StringCore( baseAddress: OpaquePointer(start), count: Int(utf8CodeUnitCount), elementShift: 0, hasCocoaBuffer: false, owner: nil)) } else { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount))) } } } extension String : StringLiteralConvertible { /// Create an instance initialized to `value`. public init(stringLiteral value: String) { self = value } } extension String : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { var result = "\"" for us in self.unicodeScalars { result += us.escaped(asASCII: false) } result += "\"" return result } } extension String { /// Returns the number of code units occupied by this string /// in the given encoding. @warn_unused_result func _encodedLength< Encoding: UnicodeCodec >(encoding: Encoding.Type) -> Int { var codeUnitCount = 0 let output: (Encoding.CodeUnit) -> Void = { _ in codeUnitCount += 1 } self._encode(encoding, output: output) return codeUnitCount } // FIXME: this function does not handle the case when a wrapped NSString // contains unpaired surrogates. Fix this before exposing this function as a // public API. But it is unclear if it is valid to have such an NSString in // the first place. If it is not, we should not be crashing in an obscure // way -- add a test for that. // Related: <rdar://problem/17340917> Please document how NSString interacts // with unpaired surrogates func _encode< Encoding: UnicodeCodec >(encoding: Encoding.Type, output: (Encoding.CodeUnit) -> Void) { return _core.encode(encoding, output: output) } } #if _runtime(_ObjC) /// Compare two strings using the Unicode collation algorithm in the /// deterministic comparison mode. (The strings which are equivalent according /// to their NFD form are considered equal. Strings which are equivalent /// according to the plain Unicode collation algorithm are additionally ordered /// based on their NFD.) /// /// See Unicode Technical Standard #10. /// /// The behavior is equivalent to `NSString.compare()` with default options. /// /// - returns: /// * an unspecified value less than zero if `lhs < rhs`, /// * zero if `lhs == rhs`, /// * an unspecified value greater than zero if `lhs > rhs`. @_silgen_name("swift_stdlib_compareNSStringDeterministicUnicodeCollation") public func _stdlib_compareNSStringDeterministicUnicodeCollation( lhs: AnyObject, _ rhs: AnyObject ) -> Int32 #endif extension String : Equatable { } @warn_unused_result public func ==(lhs: String, rhs: String) -> Bool { if lhs._core.isASCII && rhs._core.isASCII { if lhs._core.count != rhs._core.count { return false } return _swift_stdlib_memcmp( lhs._core.startASCII, rhs._core.startASCII, rhs._core.count) == 0 } return lhs._compareString(rhs) == 0 } extension String : Comparable { } extension String { #if _runtime(_ObjC) /// This is consistent with Foundation, but incorrect as defined by Unicode. /// Unicode weights some ASCII punctuation in a different order than ASCII /// value. Such as: /// /// 0022 ; [*02FF.0020.0002] # QUOTATION MARK /// 0023 ; [*038B.0020.0002] # NUMBER SIGN /// 0025 ; [*038C.0020.0002] # PERCENT SIGN /// 0026 ; [*0389.0020.0002] # AMPERSAND /// 0027 ; [*02F8.0020.0002] # APOSTROPHE /// /// - Precondition: Both `self` and `rhs` are ASCII strings. @warn_unused_result public // @testable func _compareASCII(rhs: String) -> Int { var compare = Int(_swift_stdlib_memcmp( self._core.startASCII, rhs._core.startASCII, min(self._core.count, rhs._core.count))) if compare == 0 { compare = self._core.count - rhs._core.count } // This efficiently normalizes the result to -1, 0, or 1 to match the // behavior of NSString's compare function. return (compare > 0 ? 1 : 0) - (compare < 0 ? 1 : 0) } #endif /// Compares two strings with the Unicode Collation Algorithm. @warn_unused_result @inline(never) @_semantics("stdlib_binary_only") // Hide the CF/ICU dependency public // @testable func _compareDeterministicUnicodeCollation(rhs: String) -> Int { // Note: this operation should be consistent with equality comparison of // Character. #if _runtime(_ObjC) return Int(_stdlib_compareNSStringDeterministicUnicodeCollation( _bridgeToObjectiveCImpl(), rhs._bridgeToObjectiveCImpl())) #else switch (_core.isASCII, rhs._core.isASCII) { case (true, false): let lhsPtr = UnsafePointer<Int8>(_core.startASCII) let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16) return Int(_swift_stdlib_unicode_compare_utf8_utf16( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) case (false, true): // Just invert it and recurse for this case. return -rhs._compareDeterministicUnicodeCollation(self) case (false, false): let lhsPtr = UnsafePointer<UTF16.CodeUnit>(_core.startUTF16) let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16) return Int(_swift_stdlib_unicode_compare_utf16_utf16( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) case (true, true): let lhsPtr = UnsafePointer<Int8>(_core.startASCII) let rhsPtr = UnsafePointer<Int8>(rhs._core.startASCII) return Int(_swift_stdlib_unicode_compare_utf8_utf8( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) } #endif } @warn_unused_result public // @testable func _compareString(rhs: String) -> Int { #if _runtime(_ObjC) // We only want to perform this optimization on objc runtimes. Elsewhere, // we will make it follow the unicode collation algorithm even for ASCII. if (_core.isASCII && rhs._core.isASCII) { return _compareASCII(rhs) } #endif return _compareDeterministicUnicodeCollation(rhs) } } @warn_unused_result public func <(lhs: String, rhs: String) -> Bool { return lhs._compareString(rhs) < 0 } // Support for copy-on-write extension String { /// Append the elements of `other` to `self`. public mutating func append(other: String) { _core.append(other._core) } /// Append `x` to `self`. /// /// - Complexity: Amortized O(1). public mutating func append(x: UnicodeScalar) { _core.append(x) } public // SPI(Foundation) init(_storage: _StringBuffer) { _core = _StringCore(_storage) } } #if _runtime(_ObjC) @warn_unused_result @_silgen_name("swift_stdlib_NSStringNFDHashValue") func _stdlib_NSStringNFDHashValue(str: AnyObject) -> Int @warn_unused_result @_silgen_name("swift_stdlib_NSStringASCIIHashValue") func _stdlib_NSStringASCIIHashValue(str: AnyObject) -> Int #endif extension String : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`. /// /// - Note: The hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. public var hashValue: Int { #if _runtime(_ObjC) // Mix random bits into NSString's hash so that clients don't rely on // Swift.String.hashValue and NSString.hash being the same. #if arch(i386) || arch(arm) let hashOffset = Int(bitPattern: 0x88dd_cc21) #else let hashOffset = Int(bitPattern: 0x429b_1266_88dd_cc21) #endif // FIXME(performance): constructing a temporary NSString is extremely // wasteful and inefficient. let cocoaString = unsafeBitCast( self._bridgeToObjectiveCImpl(), to: _NSStringCore.self) // If we have an ASCII string, we do not need to normalize. if self._core.isASCII { return hashOffset ^ _stdlib_NSStringASCIIHashValue(cocoaString) } else { return hashOffset ^ _stdlib_NSStringNFDHashValue(cocoaString) } #else if self._core.isASCII { return _swift_stdlib_unicode_hash_ascii( UnsafeMutablePointer<Int8>(_core.startASCII), Int32(_core.count)) } else { return _swift_stdlib_unicode_hash( UnsafeMutablePointer<UInt16>(_core.startUTF16), Int32(_core.count)) } #endif } } @warn_unused_result @effects(readonly) @_semantics("string.concat") public func + (lhs: String, rhs: String) -> String { var lhs = lhs if (lhs.isEmpty) { return rhs } lhs._core.append(rhs._core) return lhs } // String append public func += (lhs: inout String, rhs: String) { if lhs.isEmpty { lhs = rhs } else { lhs._core.append(rhs._core) } } extension String { /// Constructs a `String` in `resultStorage` containing the given UTF-8. /// /// Low-level construction interface used by introspection /// implementation in the runtime library. @_silgen_name("swift_stringFromUTF8InRawMemory") public // COMPILER_INTRINSIC static func _fromUTF8InRawMemory( resultStorage: UnsafeMutablePointer<String>, start: UnsafeMutablePointer<UTF8.CodeUnit>, utf8CodeUnitCount: Int ) { resultStorage.initialize(with: String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer(start: start, count: utf8CodeUnitCount))) } } extension String { public typealias Index = CharacterView.Index /// The position of the first `Character` in `self.characters` if /// `self` is non-empty; identical to `endIndex` otherwise. public var startIndex: Index { return characters.startIndex } /// The "past the end" position in `self.characters`. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Index { return characters.endIndex } /// Access the `Character` at `position`. /// /// - Precondition: `position` is a valid position in `self.characters` /// and `position != endIndex`. public subscript(i: Index) -> Character { return characters[i] } } @warn_unused_result public func == (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._base == rhs._base } @warn_unused_result public func < (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._base < rhs._base } extension String { /// Return the characters within the given `bounds`. /// /// - Complexity: O(1) unless bridging from Objective-C requires an /// O(N) conversion. public subscript(bounds: Range<Index>) -> String { return String(characters[bounds]) } } extension String { public mutating func reserveCapacity(n: Int) { withMutableCharacters { (v: inout CharacterView) in v.reserveCapacity(n) } } public mutating func append(c: Character) { withMutableCharacters { (v: inout CharacterView) in v.append(c) } } public mutating func append< S : Sequence where S.Iterator.Element == Character >(contentsOf newElements: S) { withMutableCharacters { (v: inout CharacterView) in v.append(contentsOf: newElements) } } /// Create an instance containing `characters`. public init< S : Sequence where S.Iterator.Element == Character >(_ characters: S) { self._core = CharacterView(characters)._core } } extension Sequence where Iterator.Element == String { /// Interpose the `separator` between elements of `self`, then concatenate /// the result. For example: /// /// ["foo", "bar", "baz"].joined(separator: "-|-") // "foo-|-bar-|-baz" @warn_unused_result public func joined(separator separator: String) -> String { var result = "" // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. let separatorSize = separator.utf16.count let reservation = self._preprocessingPass { () -> Int in var r = 0 for chunk in self { // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. r += separatorSize + chunk.utf16.count } return r - separatorSize } if let n = reservation { result.reserveCapacity(n) } if separatorSize == 0 { for x in self { result.append(x) } return result } var iter = makeIterator() if let first = iter.next() { result.append(first) while let next = iter.next() { result.append(separator) result.append(next) } } return result } } extension String { /// Replace the characters within `bounds` with the elements of /// `replacement`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`bounds.count`) if `bounds.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceSubrange< C: Collection where C.Iterator.Element == Character >( bounds: Range<Index>, with newElements: C ) { withMutableCharacters { (v: inout CharacterView) in v.replaceSubrange(bounds, with: newElements) } } /// Replace the text in `bounds` with `replacement`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`bounds.count`) if `bounds.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceSubrange( bounds: Range<Index>, with newElements: String ) { replaceSubrange(bounds, with: newElements.characters) } /// Insert `newElement` at position `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). public mutating func insert(newElement: Character, at i: Index) { withMutableCharacters { (v: inout CharacterView) in v.insert(newElement, at: i) } } /// Insert `newElements` at position `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count + newElements.count`). public mutating func insert< S : Collection where S.Iterator.Element == Character >(contentsOf newElements: S, at i: Index) { withMutableCharacters { (v: inout CharacterView) in v.insert(contentsOf: newElements, at: i) } } /// Remove and return the `Character` at position `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). public mutating func remove(at i: Index) -> Character { return withMutableCharacters { (v: inout CharacterView) in v.remove(at: i) } } /// Remove the characters in `bounds`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). public mutating func removeSubrange(bounds: Range<Index>) { withMutableCharacters { (v: inout CharacterView) in v.removeSubrange(bounds) } } /// Replace `self` with the empty string. /// /// Invalidates all indices with respect to `self`. /// /// - parameter keepCapacity: If `true`, prevents the release of /// allocated storage, which can be a useful optimization /// when `self` is going to be grown again. public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { withMutableCharacters { (v: inout CharacterView) in v.removeAll(keepingCapacity: keepCapacity) } } } #if _runtime(_ObjC) @warn_unused_result @_silgen_name("swift_stdlib_NSStringLowercaseString") func _stdlib_NSStringLowercaseString(str: AnyObject) -> _CocoaString @warn_unused_result @_silgen_name("swift_stdlib_NSStringUppercaseString") func _stdlib_NSStringUppercaseString(str: AnyObject) -> _CocoaString #else @warn_unused_result internal func _nativeUnicodeLowercaseString(str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Try to write it out to the same length. let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) let z = _swift_stdlib_unicode_strToLower( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) _swift_stdlib_unicode_strToLower( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } @warn_unused_result internal func _nativeUnicodeUppercaseString(str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Try to write it out to the same length. let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) let z = _swift_stdlib_unicode_strToUpper( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) _swift_stdlib_unicode_strToUpper( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } #endif // Unicode algorithms extension String { // FIXME: implement case folding without relying on Foundation. // <rdar://problem/17550602> [unicode] Implement case folding /// A "table" for which ASCII characters need to be upper cased. /// To determine which bit corresponds to which ASCII character, subtract 1 /// from the ASCII value of that character and divide by 2. The bit is set iff /// that character is a lower case character. internal var _asciiLowerCaseTable: UInt64 { @inline(__always) get { return 0b0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000 } } /// The same table for upper case characters. internal var _asciiUpperCaseTable: UInt64 { @inline(__always) get { return 0b0000_0000_0000_0000_0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000 } } /// Return `self` converted to lower case. /// /// - Complexity: O(n) public func lowercased() -> String { if self._core.isASCII { let count = self._core.count let source = self._core.startASCII let buffer = _StringBuffer( capacity: count, initialSize: count, elementWidth: 1) let dest = UnsafeMutablePointer<UInt8>(buffer.start) for i in 0..<count { // For each character in the string, we lookup if it should be shifted // in our ascii table, then we return 0x20 if it should, 0x0 if not. // This code is equivalent to: // switch source[i] { // case let x where (x >= 0x41 && x <= 0x5a): // dest[i] = x &+ 0x20 // case let x: // dest[i] = x // } let value = source[i] let isUpper = _asciiUpperCaseTable >> UInt64(((value &- 1) & 0b0111_1111) >> 1) let add = (isUpper & 0x1) << 5 // Since we are left with either 0x0 or 0x20, we can safely truncate to // a UInt8 and add to our ASCII value (this will not overflow numbers in // the ASCII range). dest[i] = value &+ UInt8(truncatingBitPattern: add) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringLowercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeLowercaseString(self) #endif } /// Return `self` converted to upper case. /// /// - Complexity: O(n) public func uppercased() -> String { if self._core.isASCII { let count = self._core.count let source = self._core.startASCII let buffer = _StringBuffer( capacity: count, initialSize: count, elementWidth: 1) let dest = UnsafeMutablePointer<UInt8>(buffer.start) for i in 0..<count { // See the comment above in lowercaseString. let value = source[i] let isLower = _asciiLowerCaseTable >> UInt64(((value &- 1) & 0b0111_1111) >> 1) let add = (isLower & 0x1) << 5 dest[i] = value &- UInt8(truncatingBitPattern: add) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringUppercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeUppercaseString(self) #endif } } // Index conversions extension String.Index { /// Construct the position in `characters` that corresponds exactly to /// `unicodeScalarIndex`. If no such position exists, the result is `nil`. /// /// - Precondition: `unicodeScalarIndex` is an element of /// `characters.unicodeScalars.indices`. public init?( _ unicodeScalarIndex: String.UnicodeScalarIndex, within characters: String ) { if !unicodeScalarIndex._isOnGraphemeClusterBoundary { return nil } self.init(_base: unicodeScalarIndex) } /// Construct the position in `characters` that corresponds exactly to /// `utf16Index`. If no such position exists, the result is `nil`. /// /// - Precondition: `utf16Index` is an element of /// `characters.utf16.indices`. public init?( _ utf16Index: String.UTF16Index, within characters: String ) { if let me = utf16Index.samePosition( in: characters.unicodeScalars )?.samePosition(in: characters) { self = me } else { return nil } } /// Construct the position in `characters` that corresponds exactly to /// `utf8Index`. If no such position exists, the result is `nil`. /// /// - Precondition: `utf8Index` is an element of /// `characters.utf8.indices`. public init?( _ utf8Index: String.UTF8Index, within characters: String ) { if let me = utf8Index.samePosition( in: characters.unicodeScalars )?.samePosition(in: characters) { self = me } else { return nil } } /// Returns the position in `utf8` that corresponds exactly /// to `self`. /// /// - Precondition: `self` is an element of `String(utf8).indices`. @warn_unused_result public func samePosition( in utf8: String.UTF8View ) -> String.UTF8View.Index { return String.UTF8View.Index(self, within: utf8) } /// Returns the position in `utf16` that corresponds exactly /// to `self`. /// /// - Precondition: `self` is an element of `String(utf16).indices`. @warn_unused_result public func samePosition( in utf16: String.UTF16View ) -> String.UTF16View.Index { return String.UTF16View.Index(self, within: utf16) } /// Returns the position in `unicodeScalars` that corresponds exactly /// to `self`. /// /// - Precondition: `self` is an element of `String(unicodeScalars).indices`. @warn_unused_result public func samePosition( in unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarView.Index { return String.UnicodeScalarView.Index(self, within: unicodeScalars) } } extension String { @available(*, unavailable, renamed="append") public mutating func appendContentsOf(other: String) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="append(contentsOf:)") public mutating func appendContentsOf< S : Sequence where S.Iterator.Element == Character >(newElements: S) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="insert(contentsOf:at:)") public mutating func insertContentsOf< S : Collection where S.Iterator.Element == Character >(newElements: S, at i: Index) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="replaceSubrange") public mutating func replaceRange< C : Collection where C.Iterator.Element == Character >( subRange: Range<Index>, with newElements: C ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="replaceSubrange") public mutating func replaceRange( subRange: Range<Index>, with newElements: String ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="removeAt") public mutating func removeAtIndex(i: Index) -> Character { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="removeSubrange") public mutating func removeRange(subRange: Range<Index>) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="lowercased()") public var lowercaseString: String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="uppercased()") public var uppercaseString: String { fatalError("unavailable function can't be called") } } extension Sequence where Iterator.Element == String { @available(*, unavailable, renamed="joined") public func joinWithSeparator(separator: String) -> String { fatalError("unavailable function can't be called") } }
apache-2.0
220e7c359d10bbb7892bffef78e7acf5
30.904853
94
0.671389
4.112842
false
false
false
false
barbrobmich/linkbase
LinkBase/LinkBase/DashboardViewController.swift
1
5119
// // DashboardViewController.swift // LinkBase // // Created by Barbara Ristau on 3/27/17. // Copyright © 2017 barbrobmich. All rights reserved. // import UIKit import Parse class DashboardViewController: UIViewController { @IBOutlet weak var profileImageView: UIImageView! // need to connect this property to user @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var totalPointsLabel: UILabel! @IBOutlet weak var numProgrammingQuestionsLabel: UILabel! @IBOutlet weak var programmingAvgScoreLabel: UILabel! @IBOutlet weak var totalProgrammingScoreLabel: UILabel! @IBOutlet weak var numCommsQuestionsLabel: UILabel! @IBOutlet weak var commsAvgScoreLabel: UILabel! @IBOutlet weak var totalCommunicationScoreLabel: UILabel! @IBOutlet weak var programmingButton: UIButton! @IBOutlet weak var commsButton: UIButton! @IBOutlet weak var peerReviewButton: UIButton! var challengeGame: ScoreCard! override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.shared.delegate as! AppDelegate challengeGame = appDelegate.challengeGame } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) loadLabels() } func loadLabels() { userNameLabel.text = challengeGame.player numProgrammingQuestionsLabel.text = String(describing: challengeGame.techQuestionsAnswered.count) numCommsQuestionsLabel.text = String(describing: challengeGame.commsQuestionsAnswered.count) // get scores for each section // Programming Section var totalProgrammingScore: Int = 0 for question in challengeGame.techQuestionsAnswered { let score = question.points totalProgrammingScore += score } if totalProgrammingScore == 0 { totalProgrammingScoreLabel.text = "N/A" programmingAvgScoreLabel.text = "N/A" } else { totalProgrammingScoreLabel.text = String(describing: totalProgrammingScore) let averageScore = totalProgrammingScore / challengeGame.techQuestionsAnswered.count programmingAvgScoreLabel.text = String(describing: averageScore) } // Communication Section var totalCommunicationScore: Int = 0 for question in challengeGame.commsQuestionsAnswered { let score = question.points.submit + question.points.overall + question.points.style + question.points.relevance totalCommunicationScore += score } if totalCommunicationScore == 0 { totalCommunicationScoreLabel.text = "N/A" commsAvgScoreLabel.text = "N/A" } else { totalCommunicationScoreLabel.text = String(describing: totalCommunicationScore) let avgScore = totalCommunicationScore / challengeGame.commsQuestionsAnswered.count commsAvgScoreLabel.text = String(describing: avgScore) } totalPointsLabel.text = String(describing: totalCommunicationScore + totalProgrammingScore) // profileImageView.image = User.current() totalPointsLabel.text = "\(challengeGame.commsPoints + challengeGame.techPoints)" numProgrammingQuestionsLabel.text = "\(challengeGame.commsQuestionsAnswered.count)" programmingAvgScoreLabel.text = "\(challengeGame.techPoints / (challengeGame.techQuestionsAnswered.count == 0 ? 1 : challengeGame.techQuestionsAnswered.count))" totalProgrammingScoreLabel.text = "\(challengeGame.techPoints)" numCommsQuestionsLabel.text = "\(challengeGame.techQuestionsAnswered.count)" commsAvgScoreLabel.text = "\(challengeGame.commsPoints / (challengeGame.commsQuestionsAnswered.count == 0 ? 1 : challengeGame.commsQuestionsAnswered.count))" totalCommunicationScoreLabel.text = "\(challengeGame.commsPoints)" } // MARK: - IB Actions @IBAction func onProgrammingTapped(_ sender: UIButton) { print("Tapped on programming detail") } @IBAction func onCommsTapped(_ sender: UIButton) { print("Tapped on communication detail") } @IBAction func onPeerReviewTapped(_ sender: UIButton) { print("Tapped on peer review") } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { print("Preparing for segue") if segue.identifier == "ProgrammingDetail" { print("Going to detail") let detailVC = segue.destination as! ResultsDetailViewController detailVC.navigationItem.title = "Programming Questions" detailVC.resultsView = "Tech" } if segue.identifier == "CommunicationDetail" { print("Going to detail") let detailVC = segue.destination as! ResultsDetailViewController detailVC.navigationItem.title = "Communication Questions" detailVC.resultsView = "Comms" } } }
mit
3681b410243950a7c2079b51d5fb1c7b
34.79021
162
0.676436
5.118
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobile/PrebidMobileRendering/Prebid/Integrations/GAM/RewardedAdUnit.swift
1
5136
/*   Copyright 2018-2021 Prebid.org, 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 @objc public class RewardedAdUnit: BaseInterstitialAdUnit, RewardedEventInteractionDelegate { @objc public private(set) var reward: NSObject? // MARK: - Lifecycle @objc public convenience init(configID: String, eventHandler: AnyObject) { self.init( configID: configID, minSizePerc: nil, eventHandler: eventHandler) } @objc public convenience init(configID: String) { self.init( configID: configID, minSizePerc: nil, eventHandler: RewardedEventHandlerStandalone()) } @objc required init(configID:String, minSizePerc: NSValue?, eventHandler: AnyObject?) { super.init( configID: configID, minSizePerc: minSizePerc, eventHandler: eventHandler) adUnitConfig.adConfiguration.isOptIn = true adFormats = [.video] } // MARK: - PBMRewardedEventDelegate @objc public func userDidEarnReward(_ reward: NSObject?) { DispatchQueue.main.async(execute: { [weak self] in self?.reward = reward self?.callDelegate_rewardedAdUserDidEarnReward() }) } // MARK: - BaseInterstitialAdUnitProtocol protocol @objc public override func interstitialControllerDidCloseAd(_ interstitialController: InterstitialController) { callDelegate_rewardedAdUserDidEarnReward() super.interstitialControllerDidCloseAd(interstitialController) } // MARK: - Protected overrides @objc public override func callDelegate_didReceiveAd() { if let delegate = self.delegate as? RewardedAdUnitDelegate { delegate.rewardedAdDidReceiveAd?(self) } } @objc public override func callDelegate_didFailToReceiveAd(with error: Error?) { if let delegate = self.delegate as? RewardedAdUnitDelegate { delegate.rewardedAd?(self, didFailToReceiveAdWithError: error) } } @objc public override func callDelegate_willPresentAd() { if let delegate = self.delegate as? RewardedAdUnitDelegate { delegate.rewardedAdWillPresentAd?(self) } } @objc public override func callDelegate_didDismissAd() { if let delegate = self.delegate as? RewardedAdUnitDelegate { delegate.rewardedAdDidDismissAd?(self) } } @objc public override func callDelegate_willLeaveApplication() { if let delegate = self.delegate as? RewardedAdUnitDelegate { delegate.rewardedAdWillLeaveApplication?(self) } } @objc public override func callDelegate_didClickAd() { if let delegate = self.delegate as? RewardedAdUnitDelegate { delegate.rewardedAdDidClickAd?(self) } } @objc public override func callEventHandler_isReady() -> Bool { if let eventHandler = self.eventHandler as? RewardedEventHandlerProtocol { return eventHandler.isReady } else { return false } } @objc public override func callEventHandler_setLoadingDelegate(_ loadingDelegate: NSObject?) { if let eventHandler = self.eventHandler as? RewardedEventHandlerProtocol { eventHandler.loadingDelegate = loadingDelegate as? RewardedEventLoadingDelegate } } @objc public override func callEventHandler_setInteractionDelegate() { if let eventHandler = self.eventHandler as? RewardedEventHandlerProtocol { eventHandler.interactionDelegate = self } } @objc public override func callEventHandler_requestAd(with bidResponse: BidResponse?) { if let eventHandler = self.eventHandler as? RewardedEventHandlerProtocol { eventHandler.requestAd(with: bidResponse) } } @objc public override func callEventHandler_show(from controller: UIViewController?) { if let eventHandler = self.eventHandler as? RewardedEventHandlerProtocol { eventHandler.show(from: controller) } } @objc public override func callEventHandler_trackImpression() { if let eventHandler = self.eventHandler as? RewardedEventHandlerProtocol { eventHandler.trackImpression?() } } // MARK: - Private helpers func callDelegate_rewardedAdUserDidEarnReward() { if let delegate = self.delegate as? RewardedAdUnitDelegate { delegate.rewardedAdUserDidEarnReward?(self) } } }
apache-2.0
f9bb650a9dff6cbc23ba89f68992341d
33.628378
115
0.670049
4.909004
false
true
false
false
multinerd/Mia
Mia/Extensions/UIView/UIView+Misc.swift
1
1704
import UIKit public extension UIView { //https://stackoverflow.com/questions/32151637/swift-get-all-subviews-of-a-specific-type-and-add-to-an-array /// Get array of subviews of type 'T' /// /// - Parameter type: The object type. /// - Returns: Returns an array of objects of type 'T' public func subViews<T:UIView>(type: T.Type) -> [T] { var all = [ T ]() for view in self.subviews { if let aView = view as? T { all.append(aView) } } return all } //https://stackoverflow.com/questions/32151637/swift-get-all-subviews-of-a-specific-type-and-add-to-an-array /// Recursively get array of subviews of type 'T' /// /// - Parameter type: The object type. /// - Returns: Returns an array of objects of type 'T' public func subViewsRecursive<T:UIView>(type: T.Type) -> [T] { var all = [ T ]() func getSubview(view: UIView) { if let aView = view as? T { all.append(aView) } guard view.subviews.count > 0 else { return } view.subviews.forEach { getSubview(view: $0) } } getSubview(view: self) return all } /// Takes a screenshot of the current view. /// /// - Returns: Returns an UIImage of the screens current view. public func takeScreenshot() -> UIImage { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale) drawHierarchy(in: self.bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
mit
b688c3eb0fc60945171e8405216dc944
26.047619
112
0.59331
4.166259
false
false
false
false
jkbreunig/JBScrollingTabBarController
JBScrollingTabBarController/Classes/JBScrollingTabBarController.swift
1
12589
// // JBScrollingTabBarController.swift // JBTeam // // Created by Jeff Breunig on 11/6/16. // Copyright (c) 2016 Jeff Breunig <[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 JBScrollingTabBarController: UITabBarController, UITabBarControllerDelegate { //----------------------------------------------------------------------------------------------------------- //MARK: Public API public var scrollingTabBarViewControllers: [UIViewController]? { didSet { if scrollingTabBarViewControllers?.isEmpty == false, let vc = scrollingTabBarViewControllers?[0] { self.viewControllers = [vc] setup() } } } public var shouldRotateButtons = true public var rotateButtonDuration: Double = Defaults.rotateButtonDuration public var barTintColor: UIColor = UIColor.TabBar.barTintColor { didSet { didUpdateBarTintColor() } } public var buttonActiveColor: UIColor = UIColor.TabBar.activeItem { didSet { updateButtonColors() } } public var buttonInactiveColor: UIColor = UIColor.TabBar.inactiveItem { didSet { updateButtonColors() } } public var buttonActiveFont: UIFont = UIFont.TabBar.activeItem { didSet { updateButtonFont() } } public var buttonInactiveFont: UIFont = UIFont.TabBar.inactiveItem { didSet { updateButtonFont() } } public var bounces: Bool = true { didSet { scrollView.bounces = bounces } } public var index: Int = 0 { didSet { if let controllerCount = scrollingTabBarViewControllers?.count, index >= controllerCount { index = oldValue } else { didUpdateSelectedIndex() } } } override public var selectedViewController: UIViewController? { willSet { if let controllerCount = scrollingTabBarViewControllers?.count, controllerCount > index, let viewController = scrollingTabBarViewControllers?[index] { self.viewControllers = [viewController] } } } //----------------------------------------------------------------------------------------------------------- //MARK: Private API struct Defaults { static let rotateButtonDuration: Double = 0.5 static let imageSize = CGSize(width: 25, height: 25) static let minTabWidth: CGFloat = 50 static let maxNumberOfButtonsOnScreen = Int(UIScreen.main.bounds.width / Defaults.minTabWidth) } public private(set) var imageSize: CGSize = Defaults.imageSize // Users should use scrollingTabBarViewControllers property instead of viewControllers property. override public var viewControllers: [UIViewController]? { set { super.viewControllers = newValue } get { return scrollingTabBarViewControllers } } // Users should use index property instead of selectedIndex property. override public var selectedIndex: Int { set { } get { return index } } private var maxNumberOfButtonsOnScreen = Defaults.maxNumberOfButtonsOnScreen private let scrollView = UIScrollView() private var tabBarButtons: [JBTabBarButton]? //----------------------------------------------------------------------------------------------------------- //MARK: Designated initializer. All arguments are optional. public init( maxNumberOfButtonsOnScreen: Int = Defaults.maxNumberOfButtonsOnScreen, barTintColor: UIColor = UIColor.TabBar.barTintColor, buttonActiveColor: UIColor = UIColor.TabBar.activeItem, buttonInactiveColor: UIColor = UIColor.TabBar.inactiveItem, buttonActiveFont: UIFont = UIFont.TabBar.activeItem, buttonInactiveFont: UIFont = UIFont.TabBar.inactiveItem) { super.init(nibName: nil, bundle: nil) delegate = self self.maxNumberOfButtonsOnScreen = maxNumberOfButtonsOnScreen self.barTintColor = barTintColor self.buttonActiveColor = buttonActiveColor self.buttonInactiveColor = buttonInactiveColor self.buttonActiveFont = buttonActiveFont self.buttonInactiveFont = buttonInactiveFont } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //----------------------------------------------------------------------------------------------------------- //MARK: Setup private func setup() { tabBar.barTintColor = barTintColor setupScrollView() setupTabBarButtons() } private func setupScrollView() { // Set scrollView frame. Cannot modify constraints for UITabBar managed by a controller. scrollView.frame = CGRect(x: 0, y: 0, width: tabBar.frame.width, height: tabBar.frame.height) scrollView.backgroundColor = barTintColor scrollView.showsHorizontalScrollIndicator = false scrollView.bounces = bounces scrollView.isPagingEnabled = false tabBar.addSubview(scrollView) } private func setupTabBarButtons() { let numberOfButtons = scrollingTabBarViewControllers?.count ?? 0 let buttonHeight = tabBar.frame.height let scrollViewWidth = scrollView.frame.width let buttonWidth: CGFloat if numberOfButtons > maxNumberOfButtonsOnScreen { buttonWidth = scrollViewWidth / CGFloat(maxNumberOfButtonsOnScreen) } else { buttonWidth = scrollViewWidth / CGFloat(numberOfButtons) } var initialButton: JBTabBarButton? var buttons = [JBTabBarButton]() var x: CGFloat = 0 for i in 0 ..< numberOfButtons { if let item = scrollingTabBarViewControllers?[i].tabBarItem { let button = setupButton(xOffset: x, buttonSize: CGSize(width: buttonWidth, height: buttonHeight), item: item, tag: i) scrollView.addSubview(button) buttons.append(button) if i == index { initialButton = button } x += buttonWidth } } tabBarButtons = buttons scrollView.contentSize = CGSize(width: x, height: buttonHeight) if let initialButton = initialButton { didTapButton(initialButton) } else if let tabBarButtons = tabBarButtons, !tabBarButtons.isEmpty { didTapButton(tabBarButtons[0]) } } private func setupButton(xOffset: CGFloat, buttonSize: CGSize, item: UITabBarItem, tag: Int) -> JBTabBarButton { let button = JBTabBarButton(image: item.selectedImage, activeColor: buttonActiveColor, inactiveColor: buttonInactiveColor, activeFont: buttonActiveFont, inactiveFont: buttonInactiveFont) button.frame = CGRect(x: xOffset, y: 0, width: buttonSize.width, height: buttonSize.height) button.backgroundColor = barTintColor button.setTitle(item.title, for: .normal) button.tag = tag button.addTarget(self, action: #selector(self.didTapButton(_:)), for: .touchUpInside) return button } //----------------------------------------------------------------------------------------------------------- //MARK: UITabBarControllerDelegate public func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { didUpdateSelectedIndex() } //----------------------------------------------------------------------------------------------------------- //MARK: Actions func didTapButton(_ button: JBTabBarButton) { index = button.tag } private func didUpdateSelectedIndex() { if let tabBarButtons = tabBarButtons, tabBarButtons.count > index { selectedViewController = scrollingTabBarViewControllers?[index] let offset = scrollView.contentOffset tabBar.bringSubview(toFront: scrollView) scrollView.contentOffset = offset // update buttons let selectedButton = tabBarButtons[index] updateActiveState(selectedButton: selectedButton) rotate(selectedButton: selectedButton) center(selectedButton: selectedButton) } } private func updateActiveState(selectedButton: JBTabBarButton) { tabBarButtons?.forEach { button in if button !== selectedButton { button.isActive = false } else { button.isActive = true } } } private func rotate(selectedButton button: JBTabBarButton) { if shouldRotateButtons { UIView.animate(withDuration: rotateButtonDuration, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in button.iv.rotateView() }, completion: nil) } } private func center(selectedButton: JBTabBarButton) { if scrollView.contentSize.width <= tabBar.bounds.width { return } let pointInSuperview = scrollView.convert(selectedButton.center, to: tabBar) let superviewCenter = scrollView.center var centerXOffset: CGFloat if selectedButton.frame.origin.x < superviewCenter.x { centerXOffset = 0 } else if selectedButton.frame.origin.x > scrollView.contentSize.width - superviewCenter.x { centerXOffset = scrollView.contentSize.width - scrollView.frame.width } else { let diff = superviewCenter.x - pointInSuperview.x centerXOffset = scrollView.contentOffset.x - diff } UIView.animate(withDuration: 0.3) { self.scrollView.contentOffset = CGPoint(x: centerXOffset, y: self.scrollView.contentOffset.y) } } //----------------------------------------------------------------------------------------------------------- //MARK: Update UI private func didUpdateBarTintColor() { tabBar.barTintColor = barTintColor scrollView.backgroundColor = barTintColor tabBarButtons?.forEach { $0.backgroundColor = barTintColor } } private func updateButtonColors() { tabBarButtons?.forEach { $0.update(activeColor: buttonActiveColor, inactiveColor: buttonInactiveColor) } } private func updateButtonFont() { tabBarButtons?.forEach { $0.update(activeFont: buttonActiveFont, inactiveFont: buttonInactiveFont) } } }
mit
fed87ec36624c0aa9c8879a51b4d145e
37.498471
113
0.581539
5.902016
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressNotificationContentExtension/Sources/Tracks/Tracks+ContentExtension.swift
1
1932
import Foundation /// Characterizes the types of content extension events we're interested in tracking. /// The raw value corresponds to the event name in Tracks. /// /// - launched: the content extension was successfully entered & launched /// private enum ContentExtensionEvents: String { case launched = "notification_content_extension_launched" case failedToMarkAsRead = "notification_content_extension_failed_mark_as_read" } // MARK: - Supports tracking notification content extension events. extension Tracks { /// Tracks the successful launch of the notification content extension. /// /// - Parameter wpcomAvailable: `true` if an OAuth token exists, `false` otherwise func trackExtensionLaunched(_ wpcomAvailable: Bool) { let properties = [ "is_configured_dotcom": wpcomAvailable ] trackEvent(ContentExtensionEvents.launched, properties: properties as [String: AnyObject]?) } /// Tracks the failure to mark a notification as read via the REST API. /// /// - Parameters: /// - notificationIdentifier: the value of the `note_id` from the APNS payload /// - errorDescription: description of the error encountered, ideally localized func trackFailedToMarkNotificationAsRead(notificationIdentifier: String, errorDescription: String) { let properties = [ "note_id": notificationIdentifier, "error": errorDescription ] trackEvent(ContentExtensionEvents.failedToMarkAsRead, properties: properties as [String: AnyObject]?) } /// Utility method to capture an event & submit it to Tracks. /// /// - Parameters: /// - event: the event to track /// - properties: any accompanying metadata private func trackEvent(_ event: ContentExtensionEvents, properties: [String: AnyObject]? = nil) { track(event.rawValue, properties: properties) } }
gpl-2.0
2b4ea77106983915cfdf1837b284b7de
40.106383
109
0.693582
4.953846
false
false
false
false
khoren93/SwiftHub
SwiftHub/Extensions/RxSwift/Observable+Operators.swift
1
6430
// // Observable+Operators.swift // Cake Builder // // Created by Khoren Markosyan on 10/19/16. // Copyright © 2016 Khoren Markosyan. All rights reserved. // import Foundation import RxSwift import RxCocoa extension Reactive where Base: UIView { func tap() -> Observable<Void> { return tapGesture().when(.recognized).mapToVoid() } } protocol OptionalType { associatedtype Wrapped var value: Wrapped? { get } } extension Optional: OptionalType { var value: Wrapped? { return self } } extension Observable where Element: OptionalType { func filterNil() -> Observable<Element.Wrapped> { return flatMap { (element) -> Observable<Element.Wrapped> in if let value = element.value { return .just(value) } else { return .empty() } } } func filterNilKeepOptional() -> Observable<Element> { return self.filter { (element) -> Bool in return element.value != nil } } func replaceNil(with nilValue: Element.Wrapped) -> Observable<Element.Wrapped> { return flatMap { (element) -> Observable<Element.Wrapped> in if let value = element.value { return .just(value) } else { return .just(nilValue) } } } } protocol BooleanType { var boolValue: Bool { get } } extension Bool: BooleanType { var boolValue: Bool { return self } } // Maps true to false and vice versa extension Observable where Element: BooleanType { func not() -> Observable<Bool> { return self.map { input in return !input.boolValue } } } extension Observable where Element: Equatable { func ignore(value: Element) -> Observable<Element> { return filter { (selfE) -> Bool in return value != selfE } } } extension ObservableType where Element == Bool { /// Boolean not operator public func not() -> Observable<Bool> { return self.map(!) } } extension SharedSequenceConvertibleType { func mapToVoid() -> SharedSequence<SharingStrategy, Void> { return map { _ in } } } extension ObservableType { func asDriverOnErrorJustComplete() -> Driver<Element> { return asDriver { error in assertionFailure("Error \(error)") return Driver.empty() } } func mapToVoid() -> Observable<Void> { return map { _ in } } } //https://gist.github.com/brocoo/aaabf12c6c2b13d292f43c971ab91dfa extension Reactive where Base: UIScrollView { public var reachedBottom: Observable<Void> { let scrollView = self.base as UIScrollView return self.contentOffset.flatMap { [weak scrollView] (contentOffset) -> Observable<Void> in guard let scrollView = scrollView else { return Observable.empty() } let visibleHeight = scrollView.frame.height - self.base.contentInset.top - scrollView.contentInset.bottom let y = contentOffset.y + scrollView.contentInset.top let threshold = max(0.0, scrollView.contentSize.height - visibleHeight) return (y > threshold) ? Observable.just(()) : Observable.empty() } } } // Two way binding operator between control property and variable, that's all it takes { infix operator <-> : DefaultPrecedence func nonMarkedText(_ textInput: UITextInput) -> String? { let start = textInput.beginningOfDocument let end = textInput.endOfDocument guard let rangeAll = textInput.textRange(from: start, to: end), let text = textInput.text(in: rangeAll) else { return nil } guard let markedTextRange = textInput.markedTextRange else { return text } guard let startRange = textInput.textRange(from: start, to: markedTextRange.start), let endRange = textInput.textRange(from: markedTextRange.end, to: end) else { return text } return (textInput.text(in: startRange) ?? "") + (textInput.text(in: endRange) ?? "") } func <-> <Base>(textInput: TextInput<Base>, variable: BehaviorRelay<String>) -> Disposable { let bindToUIDisposable = variable.asObservable() .bind(to: textInput.text) let bindToVariable = textInput.text .subscribe(onNext: { [weak base = textInput.base] value in guard let base = base else { return } let nonMarkedTextValue = nonMarkedText(base) /** In some cases `textInput.textRangeFromPosition(start, toPosition: end)` will return nil even though the underlying value is not nil. This appears to be an Apple bug. If it's not, and we are doing something wrong, please let us know. The can be reproed easily if replace bottom code with if nonMarkedTextValue != variable.value { variable.value = nonMarkedTextValue ?? "" } and you hit "Done" button on keyboard. */ if let nonMarkedTextValue = nonMarkedTextValue, nonMarkedTextValue != variable.value { variable.accept(nonMarkedTextValue) } }, onCompleted: { bindToUIDisposable.dispose() }) return Disposables.create(bindToUIDisposable, bindToVariable) } func <-> <T>(property: ControlProperty<T>, variable: BehaviorRelay<T>) -> Disposable { if T.self == String.self { #if DEBUG fatalError("It is ok to delete this message, but this is here to warn that you are maybe trying to bind to some `rx.text` property directly to variable.\n" + "That will usually work ok, but for some languages that use IME, that simplistic method could cause unexpected issues because it will return intermediate results while text is being inputed.\n" + "REMEDY: Just use `textField <-> variable` instead of `textField.rx.text <-> variable`.\n" + "Find out more here: https://github.com/ReactiveX/RxSwift/issues/649\n" ) #endif } let bindToUIDisposable = variable.asObservable() .bind(to: property) let bindToVariable = property .subscribe(onNext: { value in variable.accept(value) }, onCompleted: { bindToUIDisposable.dispose() }) return Disposables.create(bindToUIDisposable, bindToVariable) }
mit
b577373c0e8e2779f50823f68cc92ad5
30.985075
207
0.62918
4.572546
false
false
false
false
liakhandrii/google-translate-swift
TranslateQuery.swift
1
7015
// // TranslateQuery.swift // // Created by Andrii Liakh on 14.03.2015. Updated by Mike ([email protected]) on 01.03.2016. // import Foundation extension String { public func urlEncode() -> String { let encodedURL = CFURLCreateStringByAddingPercentEscapes( nil, self as NSString, nil, "!@#$%&*'();:=+,/?[]", CFStringBuiltInEncodings.UTF8.rawValue) return encodedURL as String } } public class TranslateQuery { private let translateQuery = "https://www.googleapis.com/language/translate/v2" private let getLanguagesQuery = "https://www.googleapis.com/language/translate/v2/languages" private let detectLanguageQuery = "https://www.googleapis.com/language/translate/v2/detect" private var sourceStr:String private var sourceLang:String private var targetLang:String="en" private var status="error" private var defaultQuery:String private var jsonName:String private var parameters:NSMutableDictionary = NSMutableDictionary() var languages:Array<Language>; var queryResult:String var queryResultMessage:String init(sourceString:String, optional sourceLanguage:String, optional targetLanguage:String, withKey apiKey:String) { sourceStr = sourceString sourceLang=sourceLanguage if (!targetLanguage.isEmpty) { targetLang=targetLanguage } if (!sourceLanguage.isEmpty) { sourceLang=sourceLanguage } status = "" queryResult = "" queryResultMessage = "Nothing done..." defaultQuery = detectLanguageQuery jsonName = "detections" languages=Array<Language>() addParameter(named: "key", value: apiKey) } func translate() -> Bool { addParameter(named: "target",value: targetLang) addParameter(named: "q",value: sourceStr.urlEncode()) let availableLangs = languages.filter { $0.targetLanguage == targetLang } if (availableLangs.isEmpty) { //discover supported languages for this target language setType(TranslateQueryType.GET_LANGUAGES) let arrResults=runQuery() for result in arrResults { let lang=Language() lang.targetLanguage=targetLang for (key,val) in result as! NSDictionary { if (key as! String == "language") { lang.supportedLanguageCode=val as! String } if (key as! String == "name") { lang.supportedLanguageName=val as! String } } languages.append(lang) } } if (sourceLang.isEmpty) { setType(TranslateQueryType.DETECT) let arrResults=runQuery() if (arrResults.count>0) { if let result = arrResults.lastObject!.lastObject as? NSDictionary { sourceLang=result["language"] as! String queryResultMessage="Detected" } } else { queryResultMessage="Сannot determine source language" return false } } addParameter(named: "source",value: sourceLang) //here we should have known source and target languages let thisLang = languages.filter { $0.targetLanguage == targetLang && $0.supportedLanguageCode == sourceLang} //report with friendlyname of detected language if (!thisLang.isEmpty) { queryResultMessage+=" " + thisLang[0].supportedLanguageName queryResultMessage=queryResultMessage.stringByTrimmingCharactersInSet( NSCharacterSet.whitespaceAndNewlineCharacterSet()) } //now let's translate stuff let array = sourceStr.componentsSeparatedByString("\n") for translateThis in array { setType(TranslateQueryType.TRANSLATE) addParameter(named: "q",value: translateThis.urlEncode()) let arrResults=runQuery() if (status == "error") { queryResultMessage=arrResults[0] as! String return false } else { for result in arrResults { for (key,val) in (result as? NSDictionary)! { if (key as! String == "translatedText") { queryResult+=val as! String + "\n" } } } } } return true } private func setType(type:TranslateQueryType) { switch type{ case TranslateQueryType.TRANSLATE: defaultQuery = translateQuery status = "" jsonName = "translations" case TranslateQueryType.GET_LANGUAGES: defaultQuery = getLanguagesQuery status = "" jsonName = "languages" case TranslateQueryType.DETECT: defaultQuery = detectLanguageQuery status = "" jsonName = "detections" } } private func addParameter(named name:String, value val:String) { parameters.setObject(val, forKey: name) } private func runQuery() -> NSArray { var query:String = "\(defaultQuery)?" for (parameter, value) in parameters { query += "&\(parameter)=\(value)" } let request = NSMutableURLRequest(URL: NSURL(string: query)!) request.HTTPMethod = "GET" request.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "content-type") var response:NSURLResponse? do { let responseData:NSData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) let jsonResult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary if (jsonResult.objectForKey("data") != nil){ return (jsonResult.objectForKey("data") as! NSDictionary).objectForKey(jsonName) as! NSArray } else if(jsonResult.objectForKey("error") != nil) { status="error" return (jsonResult.objectForKey("error")as! NSDictionary).allValues } else { return NSArray() } } catch { return NSArray() } } } class Language { var targetLanguage: String = "" var supportedLanguageCode = "" var supportedLanguageName = "" } private enum TranslateQueryType:Int { case TRANSLATE = 1 case GET_LANGUAGES = 2 case DETECT = 3 }
gpl-2.0
e91da64e1cc4467419069b2da46dab5e
31.929577
164
0.567722
5.230425
false
false
false
false
alvarozizou/Noticias-Leganes-iOS
Pods/Kingfisher/Sources/Image/ImageProgressive.swift
2
10721
// // ImageProgressive.swift // Kingfisher // // Created by lixiang on 2019/5/10. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics private let sharedProcessingQueue: CallbackQueue = .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) public struct ImageProgressive { /// A default `ImageProgressive` could be used across. public static let `default` = ImageProgressive( isBlur: true, isFastestScan: true, scanInterval: 0 ) /// Whether to enable blur effect processing let isBlur: Bool /// Whether to enable the fastest scan let isFastestScan: Bool /// Minimum time interval for each scan let scanInterval: TimeInterval public init(isBlur: Bool, isFastestScan: Bool, scanInterval: TimeInterval) { self.isBlur = isBlur self.isFastestScan = isFastestScan self.scanInterval = scanInterval } } protocol ImageSettable: AnyObject { var image: KFCrossPlatformImage? { get set } } final class ImageProgressiveProvider: DataReceivingSideEffect { var onShouldApply: () -> Bool = { return true } func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { update(data: task.mutableData, with: task.callbacks) } private let option: ImageProgressive private let refresh: (KFCrossPlatformImage) -> Void private let decoder: ImageProgressiveDecoder private let queue = ImageProgressiveSerialQueue() init?(_ options: KingfisherParsedOptionsInfo, refresh: @escaping (KFCrossPlatformImage) -> Void) { guard let option = options.progressiveJPEG else { return nil } self.option = option self.refresh = refresh self.decoder = ImageProgressiveDecoder( option, processingQueue: options.processingQueue ?? sharedProcessingQueue, creatingOptions: options.imageCreatingOptions ) } func update(data: Data, with callbacks: [SessionDataTask.TaskCallback]) { guard !data.isEmpty else { return } queue.add(minimum: option.scanInterval) { completion in guard self.onShouldApply() else { self.queue.clean() completion() return } func decode(_ data: Data) { self.decoder.decode(data, with: callbacks) { image in defer { completion() } guard self.onShouldApply() else { return } guard let image = image else { return } self.refresh(image) } } if self.option.isFastestScan { decode(self.decoder.scanning(data) ?? Data()) } else { self.decoder.scanning(data).forEach { decode($0) } } } } } private final class ImageProgressiveDecoder { private let option: ImageProgressive private let processingQueue: CallbackQueue private let creatingOptions: ImageCreatingOptions private(set) var scannedCount = 0 private(set) var scannedIndex = -1 init(_ option: ImageProgressive, processingQueue: CallbackQueue, creatingOptions: ImageCreatingOptions) { self.option = option self.processingQueue = processingQueue self.creatingOptions = creatingOptions } func scanning(_ data: Data) -> [Data] { guard data.kf.contains(jpeg: .SOF2) else { return [] } guard scannedIndex + 1 < data.count else { return [] } var datas: [Data] = [] var index = scannedIndex + 1 var count = scannedCount while index < data.count - 1 { scannedIndex = index // 0xFF, 0xDA - Start Of Scan let SOS = ImageFormat.JPEGMarker.SOS.bytes if data[index] == SOS[0], data[index + 1] == SOS[1] { if count > 0 { datas.append(data[0 ..< index]) } count += 1 } index += 1 } // Found more scans this the previous time guard count > scannedCount else { return [] } scannedCount = count // `> 1` checks that we've received a first scan (SOS) and then received // and also received a second scan (SOS). This way we know that we have // at least one full scan available. guard count > 1 else { return [] } return datas } func scanning(_ data: Data) -> Data? { guard data.kf.contains(jpeg: .SOF2) else { return nil } guard scannedIndex + 1 < data.count else { return nil } var index = scannedIndex + 1 var count = scannedCount var lastSOSIndex = 0 while index < data.count - 1 { scannedIndex = index // 0xFF, 0xDA - Start Of Scan let SOS = ImageFormat.JPEGMarker.SOS.bytes if data[index] == SOS[0], data[index + 1] == SOS[1] { lastSOSIndex = index count += 1 } index += 1 } // Found more scans this the previous time guard count > scannedCount else { return nil } scannedCount = count // `> 1` checks that we've received a first scan (SOS) and then received // and also received a second scan (SOS). This way we know that we have // at least one full scan available. guard count > 1 && lastSOSIndex > 0 else { return nil } return data[0 ..< lastSOSIndex] } func decode(_ data: Data, with callbacks: [SessionDataTask.TaskCallback], completion: @escaping (KFCrossPlatformImage?) -> Void) { guard data.kf.contains(jpeg: .SOF2) else { CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } return } func processing(_ data: Data) { let processor = ImageDataProcessor( data: data, callbacks: callbacks, processingQueue: processingQueue ) processor.onImageProcessed.delegate(on: self) { (self, result) in guard let image = try? result.0.get() else { CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } return } CallbackQueue.mainCurrentOrAsync.execute { completion(image) } } processor.process() } // Blur partial images. let count = scannedCount if option.isBlur, count < 6 { processingQueue.execute { // Progressively reduce blur as we load more scans. let image = KingfisherWrapper<KFCrossPlatformImage>.image( data: data, options: self.creatingOptions ) let radius = max(2, 14 - count * 4) let temp = image?.kf.blurred(withRadius: CGFloat(radius)) processing(temp?.kf.data(format: .JPEG) ?? data) } } else { processing(data) } } } private final class ImageProgressiveSerialQueue { typealias ClosureCallback = ((@escaping () -> Void)) -> Void private let queue: DispatchQueue = .init(label: "com.onevcat.Kingfisher.ImageProgressive.SerialQueue") private var items: [DispatchWorkItem] = [] private var notify: (() -> Void)? private var lastTime: TimeInterval? var count: Int { return items.count } func add(minimum interval: TimeInterval, closure: @escaping ClosureCallback) { let completion = { [weak self] in guard let self = self else { return } self.queue.async { [weak self] in guard let self = self else { return } guard !self.items.isEmpty else { return } self.items.removeFirst() if let next = self.items.first { self.queue.asyncAfter( deadline: .now() + interval, execute: next ) } else { self.lastTime = Date().timeIntervalSince1970 self.notify?() self.notify = nil } } } queue.async { [weak self] in guard let self = self else { return } let item = DispatchWorkItem { closure(completion) } if self.items.isEmpty { let difference = Date().timeIntervalSince1970 - (self.lastTime ?? 0) let delay = difference < interval ? interval - difference : 0 self.queue.asyncAfter(deadline: .now() + delay, execute: item) } self.items.append(item) } } func notify(_ closure: @escaping () -> Void) { self.notify = closure } func clean() { queue.async { [weak self] in guard let self = self else { return } self.items.forEach { $0.cancel() } self.items.removeAll() } } }
mit
ad1bc7fe55221885b411e148fc82a57a
33.695793
106
0.561608
4.938277
false
false
false
false
ismailbozkurt77/ZendeskClient
ZendeskExercise/Modules/TicketList/Presenter/TicketListPresenter.swift
1
1250
// // TicketListPresenter.swift // ZendeskExercise // // Created by Ismail on 07/01/2017. // Copyright © 2017 Zendesk. All rights reserved. // import UIKit class TicketListPresenter: NSObject, TicketListEventHandler { // MARK: - Properties var interactor: TicketListInteractor weak var view: TicketListView? private let mapper = TicketMapper() // MARK: - Lifecycle init(view: TicketListView, interactor: TicketListInteractor) { self.view = view self.interactor = interactor } // MARK: - <TicketListEventHandler> func viewIsReady() { fetchTickets() } func retry() { fetchTickets() } // MARK: - Private Helpers func fetchTickets() { self.view?.displayLoading() self.interactor.fetchTickets { [weak self] (tickets: [Ticket]?, error: Error?) in self?.view?.dismissLoading() if error == nil && tickets != nil { let tickets = self?.mapper.ticketViewModelArray(models: tickets!) self?.view?.displayTickets(tickets) } else if error != nil { self?.view?.displayError(error: error!) } } } }
mit
291df7786c9584452752dfcd52741142
25.020833
89
0.579664
4.509025
false
false
false
false
esttorhe/SwiftObjLoader
SwiftObjLoaderTests/ObjLoaderTests.swift
1
4663
// // ObjLoaderTests.swift // SwiftObjLoader // // Created by Hugo Tunius on 02/09/15. // Copyright © 2015 Hugo Tunius. All rights reserved. // import XCTest @testable import SwiftObjLoader class ObjLoaderTests: XCTestCase { var fixtureHelper: FixtureHelper! override func setUp() { fixtureHelper = FixtureHelper() } func testSimple() { let source = try? fixtureHelper.loadObjFixture("simple") let loader = ObjLoader(source: source!) do { let shapes = try loader.read() XCTAssertEqual(shapes.count, 1) let vertices = [ // v 1.000905 -0.903713 -1.120729 [1.000905, -0.903713, -1.120729, 1.0], // v 1.000905 -0.903713 0.879271 [1.000905, -0.903713, 0.879271, 1.0], // v -0.999095 -0.903713 0.879271 [-0.999095, -0.903713, 0.879271, 1.0], // v -0.999095 -0.903713 -1.120729 [-0.999095, -0.903713, -1.120729, 1.0], // v 1.000905 1.096287 -1.120728 [1.000905, 1.096287, -1.120728, 1.0], // v 1.000904 1.096287 0.879272 [1.000904, 1.096287, 0.879272, 1.0], // v -0.999095 1.096287 0.879271 [-0.999095, 1.096287, 0.879271, 1.0], // v -0.999095 1.096287 -1.120729 [-0.999095, 1.096287, -1.120729, 1.0] ] let normals = [ // vn 0.000000 -1.000000 0.000000 [0.000000, -1.000000, 0.000000, 1.0], // vn 0.000000 1.000000 0.000000 [0.000000, 1.000000, 0.000000, 1.0], // vn 1.000000 0.000000 0.000000 [1.000000, 0.000000, 0.000000, 1.0], // vn 1.000000 0.000000 0.000000 [-0.000000, -0.000000, 1.000000, 1.0], // vn -1.000000 -0.000000 -0.000000 [-1.000000, -0.000000, -0.000000, 1.0], // vn 0.000000 0.000000 -1.000000 [0.000000, 0.000000, -1.000000, 1.0] ] let faces = [ // f 1//1 2//1 3//1 4//1 [ VertexIndex(vIndex: 0, nIndex: 0, tIndex: nil), VertexIndex(vIndex: 1, nIndex: 0, tIndex: nil), VertexIndex(vIndex: 2, nIndex: 0, tIndex: nil), VertexIndex(vIndex: 3, nIndex: 0, tIndex: nil) ], // f 5//2 8//2 7//2 6//2 [ VertexIndex(vIndex: 4, nIndex: 1, tIndex: nil), VertexIndex(vIndex: 7, nIndex: 1, tIndex: nil), VertexIndex(vIndex: 6, nIndex: 1, tIndex: nil), VertexIndex(vIndex: 5, nIndex: 1, tIndex: nil) ], // f 1//3 5//3 6//3 2//3 [ VertexIndex(vIndex: 0, nIndex: 2, tIndex: nil), VertexIndex(vIndex: 4, nIndex: 2, tIndex: nil), VertexIndex(vIndex: 5, nIndex: 2, tIndex: nil), VertexIndex(vIndex: 1, nIndex: 2, tIndex: nil) ], // f 2//4 6//4 7//4 3//4 [ VertexIndex(vIndex: 1, nIndex: 3, tIndex: nil), VertexIndex(vIndex: 5, nIndex: 3, tIndex: nil), VertexIndex(vIndex: 6, nIndex: 3, tIndex: nil), VertexIndex(vIndex: 2, nIndex: 3, tIndex: nil) ], // f 3//5 7//5 8//5 4//5 [ VertexIndex(vIndex: 2, nIndex: 4, tIndex: nil), VertexIndex(vIndex: 6, nIndex: 4, tIndex: nil), VertexIndex(vIndex: 7, nIndex: 4, tIndex: nil), VertexIndex(vIndex: 3, nIndex: 4, tIndex: nil) ], // f 5//6 1//6 4//6 8//6 [ VertexIndex(vIndex: 4, nIndex: 5, tIndex: nil), VertexIndex(vIndex: 0, nIndex: 5, tIndex: nil), VertexIndex(vIndex: 3, nIndex: 5, tIndex: nil), VertexIndex(vIndex: 7, nIndex: 5, tIndex: nil) ] ] let expectedShape = Shape(name: "Cube", vertices: vertices, normals: normals, textureCoords: [], faces: faces) XCTAssertEqual(expectedShape, shapes[0]) } catch ObjLoadingError.UnexpectedFileFormat(let errorMessage) { XCTFail("Parsing failed with error \(errorMessage)") } catch { XCTFail("Parsing failed with unknown error") } } }
mit
78e749166d62fcb289c421f30bcc82ee
41.381818
122
0.465036
3.515837
false
true
false
false
TCA-Team/iOS
TUM Campus App/DataSources/LecturesDataSource.swift
1
3244
// // LecturesDataSource.swift // Campus // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // 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, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit class LecturesDataSource: NSObject, TUMDataSource, TUMInteractiveDataSource { let parent: CardViewController var manager: PersonalLectureManager let cellType: AnyClass = LecturesCollectionViewCell.self var isEmpty: Bool { return data.isEmpty } let cardKey: CardKey = .lectures var data: [Lecture] = [] var preferredHeight: CGFloat = 252.0 lazy var flowLayoutDelegate: ColumnsFlowLayoutDelegate = FixedColumnsVerticalItemsFlowLayoutDelegate(delegate: self) init(parent: CardViewController, manager: PersonalLectureManager) { self.parent = parent self.manager = manager super.init() } func refresh(group: DispatchGroup) { group.enter() manager.fetch().onSuccess(in: .main) { data in self.data = data group.leave() } } func onItemSelected(at indexPath: IndexPath) { let storyboard = UIStoryboard(name: "LectureDetail", bundle: nil) let lecture = data[indexPath.row] if let destination = storyboard.instantiateInitialViewController() as? LectureDetailsTableViewController { destination.delegate = parent destination.lecture = lecture parent.navigationController?.pushViewController(destination, animated: true) } } func onShowMore() { let storyboard = UIStoryboard(name: "Lecture", bundle: nil) if let destination = storyboard.instantiateInitialViewController() as? LecturesTableViewController { destination.delegate = parent destination.values = data parent.navigationController?.pushViewController(destination, animated: true) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: cellReuseID, for: indexPath) as! LecturesCollectionViewCell let lecture = data[indexPath.row] cell.lectureNameLabel.text = lecture.name cell.semesterLabel.text = lecture.semester cell.iconLabel.text = String(lecture.type.first ?? "-") return cell } }
gpl-3.0
86a6809eac7459bf74f1361eb96d763e
35.863636
114
0.67016
5.01391
false
false
false
false
jhwayne/Minimo
TouchID/TouchID/LoginViewController.swift
1
4559
// // LoginViewController.swift // TouchID // // Created by Simon Ng on 24/2/15. // Copyright (c) 2015 AppCoda. All rights reserved. // import UIKit import LocalAuthentication class LoginViewController: UIViewController { @IBOutlet weak var backgroundImageView:UIImageView! @IBOutlet weak var loginView:UIView! @IBOutlet weak var emailTextField:UITextField! @IBOutlet weak var passwordTextField:UITextField! @IBAction func authenticateWithPassword() { if emailTextField.text == "[email protected]" && passwordTextField.text == "1234" { performSegueWithIdentifier("showHomeScreen", sender: nil) }else { // Shake to indicate wrong login ID/password loginView.transform = CGAffineTransformMakeTranslation(25, 0) UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.15, initialSpringVelocity: 0.3, options: .CurveEaseInOut, animations: { self.loginView.transform = CGAffineTransformIdentity }, completion: nil) } } private var imageSet = ["coffee"] func authenticateWithTouchID(){ //Get the local authentication context. let localAuthContext = LAContext() let reasonText = "Authentication is required to login to Brew" var authError: NSError? if !localAuthContext.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &authError) { println(authError?.localizedDescription) // Display the login dialog when Touch ID is not available (e.g. in simulator) showLoginDialog() return } // Perform the Touch ID authentication localAuthContext.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reasonText, reply: { (success: Bool, error: NSError!) -> Void in if success { println("Successfully authenticated") NSOperationQueue.mainQueue().addOperationWithBlock({ self.performSegueWithIdentifier("showHomeScreen", sender: nil) }) } else { switch error.code { case LAError.AuthenticationFailed.rawValue: println("Authentication failed") case LAError.PasscodeNotSet.rawValue: println("Passcode not set") case LAError.SystemCancel.rawValue: println("Authentication was canceled by system") case LAError.UserCancel.rawValue: println("Authentication was canceled by the user") case LAError.TouchIDNotEnrolled.rawValue: println("Authentication could not start because Touch ID has no enrolled fingers.") case LAError.TouchIDNotAvailable.rawValue: println("Authentication could not start because Touch ID is not available.") case LAError.UserFallback.rawValue: println("User tapped the fallback button (Enter Password).") default: println(error.localizedDescription) } // Fallback to password authentication NSOperationQueue.mainQueue().addOperationWithBlock({ self.showLoginDialog() }) } }) } override func viewDidLoad() { super.viewDidLoad() // Randomly pick an image let selectedImageIndex = Int(arc4random_uniform(0)) // Apply blurring effect backgroundImageView.image = UIImage(named: imageSet[selectedImageIndex]) // let blurEffect = UIBlurEffect(style: .Dark) // let blurEffectView = UIVisualEffectView(effect: blurEffect) // blurEffectView.frame = view.bounds // backgroundImageView.addSubview(blurEffectView) loginView.hidden = true authenticateWithTouchID() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func showLoginDialog() { // Move the login view off screen loginView.hidden = false loginView.transform = CGAffineTransformMakeTranslation(0, -700) UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: .CurveEaseInOut, animations: { self.loginView.transform = CGAffineTransformIdentity }, completion: nil) } }
mit
69db52a034fd58cf78a1c59a8ba84d47
37.635593
171
0.636762
5.859897
false
false
false
false
alitaso345/swift-annict-client
AnnictAPIClient/Status.swift
1
427
enum Status { case wanna_watch case watching case watched case on_hold case stop_watching init?(kind: String) { switch kind { case "wanna_watch": self = .wanna_watch case "watching": self = .watching case "watched": self = .watched case "on_hold": self = .on_hold case "stop_watching": self = .stop_watching default: return nil } } }
mit
c58371a85beb73b849671415cb08e330
22.722222
51
0.559719
3.990654
false
false
false
false
pantuspavel/PPAssetsActionController
PPAssetsActionController/Classes/PPAssetsActionConfig.swift
1
1593
import UIKit /** Configuration of Assets Action Controller. */ public struct PPAssetsActionConfig { /// Tint Color. System's by default. public var tintColor = UIView().tintColor /// Font to be used on buttons. public var font = UIFont.systemFont(ofSize: 19.0) /** Indicates whether Assets Action Controller should ask for photo permissions in case they were not previously granted. If false, no room will be allocated for Assets View Controller. */ public var askPhotoPermissions = true /// Regular (folded) height of Assets View Controller. public var assetsPreviewRegularHeight: CGFloat = 140.0 /// Expanded height of Assets View Controller. public var assetsPreviewExpandedHeight: CGFloat = 220.0 /// Left, Right and Bottom insets of Assets Action Controller. public var inset: CGFloat = 16.0 /// Spacing between Cancel and option buttons. public var sectionSpacing: CGFloat = 16.0 /// Background color of Assets View Controller. public var backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.35) /// In and Out animation duration. public var animationDuration: TimeInterval = 0.5 /// Height of each button (Options and Cancel). public var buttonHeight: CGFloat = 50.0 /// If enabled shows live camera view as a first cell. public var showLiveCameraCell = true /// If enabled shows videos in Assets Collection Controller and autoplays them. public var showVideos = true public init() {} }
mit
3266a71f6e0e8ffa454c347b540de102
31.510204
88
0.679849
4.886503
false
false
false
false
vvw/XWebView
XWebView/XWVLoader.swift
2
1933
/* Copyright 2015 XWebView Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation public class XWVLoader: NSObject, XWVScripting { private let _inventory: XWVInventory public init(inventory: XWVInventory) { self._inventory = inventory super.init() } func defaultMethod(namespace: String, argument: AnyObject?, _Promise: XWVScriptObject) { if let plugin: AnyClass = _inventory.plugin(forNamespace: namespace), let channel = scriptObject?.channel { let initializer = Selector(argument == nil ? "init" : "initWitArgument:") let args: [AnyObject]? = argument == nil ? nil : [argument!] let object = XWVInvocation.constructOnThread(channel.thread, `class`: plugin, initializer: initializer, arguments: args) as! NSObject! if object != nil, let obj = channel.webView?.loadPlugin(object, namespace: namespace) { _Promise.callMethod("resolve", withArguments: [obj], resultHandler: nil) return } } _Promise.callMethod("reject", withArguments: nil, resultHandler: nil) } public class func isSelectorForDefaultMethod(selector: Selector) -> Bool { return selector == Selector("defaultMethod:argument:_Promise:") } public class func isSelectorExcludedFromScript(selector: Selector) -> Bool { return selector != Selector("defaultMethod:argument:_Promise:") } }
apache-2.0
c1b39cf1133cc3bb64af56887a49001e
41.021739
146
0.69581
4.737745
false
false
false
false
gtranchedone/FlickrParty
FlickrPartyTests/AppDelegateTests.swift
1
3996
// // AppDelegateTests.swift // FlickrParty // // Created by Gianluca Tranchedone on 04/05/2015. // Copyright (c) 2015 Gianluca Tranchedone. All rights reserved. // import UIKit import XCTest import FlickrParty class AppDelegateTests: XCTestCase { var appDelegate: AppDelegate? override func setUp() { super.setUp() appDelegate = AppDelegate() appDelegate?.application(UIApplication.sharedApplication(), didFinishLaunchingWithOptions: nil) } override func tearDown() { appDelegate = nil super.tearDown() } // MARK: - Tests for Application Setup func testRootViewControllerIsTabBarController() { let window = appDelegate?.window let rootViewController = window?.rootViewController XCTAssert(rootViewController is UITabBarController, "The app's rootViewController isn't a TabBarController") } // MARK: First Tab (Photos from Parties) func testViewControllerInFirstTabHasAppropriateTitleAfterViewDidLoad() { let viewController = viewControllerInFirstTab() let actualTitle = viewController!.title XCTAssertEqual("All Parties", actualTitle!, "PartyPhotosViewController doesn't have an appropriate title") } func testRootViewControllerHasPartyPhotosControllerAsFirstTab() { let viewController = viewControllerInFirstTab() XCTAssert(viewController is PhotosViewController, "The first tab doesn't contain a PartyPhotosViewController") } func testPartyPhotosViewControllerHasPhotoDataSource() { let window = appDelegate?.window let rootViewController = window?.rootViewController as? UITabBarController let navigationController: UINavigationController? = rootViewController?.viewControllers?.first as? UINavigationController let viewController = navigationController?.viewControllers.first as? PhotosViewController XCTAssertTrue(viewController?.dataSource! is PhotosDataSource, "The PhotosViewController hasn't the right dataSource") } func testPartyPhotosViewControllerHasPhotoDataSourceWithRightAPIClient() { let window = appDelegate?.window let rootViewController = window?.rootViewController as? UITabBarController let navigationController: UINavigationController? = rootViewController?.viewControllers?.first as? UINavigationController let viewController = navigationController?.viewControllers.first as? PhotosViewController XCTAssertTrue(viewController!.dataSource!.apiClient is FlickrAPIClient, "The photosDataSource wasn't setup properly") } // MARK: Second Tab (Photos from Parties Near You) func testViewControllerInSecondTabHasAppropriateTitleAfterViewDidLoad() { let viewController = viewControllerInSecondTab() let actualTitle = viewController!.title XCTAssertEqual("Parties Nearby", actualTitle!, "PartyPhotosViewController doesn't have an appropriate title") } func testRootViewControllerHasNearbyPartyPhotosControllerAsSecondTab() { let viewController = viewControllerInSecondTab() XCTAssert(viewController is NearbyPartyPhotosViewController, "The second tab doesn't contain a NearbyPartyPhotosViewController") } // MARK: Private func viewControllerInFirstTab() -> UIViewController? { return viewControllerInTabAtIndex(0) } func viewControllerInSecondTab() -> UIViewController? { return viewControllerInTabAtIndex(1) } func viewControllerInTabAtIndex(index: Int) -> UIViewController? { let window = appDelegate?.window let rootViewController = window?.rootViewController as? UITabBarController let navigationController: UINavigationController? = rootViewController?.viewControllers?[index] as? UINavigationController let viewController = navigationController?.viewControllers.first return viewController } }
mit
d84f4dda207de6ff48b3a3b1db735304
40.625
136
0.737988
6.176198
false
true
false
false
roecrew/AudioKit
AudioKit/Common/Nodes/Effects/Reverb/Flat Frequency Response Reverb/AKFlatFrequencyResponseReverb.swift
1
4653
// // AKFlatFrequencyResponseReverb.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// This filter reiterates the input with an echo density determined by loop /// time. The attenuation rate is independent and is determined by the /// reverberation time (defined as the time in seconds for a signal to decay to /// 1/1000, or 60dB down from its original amplitude). Output will begin to /// appear immediately. /// /// - Parameters: /// - input: Input node to process /// - reverbDuration: The duration in seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude. /// - loopDuration: The loop duration of the filter, in seconds. This can also be thought of as the delay time or “echo density” of the reverberation. /// public class AKFlatFrequencyResponseReverb: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKFlatFrequencyResponseReverbAudioUnit? internal var token: AUParameterObserverToken? private var reverbDurationParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// The duration in seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude. public var reverbDuration: Double = 0.5 { willSet { if reverbDuration != newValue { if internalAU!.isSetUp() { reverbDurationParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.reverbDuration = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this reverb node /// /// - Parameters: /// - input: Input node to process /// - reverbDuration: The duration in seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude. /// - loopDuration: The loop duration of the filter, in seconds. This can also be thought of as the delay time or “echo density” of the reverberation. /// public init( _ input: AKNode, reverbDuration: Double = 0.5, loopDuration: Double = 0.1) { self.reverbDuration = reverbDuration var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = fourCC("alps") description.componentManufacturer = fourCC("AuKt") description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKFlatFrequencyResponseReverbAudioUnit.self, asComponentDescription: description, name: "Local AKFlatFrequencyResponseReverb", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKFlatFrequencyResponseReverbAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) self.internalAU!.setLoopDuration(Float(loopDuration)) } guard let tree = internalAU?.parameterTree else { return } reverbDurationParameter = tree.valueForKey("reverbDuration") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.reverbDurationParameter!.address { self.reverbDuration = Double(value) } } } internalAU?.reverbDuration = Float(reverbDuration) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
854462258dd16458485e01ceb9250ad0
34.730769
156
0.646502
5.382387
false
false
false
false
liuwin7/FDCountDownView
FDCountDownView/Classes/FDLoginView.swift
1
15716
// // FDLoginView.swift // Pods // // Created by tropsci on 16/5/11. // // import UIKit public class FDLoginView: UIView { public enum FDLoginStatus { case NoneState case Success case Failure case Reset case Loading } // MARK: - public propertise /// modify this status to control the button status public var loadingStatus: FDLoginStatus = .NoneState { didSet { switch loadingStatus { case .Reset: self.animateForReset() case .Failure: self.animateForFailed() case .Success: self.animateForSuccess() default: break } } } public var title: String // MARK: - private properties private let tapActionSelector = #selector(tapAction(_:)) private var tapGesture: UITapGestureRecognizer! private var backgroundLayer: CAShapeLayer! private var textLayer: CATextLayer! private var isLoading: Bool = false private var successLayer: CAShapeLayer? private var faliureLayer: CAShapeLayer? public init(frame: CGRect, title: String) { self.title = title super.init(frame: frame) setupBackgroundLayer() setupTextLayer(self.title) setupTapGesture() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupBackgroundLayer() { backgroundLayer = CAShapeLayer() backgroundLayer.frame = self.bounds let backgroundStartPath = UIBezierPath(roundedRect: backgroundLayer.bounds, cornerRadius: 5) backgroundLayer.path = backgroundStartPath.CGPath backgroundLayer.fillColor = UIColor.clearColor().CGColor backgroundLayer.strokeColor = UIColor.greenColor().CGColor backgroundLayer.lineWidth = 2 self.layer.addSublayer(backgroundLayer) } private func setupTextLayer(textContent: String) { textLayer = CATextLayer() textLayer.contentsScale = UIScreen.mainScreen().scale textLayer.string = textContent textLayer.fontSize = 16 let textLayerFrame = CGRectInset(self.bounds, 0, (self.bounds.size.height - textLayer.fontSize) / 4) textLayer.frame = textLayerFrame textLayer.foregroundColor = UIColor.blackColor().CGColor textLayer.alignmentMode = kCAAlignmentCenter self.layer.addSublayer(textLayer) } private func setupTapGesture() { tapGesture = UITapGestureRecognizer(target: self, action:tapActionSelector) tapGesture.enabled = true addGestureRecognizer(tapGesture) } // MARK: - Action @objc private func tapAction(tapGestureRecognizer: UITapGestureRecognizer) -> Void { if !isLoading { animateTextLayer() animateBackgroundLayer() loadingStatus = .Loading isLoading = true } else { loadingStatus = .Reset } } /// animate text layer private func animateTextLayer() { // opacity let textLayerAnimation = CABasicAnimation(keyPath: "opacity") textLayerAnimation.toValue = 0 // transform.scale let shrinkAnimation = CABasicAnimation(keyPath: "transform.scale") shrinkAnimation.toValue = 0.4 let textGroupAnimation = CAAnimationGroup() textGroupAnimation.animations = [textLayerAnimation, shrinkAnimation] textGroupAnimation.duration = 0.75 textGroupAnimation.removedOnCompletion = false textGroupAnimation.fillMode = kCAFillModeBoth textLayer.addAnimation(textGroupAnimation, forKey: "text animation") } private func animateBackgroundLayer() { backgroundLayer.removeAllAnimations() // background layer animation let keyFrameAnimation = CAKeyframeAnimation(keyPath: "path") // middle 1 let middleRect1 = CGRectInset(backgroundLayer.bounds, backgroundLayer.bounds.size.width / 6, 0) let middlePath1 = UIBezierPath(roundedRect: middleRect1, cornerRadius: 6) // middle 2 let middleRect2 = CGRectInset(backgroundLayer.bounds, backgroundLayer.bounds.size.width / 3, 0) let middlePath2 = UIBezierPath(roundedRect: middleRect2, cornerRadius: 7) // end let sideLength = min(backgroundLayer.bounds.size.width, backgroundLayer.bounds.size.height) let backX = CGRectGetMidX(backgroundLayer.frame) - sideLength / 2 let backY = CGRectGetMidY(backgroundLayer.frame) - sideLength / 2 let endBackgroundRect = CGRect(x: backX, y: backY, width: sideLength, height: sideLength) let endPath = UIBezierPath(roundedRect: endBackgroundRect, cornerRadius: sideLength / 2 ) keyFrameAnimation.values = [backgroundLayer.path!, middlePath1.CGPath, middlePath2.CGPath, endPath.CGPath] keyFrameAnimation.duration = 0.75 keyFrameAnimation.removedOnCompletion = false keyFrameAnimation.fillMode = kCAFillModeBackwards keyFrameAnimation.calculationMode = kCAAnimationCubic keyFrameAnimation.delegate = self backgroundLayer.addAnimation(keyFrameAnimation, forKey: "background animation 1") // update shape path let center = CGPoint(x: CGRectGetMidX(endBackgroundRect), y: CGRectGetMidY(endBackgroundRect)) let radius = sideLength / 2 let startAnagle = CGFloat(M_PI_4) let endAnagle = CGFloat(M_PI) * 2 let partialCirclePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAnagle, endAngle: endAnagle, clockwise: true) self.backgroundLayer.path = partialCirclePath.CGPath let afterOneSecond = dispatch_time(DISPATCH_TIME_NOW, Int64(750 * USEC_PER_SEC)) dispatch_after(afterOneSecond, dispatch_get_main_queue()) { // keyframe animation for spin the circle let values = (0...8).flatMap({ (count) -> CGFloat? in CGFloat(M_PI_4) * CGFloat(count) }) let circleKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") circleKeyframeAnimation.values = values circleKeyframeAnimation.duration = 1.5 circleKeyframeAnimation.repeatCount = HUGE circleKeyframeAnimation.removedOnCompletion = false circleKeyframeAnimation.fillMode = kCAFillModeBoth self.backgroundLayer.addAnimation(circleKeyframeAnimation, forKey: "circle keyframe animation") } } private func animateForReset() { if !isLoading { return } isLoading = false tapGesture.enabled = true self.successLayer?.removeFromSuperlayer() self.faliureLayer?.removeFromSuperlayer() self.backgroundLayer.removeAllAnimations() let sideLength = min(backgroundLayer.bounds.size.width, backgroundLayer.bounds.size.height) let backX = CGRectGetMidX(backgroundLayer.frame) - sideLength / 2 let backY = CGRectGetMidY(backgroundLayer.frame) - sideLength / 2 let backgroundRect = CGRect(x: backX, y: backY, width: sideLength, height: sideLength) // init let initPath = UIBezierPath(roundedRect: backgroundRect, cornerRadius: sideLength / 2) self.backgroundLayer.path = initPath.CGPath let keyframeAnimation = CAKeyframeAnimation(keyPath: "path") // middle 1 let middleRect1 = CGRectInset(backgroundLayer.bounds, backgroundLayer.bounds.size.width / 3, 0) let middlePath1 = UIBezierPath(roundedRect: middleRect1, cornerRadius: 7) // middle 2 let middleRect2 = CGRectInset(backgroundLayer.bounds, backgroundLayer.bounds.size.width / 6, 0) let middlePath2 = UIBezierPath(roundedRect: middleRect2, cornerRadius: 6) // end let endRect = backgroundLayer.bounds let endPath = UIBezierPath(roundedRect: endRect, cornerRadius: 5) keyframeAnimation.values = [initPath.CGPath, middlePath1.CGPath, middlePath2.CGPath, endPath.CGPath] keyframeAnimation.duration = 0.75 keyframeAnimation.removedOnCompletion = false keyframeAnimation.fillMode = kCAFillModeBoth keyframeAnimation.calculationMode = kCAAnimationCubic backgroundLayer.addAnimation(keyframeAnimation, forKey: "background_animation_reset") backgroundLayer.path = endPath.CGPath // text reset // opacity let textLayerAnimation = CABasicAnimation(keyPath: "opacity") textLayerAnimation.toValue = 1 // transform.scale let shrinkAnimation = CABasicAnimation(keyPath: "transform.scale") shrinkAnimation.toValue = 1 let textGroupAnimation = CAAnimationGroup() textGroupAnimation.animations = [textLayerAnimation, shrinkAnimation] textGroupAnimation.duration = 0.75 textGroupAnimation.removedOnCompletion = false textGroupAnimation.fillMode = kCAFillModeBoth textLayer.addAnimation(textGroupAnimation, forKey: "text animation reset") } private func animateForSuccess() { if !isLoading { return } isLoading = false tapGesture.enabled = false let sideLength = min(backgroundLayer.bounds.size.width, backgroundLayer.bounds.size.height) let backX = CGRectGetMidX(backgroundLayer.frame) - sideLength / 2 let backY = CGRectGetMidY(backgroundLayer.frame) - sideLength / 2 let endBackgroundRect = CGRect(x: backX, y: backY, width: sideLength, height: sideLength) self.backgroundLayer.path = UIBezierPath(ovalInRect: endBackgroundRect).CGPath // add success layer successLayer = CAShapeLayer() successLayer?.lineWidth = 2 successLayer?.frame = endBackgroundRect successLayer?.fillColor = UIColor.clearColor().CGColor successLayer?.strokeColor = UIColor.greenColor().CGColor let bezier = UIBezierPath() let startPoint_X: CGFloat = 2 let circleRadius = sideLength / 2 // (x - r)^2 + (y - r)^2 = r^2 // using max value let startPoint_Y = self.yValueFor(startPoint_X, circleRadius: circleRadius, selectMaxValue: true) let padding: CGFloat = 4 let startPoint = CGPoint(x: startPoint_X + 1, y: floor(startPoint_Y) - padding) bezier.moveToPoint(startPoint) let middlePoint = CGPoint(x: sideLength / 2 - 1, y: sideLength - padding) bezier.addLineToPoint(middlePoint) let endPoint_X = sideLength - 2 let endPoint_Y = self.yValueFor(endPoint_X, circleRadius: circleRadius, selectMaxValue: false) let endPoint = CGPoint(x: endPoint_X - 1 , y: floor(endPoint_Y) + padding) bezier.addLineToPoint(endPoint) successLayer?.path = bezier.CGPath self.layer.addSublayer(successLayer!) // animation let keyframeAnimation = CAKeyframeAnimation(keyPath: "strokeEnd") keyframeAnimation.values = [0.3, 0.7, 1] keyframeAnimation.repeatCount = 1 keyframeAnimation.fillMode = kCAFillModeBoth keyframeAnimation.autoreverses = false keyframeAnimation.duration = 0.25 successLayer?.addAnimation(keyframeAnimation, forKey: "success_keyframe_animation") } private func animateForFailed() { if !isLoading { return } isLoading = false tapGesture.enabled = false let sideLength = min(backgroundLayer.bounds.size.width, backgroundLayer.bounds.size.height) let backX = CGRectGetMidX(backgroundLayer.frame) - sideLength / 2 let backY = CGRectGetMidY(backgroundLayer.frame) - sideLength / 2 let endBackgroundRect = CGRect(x: backX, y: backY, width: sideLength, height: sideLength) self.backgroundLayer.strokeColor = UIColor.redColor().CGColor self.backgroundLayer.path = UIBezierPath(ovalInRect: endBackgroundRect).CGPath // add failed layer faliureLayer = CAShapeLayer() faliureLayer?.lineWidth = 2 faliureLayer?.frame = endBackgroundRect faliureLayer?.fillColor = UIColor.clearColor().CGColor faliureLayer?.strokeColor = UIColor.redColor().CGColor let bezier = UIBezierPath() // from left to right let startPoint1_X: CGFloat = 4 let circleRadius = sideLength / 2 let startPoint_Y = self.yValueFor(startPoint1_X, circleRadius: circleRadius, selectMaxValue: false) let padding: CGFloat = 1 let startPoint1 = CGPoint(x: startPoint1_X + padding, y: floor(startPoint_Y) + padding) bezier.moveToPoint(startPoint1) let endPoint1_X = sideLength - 4 let endPoint1_Y = self.yValueFor(endPoint1_X, circleRadius: circleRadius, selectMaxValue: true) let endPoint1 = CGPoint(x: endPoint1_X - padding, y: endPoint1_Y - padding) bezier.addLineToPoint(endPoint1) // from right to left let startPoint2_X = endPoint1.x let startPoint2_Y = startPoint1.y let startPoint2 = CGPoint(x: startPoint2_X , y: startPoint2_Y) bezier.moveToPoint(startPoint2) let endPoint2_X = startPoint1.x let endPoint2_Y = endPoint1.y let endPoint2 = CGPoint(x: endPoint2_X, y: endPoint2_Y) bezier.addLineToPoint(endPoint2) faliureLayer?.path = bezier.CGPath self.layer.addSublayer(faliureLayer!) // animation let keyframeAnimation = CAKeyframeAnimation(keyPath: "strokeEnd") keyframeAnimation.values = [0, 0.25, 0.5, 0.75, 1] keyframeAnimation.repeatCount = 1 keyframeAnimation.fillMode = kCAFillModeBoth keyframeAnimation.autoreverses = false keyframeAnimation.duration = 0.25 faliureLayer?.addAnimation(keyframeAnimation, forKey: "failed_keyframe_animation") } //MARK: - Helper /** Calculate the Y value for a X value - parameter pointX: a CGFloat the x value of one point - parameter circleRadius: circle radius - parameter selectMaxValue: indicate using max value or min value - returns: return the Y of one point which the X is pointX, if the pointX out of bounds return -1 */ private func yValueFor(pointX: CGFloat, circleRadius: CGFloat, selectMaxValue: Bool) -> CGFloat { if pointX < 0 || pointX > 2 * circleRadius { return -1 } let item = sqrt(pointX * (2 * circleRadius - pointX)) if selectMaxValue { return circleRadius + item } else { return circleRadius - item } } } extension FDLoginView { public override func animationDidStart(anim: CAAnimation) { self.tapGesture.enabled = false } public override func animationDidStop(anim: CAAnimation, finished flag: Bool) { self.tapGesture.enabled = true } }
mit
847fb36d6c0be209c51ff44f1508088c
37.70936
114
0.637503
5.242161
false
false
false
false
jpipard/DKImagePickerController
DKImagePickerController/DKImagePickerController.swift
1
13844
// // DKImagePickerController.swift // DKImagePickerController // // Created by ZhangAo on 14-10-2. // Copyright (c) 2014年 ZhangAo. All rights reserved. // import UIKit import Photos @objc public protocol DKImagePickerControllerUIDelegate { /** The picker calls -prepareLayout once at its first layout as the first message to the UIDelegate instance. */ func prepareLayout(imagePickerController: DKImagePickerController, vc: UIViewController) /** Returns a custom camera. **Note** If you are using a UINavigationController as the custom camera, you should also set the picker's modalPresentationStyle to .OverCurrentContext, like this: ``` pickerController.modalPresentationStyle = .OverCurrentContext ``` */ func imagePickerControllerCreateCamera(imagePickerController: DKImagePickerController, didCancel: (() -> Void), didFinishCapturingImage: ((image: UIImage) -> Void), didFinishCapturingVideo: ((videoURL: NSURL) -> Void)) -> UIViewController /** The camera image to be displayed in the album's first cell. */ func imagePickerControllerCameraImage() -> UIImage /** The layout is to provide information about the position and visual state of items in the collection view. */ func layoutForImagePickerController(imagePickerController: DKImagePickerController) -> UICollectionViewLayout.Type /** Called when the user needs to show the cancel button. */ func imagePickerController(imagePickerController: DKImagePickerController, showsCancelButtonForVC vc: UIViewController) /** Called when the user needs to hide the cancel button. */ func imagePickerController(imagePickerController: DKImagePickerController, hidesCancelButtonForVC vc: UIViewController) /** Called after the user changes the selection. */ func imagePickerController(imagePickerController: DKImagePickerController, didSelectAsset: DKAsset) /** Called after the user changes the selection. */ func imagePickerController(imagePickerController: DKImagePickerController, didDeselectAsset: DKAsset) /** Called when the selectedAssets'count did reach `maxSelectableCount`. */ func imagePickerControllerDidReachMaxLimit(imagePickerController: DKImagePickerController) /** Accessory view below content. default is nil. */ func imagePickerControllerFooterView(imagePickerController: DKImagePickerController) -> UIView? } /** - AllPhotos: Get all photos assets in the assets group. - AllVideos: Get all video assets in the assets group. - AllAssets: Get all assets in the group. */ @objc public enum DKImagePickerControllerAssetType : Int { case AllPhotos, AllVideos, AllAssets } @objc public enum DKImagePickerControllerSourceType : Int { case Camera, Photo, Both } // MARK: - Public DKImagePickerController /** * The `DKImagePickerController` class offers the all public APIs which will affect the UI. */ public class DKImagePickerController : UINavigationController { public var UIDelegate: DKImagePickerControllerUIDelegate = { return DKImagePickerControllerDefaultUIDelegate() }() /// Forces selection of tapped image immediatly. public var singleSelect = false public var backgroundColor = UIColor.whiteColor() /// The maximum count of assets which the user will be able to select. public var maxSelectableCount = 999 /// Set the defaultAssetGroup to specify which album is the default asset group. public var defaultAssetGroup: PHAssetCollectionSubtype? /// The types of PHAssetCollection to display in the picker. public var assetGroupTypes: [PHAssetCollectionSubtype] = [ .SmartAlbumUserLibrary, .SmartAlbumFavorites, .AlbumRegular ] { didSet { getImageManager().groupDataManager.assetGroupTypes = self.assetGroupTypes } } /// Set the showsEmptyAlbums to specify whether or not the empty albums is shown in the picker. public var showsEmptyAlbums = true { didSet { getImageManager().groupDataManager.showsEmptyAlbums = self.showsEmptyAlbums } } /// The type of picker interface to be displayed by the controller. public var assetType: DKImagePickerControllerAssetType = .AllAssets { didSet { getImageManager().groupDataManager.assetFetchOptions = self.createAssetFetchOptions() } } /// The predicate applies to images only. public var imageFetchPredicate: NSPredicate? { didSet { getImageManager().groupDataManager.assetFetchOptions = self.createAssetFetchOptions() } } /// The predicate applies to videos only. public var videoFetchPredicate: NSPredicate? { didSet { getImageManager().groupDataManager.assetFetchOptions = self.createAssetFetchOptions() } } /// If sourceType is Camera will cause the assetType & maxSelectableCount & allowMultipleTypes & defaultSelectedAssets to be ignored. public var sourceType: DKImagePickerControllerSourceType = .Both { didSet { /// If source type changed in the scenario of sharing instance, view controller should be reinitialized. if(oldValue != sourceType) { self.hasInitialized = false } } } /// Whether allows to select photos and videos at the same time. public var allowMultipleTypes = true /// If YES, and the requested image is not stored on the local device, the Picker downloads the image from iCloud. public var autoDownloadWhenAssetIsInCloud = true { didSet { getImageManager().autoDownloadWhenAssetIsInCloud = self.autoDownloadWhenAssetIsInCloud } } /// Determines whether or not the rotation is enabled. public var allowsLandscape = false /// The callback block is executed when user pressed the cancel button. public var didCancel: (() -> Void)? public var showsCancelButton = false { didSet { if let rootVC = self.viewControllers.first { self.updateCancelButtonForVC(rootVC) } } } /// The callback block is executed when user pressed the select button. public var didSelectAssets: ((assets: [DKAsset]) -> Void)? /// It will have selected the specific assets. public var defaultSelectedAssets: [DKAsset]? { didSet { if self.defaultSelectedAssets?.count > 0 { self.selectedAssets = self.defaultSelectedAssets ?? [] if let rootVC = self.viewControllers.first as? DKAssetGroupDetailVC { rootVC.collectionView.reloadData() } } } } public var selectedAssets = [DKAsset]() public convenience init() { let rootVC = UIViewController() self.init(rootViewController: rootVC) self.preferredContentSize = CGSize(width: 680, height: 600) rootVC.navigationItem.hidesBackButton = true getImageManager().groupDataManager.assetGroupTypes = self.assetGroupTypes getImageManager().groupDataManager.assetFetchOptions = self.createAssetFetchOptions() getImageManager().groupDataManager.showsEmptyAlbums = self.showsEmptyAlbums getImageManager().autoDownloadWhenAssetIsInCloud = self.autoDownloadWhenAssetIsInCloud } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) getImageManager().invalidate() } override public func viewDidLoad() { super.viewDidLoad() } private var hasInitialized = false override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if !hasInitialized { hasInitialized = true if self.sourceType == .Camera { self.navigationBarHidden = true let camera = self.createCamera() if camera is UINavigationController { self.presentViewController(self.createCamera(), animated: true, completion: nil) self.setViewControllers([], animated: false) } else { self.setViewControllers([camera], animated: false) } } else { self.navigationBarHidden = false let rootVC = DKAssetGroupDetailVC() rootVC.imagePickerController = self self.UIDelegate.prepareLayout(self, vc: rootVC) self.updateCancelButtonForVC(rootVC) self.setViewControllers([rootVC], animated: false) if self.defaultSelectedAssets?.count > 0 { self.UIDelegate.imagePickerController(self, didSelectAsset: self.defaultSelectedAssets!.last!) } } } } private lazy var assetFetchOptions: PHFetchOptions = { let assetFetchOptions = PHFetchOptions() assetFetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] return assetFetchOptions }() private func createAssetFetchOptions() -> PHFetchOptions? { let createImagePredicate = { () -> NSPredicate in var imagePredicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.Image.rawValue) if let imageFetchPredicate = self.imageFetchPredicate { imagePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [imagePredicate, imageFetchPredicate]) } return imagePredicate } let createVideoPredicate = { () -> NSPredicate in var videoPredicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.Video.rawValue) if let videoFetchPredicate = self.videoFetchPredicate { videoPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [videoPredicate, videoFetchPredicate]) } return videoPredicate } var predicate: NSPredicate? switch self.assetType { case .AllAssets: predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [createImagePredicate(), createVideoPredicate()]) case .AllPhotos: predicate = createImagePredicate() case .AllVideos: predicate = createVideoPredicate() } self.assetFetchOptions.predicate = predicate return self.assetFetchOptions } private func updateCancelButtonForVC(vc: UIViewController) { if self.showsCancelButton { self.UIDelegate.imagePickerController(self, showsCancelButtonForVC: vc) } else { self.UIDelegate.imagePickerController(self, hidesCancelButtonForVC: vc) } } private func createCamera() -> UIViewController { let didCancel = { () in if self.presentedViewController != nil { self.dismissViewControllerAnimated(true, completion: nil) } else { self.dismiss() } } let didFinishCapturingImage = { (image: UIImage) in var newImageIdentifier: String! PHPhotoLibrary.sharedPhotoLibrary().performChanges( { () in let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image) newImageIdentifier = assetRequest.placeholderForCreatedAsset!.localIdentifier }, completionHandler: { (success, error) in dispatch_async(dispatch_get_main_queue(), { if success { if let newAsset = PHAsset.fetchAssetsWithLocalIdentifiers([newImageIdentifier], options: nil).firstObject as? PHAsset { if self.sourceType != .Camera || self.viewControllers.count == 0 { self.dismissViewControllerAnimated(true, completion: nil) } self.selectedImage(DKAsset(originalAsset: newAsset)) } } else { if self.sourceType != .Camera { self.dismissViewControllerAnimated(true, completion: nil) } self.selectedImage(DKAsset(image: image)) } }) }) } let didFinishCapturingVideo = { (videoURL: NSURL) in var newVideoIdentifier: String! PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoURL) newVideoIdentifier = assetRequest?.placeholderForCreatedAsset?.localIdentifier }, completionHandler: { (success, error) in dispatch_async(dispatch_get_main_queue(), { if success { if let newAsset = PHAsset.fetchAssetsWithLocalIdentifiers([newVideoIdentifier], options: nil).firstObject as? PHAsset { if self.sourceType != .Camera || self.viewControllers.count == 0 { self.dismissViewControllerAnimated(true, completion: nil) } self.selectedImage(DKAsset(originalAsset: newAsset)) } } else { self.dismissViewControllerAnimated(true, completion: nil) } }) }) } let camera = self.UIDelegate.imagePickerControllerCreateCamera(self, didCancel: didCancel, didFinishCapturingImage: didFinishCapturingImage, didFinishCapturingVideo: didFinishCapturingVideo) return camera } internal func presentCamera() { self.presentViewController(self.createCamera(), animated: true, completion: nil) } public func dismiss() { self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) self.didCancel?() } public func done() { //self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) self.didSelectAssets?(assets: self.selectedAssets) self.selectedAssets = [DKAsset]() } // MARK: - Selection Image internal func selectedImage(asset: DKAsset) { selectedAssets.append(asset) if self.sourceType == .Camera { self.done() } else if self.singleSelect { self.done() } else { self.UIDelegate.imagePickerController(self, didSelectAsset: asset) } } internal func unselectedImage(asset: DKAsset) { selectedAssets.removeAtIndex(selectedAssets.indexOf(asset)!) self.UIDelegate.imagePickerController(self, didDeselectAsset: asset) } // MARK: - Handles Orientation public override func shouldAutorotate() -> Bool { return self.allowsLandscape && self.sourceType != .Camera ? true : false } public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if self.allowsLandscape { return super.supportedInterfaceOrientations() } else { return UIInterfaceOrientationMask.Portrait } } }
mit
df550b3408cc254dd2b5721050754cb8
32.114833
137
0.722222
4.887712
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/TextField/Formatters/CardExpirationDateFormatter.swift
1
3404
// Copyright © Blockchain Luxembourg S.A. All rights reserved. final class CardExpirationDateFormatter: TextFormatting { func format(_ string: String, operation: TextInputOperation) -> TextFormattingSource { var text = "" let (monthString, yearString) = prepareComponents(string) processMonth(from: string, operation: operation, month: monthString, year: yearString, output: &text) processYear(from: string, year: yearString, output: &text) return text == string ? .original(text: text) : .formatted(to: text) } private func processYear( from string: String, year: String, output: inout String ) { guard let yearInteger = Int(year) else { return } switch yearInteger { case 0, 1: output += "2" case 2...9: output += "\(year)" case 20...99: output += String(format: "%02d", yearInteger) default: break } } private func processMonth( from string: String, operation: TextInputOperation, month: String, year: String, output: inout String ) { guard let monthInteger = Int(month) else { return } if string.count == 2, operation == .deletion { output = String(string.prefix(1)) } else { switch monthInteger { case 0 where year.isEmpty: output += "0" case 1 where month.count == 1: if operation == .addition { output += "\(monthInteger)" } case 1...9: if month.count == 1 { output += String(format: "%02d/", monthInteger) } else if !year.isEmpty { // The year is filled output += String(format: "%02d/", monthInteger) } else { // Year has not been filled yet if month.count >= 2, month.first == "0" { output += String(format: "%02d/", monthInteger) } else { output += "\(monthInteger)" } } case 10...12: output += String(format: "%02d/", monthInteger) default: break } } } private func prepareComponents(_ string: String) -> (monthString: String, yearString: String) { let components = string.split(separator: "/") let rawComponents: [String] if components.isEmpty { if string.contains("/") { rawComponents = ["", ""] } else { let month = String(string.prefix(2)) let year = String(string.dropFirst(2).prefix(2)) rawComponents = [month, year] } } else if components.count == 1 { rawComponents = [String(components[0]), ""] } else { var yearComponent = String(components[1]) if yearComponent.count > 2 { yearComponent = String(yearComponent.prefix(1)) + String(yearComponent.suffix(1)) } rawComponents = [String(components[0]), yearComponent] } let monthString = String(rawComponents[0]) let yearString = String(rawComponents[1]) return (monthString, yearString) } }
lgpl-3.0
753b8647b9d89cdead27c3064a7682db
34.082474
109
0.51484
4.739554
false
false
false
false
modocache/swift
test/expr/closure/default_args.swift
4
935
// RUN: %target-parse-verify-swift func simple_default_args() { // <rdar://problem/22753605> QoI: bad diagnostic when closure has default argument let _ : (Int) -> Int = {(x : Int = 1) in x+1} // expected-error{{default arguments are not allowed in closures}} {{36-39=}} let _ : () -> Int = {(_ x : Int = 1) in x+1} // expected-error{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}} expected-error {{default arguments are not allowed in closures}} {{35-38=}} let _ : () -> Int = {(_ x : Int) in x+1} // expected-error{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}} } func func_default_args() { func has_default_args(x: Int = 1) -> Int { return x+1 } var _ : (Int) -> Int = has_default_args // okay var _ : () -> Int = has_default_args // expected-error{{cannot convert value of type '(Int) -> Int' to specified type '() -> Int'}} }
apache-2.0
3227d9e3407a4de0de0230ac3fc2d5e2
61.333333
231
0.626738
3.387681
false
false
false
false
trilliwon/JNaturalKorean
Sources/JNaturalKorean/JNaturalKorean.swift
2
8691
// // Created by trilliwon on 2016. 3. 2.. // Copyright © 2016년 trilliwon. All rights reserved. // import Foundation // MARK: - JNaturalKorean Public API open class JNaturalKorean { // 한글 unicode fileprivate static let baseCode = 44032 fileprivate static let choSung = 588 // 초성 fileprivate static let jungSung = 28 // 중성 // 초성 list fileprivate static let choSungList = ["ㄱ", "ㄲ", "ㄴ", "ㄷ", "ㄸ", "ㄹ", "ㅁ", "ㅂ", "ㅃ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅉ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ"] // 중성 list fileprivate static let jungSungList = ["ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ", "ㅕ", "ㅖ", "ㅗ", "ㅘ", "ㅙ", "ㅚ", "ㅛ", "ㅜ", "ㅝ", "ㅞ", "ㅟ", "ㅠ", "ㅡ", "ㅢ", "ㅣ"] // 종성 list fileprivate static let jongSungList = [" ", "ㄱ", "ㄲ", "ㄳ", "ㄴ", "ㄵ", "ㄶ", "ㄷ", "ㄹ", "ㄺ", "ㄻ", "ㄼ", "ㄽ", "ㄾ", "ㄿ", "ㅀ", "ㅁ", "ㅂ", "ㅄ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ"] // english list fileprivate static let engCheckList = ["A", "a", "E", "e", "F", "f", "G", "g", "H", "h", "I", "i", "J", "j", "O", "o", "R", "r", "S", "s", "U", "u", "V", "v", "X", "x", "Y", "y", "Z", "z"] // MARK: - 이/가 // ex) - 그 사람**이** 소크라테스 입니다. // ex) - 그 프로그래머**가** 실력자 입니다. open class func get_이_가(word: String) -> String { if word.isHangul { return (word.isThere종성 ? "이" : "가") } else if word.isEnglish { return (word.isKindOf받침 ? "이" : "가") } else if word.isEndWithNumber { return (word.isKineOf받침Number ? "이" : "가") }else { return "" } } open class func get_이_가_with(word: String) -> String { return "\(word)\(get_이_가(word: word))" } // MARK: - 은/는 // ex) - 그 사람**은** 소크라테스 입니다. // ex) - 그 프로그래머**는** 실력자 입니다. open class func get_은_는(word: String) -> String { if word.isHangul { return (word.isThere종성 ? "은" : "는") } else if word.isEnglish { return (word.isKindOf받침 ? "은" : "는") } else if word.isEndWithNumber { return (word.isKineOf받침Number ? "은" : "는") }else { return "" } } open class func get_은_는_with(word: String) -> String { return "\(word)\(get_은_는(word: word))" } // MARK: - 을/를 // ex) - 그 사람**을** 채용합시다. // ex) - 그 프로그래머**를** 채용합시다. open class func get_을_를(word: String) -> String { if word.isHangul { return (word.isThere종성 ? "을" : "를") } else if word.isEnglish { return (word.isKindOf받침 ? "을" : "를") } else if word.isEndWithNumber { return (word.isKineOf받침Number ? "을" : "를") }else { return "" } } open class func get_을_를_with(word: String) -> String { return "\(word)\(get_을_를(word: word))" } // MARK: - 으로/로 // ex) - 그 사람**으로** 보여지다. // ex) - 그 프로그래머**로** 보여지다. open class func get_으로_로(word: String) -> String { if word.isHangul { return (word.isㄹ종성 ? "로" : (word.isThere종성 ? "으로" : "로")) } else if word.isEnglish { return (word.isL ? "로" : (word.isKindOf받침 ? "으로" : "로")) } else if word.isEndWithNumber { return (word.isOne ? "로" : (word.isKineOf받침Number ? "으로" : "로")) }else { return "" } } open class func get_으로_로_with(word: String) -> String { return "\(word)\(get_으로_로(word: word))" } // MARK: - 아/야 // ex) - 이 인간**아**!. // ex) - 이 여자**야**!. open class func get_아_야(word: String) -> String { if word.isHangul { return (word.isThere종성 ? "아" : "야") } else if word.isEnglish { return (word.isKindOf받침 ? "아" : "야") } else if word.isEndWithNumber { return (word.isKineOf받침Number ? "아" : "야") }else { return "" } } open class func get_아_야_with(word: String) -> String { return "\(word)\(get_아_야(word: word))" } // MARK: - 와/과 // ex) - 그 여자**와** 단둘이. // ex) - 이 사람**과** 둘이서. open class func get_와_과(word: String) -> String { if word.isHangul { return (word.isThere종성 ? "과" : "와") } else if word.isEnglish { return (word.isKindOf받침 ? "과" : "와") } else if word.isEndWithNumber { return (word.isKineOf받침Number ? "과" : "와") }else { return "" } } open class func get_와_과_with(word: String) -> String { return "\(word)\(get_와_과(word: word))" } } // MARK: - String+JNaturalKorean Private Utils for 한글 extension String { fileprivate var isHangul: Bool { guard let lastUnicode = self.unicodeScalars.last else { return false } let last = Int(lastUnicode.value) return 44032 <= last && last <= 55199 } fileprivate var isThere종성: Bool { let cBase = Int((String(self.last!).unicodeScalars.first?.value)!) - JNaturalKorean.baseCode let cs = (cBase / JNaturalKorean.choSung) let jus = (cBase - (JNaturalKorean.choSung * cs)) / JNaturalKorean.jungSung let jos = (cBase - (JNaturalKorean.choSung * cs) - (JNaturalKorean.jungSung * jus)) return (JNaturalKorean.jongSungList[jos] != " ") } fileprivate var isㄹ종성: Bool { let cBase = Int((String(self.last!).unicodeScalars.first?.value)!) - JNaturalKorean.baseCode let cs = cBase / JNaturalKorean.choSung let jus = (cBase - (JNaturalKorean.choSung * cs)) / JNaturalKorean.jungSung let jos = (cBase - (JNaturalKorean.choSung * cs) - (JNaturalKorean.jungSung * jus)) return (JNaturalKorean.jongSungList[jos] == "ㄹ") } } // MARK: - String+JNaturalKorean Private Util for English private enum 영어받침: String { case NG = "NG" case LE = "LE" case ME = "ME" case ND = "ND" case ED = "ED" case LT = "LT" case ST = "ST" case RD = "RD" case LD = "LD" case PE = "PE" } extension String { fileprivate var isEnglish: Bool { guard let lastUnicode = self.unicodeScalars.last else { return false } let last = Int(lastUnicode.value) return (65 <= last && last <= 90) || (97 <= last && last <= 122) } fileprivate var lastTwoCharString: String { return self.suffix(2).map { char in return String(char) }.reduce("", +) } fileprivate var isKindOf받침: Bool { guard let 영어받침 = 영어받침(rawValue: self.lastTwoCharString.uppercased()) else { return !JNaturalKorean.engCheckList.contains(String(self.last!)) } switch 영어받침 { case .NG, .LE, .ME, .PE: return true case .ND, .ED, .LT, .ST, .LD, .RD: return false } } fileprivate var isL: Bool { let value = Int((String(self.last!).unicodeScalars.first?.value)!) return (value == 76 || value == 108) } } // MARK: - String+JNaturalKorean Private Util for Number enum Number: String { case zero = "0" case one = "1" case two = "2" case three = "3" case four = "4" case five = "5" case six = "6" case seven = "7" case eight = "8" case nine = "9" } extension String { fileprivate var isEndWithNumber: Bool { guard let lastUnicode = self.unicodeScalars.last else { return false } let last = Int(lastUnicode.value) return (48 <= last && last <= 57) } fileprivate var isKineOf받침Number: Bool { guard let lastCharacter = self.last, let number = Number(rawValue: String(lastCharacter)) else { return false } switch number { case .zero, .one, .three, .six, .seven, .eight: return true case .two, .four, .five, .nine: return false } } fileprivate var isOne: Bool { guard let lastCharacter = self.last else{ return false } return ("1" == String(lastCharacter)) } }
mit
edad6a28ebf378727960f466cc2f5dc7
28.025455
192
0.515535
2.866068
false
false
false
false
jifusheng/MyDouYuTV
DouYuTV/DouYuTV/Classes/Main/View/PageTitleView.swift
1
6411
// // PageTitleView.swift // DouYuTV // // Created by 王建伟 on 2016/11/17. // Copyright © 2016年 jifusheng. All rights reserved. // import UIKit // MARK: - 设置代理 protocol PageTitleViewDelegate : class { func pageTitleView(titleView : PageTitleView ,selectedIndex index : Int) } // MARK: - 定义一些颜色常量 private var kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private var kSelectedColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) class PageTitleView: UIView { // MARK: - 定义属性 fileprivate var titles : [String] fileprivate var currentIndex : Int = 0 weak var delegate : PageTitleViewDelegate? // MARK: - 懒加载一个数组存放所以的Label fileprivate lazy var titleLabels : [UILabel] = [UILabel]() // MARK: - scrollView懒加载 fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() // MARK: - scrollLine懒加载 fileprivate lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2) return scrollLine }() // MARK: - 自定义构造函数 init(frame: CGRect, titles : [String]) { self.titles = titles super.init(frame: frame) //创建UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { fileprivate func setupUI() { //1、添加scrollView addSubview(scrollView) scrollView.frame = bounds //2、添加title对应的Label setupTitleLabels() //3、设置底线和滚动滑块 setupBottomLineAndScrollLine() } // MARK: - 创建标题的Label private func setupTitleLabels() { //0、初始化一些值 let labelW : CGFloat = frame.width / CGFloat(titles.count) let labelH : CGFloat = frame.height - kScrollLineH let labelY : CGFloat = 0 for (index ,title) in titles.enumerated() { //1、创建Label let label = UILabel() //2、设置label属性 label.text = title label.tag = index label.font = .systemFont(ofSize: 16) label.textColor = index == 0 ? UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2) : UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center //3、设置label的frame let labelX : CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) //4、把Label添加到scrollView scrollView.addSubview(label) //5、把Label添加到数组中 titleLabels.append(label) //6、给Label添加手势 label.isUserInteractionEnabled = true let gesture = UITapGestureRecognizer(target: self, action: #selector(self.labelTapGesture(_:))) label.addGestureRecognizer(gesture) } } // MARK: - 创建底部分割线和小滑快 private func setupBottomLineAndScrollLine() { //1、创建分割线 let bottomLine = UILabel() let bottomLineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - bottomLineH, width: frame.width, height: bottomLineH) bottomLine.backgroundColor = UIColor(red: 234/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1.0) addSubview(bottomLine) //2、创建滑块 //2.1、取出第一个Label guard let firstLabel = titleLabels.first else { return } scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH) } } // MARK: - 事件处理 extension PageTitleView { @objc fileprivate func labelTapGesture(_ tap : UITapGestureRecognizer) { //1、获取点击之前的Label let lastLabel = titleLabels[currentIndex] //2、获取当前点击的Label guard let currentLabel = tap.view as? UILabel else { return } //3、修改Label的文字颜色 lastLabel.textColor = .darkGray currentLabel.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2) //4、把当前的下标保存 currentIndex = currentLabel.tag //5、设置滑块的位置,执行动画 UIView.animate(withDuration: 0.15) { self.scrollLine.center.x = currentLabel.center.x } //6、通知代理做事情 delegate?.pageTitleView(titleView: self, selectedIndex: currentLabel.tag) } } // MARK: - 外部可以调用的方法 extension PageTitleView { func setTitleWithProgress(progress: CGFloat ,currentIndex: Int, targetIndex: Int) { //1、取出当前的或目标Label let currentLbl = titleLabels[currentIndex] let targetLbl = titleLabels[targetIndex] //2、记录当前的下标 self.currentIndex = targetIndex //3、如果当前的index和目标index相同就返回 if currentIndex == targetIndex { return } //4、处理滑块的逻辑 let moveTotalX = targetLbl.frame.origin.x - currentLbl.frame.origin.x let movingX = moveTotalX * progress scrollLine.frame.origin.x = currentLbl.frame.origin.x + movingX //5、设置渐变颜色 //5.1、颜色渐变范围 let colorChanged = (kSelectedColor.0 - kNormalColor.0, kSelectedColor.1 - kNormalColor.1, kSelectedColor.2 - kNormalColor.2) //5.2、设置变化的当前的Label currentLbl.textColor = UIColor(r: kSelectedColor.0 - colorChanged.0 * progress, g: kSelectedColor.1 - colorChanged.1 * progress, b: kSelectedColor.2 - colorChanged.2 * progress) //5.3、设置变化的目标的Label targetLbl.textColor = UIColor(r: kNormalColor.0 + colorChanged.0 * progress, g: kNormalColor.1 + colorChanged.1 * progress, b: kNormalColor.2 + colorChanged.2 * progress) } }
mit
dbe93ec62efd5743d6a5d3601c1b18d1
35.6375
185
0.636643
4.226388
false
false
false
false
maxoly/PulsarKit
PulsarKit/PulsarKit/Sources/Contexts/ActionContext.swift
1
822
// // ActionContext.swift // PulsarKit // // Created by Massimo Oliviero on 06/10/2018. // Copyright © 2019 Nacoon. All rights reserved. // import Foundation public final class ActionContext<Model: Hashable> { public let model: Model public let container: UICollectionView public let indexPath: IndexPath public let action: Selector? public let sender: Any? init(model: Model, container: UICollectionView, indexPath: IndexPath, action: Selector?, sender: Any?) { self.model = model self.container = container self.indexPath = indexPath self.action = action self.sender = sender } } extension ActionContext { var standard: StandardContext<Model> { StandardContext(model: model, container: container, indexPath: indexPath) } }
mit
5d3f7020f3fbeebee5b3bceaf402e6cb
25.483871
108
0.682095
4.298429
false
false
false
false
ikesyo/KeychainAccess
Lib/KeychainAccess/Keychain.swift
1
114159
// // Keychain.swift // KeychainAccess // // Created by kishikawa katsumi on 2014/12/24. // Copyright (c) 2014 kishikawa katsumi. All rights reserved. // import Foundation import Security public let KeychainAccessErrorDomain = "com.kishikawakatsumi.KeychainAccess.error" public enum ItemClass { case GenericPassword case InternetPassword } public enum ProtocolType { case FTP case FTPAccount case HTTP case IRC case NNTP case POP3 case SMTP case SOCKS case IMAP case LDAP case AppleTalk case AFP case Telnet case SSH case FTPS case HTTPS case HTTPProxy case HTTPSProxy case FTPProxy case SMB case RTSP case RTSPProxy case DAAP case EPPC case IPP case NNTPS case LDAPS case TelnetS case IMAPS case IRCS case POP3S } public enum AuthenticationType { case NTLM case MSN case DPA case RPA case HTTPBasic case HTTPDigest case HTMLForm case Default } public enum Accessibility { /** Item data can only be accessed while the device is unlocked. This is recommended for items that only need be accesible while the application is in the foreground. Items with this attribute will migrate to a new device when using encrypted backups. */ case WhenUnlocked /** Item data can only be accessed once the device has been unlocked after a restart. This is recommended for items that need to be accesible by background applications. Items with this attribute will migrate to a new device when using encrypted backups. */ case AfterFirstUnlock /** Item data can always be accessed regardless of the lock state of the device. This is not recommended for anything except system use. Items with this attribute will migrate to a new device when using encrypted backups. */ case Always /** Item data can only be accessed while the device is unlocked. This class is only available if a passcode is set on the device. This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode will cause all items in this class to be deleted. */ @available(iOS 8.0, OSX 10.10, *) case WhenPasscodeSetThisDeviceOnly /** Item data can only be accessed while the device is unlocked. This is recommended for items that only need be accesible while the application is in the foreground. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. */ case WhenUnlockedThisDeviceOnly /** Item data can only be accessed once the device has been unlocked after a restart. This is recommended for items that need to be accessible by background applications. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device these items will be missing. */ case AfterFirstUnlockThisDeviceOnly /** Item data can always be accessed regardless of the lock state of the device. This option is not recommended for anything except system use. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. */ case AlwaysThisDeviceOnly } public struct AuthenticationPolicy : OptionSetType { /** User presence policy using Touch ID or Passcode. Touch ID does not have to be available or enrolled. Item is still accessible by Touch ID even if fingers are added or removed. */ @available(iOS 8.0, OSX 10.10, *) @available(watchOS, unavailable) public static let UserPresence = AuthenticationPolicy(rawValue: 1 << 0) /** Constraint: Touch ID (any finger). Touch ID must be available and at least one finger must be enrolled. Item is still accessible by Touch ID even if fingers are added or removed. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let TouchIDAny = AuthenticationPolicy(rawValue: 1 << 1) /** Constraint: Touch ID from the set of currently enrolled fingers. Touch ID must be available and at least one finger must be enrolled. When fingers are added or removed, the item is invalidated. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let TouchIDCurrentSet = AuthenticationPolicy(rawValue: 1 << 3) /** Constraint: Device passcode */ @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) public static let DevicePasscode = AuthenticationPolicy(rawValue: 1 << 4) /** Constraint logic operation: when using more than one constraint, at least one of them must be satisfied. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let Or = AuthenticationPolicy(rawValue: 1 << 14) /** Constraint logic operation: when using more than one constraint, all must be satisfied. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let And = AuthenticationPolicy(rawValue: 1 << 15) /** Create access control for private key operations (i.e. sign operation) */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let PrivateKeyUsage = AuthenticationPolicy(rawValue: 1 << 30) /** Security: Application provided password for data encryption key generation. This is not a constraint but additional item encryption mechanism. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let ApplicationPassword = AuthenticationPolicy(rawValue: 1 << 31) public let rawValue : Int public init(rawValue:Int) { self.rawValue = rawValue } } public struct Attributes { public var `class`: String? { return attributes[Class] as? String } public var data: NSData? { return attributes[ValueData] as? NSData } public var ref: NSData? { return attributes[ValueRef] as? NSData } public var persistentRef: NSData? { return attributes[ValuePersistentRef] as? NSData } public var accessible: String? { return attributes[AttributeAccessible] as? String } public var accessControl: SecAccessControl? { if #available(OSX 10.10, *) { if let accessControl = attributes[AttributeAccessControl] { return (accessControl as! SecAccessControl) } return nil } else { return nil } } public var accessGroup: String? { return attributes[AttributeAccessGroup] as? String } public var synchronizable: Bool? { return attributes[AttributeSynchronizable] as? Bool } public var creationDate: NSDate? { return attributes[AttributeCreationDate] as? NSDate } public var modificationDate: NSDate? { return attributes[AttributeModificationDate] as? NSDate } public var attributeDescription: String? { return attributes[AttributeDescription] as? String } public var comment: String? { return attributes[AttributeComment] as? String } public var creator: String? { return attributes[AttributeCreator] as? String } public var type: String? { return attributes[AttributeType] as? String } public var label: String? { return attributes[AttributeLabel] as? String } public var isInvisible: Bool? { return attributes[AttributeIsInvisible] as? Bool } public var isNegative: Bool? { return attributes[AttributeIsNegative] as? Bool } public var account: String? { return attributes[AttributeAccount] as? String } public var service: String? { return attributes[AttributeService] as? String } public var generic: NSData? { return attributes[AttributeGeneric] as? NSData } public var securityDomain: String? { return attributes[AttributeSecurityDomain] as? String } public var server: String? { return attributes[AttributeServer] as? String } public var `protocol`: String? { return attributes[AttributeProtocol] as? String } public var authenticationType: String? { return attributes[AttributeAuthenticationType] as? String } public var port: Int? { return attributes[AttributePort] as? Int } public var path: String? { return attributes[AttributePath] as? String } private let attributes: [String: AnyObject] init(attributes: [String: AnyObject]) { self.attributes = attributes } public subscript(key: String) -> AnyObject? { get { return attributes[key] } } } public class Keychain { public var itemClass: ItemClass { return options.itemClass } public var service: String { return options.service } public var accessGroup: String? { return options.accessGroup } public var server: NSURL { return options.server } public var protocolType: ProtocolType { return options.protocolType } public var authenticationType: AuthenticationType { return options.authenticationType } public var accessibility: Accessibility { return options.accessibility } @available(iOS 8.0, OSX 10.10, *) @available(watchOS, unavailable) public var authenticationPolicy: AuthenticationPolicy? { return options.authenticationPolicy } public var synchronizable: Bool { return options.synchronizable } public var label: String? { return options.label } public var comment: String? { return options.comment } @available(iOS 8.0, OSX 10.10, *) @available(watchOS, unavailable) public var authenticationPrompt: String? { return options.authenticationPrompt } private let options: Options // MARK: public convenience init() { var options = Options() if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier { options.service = bundleIdentifier } self.init(options) } public convenience init(service: String) { var options = Options() options.service = service self.init(options) } public convenience init(accessGroup: String) { var options = Options() if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier { options.service = bundleIdentifier } options.accessGroup = accessGroup self.init(options) } public convenience init(service: String, accessGroup: String) { var options = Options() options.service = service options.accessGroup = accessGroup self.init(options) } public convenience init(server: String, protocolType: ProtocolType, authenticationType: AuthenticationType = .Default) { self.init(server: NSURL(string: server)!, protocolType: protocolType, authenticationType: authenticationType) } public convenience init(server: NSURL, protocolType: ProtocolType, authenticationType: AuthenticationType = .Default) { var options = Options() options.itemClass = .InternetPassword options.server = server options.protocolType = protocolType options.authenticationType = authenticationType self.init(options) } private init(_ opts: Options) { options = opts } // MARK: public func accessibility(accessibility: Accessibility) -> Keychain { var options = self.options options.accessibility = accessibility return Keychain(options) } @available(iOS 8.0, OSX 10.10, *) @available(watchOS, unavailable) public func accessibility(accessibility: Accessibility, authenticationPolicy: AuthenticationPolicy) -> Keychain { var options = self.options options.accessibility = accessibility options.authenticationPolicy = authenticationPolicy return Keychain(options) } public func synchronizable(synchronizable: Bool) -> Keychain { var options = self.options options.synchronizable = synchronizable return Keychain(options) } public func label(label: String) -> Keychain { var options = self.options options.label = label return Keychain(options) } public func comment(comment: String) -> Keychain { var options = self.options options.comment = comment return Keychain(options) } public func attributes(attributes: [String: AnyObject]) -> Keychain { var options = self.options attributes.forEach { options.attributes.updateValue($1, forKey: $0) } return Keychain(options) } @available(iOS 8.0, OSX 10.10, *) @available(watchOS, unavailable) public func authenticationPrompt(authenticationPrompt: String) -> Keychain { var options = self.options options.authenticationPrompt = authenticationPrompt return Keychain(options) } // MARK: public func get(key: String) throws -> String? { return try getString(key) } public func getString(key: String) throws -> String? { guard let data = try getData(key) else { return nil } guard let string = NSString(data: data, encoding: NSUTF8StringEncoding) as? String else { throw conversionError(message: "failed to convert data to string") } return string } public func getData(key: String) throws -> NSData? { var query = options.query() query[MatchLimit] = MatchLimitOne query[ReturnData] = true query[AttributeAccount] = key var result: AnyObject? let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: guard let data = result as? NSData else { throw Status.UnexpectedError } return data case errSecItemNotFound: return nil default: throw securityError(status: status) } } public func get<T>(key: String, @noescape handler: Attributes? -> T) throws -> T { var query = options.query() query[MatchLimit] = MatchLimitOne query[ReturnData] = true query[ReturnAttributes] = true query[ReturnRef] = true query[ReturnPersistentRef] = true query[AttributeAccount] = key var result: AnyObject? let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: guard let attributes = result as? [String: AnyObject] else { throw Status.UnexpectedError } return handler(Attributes(attributes: attributes)) case errSecItemNotFound: return handler(nil) default: throw securityError(status: status) } } // MARK: public func set(value: String, key: String) throws { guard let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) else { throw conversionError(message: "failed to convert string to data") } try set(data, key: key) } public func set(value: NSData, key: String) throws { var query = options.query() query[AttributeAccount] = key #if os(iOS) if #available(iOS 9.0, *) { query[UseAuthenticationUI] = UseAuthenticationUIFail } else { query[UseNoAuthenticationUI] = true } #elseif os(OSX) if #available(OSX 10.11, *) { query[UseAuthenticationUI] = UseAuthenticationUIFail } #endif var status = SecItemCopyMatching(query, nil) switch status { case errSecSuccess, errSecInteractionNotAllowed: var query = options.query() query[AttributeAccount] = key var (attributes, error) = options.attributes(key: nil, value: value) if let error = error { print(error.localizedDescription) throw error } options.attributes.forEach { attributes.updateValue($1, forKey: $0) } #if os(iOS) if status == errSecInteractionNotAllowed && floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_8_0) { try remove(key) try set(value, key: key) } else { status = SecItemUpdate(query, attributes) if status != errSecSuccess { throw securityError(status: status) } } #else status = SecItemUpdate(query, attributes) if status != errSecSuccess { throw securityError(status: status) } #endif case errSecItemNotFound: var (attributes, error) = options.attributes(key: key, value: value) if let error = error { print(error.localizedDescription) throw error } options.attributes.forEach { attributes.updateValue($1, forKey: $0) } status = SecItemAdd(attributes, nil) if status != errSecSuccess { throw securityError(status: status) } default: throw securityError(status: status) } } public subscript(key: String) -> String? { get { return (try? get(key)).flatMap { $0 } } set { if let value = newValue { do { try set(value, key: key) } catch {} } else { do { try remove(key) } catch {} } } } public subscript(string key: String) -> String? { get { return self[key] } set { self[key] = newValue } } public subscript(data key: String) -> NSData? { get { return (try? getData(key)).flatMap { $0 } } set { if let value = newValue { do { try set(value, key: key) } catch {} } else { do { try remove(key) } catch {} } } } public subscript(attributes key: String) -> Attributes? { get { return (try? get(key) { $0 }).flatMap { $0 } } } // MARK: public func remove(key: String) throws { var query = options.query() query[AttributeAccount] = key let status = SecItemDelete(query) if status != errSecSuccess && status != errSecItemNotFound { throw securityError(status: status) } } public func removeAll() throws { var query = options.query() #if !os(iOS) && !os(watchOS) && !os(tvOS) query[MatchLimit] = MatchLimitAll #endif let status = SecItemDelete(query) if status != errSecSuccess && status != errSecItemNotFound { throw securityError(status: status) } } // MARK: public func contains(key: String) throws -> Bool { var query = options.query() query[AttributeAccount] = key let status = SecItemCopyMatching(query, nil) switch status { case errSecSuccess: return true case errSecItemNotFound: return false default: throw securityError(status: status) } } // MARK: public class func allKeys(itemClass: ItemClass) -> [(String, String)] { var query = [String: AnyObject]() query[Class] = itemClass.rawValue query[AttributeSynchronizable] = SynchronizableAny query[MatchLimit] = MatchLimitAll query[ReturnAttributes] = true var result: AnyObject? let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let items = result as? [[String: AnyObject]] { return prettify(itemClass: itemClass, items: items).map { switch itemClass { case .GenericPassword: return (($0["service"] ?? "") as! String, ($0["key"] ?? "") as! String) case .InternetPassword: return (($0["server"] ?? "") as! String, ($0["key"] ?? "") as! String) } } } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } public func allKeys() -> [String] { return self.dynamicType.prettify(itemClass: itemClass, items: items()).map { $0["key"] as! String } } public class func allItems(itemClass: ItemClass) -> [[String: AnyObject]] { var query = [String: AnyObject]() query[Class] = itemClass.rawValue query[MatchLimit] = MatchLimitAll query[ReturnAttributes] = true #if os(iOS) || os(watchOS) || os(tvOS) query[ReturnData] = true #endif var result: AnyObject? let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let items = result as? [[String: AnyObject]] { return prettify(itemClass: itemClass, items: items) } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } public func allItems() -> [[String: AnyObject]] { return self.dynamicType.prettify(itemClass: itemClass, items: items()) } #if os(iOS) @available(iOS 8.0, *) public func getSharedPassword(completion: (account: String?, password: String?, error: NSError?) -> () = { account, password, error -> () in }) { if let domain = server.host { self.dynamicType.requestSharedWebCredential(domain: domain, account: nil) { (credentials, error) -> () in if let credential = credentials.first { let account = credential["account"] let password = credential["password"] completion(account: account, password: password, error: error) } else { completion(account: nil, password: nil, error: error) } } } else { let error = securityError(status: Status.Param.rawValue) completion(account: nil, password: nil, error: error) } } #endif #if os(iOS) @available(iOS 8.0, *) public func getSharedPassword(account: String, completion: (password: String?, error: NSError?) -> () = { password, error -> () in }) { if let domain = server.host { self.dynamicType.requestSharedWebCredential(domain: domain, account: account) { (credentials, error) -> () in if let credential = credentials.first { if let password = credential["password"] { completion(password: password, error: error) } else { completion(password: nil, error: error) } } else { completion(password: nil, error: error) } } } else { let error = securityError(status: Status.Param.rawValue) completion(password: nil, error: error) } } #endif #if os(iOS) @available(iOS 8.0, *) public func setSharedPassword(password: String, account: String, completion: (error: NSError?) -> () = { e -> () in }) { setSharedPassword(password as String?, account: account, completion: completion) } #endif #if os(iOS) @available(iOS 8.0, *) private func setSharedPassword(password: String?, account: String, completion: (error: NSError?) -> () = { e -> () in }) { if let domain = server.host { SecAddSharedWebCredential(domain, account, password) { error -> () in if let error = error { completion(error: error.error) } else { completion(error: nil) } } } else { let error = securityError(status: Status.Param.rawValue) completion(error: error) } } #endif #if os(iOS) @available(iOS 8.0, *) public func removeSharedPassword(account: String, completion: (error: NSError?) -> () = { e -> () in }) { setSharedPassword(nil, account: account, completion: completion) } #endif #if os(iOS) @available(iOS 8.0, *) public class func requestSharedWebCredential(completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: nil, account: nil, completion: completion) } #endif #if os(iOS) @available(iOS 8.0, *) public class func requestSharedWebCredential(domain domain: String, completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: domain, account: nil, completion: completion) } #endif #if os(iOS) @available(iOS 8.0, *) public class func requestSharedWebCredential(domain domain: String, account: String, completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: Optional(domain), account: Optional(account), completion: completion) } #endif #if os(iOS) @available(iOS 8.0, *) private class func requestSharedWebCredential(domain domain: String?, account: String?, completion: (credentials: [[String: String]], error: NSError?) -> ()) { SecRequestSharedWebCredential(domain, account) { (credentials, error) -> () in var remoteError: NSError? if let error = error { remoteError = error.error if remoteError?.code != Int(errSecItemNotFound) { print("error:[\(remoteError!.code)] \(remoteError!.localizedDescription)") } } if let credentials = credentials as? [[String: AnyObject]] { let credentials = credentials.map { credentials -> [String: String] in var credential = [String: String]() if let server = credentials[AttributeServer] as? String { credential["server"] = server } if let account = credentials[AttributeAccount] as? String { credential["account"] = account } if let password = credentials[SharedPassword] as? String { credential["password"] = password } return credential } completion(credentials: credentials, error: remoteError) } else { completion(credentials: [], error: remoteError) } } } #endif #if os(iOS) /** @abstract Returns a randomly generated password. @return String password in the form xxx-xxx-xxx-xxx where x is taken from the sets "abcdefghkmnopqrstuvwxy", "ABCDEFGHJKLMNPQRSTUVWXYZ", "3456789" with at least one character from each set being present. */ @available(iOS 8.0, *) public class func generatePassword() -> String { return SecCreateSharedWebCredentialPassword()! as String } #endif // MARK: private func items() -> [[String: AnyObject]] { var query = options.query() query[MatchLimit] = MatchLimitAll query[ReturnAttributes] = true #if os(iOS) || os(watchOS) || os(tvOS) query[ReturnData] = true #endif var result: AnyObject? let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let items = result as? [[String: AnyObject]] { return items } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } private class func prettify(itemClass itemClass: ItemClass, items: [[String: AnyObject]]) -> [[String: AnyObject]] { let items = items.map { attributes -> [String: AnyObject] in var item = [String: AnyObject]() item["class"] = itemClass.description switch itemClass { case .GenericPassword: if let service = attributes[AttributeService] as? String { item["service"] = service } if let accessGroup = attributes[AttributeAccessGroup] as? String { item["accessGroup"] = accessGroup } case .InternetPassword: if let server = attributes[AttributeServer] as? String { item["server"] = server } if let proto = attributes[AttributeProtocol] as? String { if let protocolType = ProtocolType(rawValue: proto) { item["protocol"] = protocolType.description } } if let auth = attributes[AttributeAuthenticationType] as? String { if let authenticationType = AuthenticationType(rawValue: auth) { item["authenticationType"] = authenticationType.description } } } if let key = attributes[AttributeAccount] as? String { item["key"] = key } if let data = attributes[ValueData] as? NSData { if let text = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { item["value"] = text } else { item["value"] = data } } if let accessible = attributes[AttributeAccessible] as? String { if let accessibility = Accessibility(rawValue: accessible) { item["accessibility"] = accessibility.description } } if let synchronizable = attributes[AttributeSynchronizable] as? Bool { item["synchronizable"] = synchronizable ? "true" : "false" } return item } return items } // MARK: private class func conversionError(message message: String) -> NSError { let error = NSError(domain: KeychainAccessErrorDomain, code: Int(Status.ConversionError.rawValue), userInfo: [NSLocalizedDescriptionKey: message]) print("error:[\(error.code)] \(error.localizedDescription)") return error } private func conversionError(message message: String) -> NSError { return self.dynamicType.conversionError(message: message) } private class func securityError(status status: OSStatus) -> NSError { let message = Status(status: status).description let error = NSError(domain: KeychainAccessErrorDomain, code: Int(status), userInfo: [NSLocalizedDescriptionKey: message]) print("OSStatus error:[\(error.code)] \(error.localizedDescription)") return error } private func securityError(status status: OSStatus) -> NSError { return self.dynamicType.securityError(status: status) } } struct Options { var itemClass: ItemClass = .GenericPassword var service: String = "" var accessGroup: String? = nil var server: NSURL! var protocolType: ProtocolType! var authenticationType: AuthenticationType = .Default var accessibility: Accessibility = .AfterFirstUnlock var authenticationPolicy: AuthenticationPolicy? var synchronizable: Bool = false var label: String? var comment: String? var authenticationPrompt: String? var attributes = [String: AnyObject]() } /** Class Key Constant */ private let Class = String(kSecClass) /** Attribute Key Constants */ private let AttributeAccessible = String(kSecAttrAccessible) @available(iOS 8.0, OSX 10.10, *) private let AttributeAccessControl = String(kSecAttrAccessControl) private let AttributeAccessGroup = String(kSecAttrAccessGroup) private let AttributeSynchronizable = String(kSecAttrSynchronizable) private let AttributeCreationDate = String(kSecAttrCreationDate) private let AttributeModificationDate = String(kSecAttrModificationDate) private let AttributeDescription = String(kSecAttrDescription) private let AttributeComment = String(kSecAttrComment) private let AttributeCreator = String(kSecAttrCreator) private let AttributeType = String(kSecAttrType) private let AttributeLabel = String(kSecAttrLabel) private let AttributeIsInvisible = String(kSecAttrIsInvisible) private let AttributeIsNegative = String(kSecAttrIsNegative) private let AttributeAccount = String(kSecAttrAccount) private let AttributeService = String(kSecAttrService) private let AttributeGeneric = String(kSecAttrGeneric) private let AttributeSecurityDomain = String(kSecAttrSecurityDomain) private let AttributeServer = String(kSecAttrServer) private let AttributeProtocol = String(kSecAttrProtocol) private let AttributeAuthenticationType = String(kSecAttrAuthenticationType) private let AttributePort = String(kSecAttrPort) private let AttributePath = String(kSecAttrPath) private let SynchronizableAny = kSecAttrSynchronizableAny /** Search Constants */ private let MatchLimit = String(kSecMatchLimit) private let MatchLimitOne = kSecMatchLimitOne private let MatchLimitAll = kSecMatchLimitAll /** Return Type Key Constants */ private let ReturnData = String(kSecReturnData) private let ReturnAttributes = String(kSecReturnAttributes) private let ReturnRef = String(kSecReturnRef) private let ReturnPersistentRef = String(kSecReturnPersistentRef) /** Value Type Key Constants */ private let ValueData = String(kSecValueData) private let ValueRef = String(kSecValueRef) private let ValuePersistentRef = String(kSecValuePersistentRef) /** Other Constants */ @available(iOS 8.0, OSX 10.10, *) private let UseOperationPrompt = String(kSecUseOperationPrompt) #if os(iOS) @available(iOS, introduced=8.0, deprecated=9.0, message="Use a UseAuthenticationUI instead.") private let UseNoAuthenticationUI = String(kSecUseNoAuthenticationUI) #endif @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUI = String(kSecUseAuthenticationUI) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationContext = String(kSecUseAuthenticationContext) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUIAllow = String(kSecUseAuthenticationUIAllow) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUIFail = String(kSecUseAuthenticationUIFail) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUISkip = String(kSecUseAuthenticationUISkip) #if os(iOS) /** Credential Key Constants */ private let SharedPassword = String(kSecSharedPassword) #endif extension Keychain : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { let items = allItems() if items.isEmpty { return "[]" } var description = "[\n" for item in items { description += " " description += "\(item)\n" } description += "]" return description } public var debugDescription: String { return "\(items())" } } extension Options { func query() -> [String: AnyObject] { var query = [String: AnyObject]() query[Class] = itemClass.rawValue query[AttributeSynchronizable] = SynchronizableAny switch itemClass { case .GenericPassword: query[AttributeService] = service // Access group is not supported on any simulators. #if (!arch(i386) && !arch(x86_64)) || (!os(iOS) && !os(watchOS) && !os(tvOS)) if let accessGroup = self.accessGroup { query[AttributeAccessGroup] = accessGroup } #endif case .InternetPassword: query[AttributeServer] = server.host query[AttributePort] = server.port query[AttributeProtocol] = protocolType.rawValue query[AttributeAuthenticationType] = authenticationType.rawValue } if #available(OSX 10.10, *) { if authenticationPrompt != nil { query[UseOperationPrompt] = authenticationPrompt } } return query } func attributes(key key: String?, value: NSData) -> ([String: AnyObject], NSError?) { var attributes: [String: AnyObject] if key != nil { attributes = query() attributes[AttributeAccount] = key } else { attributes = [String: AnyObject]() } attributes[ValueData] = value if label != nil { attributes[AttributeLabel] = label } if comment != nil { attributes[AttributeComment] = comment } if let policy = authenticationPolicy { if #available(OSX 10.10, *) { var error: Unmanaged<CFError>? guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, SecAccessControlCreateFlags(rawValue: policy.rawValue), &error) else { if let error = error?.takeUnretainedValue() { return (attributes, error.error) } let message = Status.UnexpectedError.description return (attributes, NSError(domain: KeychainAccessErrorDomain, code: Int(Status.UnexpectedError.rawValue), userInfo: [NSLocalizedDescriptionKey: message])) } attributes[AttributeAccessControl] = accessControl } else { print("Unavailable 'Touch ID integration' on OS X versions prior to 10.10.") } } else { attributes[AttributeAccessible] = accessibility.rawValue } attributes[AttributeSynchronizable] = synchronizable return (attributes, nil) } } // MARK: extension Attributes : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "\(attributes)" } public var debugDescription: String { return description } } extension ItemClass : RawRepresentable, CustomStringConvertible { public init?(rawValue: String) { switch rawValue { case String(kSecClassGenericPassword): self = GenericPassword case String(kSecClassInternetPassword): self = InternetPassword default: return nil } } public var rawValue: String { switch self { case GenericPassword: return String(kSecClassGenericPassword) case InternetPassword: return String(kSecClassInternetPassword) } } public var description : String { switch self { case GenericPassword: return "GenericPassword" case InternetPassword: return "InternetPassword" } } } extension ProtocolType : RawRepresentable, CustomStringConvertible { public init?(rawValue: String) { switch rawValue { case String(kSecAttrProtocolFTP): self = FTP case String(kSecAttrProtocolFTPAccount): self = FTPAccount case String(kSecAttrProtocolHTTP): self = HTTP case String(kSecAttrProtocolIRC): self = IRC case String(kSecAttrProtocolNNTP): self = NNTP case String(kSecAttrProtocolPOP3): self = POP3 case String(kSecAttrProtocolSMTP): self = SMTP case String(kSecAttrProtocolSOCKS): self = SOCKS case String(kSecAttrProtocolIMAP): self = IMAP case String(kSecAttrProtocolLDAP): self = LDAP case String(kSecAttrProtocolAppleTalk): self = AppleTalk case String(kSecAttrProtocolAFP): self = AFP case String(kSecAttrProtocolTelnet): self = Telnet case String(kSecAttrProtocolSSH): self = SSH case String(kSecAttrProtocolFTPS): self = FTPS case String(kSecAttrProtocolHTTPS): self = HTTPS case String(kSecAttrProtocolHTTPProxy): self = HTTPProxy case String(kSecAttrProtocolHTTPSProxy): self = HTTPSProxy case String(kSecAttrProtocolFTPProxy): self = FTPProxy case String(kSecAttrProtocolSMB): self = SMB case String(kSecAttrProtocolRTSP): self = RTSP case String(kSecAttrProtocolRTSPProxy): self = RTSPProxy case String(kSecAttrProtocolDAAP): self = DAAP case String(kSecAttrProtocolEPPC): self = EPPC case String(kSecAttrProtocolIPP): self = IPP case String(kSecAttrProtocolNNTPS): self = NNTPS case String(kSecAttrProtocolLDAPS): self = LDAPS case String(kSecAttrProtocolTelnetS): self = TelnetS case String(kSecAttrProtocolIMAPS): self = IMAPS case String(kSecAttrProtocolIRCS): self = IRCS case String(kSecAttrProtocolPOP3S): self = POP3S default: return nil } } public var rawValue: String { switch self { case FTP: return String(kSecAttrProtocolFTP) case FTPAccount: return String(kSecAttrProtocolFTPAccount) case HTTP: return String(kSecAttrProtocolHTTP) case IRC: return String(kSecAttrProtocolIRC) case NNTP: return String(kSecAttrProtocolNNTP) case POP3: return String(kSecAttrProtocolPOP3) case SMTP: return String(kSecAttrProtocolSMTP) case SOCKS: return String(kSecAttrProtocolSOCKS) case IMAP: return String(kSecAttrProtocolIMAP) case LDAP: return String(kSecAttrProtocolLDAP) case AppleTalk: return String(kSecAttrProtocolAppleTalk) case AFP: return String(kSecAttrProtocolAFP) case Telnet: return String(kSecAttrProtocolTelnet) case SSH: return String(kSecAttrProtocolSSH) case FTPS: return String(kSecAttrProtocolFTPS) case HTTPS: return String(kSecAttrProtocolHTTPS) case HTTPProxy: return String(kSecAttrProtocolHTTPProxy) case HTTPSProxy: return String(kSecAttrProtocolHTTPSProxy) case FTPProxy: return String(kSecAttrProtocolFTPProxy) case SMB: return String(kSecAttrProtocolSMB) case RTSP: return String(kSecAttrProtocolRTSP) case RTSPProxy: return String(kSecAttrProtocolRTSPProxy) case DAAP: return String(kSecAttrProtocolDAAP) case EPPC: return String(kSecAttrProtocolEPPC) case IPP: return String(kSecAttrProtocolIPP) case NNTPS: return String(kSecAttrProtocolNNTPS) case LDAPS: return String(kSecAttrProtocolLDAPS) case TelnetS: return String(kSecAttrProtocolTelnetS) case IMAPS: return String(kSecAttrProtocolIMAPS) case IRCS: return String(kSecAttrProtocolIRCS) case POP3S: return String(kSecAttrProtocolPOP3S) } } public var description : String { switch self { case FTP: return "FTP" case FTPAccount: return "FTPAccount" case HTTP: return "HTTP" case IRC: return "IRC" case NNTP: return "NNTP" case POP3: return "POP3" case SMTP: return "SMTP" case SOCKS: return "SOCKS" case IMAP: return "IMAP" case LDAP: return "LDAP" case AppleTalk: return "AppleTalk" case AFP: return "AFP" case Telnet: return "Telnet" case SSH: return "SSH" case FTPS: return "FTPS" case HTTPS: return "HTTPS" case HTTPProxy: return "HTTPProxy" case HTTPSProxy: return "HTTPSProxy" case FTPProxy: return "FTPProxy" case SMB: return "SMB" case RTSP: return "RTSP" case RTSPProxy: return "RTSPProxy" case DAAP: return "DAAP" case EPPC: return "EPPC" case IPP: return "IPP" case NNTPS: return "NNTPS" case LDAPS: return "LDAPS" case TelnetS: return "TelnetS" case IMAPS: return "IMAPS" case IRCS: return "IRCS" case POP3S: return "POP3S" } } } extension AuthenticationType : RawRepresentable, CustomStringConvertible { public init?(rawValue: String) { switch rawValue { case String(kSecAttrAuthenticationTypeNTLM): self = NTLM case String(kSecAttrAuthenticationTypeMSN): self = MSN case String(kSecAttrAuthenticationTypeDPA): self = DPA case String(kSecAttrAuthenticationTypeRPA): self = RPA case String(kSecAttrAuthenticationTypeHTTPBasic): self = HTTPBasic case String(kSecAttrAuthenticationTypeHTTPDigest): self = HTTPDigest case String(kSecAttrAuthenticationTypeHTMLForm): self = HTMLForm case String(kSecAttrAuthenticationTypeDefault): self = Default default: return nil } } public var rawValue: String { switch self { case NTLM: return String(kSecAttrAuthenticationTypeNTLM) case MSN: return String(kSecAttrAuthenticationTypeMSN) case DPA: return String(kSecAttrAuthenticationTypeDPA) case RPA: return String(kSecAttrAuthenticationTypeRPA) case HTTPBasic: return String(kSecAttrAuthenticationTypeHTTPBasic) case HTTPDigest: return String(kSecAttrAuthenticationTypeHTTPDigest) case HTMLForm: return String(kSecAttrAuthenticationTypeHTMLForm) case Default: return String(kSecAttrAuthenticationTypeDefault) } } public var description : String { switch self { case NTLM: return "NTLM" case MSN: return "MSN" case DPA: return "DPA" case RPA: return "RPA" case HTTPBasic: return "HTTPBasic" case HTTPDigest: return "HTTPDigest" case HTMLForm: return "HTMLForm" case Default: return "Default" } } } extension Accessibility : RawRepresentable, CustomStringConvertible { public init?(rawValue: String) { if #available(OSX 10.10, *) { switch rawValue { case String(kSecAttrAccessibleWhenUnlocked): self = WhenUnlocked case String(kSecAttrAccessibleAfterFirstUnlock): self = AfterFirstUnlock case String(kSecAttrAccessibleAlways): self = Always case String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly): self = WhenPasscodeSetThisDeviceOnly case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly): self = WhenUnlockedThisDeviceOnly case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly): self = AfterFirstUnlockThisDeviceOnly case String(kSecAttrAccessibleAlwaysThisDeviceOnly): self = AlwaysThisDeviceOnly default: return nil } } else { switch rawValue { case String(kSecAttrAccessibleWhenUnlocked): self = WhenUnlocked case String(kSecAttrAccessibleAfterFirstUnlock): self = AfterFirstUnlock case String(kSecAttrAccessibleAlways): self = Always case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly): self = WhenUnlockedThisDeviceOnly case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly): self = AfterFirstUnlockThisDeviceOnly case String(kSecAttrAccessibleAlwaysThisDeviceOnly): self = AlwaysThisDeviceOnly default: return nil } } } public var rawValue: String { switch self { case WhenUnlocked: return String(kSecAttrAccessibleWhenUnlocked) case AfterFirstUnlock: return String(kSecAttrAccessibleAfterFirstUnlock) case Always: return String(kSecAttrAccessibleAlways) case WhenPasscodeSetThisDeviceOnly: if #available(OSX 10.10, *) { return String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly) } else { fatalError("'Accessibility.WhenPasscodeSetThisDeviceOnly' is not available on this version of OS.") } case WhenUnlockedThisDeviceOnly: return String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly) case AfterFirstUnlockThisDeviceOnly: return String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) case AlwaysThisDeviceOnly: return String(kSecAttrAccessibleAlwaysThisDeviceOnly) } } public var description : String { switch self { case WhenUnlocked: return "WhenUnlocked" case AfterFirstUnlock: return "AfterFirstUnlock" case Always: return "Always" case WhenPasscodeSetThisDeviceOnly: return "WhenPasscodeSetThisDeviceOnly" case WhenUnlockedThisDeviceOnly: return "WhenUnlockedThisDeviceOnly" case AfterFirstUnlockThisDeviceOnly: return "AfterFirstUnlockThisDeviceOnly" case AlwaysThisDeviceOnly: return "AlwaysThisDeviceOnly" } } } extension CFError { var error: NSError { let domain = CFErrorGetDomain(self) as String let code = CFErrorGetCode(self) let userInfo = CFErrorCopyUserInfo(self) as [NSObject: AnyObject] return NSError(domain: domain, code: code, userInfo: userInfo) } } public enum Status : OSStatus, ErrorType { case Success = 0 case Unimplemented = -4 case DiskFull = -34 case IO = -36 case OpWr = -49 case Param = -50 case WrPerm = -61 case Allocate = -108 case UserCanceled = -128 case BadReq = -909 case InternalComponent = -2070 case NotAvailable = -25291 case ReadOnly = -25292 case AuthFailed = -25293 case NoSuchKeychain = -25294 case InvalidKeychain = -25295 case DuplicateKeychain = -25296 case DuplicateCallback = -25297 case InvalidCallback = -25298 case DuplicateItem = -25299 case ItemNotFound = -25300 case BufferTooSmall = -25301 case DataTooLarge = -25302 case NoSuchAttr = -25303 case InvalidItemRef = -25304 case InvalidSearchRef = -25305 case NoSuchClass = -25306 case NoDefaultKeychain = -25307 case InteractionNotAllowed = -25308 case ReadOnlyAttr = -25309 case WrongSecVersion = -25310 case KeySizeNotAllowed = -25311 case NoStorageModule = -25312 case NoCertificateModule = -25313 case NoPolicyModule = -25314 case InteractionRequired = -25315 case DataNotAvailable = -25316 case DataNotModifiable = -25317 case CreateChainFailed = -25318 case InvalidPrefsDomain = -25319 case InDarkWake = -25320 case ACLNotSimple = -25240 case PolicyNotFound = -25241 case InvalidTrustSetting = -25242 case NoAccessForItem = -25243 case InvalidOwnerEdit = -25244 case TrustNotAvailable = -25245 case UnsupportedFormat = -25256 case UnknownFormat = -25257 case KeyIsSensitive = -25258 case MultiplePrivKeys = -25259 case PassphraseRequired = -25260 case InvalidPasswordRef = -25261 case InvalidTrustSettings = -25262 case NoTrustSettings = -25263 case Pkcs12VerifyFailure = -25264 case InvalidCertificate = -26265 case NotSigner = -26267 case PolicyDenied = -26270 case InvalidKey = -26274 case Decode = -26275 case Internal = -26276 case UnsupportedAlgorithm = -26268 case UnsupportedOperation = -26271 case UnsupportedPadding = -26273 case ItemInvalidKey = -34000 case ItemInvalidKeyType = -34001 case ItemInvalidValue = -34002 case ItemClassMissing = -34003 case ItemMatchUnsupported = -34004 case UseItemListUnsupported = -34005 case UseKeychainUnsupported = -34006 case UseKeychainListUnsupported = -34007 case ReturnDataUnsupported = -34008 case ReturnAttributesUnsupported = -34009 case ReturnRefUnsupported = -34010 case ReturnPersitentRefUnsupported = -34011 case ValueRefUnsupported = -34012 case ValuePersistentRefUnsupported = -34013 case ReturnMissingPointer = -34014 case MatchLimitUnsupported = -34015 case ItemIllegalQuery = -34016 case WaitForCallback = -34017 case MissingEntitlement = -34018 case UpgradePending = -34019 case MPSignatureInvalid = -25327 case OTRTooOld = -25328 case OTRIDTooNew = -25329 case ServiceNotAvailable = -67585 case InsufficientClientID = -67586 case DeviceReset = -67587 case DeviceFailed = -67588 case AppleAddAppACLSubject = -67589 case ApplePublicKeyIncomplete = -67590 case AppleSignatureMismatch = -67591 case AppleInvalidKeyStartDate = -67592 case AppleInvalidKeyEndDate = -67593 case ConversionError = -67594 case AppleSSLv2Rollback = -67595 case QuotaExceeded = -67596 case FileTooBig = -67597 case InvalidDatabaseBlob = -67598 case InvalidKeyBlob = -67599 case IncompatibleDatabaseBlob = -67600 case IncompatibleKeyBlob = -67601 case HostNameMismatch = -67602 case UnknownCriticalExtensionFlag = -67603 case NoBasicConstraints = -67604 case NoBasicConstraintsCA = -67605 case InvalidAuthorityKeyID = -67606 case InvalidSubjectKeyID = -67607 case InvalidKeyUsageForPolicy = -67608 case InvalidExtendedKeyUsage = -67609 case InvalidIDLinkage = -67610 case PathLengthConstraintExceeded = -67611 case InvalidRoot = -67612 case CRLExpired = -67613 case CRLNotValidYet = -67614 case CRLNotFound = -67615 case CRLServerDown = -67616 case CRLBadURI = -67617 case UnknownCertExtension = -67618 case UnknownCRLExtension = -67619 case CRLNotTrusted = -67620 case CRLPolicyFailed = -67621 case IDPFailure = -67622 case SMIMEEmailAddressesNotFound = -67623 case SMIMEBadExtendedKeyUsage = -67624 case SMIMEBadKeyUsage = -67625 case SMIMEKeyUsageNotCritical = -67626 case SMIMENoEmailAddress = -67627 case SMIMESubjAltNameNotCritical = -67628 case SSLBadExtendedKeyUsage = -67629 case OCSPBadResponse = -67630 case OCSPBadRequest = -67631 case OCSPUnavailable = -67632 case OCSPStatusUnrecognized = -67633 case EndOfData = -67634 case IncompleteCertRevocationCheck = -67635 case NetworkFailure = -67636 case OCSPNotTrustedToAnchor = -67637 case RecordModified = -67638 case OCSPSignatureError = -67639 case OCSPNoSigner = -67640 case OCSPResponderMalformedReq = -67641 case OCSPResponderInternalError = -67642 case OCSPResponderTryLater = -67643 case OCSPResponderSignatureRequired = -67644 case OCSPResponderUnauthorized = -67645 case OCSPResponseNonceMismatch = -67646 case CodeSigningBadCertChainLength = -67647 case CodeSigningNoBasicConstraints = -67648 case CodeSigningBadPathLengthConstraint = -67649 case CodeSigningNoExtendedKeyUsage = -67650 case CodeSigningDevelopment = -67651 case ResourceSignBadCertChainLength = -67652 case ResourceSignBadExtKeyUsage = -67653 case TrustSettingDeny = -67654 case InvalidSubjectName = -67655 case UnknownQualifiedCertStatement = -67656 case MobileMeRequestQueued = -67657 case MobileMeRequestRedirected = -67658 case MobileMeServerError = -67659 case MobileMeServerNotAvailable = -67660 case MobileMeServerAlreadyExists = -67661 case MobileMeServerServiceErr = -67662 case MobileMeRequestAlreadyPending = -67663 case MobileMeNoRequestPending = -67664 case MobileMeCSRVerifyFailure = -67665 case MobileMeFailedConsistencyCheck = -67666 case NotInitialized = -67667 case InvalidHandleUsage = -67668 case PVCReferentNotFound = -67669 case FunctionIntegrityFail = -67670 case InternalError = -67671 case MemoryError = -67672 case InvalidData = -67673 case MDSError = -67674 case InvalidPointer = -67675 case SelfCheckFailed = -67676 case FunctionFailed = -67677 case ModuleManifestVerifyFailed = -67678 case InvalidGUID = -67679 case InvalidHandle = -67680 case InvalidDBList = -67681 case InvalidPassthroughID = -67682 case InvalidNetworkAddress = -67683 case CRLAlreadySigned = -67684 case InvalidNumberOfFields = -67685 case VerificationFailure = -67686 case UnknownTag = -67687 case InvalidSignature = -67688 case InvalidName = -67689 case InvalidCertificateRef = -67690 case InvalidCertificateGroup = -67691 case TagNotFound = -67692 case InvalidQuery = -67693 case InvalidValue = -67694 case CallbackFailed = -67695 case ACLDeleteFailed = -67696 case ACLReplaceFailed = -67697 case ACLAddFailed = -67698 case ACLChangeFailed = -67699 case InvalidAccessCredentials = -67700 case InvalidRecord = -67701 case InvalidACL = -67702 case InvalidSampleValue = -67703 case IncompatibleVersion = -67704 case PrivilegeNotGranted = -67705 case InvalidScope = -67706 case PVCAlreadyConfigured = -67707 case InvalidPVC = -67708 case EMMLoadFailed = -67709 case EMMUnloadFailed = -67710 case AddinLoadFailed = -67711 case InvalidKeyRef = -67712 case InvalidKeyHierarchy = -67713 case AddinUnloadFailed = -67714 case LibraryReferenceNotFound = -67715 case InvalidAddinFunctionTable = -67716 case InvalidServiceMask = -67717 case ModuleNotLoaded = -67718 case InvalidSubServiceID = -67719 case AttributeNotInContext = -67720 case ModuleManagerInitializeFailed = -67721 case ModuleManagerNotFound = -67722 case EventNotificationCallbackNotFound = -67723 case InputLengthError = -67724 case OutputLengthError = -67725 case PrivilegeNotSupported = -67726 case DeviceError = -67727 case AttachHandleBusy = -67728 case NotLoggedIn = -67729 case AlgorithmMismatch = -67730 case KeyUsageIncorrect = -67731 case KeyBlobTypeIncorrect = -67732 case KeyHeaderInconsistent = -67733 case UnsupportedKeyFormat = -67734 case UnsupportedKeySize = -67735 case InvalidKeyUsageMask = -67736 case UnsupportedKeyUsageMask = -67737 case InvalidKeyAttributeMask = -67738 case UnsupportedKeyAttributeMask = -67739 case InvalidKeyLabel = -67740 case UnsupportedKeyLabel = -67741 case InvalidKeyFormat = -67742 case UnsupportedVectorOfBuffers = -67743 case InvalidInputVector = -67744 case InvalidOutputVector = -67745 case InvalidContext = -67746 case InvalidAlgorithm = -67747 case InvalidAttributeKey = -67748 case MissingAttributeKey = -67749 case InvalidAttributeInitVector = -67750 case MissingAttributeInitVector = -67751 case InvalidAttributeSalt = -67752 case MissingAttributeSalt = -67753 case InvalidAttributePadding = -67754 case MissingAttributePadding = -67755 case InvalidAttributeRandom = -67756 case MissingAttributeRandom = -67757 case InvalidAttributeSeed = -67758 case MissingAttributeSeed = -67759 case InvalidAttributePassphrase = -67760 case MissingAttributePassphrase = -67761 case InvalidAttributeKeyLength = -67762 case MissingAttributeKeyLength = -67763 case InvalidAttributeBlockSize = -67764 case MissingAttributeBlockSize = -67765 case InvalidAttributeOutputSize = -67766 case MissingAttributeOutputSize = -67767 case InvalidAttributeRounds = -67768 case MissingAttributeRounds = -67769 case InvalidAlgorithmParms = -67770 case MissingAlgorithmParms = -67771 case InvalidAttributeLabel = -67772 case MissingAttributeLabel = -67773 case InvalidAttributeKeyType = -67774 case MissingAttributeKeyType = -67775 case InvalidAttributeMode = -67776 case MissingAttributeMode = -67777 case InvalidAttributeEffectiveBits = -67778 case MissingAttributeEffectiveBits = -67779 case InvalidAttributeStartDate = -67780 case MissingAttributeStartDate = -67781 case InvalidAttributeEndDate = -67782 case MissingAttributeEndDate = -67783 case InvalidAttributeVersion = -67784 case MissingAttributeVersion = -67785 case InvalidAttributePrime = -67786 case MissingAttributePrime = -67787 case InvalidAttributeBase = -67788 case MissingAttributeBase = -67789 case InvalidAttributeSubprime = -67790 case MissingAttributeSubprime = -67791 case InvalidAttributeIterationCount = -67792 case MissingAttributeIterationCount = -67793 case InvalidAttributeDLDBHandle = -67794 case MissingAttributeDLDBHandle = -67795 case InvalidAttributeAccessCredentials = -67796 case MissingAttributeAccessCredentials = -67797 case InvalidAttributePublicKeyFormat = -67798 case MissingAttributePublicKeyFormat = -67799 case InvalidAttributePrivateKeyFormat = -67800 case MissingAttributePrivateKeyFormat = -67801 case InvalidAttributeSymmetricKeyFormat = -67802 case MissingAttributeSymmetricKeyFormat = -67803 case InvalidAttributeWrappedKeyFormat = -67804 case MissingAttributeWrappedKeyFormat = -67805 case StagedOperationInProgress = -67806 case StagedOperationNotStarted = -67807 case VerifyFailed = -67808 case QuerySizeUnknown = -67809 case BlockSizeMismatch = -67810 case PublicKeyInconsistent = -67811 case DeviceVerifyFailed = -67812 case InvalidLoginName = -67813 case AlreadyLoggedIn = -67814 case InvalidDigestAlgorithm = -67815 case InvalidCRLGroup = -67816 case CertificateCannotOperate = -67817 case CertificateExpired = -67818 case CertificateNotValidYet = -67819 case CertificateRevoked = -67820 case CertificateSuspended = -67821 case InsufficientCredentials = -67822 case InvalidAction = -67823 case InvalidAuthority = -67824 case VerifyActionFailed = -67825 case InvalidCertAuthority = -67826 case InvaldCRLAuthority = -67827 case InvalidCRLEncoding = -67828 case InvalidCRLType = -67829 case InvalidCRL = -67830 case InvalidFormType = -67831 case InvalidID = -67832 case InvalidIdentifier = -67833 case InvalidIndex = -67834 case InvalidPolicyIdentifiers = -67835 case InvalidTimeString = -67836 case InvalidReason = -67837 case InvalidRequestInputs = -67838 case InvalidResponseVector = -67839 case InvalidStopOnPolicy = -67840 case InvalidTuple = -67841 case MultipleValuesUnsupported = -67842 case NotTrusted = -67843 case NoDefaultAuthority = -67844 case RejectedForm = -67845 case RequestLost = -67846 case RequestRejected = -67847 case UnsupportedAddressType = -67848 case UnsupportedService = -67849 case InvalidTupleGroup = -67850 case InvalidBaseACLs = -67851 case InvalidTupleCredendtials = -67852 case InvalidEncoding = -67853 case InvalidValidityPeriod = -67854 case InvalidRequestor = -67855 case RequestDescriptor = -67856 case InvalidBundleInfo = -67857 case InvalidCRLIndex = -67858 case NoFieldValues = -67859 case UnsupportedFieldFormat = -67860 case UnsupportedIndexInfo = -67861 case UnsupportedLocality = -67862 case UnsupportedNumAttributes = -67863 case UnsupportedNumIndexes = -67864 case UnsupportedNumRecordTypes = -67865 case FieldSpecifiedMultiple = -67866 case IncompatibleFieldFormat = -67867 case InvalidParsingModule = -67868 case DatabaseLocked = -67869 case DatastoreIsOpen = -67870 case MissingValue = -67871 case UnsupportedQueryLimits = -67872 case UnsupportedNumSelectionPreds = -67873 case UnsupportedOperator = -67874 case InvalidDBLocation = -67875 case InvalidAccessRequest = -67876 case InvalidIndexInfo = -67877 case InvalidNewOwner = -67878 case InvalidModifyMode = -67879 case MissingRequiredExtension = -67880 case ExtendedKeyUsageNotCritical = -67881 case TimestampMissing = -67882 case TimestampInvalid = -67883 case TimestampNotTrusted = -67884 case TimestampServiceNotAvailable = -67885 case TimestampBadAlg = -67886 case TimestampBadRequest = -67887 case TimestampBadDataFormat = -67888 case TimestampTimeNotAvailable = -67889 case TimestampUnacceptedPolicy = -67890 case TimestampUnacceptedExtension = -67891 case TimestampAddInfoNotAvailable = -67892 case TimestampSystemFailure = -67893 case SigningTimeMissing = -67894 case TimestampRejection = -67895 case TimestampWaiting = -67896 case TimestampRevocationWarning = -67897 case TimestampRevocationNotification = -67898 case UnexpectedError = -99999 } extension Status : RawRepresentable, CustomStringConvertible { public init(status: OSStatus) { if let mappedStatus = Status(rawValue: status) { self = mappedStatus } else { self = .UnexpectedError } } public var description : String { switch self { case Success: return "No error." case Unimplemented: return "Function or operation not implemented." case DiskFull: return "The disk is full." case IO: return "I/O error (bummers)" case OpWr: return "file already open with with write permission" case Param: return "One or more parameters passed to a function were not valid." case WrPerm: return "write permissions error" case Allocate: return "Failed to allocate memory." case UserCanceled: return "User canceled the operation." case BadReq: return "Bad parameter or invalid state for operation." case InternalComponent: return "" case NotAvailable: return "No keychain is available. You may need to restart your computer." case ReadOnly: return "This keychain cannot be modified." case AuthFailed: return "The user name or passphrase you entered is not correct." case NoSuchKeychain: return "The specified keychain could not be found." case InvalidKeychain: return "The specified keychain is not a valid keychain file." case DuplicateKeychain: return "A keychain with the same name already exists." case DuplicateCallback: return "The specified callback function is already installed." case InvalidCallback: return "The specified callback function is not valid." case DuplicateItem: return "The specified item already exists in the keychain." case ItemNotFound: return "The specified item could not be found in the keychain." case BufferTooSmall: return "There is not enough memory available to use the specified item." case DataTooLarge: return "This item contains information which is too large or in a format that cannot be displayed." case NoSuchAttr: return "The specified attribute does not exist." case InvalidItemRef: return "The specified item is no longer valid. It may have been deleted from the keychain." case InvalidSearchRef: return "Unable to search the current keychain." case NoSuchClass: return "The specified item does not appear to be a valid keychain item." case NoDefaultKeychain: return "A default keychain could not be found." case InteractionNotAllowed: return "User interaction is not allowed." case ReadOnlyAttr: return "The specified attribute could not be modified." case WrongSecVersion: return "This keychain was created by a different version of the system software and cannot be opened." case KeySizeNotAllowed: return "This item specifies a key size which is too large." case NoStorageModule: return "A required component (data storage module) could not be loaded. You may need to restart your computer." case NoCertificateModule: return "A required component (certificate module) could not be loaded. You may need to restart your computer." case NoPolicyModule: return "A required component (policy module) could not be loaded. You may need to restart your computer." case InteractionRequired: return "User interaction is required, but is currently not allowed." case DataNotAvailable: return "The contents of this item cannot be retrieved." case DataNotModifiable: return "The contents of this item cannot be modified." case CreateChainFailed: return "One or more certificates required to validate this certificate cannot be found." case InvalidPrefsDomain: return "The specified preferences domain is not valid." case InDarkWake: return "In dark wake, no UI possible" case ACLNotSimple: return "The specified access control list is not in standard (simple) form." case PolicyNotFound: return "The specified policy cannot be found." case InvalidTrustSetting: return "The specified trust setting is invalid." case NoAccessForItem: return "The specified item has no access control." case InvalidOwnerEdit: return "Invalid attempt to change the owner of this item." case TrustNotAvailable: return "No trust results are available." case UnsupportedFormat: return "Import/Export format unsupported." case UnknownFormat: return "Unknown format in import." case KeyIsSensitive: return "Key material must be wrapped for export." case MultiplePrivKeys: return "An attempt was made to import multiple private keys." case PassphraseRequired: return "Passphrase is required for import/export." case InvalidPasswordRef: return "The password reference was invalid." case InvalidTrustSettings: return "The Trust Settings Record was corrupted." case NoTrustSettings: return "No Trust Settings were found." case Pkcs12VerifyFailure: return "MAC verification failed during PKCS12 import (wrong password?)" case InvalidCertificate: return "This certificate could not be decoded." case NotSigner: return "A certificate was not signed by its proposed parent." case PolicyDenied: return "The certificate chain was not trusted due to a policy not accepting it." case InvalidKey: return "The provided key material was not valid." case Decode: return "Unable to decode the provided data." case Internal: return "An internal error occurred in the Security framework." case UnsupportedAlgorithm: return "An unsupported algorithm was encountered." case UnsupportedOperation: return "The operation you requested is not supported by this key." case UnsupportedPadding: return "The padding you requested is not supported." case ItemInvalidKey: return "A string key in dictionary is not one of the supported keys." case ItemInvalidKeyType: return "A key in a dictionary is neither a CFStringRef nor a CFNumberRef." case ItemInvalidValue: return "A value in a dictionary is an invalid (or unsupported) CF type." case ItemClassMissing: return "No kSecItemClass key was specified in a dictionary." case ItemMatchUnsupported: return "The caller passed one or more kSecMatch keys to a function which does not support matches." case UseItemListUnsupported: return "The caller passed in a kSecUseItemList key to a function which does not support it." case UseKeychainUnsupported: return "The caller passed in a kSecUseKeychain key to a function which does not support it." case UseKeychainListUnsupported: return "The caller passed in a kSecUseKeychainList key to a function which does not support it." case ReturnDataUnsupported: return "The caller passed in a kSecReturnData key to a function which does not support it." case ReturnAttributesUnsupported: return "The caller passed in a kSecReturnAttributes key to a function which does not support it." case ReturnRefUnsupported: return "The caller passed in a kSecReturnRef key to a function which does not support it." case ReturnPersitentRefUnsupported: return "The caller passed in a kSecReturnPersistentRef key to a function which does not support it." case ValueRefUnsupported: return "The caller passed in a kSecValueRef key to a function which does not support it." case ValuePersistentRefUnsupported: return "The caller passed in a kSecValuePersistentRef key to a function which does not support it." case ReturnMissingPointer: return "The caller passed asked for something to be returned but did not pass in a result pointer." case MatchLimitUnsupported: return "The caller passed in a kSecMatchLimit key to a call which does not support limits." case ItemIllegalQuery: return "The caller passed in a query which contained too many keys." case WaitForCallback: return "This operation is incomplete, until the callback is invoked (not an error)." case MissingEntitlement: return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements." case UpgradePending: return "Error returned if keychain database needs a schema migration but the device is locked, clients should wait for a device unlock notification and retry the command." case MPSignatureInvalid: return "Signature invalid on MP message" case OTRTooOld: return "Message is too old to use" case OTRIDTooNew: return "Key ID is too new to use! Message from the future?" case ServiceNotAvailable: return "The required service is not available." case InsufficientClientID: return "The client ID is not correct." case DeviceReset: return "A device reset has occurred." case DeviceFailed: return "A device failure has occurred." case AppleAddAppACLSubject: return "Adding an application ACL subject failed." case ApplePublicKeyIncomplete: return "The public key is incomplete." case AppleSignatureMismatch: return "A signature mismatch has occurred." case AppleInvalidKeyStartDate: return "The specified key has an invalid start date." case AppleInvalidKeyEndDate: return "The specified key has an invalid end date." case ConversionError: return "A conversion error has occurred." case AppleSSLv2Rollback: return "A SSLv2 rollback error has occurred." case QuotaExceeded: return "The quota was exceeded." case FileTooBig: return "The file is too big." case InvalidDatabaseBlob: return "The specified database has an invalid blob." case InvalidKeyBlob: return "The specified database has an invalid key blob." case IncompatibleDatabaseBlob: return "The specified database has an incompatible blob." case IncompatibleKeyBlob: return "The specified database has an incompatible key blob." case HostNameMismatch: return "A host name mismatch has occurred." case UnknownCriticalExtensionFlag: return "There is an unknown critical extension flag." case NoBasicConstraints: return "No basic constraints were found." case NoBasicConstraintsCA: return "No basic CA constraints were found." case InvalidAuthorityKeyID: return "The authority key ID is not valid." case InvalidSubjectKeyID: return "The subject key ID is not valid." case InvalidKeyUsageForPolicy: return "The key usage is not valid for the specified policy." case InvalidExtendedKeyUsage: return "The extended key usage is not valid." case InvalidIDLinkage: return "The ID linkage is not valid." case PathLengthConstraintExceeded: return "The path length constraint was exceeded." case InvalidRoot: return "The root or anchor certificate is not valid." case CRLExpired: return "The CRL has expired." case CRLNotValidYet: return "The CRL is not yet valid." case CRLNotFound: return "The CRL was not found." case CRLServerDown: return "The CRL server is down." case CRLBadURI: return "The CRL has a bad Uniform Resource Identifier." case UnknownCertExtension: return "An unknown certificate extension was encountered." case UnknownCRLExtension: return "An unknown CRL extension was encountered." case CRLNotTrusted: return "The CRL is not trusted." case CRLPolicyFailed: return "The CRL policy failed." case IDPFailure: return "The issuing distribution point was not valid." case SMIMEEmailAddressesNotFound: return "An email address mismatch was encountered." case SMIMEBadExtendedKeyUsage: return "The appropriate extended key usage for SMIME was not found." case SMIMEBadKeyUsage: return "The key usage is not compatible with SMIME." case SMIMEKeyUsageNotCritical: return "The key usage extension is not marked as critical." case SMIMENoEmailAddress: return "No email address was found in the certificate." case SMIMESubjAltNameNotCritical: return "The subject alternative name extension is not marked as critical." case SSLBadExtendedKeyUsage: return "The appropriate extended key usage for SSL was not found." case OCSPBadResponse: return "The OCSP response was incorrect or could not be parsed." case OCSPBadRequest: return "The OCSP request was incorrect or could not be parsed." case OCSPUnavailable: return "OCSP service is unavailable." case OCSPStatusUnrecognized: return "The OCSP server did not recognize this certificate." case EndOfData: return "An end-of-data was detected." case IncompleteCertRevocationCheck: return "An incomplete certificate revocation check occurred." case NetworkFailure: return "A network failure occurred." case OCSPNotTrustedToAnchor: return "The OCSP response was not trusted to a root or anchor certificate." case RecordModified: return "The record was modified." case OCSPSignatureError: return "The OCSP response had an invalid signature." case OCSPNoSigner: return "The OCSP response had no signer." case OCSPResponderMalformedReq: return "The OCSP responder was given a malformed request." case OCSPResponderInternalError: return "The OCSP responder encountered an internal error." case OCSPResponderTryLater: return "The OCSP responder is busy, try again later." case OCSPResponderSignatureRequired: return "The OCSP responder requires a signature." case OCSPResponderUnauthorized: return "The OCSP responder rejected this request as unauthorized." case OCSPResponseNonceMismatch: return "The OCSP response nonce did not match the request." case CodeSigningBadCertChainLength: return "Code signing encountered an incorrect certificate chain length." case CodeSigningNoBasicConstraints: return "Code signing found no basic constraints." case CodeSigningBadPathLengthConstraint: return "Code signing encountered an incorrect path length constraint." case CodeSigningNoExtendedKeyUsage: return "Code signing found no extended key usage." case CodeSigningDevelopment: return "Code signing indicated use of a development-only certificate." case ResourceSignBadCertChainLength: return "Resource signing has encountered an incorrect certificate chain length." case ResourceSignBadExtKeyUsage: return "Resource signing has encountered an error in the extended key usage." case TrustSettingDeny: return "The trust setting for this policy was set to Deny." case InvalidSubjectName: return "An invalid certificate subject name was encountered." case UnknownQualifiedCertStatement: return "An unknown qualified certificate statement was encountered." case MobileMeRequestQueued: return "The MobileMe request will be sent during the next connection." case MobileMeRequestRedirected: return "The MobileMe request was redirected." case MobileMeServerError: return "A MobileMe server error occurred." case MobileMeServerNotAvailable: return "The MobileMe server is not available." case MobileMeServerAlreadyExists: return "The MobileMe server reported that the item already exists." case MobileMeServerServiceErr: return "A MobileMe service error has occurred." case MobileMeRequestAlreadyPending: return "A MobileMe request is already pending." case MobileMeNoRequestPending: return "MobileMe has no request pending." case MobileMeCSRVerifyFailure: return "A MobileMe CSR verification failure has occurred." case MobileMeFailedConsistencyCheck: return "MobileMe has found a failed consistency check." case NotInitialized: return "A function was called without initializing CSSM." case InvalidHandleUsage: return "The CSSM handle does not match with the service type." case PVCReferentNotFound: return "A reference to the calling module was not found in the list of authorized callers." case FunctionIntegrityFail: return "A function address was not within the verified module." case InternalError: return "An internal error has occurred." case MemoryError: return "A memory error has occurred." case InvalidData: return "Invalid data was encountered." case MDSError: return "A Module Directory Service error has occurred." case InvalidPointer: return "An invalid pointer was encountered." case SelfCheckFailed: return "Self-check has failed." case FunctionFailed: return "A function has failed." case ModuleManifestVerifyFailed: return "A module manifest verification failure has occurred." case InvalidGUID: return "An invalid GUID was encountered." case InvalidHandle: return "An invalid handle was encountered." case InvalidDBList: return "An invalid DB list was encountered." case InvalidPassthroughID: return "An invalid passthrough ID was encountered." case InvalidNetworkAddress: return "An invalid network address was encountered." case CRLAlreadySigned: return "The certificate revocation list is already signed." case InvalidNumberOfFields: return "An invalid number of fields were encountered." case VerificationFailure: return "A verification failure occurred." case UnknownTag: return "An unknown tag was encountered." case InvalidSignature: return "An invalid signature was encountered." case InvalidName: return "An invalid name was encountered." case InvalidCertificateRef: return "An invalid certificate reference was encountered." case InvalidCertificateGroup: return "An invalid certificate group was encountered." case TagNotFound: return "The specified tag was not found." case InvalidQuery: return "The specified query was not valid." case InvalidValue: return "An invalid value was detected." case CallbackFailed: return "A callback has failed." case ACLDeleteFailed: return "An ACL delete operation has failed." case ACLReplaceFailed: return "An ACL replace operation has failed." case ACLAddFailed: return "An ACL add operation has failed." case ACLChangeFailed: return "An ACL change operation has failed." case InvalidAccessCredentials: return "Invalid access credentials were encountered." case InvalidRecord: return "An invalid record was encountered." case InvalidACL: return "An invalid ACL was encountered." case InvalidSampleValue: return "An invalid sample value was encountered." case IncompatibleVersion: return "An incompatible version was encountered." case PrivilegeNotGranted: return "The privilege was not granted." case InvalidScope: return "An invalid scope was encountered." case PVCAlreadyConfigured: return "The PVC is already configured." case InvalidPVC: return "An invalid PVC was encountered." case EMMLoadFailed: return "The EMM load has failed." case EMMUnloadFailed: return "The EMM unload has failed." case AddinLoadFailed: return "The add-in load operation has failed." case InvalidKeyRef: return "An invalid key was encountered." case InvalidKeyHierarchy: return "An invalid key hierarchy was encountered." case AddinUnloadFailed: return "The add-in unload operation has failed." case LibraryReferenceNotFound: return "A library reference was not found." case InvalidAddinFunctionTable: return "An invalid add-in function table was encountered." case InvalidServiceMask: return "An invalid service mask was encountered." case ModuleNotLoaded: return "A module was not loaded." case InvalidSubServiceID: return "An invalid subservice ID was encountered." case AttributeNotInContext: return "An attribute was not in the context." case ModuleManagerInitializeFailed: return "A module failed to initialize." case ModuleManagerNotFound: return "A module was not found." case EventNotificationCallbackNotFound: return "An event notification callback was not found." case InputLengthError: return "An input length error was encountered." case OutputLengthError: return "An output length error was encountered." case PrivilegeNotSupported: return "The privilege is not supported." case DeviceError: return "A device error was encountered." case AttachHandleBusy: return "The CSP handle was busy." case NotLoggedIn: return "You are not logged in." case AlgorithmMismatch: return "An algorithm mismatch was encountered." case KeyUsageIncorrect: return "The key usage is incorrect." case KeyBlobTypeIncorrect: return "The key blob type is incorrect." case KeyHeaderInconsistent: return "The key header is inconsistent." case UnsupportedKeyFormat: return "The key header format is not supported." case UnsupportedKeySize: return "The key size is not supported." case InvalidKeyUsageMask: return "The key usage mask is not valid." case UnsupportedKeyUsageMask: return "The key usage mask is not supported." case InvalidKeyAttributeMask: return "The key attribute mask is not valid." case UnsupportedKeyAttributeMask: return "The key attribute mask is not supported." case InvalidKeyLabel: return "The key label is not valid." case UnsupportedKeyLabel: return "The key label is not supported." case InvalidKeyFormat: return "The key format is not valid." case UnsupportedVectorOfBuffers: return "The vector of buffers is not supported." case InvalidInputVector: return "The input vector is not valid." case InvalidOutputVector: return "The output vector is not valid." case InvalidContext: return "An invalid context was encountered." case InvalidAlgorithm: return "An invalid algorithm was encountered." case InvalidAttributeKey: return "A key attribute was not valid." case MissingAttributeKey: return "A key attribute was missing." case InvalidAttributeInitVector: return "An init vector attribute was not valid." case MissingAttributeInitVector: return "An init vector attribute was missing." case InvalidAttributeSalt: return "A salt attribute was not valid." case MissingAttributeSalt: return "A salt attribute was missing." case InvalidAttributePadding: return "A padding attribute was not valid." case MissingAttributePadding: return "A padding attribute was missing." case InvalidAttributeRandom: return "A random number attribute was not valid." case MissingAttributeRandom: return "A random number attribute was missing." case InvalidAttributeSeed: return "A seed attribute was not valid." case MissingAttributeSeed: return "A seed attribute was missing." case InvalidAttributePassphrase: return "A passphrase attribute was not valid." case MissingAttributePassphrase: return "A passphrase attribute was missing." case InvalidAttributeKeyLength: return "A key length attribute was not valid." case MissingAttributeKeyLength: return "A key length attribute was missing." case InvalidAttributeBlockSize: return "A block size attribute was not valid." case MissingAttributeBlockSize: return "A block size attribute was missing." case InvalidAttributeOutputSize: return "An output size attribute was not valid." case MissingAttributeOutputSize: return "An output size attribute was missing." case InvalidAttributeRounds: return "The number of rounds attribute was not valid." case MissingAttributeRounds: return "The number of rounds attribute was missing." case InvalidAlgorithmParms: return "An algorithm parameters attribute was not valid." case MissingAlgorithmParms: return "An algorithm parameters attribute was missing." case InvalidAttributeLabel: return "A label attribute was not valid." case MissingAttributeLabel: return "A label attribute was missing." case InvalidAttributeKeyType: return "A key type attribute was not valid." case MissingAttributeKeyType: return "A key type attribute was missing." case InvalidAttributeMode: return "A mode attribute was not valid." case MissingAttributeMode: return "A mode attribute was missing." case InvalidAttributeEffectiveBits: return "An effective bits attribute was not valid." case MissingAttributeEffectiveBits: return "An effective bits attribute was missing." case InvalidAttributeStartDate: return "A start date attribute was not valid." case MissingAttributeStartDate: return "A start date attribute was missing." case InvalidAttributeEndDate: return "An end date attribute was not valid." case MissingAttributeEndDate: return "An end date attribute was missing." case InvalidAttributeVersion: return "A version attribute was not valid." case MissingAttributeVersion: return "A version attribute was missing." case InvalidAttributePrime: return "A prime attribute was not valid." case MissingAttributePrime: return "A prime attribute was missing." case InvalidAttributeBase: return "A base attribute was not valid." case MissingAttributeBase: return "A base attribute was missing." case InvalidAttributeSubprime: return "A subprime attribute was not valid." case MissingAttributeSubprime: return "A subprime attribute was missing." case InvalidAttributeIterationCount: return "An iteration count attribute was not valid." case MissingAttributeIterationCount: return "An iteration count attribute was missing." case InvalidAttributeDLDBHandle: return "A database handle attribute was not valid." case MissingAttributeDLDBHandle: return "A database handle attribute was missing." case InvalidAttributeAccessCredentials: return "An access credentials attribute was not valid." case MissingAttributeAccessCredentials: return "An access credentials attribute was missing." case InvalidAttributePublicKeyFormat: return "A public key format attribute was not valid." case MissingAttributePublicKeyFormat: return "A public key format attribute was missing." case InvalidAttributePrivateKeyFormat: return "A private key format attribute was not valid." case MissingAttributePrivateKeyFormat: return "A private key format attribute was missing." case InvalidAttributeSymmetricKeyFormat: return "A symmetric key format attribute was not valid." case MissingAttributeSymmetricKeyFormat: return "A symmetric key format attribute was missing." case InvalidAttributeWrappedKeyFormat: return "A wrapped key format attribute was not valid." case MissingAttributeWrappedKeyFormat: return "A wrapped key format attribute was missing." case StagedOperationInProgress: return "A staged operation is in progress." case StagedOperationNotStarted: return "A staged operation was not started." case VerifyFailed: return "A cryptographic verification failure has occurred." case QuerySizeUnknown: return "The query size is unknown." case BlockSizeMismatch: return "A block size mismatch occurred." case PublicKeyInconsistent: return "The public key was inconsistent." case DeviceVerifyFailed: return "A device verification failure has occurred." case InvalidLoginName: return "An invalid login name was detected." case AlreadyLoggedIn: return "The user is already logged in." case InvalidDigestAlgorithm: return "An invalid digest algorithm was detected." case InvalidCRLGroup: return "An invalid CRL group was detected." case CertificateCannotOperate: return "The certificate cannot operate." case CertificateExpired: return "An expired certificate was detected." case CertificateNotValidYet: return "The certificate is not yet valid." case CertificateRevoked: return "The certificate was revoked." case CertificateSuspended: return "The certificate was suspended." case InsufficientCredentials: return "Insufficient credentials were detected." case InvalidAction: return "The action was not valid." case InvalidAuthority: return "The authority was not valid." case VerifyActionFailed: return "A verify action has failed." case InvalidCertAuthority: return "The certificate authority was not valid." case InvaldCRLAuthority: return "The CRL authority was not valid." case InvalidCRLEncoding: return "The CRL encoding was not valid." case InvalidCRLType: return "The CRL type was not valid." case InvalidCRL: return "The CRL was not valid." case InvalidFormType: return "The form type was not valid." case InvalidID: return "The ID was not valid." case InvalidIdentifier: return "The identifier was not valid." case InvalidIndex: return "The index was not valid." case InvalidPolicyIdentifiers: return "The policy identifiers are not valid." case InvalidTimeString: return "The time specified was not valid." case InvalidReason: return "The trust policy reason was not valid." case InvalidRequestInputs: return "The request inputs are not valid." case InvalidResponseVector: return "The response vector was not valid." case InvalidStopOnPolicy: return "The stop-on policy was not valid." case InvalidTuple: return "The tuple was not valid." case MultipleValuesUnsupported: return "Multiple values are not supported." case NotTrusted: return "The trust policy was not trusted." case NoDefaultAuthority: return "No default authority was detected." case RejectedForm: return "The trust policy had a rejected form." case RequestLost: return "The request was lost." case RequestRejected: return "The request was rejected." case UnsupportedAddressType: return "The address type is not supported." case UnsupportedService: return "The service is not supported." case InvalidTupleGroup: return "The tuple group was not valid." case InvalidBaseACLs: return "The base ACLs are not valid." case InvalidTupleCredendtials: return "The tuple credentials are not valid." case InvalidEncoding: return "The encoding was not valid." case InvalidValidityPeriod: return "The validity period was not valid." case InvalidRequestor: return "The requestor was not valid." case RequestDescriptor: return "The request descriptor was not valid." case InvalidBundleInfo: return "The bundle information was not valid." case InvalidCRLIndex: return "The CRL index was not valid." case NoFieldValues: return "No field values were detected." case UnsupportedFieldFormat: return "The field format is not supported." case UnsupportedIndexInfo: return "The index information is not supported." case UnsupportedLocality: return "The locality is not supported." case UnsupportedNumAttributes: return "The number of attributes is not supported." case UnsupportedNumIndexes: return "The number of indexes is not supported." case UnsupportedNumRecordTypes: return "The number of record types is not supported." case FieldSpecifiedMultiple: return "Too many fields were specified." case IncompatibleFieldFormat: return "The field format was incompatible." case InvalidParsingModule: return "The parsing module was not valid." case DatabaseLocked: return "The database is locked." case DatastoreIsOpen: return "The data store is open." case MissingValue: return "A missing value was detected." case UnsupportedQueryLimits: return "The query limits are not supported." case UnsupportedNumSelectionPreds: return "The number of selection predicates is not supported." case UnsupportedOperator: return "The operator is not supported." case InvalidDBLocation: return "The database location is not valid." case InvalidAccessRequest: return "The access request is not valid." case InvalidIndexInfo: return "The index information is not valid." case InvalidNewOwner: return "The new owner is not valid." case InvalidModifyMode: return "The modify mode is not valid." case MissingRequiredExtension: return "A required certificate extension is missing." case ExtendedKeyUsageNotCritical: return "The extended key usage extension was not marked critical." case TimestampMissing: return "A timestamp was expected but was not found." case TimestampInvalid: return "The timestamp was not valid." case TimestampNotTrusted: return "The timestamp was not trusted." case TimestampServiceNotAvailable: return "The timestamp service is not available." case TimestampBadAlg: return "An unrecognized or unsupported Algorithm Identifier in timestamp." case TimestampBadRequest: return "The timestamp transaction is not permitted or supported." case TimestampBadDataFormat: return "The timestamp data submitted has the wrong format." case TimestampTimeNotAvailable: return "The time source for the Timestamp Authority is not available." case TimestampUnacceptedPolicy: return "The requested policy is not supported by the Timestamp Authority." case TimestampUnacceptedExtension: return "The requested extension is not supported by the Timestamp Authority." case TimestampAddInfoNotAvailable: return "The additional information requested is not available." case TimestampSystemFailure: return "The timestamp request cannot be handled due to system failure." case SigningTimeMissing: return "A signing time was expected but was not found." case TimestampRejection: return "A timestamp transaction was rejected." case TimestampWaiting: return "A timestamp transaction is waiting." case TimestampRevocationWarning: return "A timestamp authority revocation warning was issued." case TimestampRevocationNotification: return "A timestamp authority revocation notification was issued." case UnexpectedError: return "Unexpected error has occurred." } } }
mit
99dc8184a0307b8e03041ce28ef01ae2
38.985639
207
0.60562
5.698832
false
false
false
false
ozgur/AutoLayoutAnimation
ImageViewController.swift
1
3372
// // ImageViewController.swift // AutoLayoutAnimation // // Created by Ozgur Vatansever on 11/1/15. // Copyright © 2015 Techshed. All rights reserved. // import UIKit import Cartography class ImageViewController: UIViewController { var firstImageView: UIImageView! var secondImageView: UIImageView! var thirdImageView: UIImageView! var scrollView: UIScrollView! var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = UIRectEdge() view.backgroundColor = .white title = "Scaling" print("Ozgur".length) scrollView = UIScrollView(frame: CGRect.zero) view.addSubview(scrollView) constrain(scrollView, v2: view) { scrollView, view in scrollView.leading == view.leading scrollView.trailing == view.trailing scrollView.top == view.top scrollView.bottom == view.bottom } let image = UIImage(named: "[email protected]")! firstImageView = UIImageView(image: image) firstImageView.backgroundColor = .clear secondImageView = UIImageView( image: UIImage(image: image, scaleAspectFitTo: CGSize(width: 283.375, height: 201.0)) ) secondImageView.contentMode = .center secondImageView.backgroundColor = .clear thirdImageView = UIImageView( image: UIImage(image: image, scaleAspectFillTo: CGSize(width: 283.375, height: 150.0)) ) thirdImageView.contentMode = .center thirdImageView.backgroundColor = .clear scrollView.translatesAutoresizingMaskIntoConstraints = false firstImageView.translatesAutoresizingMaskIntoConstraints = false secondImageView.translatesAutoresizingMaskIntoConstraints = false thirdImageView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(firstImageView) scrollView.addSubview(secondImageView) scrollView.addSubview(thirdImageView) constrain(firstImageView, v2: secondImageView, v3: scrollView) { firstImageView, secondImageView, scrollView in firstImageView.top == scrollView.top + 9.0 firstImageView.centerX == scrollView.centerX firstImageView.width == 283.375 firstImageView.height == 201.0 secondImageView.top == firstImageView.bottom + 9.0 secondImageView.centerX == firstImageView.centerX secondImageView.width == 283.375 secondImageView.height == 201.0 } constrain(thirdImageView, v2: secondImageView, v3: scrollView) { thirdImageView, secondImageView, scrollView in thirdImageView.top == secondImageView.bottom + 9.0 thirdImageView.centerX == secondImageView.centerX thirdImageView.width == 283.375 thirdImageView.height == 150.0 } textField = UITextField(frame: CGRect.zero) textField.borderStyle = .roundedRect textField.translatesAutoresizingMaskIntoConstraints = false textField.text = "aaaa" scrollView.addSubview(textField) constrain(textField, v2: thirdImageView, v3: scrollView) { textField, thirdImageView, scrollView in textField.top == thirdImageView.bottom + 9.0 textField.centerX == scrollView.centerX textField.width == 283.375 textField.height == 50.0 textField.bottom == scrollView.bottom - 9.0 } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } }
mit
8c449093d8dfc566ced249cbffc4ef4f
32.04902
115
0.718481
4.829513
false
false
false
false
harlanhaskins/csh.link
Sources/csh.link/Middleware/CSHMiddleware.swift
1
4314
import Vapor import TurnstileCSH import TurnstileCrypto import Auth import HTTP import URI import Foundation enum CSHMiddlewareError: Error, CustomStringConvertible { case noClientID case noClientSecret var example: String { return [ "{", " \"csh\": {", " \"client-id\": \"your-client-id\",", " \"client-secret: \"your-client-secret\"", " }", "}" ].joined(separator: "\n") } var description: String { var s = "Invalid CSH config file. You must have a " switch self { case .noClientID: s += "'client-id'" case .noClientSecret: s += "'client-secret'" } s += " key in your Vapor config, like so: " s += "\n" + example return s } } struct CSHMiddleware: Middleware { let authMiddleware: AuthMiddleware<CSHAccount> init(droplet: Droplet) throws { guard let clientID = droplet.config["app", "csh", "client-id"]?.string else { throw CSHMiddlewareError.noClientID } guard let clientSecret = droplet.config["app", "csh", "client-secret"]?.string else { throw CSHMiddlewareError.noClientSecret } let cshRealm = CSH(clientID: clientID, clientSecret: clientSecret) droplet.get("csh", "login") { request in let state = URandom().secureToken let redirect = request.uri .deletingLastPathComponent() .appendingPathComponent("consumer") .description let url = cshRealm.getLoginLink(redirectURL: redirect, state: state) let response = Response(redirect: url.absoluteString) response.cookies["csh-link-auth-state"] = state return response } authMiddleware = AuthMiddleware(user: CSHAccount.self, realm: cshRealm) droplet.group(authMiddleware) { group in group.get("csh", "consumer") { request in guard let state = request.cookies["csh-link-auth-state"] else { throw RequestError.csrfViolation } let cshAccount = try cshRealm.authenticate(authorizationCodeCallbackURL: request.uri.description, state: state) as! CSHAccount try request.auth.login(cshAccount) var redirected = request.uri .removingPath() redirected.query = nil if let next = try request.query?.extract("next") as String? { redirected = redirected.with(path: next) } return Response(redirect: redirected.description) } } } func respond(to request: Request, chainingTo next: Responder) throws -> Response { do { let _ = try request.auth.user() as! CSHAccount } catch { let newURI = request.uri .removingPath() .appendingPathComponent("csh") .appendingPathComponent("login") // FIXME: Figure out a way to get this to remain percent escaped // throughout the redirection. // newURI.append(query: [ // "next": path.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! // ]) return Response(redirect: newURI.description) } return try next.respond(to: request) } } extension URI { func with(scheme: String? = nil, userInfo: UserInfo? = nil, host: String? = nil, port: Int? = nil, path: String? = nil, query: String? = nil, fragment: String? = nil) -> URI { return URI(scheme: scheme ?? self.scheme, userInfo: userInfo ?? self.userInfo, host: host ?? self.host, port: port ?? self.port, path: path ?? self.path, query: query ?? self.query, fragment: fragment ?? self.fragment) } }
mit
6736f282d23a45f7bf438392467b79cb
36.189655
100
0.519471
4.919042
false
false
false
false
Tj3n/TVNExtensions
Rx/ReachabilityService.swift
1
2540
// // ReachabilityType.swift // TVNExtensions // // Created by TienVu on 2/21/19. // import Foundation import RxSwift import class Dispatch.DispatchQueue public enum ReachabilityStatus { case reachable(viaWiFi: Bool) case unreachable } extension ReachabilityStatus { var reachable: Bool { switch self { case .reachable: return true case .unreachable: return false } } } public protocol ReachabilityService { var reachability: Observable<ReachabilityStatus> { get } } public enum ReachabilityServiceError: Error { case failedToCreate } public class DefaultReachabilityService: ReachabilityService { private let _reachabilitySubject: BehaviorSubject<ReachabilityStatus> public var reachability: Observable<ReachabilityStatus> { return _reachabilitySubject.asObservable() } let _reachability: Reachability init() throws { guard let reachabilityRef = Reachability() else { throw ReachabilityServiceError.failedToCreate } let reachabilitySubject = BehaviorSubject<ReachabilityStatus>(value: .unreachable) // so main thread isn't blocked when reachability via WiFi is checked let backgroundQueue = DispatchQueue(label: "reachability.wificheck") reachabilityRef.whenReachable = { reachability in backgroundQueue.async { reachabilitySubject.on(.next(.reachable(viaWiFi: reachabilityRef.connection == .wifi))) } } reachabilityRef.whenUnreachable = { reachability in backgroundQueue.async { reachabilitySubject.on(.next(.unreachable)) } } try reachabilityRef.startNotifier() _reachability = reachabilityRef _reachabilitySubject = reachabilitySubject } deinit { _reachability.stopNotifier() } } extension ObservableConvertibleType { public func retryOnBecomesReachable(_ valueOnFailure:Element, reachabilityService: ReachabilityService) -> Observable<Element> { return self.asObservable() .catchError { (Element) -> Observable<Element> in reachabilityService.reachability .skip(1) .filter { $0.reachable } .flatMap { _ in Observable.error(Element) } .startWith(valueOnFailure) } .retry() } }
mit
a9e7402dcc4fb6a5489c789f0d6905e5
27.539326
132
0.629134
5.799087
false
false
false
false
j-j-m/DataTableKit
DataTableKit/Classes/TableRowAction.swift
1
3232
// // Copyright (c) 2015 Max Sokolov https://twitter.com/max_sokolov // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit open class TableRowActionOptions<CellType: ConfigurableCell> where CellType: UITableViewCell { open let item: CellType.T open let cell: CellType? open let indexPath: IndexPath open let userInfo: [AnyHashable: Any]? init(item: CellType.T, cell: CellType?, path: IndexPath, userInfo: [AnyHashable: Any]?) { self.item = item self.cell = cell self.indexPath = path self.userInfo = userInfo } } private enum TableRowActionHandler<CellType: ConfigurableCell> where CellType: UITableViewCell { case voidAction((TableRowActionOptions<CellType>) -> Void) case action((TableRowActionOptions<CellType>) -> Any?) func invoke(withOptions options: TableRowActionOptions<CellType>) -> Any? { switch self { case .voidAction(let handler): return handler(options) case .action(let handler): return handler(options) } } } open class TableRowAction<CellType: ConfigurableCell> where CellType: UITableViewCell { open var id: String? open let type: TableRowActionType private let handler: TableRowActionHandler<CellType> public init(_ type: TableRowActionType, handler: @escaping (_ options: TableRowActionOptions<CellType>) -> Void) { self.type = type self.handler = .voidAction(handler) } public init(_ key: String, handler: @escaping (_ options: TableRowActionOptions<CellType>) -> Void) { self.type = .custom(key) self.handler = .voidAction(handler) } public init<T>(_ type: TableRowActionType, handler: @escaping (_ options: TableRowActionOptions<CellType>) -> T) { self.type = type self.handler = .action(handler) } public func invokeActionOn(cell: UITableViewCell?, item: CellType.T, path: IndexPath, userInfo: [AnyHashable: Any]?) -> Any? { return handler.invoke(withOptions: TableRowActionOptions(item: item, cell: cell as? CellType, path: path, userInfo: userInfo)) } }
mit
64d259d8e4bd30f6ca1f3bca71395db1
37.939759
134
0.693069
4.564972
false
false
false
false
pentateu/SwiftCrypt
SwiftCrypt/Cipher.swift
1
7984
// // Cipher.swift // SwiftCrypt // // Created by Rafael Almeida on 19/10/14. // Copyright (c) 2014 ISWE. All rights reserved. // import CommonCrypto import Foundation import Security public class Cipher { public enum Operation { case Encrypt, Decrypt func nativeValue() -> CCOperation { switch self { case Encrypt : return CCOperation(kCCEncrypt) case Decrypt : return CCOperation(kCCDecrypt) } } } private let chosenCipherBlockSize = kCCBlockSizeAES128 //Crypto reference. private var cryptorRefPointer = UnsafeMutablePointer<CCCryptorRef>.alloc(1) private var accumulator : [UInt8] = [] var dataIn:NSData var dataInLength:Int var symmetricKey:SymmetricKey var keyBytes:UnsafePointer<Void> init(input:NSData, symmetricKey:SymmetricKey){ self.dataIn = input self.symmetricKey = symmetricKey self.dataInLength = dataIn.length self.keyBytes = symmetricKey.getSymmetricKeyBits()!.bytes } convenience init(input:String, symmetricKey:SymmetricKey){ let str = input as NSString self.init(input: str.dataUsingEncoding(NSUTF8StringEncoding)!, symmetricKey: symmetricKey) } func createCipher(operation:Operation, padding:Options) -> Status { var pkcs7 = padding var ivBuffer = UnsafePointer<Void>() // We don't want to toss padding on if we don't need to if (operation == .Encrypt) { if (padding.rawValue != UInt(kCCOptionECBMode)) { if ((dataIn.length % chosenCipherBlockSize) == 0) { pkcs7 = Options.None } else { pkcs7 = Options.PKCS7Padding } } } // Create and Initialize the crypto reference. let rawStatus = CCCryptorCreate(operation.nativeValue(), CCAlgorithm(kCCAlgorithmAES128), CCOptions(pkcs7.toRaw()), keyBytes, chosenCipherBlockSize, ivBuffer, cryptorRefPointer ) if let status = Status.fromRaw(rawStatus) { return status } else { println("FATAL_ERROR: CCCryptorCreate returned unexpected status (\(rawStatus)).") fatalError("CCCryptorCreate returned unexpected status.") } } /** Determines the number of bytes that wil be output by this Cryptor if inputBytes of additional data is input. :param: inputByteCount number of bytes that will be input. :param: isFinal true if buffer to be input will be the last input buffer, false otherwise. */ func getOutputLength(inputByteCount : Int, isFinal : Bool = false) -> Int { return CCCryptorGetOutputLength(cryptorRefPointer.memory, inputByteCount, isFinal) } func update() -> Status { // Calculate byte block alignment for all calls through to and including final. let dataOutAvailable = getOutputLength(dataIn.length, isFinal: true) var dataOut = Array<UInt8>(count:Int(dataOutAvailable), repeatedValue:0) var dataOutMoved:Int = 0 // Actually perform the encryption or decryption. let rawStatus = CCCryptorUpdate(cryptorRefPointer.memory, dataIn.bytes, dataInLength, &dataOut, dataOutAvailable, &dataOutMoved ) if let status = Status.fromRaw(rawStatus) { if(status == Status.Success){ accumulator += dataOut[0..<Int(dataOutMoved)] } return status } else { println("FATAL_ERROR: CCCryptorUpdate returned unexpected status (\(rawStatus)).") fatalError("CCCryptorUpdate returned unexpected status.") } } /** Retrieves all remaining encrypted or decrypted data from this cryptor. :note: If the underlying algorithm is an block cipher and the padding option has not been specified and the cumulative input to the cryptor has not been an integral multiple of the block length this will fail with an alignment error. :note: This method updates the status property :param: byteArrayOut the output bffer :returns: a tuple containing the number of output bytes produced and the status (see Status) */ public func final() -> NSData? { let dataOutAvailable = getOutputLength(dataIn.length, isFinal: true) var dataOut = Array<UInt8>(count:Int(dataOutAvailable), repeatedValue:0) var dataOutMoved:Int = 0 let rawStatus = CCCryptorFinal(cryptorRefPointer.memory, &dataOut, dataOutAvailable, &dataOutMoved) if let status = Status.fromRaw(rawStatus) { if status == Status.Success { accumulator += dataOut[0..<Int(dataOutMoved)] let result = NSData(bytes:accumulator, length:accumulator.count) return result } else{ println("FATAL_ERROR: CCCryptorFinal returned unexpected status (\(rawStatus)).") } return nil } else{ println("FATAL_ERROR: CCCryptorFinal returned unexpected status (\(rawStatus)).") fatalError("CCCryptorUpdate returned unexpected status.") } } func encryptAndDecrypt(operation:Operation) -> NSData? { var status = createCipher(operation, padding: Options.PKCS7Padding) if status != Status.Success { return nil } status = update() if status != Status.Success { return nil } let result = final() return result } public func encrypt() -> NSData? { return encryptAndDecrypt(Operation.Encrypt) } public func decrypt() -> NSData? { return encryptAndDecrypt(Operation.Decrypt) } /* * It turns out to be rather tedious to reprent ORable * bitmask style options in Swift. I would love to * to say that I was smart enough to figure out the * magic incantions below for myself, but it was, in fact, * NSHipster * From: http://nshipster.com/rawoptionsettype/ */ public struct Options : RawOptionSetType, BooleanType { private var value: UInt = 0 typealias RawValue = UInt public var rawValue : UInt { return self.value } public init(_ rawValue: UInt) { self.value = rawValue } // Needed for 1.1 RawRepresentable public init(rawValue: UInt) { self.value = rawValue } // Needed for 1.1 NilLiteralConverable public init(nilLiteral: ()) { } // Needed for 1.0 _RawOptionSet public static func fromMask(raw: UInt) -> Options { return self(raw) } public static func fromRaw(raw: UInt) -> Options? { return self(raw) } public func toRaw() -> UInt { return value } public var boolValue: Bool { return value != 0 } public static var allZeros: Options { return self(0) } public static func convertFromNilLiteral() -> Options { return self(0) } public static var None: Options { return self(0) } public static var PKCS7Padding: Options { return self(UInt(kCCOptionPKCS7Padding)) } public static var ECBMode: Options { return self(UInt(kCCOptionECBMode)) } } }
mit
9ea3826a22d99b9e77c189b84fb681b6
30.686508
107
0.578783
5.157623
false
false
false
false
GianniCarlo/Audiobook-Player
BookPlayer/Player/Player Screen/PlayerViewController.swift
1
15483
// // PlayerViewController.swift // BookPlayer // // Created by Gianni Carlo on 12/8/21. // Copyright © 2021 Tortuga Power. All rights reserved. // import AVFoundation import AVKit import BookPlayerKit import Combine import MediaPlayer import StoreKit import Themeable import UIKit class PlayerViewController: UIViewController, TelemetryProtocol { @IBOutlet private weak var closeButton: UIButton! @IBOutlet private weak var closeButtonTop: NSLayoutConstraint! @IBOutlet private weak var bottomToolbar: UIToolbar! @IBOutlet private weak var speedButton: UIBarButtonItem! @IBOutlet private weak var sleepButton: UIBarButtonItem! @IBOutlet private var sleepLabel: UIBarButtonItem! @IBOutlet private var chaptersButton: UIBarButtonItem! @IBOutlet private weak var moreButton: UIBarButtonItem! @IBOutlet private weak var artworkControl: ArtworkControl! @IBOutlet private weak var progressSlider: ProgressSlider! @IBOutlet private weak var currentTimeLabel: UILabel! @IBOutlet private weak var maxTimeButton: UIButton! @IBOutlet private weak var progressButton: UIButton! @IBOutlet weak var previousChapterButton: UIButton! @IBOutlet weak var nextChapterButton: UIButton! @IBOutlet weak var rewindIconView: PlayerJumpIconRewind! @IBOutlet weak var playIconView: PlayPauseIconView! @IBOutlet weak var forwardIconView: PlayerJumpIconForward! @IBOutlet weak var containerItemStackView: UIStackView! private var themedStatusBarStyle: UIStatusBarStyle? private var panGestureRecognizer: UIPanGestureRecognizer! private let dismissThreshold: CGFloat = 44.0 * UIScreen.main.nativeScale private var dismissFeedbackTriggered = false private var disposeBag = Set<AnyCancellable>() private var playingProgressSubscriber: AnyCancellable? private var viewModel = PlayerViewModel() // computed properties override var preferredStatusBarStyle: UIStatusBarStyle { let style = ThemeManager.shared.useDarkVariant ? UIStatusBarStyle.lightContent : UIStatusBarStyle.default return self.themedStatusBarStyle ?? style } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setup() setUpTheming() setupToolbar() setupGestures() bindGeneralObservers() bindProgressObservers() bindPlaybackControlsObservers() bindBookPlayingProgressEvents() bindTimerObserver() self.containerItemStackView.setCustomSpacing(26, after: self.artworkControl) } // Prevents dragging the view down from changing the safeAreaInsets.top // Note: I'm pretty sure there is a better solution for this that I haven't found yet - @pichfl override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() let window = UIApplication.shared.windows[0] let insets: UIEdgeInsets = window.safeAreaInsets self.closeButtonTop.constant = self.view.safeAreaInsets.top == 0.0 ? insets.top : 0 } func setup() { NotificationCenter.default.post(name: .playerPresented, object: nil) self.closeButton.accessibilityLabel = "voiceover_dismiss_player_title".localized } func setupPlayerView(with currentBook: Book) { guard !currentBook.isFault else { return } self.artworkControl.setupInfo(with: currentBook) self.updateView(with: self.viewModel.getCurrentProgressState()) applyTheme(self.themeProvider.currentTheme) // Solution thanks to https://forums.developer.apple.com/thread/63166#180445 self.modalPresentationCapturesStatusBarAppearance = true self.setNeedsStatusBarAppearanceUpdate() } func updateView(with progressObject: ProgressObject, shouldSetSliderValue: Bool = true) { if shouldSetSliderValue && self.progressSlider.isTracking { return } self.currentTimeLabel.text = progressObject.formattedCurrentTime if let progress = progressObject.progress { self.progressButton.setTitle(progress, for: .normal) } if let maxTime = progressObject.formattedMaxTime { self.maxTimeButton.setTitle(maxTime, for: .normal) } if shouldSetSliderValue { self.progressSlider.setProgress(progressObject.sliderValue) } self.previousChapterButton.isEnabled = self.viewModel.hasPreviousChapter() self.nextChapterButton.isEnabled = self.viewModel.hasNextChapter() } } // MARK: - Observers extension PlayerViewController { func bindProgressObservers() { self.progressSlider.publisher(for: .touchDown) .sink { [weak self] _ in // Disable recurring playback time events self?.playingProgressSubscriber?.cancel() self?.viewModel.handleSliderDownEvent() }.store(in: &disposeBag) self.progressSlider.publisher(for: .touchUpInside) .sink { [weak self] sender in guard let slider = sender as? UISlider else { return } self?.viewModel.handleSliderUpEvent(with: slider.value) // Enable back recurring playback time events after one second DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { self?.bindBookPlayingProgressEvents() } }.store(in: &disposeBag) self.progressSlider.publisher(for: .valueChanged) .sink { [weak self] sender in guard let self = self, let slider = sender as? UISlider else { return } self.progressSlider.setNeedsDisplay() let progressObject = self.viewModel.processSliderValueChangedEvent(with: slider.value) self.updateView(with: progressObject, shouldSetSliderValue: false) }.store(in: &disposeBag) } func bindBookPlayingProgressEvents() { self.playingProgressSubscriber?.cancel() self.playingProgressSubscriber = NotificationCenter.default.publisher(for: .bookPlaying) .sink { [weak self] _ in guard let self = self else { return } self.updateView(with: self.viewModel.getCurrentProgressState()) } } func bindPlaybackControlsObservers() { self.viewModel.isPlayingObserver() .receive(on: DispatchQueue.main) .sink { isPlaying in self.playIconView.isPlaying = isPlaying } .store(in: &disposeBag) self.maxTimeButton.publisher(for: .touchUpInside) .sink { [weak self] _ in guard let self = self, !self.progressSlider.isTracking else { return } let progressObject = self.viewModel.processToggleMaxTime() self.updateView(with: progressObject) }.store(in: &disposeBag) self.progressButton.publisher(for: .touchUpInside) .sink { [weak self] _ in guard let self = self, !self.progressSlider.isTracking else { return } let progressObject = self.viewModel.processToggleProgressState() self.updateView(with: progressObject) }.store(in: &disposeBag) self.playIconView.observeActionEvents() .sink { [weak self] _ in self?.viewModel.handlePlayPauseAction() } .store(in: &disposeBag) self.rewindIconView.observeActionEvents() .sink { [weak self] _ in self?.viewModel.handleRewindAction() } .store(in: &disposeBag) self.forwardIconView.observeActionEvents() .sink { [weak self] _ in self?.viewModel.handleForwardAction() } .store(in: &disposeBag) self.previousChapterButton.publisher(for: .touchUpInside) .sink { [weak self] _ in self?.viewModel.handlePreviousChapterAction() } .store(in: &disposeBag) self.nextChapterButton.publisher(for: .touchUpInside) .sink { [weak self] _ in self?.viewModel.handleNextChapterAction() } .store(in: &disposeBag) } func bindTimerObserver() { SleepTimer.shared.timeLeftFormatted.sink { timeFormatted in self.sleepLabel.title = timeFormatted if let timeFormatted = timeFormatted { self.sleepLabel.isAccessibilityElement = true let remainingTitle = String(describing: String.localizedStringWithFormat("sleep_remaining_title".localized, timeFormatted)) self.sleepLabel.accessibilityLabel = String(describing: remainingTitle) if let items = self.bottomToolbar.items, !items.contains(self.sleepLabel) { self.updateToolbar(true, animated: true) } } else { self.sleepLabel.isAccessibilityElement = false if let items = self.bottomToolbar.items, items.contains(self.sleepLabel) { self.updateToolbar(false, animated: true) } } }.store(in: &disposeBag) } func bindGeneralObservers() { NotificationCenter.default.publisher(for: .requestReview) .debounce(for: 1.0, scheduler: DispatchQueue.main) .sink { [weak self] _ in self?.viewModel.requestReview() } .store(in: &disposeBag) NotificationCenter.default.publisher(for: .bookEnd) .debounce(for: 1.0, scheduler: DispatchQueue.main) .sink { [weak self] _ in self?.viewModel.requestReview() } .store(in: &disposeBag) self.viewModel.currentBookObserver().sink { [weak self] book in guard let self = self, let book = book else { return } self.setupPlayerView(with: book) }.store(in: &disposeBag) self.viewModel.hasChapters().sink { hasChapters in self.chaptersButton.isEnabled = hasChapters }.store(in: &disposeBag) SpeedManager.shared.currentSpeed.sink { [weak self] speed in guard let self = self else { return } self.speedButton.title = self.formatSpeed(speed) self.speedButton.accessibilityLabel = String(describing: self.formatSpeed(speed) + " \("speed_title".localized)") }.store(in: &disposeBag) } } // MARK: - Toolbar extension PlayerViewController { func setupToolbar() { self.bottomToolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default) self.bottomToolbar.setShadowImage(UIImage(), forToolbarPosition: .any) self.speedButton.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18.0, weight: .semibold)], for: .normal) } func updateToolbar(_ showTimerLabel: Bool = false, animated: Bool = false) { let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) var items: [UIBarButtonItem] = [ self.speedButton, spacer, self.sleepButton ] if showTimerLabel { items.append(self.sleepLabel) } items.append(spacer) items.append(self.chaptersButton) let avRoutePickerBarButtonItem = UIBarButtonItem(customView: AVRoutePickerView(frame: CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0))) avRoutePickerBarButtonItem.isAccessibilityElement = true avRoutePickerBarButtonItem.accessibilityLabel = "audio_source_title".localized items.append(spacer) items.append(avRoutePickerBarButtonItem) items.append(spacer) items.append(self.moreButton) self.bottomToolbar.setItems(items, animated: animated) } } // MARK: - Actions extension PlayerViewController { // MARK: - Interface actions @IBAction func dismissPlayer() { self.dismiss(animated: true, completion: nil) NotificationCenter.default.post(name: .playerDismissed, object: nil, userInfo: nil) } // MARK: - Toolbar actions @IBAction func setSpeed() { let actionSheet = self.viewModel.getSpeedActionSheet() self.present(actionSheet, animated: true, completion: nil) } @IBAction func setSleepTimer() { let actionSheet = SleepTimer.shared.actionSheet() self.present(actionSheet, animated: true, completion: nil) } @IBAction func showMore() { guard PlayerManager.shared.hasLoadedBook else { return } let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "jump_start_title".localized, style: .default, handler: { _ in PlayerManager.shared.pause() PlayerManager.shared.jumpTo(0.0) })) let markTitle = self.viewModel.isBookFinished() ? "mark_unfinished_title".localized : "mark_finished_title".localized actionSheet.addAction(UIAlertAction(title: markTitle, style: .default, handler: { _ in PlayerManager.shared.pause() PlayerManager.shared.markAsCompleted(!self.viewModel.isBookFinished()) })) actionSheet.addAction(UIAlertAction(title: "cancel_button".localized, style: .cancel, handler: nil)) self.present(actionSheet, animated: true, completion: nil) } } extension PlayerViewController: UIGestureRecognizerDelegate { func setupGestures() { self.panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.panAction)) self.panGestureRecognizer.delegate = self self.panGestureRecognizer.maximumNumberOfTouches = 1 self.panGestureRecognizer.cancelsTouchesInView = true self.view.addGestureRecognizer(self.panGestureRecognizer) } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == self.panGestureRecognizer { return limitPanAngle(self.panGestureRecognizer, degreesOfFreedom: 45.0, comparator: .greaterThan) } return true } private func updatePresentedViewForTranslation(_ yTranslation: CGFloat) { let translation: CGFloat = rubberBandDistance(yTranslation, dimension: self.view.frame.height, constant: 0.55) self.view?.transform = CGAffineTransform(translationX: 0, y: max(translation, 0.0)) } @objc private func panAction(gestureRecognizer: UIPanGestureRecognizer) { guard gestureRecognizer.isEqual(self.panGestureRecognizer) else { return } switch gestureRecognizer.state { case .began: gestureRecognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view.superview) case .changed: let translation = gestureRecognizer.translation(in: self.view) self.updatePresentedViewForTranslation(translation.y) if translation.y > self.dismissThreshold, !self.dismissFeedbackTriggered { self.dismissFeedbackTriggered = true UIImpactFeedbackGenerator(style: .medium).impactOccurred() } case .ended, .cancelled, .failed: let translation = gestureRecognizer.translation(in: self.view) if translation.y > self.dismissThreshold { self.dismissPlayer() return } self.dismissFeedbackTriggered = false UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.75, initialSpringVelocity: 1.5, options: .preferredFramesPerSecond60, animations: { self.view?.transform = .identity }) default: break } } } extension PlayerViewController: Themeable { func applyTheme(_ theme: Theme) { self.themedStatusBarStyle = theme.useDarkVariant ? .lightContent : .default setNeedsStatusBarAppearanceUpdate() self.view.backgroundColor = theme.systemBackgroundColor self.bottomToolbar.tintColor = theme.primaryColor self.closeButton.tintColor = theme.linkColor // controls self.progressSlider.minimumTrackTintColor = theme.primaryColor self.progressSlider.maximumTrackTintColor = theme.primaryColor.withAlpha(newAlpha: 0.3) self.currentTimeLabel.textColor = theme.primaryColor self.maxTimeButton.setTitleColor(theme.primaryColor, for: .normal) self.progressButton.setTitleColor(theme.primaryColor, for: .normal) } }
gpl-3.0
845ed110ea55449f19832b13818b6d20
32.223176
141
0.713345
4.628401
false
false
false
false
cliffpanos/True-Pass-iOS
iOSApp/CheckInWatchKitApp Extension/Models/Pass.swift
1
758
// // Pass.swift // True Pass // // Created by Cliff Panos on 5/12/17. // Copyright © 2017 Clifford Panos. All rights reserved. // import Foundation class Pass: Equatable, Hashable { var name: String! var email: String! var image: Data! var timeStart: Date! var timeEnd: Date! var didCheckIn: Bool? var locationName: String? var hashValue: Int { return 1 //TODO } static func == (p1: Pass, p2: Pass) -> Bool { //== cannot compare the image data because the WCD.deletePass does not send the image data let condition = p1.name == p2.name && p1.email == p2.email && p1.timeStart == p2.timeStart && p1.timeEnd == p2.timeEnd return condition } }
apache-2.0
8264f503f60a73efffaa37aed69b6890
21.939394
126
0.595773
3.692683
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/ImageDownload.swift
1
1902
import Foundation public enum ImageOrigin: Int { case network = 0 case disk = 1 case memory = 2 case unknown = 3 } extension ImageOrigin { public var debugColor: UIColor { switch self { case .network: return UIColor.red case .disk: return UIColor.yellow case .memory: return UIColor.green case .unknown: return UIColor.black } } } public protocol ImageOriginConvertible { func asImageOrigin() -> ImageOrigin } public func asImageOrigin<T: ImageOriginConvertible>(_ c: T) -> ImageOrigin { return c.asImageOrigin() } @objc(WMFImage) public class Image: NSObject { @objc open var staticImage: UIImage @objc open var animatedImage: FLAnimatedImage? @objc public init(staticImage: UIImage, animatedImage: FLAnimatedImage?) { self.staticImage = staticImage self.animatedImage = animatedImage } } @objc(WMFImageDownload) public class ImageDownload: NSObject { // Exposing enums as string constants for ObjC compatibility @objc public static let imageOriginNetwork = ImageOrigin.network.rawValue @objc public static let imageOriginDisk = ImageOrigin.disk.rawValue @objc public static let imageOriginMemory = ImageOrigin.memory.rawValue @objc public static let imageOriginUnknown = ImageOrigin.unknown.rawValue @objc open var url: URL @objc open var image: Image open var origin: ImageOrigin @objc open var originRawValue: Int { return origin.rawValue } public init(url: URL, image: Image, origin: ImageOrigin) { self.url = url self.image = image self.origin = origin } public init(url: URL, image: Image, originRawValue: Int) { self.url = url self.image = image self.origin = ImageOrigin(rawValue: originRawValue)! } }
mit
386accee18aa96307ac4dbbb4affb43a
27.38806
104
0.664038
4.475294
false
false
false
false
ello/ello-ios
Sources/Controllers/Onboarding/OnboardingInterestsViewController.swift
1
3764
//// /// OnboardingInterestsViewController.swift // class OnboardingInterestsViewController: StreamableViewController { var mockScreen: Screen? var screen: Screen { return mockScreen ?? (self.view as! Screen) } var selectedCategories: [Category] = [] var onboardingViewController: OnboardingViewController? var onboardingData: OnboardingData! required init() { super.init(nibName: nil, bundle: nil) streamViewController.streamKind = .onboardingCategories } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { let screen = Screen() view = screen viewContainer = screen } override func viewDidLoad() { super.viewDidLoad() streamViewController.isPullToRefreshEnabled = false streamViewController.showLoadingSpinner() streamViewController.loadInitialPage() } override func showNavBars(animated: Bool) {} override func hideNavBars(animated: Bool) {} override func streamViewStreamCellItems( jsonables: [Model], defaultGenerator generator: StreamCellItemGenerator ) -> [StreamCellItem]? { let header = NSAttributedString( primaryHeader: InterfaceString.Onboard.PickCategoriesPrimary, secondaryHeader: InterfaceString.Onboard.PickCategoriesSecondary ) let headerCellItem = StreamCellItem(type: .tallHeader(header)) var items: [StreamCellItem] = [headerCellItem] if let categories = jsonables as? [Category] { let onboardingCategories = categories.filter { $0.allowInOnboarding } items += onboardingCategories.map { StreamCellItem(jsonable: $0, type: .onboardingCategoryCard) } } return items } } extension OnboardingInterestsViewController: OnboardingStepController { func onboardingStepBegin() { let prompt = InterfaceString.Onboard.Pick(3) onboardingViewController?.hasAbortButton = false onboardingViewController?.canGoNext = false onboardingViewController?.prompt = prompt } func onboardingWillProceed( abort: Bool, proceedClosure: @escaping (_ success: OnboardingViewController.OnboardingProceed) -> Void ) { guard selectedCategories.count > 0 else { return } onboardingData.categories = selectedCategories for category in selectedCategories { Tracker.shared.onboardingCategorySelected(category) } ProfileService().update(categories: selectedCategories, onboarding: true) .done { _ in proceedClosure(.continue) } .catch { [weak self] _ in guard let `self` = self else { return } let alertController = AlertViewController( confirmation: InterfaceString.GenericError ) self.appViewController?.present(alertController, animated: true, completion: nil) proceedClosure(.error) } } } extension OnboardingInterestsViewController: SelectedCategoryResponder { func categoriesSelectionChanged(selection: [Category]) { let selectionCount = selection.count let prompt: String? let canGoNext: Bool switch selectionCount { case 0, 1, 2: prompt = InterfaceString.Onboard.Pick(3 - selectionCount) canGoNext = false default: prompt = nil canGoNext = true } selectedCategories = selection onboardingViewController?.prompt = prompt onboardingViewController?.canGoNext = canGoNext } }
mit
4da4a46a1e6a1398bc3ceac362ace6ef
32.017544
97
0.650106
5.527166
false
false
false
false
nodes-ios/NStackSDK
NStackSDK/NStackSDK/Classes/Model/TranslationsResponse.swift
1
1557
// // TranslationsResponse.swift // NStackSDK // // Created by Dominik Hádl on 15/08/16. // Copyright © 2016 Nodes ApS. All rights reserved. // import Foundation #if os(iOS) import UIKit import TranslationManager #elseif os(tvOS) import TranslationManager_tvOS #elseif os(watchOS) import TranslationManager_watchOS #elseif os(macOS) import TranslationManager_macOS #endif public struct TranslationsResponse: Codable { let translations: [String: Any] let language: Language? enum CodingKeys: String, CodingKey { case translations = "data" case languageData = "meta" } enum LanguageCodingKeys: String, CodingKey { case language } init() { self.translations = [:] self.language = nil } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) translations = try values.decodeIfPresent([String: Any].self, forKey: .translations) ?? [:] let languageData = try values.nestedContainer(keyedBy: LanguageCodingKeys.self, forKey: .languageData) language = try languageData.decodeIfPresent(Language.self, forKey: .language) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(translations, forKey: .translations) var languageData = container.nestedContainer(keyedBy: LanguageCodingKeys.self, forKey: .languageData) try languageData.encode(language, forKey: .language) } }
mit
2b9d1daed1752620b029d0ab344a4ad1
27.272727
110
0.700965
4.442857
false
false
false
false
jaksatomovic/Snapgram
Snapgram/resetPasswordVC.swift
1
3146
// // resetPasswordVC.swift // Snapgram // // Created by Jaksa Tomovic on 28/11/16. // Copyright © 2016 Jaksa Tomovic. All rights reserved. // import UIKit import Parse class resetPasswordVC: UIViewController { // textfield @IBOutlet weak var emailTxt: UITextField! // buttons @IBOutlet weak var resetBtn: UIButton! @IBOutlet weak var cancelBtn: UIButton! // default func override func viewDidLoad() { super.viewDidLoad() // alignment emailTxt.frame = CGRect(x: 10, y: 120, width: self.view.frame.size.width - 20, height: 30) resetBtn.frame = CGRect(x: 20, y: emailTxt.frame.origin.y + 50, width: self.view.frame.size.width / 4, height: 30) resetBtn.layer.cornerRadius = resetBtn.frame.size.width / 20 cancelBtn.frame = CGRect(x: self.view.frame.size.width - self.view.frame.size.width / 4 - 20, y: resetBtn.frame.origin.y, width: self.view.frame.size.width / 4, height: 30) cancelBtn.layer.cornerRadius = cancelBtn.frame.size.width / 20 // background let bg = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)) bg.image = UIImage(named: "bg.jpg") bg.layer.zPosition = -1 self.view.addSubview(bg) } // clicked reset button @IBAction func resetBtn_click(_ sender: AnyObject) { // hide keyboard self.view.endEditing(true) // email textfield is empty if emailTxt.text!.isEmpty { // show alert message let alert = UIAlertController(title: "Email field", message: "is empty", preferredStyle: UIAlertControllerStyle.alert) let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil) alert.addAction(ok) self.present(alert, animated: true, completion: nil) } // request for reseting password PFUser.requestPasswordResetForEmail(inBackground: emailTxt.text!) { (success, error) -> Void in if success { // show alert message let alert = UIAlertController(title: "Email for reseting password", message: "has been sent to texted email", preferredStyle: UIAlertControllerStyle.alert) // if pressed OK call self.dismiss.. function let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (UIAlertAction) -> Void in self.dismiss(animated: true, completion: nil) }) alert.addAction(ok) self.present(alert, animated: true, completion: nil) } else { print(error?.localizedDescription) } } } // clicked cancel button @IBAction func cancelBtn_click(_ sender: AnyObject) { // hide keyboard when pressed cancel self.view.endEditing(true) self.dismiss(animated: true, completion: nil) } }
mit
2ff04cdfe35a0cab90f5f0e41df38bfc
33.944444
180
0.592687
4.492857
false
false
false
false
esttorhe/RxSwift
RxExample/RxExample/Examples/GitHubSignup/GitHubAPI/GitHubAPI.swift
1
2008
// // GitHubAPI.swift // RxExample // // Created by Krunoslav Zaher on 4/25/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift import RxCocoa enum SignupState: Equatable { case InitialState case SigningUp case SignedUp(signedUp: Bool) } func ==(lhs: SignupState, rhs: SignupState) -> Bool { switch (lhs, rhs) { case (.InitialState, .InitialState): return true case (.SigningUp, .SigningUp): return true case (.SignedUp(let lhsSignup), .SignedUp(let rhsSignup)): return lhsSignup == rhsSignup default: return false } } class GitHubAPI { let dataScheduler: ImmediateScheduler let URLSession: NSURLSession init(dataScheduler: ImmediateScheduler, URLSession: NSURLSession) { self.dataScheduler = dataScheduler self.URLSession = URLSession } func usernameAvailable(username: String) -> Observable<Bool> { // this is ofc just mock, but good enough let URL = NSURL(string: "https://github.com/\(URLEscape(username))")! let request = NSURLRequest(URL: URL) return self.URLSession.rx_response(request) >- map { (maybeData, maybeResponse) in if let response = maybeResponse as? NSHTTPURLResponse { return response.statusCode == 404 } else { return false } } >- observeSingleOn(self.dataScheduler) >- onError { result in return just(false) } } func signup(username: String, password: String) -> Observable<SignupState> { // this is also just a mock let signupResult = SignupState.SignedUp(signedUp: arc4random() % 5 == 0 ? false : true) return concat([just(signupResult), never()]) >- throttle(5, MainScheduler.sharedInstance) >- startWith(SignupState.SigningUp) } }
mit
c920c9c6518deff7af77bb828a3e8ad5
28.544118
95
0.603586
4.584475
false
false
false
false
EstefaniaGilVaquero/ciceIOS
AppCiceTarget/CICETARGET/ViewController.swift
1
3307
// // ViewController.swift // CICETARGET // // Created by formador on 23/5/16. // Copyright © 2016 Cice. All rights reserved. // import UIKit class ViewController: UIViewController { //MARK: - IBOUTLET //MARK: - VARIABLES LOCALES GLOBALES var currentValue = 50 var targetValue = 0 var puntuacion = 0 var ronda = 0 //MARK: - IBOUTLET @IBOutlet weak var myTargetValue: UILabel! @IBOutlet weak var myPuntuacionLBL: UILabel! @IBOutlet weak var myRondaLBL: UILabel! @IBOutlet weak var mySliderCustom: UISlider! //MARK: - IBACTION @IBAction func showAlertACTION(sender: AnyObject) { /*let diferencia : Int if currentValue > targetValue{ diferencia = currentValue - targetValue }else if targetValue > currentValue{ diferencia = targetValue - currentValue }else{ diferencia = 0 }*/ let diferencia = abs(targetValue - currentValue) var puntos = 100 - diferencia let title : String if diferencia == 0{ title = "Perfecto" puntos += 100 }else if diferencia < 5{ title = "Casi das en el blanco" puntos += 50 }else if diferencia < 10{ title = "Tienes que mejorar" puntos += 10 }else{ title = "No tienes punteria" } puntuacion += puntos /*let message = "El valor del slider es \(currentValue) \n y el valor del target es \(targetValue) \n y la diferencia es \(diferencia)"*/ let message = "tu puntuacion es \(puntos)" let alertVC = UIAlertController(title: title, message: message, preferredStyle: .Alert) alertVC.addAction(UIAlertAction(title: "Asombroso", style: .Default, handler: { action in self.startNewRound() self.updateLabels() })) presentViewController(alertVC, animated: true, completion: nil) //startNewRound() //updateLabels() } @IBAction func sliderMovidoACTION(mySlider: UISlider) { currentValue = Int(mySlider.value) //("El slider tiene un valor de \(currentValue)") } @IBAction func resetGame(sender: AnyObject) { starNewGame() updateLabels() } //MARK: - VIDA DEL VC override func viewDidLoad() { super.viewDidLoad() starNewGame() updateLabels() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - UTILS func startNewRound(){ ronda += 1 currentValue = 50 targetValue = 1 + Int(arc4random_uniform(100)) mySliderCustom.value = Float(currentValue) } func updateLabels(){ myTargetValue.text = String(targetValue) myPuntuacionLBL.text = String(puntuacion) //Interpolacion de entero, es lo mismo que el casting a String myRondaLBL.text = "\(ronda)" } func starNewGame(){ puntuacion = 0 ronda = 0 startNewRound() } }
apache-2.0
e560ae59e0a25a3751ad51c48f8bb5ba
24.045455
145
0.565033
4.566298
false
false
false
false
Elm-Tree-Island/Shower
Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/UIKit/UIProgressViewSpec.swift
6
905
import ReactiveSwift import ReactiveCocoa import UIKit import Quick import Nimble import enum Result.NoError class UIProgressViewSpec: QuickSpec { override func spec() { var progressView: UIProgressView! weak var _progressView: UIProgressView? beforeEach { progressView = UIProgressView(frame: .zero) _progressView = progressView } afterEach { progressView = nil expect(_progressView).to(beNil()) } it("should accept changes from bindings to its progress value") { let firstChange: Float = 0.5 let secondChange: Float = 0.0 progressView.progress = 1.0 let (pipeSignal, observer) = Signal<Float, NoError>.pipe() progressView.reactive.progress <~ SignalProducer(pipeSignal) observer.send(value: firstChange) expect(progressView.progress) ≈ firstChange observer.send(value: secondChange) expect(progressView.progress) ≈ secondChange } } }
gpl-3.0
7a8c0c5b22eb323bdede58573997fbd5
22.102564
67
0.739179
4.004444
false
false
false
false
apple/swift
test/IRGen/multi_module_resilience.swift
13
4082
// RUN: rm -rf %t // RUN: mkdir %t // RUN: %target-swift-frontend -emit-module -enable-library-evolution \ // RUN: -emit-module-path=%t/resilient_struct.swiftmodule \ // RUN: -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -I %t \ // RUN: -emit-module-path=%t/OtherModule.swiftmodule \ // RUN: -module-name=OtherModule %S/Inputs/OtherModule.swift // RUN: %target-swift-frontend -module-name main -I %t -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize // rdar://39763787 import OtherModule // CHECK-LABEL: define {{(dllexport |protected )?}}swiftcc void @"$s4main7copyFoo3foo11OtherModule0C0VAF_tF" // CHECK: [[SRET:%.*]] = bitcast %swift.opaque* %0 to %T11OtherModule3FooV* // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s11OtherModule3FooVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: [[VWT:%.*]] = load i8**, // Allocate 'copy'. // CHECK: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK: [[SIZE_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8 // CHECK: [[SIZE:%.*]] = load [[INT]], [[INT]]* [[SIZE_ADDR]] // CHECK: [[ALLOCA:%.*]] = alloca i8, [[INT]] [[SIZE]], // CHECK: [[COPY:%.*]] = bitcast i8* [[ALLOCA]] to [[FOO:%T11OtherModule3FooV]]* // Perform 'initializeWithCopy' via the VWT instead of trying to inline it. // CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2 // CHECK: [[T1:%.*]] = load i8*, i8** [[T0]], // CHECK: [[COPYFN:%.*]] = bitcast i8* [[T1]] to %swift.opaque* (%swift.opaque*, %swift.opaque*, %swift.type*)* // CHECK: [[DEST:%.*]] = bitcast [[FOO]]* [[COPY]] to %swift.opaque* // CHECK: [[SRC:%.*]] = bitcast [[FOO]]* %1 to %swift.opaque* // CHECK: call %swift.opaque* [[COPYFN]](%swift.opaque* noalias [[DEST]], %swift.opaque* noalias [[SRC]], %swift.type* [[METADATA]]) // Perform 'initializeWithCopy' via the VWT. // CHECK: [[DEST:%.*]] = bitcast [[FOO]]* [[SRET]] to %swift.opaque* // CHECK: [[SRC:%.*]] = bitcast [[FOO]]* [[COPY]] to %swift.opaque* // CHECK: call %swift.opaque* [[COPYFN]](%swift.opaque* noalias [[DEST]], %swift.opaque* noalias [[SRC]], %swift.type* [[METADATA]]) public func copyFoo(foo: Foo) -> Foo { let copy = foo return copy } // CHECK-LABEL: define {{(dllexport |protected )?}}swiftcc void @"$s4main7copyBar3bar11OtherModule0C0VAF_tF" // CHECK: [[SRET:%.*]] = bitcast %swift.opaque* %0 to %T11OtherModule3BarV* // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s11OtherModule3BarVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: [[VWT:%.*]] = load i8**, // Allocate 'copy'. // CHECK: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK: [[SIZE_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8 // CHECK: [[SIZE:%.*]] = load [[INT]], [[INT]]* [[SIZE_ADDR]] // CHECK: [[ALLOCA:%.*]] = alloca i8, [[INT]] [[SIZE]], // CHECK: [[COPY:%.*]] = bitcast i8* [[ALLOCA]] to [[BAR:%T11OtherModule3BarV]]* // Perform 'initializeWithCopy' via the VWT instead of trying to inline it. // CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2 // CHECK: [[T1:%.*]] = load i8*, i8** [[T0]], // CHECK: [[COPYFN:%.*]] = bitcast i8* [[T1]] to %swift.opaque* (%swift.opaque*, %swift.opaque*, %swift.type*)* // CHECK: [[DEST:%.*]] = bitcast [[BAR]]* [[COPY]] to %swift.opaque* // CHECK: [[SRC:%.*]] = bitcast [[BAR]]* %1 to %swift.opaque* // CHECK: call %swift.opaque* [[COPYFN]](%swift.opaque* noalias [[DEST]], %swift.opaque* noalias [[SRC]], %swift.type* [[METADATA]]) // Perform 'initializeWithCopy' via the VWT. // CHECK: [[DEST:%.*]] = bitcast [[BAR]]* [[SRET]] to %swift.opaque* // CHECK: [[SRC:%.*]] = bitcast [[BAR]]* [[COPY]] to %swift.opaque* // CHECK: call %swift.opaque* [[COPYFN]](%swift.opaque* noalias [[DEST]], %swift.opaque* noalias [[SRC]], %swift.type* [[METADATA]]) public func copyBar(bar: Bar) -> Bar { let copy = bar return copy }
apache-2.0
578c99eeeb17c463e6dbced0e48493ef
57.314286
132
0.61367
3.194053
false
false
false
false
momo13014/RayWenderlichDemo
RayCoreConcepts_SB1/RayCoreConcepts_SB1/PlayersViewController.swift
1
3978
// // PlayersViewController.swift // RayCoreConcepts_SB1 // // Created by shendong on 16/8/31. // Copyright © 2016年 shendong. All rights reserved. // import UIKit class PlayersViewController: UITableViewController { var players:[Player] = playerData override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return players.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PlayerCell", forIndexPath: indexPath) as! PlayerCell // Configure the cell... let player = players[indexPath.row] as Player cell.player = player return cell } @IBAction func savePlayerDetail(segue: UIStoryboardSegue){ if let playerDetailViewController = segue.sourceViewController as? PlayerDetailsViewController { if let player = playerDetailViewController.plaer{ players.append(player) let indexPath = NSIndexPath(forRow: players.count - 1, inSection: 0) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } } @IBAction func cancelToPlayersViewController(segue: UIStoryboardSegue) { print("cancel") } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
459bbda6e2f2953a6a935e78b0f6011a
35.805556
157
0.682516
5.543933
false
false
false
false
klaaspieter/Numeric
numeric/time.swift
1
3040
import Foundation extension NSDateComponents { public var ago: NSDate { let units = [NSCalendarUnit.Year, .Month, .WeekOfYear, .Day, .Hour, .Minute, .Second] for unit in units { let value = self.valueForComponent(unit) if (value != Int.max) { self.setValue(-value, forComponent: unit) } } return self.advance(); } public var fromNow: NSDate { return self.advance() } private func advance() -> NSDate { var calendar : NSCalendar if let c = self.calendar { calendar = c } else { calendar = NSCalendar.currentCalendar() } let date = calendar.dateByAddingComponents(self, toDate: NSDate(), options: NSCalendarOptions()) return date! } } extension Int { public var second: NSDateComponents { return self.seconds } public var seconds: NSDateComponents { return toDateComponent(NSCalendarUnit.Second) } public var minute: NSDateComponents { return self.minutes } public var minutes: NSDateComponents { return toDateComponent(NSCalendarUnit.Minute) } public var hour: NSDateComponents { return self.hours } public var hours: NSDateComponents { return toDateComponent(NSCalendarUnit.Hour) } public var day: NSDateComponents { return self.days } public var days: NSDateComponents { return toDateComponent(NSCalendarUnit.Day) } public var week: NSDateComponents { return self.weeks } public var weeks: NSDateComponents { return toDateComponent(NSCalendarUnit.WeekOfYear) } public var month: NSDateComponents { return self.months } public var months: NSDateComponents { return toDateComponent(NSCalendarUnit.Month) } public var year: NSDateComponents { return self.years } public var years: NSDateComponents { return toDateComponent(NSCalendarUnit.Year) } private func toDateComponent(unit: NSCalendarUnit) -> NSDateComponents { let components = NSDateComponents() components.setValue(self, forComponent: unit) return components } } extension NSDate { public class func create(era era: Int = 1, year: Int = 2001, month: Int = 1, day: Int = 1, hour: Int = 0, minute: Int = 0, second: Int = 0, nanosecond: Int = 0) -> NSDate { return NSDateComponents.create(era: era, year: year, month: month, day: day, hour: hour, minute: minute, second: second, nanosecond: nanosecond).date! } } extension NSDateComponents { public class func create(era era: Int = 1, year: Int = 2001, month: Int = 1, day: Int = 1, hour: Int = 0, minute: Int = 0, second: Int = 0, nanosecond: Int = 0, calendar: NSCalendar? = nil) -> NSDateComponents { let components = NSDateComponents() components.era = era components.year = year components.month = month components.day = day components.hour = hour components.minute = minute components.second = second components.nanosecond = nanosecond components.calendar = calendar ?? NSCalendar.autoupdatingCurrentCalendar() return components } }
mit
466432b5d1d9798fa0532769aefccf74
29.09901
213
0.690461
4.477172
false
false
false
false
edx/edx-app-ios
Source/CourseSectionTableViewCell.swift
1
9298
// // CourseSectionTableViewCell.swift // edX // // Created by Ehmad Zubair Chughtai on 04/06/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit protocol CourseSectionTableViewCellDelegate : AnyObject { func sectionCellChoseDownload(cell : CourseSectionTableViewCell, videos : [OEXHelperVideoDownload], forBlock block : CourseBlock) func sectionCellChoseShowDownloads(cell : CourseSectionTableViewCell) func reloadCell(cell: UITableViewCell) } class CourseSectionTableViewCell: SwipeableCell, CourseBlockContainerCell { static let identifier = "CourseSectionTableViewCellIdentifier" fileprivate let content = CourseOutlineItemView() fileprivate let videosStream = BackedStream<[OEXHelperVideoDownload]>() fileprivate let downloadView = DownloadsAccessoryView() weak var delegate : CourseSectionTableViewCellDelegate? fileprivate var spinnerTimer = Timer() var courseID: String? var courseOutlineMode: CourseOutlineMode = .full var videos : OEXStream<[OEXHelperVideoDownload]> = OEXStream() { didSet { videosStream.backWithStream(videos) } } var courseQuerier: CourseOutlineQuerier? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(content) content.snp.makeConstraints { make in make.edges.equalTo(contentView) } for notification in [NSNotification.Name.OEXDownloadProgressChanged, NSNotification.Name.OEXDownloadEnded, NSNotification.Name.OEXVideoStateChanged] { NotificationCenter.default.oex_addObserver(observer: self, name: notification.rawValue) { (_, observer, _) -> Void in if let state = observer.downloadStateForDownloads(videos: observer.videosStream.value) { if observer.downloadView.state != state { observer.downloadView.state = state } } else { observer.content.hideTrailingView() } } } let tapGesture = UITapGestureRecognizer() tapGesture.addAction {[weak self]_ in if let owner = self, owner.downloadView.state == .Downloading { owner.delegate?.sectionCellChoseShowDownloads(cell: owner) } } downloadView.addGestureRecognizer(tapGesture) setAccessibilityIdentifiers() } private func setAccessibilityIdentifiers() { accessibilityIdentifier = "CourseSectionTableViewCell:view" content.accessibilityIdentifier = "CourseSectionTableViewCell:content-view" downloadView.accessibilityIdentifier = "CourseSectionTableViewCell:download-view" } func hideLeadingView() { content.hideLeadingView() } private func setupDownloadView() { downloadView.downloadAction = { [weak self] in if let owner = self, let block = owner.block, let videos = owner.videosStream.value { owner.delegate?.sectionCellChoseDownload(cell: owner, videos: videos, forBlock: block) } } videosStream.listen(self) { [weak self] downloads in if let downloads = downloads.value, let downloadView = self?.downloadView, let state = self?.downloadStateForDownloads(videos: downloads) { self?.downloadView.state = state self?.content.trailingView = downloadView self?.downloadView.itemCount = downloads.count } else { self?.content.hideTrailingView() } } } override func prepareForReuse() { super.prepareForReuse() videosStream.backWithStream(OEXStream(value:[])) reset() } func downloadStateForDownloads(videos : [OEXHelperVideoDownload]?) -> DownloadsAccessoryView.State? { guard let videos = videos, videos.count > 0 else { return nil } let allCompleted = videos.reduce(true) {(acc, video) in return acc && video.downloadState == .complete } if allCompleted { return .Done } let filteredVideos = filterVideos(videos: videos) let allDownloading = filteredVideos.reduce(true) {(acc, video) in return acc && video.downloadState == .partial } if allDownloading { return .Downloading } else { return .Available } } private func filterVideos(videos: [OEXHelperVideoDownload])-> [OEXHelperVideoDownload]{ var incompleteVideos:[OEXHelperVideoDownload] = [] for video in videos { // only return incomplete videos if video.downloadState != .complete { incompleteVideos.append(video) } } return incompleteVideos } public func deleteVideos(videos : [OEXHelperVideoDownload]) { OEXInterface.shared().deleteDownloadedVideos(videos) { _ in } OEXAnalytics.shared().trackSubsectionDeleteVideos(courseID: courseID ?? "", subsectionID: block?.blockID ?? "") } public func areAllVideosDownloaded(videos: [OEXHelperVideoDownload]) -> Bool { let videosState = downloadStateForDownloads(videos: videos) return (videosState == .Done) } var completionAction : (() -> ())? var block: CourseBlock? = nil { didSet { guard let block = block else { return } content.setTitleText(title: block.displayName, elipsis: false) content.isGraded = block.graded content.setDetailText(title: block.format ?? "", dueDate: block.dueDate, blockType: block.type) if courseOutlineMode == .video, let sectionChild = courseQuerier?.childrenOfBlockWithID(blockID: block.blockID, forMode: .video).value, sectionChild.block.type == .Section, let unitChild = courseQuerier?.childrenOfBlockWithID(blockID: sectionChild.block.blockID, forMode: .video).value, unitChild.children.allSatisfy ({ $0.isCompleted }) { completionAction?() showCompletionBackground() } else { handleBlockNormally(block) } setupDownloadView() } } private func handleBlockNormally(_ block: CourseBlock) { if block.isCompleted { let shouldShowIcon = courseOutlineMode == .full ? true : false showCompletionBackground(showIcon: shouldShowIcon) } else { showNeutralBackground() } } private func showCompletionBackground(showIcon: Bool = true) { content.backgroundColor = OEXStyles.shared().successXXLight() content.setContentIcon(icon: showIcon ? Icon.CheckCircle : nil, color: OEXStyles.shared().successBase()) content.setSeperatorColor(color: OEXStyles.shared().successXLight()) content.setCompletionAccessibility(completion: true) } private func showNeutralBackground() { content.backgroundColor = OEXStyles.shared().neutralWhite() content.setContentIcon(icon: nil, color: .clear) content.setSeperatorColor(color: OEXStyles.shared().neutralXLight()) content.setCompletionAccessibility() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CourseSectionTableViewCell: SwipeableCellDelegate { func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeActionButton]? { var downloadVideos:[OEXHelperVideoDownload] = [] videosStream.listen(self) { downloads in if let videos = downloads.value { downloadVideos = videos } } if(!areAllVideosDownloaded(videos: downloadVideos)) { return nil } let deleteButton = SwipeActionButton(title: nil, image: Icon.DeleteIcon.imageWithFontSize(size: 20)) {[weak self] action, indexPath in if let owner = self { //Showing a spinner while deleting video owner.deleteVideos(videos: downloadVideos) owner.downloadView.state = .Deleting owner.spinnerTimer = Timer.scheduledTimer(timeInterval: 0.4, target:owner, selector: #selector(owner.invalidateTimer), userInfo: nil, repeats: true) } } return [deleteButton] } @objc private func invalidateTimer(){ spinnerTimer.invalidate() downloadView.state = .Done delegate?.reloadCell(cell: self) } } extension CourseSectionTableViewCell { public func t_setup() -> OEXStream<[OEXHelperVideoDownload]> { return videos } public func t_areAllVideosDownloaded(videos: [OEXHelperVideoDownload]) -> Bool { return areAllVideosDownloaded(videos: videos) } }
apache-2.0
3d69be9ba4c463dec4bf40f1e60d8faf
37.263374
164
0.631426
5.267989
false
false
false
false
touchopia/Codementor-Swift-101
Week-1/Examples/Counter/Counter/ViewController.swift
1
1078
// // ViewController.swift // Counter // // Created by Phil Wright on 8/18/14. // Copyright (c) 2014 Touchopia, LLC. All rights reserved. // import UIKit class ViewController: UIViewController { var counter: Int = 0 @IBOutlet weak var countButtonClicked: UIButton! @IBOutlet weak var counterLabel: UILabel! @IBAction func resetButtonClicked(sender: AnyObject) { // Clear the counter label counterLabel.text = "0" // Set the counter variable back to zero counter = 0; } @IBAction func addButtonClicked(sender: AnyObject) { // increment variable count by one counter = counter + 1; // Display the variable in the counter label counterLabel.text = "\(counter)" } @IBAction func subtractButtonClicked(sender: AnyObject) { // decrement variable count by one counter = counter - 1; // Display the variable in the counter label counterLabel.text = "\(counter)" } }
mit
b0ea5a2e0bfad1c34a27977906b3122d
21.93617
61
0.595547
4.944954
false
false
false
false
Henawey/DevTest
BonialCodingTest/SectorHeaderTableViewCell.swift
1
1050
// // SectorHeaderTableViewCell.swift // BonialCodingTest // // Created by Ahmed Henawey on 10/23/16. // Copyright © 2016 Ahmed Henawey. All rights reserved. // import UIKit class SectorHeaderTableViewCell: UITableViewCell { private let imageDownloader = ImageDownloader() @IBOutlet private weak var name: UILabel! @IBOutlet private weak var logo: UIImageView! @IBOutlet private weak var numberOfItems: UILabel! func setName(name:String,imageURL:String,numberOfItems:Int){ self.name.text = name self.numberOfItems.text = "\(NSLocalizedString("Number Of Brochures", comment: "")): \(numberOfItems)" imageDownloader.fetchImageFromUrl(imageURL) { (image, error) in if error == nil{ dispatch_async(dispatch_get_main_queue(), { () -> Void in self.logo.image = image }) }else{ NSLog("Error \(error?.domain) happen during download sector logo from url \(imageURL)") } } } }
unlicense
bb45d005ed414be9442e01074cff1299
30.787879
110
0.625357
4.541126
false
false
false
false
sunshinejr/Moya-ModelMapper
Sources/RxMoya-ModelMapper/Single+ModelMapper.swift
1
3520
import Foundation import RxSwift import Moya import Mapper #if !COCOAPODS import Moya_ModelMapper #endif /// Extension for processing Responses into Mappable objects through ObjectMapper extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response { /// Maps data received from the signal into an object which implements the Mappable protocol. /// If the conversion fails, the signal errors. public func map<T: Mappable>(to type: T.Type, keyPath: String? = nil) -> Single<T> { return flatMap { response -> Single<T> in return Single.just(try response.map(to: type, keyPath: keyPath)) } } /// Maps data received from the signal into an array of objects which implement the Mappable protocol. /// If the conversion fails, the signal errors. public func map<T: Mappable>(to type: [T].Type, keyPath: String? = nil) -> Single<[T]> { return flatMap { response -> Single<[T]> in return Single.just(try response.map(to: type, keyPath: keyPath)) } } /// Maps data received from the signal into an array of objects which implement the Mappable protocol. /// If the conversion fails at any object, it's removed from the response array. /// If you want to throw an error on any failure, use `map()` instead. public func compactMap<T: Mappable>(to type: [T].Type, keyPath: String? = nil) -> Single<[T]> { return flatMap { response -> Single<[T]> in return Single.just(try response.compactMap(to: type, keyPath: keyPath)) } } /// Maps data received from the signal into an object which implements the Mappable protocol. /// If the conversion fails, the nil is returned instead of error signal. public func mapOptional<T: Mappable>(to type: T.Type, keyPath: String? = nil) -> Single<T?> { return flatMap { response -> Single<T?> in do { let object = try response.map(to: type, keyPath: keyPath) return Single.just(object) } catch { return Single.just(nil) } } } /// Maps data received from the signal into an array of objects which implement the Mappable protocol. /// If the conversion fails, the nil is returned instead of error signal. public func mapOptional<T: Mappable>(to type: [T].Type, keyPath: String? = nil) -> Single<[T]?> { return flatMap { response -> Single<[T]?> in do { let object = try response.map(to: type, keyPath: keyPath) return Single.just(object) } catch { return Single.just(nil) } } } /// Maps data received from the signal into an array of objects which implement the Mappable protocol. /// If the conversion fails at any object, it's removed from the response array. /// If the whole conversion fails, the nil is returned instead of error signal. /// Please see `map` and `compactMap` for other solutions to this problem. public func compactMapOptional<T: Mappable>(to type: [T].Type, keyPath: String? = nil) -> Single<[T]?> { return flatMap { response -> Single<[T]?> in do { let object = try response.compactMap(to: type, keyPath: keyPath) return Single.just(object) } catch { return Single.just(nil) } } } }
mit
74a1f23a3f9a8a04faa262e3dd79daa4
44.128205
108
0.614773
4.625493
false
false
false
false
aichamorro/fitness-tracker
Clients/Apple/FitnessTracker/FitnessTrackerTests/RemoveRecordTests.swift
1
6437
// // RemoveRecordTests.swift // FitnessTracker // // Created by Alberto Chamorro - Personal on 30/07/2017. // Copyright © 2017 OnsetBits. All rights reserved. // import Foundation import Quick import Nimble import RxSwift @testable import FitnessTracker class RemoveReadingInteractorTests: QuickSpec { // swiftlint:disable function_body_length override func spec() { describe("As user I would like to be able to remove readings") { var repository: CoreDataFitnessInfoRepository! var removeRecordInteractor: RemoveReadingInteractor! var disposeBag: DisposeBag! let record: IFitnessInfo = FitnessInfo(weight: 72.2, height: 171, bodyFatPercentage: 20.9, musclePercentage: 35.1, waterPercentage: 53.7) beforeEach { let managedObjectContext = SetUpInMemoryManagedObjectContext() let coreDataEngine = CoreDataEngineImpl(managedObjectContext: managedObjectContext) repository = CoreDataFitnessInfoRepository(coreDataEngine: coreDataEngine) removeRecordInteractor = RemoveReadingInteractorImpl(repository: repository) disposeBag = DisposeBag() } context("When there is a record in the repository") { var saved: IFitnessInfo! var didRemove = false var repositoryDidUpdate = false beforeEach { saved = try! repository.save(record) expect(repository.findAll().count).to(equal(1)) repository.rx_updated .subscribe(onNext: { repositoryDidUpdate = true }).addDisposableTo(disposeBag) waitUntil { done in removeRecordInteractor .rx_output .subscribe(onNext: { didRemove = ($0 != nil) done() }).addDisposableTo(disposeBag) removeRecordInteractor.rx_input.onNext(saved) } } it("Was removed") { expect(didRemove).to(beTrue()) expect(repository.findAll()).to(beEmpty()) } it("Notifies of changes in the repository") { expect(repositoryDidUpdate).toEventually(beTrue()) } } context("When there is no matching record in the repository") { var didThrow = true var didRemove = true beforeEach { let saved = try! repository.save(record) try! repository.remove(saved) waitUntil { done in removeRecordInteractor .rx_output .subscribe(onNext: { didThrow = false didRemove = ($0 != nil && $0! == saved) done() }, onError: { _ in didThrow = true done() }).addDisposableTo(disposeBag) removeRecordInteractor.rx_input.onNext(saved) } } it("Does not throw") { expect(didRemove).to(beFalse()) expect(didThrow).to(beFalse()) } } } } } class DummyRemoveReadingView: RemoveReadingView { let removeReadingSubject = PublishSubject<IFitnessInfo>() var saved: [IFitnessInfo] = [] var rx_removeReading: Observable<IFitnessInfo> { return removeReadingSubject.asObservable() } } class RemoveReadingPresenterSpec: QuickSpec { override func spec() { describe("The Presenter works in conjunction with the interactor") { var interactor: RemoveReadingInteractor! var disposeBag: DisposeBag! var view: RemoveReadingView! beforeEach { disposeBag = DisposeBag() let coreDataEngine = CoreDataEngineImpl(managedObjectContext: SetUpInMemoryManagedObjectContext()) let repository = CoreDataFitnessInfoRepository(coreDataEngine: coreDataEngine) try! repository.save(FitnessInfo(weight: 71.8, height: 171, bodyFatPercentage: 20.9, musclePercentage: 35.0, waterPercentage: 53.7)) try! repository.save(FitnessInfo(weight: 71.8, height: 171, bodyFatPercentage: 20.9, musclePercentage: 35.0, waterPercentage: 53.7)) try! repository.save(FitnessInfo(weight: 71.8, height: 171, bodyFatPercentage: 20.9, musclePercentage: 35.0, waterPercentage: 53.7)) try! repository.save(FitnessInfo(weight: 71.8, height: 171, bodyFatPercentage: 20.9, musclePercentage: 35.0, waterPercentage: 53.7)) try! repository.save(FitnessInfo(weight: 71.8, height: 171, bodyFatPercentage: 20.9, musclePercentage: 35.0, waterPercentage: 53.7)) let dummyView = DummyRemoveReadingView() dummyView.saved = repository.findAll() view = dummyView interactor = RemoveReadingInteractorImpl(repository: repository) RemoveReadingPresenterImpl(interactor, view, disposeBag) } afterEach { interactor = nil } context("Removing an item") { var removed: IFitnessInfo? beforeEach { let dummyView = view as! DummyRemoveReadingView waitUntil { done in interactor.rx_output.subscribe(onNext: { removed = $0 done() }, onError: { _ in fail() done() }).addDisposableTo(disposeBag) dummyView.removeReadingSubject.asObserver().onNext(dummyView.saved[0]) } } it("Can remove an item") { expect(removed).toNot(beNil()) } } } } }
gpl-3.0
ac99d301e8a25d1a9229a0540f33a19d
37.309524
149
0.525482
5.78777
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Widgets/PhotonActionSheet/PhotonActionSheet.swift
1
19845
// 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 Storage import Shared import UIKit extension PhotonActionSheet: Notifiable { func handleNotifications(_ notification: Notification) { switch notification.name { case .ProfileDidFinishSyncing, .ProfileDidStartSyncing: stopRotateSyncIcon() case UIAccessibility.reduceTransparencyStatusDidChangeNotification: reduceTransparencyChanged() default: break } } } // This file is main table view used for the action sheet class PhotonActionSheet: UIViewController { struct UX { static let maxWidth: CGFloat = 414 static let padding: CGFloat = 6 static let rowHeight: CGFloat = 44 static let cornerRadius: CGFloat = 10 static let siteImageViewSize: CGFloat = 52 static let iconSize = CGSize(width: 24, height: 24) static let closeButtonHeight: CGFloat = 56 static let tablePadding: CGFloat = 6 static let separatorRowHeight: CGFloat = 8 static let titleHeaderSectionHeight: CGFloat = 40 static let bigSpacing: CGFloat = 32 static let spacing: CGFloat = 16 static let smallSpacing: CGFloat = 8 } // MARK: - Variables private var tableView = UITableView(frame: .zero, style: .grouped) let viewModel: PhotonActionSheetViewModel private var constraints = [NSLayoutConstraint]() var notificationCenter: NotificationProtocol = NotificationCenter.default private lazy var closeButton: UIButton = .build { button in button.setTitle(.CloseButtonTitle, for: .normal) button.setTitleColor(UIConstants.SystemBlueColor, for: .normal) button.layer.cornerRadius = UX.cornerRadius button.titleLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontExtraLargeBold button.addTarget(self, action: #selector(self.dismiss), for: .touchUpInside) button.accessibilityIdentifier = "PhotonMenu.close" } var photonTransitionDelegate: UIViewControllerTransitioningDelegate? { didSet { transitioningDelegate = photonTransitionDelegate } } // MARK: - Init init(viewModel: PhotonActionSheetViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) title = viewModel.title modalPresentationStyle = viewModel.modalStyle closeButton.setTitle(viewModel.closeButtonTitle, for: .normal) tableView.estimatedRowHeight = UX.rowHeight } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { tableView.dataSource = nil tableView.delegate = nil notificationCenter.removeObserver(self) } // MARK: - View cycle override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) view.accessibilityIdentifier = "Action Sheet" tableView.backgroundColor = .clear tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil) // In a popover the popover provides the blur background // Not using a background color allows the view to style correctly with the popover arrow if self.popoverPresentationController == nil { let blurEffect = UIBlurEffect(style: UIColor.theme.actionMenu.iPhoneBackgroundBlurStyle) let blurEffectView = UIVisualEffectView(effect: blurEffect) tableView.backgroundView = blurEffectView } if viewModel.presentationStyle == .bottom { setupBottomStyle() } else if viewModel.presentationStyle == .popover { setupPopoverStyle() } else { setupCenteredStyle() } tableViewHeightConstraint = tableView.heightAnchor.constraint(equalToConstant: 0) tableViewHeightConstraint?.isActive = true NSLayoutConstraint.activate(constraints) setupNotifications(forObserver: self, observing: [.ProfileDidFinishSyncing, .ProfileDidStartSyncing, UIAccessibility.reduceTransparencyStatusDidChangeNotification]) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) tableView.removeObserver(self, forKeyPath: "contentSize") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) applyTheme() tableView.bounces = false tableView.delegate = self tableView.dataSource = self tableView.keyboardDismissMode = .onDrag tableView.register(PhotonActionSheetSeparator.self, forHeaderFooterViewReuseIdentifier: PhotonActionSheetSeparator.cellIdentifier) tableView.register(PhotonActionSheetContainerCell.self, forCellReuseIdentifier: PhotonActionSheetContainerCell.cellIdentifier) tableView.register(PhotonActionSheetSiteHeaderView.self, forHeaderFooterViewReuseIdentifier: PhotonActionSheetSiteHeaderView.cellIdentifier) tableView.register(PhotonActionSheetTitleHeaderView.self, forHeaderFooterViewReuseIdentifier: PhotonActionSheetTitleHeaderView.cellIdentifier) tableView.register(PhotonActionSheetLineSeparator.self, forHeaderFooterViewReuseIdentifier: PhotonActionSheetLineSeparator.cellIdentifier) tableView.isScrollEnabled = true tableView.showsVerticalScrollIndicator = false tableView.layer.cornerRadius = UX.cornerRadius // Don't show separators on ETP menu if viewModel.title != nil { tableView.separatorStyle = .none } tableView.separatorColor = UIColor.clear tableView.separatorInset = .zero tableView.cellLayoutMarginsFollowReadableWidth = false tableView.accessibilityIdentifier = "Context Menu" tableView.translatesAutoresizingMaskIntoConstraints = false if viewModel.isMainMenuInverted { tableView.transform = CGAffineTransform(scaleX: 1, y: -1) } tableView.reloadData() DispatchQueue.main.async { // Pick up the correct/final tableview.content size in order to set the height. // Without async dispatch, the content size is wrong. self.view.setNeedsLayout() self.view.layoutIfNeeded() } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() setTableViewHeight() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if traitCollection.verticalSizeClass != previousTraitCollection?.verticalSizeClass || traitCollection.horizontalSizeClass != previousTraitCollection?.horizontalSizeClass { updateViewConstraints() } } // MARK: - Setup private func setupBottomStyle() { self.view.addSubview(closeButton) let bottomConstraints = [ closeButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), closeButton.widthAnchor.constraint(equalToConstant: centeredAndBottomWidth), closeButton.heightAnchor.constraint(equalToConstant: UX.closeButtonHeight), closeButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -UX.padding), tableView.centerXAnchor.constraint(equalTo: view.centerXAnchor), tableView.bottomAnchor.constraint(equalTo: closeButton.topAnchor, constant: -UX.padding), tableView.widthAnchor.constraint(equalToConstant: centeredAndBottomWidth), ] constraints.append(contentsOf: bottomConstraints) } private func setupPopoverStyle() { let width: CGFloat = viewModel.popOverWidthForTraitCollection(trait: view.traitCollection) var tableViewConstraints = [ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), tableView.widthAnchor.constraint(greaterThanOrEqualToConstant: width), ] // Can't set this on iPad (not in multitasking) since it causes the menu to take all the width of the screen. if PhotonActionSheetViewModel.isSmallSizeForTraitCollection(trait: view.traitCollection) { tableViewConstraints.append( tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ) } constraints.append(contentsOf: tableViewConstraints) } private func setupCenteredStyle() { let tableViewConstraints = [ tableView.centerXAnchor.constraint(equalTo: view.centerXAnchor), tableView.centerYAnchor.constraint(equalTo: view.centerYAnchor), tableView.widthAnchor.constraint(equalToConstant: centeredAndBottomWidth), ] constraints.append(contentsOf: tableViewConstraints) applyBackgroundBlur() viewModel.tintColor = UIConstants.SystemBlueColor } // The width used for the .centered and .bottom style private var centeredAndBottomWidth: CGFloat { let minimumWidth = min(view.frame.size.width, UX.maxWidth) return minimumWidth - (UX.padding * 2) } // MARK: - Theme @objc func reduceTransparencyChanged() { // If the user toggles transparency settings, re-apply the theme to also toggle the blur effect. applyTheme() } private func applyBackgroundBlur() { guard let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate, let screenshot = sceneDelegate.window?.screenshot() else { return } let blurredImage = screenshot.applyBlur(withRadius: 5, blurType: BOXFILTER, tintColor: UIColor.black.withAlphaComponent(0.2), saturationDeltaFactor: 1.8, maskImage: nil) let imageView = UIImageView(image: blurredImage) view.insertSubview(imageView, belowSubview: tableView) } // MARK: - Actions @objc private func stopRotateSyncIcon() { ensureMainThread { self.tableView.reloadData() } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { if viewModel.presentationStyle == .popover && !wasHeightOverriden { if #available(iOS 15.4, *) { var size = tableView.contentSize size.height = tableView.contentSize.height - UX.spacing - UX.tablePadding preferredContentSize = size } else { preferredContentSize = tableView.contentSize } } } @objc private func dismiss(_ gestureRecognizer: UIGestureRecognizer?) { dismissVC() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) // Need to handle click outside view for non-popover sheet styles guard let touch = touches.first else { return } if !tableView.frame.contains(touch.location(in: view)) { dismissVC() } } // MARK: - TableView height private var tableViewHeightConstraint: NSLayoutConstraint? private func setTableViewHeight() { if viewModel.isMainMenu { setMainMenuTableViewHeight() } else { setDefaultStyleTableViewHeight() } } // Needed to override the preferredContentSize, so key value observer doesn't get called private var wasHeightOverriden = false /// Main menu table view height is calculated so if there's not enough space for the menu to be shown completely, /// we make sure that the last cell shown is half shown. This indicates to the user that the menu can be scrolled. private func setMainMenuTableViewHeight() { let visibleCellsHeight = getViewsHeightSum(views: tableView.visibleCells) let headerCellsHeight = getViewsHeightSum(views: tableView.visibleHeaders) let totalCellsHeight = visibleCellsHeight + headerCellsHeight let availableHeight = viewModel.availableMainMenuHeight let needsHeightAdjustment = availableHeight - totalCellsHeight < 0 if needsHeightAdjustment && totalCellsHeight != 0 && !wasHeightOverriden { let newHeight: CGFloat if viewModel.isAtTopMainMenu { let halfCellHeight = (tableView.visibleCells.last?.frame.height ?? 0) / 2 newHeight = totalCellsHeight - halfCellHeight } else { let halfCellHeight = (tableView.visibleCells.first?.frame.height ?? 0) / 2 let aCellAndAHalfHeight = halfCellHeight * 3 newHeight = totalCellsHeight - aCellAndAHalfHeight } wasHeightOverriden = true tableViewHeightConstraint?.constant = newHeight tableViewHeightConstraint?.priority = .required preferredContentSize = view.systemLayoutSizeFitting( UIView.layoutFittingCompressedSize ) view.setNeedsLayout() view.layoutIfNeeded() } } private func setDefaultStyleTableViewHeight() { let frameHeight = view.safeAreaLayoutGuide.layoutFrame.size.height let buttonHeight = viewModel.presentationStyle == .bottom ? UX.closeButtonHeight : 0 let maxHeight = frameHeight - buttonHeight // The height of the menu should be no more than 90 percent of the screen let height = min(tableView.contentSize.height, maxHeight * 0.90) tableViewHeightConstraint?.constant = height } private func getViewsHeightSum(views: [UIView]) -> CGFloat { return views.map { $0.frame.height }.reduce(0, +) } } // MARK: - UITableViewDataSource, UITableViewDelegate extension PhotonActionSheet: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let section = viewModel.actions[safe: indexPath.section], let action = section[safe: indexPath.row], let custom = action.items[0].customHeight else { return UITableView.automaticDimension } // Nested tableview rows get additional height return custom(action.items[0]) } func numberOfSections(in tableView: UITableView) -> Int { return viewModel.actions.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.actions[section].count } func tableView(_ tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: IndexPath) -> Bool { return false } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell( withIdentifier: PhotonActionSheetContainerCell.cellIdentifier, for: indexPath) as? PhotonActionSheetContainerCell else { return UITableViewCell() } let actions = viewModel.actions[indexPath.section][indexPath.row] cell.configure(actions: actions, viewModel: viewModel) cell.delegate = self if viewModel.isMainMenuInverted { let rowIsLastInSection = indexPath.row == tableView.numberOfRows(inSection: indexPath.section) - 1 cell.hideBottomBorder(isHidden: rowIsLastInSection) } else { let isLastRow = indexPath.row == tableView.numberOfRows(inSection: indexPath.section) - 1 cell.hideBottomBorder(isHidden: isLastRow) } return cell } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0 } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return viewModel.getHeaderHeightForSection(section: section) } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return viewModel.getViewHeader(tableView: tableView, section: section) } } // MARK: - PhotonActionSheetViewDelegate extension PhotonActionSheet: PhotonActionSheetContainerCellDelegate { func didClick(item: SingleActionViewModel?) { dismissVC() } func layoutChanged(item: SingleActionViewModel) { tableView.reloadData() } } // MARK: - Visible Headers extension UITableView { var visibleHeaders: [UITableViewHeaderFooterView] { var visibleHeaders = [UITableViewHeaderFooterView]() for sectionIndex in indexesOfVisibleHeaderSections { guard let sectionHeader = headerView(forSection: sectionIndex) else { continue } visibleHeaders.append(sectionHeader) } return visibleHeaders } private var indexesOfVisibleHeaderSections: [Int] { var visibleSectionIndexes = [Int]() (0..<numberOfSections).forEach { index in let headerRect = rect(forSection: index) // The "visible part" of the tableView is based on the content offset and the tableView's size. let visiblePartOfTableView = CGRect(x: contentOffset.x, y: contentOffset.y, width: bounds.size.width, height: bounds.size.height) if visiblePartOfTableView.intersects(headerRect) { visibleSectionIndexes.append(index) } } return visibleSectionIndexes } } // MARK: - NotificationThemeable extension PhotonActionSheet: NotificationThemeable { func applyTheme() { if viewModel.presentationStyle == .popover { view.backgroundColor = UIColor.theme.browser.background.withAlphaComponent(0.7) } else { tableView.backgroundView?.backgroundColor = UIColor.theme.actionMenu.iPhoneBackground } // Apply or remove the background blur effect if let visualEffectView = tableView.backgroundView as? UIVisualEffectView { if UIAccessibility.isReduceTransparencyEnabled { // Remove the visual effect and the background alpha visualEffectView.effect = nil tableView.backgroundView?.backgroundColor = UIColor.theme.actionMenu.iPhoneBackground.withAlphaComponent(1.0) } else { visualEffectView.effect = UIBlurEffect(style: UIColor.theme.actionMenu.iPhoneBackgroundBlurStyle) } } viewModel.tintColor = UIColor.theme.actionMenu.foreground closeButton.backgroundColor = UIColor.theme.actionMenu.closeButtonBackground tableView.headerView(forSection: 0)?.backgroundColor = UIColor.Photon.DarkGrey05 } }
mpl-2.0
73df6d1f845392c0f10dc93bef747d22
39.5
125
0.666112
5.767219
false
false
false
false
avito-tech/Paparazzo
Paparazzo/Core/VIPER/MediaPicker/View/ThumbnailsView/CameraThumbnailCell.swift
1
3293
import ImageSource import UIKit final class CameraThumbnailCell: UICollectionViewCell { private let button = UIButton() private var cameraOutputView: CameraOutputView? var selectedBorderColor: UIColor? = .blue { didSet { adjustBorderColor() } } func setCameraIcon(_ icon: UIImage?) { button.setImage(icon, for: .normal) } func setCameraIconTransform(_ transform: CGAffineTransform) { button.transform = transform } func setOutputParameters(_ parameters: CameraOutputParameters) { let newCameraOutputView = CameraOutputView( captureSession: parameters.captureSession, outputOrientation: parameters.orientation ) newCameraOutputView.layer.cornerRadius = 6 if UIDevice.systemVersionLessThan(version: "9.0"), let currentCameraOutputView = self.cameraOutputView { // AI-3326: костыль для iOS 8. // Удаляем предыдущую вьюху, как только будет нарисован первый фрейм новой вьюхи, иначе будет мелькание. newCameraOutputView.onFrameDraw = { [weak newCameraOutputView] in newCameraOutputView?.onFrameDraw = nil DispatchQueue.main.async { currentCameraOutputView.removeFromSuperviewAfterFadingOut(withDuration: 0.25) } } } else { cameraOutputView?.removeFromSuperview() } insertSubview(newCameraOutputView, belowSubview: button) self.cameraOutputView = newCameraOutputView // AI-3610: костыль для iPhone 4, чтобы не было белой рамки вокруг ячейки. // Если ставить clearColor, скругление углов теряется на iOS 9. self.backgroundColor = UIColor.white.withAlphaComponent(0.1) } func setOutputOrientation(_ orientation: ExifOrientation) { cameraOutputView?.orientation = orientation } // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .black layer.cornerRadius = 6 layer.masksToBounds = true button.tintColor = .white button.isUserInteractionEnabled = false adjustBorderColor() addSubview(button) setAccessibilityId(.cameraThumbnailCell) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UICollectionViewCell override var isSelected: Bool { didSet { layer.borderWidth = isSelected ? 4 : 0 } } override func layoutSubviews() { super.layoutSubviews() let insets = UIEdgeInsets(top: 0.5, left: 0.5, bottom: 0.5, right: 0.5) cameraOutputView?.frame = bounds.inset(by: insets) button.frame = bounds } // MARK: - Private private func adjustBorderColor() { layer.borderColor = selectedBorderColor?.cgColor } }
mit
08cd0267e1f2ddb85cdbfa308c7cc3ed
28.990385
116
0.60949
4.813272
false
false
false
false
PrinceChen/DouYu
DouYu/DouYu/Classes/Main/View/PageTitleView.swift
1
5400
// // PageTitleView.swift // DouYu // // Created by prince.chen on 2017/3/1. // Copyright © 2017年 prince.chen. All rights reserved. // import UIKit protocol PageTitleViewDelegate: class { func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) } // MARK: - Constants fileprivate let kScrollLineH: CGFloat = 2 fileprivate let kNormalColor: (CGFloat, CGFloat, CGFloat) = (85, 85, 85) fileprivate let kSelectedColor: (CGFloat, CGFloat, CGFloat) = (255, 128, 0) class PageTitleView: UIView { fileprivate var currentIndex: Int = 0 fileprivate var titles: [String] weak var delegate: PageTitleViewDelegate? fileprivate lazy var titlesLabels: [UILabel] = [UILabel]() fileprivate lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() fileprivate lazy var scrollLine: UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() init(frame: CGRect, titles: [String]) { self.titles = titles super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { fileprivate func setupUI() { addSubview(scrollView) scrollView.frame = bounds setupTitleLabels() setupBottomMenuAndScrollLine() } fileprivate func setupTitleLabels() { let labelW: CGFloat = frame.width / CGFloat(titles.count) let labelH: CGFloat = frame.height - kScrollLineH let labelY: CGFloat = 0 for (index, title) in titles.enumerated() { let label = UILabel() label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center let labelX: CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) scrollView.addSubview(label) titlesLabels.append(label) label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } fileprivate func setupBottomMenuAndScrollLine() { let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH: CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) guard let firstLabel = titlesLabels.first else {return} firstLabel.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2) scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x , y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH) } } extension PageTitleView { @objc fileprivate func titleLabelClick(tapGes: UITapGestureRecognizer) { // print(#function) guard let currentLabel = tapGes.view as? UILabel else {return} if currentLabel.tag == currentIndex{ return } let oldLabel = titlesLabels[currentIndex] currentLabel.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) currentIndex = currentLabel.tag let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.15) { self.scrollLine.frame.origin.x = scrollLineX } delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } extension PageTitleView { func setTitleWithProgress(progress: CGFloat, sourceIndex: Int, targetIndex: Int) { let sourceLabel = titlesLabels[sourceIndex] let targetLabel = titlesLabels[targetIndex] let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 颜色渐变 let colorDelta = (kSelectedColor.0 - kNormalColor.0, kSelectedColor.1 - kNormalColor.1, kSelectedColor.2 - kNormalColor.2) sourceLabel.textColor = UIColor(r: kSelectedColor.0 - colorDelta.0 * progress, g: kSelectedColor.1 - colorDelta.1 * progress, b: kSelectedColor.2 - colorDelta.2 * progress) targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) currentIndex = targetIndex } }
mit
34d41393e6161e9e618f0c48727b204b
28.60989
180
0.626832
4.975993
false
false
false
false
Wu-Dong-Hui/EnumerateAssetByPhotos-
PhotoFrameworkDemo/PhotoCollectionController.swift
1
4865
// // PhotoCollectionController.swift // PhotoFrameworkDemo // // Created by Roy on 15/9/25. // Copyright © 2015年 Pixshow. All rights reserved. // import UIKit import Photos class PhotoCollectionController: UIViewController , UICollectionViewDataSource , UICollectionViewDelegate { var assetMediaType: PHAssetMediaType = .Image var collectionView: UICollectionView! var models = [Model]() convenience init(mediaType: PHAssetMediaType) { self.init() self.assetMediaType = mediaType } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = UIColor.whiteColor() let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.itemSize = CGSize(width: view.bounds.width / 2, height: view.bounds.width / 2) collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) view.addSubview(collectionView) collectionView.registerClass(Cell.self, forCellWithReuseIdentifier: NSStringFromClass(Cell)) collectionView.delegate = self collectionView.dataSource = self self.enumPhotos() } func enumPhotos() { // let smartResult = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.SmartAlbum, subtype: PHAssetCollectionSubtype.SmartAlbumUserLibrary, options: nil) // NSLog("smart result : \(smartResult)") // smartResult.enumerateObjectsUsingBlock { (assetCollection, index, finished) -> Void in // NSLog("assetCollection : \(assetCollection), index : \(index), finished : \(finished)") // } // // let topLevelResult = PHCollectionList.fetchTopLevelUserCollectionsWithOptions(nil) // NSLog("top level result: \(topLevelResult)") // topLevelResult.enumerateObjectsUsingBlock { (assetCollection, index, finished) -> Void in // NSLog("assetCollection : \(assetCollection), index : \(index), finished : \(finished)") // } let imageAssets = PHAsset.fetchAssetsWithMediaType(self.assetMediaType, options: nil) imageAssets.enumerateObjectsUsingBlock { [weak self] (assetCollection, index, finished) -> Void in // NSLog("assetCollection : \(assetCollection), index : \(index), finished : \(finished)") let model = Model() model.asset = assetCollection as! PHAsset self?.models.append(model) if index == imageAssets.count - 1 { self?.collectionView.reloadData() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let model = models[indexPath.row] let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NSStringFromClass(Cell), forIndexPath: indexPath) as! Cell cell.setupWithModel(model) return cell } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return models.count } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } //********** class Model: NSObject { var asset: PHAsset! } //*********** class Cell: UICollectionViewCell { var model: Model! var imageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) imageView = UIImageView(frame: self.bounds) imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true contentView.addSubview(imageView) } func setupWithModel(model: Model) { self.model = model let imageRequestOption = PHImageRequestOptions() imageRequestOption.resizeMode = .Exact imageRequestOption.deliveryMode = .HighQualityFormat imageRequestOption.normalizedCropRect = CGRect(origin: CGPointZero, size: self.bounds.size) PHImageManager.defaultManager().requestImageForAsset(model.asset, targetSize: self.bounds.size, contentMode: PHImageContentMode.AspectFill, options: imageRequestOption) { [weak self] (image, dict) -> Void in self?.imageView.image = image } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
f32dafaca354cd8acb99b20075c56479
40.913793
215
0.681407
5.30786
false
false
false
false
PigDogBay/Food-Hygiene-Ratings
Food Hygiene Ratings/ListViewController.swift
1
3721
// // ListViewController.swift // Food Hygiene Ratings // // Created by Mark Bailey on 01/03/2017. // Copyright © 2017 MPD Bailey Technology. All rights reserved. // import UIKit class ListViewController: UITableViewController { var id = 0 var listItems : [String]! var selectedIndex : Int? var selectedItem : String? { didSet { if let item = selectedItem { selectedIndex = listItems.index(of: item) } } } let cellReuseId = "cellListItem" override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return listItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseId, for: indexPath) cell.textLabel?.text = listItems[indexPath.row] cell.accessoryType = .none if indexPath.row == selectedIndex { cell.accessoryType = .checkmark } return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cell = sender as? UITableViewCell { let indexPath = self.tableView.indexPath(for: cell) if let index = indexPath?.row{ self.selectedIndex = index self.selectedItem = listItems[index] } } } }
apache-2.0
451ec4dd75d75b9539c094a89d430a40
31.920354
136
0.648118
5.254237
false
false
false
false
volodg/iAsync.network
Sources/Extensions/NSMutableURLRequest+CreateRequestWithURLParams.swift
1
1263
// // NSMutableURLRequest+CreateRequestWithURLParams.swift // iAsync_network // // Created by Vladimir Gorbenko on 24.09.14. // Copyright © 2014 EmbeddedSources. All rights reserved. // import Foundation import let iAsync_utils.iAsync_utils_logger import enum ReactiveKit.Result //todo NS extension NSMutableURLRequest { convenience init(params: URLConnectionParams) { let inputStream: InputStream? if let factory = params.httpBodyStreamBuilder { let streamResult = factory() if let error = streamResult.error { iAsync_utils_logger.logError("create stream error: \(error)", context: #function) } inputStream = streamResult.value } else { inputStream = nil } assert(!((params.httpBody != nil) && (inputStream != nil))) self.init( url : params.url, cachePolicy : .reloadIgnoringLocalCacheData, timeoutInterval: 60.0) self.httpBodyStream = inputStream if params.httpBody != nil { self.httpBody = params.httpBody } self.allHTTPHeaderFields = params.headers self.httpMethod = params.httpMethod.rawValue } }
mit
8f5327df3218dd453a03951d32a7e232
24.755102
97
0.616482
4.94902
false
false
false
false
kstaring/swift
stdlib/public/core/Zip.swift
4
5352
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Creates a sequence of pairs built out of two underlying sequences. /// /// In the `Zip2Sequence` instance returned by this function, the elements of /// the *i*th pair are the *i*th elements of each underlying sequence. The /// following example uses the `zip(_:_:)` function to iterate over an array /// of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// If the two sequences passed to `zip(_:_:)` are different lengths, the /// resulting sequence is the same length as the shorter sequence. In this /// example, the resulting array is the same length as `words`: /// /// let naturalNumbers = 1...Int.max /// let zipped = Array(zip(words, naturalNumbers)) /// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)] /// /// - Parameters: /// - sequence1: The first sequence or collection to zip. /// - sequence2: The second sequence or collection to zip. /// - Returns: A sequence of tuple pairs, where the elements of each pair are /// corresponding elements of `sequence1` and `sequence2`. public func zip<Sequence1 : Sequence, Sequence2 : Sequence>( _ sequence1: Sequence1, _ sequence2: Sequence2 ) -> Zip2Sequence<Sequence1, Sequence2> { return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2) } /// An iterator for `Zip2Sequence`. public struct Zip2Iterator< Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol > : IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = (Iterator1.Element, Iterator2.Element) /// Creates an instance around a pair of underlying iterators. internal init(_ iterator1: Iterator1, _ iterator2: Iterator2) { (_baseStream1, _baseStream2) = (iterator1, iterator2) } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. public mutating func next() -> Element? { // The next() function needs to track if it has reached the end. If we // didn't, and the first sequence is longer than the second, then when we // have already exhausted the second sequence, on every subsequent call to // next() we would consume and discard one additional element from the // first sequence, even though next() had already returned nil. if _reachedEnd { return nil } guard let element1 = _baseStream1.next(), let element2 = _baseStream2.next() else { _reachedEnd = true return nil } return (element1, element2) } internal var _baseStream1: Iterator1 internal var _baseStream2: Iterator2 internal var _reachedEnd: Bool = false } /// A sequence of pairs built out of two underlying sequences. /// /// In a `Zip2Sequence` instance, the elements of the *i*th pair are the *i*th /// elements of each underlying sequence. To create a `Zip2Sequence` instance, /// use the `zip(_:_:)` function. /// /// The following example uses the `zip(_:_:)` function to iterate over an /// array of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// - SeeAlso: `zip(_:_:)` public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence> : Sequence { public typealias Stream1 = Sequence1.Iterator public typealias Stream2 = Sequence2.Iterator /// A type whose instances can produce the elements of this /// sequence, in order. public typealias Iterator = Zip2Iterator<Stream1, Stream2> @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator /// Creates an instance that makes pairs of elements from `sequence1` and /// `sequence2`. public // @testable init(_sequence1 sequence1: Sequence1, _sequence2 sequence2: Sequence2) { (_sequence1, _sequence2) = (sequence1, sequence2) } /// Returns an iterator over the elements of this sequence. public func makeIterator() -> Iterator { return Iterator( _sequence1.makeIterator(), _sequence2.makeIterator()) } internal let _sequence1: Sequence1 internal let _sequence2: Sequence2 } extension Zip2Sequence { @available(*, unavailable, message: "use zip(_:_:) free function instead") public init(_ sequence1: Sequence1, _ sequence2: Sequence2) { Builtin.unreachable() } }
apache-2.0
3c447070140ea734672404a2e5cdd5e6
35.162162
80
0.644432
4.057619
false
false
false
false
AdamZikmund/strv
strv/strv/Classes/Controller/SettingsTableViewController.swift
1
2466
// // SettingsTableViewController.swift // strv // // Created by Adam Zikmund on 13.05.15. // Copyright (c) 2015 Adam Zikmund. All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController { private let settings = StorageHandler.sharedInstance.getSettings() @IBOutlet var lenghtDetailLabel: UILabel! @IBOutlet var temperatureDetailLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.title = "Settings" switch settings.getUnitOfLenght() { case .Meters: lenghtDetailLabel.text = "Meters" case .Miles: lenghtDetailLabel.text = "Miles" } switch settings.getUnitOfTemperature() { case .Celsius: temperatureDetailLabel.text = "Celsius" case .Fahrenheit: temperatureDetailLabel.text = "Fahrenheit" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let headerView = view as? UITableViewHeaderFooterView { headerView.textLabel.textColor = UIColor.customLightBlue() headerView.textLabel.font = UIFont(name: "ProximaNova-Semibold", size: 14.0) } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) if indexPath.row == 0 { switch settings.getUnitOfLenght() { case .Meters: settings.setUnitOfLenght(.Miles) lenghtDetailLabel.text = "Miles" case .Miles: settings.setUnitOfLenght(.Meters) lenghtDetailLabel.text = "Meters" } } else if indexPath.row == 1 { switch settings.getUnitOfTemperature() { case .Celsius: settings.setUnitOfTemperature(.Fahrenheit) temperatureDetailLabel.text = "Fahrenheit" case .Fahrenheit: settings.setUnitOfTemperature(.Celsius) temperatureDetailLabel.text = "Celsius" } } tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
1011468a29983b676f644f8404cf2d31
31.88
114
0.613544
5.202532
false
false
false
false
smartdevicelink/sdl_ios
Example Apps/Example Swift/ConnectionIAPTableViewController.swift
1
2270
// // ConnectionIAPTableViewController.swift // SmartDeviceLink-ExampleSwift // // Copyright © 2017 smartdevicelink. All rights reserved. // import UIKit class ConnectionIAPTableViewController: UITableViewController { @IBOutlet weak var connectTableViewCell: UITableViewCell! @IBOutlet weak var table: UITableView! @IBOutlet weak var connectButton: UIButton! var proxyState = ProxyState.stopped override func viewDidLoad() { super.viewDidLoad() ProxyManager.sharedManager.delegate = self title = "iAP" table.keyboardDismissMode = .onDrag table.isScrollEnabled = false configureConnectButton() } private func configureConnectButton() { self.connectTableViewCell.backgroundColor = UIColor.systemRed self.connectButton.setTitle("Connect", for: .normal) self.connectButton.setTitleColor(.white, for: .normal) } } extension ConnectionIAPTableViewController: ProxyManagerDelegate { func didChangeProxyState(_ newState: ProxyState) { proxyState = newState var newColor: UIColor? = nil var newTitle: String? = nil switch newState { case .stopped: newColor = .systemRed newTitle = "Connect" case .searching: newColor = .systemOrange newTitle = "Stop Searching" case .connected: newColor = .systemGreen newTitle = "Disconnect" } if (newColor != nil) || (newTitle != nil) { DispatchQueue.main.async(execute: {[weak self]() -> Void in self?.connectTableViewCell.backgroundColor = newColor self?.connectButton.setTitle(newTitle, for: .normal) self?.connectButton.setTitleColor(.white, for: .normal) }) } } } // MARK: - IBActions extension ConnectionIAPTableViewController { @IBAction private func connectButtonWasPressed(_ sender: UIButton) { switch proxyState { case .stopped: ProxyManager.sharedManager.start(with: .iap) case .searching: ProxyManager.sharedManager.stopConnection() case .connected: ProxyManager.sharedManager.stopConnection() } } }
bsd-3-clause
284b9e4d5b0764866eedd90bec08cc80
30.513889
72
0.643015
5.042222
false
false
false
false
minikin/Algorithmics
Pods/Charts/Charts/Classes/Components/ChartAxisBase.swift
5
2982
// // ChartAxisBase.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 CoreGraphics public class ChartAxisBase: ChartComponentBase { public var labelFont = NSUIFont.systemFontOfSize(10.0) public var labelTextColor = NSUIColor.blackColor() public var axisLineColor = NSUIColor.grayColor() public var axisLineWidth = CGFloat(0.5) public var axisLineDashPhase = CGFloat(0.0) public var axisLineDashLengths: [CGFloat]! public var gridColor = NSUIColor.grayColor().colorWithAlphaComponent(0.9) public var gridLineWidth = CGFloat(0.5) public var gridLineDashPhase = CGFloat(0.0) public var gridLineDashLengths: [CGFloat]! public var gridLineCap = CGLineCap.Butt public var drawGridLinesEnabled = true public var drawAxisLineEnabled = true /// flag that indicates of the labels of this axis should be drawn or not public var drawLabelsEnabled = true /// array of limitlines that can be set for the axis private var _limitLines = [ChartLimitLine]() /// Are the LimitLines drawn behind the data or in front of the data? /// /// **default**: false public var drawLimitLinesBehindDataEnabled = false /// the flag can be used to turn off the antialias for grid lines public var gridAntialiasEnabled = true public override init() { super.init() } public func getLongestLabel() -> String { fatalError("getLongestLabel() cannot be called on ChartAxisBase") } public var isDrawGridLinesEnabled: Bool { return drawGridLinesEnabled; } public var isDrawAxisLineEnabled: Bool { return drawAxisLineEnabled; } public var isDrawLabelsEnabled: Bool { return drawLabelsEnabled; } /// Are the LimitLines drawn behind the data or in front of the data? /// /// **default**: false public var isDrawLimitLinesBehindDataEnabled: Bool { return drawLimitLinesBehindDataEnabled; } /// Adds a new ChartLimitLine to this axis. public func addLimitLine(line: ChartLimitLine) { _limitLines.append(line) } /// Removes the specified ChartLimitLine from the axis. public func removeLimitLine(line: ChartLimitLine) { for (var i = 0; i < _limitLines.count; i++) { if (_limitLines[i] === line) { _limitLines.removeAtIndex(i) return } } } /// Removes all LimitLines from the axis. public func removeAllLimitLines() { _limitLines.removeAll(keepCapacity: false) } /// - returns: the LimitLines of this axis. public var limitLines : [ChartLimitLine] { return _limitLines } }
mit
a43aa5975d9a25533e8c956277558ad5
28.245098
98
0.657612
4.920792
false
false
false
false
huangboju/Moots
UICollectionViewLayout/MagazineLayout-master/MagazineLayout/LayoutCore/ModelState.swift
1
40537
// Created by bryankeller on 2/25/18. // Copyright © 2018 Airbnb, 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 CoreGraphics import Foundation /// Manages the state of section and element models. final class ModelState { // MARK: Lifecycle init(currentVisibleBoundsProvider: @escaping () -> CGRect) { self.currentVisibleBoundsProvider = currentVisibleBoundsProvider } // MARK: Internal enum BatchUpdateStage { case beforeUpdates case afterUpdates } private(set) var isPerformingBatchUpdates: Bool = false private(set) var sectionIndicesToInsert = Set<Int>() private(set) var sectionIndicesToDelete = Set<Int>() private(set) var itemIndexPathsToInsert = Set<IndexPath>() private(set) var itemIndexPathsToDelete = Set<IndexPath>() func numberOfSections(_ batchUpdateStage: BatchUpdateStage) -> Int { return sectionModels(batchUpdateStage).count } func numberOfItems( inSectionAtIndex sectionIndex: Int, _ batchUpdateStage: BatchUpdateStage) -> Int { let sectionModels = self.sectionModels(batchUpdateStage) return sectionModels[sectionIndex].numberOfItems } func idForItemModel(at indexPath: IndexPath, _ batchUpdateStage: BatchUpdateStage) -> String? { let sectionModels = self.sectionModels(batchUpdateStage) guard indexPath.section < sectionModels.count, indexPath.item < sectionModels[indexPath.section].numberOfItems else { // This occurs when getting layout attributes for initial / final animations return nil } return sectionModels[indexPath.section].idForItemModel(atIndex: indexPath.item) } func indexPathForItemModel( withID id: String, _ batchUpdateStage: BatchUpdateStage) -> IndexPath? { let sectionModels = self.sectionModels(batchUpdateStage) for sectionIndex in 0..<sectionModels.count { guard let index = sectionModels[sectionIndex].indexForItemModel(withID: id) else { continue } return IndexPath(item: index, section: sectionIndex) } return nil } func idForSectionModel(atIndex index: Int, _ batchUpdateStage: BatchUpdateStage) -> String? { let sectionModels = self.sectionModels(batchUpdateStage) guard index < sectionModels.count else { // This occurs when getting layout attributes for initial / final animations return nil } return sectionModels[index].id } func indexForSectionModel(withID id: String, _ batchUpdateStage: BatchUpdateStage) -> Int? { let sectionModels = self.sectionModels(batchUpdateStage) for sectionIndex in 0..<sectionModels.count { guard sectionModels[sectionIndex].id == id else { continue } return sectionIndex } return nil } func itemModelHeightModeDuringPreferredAttributesCheck( at indexPath: IndexPath) -> MagazineLayoutItemHeightMode? { func itemModelHeightModeDuringPreferredAttributesCheck( at indexPath: IndexPath, sectionModels: inout [SectionModel]) -> MagazineLayoutItemHeightMode? { guard indexPath.section < sectionModels.count, indexPath.item < sectionModels[indexPath.section].numberOfItems else { assertionFailure("Height mode for item at \(indexPath) is out of bounds") return nil } return sectionModels[indexPath.section].itemModel(atIndex: indexPath.item).sizeMode.heightMode } switch updateContextForItemPreferredHeightUpdate(at: indexPath) { case .updatePreviousModels, .updatePreviousAndCurrentModels: return itemModelHeightModeDuringPreferredAttributesCheck( at: indexPath, sectionModels: &sectionModelsBeforeBatchUpdates) case .updateCurrentModels: return itemModelHeightModeDuringPreferredAttributesCheck( at: indexPath, sectionModels: &currentSectionModels) } } func headerModelHeightModeDuringPreferredAttributesCheck( atSectionIndex sectionIndex: Int) -> MagazineLayoutHeaderHeightMode? { func headerModelHeightModeDuringPreferredAttributesCheck( atSectionIndex sectionIndex: Int, sectionModels: inout [SectionModel]) -> MagazineLayoutHeaderHeightMode? { guard sectionIndex < sectionModels.count else { assertionFailure("Height mode for header at section index \(sectionIndex) is out of bounds") return nil } return sectionModels[sectionIndex].headerModel?.heightMode } switch updateContextForSupplementaryViewPreferredHeightUpdate(inSectionAtIndex: sectionIndex) { case .updatePreviousModels, .updatePreviousAndCurrentModels: return headerModelHeightModeDuringPreferredAttributesCheck( atSectionIndex: sectionIndex, sectionModels: &sectionModelsBeforeBatchUpdates) case .updateCurrentModels: return headerModelHeightModeDuringPreferredAttributesCheck( atSectionIndex: sectionIndex, sectionModels: &currentSectionModels) } } func footerModelHeightModeDuringPreferredAttributesCheck( atSectionIndex sectionIndex: Int) -> MagazineLayoutFooterHeightMode? { func footerModelHeightModeDuringPreferredAttributesCheck( atSectionIndex sectionIndex: Int, sectionModels: inout [SectionModel]) -> MagazineLayoutFooterHeightMode? { guard sectionIndex < sectionModels.count else { assertionFailure("Height mode for footer at section index \(sectionIndex) is out of bounds") return nil } return sectionModels[sectionIndex].footerModel?.heightMode } switch updateContextForSupplementaryViewPreferredHeightUpdate(inSectionAtIndex: sectionIndex) { case .updatePreviousModels, .updatePreviousAndCurrentModels: return footerModelHeightModeDuringPreferredAttributesCheck( atSectionIndex: sectionIndex, sectionModels: &sectionModelsBeforeBatchUpdates) case .updateCurrentModels: return footerModelHeightModeDuringPreferredAttributesCheck( atSectionIndex: sectionIndex, sectionModels: &currentSectionModels) } } func itemModelPreferredHeightDuringPreferredAttributesCheck(at indexPath: IndexPath) -> CGFloat? { func itemModelPreferredHeightDuringPreferredAttributesCheck( at indexPath: IndexPath, sectionModels: inout [SectionModel]) -> CGFloat? { guard indexPath.section < sectionModels.count, indexPath.item < sectionModels[indexPath.section].numberOfItems else { assertionFailure("Height mode for item at \(indexPath) is out of bounds") return nil } return sectionModels[indexPath.section].preferredHeightForItemModel(atIndex: indexPath.item) } switch updateContextForItemPreferredHeightUpdate(at: indexPath) { case .updatePreviousModels, .updatePreviousAndCurrentModels: return itemModelPreferredHeightDuringPreferredAttributesCheck( at: indexPath, sectionModels: &sectionModelsBeforeBatchUpdates) case .updateCurrentModels: return itemModelPreferredHeightDuringPreferredAttributesCheck( at: indexPath, sectionModels: &currentSectionModels) } } func itemLocationFramePairs(forItemsIn rect: CGRect) -> ElementLocationFramePairs { return elementLocationFramePairsForElements( in: rect, withElementLocationsForFlattenedIndices: itemLocationsForFlattenedIndices, andFramesProvidedBy: { itemLocation -> CGRect in return frameForItem(at: itemLocation, .afterUpdates) }) } func headerLocationFramePairs(forHeadersIn rect: CGRect) -> ElementLocationFramePairs { return elementLocationFramePairsForElements( in: rect, withElementLocationsForFlattenedIndices: headerLocationsForFlattenedIndices, andFramesProvidedBy: { headerLocation -> CGRect in guard let headerFrame = frameForHeader( inSectionAtIndex: headerLocation.sectionIndex, .afterUpdates) else { assertionFailure("Expected a frame for header in section at \(headerLocation.sectionIndex)") return .zero } return headerFrame }) } func footerLocationFramePairs(forFootersIn rect: CGRect) -> ElementLocationFramePairs { return elementLocationFramePairsForElements( in: rect, withElementLocationsForFlattenedIndices: footerLocationsForFlattenedIndices, andFramesProvidedBy: { footerLocation -> CGRect in guard let footerFrame = frameForFooter( inSectionAtIndex: footerLocation.sectionIndex, .afterUpdates) else { assertionFailure("Expected a frame for footer in section at \(footerLocation.sectionIndex)") return .zero } return footerFrame }) } func backgroundLocationFramePairs(forBackgroundsIn rect: CGRect) -> ElementLocationFramePairs { return elementLocationFramePairsForElements( in: rect, withElementLocationsForFlattenedIndices: backgroundLocationsForFlattenedIndices, andFramesProvidedBy: { backgroundLocation -> CGRect in guard let backgroundFrame = frameForBackground( inSectionAtIndex: backgroundLocation.sectionIndex, .afterUpdates) else { assertionFailure("Expected a frame for background in section at \(backgroundLocation.sectionIndex)") return .zero } return backgroundFrame }) } func sectionMaxY( forSectionAtIndex targetSectionIndex: Int, _ batchUpdateStage: BatchUpdateStage) -> CGFloat { func sectionMaxY( forSectionAtIndex targetSectionIndex: Int, sectionModelsPointer: UnsafeMutableRawPointer, numberOfSectionModels: Int) -> CGFloat { guard targetSectionIndex >= 0 && targetSectionIndex < numberOfSectionModels else { assertionFailure("`targetSectionIndex` is not within the bounds of the section models array") return 0 } let sectionModels = sectionModelsPointer.assumingMemoryBound(to: SectionModel.self) var totalHeight: CGFloat = 0 for sectionIndex in 0...targetSectionIndex { totalHeight += sectionModels[sectionIndex].calculateHeight() } return totalHeight } switch batchUpdateStage { case .beforeUpdates: return sectionMaxY( forSectionAtIndex: targetSectionIndex, sectionModelsPointer: &sectionModelsBeforeBatchUpdates, numberOfSectionModels: sectionModelsBeforeBatchUpdates.count) case .afterUpdates: let maxY = cachedMaxYForSection(atIndex: targetSectionIndex) ?? sectionMaxY( forSectionAtIndex: targetSectionIndex, sectionModelsPointer: &currentSectionModels, numberOfSectionModels: currentSectionModels.count) cacheMaxY(maxY, forSectionAtIndex: targetSectionIndex) return maxY } } func frameForItem( at itemLocation: ElementLocation, _ batchUpdateStage: BatchUpdateStage) -> CGRect { let sectionMinY: CGFloat if itemLocation.sectionIndex == 0 { sectionMinY = 0 } else { sectionMinY = sectionMaxY( forSectionAtIndex: itemLocation.sectionIndex - 1, batchUpdateStage) } let sectionModelsPointer = self.sectionModelsPointer(batchUpdateStage) let sectionModels = sectionModelsPointer.assumingMemoryBound(to: SectionModel.self) var itemFrame = sectionModels[itemLocation.sectionIndex].calculateFrameForItem( atIndex: itemLocation.elementIndex) itemFrame.origin.y += sectionMinY return itemFrame } func frameForHeader( inSectionAtIndex sectionIndex: Int, _ batchUpdateStage: BatchUpdateStage) -> CGRect? { let sectionMinY: CGFloat if sectionIndex == 0 { sectionMinY = 0 } else { sectionMinY = sectionMaxY(forSectionAtIndex: sectionIndex - 1, batchUpdateStage) } let sectionModelsPointer = self.sectionModelsPointer(batchUpdateStage) let sectionModels = sectionModelsPointer.assumingMemoryBound(to: SectionModel.self) let currentVisibleBounds = currentVisibleBoundsProvider() var headerFrame = sectionModels[sectionIndex].calculateFrameForHeader( inSectionVisibleBounds: CGRect( x: currentVisibleBounds.minX, y: currentVisibleBounds.minY - sectionMinY, width: currentVisibleBounds.width, height: currentVisibleBounds.height)) headerFrame?.origin.y += sectionMinY return headerFrame } func frameForFooter( inSectionAtIndex sectionIndex: Int, _ batchUpdateStage: BatchUpdateStage) -> CGRect? { let sectionMinY: CGFloat if sectionIndex == 0 { sectionMinY = 0 } else { sectionMinY = sectionMaxY(forSectionAtIndex: sectionIndex - 1, batchUpdateStage) } let sectionModelsPointer = self.sectionModelsPointer(batchUpdateStage) let sectionModels = sectionModelsPointer.assumingMemoryBound(to: SectionModel.self) let currentVisibleBounds = currentVisibleBoundsProvider() var footerFrame = sectionModels[sectionIndex].calculateFrameForFooter( inSectionVisibleBounds: CGRect( x: currentVisibleBounds.minX, y: currentVisibleBounds.minY - sectionMinY, width: currentVisibleBounds.width, height: currentVisibleBounds.height)) footerFrame?.origin.y += sectionMinY return footerFrame } func frameForBackground( inSectionAtIndex sectionIndex: Int, _ batchUpdateStage: BatchUpdateStage) -> CGRect? { let sectionMinY: CGFloat if sectionIndex == 0 { sectionMinY = 0 } else { sectionMinY = sectionMaxY(forSectionAtIndex: sectionIndex - 1, batchUpdateStage) } let sectionModelsPointer = self.sectionModelsPointer(batchUpdateStage) let sectionModels = sectionModelsPointer.assumingMemoryBound(to: SectionModel.self) var backgroundFrame = sectionModels[sectionIndex].calculateFrameForBackground() backgroundFrame?.origin.y += sectionMinY return backgroundFrame } func updateItemHeight( toPreferredHeight preferredHeight: CGFloat, forItemAt indexPath: IndexPath) { func updateItemHeight( toPreferredHeight preferredHeight: CGFloat, forItemAt indexPath: IndexPath, sectionModels: inout [SectionModel]) { guard indexPath.section < sectionModels.count, indexPath.item < sectionModels[indexPath.section].numberOfItems else { assertionFailure("Updating the preferred height for an item model at \(indexPath) is out of bounds") return } sectionModels[indexPath.section].updateItemHeight( toPreferredHeight: preferredHeight, atIndex: indexPath.item) } switch updateContextForItemPreferredHeightUpdate(at: indexPath) { case .updatePreviousModels: updateItemHeight( toPreferredHeight: preferredHeight, forItemAt: indexPath, sectionModels: &sectionModelsBeforeBatchUpdates) case .updateCurrentModels: updateItemHeight( toPreferredHeight: preferredHeight, forItemAt: indexPath, sectionModels: &currentSectionModels) invalidateSectionMaxYsCacheForSectionIndices(startingAt: indexPath.section) case let .updatePreviousAndCurrentModels(previousIndexPath, currentIndexPath): updateItemHeight( toPreferredHeight: preferredHeight, forItemAt: previousIndexPath, sectionModels: &sectionModelsBeforeBatchUpdates) updateItemHeight( toPreferredHeight: preferredHeight, forItemAt: currentIndexPath, sectionModels: &currentSectionModels) invalidateSectionMaxYsCacheForSectionIndices(startingAt: currentIndexPath.section) } } func updateHeaderHeight( toPreferredHeight preferredHeight: CGFloat, forSectionAtIndex sectionIndex: Int) { func updateHeaderHeight( toPreferredHeight preferredHeight: CGFloat, forSectionAtIndex sectionIndex: Int, sectionModels: inout [SectionModel]) { guard sectionIndex < sectionModels.count else { assertionFailure("Updating the preferred height for a header model at section index \(sectionIndex) is out of bounds") return } sectionModels[sectionIndex].updateHeaderHeight(toPreferredHeight: preferredHeight) } switch updateContextForSupplementaryViewPreferredHeightUpdate(inSectionAtIndex: sectionIndex) { case .updatePreviousModels: updateHeaderHeight( toPreferredHeight: preferredHeight, forSectionAtIndex: sectionIndex, sectionModels: &sectionModelsBeforeBatchUpdates) case .updateCurrentModels: updateHeaderHeight( toPreferredHeight: preferredHeight, forSectionAtIndex: sectionIndex, sectionModels: &currentSectionModels) invalidateSectionMaxYsCacheForSectionIndices(startingAt: sectionIndex) case let .updatePreviousAndCurrentModels(previousSectionIndex, currentSectionIndex): updateHeaderHeight( toPreferredHeight: preferredHeight, forSectionAtIndex: previousSectionIndex, sectionModels: &sectionModelsBeforeBatchUpdates) updateHeaderHeight( toPreferredHeight: preferredHeight, forSectionAtIndex: currentSectionIndex, sectionModels: &currentSectionModels) invalidateSectionMaxYsCacheForSectionIndices(startingAt: currentSectionIndex) } } func updateFooterHeight( toPreferredHeight preferredHeight: CGFloat, forSectionAtIndex sectionIndex: Int) { func updateFooterHeight( toPreferredHeight preferredHeight: CGFloat, forSectionAtIndex sectionIndex: Int, sectionModels: inout [SectionModel]) { guard sectionIndex < sectionModels.count else { assertionFailure("Updating the preferred height for a footer model at section index \(sectionIndex) is out of bounds") return } sectionModels[sectionIndex].updateFooterHeight(toPreferredHeight: preferredHeight) } switch updateContextForSupplementaryViewPreferredHeightUpdate(inSectionAtIndex: sectionIndex) { case .updatePreviousModels: updateFooterHeight( toPreferredHeight: preferredHeight, forSectionAtIndex: sectionIndex, sectionModels: &sectionModelsBeforeBatchUpdates) case .updateCurrentModels: updateFooterHeight( toPreferredHeight: preferredHeight, forSectionAtIndex: sectionIndex, sectionModels: &currentSectionModels) invalidateSectionMaxYsCacheForSectionIndices(startingAt: sectionIndex) case let .updatePreviousAndCurrentModels(previousSectionIndex, currentSectionIndex): updateFooterHeight( toPreferredHeight: preferredHeight, forSectionAtIndex: previousSectionIndex, sectionModels: &sectionModelsBeforeBatchUpdates) updateFooterHeight( toPreferredHeight: preferredHeight, forSectionAtIndex: currentSectionIndex, sectionModels: &currentSectionModels) invalidateSectionMaxYsCacheForSectionIndices(startingAt: currentSectionIndex) } } func updateMetrics( to sectionMetrics: MagazineLayoutSectionMetrics, forSectionAtIndex sectionIndex: Int) { currentSectionModels[sectionIndex].updateMetrics(to: sectionMetrics) invalidateSectionMaxYsCacheForSectionIndices(startingAt: sectionIndex) } func updateItemSizeMode(to sizeMode: MagazineLayoutItemSizeMode, forItemAt indexPath: IndexPath) { currentSectionModels[indexPath.section].updateItemSizeMode( to: sizeMode, atIndex: indexPath.item) invalidateSectionMaxYsCacheForSectionIndices(startingAt: indexPath.section) } func setHeader(_ headerModel: HeaderModel, forSectionAtIndex sectionIndex: Int) { currentSectionModels[sectionIndex].setHeader(headerModel) invalidateSectionMaxYsCacheForSectionIndices(startingAt: sectionIndex) prepareElementLocationsForFlattenedIndices() } func removeHeader(forSectionAtIndex sectionIndex: Int) { currentSectionModels[sectionIndex].removeHeader() invalidateSectionMaxYsCacheForSectionIndices(startingAt: sectionIndex) prepareElementLocationsForFlattenedIndices() } func setFooter(_ footerModel: FooterModel, forSectionAtIndex sectionIndex: Int) { currentSectionModels[sectionIndex].setFooter(footerModel) invalidateSectionMaxYsCacheForSectionIndices(startingAt: sectionIndex) prepareElementLocationsForFlattenedIndices() } func removeFooter(forSectionAtIndex sectionIndex: Int) { currentSectionModels[sectionIndex].removeFooter() invalidateSectionMaxYsCacheForSectionIndices(startingAt: sectionIndex) prepareElementLocationsForFlattenedIndices() } func setBackground( _ backgroundModel: BackgroundModel, forSectionAtIndex sectionIndex: Int) { currentSectionModels[sectionIndex].setBackground(backgroundModel) prepareElementLocationsForFlattenedIndices() } func removeBackground(forSectionAtIndex sectionIndex: Int) { currentSectionModels[sectionIndex].removeBackground() prepareElementLocationsForFlattenedIndices() } func setSections(_ sectionModels: [SectionModel]) { currentSectionModels = sectionModels invalidateEntireSectionMaxYsCache() allocateMemoryForSectionMaxYsCache() prepareElementLocationsForFlattenedIndices() } func applyUpdates( _ updates: [CollectionViewUpdate<SectionModel, ItemModel>]) { isPerformingBatchUpdates = true sectionModelsBeforeBatchUpdates = currentSectionModels invalidateEntireSectionMaxYsCache() var sectionModelReloadIndexPairs = [(sectionModel: SectionModel, reloadIndex: Int)]() var itemModelReloadIndexPathPairs = [(itemModel: ItemModel, reloadIndexPath: IndexPath)]() var sectionIndicesToDelete = [Int]() var itemIndexPathsToDelete = [IndexPath]() var sectionModelInsertIndexPairs = [(sectionModel: SectionModel, insertIndex: Int)]() var itemModelInsertIndexPathPairs = [(itemModel: ItemModel, insertIndexPath: IndexPath)]() for update in updates { switch update { case let .sectionReload(sectionIndex, newSection): sectionModelReloadIndexPairs.append((newSection, sectionIndex)) case let .itemReload(itemIndexPath, newItem): itemModelReloadIndexPathPairs.append((newItem, itemIndexPath)) case let .sectionDelete(sectionIndex): sectionIndicesToDelete.append(sectionIndex) self.sectionIndicesToDelete.insert(sectionIndex) case let .itemDelete(itemIndexPath): itemIndexPathsToDelete.append(itemIndexPath) self.itemIndexPathsToDelete.insert(itemIndexPath) case let .sectionMove(initialSectionIndex, finalSectionIndex): sectionIndicesToDelete.append(initialSectionIndex) let sectionModelToMove = sectionModelsBeforeBatchUpdates[initialSectionIndex] sectionModelInsertIndexPairs.append((sectionModelToMove, finalSectionIndex)) case let .itemMove(initialItemIndexPath, finalItemIndexPath): itemIndexPathsToDelete.append(initialItemIndexPath) let sectionContainingItemModelToMove = sectionModelsBeforeBatchUpdates[initialItemIndexPath.section] let itemModelToMove = sectionContainingItemModelToMove.itemModel( atIndex: initialItemIndexPath.item) itemModelInsertIndexPathPairs.append((itemModelToMove, finalItemIndexPath)) case let .sectionInsert(sectionIndex, newSection): sectionModelInsertIndexPairs.append((newSection, sectionIndex)) sectionIndicesToInsert.insert(sectionIndex) case let .itemInsert(itemIndexPath, newItem): itemModelInsertIndexPathPairs.append((newItem, itemIndexPath)) itemIndexPathsToInsert.insert(itemIndexPath) } } reloadItemModels(itemModelReloadIndexPathPairs: itemModelReloadIndexPathPairs) reloadSectionModels(sectionModelReloadIndexPairs: sectionModelReloadIndexPairs) deleteItemModels(atIndexPaths: itemIndexPathsToDelete) deleteSectionModels(atIndices: sectionIndicesToDelete) insertSectionModels(sectionModelInsertIndexPairs: sectionModelInsertIndexPairs) insertItemModels(itemModelInsertIndexPathPairs: itemModelInsertIndexPathPairs) allocateMemoryForSectionMaxYsCache() prepareElementLocationsForFlattenedIndices() } func clearInProgressBatchUpdateState() { sectionModelsBeforeBatchUpdates.removeAll() sectionIndicesToInsert.removeAll() sectionIndicesToDelete.removeAll() itemIndexPathsToInsert.removeAll() itemIndexPathsToDelete.removeAll() isPerformingBatchUpdates = false } // MARK: Private private enum ItemPreferredHeightUpdateContext { case updatePreviousModels case updateCurrentModels case updatePreviousAndCurrentModels(previousIndexPath: IndexPath, currentIndexPath: IndexPath) } private enum SupplementaryViewPreferredHeightUpdateContext { case updatePreviousModels case updateCurrentModels case updatePreviousAndCurrentModels(previousSectionIndex: Int, currentSectionIndex: Int) } private let currentVisibleBoundsProvider: () -> CGRect private var currentSectionModels = [SectionModel]() private var sectionModelsBeforeBatchUpdates = [SectionModel]() private var sectionMaxYsCache = [CGFloat?]() private var headerLocationsForFlattenedIndices = [Int: ElementLocation]() private var footerLocationsForFlattenedIndices = [Int: ElementLocation]() private var backgroundLocationsForFlattenedIndices = [Int: ElementLocation]() private var itemLocationsForFlattenedIndices = [Int: ElementLocation]() private func sectionModels(_ batchUpdateStage: BatchUpdateStage) -> [SectionModel] { switch batchUpdateStage { case .beforeUpdates: return sectionModelsBeforeBatchUpdates case .afterUpdates: return currentSectionModels } } private func sectionModelsPointer( _ batchUpdateStage: BatchUpdateStage) -> UnsafeMutableRawPointer { // Accessing these arrays using unsafe, untyped (raw) pointers // avoids expensive copy-on-writes and Swift retain / release calls. switch batchUpdateStage { case .beforeUpdates: return UnsafeMutableRawPointer(mutating: &sectionModelsBeforeBatchUpdates) case .afterUpdates: return UnsafeMutableRawPointer(mutating: &currentSectionModels) } } private func prepareElementLocationsForFlattenedIndices() { headerLocationsForFlattenedIndices.removeAll() footerLocationsForFlattenedIndices.removeAll() backgroundLocationsForFlattenedIndices.removeAll() itemLocationsForFlattenedIndices.removeAll() var flattenedHeaderIndex = 0 var flattenedFooterIndex = 0 var flattenedBackgroundIndex = 0 var flattenedItemIndex = 0 for sectionIndex in 0..<currentSectionModels.count { if currentSectionModels[sectionIndex].headerModel != nil { headerLocationsForFlattenedIndices[flattenedHeaderIndex] = ElementLocation( elementIndex: 0, sectionIndex: sectionIndex) flattenedHeaderIndex += 1 } if currentSectionModels[sectionIndex].footerModel != nil { footerLocationsForFlattenedIndices[flattenedFooterIndex] = ElementLocation( elementIndex: 0, sectionIndex: sectionIndex) flattenedFooterIndex += 1 } if currentSectionModels[sectionIndex].backgroundModel != nil { backgroundLocationsForFlattenedIndices[flattenedBackgroundIndex] = ElementLocation( elementIndex: 0, sectionIndex: sectionIndex) flattenedBackgroundIndex += 1 } for itemIndex in 0..<currentSectionModels[sectionIndex].numberOfItems { itemLocationsForFlattenedIndices[flattenedItemIndex] = ElementLocation( elementIndex: itemIndex, sectionIndex: sectionIndex) flattenedItemIndex += 1 } } } private func elementLocationFramePairsForElements( in rect: CGRect, withElementLocationsForFlattenedIndices elementLocationsForFlattenedIndices: [Int: ElementLocation], andFramesProvidedBy frameProvider: ((ElementLocation) -> CGRect)) -> ElementLocationFramePairs { var elementLocationFramePairs = ElementLocationFramePairs() guard let indexOfFirstFoundElement = indexOfFirstFoundElement( in: rect, withElementLocationsForFlattenedIndices: elementLocationsForFlattenedIndices, andFramesProvidedBy: frameProvider) else { return elementLocationFramePairs } // Used to handle the case where we encounter an element that doesn't intersect the rect, but // previous elements in the same row might. var minYOfNonIntersectingElement: CGFloat? // Look backward to find visible elements for elementLocationIndex in (0..<indexOfFirstFoundElement).reversed() { let elementLocation = self.elementLocation( forFlattenedIndex: elementLocationIndex, in: elementLocationsForFlattenedIndices) let frame = frameProvider(elementLocation) guard frame.maxY > rect.minY else { if let minY = minYOfNonIntersectingElement, frame.minY < minY { // We're in a previous row, so we know we've captured all intersecting rects for the // subsequent row. break } else { // We've found a non-intersecting item, but still need to check other items in the same // row. minYOfNonIntersectingElement = frame.minY continue } } elementLocationFramePairs.append( ElementLocationFramePair(elementLocation: elementLocation, frame: frame)) } // Look forward to find visible elements for elementLocationIndex in indexOfFirstFoundElement..<elementLocationsForFlattenedIndices.count { let elementLocation = self.elementLocation( forFlattenedIndex: elementLocationIndex, in: elementLocationsForFlattenedIndices) let frame = frameProvider(elementLocation) guard frame.minY < rect.maxY else { break } elementLocationFramePairs.append( ElementLocationFramePair(elementLocation: elementLocation, frame: frame)) } return elementLocationFramePairs } private func indexOfFirstFoundElement( in rect: CGRect, withElementLocationsForFlattenedIndices elementLocationsForFlattenedIndices: [Int: ElementLocation], andFramesProvidedBy frameProvider: ((ElementLocation) -> CGRect)) -> Int? { var lowerBound = 0 var upperBound = elementLocationsForFlattenedIndices.count - 1 while lowerBound <= upperBound { let index = (lowerBound + upperBound) / 2 let elementLocation = self.elementLocation( forFlattenedIndex: index, in: elementLocationsForFlattenedIndices) let elementFrame = frameProvider(elementLocation) if elementFrame.maxY <= rect.minY { lowerBound = index + 1 } else if elementFrame.minY >= rect.maxY { upperBound = index - 1 } else { return index } } return nil } private func elementLocation( forFlattenedIndex index: Int, in elementLocationsForFlattenedIndices: [Int: ElementLocation]) -> ElementLocation { guard let elementLocation = elementLocationsForFlattenedIndices[index] else { preconditionFailure("`elementLocationsForFlattenedIndices` must have a complete mapping of indices in 0..<\(elementLocationsForFlattenedIndices.count) to element locations") } return elementLocation } private func updateContextForItemPreferredHeightUpdate( at indexPath: IndexPath) -> ItemPreferredHeightUpdateContext { // iOS 12 fixes an issue that causes `UICollectionView` to provide preferred attributes for old, // invalid item index paths. This happens when an item is deleted, causing an off-screen, // unsized item to slide up into view. At this point, `UICollectionView` sizes that item since // it's now visible, but it provides the preferred attributes for the item's index path *before* // the delete batch update. // This issue actually causes `UICollectionViewFlowLayout` to crash on iOS 11 and earlier. // https://openradar.appspot.com/radar?id=5006149438930944 // Related animation issue ticket: https://openradar.appspot.com/radar?id=4929660190195712 // Once we drop support for iOS 11, we can delete everything outside of the // `#available(iOS 12.0, *)` check. if #available(iOS 12.0, *) { return .updateCurrentModels } else if !isPerformingBatchUpdates { return .updateCurrentModels } else { if itemIndexPathsToInsert.contains(indexPath) || sectionIndicesToInsert.contains(indexPath.section) { // If an item is being inserted, or it's in a section that's being inserted, update its // height in the section models after batch updates, since it won't exist in the previous // section models. return .updateCurrentModels } else if itemIndexPathsToDelete.contains(indexPath) || sectionIndicesToDelete.contains(indexPath.section) { // If an item is being deleted, or it's in a section that's being deleted, update its height // in the section models before batch updates, since it won't exist in the current section // models. return .updatePreviousModels } else if indexPath.section < sectionModelsBeforeBatchUpdates.count, indexPath.item < sectionModelsBeforeBatchUpdates[indexPath.section].numberOfItems, let previousItemModelID = idForItemModel(at: indexPath, .beforeUpdates), let currentIndexPath = indexPathForItemModel(withID: previousItemModelID, .afterUpdates) { // If an item was moved, then it will have an ID in the section models before batch updates, // and that ID will match an index path in the current section models. In this scenario, we // want to update the section models from before and after batch updates. return .updatePreviousAndCurrentModels( previousIndexPath: indexPath, currentIndexPath: currentIndexPath) } } return .updateCurrentModels } private func updateContextForSupplementaryViewPreferredHeightUpdate( inSectionAtIndex sectionIndex: Int) -> SupplementaryViewPreferredHeightUpdateContext { // An issue exists that causes `UICollectionView` to provide preferred attributes for old, // invalid supplementary view index paths. This happens when a section is deleted, causing an // off-screen, unsized supplementary view to slide up into view. At this point, // `UICollectionView` sizes that supplementary view since it's now visible, but it provides the // preferred attributes for the supplementary view's index path *before* the delete batch // update. // https://openradar.appspot.com/radar?id=5023315789873152 if !isPerformingBatchUpdates { return .updateCurrentModels } else { if sectionIndicesToInsert.contains(sectionIndex) { // If a section is being inserted, update the supplementary view's height in the section // models after batch updates, since it won't exist in the previous section models. return .updateCurrentModels } else if sectionIndicesToDelete.contains(sectionIndex) { // If a section is being deleted, update the supplementary view's height in the section // models before batch updates, since it won't exist in the current section models. return .updatePreviousModels } else if sectionIndex < sectionModelsBeforeBatchUpdates.count, let previousSectionModelID = idForSectionModel(atIndex: sectionIndex, .beforeUpdates), let currentSectionIndex = indexForSectionModel( withID: previousSectionModelID, .afterUpdates) { // If a supplementary view was moved, then it will have an ID in the section models before // batch updates, and that ID will match a section index in the current section models. In // this scenario, we want to update the section models from before and after batch updates. return .updatePreviousAndCurrentModels( previousSectionIndex: sectionIndex, currentSectionIndex: currentSectionIndex) } } return .updateCurrentModels } private func allocateMemoryForSectionMaxYsCache() { let arraySizeDelta = currentSectionModels.count - sectionMaxYsCache.count if arraySizeDelta > 0 { // Allocate more memory for _ in 0..<arraySizeDelta { sectionMaxYsCache.append(nil) } } else if arraySizeDelta < 0 { // Reclaim memory for _ in 0..<abs(arraySizeDelta) { sectionMaxYsCache.removeLast() } } } private func cachedMaxYForSection(atIndex sectionIndex: Int) -> CGFloat? { guard sectionIndex >= 0 && sectionIndex < sectionMaxYsCache.count else { return nil } return sectionMaxYsCache[sectionIndex] } private func cacheMaxY(_ sectionMaxY: CGFloat, forSectionAtIndex sectionIndex: Int) { guard sectionIndex >= 0 && sectionIndex < sectionMaxYsCache.count else { return } sectionMaxYsCache[sectionIndex] = sectionMaxY } private func invalidateEntireSectionMaxYsCache() { guard sectionMaxYsCache.count > 0 else { return } invalidateSectionMaxYsCacheForSectionIndices(startingAt: 0) } private func invalidateSectionMaxYsCacheForSectionIndices(startingAt sectionIndex: Int) { guard sectionIndex >= 0, sectionIndex < sectionMaxYsCache.count else { assertionFailure("Cannot invalidate `sectionMaxYsCache` starting at an invalid (negative or out-of-bounds) `sectionIndex` (\(sectionIndex)).") return } for sectionIndex in sectionIndex..<sectionMaxYsCache.count { sectionMaxYsCache[sectionIndex] = nil } } private func reloadSectionModels( sectionModelReloadIndexPairs: [(sectionModel: SectionModel, reloadIndex: Int)]) { for (sectionModel, reloadIndex) in sectionModelReloadIndexPairs { currentSectionModels.remove(at: reloadIndex) currentSectionModels.insert(sectionModel, at: reloadIndex) } } private func reloadItemModels( itemModelReloadIndexPathPairs: [(itemModel: ItemModel, reloadIndexPath: IndexPath)]) { for (itemModel, reloadIndexPath) in itemModelReloadIndexPathPairs { currentSectionModels[reloadIndexPath.section].deleteItemModel( atIndex: reloadIndexPath.item) currentSectionModels[reloadIndexPath.section].insert( itemModel, atIndex: reloadIndexPath.item) } } private func deleteSectionModels(atIndices indicesOfSectionModelsToDelete: [Int]) { // Always delete in descending order for indexOfSectionModelToDelete in (indicesOfSectionModelsToDelete.sorted { $0 > $1 }) { currentSectionModels.remove(at: indexOfSectionModelToDelete) } } private func deleteItemModels(atIndexPaths indexPathsOfItemModelsToDelete: [IndexPath]) { // Always delete in descending order for indexPathOfItemModelToDelete in (indexPathsOfItemModelsToDelete.sorted { $0 > $1 }) { currentSectionModels[indexPathOfItemModelToDelete.section].deleteItemModel( atIndex: indexPathOfItemModelToDelete.item) } } private func insertSectionModels( sectionModelInsertIndexPairs: [(sectionModel: SectionModel, insertIndex: Int)]) { // Always insert in ascending order for (sectionModel, insertIndex) in (sectionModelInsertIndexPairs.sorted { $0.insertIndex < $1.insertIndex }) { currentSectionModels.insert(sectionModel, at: insertIndex) } } private func insertItemModels( itemModelInsertIndexPathPairs: [(itemModel: ItemModel, insertIndexPath: IndexPath)]) { // Always insert in ascending order for (itemModel, insertIndexPath) in (itemModelInsertIndexPathPairs.sorted { $0.insertIndexPath < $1.insertIndexPath }) { currentSectionModels[insertIndexPath.section].insert(itemModel, atIndex: insertIndexPath.item) } } }
mit
809e52d361626d8432148c47d0e92996
36.360369
179
0.7388
5.271261
false
false
false
false
optimizely/swift-sdk
Tests/OptimizelyTests-Common/BucketTests_GroupToExp.swift
1
6763
// // Copyright 2019-2021, Optimizely, Inc. and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest class BucketTests_GroupToExp: XCTestCase { var optimizely: OptimizelyClient! var config: ProjectConfig! var bucketer: DefaultBucketer! var kUserId = "12345" var kGroupId = "333333" var kExperimentKey1 = "countryExperiment" var kExperimentId1 = "country11" var kExperimentKey2 = "ageExperiment" var kExperimentId2 = "age11" var kExperimentKey3 = "browserExperiment" var kExperimentId3 = "browser11" var kAudienceIdCountry = "10" var kAudienceIdAge = "20" var kAudienceIdInvalid = "9999999" var kAttributesCountryMatch: [String: Any] = ["country": "us"] var kAttributesCountryNotMatch: [String: Any] = ["country": "ca"] var kAttributesAgeMatch: [String: Any] = ["age": 30] var kAttributesAgeNotMatch: [String: Any] = ["age": 10] var kAttributesEmpty: [String: Any] = [:] var experiment: Experiment! var variation: Variation! // MARK: - Sample datafile data var sampleExperimentData1: [String: Any] { return [ "status": "Running", "id": kExperimentId1, "key": kExperimentKey1, "layerId": "10420273888", "trafficAllocation": [], "audienceIds": [], "variations": [], "forcedVariations": [:] ] } var sampleExperimentData2: [String: Any] { return [ "status": "Running", "id": kExperimentId2, "key": kExperimentKey2, "layerId": "10420273888", "trafficAllocation": [], "audienceIds": [], "variations": [], "forcedVariations": [:] ] } var sampleExperimentData3: [String: Any] { return [ "status": "Running", "id": kExperimentId3, "key": kExperimentKey3, "layerId": "10420273888", "trafficAllocation": [], "audienceIds": [], "variations": [], "forcedVariations": [:] ] } var sampleGroupData: [String: Any] { return ["id": kGroupId, "policy": "random", "trafficAllocation": [ ["entityId": kExperimentId1, "endOfRange": 3000], ["entityId": kExperimentId2, "endOfRange": 6000], ["entityId": kExperimentId3, "endOfRange": 10000] ], "experiments": [sampleExperimentData1, sampleExperimentData2, sampleExperimentData3] ] } // MARK: - Setup override func setUp() { super.setUp() self.optimizely = OTUtils.createOptimizely(datafileName: "empty_datafile", clearUserProfileService: true) self.config = self.optimizely.config self.bucketer = ((optimizely.decisionService as! DefaultDecisionService).bucketer as! DefaultBucketer) } } // MARK: - bucket to experiment (group) extension BucketTests_GroupToExp { func testBucketGroup() { self.config.project.groups = [try! OTUtils.model(from: sampleGroupData)] let tests = [["userId": "ppid1", "expect": kExperimentKey1], ["userId": "ppid2", "expect": kExperimentKey3], ["userId": "ppid3", "expect": kExperimentKey3], ["userId": "a very very very very very very very very very very very very very very very long ppd string", "expect": kExperimentKey2]] let group = self.config.getGroup(id: kGroupId) for (idx, test) in tests.enumerated() { let experiment = bucketer.bucketToExperiment(config: self.config, group: group!, bucketingId: test["userId"]!).result XCTAssertEqual(test["expect"], experiment?.key, "test[\(idx)] failed") } } func testBucketGroupWithTrafficAllocationEmpty() { var group: Group = try! OTUtils.model(from: sampleGroupData) group.trafficAllocation = [] self.config.project.groups = [group] let tests = [["userId": "ppid1"], ["userId": "ppid2"], ["userId": "ppid3"], ["userId": "a very very very very very very very very very very very very very very very long ppd string"]] for test in tests { let experiment = bucketer.bucketToExperiment(config: self.config, group: group, bucketingId: test["userId"]!).result XCTAssertNil(experiment) } } func testBucketGroupWithTrafficAllocationToInvalidExperiment() { var group: Group = try! OTUtils.model(from: sampleGroupData) group.trafficAllocation[0].entityId = "99999" group.trafficAllocation[0].endOfRange = 10000 self.config.project.groups = [group] let tests = [["userId": "ppid1"], ["userId": "ppid2"], ["userId": "ppid3"], ["userId": "a very very very very very very very very very very very very very very very long ppd string"]] for test in tests { let experiment = bucketer.bucketToExperiment(config: self.config, group: group, bucketingId: test["userId"]!).result XCTAssertNil(experiment) } } func testBucketGroupWithTrafficAllocationNotAllocated() { var group: Group = try! OTUtils.model(from: sampleGroupData) group.trafficAllocation[0].endOfRange = 10 group.trafficAllocation[1].endOfRange = 20 group.trafficAllocation[2].endOfRange = 30 self.config.project.groups = [group] let tests = [["userId": "ppid1"], ["userId": "ppid2"], ["userId": "ppid3"], ["userId": "a very very very very very very very very very very very very very very very long ppd string"]] for test in tests { let experiment = bucketer.bucketToExperiment(config: self.config, group: group, bucketingId: test["userId"]!).result XCTAssertNil(experiment) } } }
apache-2.0
9756db6b1a4bfb546afe69493a1f4c97
35.556757
155
0.586278
4.461082
false
true
false
false
mightydeveloper/swift
stdlib/public/SDK/Contacts/Contacts.swift
10
743
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Contacts import Foundation @available(OSX, introduced=10.11) @available(iOS, introduced=9.0) extension CNErrorCode : _BridgedNSError { public static var _NSErrorDomain: String { return CNErrorDomain } }
apache-2.0
dd50bb55be90d1bcc2e7b4f7158d7bd6
34.380952
80
0.590848
4.953333
false
false
false
false
huonw/swift
test/IDE/reconstruct_type_from_mangled_name.swift
2
8549
// RUN: %target-swift-ide-test -reconstruct-type -source-filename %s | %FileCheck %s -implicit-check-not="FAILURE" struct Mystruct1 { // CHECK: decl: struct Mystruct1 func s1f1() -> Int { return 0 } // CHECK: decl: func s1f1() -> Int var intField = 3 // CHECK: decl: var intField: Int // CHECK: decl: init(intField: Int) // CHECK: decl: init() } struct MyStruct2 { // CHECK: decl: struct MyStruct2 init() {} // CHECK: decl: init() init(x: Int) {} // CHECK: decl: init(x: Int) init(x: Int, y: Int) {} // CHECK: decl: init(x: Int, y: Int) } class Myclass1 { // CHECK: decl: class Myclass1 var intField = 4 // CHECK: decl: var intField: Int // CHECK: decl: init() } func f1() { // CHECK: decl: func f1() var s1ins = Mystruct1() // Implicit ctor // CHECK: decl: var s1ins: Mystruct1 _ = Mystruct1(intField: 1) // Implicit ctor s1ins.intField = 34 // CHECK: type: Mystruct1 // CHECK: type: Int var c1ins = Myclass1() // CHECK: decl: var c1ins: Myclass1 // CHECK: type: Myclass1 c1ins.intField = 3 // CHECK: type: Int s1ins.s1f1() // CHECK: type: Mystruct1 // CHECK: type: (Mystruct1) -> () -> Int if let ifletf1 = Int?(1) { // FIXME: lookup incorrect for if let binding. // CHECK: decl: struct Int : {{.*}} for 'ifletf1' usr=s:14swift_ide_test2f1yyF7ifletf1L_Siv } } class Myclass2 { // CHECK: decl: class Myclass2 func f1() { // CHECK: decl: func f1() var arr1 = [1, 2] // CHECK: decl: var arr1: [Int] // CHECK: type: Array<Int> arr1.append(1) // FIXME: missing append() // CHECK: dref: FAILURE for 'append' usr=s:Sa6appendyyxF // CHECK: type: (inout Array<Int>) -> (Int) -> () var arr2 : [Mystruct1] // CHECK: decl: var arr2: [Mystruct1] // CHECK: type: Array<Mystruct1> arr2.append(Mystruct1()) // CHECK: type: (inout Array<Mystruct1>) -> (Mystruct1) -> () var arr3 : [Myclass1] // CHECK: decl: var arr3: [Myclass1] // CHECK: type: Array<Myclass1> arr3.append(Myclass1()) // CHECK: type: (inout Array<Myclass1>) -> (Myclass1) -> () _ = Myclass2.init() // CHECK: dref: init() } } // CHECK: decl: enum MyEnum enum MyEnum { // FIXME // CHECK: decl: for 'ravioli' case ravioli // CHECK: decl: for 'pasta' case pasta // CHECK: decl: func method() -> Int func method() -> Int { return 0 } // CHECK: decl: func compare(_ other: MyEnum) -> Int func compare(_ other: MyEnum) -> Int { // CHECK: decl: let other: MyEnum return 0 } // CHECK: decl: mutating func mutatingMethod() mutating func mutatingMethod() {} } // CHECK: decl: func f2() func f2() { // CHECK: type: (MyEnum.Type) -> MyEnum var e = MyEnum.pasta // CHECK: type: (MyEnum) -> () -> Int e.method() // CHECK: (MyEnum) -> (MyEnum) -> Int e.compare(e) // CHECK: (inout MyEnum) -> () -> () e.mutatingMethod() } struct MyGenStruct1<T, U: ExpressibleByStringLiteral, V: Sequence> { // CHECK: decl: struct MyGenStruct1<T, U, V> where U : ExpressibleByStringLiteral, V : Sequence // FIXME: why are these references to the base type? // FIXME: TypeReconstruction should support Node::Kind::GenericTypeParamDecl ('fp') // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test12MyGenStruct1V1Txmfp // CHECK: decl: FAILURE for 'U' usr=s:14swift_ide_test12MyGenStruct1V1Uq_mfp // CHECK: decl: FAILURE for 'V' usr=s:14swift_ide_test12MyGenStruct1V1Vq0_mfp let x: T // CHECK: decl: let x: T let y: U // CHECK: decl: let y: U let z: V // CHECK: decl: let z: V func test000() { _ = x // CHECK: type: T _ = y // CHECK: type: U _ = z // CHECK: type: V } // CHECK: decl: func takesT(_ t: T) func takesT(_ t: T) { // CHECK: decl: let t: T } } let genstruct1 = MyGenStruct1<Int, String, [Float]>(x: 1, y: "", z: [1.0]) // CHECK: decl: let genstruct1: MyGenStruct1<Int, String, [Float]> func test001() { // CHECK: decl: func test001() _ = genstruct1 // CHECK: type: MyGenStruct1<Int, String, Array<Float>> var genstruct2: MyGenStruct1<Int, String, [Int: Int]> // CHECK: decl: var genstruct2: MyGenStruct1<Int, String, [Int : Int]> _ = genstruct2 // CHECK: type: MyGenStruct1<Int, String, Dictionary<Int, Int>> _ = genstruct2.x // CHECK: type: Int _ = genstruct2.y // CHECK: type: String _ = genstruct2.z // CHECK: type: Dictionary<Int, Int> genstruct2.takesT(123) } // CHECK: decl: protocol P1 protocol P1 {} // CHECK: decl: func foo1(p: P1) func foo1(p: P1) { // CHECK: decl: let p: P1 // CHECK: type: (P1) -> () foo1(p: p) } // CHECK: decl: protocol P2 protocol P2 {} // CHECK: decl: func foo2(p: P1 & P2) func foo2(p: P1 & P2) { // CHECK: decl: let p: P1 & P2 foo2(p: p) } // CHECK: func foo3(p: P1 & AnyObject) func foo3(p: P1 & AnyObject) { // CHECK: decl: let p: P1 & AnyObject foo3(p: p) } // CHECK: func foo4(p: Myclass1 & P1 & P2) func foo4(p: P1 & P2 & Myclass1) { // CHECK: decl: let p: Myclass1 & P1 & P2 foo4(p: p) } func genericFunction<T : AnyObject>(t: T) { // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test15genericFunction1tyx_tRlzClF1TL_xmfp genericFunction(t: t) } // CHECK: decl: func takesInOut(fn: (inout Int) -> ()) // CHECK: decl: let fn: (inout Int) -> () for 'fn' func takesInOut(fn: (inout Int) -> ()) {} struct Outer { struct Inner { let x: Int } struct GenericInner<T> { // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test5OuterV12GenericInnerV1Txmfp let t: T } } struct GenericOuter<T> { // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test12GenericOuterV1Txmfp struct Inner { let t: T let x: Int } struct GenericInner<U> { // CHECK: decl: FAILURE for 'U' usr=s:14swift_ide_test12GenericOuterV0D5InnerV1Uqd__mfp let t: T let u: U } } // CHECK: decl: func takesGeneric(_ t: Outer.GenericInner<Int>) func takesGeneric(_ t: Outer.GenericInner<Int>) { takesGeneric(t) } // CHECK: decl: func takesGeneric(_ t: GenericOuter<Int>.Inner) func takesGeneric(_ t: GenericOuter<Int>.Inner) { takesGeneric(t) } // CHECK: decl: func takesGeneric(_ t: GenericOuter<Int>.GenericInner<String>) func takesGeneric(_ t: GenericOuter<Int>.GenericInner<String>) { takesGeneric(t) } func hasLocalDecls() { func localFunction() {} // FIXME // CHECK: decl: FAILURE for 'LocalType' struct LocalType { // CHECK: FAILURE for 'localMethod' func localMethod() {} // CHECK: FAILURE for 'subscript' subscript(x: Int) { get {} set {} } // CHECK: decl: FAILURE for '' // CHECK: decl: FAILURE for '' // CHECK: decl: FAILURE for '' } // FIXME // CHECK: decl: FAILURE for 'LocalClass' class LocalClass { // CHECK: FAILURE for 'deinit' deinit {} // CHECK: decl: FAILURE for '' } // CHECK: decl: FAILURE for 'LocalAlias' typealias LocalAlias = LocalType } fileprivate struct VeryPrivateData {} // CHECK: decl: fileprivate func privateFunction(_ d: VeryPrivateData) for 'privateFunction' fileprivate func privateFunction(_ d: VeryPrivateData) {} struct HasSubscript { // CHECK: decl: subscript(t: Int) -> Int { get set } subscript(_ t: Int) -> Int { // CHECK: decl: get {} for '' usr=s:14swift_ide_test12HasSubscriptVyS2icig get { return t } // CHECK: decl: set {} for '' usr=s:14swift_ide_test12HasSubscriptVyS2icis set {} } } // FIXME // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test19HasGenericSubscriptV1Txmfp struct HasGenericSubscript<T> { // CHECK: subscript<U>(t: T) -> U { get set } for 'subscript' usr=s:14swift_ide_test19HasGenericSubscriptVyqd__xclui // FIXME // CHECK: decl: FAILURE for 'U' // FIXME // CHECK: decl: FAILURE for 't' subscript<U>(_ t: T) -> U { // CHECK: decl: get {} for '' usr=s:14swift_ide_test19HasGenericSubscriptVyqd__xcluig // FIXME // CHECK: dref: FAILURE for 't' get { return t as! U } // FIXME // CHECK: dref: FAILURE for 'U' // CHECK: decl: set {} for '' usr=s:14swift_ide_test19HasGenericSubscriptVyqd__xcluis set {} } } private // CHECK: decl: private func patatino<T>(_ vers1: T, _ vers2: T) -> Bool where T : Comparable for func patatino<T: Comparable>(_ vers1: T, _ vers2: T) -> Bool { // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test8patatino33_D7B956AE2D93947DFA67A1ECF93EF238LLySbx_xts10ComparableRzlF1TL_xmfp decl // CHECK: decl: let vers1: T for 'vers1' usr=s:14swift_ide_test8patatino33_D7B956AE2D93947DFA67A1ECF93EF238LLySbx_xts10ComparableRzlF5vers1L_xvp // CHECK: decl: let vers2: T for 'vers2' usr=s:14swift_ide_test8patatino33_D7B956AE2D93947DFA67A1ECF93EF238LLySbx_xts10ComparableRzlF5vers2L_xvp return vers1 < vers2; }
apache-2.0
f2eac45f8cf83ff9bdbfc31a776ac360
24.595808
151
0.64335
2.96018
false
true
false
false
zzcgumn/MvvmTouch
MvvmTouch/MvvmTouch/FlowController/ShowFlowController.swift
1
1398
// // ShowFlowController.swift // MvvmTouch // // Created by Martin Nygren on 05/02/2017. // Copyright © 2017 Martin Nygren. All rights reserved. // import UIKit public class ShowFlowController<Presented, ViewModel> : FlowController where Presented: MvvmViewController<ViewModel> { static public var sequeIdentifier: String { let viewModelName = String(describing: ViewModel.self) return "show\(viewModelName)" } public init() { } public func present(presentingViewController: UIViewController, makeViewModel: () -> ViewModel, makeViewController: () -> Presented = {Presented()}) { let presentedViewController = makeViewController() let vm = makeViewModel() presentedViewController.viewModel = vm presentedViewController.showCloseButton = false let seque = UIStoryboardSegue(identifier: ShowFlowController.sequeIdentifier, source: presentingViewController, destination: presentedViewController) { [weak self] in if let strongSelf = self { presentingViewController.show(presentedViewController, sender: strongSelf) } } seque.perform() } }
mit
5f2e73b09ea6b60f54b5d024cfa527a5
30.75
118
0.591267
5.919492
false
false
false
false
austinzheng/swift
test/ClangImporter/macro_literals.swift
56
9410
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -Xllvm -sil-print-debuginfo -emit-sil %s | %FileCheck %s import macros // CHECK-LABEL: // testBitwiseOperations() func testBitwiseOperations() { // CHECK: %[[P0:.*]] = integer_literal $Builtin.Int64, -1, loc {{.*}} // CHECK: %{{.*}} = struct $UInt64 (%[[P0]] : $Builtin.Int64), loc {{.*}} _ = DISPATCH_TIME_FOREVER as CUnsignedLongLong // CHECK-NEXT: %[[P1:.*]] = integer_literal $Builtin.Int32, 1, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P1]] : $Builtin.Int32), loc {{.*}} _ = BIT_SHIFT_1 as CInt // CHECK-NEXT: %[[P2:.*]] = integer_literal $Builtin.Int32, 4, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P2]] : $Builtin.Int32), loc {{.*}} _ = BIT_SHIFT_2 as CInt // CHECK-NEXT: %[[P3:.*]] = integer_literal $Builtin.Int64, 24, loc {{.*}} // CHECK: %{{.*}} = struct $Int64 (%[[P3]] : $Builtin.Int64), loc {{.*}} _ = BIT_SHIFT_3 as CLongLong // CHECK-NEXT: %[[P4:.*]] = integer_literal $Builtin.Int32, 2, loc {{.*}} // CHECK: %{{.*}} = struct $UInt32 (%[[P4]] : $Builtin.Int32), loc {{.*}} _ = BIT_SHIFT_4 as CUnsignedInt // CHECK-NEXT: %[[P5:.*]] = integer_literal $Builtin.Int32, 1, loc {{.*}} // CHECK: %{{.*}} = struct $UInt32 (%[[P5]] : $Builtin.Int32), loc {{.*}} _ = RSHIFT_ONE as CUnsignedInt // CHECK-NEXT: %[[P6:.*]] = integer_literal $Builtin.Int32, -2, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P6]] : $Builtin.Int32), loc {{.*}} _ = RSHIFT_NEG as CInt // CHECK-NEXT: %[[P7:.*]] = integer_literal $Builtin.Int64, -4294967296, loc {{.*}} // CHECK: %{{.*}} = struct $UInt64 (%[[P7]] : $Builtin.Int64), loc {{.*}} _ = XOR_HIGH as CUnsignedLongLong // CHECK-NEXT: %[[P8:.*]] = integer_literal $Builtin.Int32, 256, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P8]] : $Builtin.Int32), loc {{.*}} _ = ATTR_BOLD as CInt // CHECK-NEXT: %[[P9:.*]] = integer_literal $Builtin.Int32, 512, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P9]] : $Builtin.Int32), loc {{.*}} _ = ATTR_ITALIC as CInt // CHECK-NEXT: %[[P10:.*]] = integer_literal $Builtin.Int32, 1024, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P10]] : $Builtin.Int32), loc {{.*}} _ = ATTR_UNDERLINE as CInt } // CHECK-LABEL: // testIntegerArithmetic() func testIntegerArithmetic() { // CHECK: %[[P0:.*]] = integer_literal $Builtin.Int32, 0, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P0]] : $Builtin.Int32), loc {{.*}} _ = ADD_ZERO as CInt // CHECK-NEXT: %[[P1:.*]] = integer_literal $Builtin.Int32, 1, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P1]] : $Builtin.Int32), loc {{.*}} _ = ADD_ONE as CInt // CHECK-NEXT: %[[P2:.*]] = integer_literal $Builtin.Int32, 2, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P2]] : $Builtin.Int32), loc {{.*}} _ = ADD_TWO as CInt // CHECK-NEXT: %[[P3:.*]] = integer_literal $Builtin.Int32, -2, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P3]] : $Builtin.Int32), loc {{.*}} _ = ADD_MINUS_TWO as CInt // CHECK-NEXT: %[[P4:.*]] = integer_literal $Builtin.Int64, 169, loc {{.*}} // CHECK: %{{.*}} = struct $Int64 (%[[P4]] : $Builtin.Int64), loc {{.*}} _ = ADD_MIXED_WIDTH as CLongLong // CHECK-NEXT: %[[P5:.*]] = integer_literal $Builtin.Int64, 142, loc {{.*}} // CHECK: %{{.*}} = struct $Int64 (%[[P5]] : $Builtin.Int64), loc {{.*}} _ = ADD_MIXED_SIGN as CLongLong // CHECK-NEXT: %[[P6:.*]] = integer_literal $Builtin.Int32, -3, loc {{.*}} // CHECK: %{{.*}} = struct $UInt32 (%[[P6]] : $Builtin.Int32), loc {{.*}} _ = ADD_UNDERFLOW as CUnsignedInt // CHECK-NEXT: %[[P7:.*]] = integer_literal $Builtin.Int32, 2, loc {{.*}} // CHECK: %{{.*}} = struct $UInt32 (%[[P7]] : $Builtin.Int32), loc {{.*}} _ = ADD_OVERFLOW as CUnsignedInt // CHECK-NEXT: %[[P8:.*]] = integer_literal $Builtin.Int32, 1, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P8]] : $Builtin.Int32), loc {{.*}} _ = SUB_ONE as CInt // CHECK-NEXT: %[[P9:.*]] = integer_literal $Builtin.Int32, 0, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P9]] : $Builtin.Int32), loc {{.*}} _ = SUB_ZERO as CInt // CHECK-NEXT: %[[P10:.*]] = integer_literal $Builtin.Int32, -1, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P10]] : $Builtin.Int32), loc {{.*}} _ = SUB_MINUS_ONE as CInt // CHECK-NEXT: %[[P11:.*]] = integer_literal $Builtin.Int64, 42, loc {{.*}} // CHECK: %{{.*}} = struct $Int64 (%[[P11]] : $Builtin.Int64), loc {{.*}} _ = SUB_MIXED_WIDTH as CLongLong // CHECK-NEXT: %[[P12:.*]] = integer_literal $Builtin.Int32, 51, loc {{.*}} // CHECK: %{{.*}} = struct $UInt32 (%[[P12]] : $Builtin.Int32), loc {{.*}} _ = SUB_MIXED_SIGN as CUnsignedInt // CHECK-NEXT: %[[P13:.*]] = integer_literal $Builtin.Int32, -1, loc {{.*}} // CHECK: %{{.*}} = struct $UInt32 (%[[P13]] : $Builtin.Int32), loc {{.*}} _ = SUB_UNDERFLOW as CUnsignedInt // CHECK-NEXT: %[[P14:.*]] = integer_literal $Builtin.Int32, 1, loc {{.*}} // CHECK: %{{.*}} = struct $UInt32 (%[[P14]] : $Builtin.Int32), loc {{.*}} _ = SUB_OVERFLOW as CUnsignedInt // CHECK-NEXT: %[[P15:.*]] = integer_literal $Builtin.Int32, 36, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P15]] : $Builtin.Int32), loc {{.*}} _ = MULT_POS as CInt // CHECK-NEXT: %[[P16:.*]] = integer_literal $Builtin.Int32, -12, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P16]] : $Builtin.Int32), loc {{.*}} _ = MULT_NEG as CInt // CHECK-NEXT: %[[P17:.*]] = integer_literal $Builtin.Int64, 8589934590, loc {{.*}} // CHECK: %{{.*}} = struct $Int64 (%[[P17]] : $Builtin.Int64), loc {{.*}} _ = MULT_MIXED_TYPES as CLongLong // CHECK-NEXT: %[[P18:.*]] = integer_literal $Builtin.Int32, 128, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P18]] : $Builtin.Int32), loc {{.*}} _ = DIVIDE_INTEGRAL as CInt // CHECK-NEXT: %[[P19:.*]] = integer_literal $Builtin.Int32, 1, loc {{.*}} // CHECK: %{{.*}} = struct $Int32 (%[[P19]] : $Builtin.Int32), loc {{.*}} _ = DIVIDE_NONINTEGRAL as CInt // CHECK-NEXT: %[[P20:.*]] = integer_literal $Builtin.Int64, 2147483648, loc {{.*}} // CHECK: %{{.*}} = struct $Int64 (%[[P20]] : $Builtin.Int64), loc {{.*}} _ = DIVIDE_MIXED_TYPES as CLongLong } // CHECK-LABEL: // testIntegerComparisons() func testIntegerComparisons() { // CHECK: %0 = integer_literal $Builtin.Int1, 0, loc {{.*}} // CHECK-NEXT: %1 = struct $Bool (%0 : $Builtin.Int1), loc {{.*}} _ = EQUAL_FALSE // CHECK-NEXT: %2 = integer_literal $Builtin.Int1, -1, loc {{.*}} // CHECK-NEXT: %3 = struct $Bool (%2 : $Builtin.Int1), loc {{.*}} _ = EQUAL_TRUE // CHECK-NEXT: %4 = integer_literal $Builtin.Int1, -1, loc {{.*}} // CHECK-NEXT: %5 = struct $Bool (%4 : $Builtin.Int1), loc {{.*}} _ = EQUAL_TRUE_MIXED_TYPES // CHECK-NEXT: %6 = integer_literal $Builtin.Int1, 0, loc {{.*}} // CHECK-NEXT: %7 = struct $Bool (%6 : $Builtin.Int1), loc {{.*}} _ = GT_FALSE // CHECK-NEXT: %8 = integer_literal $Builtin.Int1, -1, loc {{.*}} // CHECK-NEXT: %9 = struct $Bool (%8 : $Builtin.Int1), loc {{.*}} _ = GT_TRUE // CHECK-NEXT: %10 = integer_literal $Builtin.Int1, 0, loc {{.*}} // CHECK-NEXT: %11 = struct $Bool (%10 : $Builtin.Int1), loc {{.*}} _ = GTE_FALSE // CHECK-NEXT: %12 = integer_literal $Builtin.Int1, -1, loc {{.*}} // CHECK-NEXT: %13 = struct $Bool (%12 : $Builtin.Int1), loc {{.*}} _ = GTE_TRUE // CHECK-NEXT: %14 = integer_literal $Builtin.Int1, 0, loc {{.*}} // CHECK-NEXT: %15 = struct $Bool (%14 : $Builtin.Int1), loc {{.*}} _ = LT_FALSE // CHECK-NEXT: %16 = integer_literal $Builtin.Int1, -1, loc {{.*}} // CHECK-NEXT: %17 = struct $Bool (%16 : $Builtin.Int1), loc {{.*}} _ = LT_TRUE // CHECK-NEXT: %18 = integer_literal $Builtin.Int1, 0, loc {{.*}} // CHECK-NEXT: %19 = struct $Bool (%18 : $Builtin.Int1), loc {{.*}} _ = LTE_FALSE // CHECK-NEXT: %20 = integer_literal $Builtin.Int1, -1, loc {{.*}} // CHECK-NEXT: %21 = struct $Bool (%20 : $Builtin.Int1), loc {{.*}} _ = LTE_TRUE } // CHECK-LABEL: // testLogicalComparisons() func testLogicalComparisons() { // CHECK: %0 = integer_literal $Builtin.Int1, -1, loc {{.*}} // CHECK-NEXT: %1 = struct $Bool (%0 : $Builtin.Int1), loc {{.*}} _ = L_AND_TRUE // CHECK-NEXT: %2 = integer_literal $Builtin.Int1, 0, loc {{.*}} // CHECK-NEXT: %3 = struct $Bool (%2 : $Builtin.Int1), loc {{.*}} _ = L_AND_FALSE // CHECK-NEXT: %4 = integer_literal $Builtin.Int1, -1, loc {{.*}} // CHECK-NEXT: %5 = struct $Bool (%4 : $Builtin.Int1), loc {{.*}} _ = L_AND_TRUE_B // CHECK-NEXT: %6 = integer_literal $Builtin.Int1, 0, loc {{.*}} // CHECK-NEXT: %7 = struct $Bool (%6 : $Builtin.Int1), loc {{.*}} _ = L_AND_FALSE_B // CHECK-NEXT: %8 = integer_literal $Builtin.Int1, -1, loc {{.*}} // CHECK-NEXT: %9 = struct $Bool (%8 : $Builtin.Int1), loc {{.*}} _ = L_OR_TRUE // CHECK-NEXT: %10 = integer_literal $Builtin.Int1, 0, loc {{.*}} // CHECK-NEXT: %11 = struct $Bool (%10 : $Builtin.Int1), loc {{.*}} _ = L_OR_FALSE // CHECK-NEXT: %12 = integer_literal $Builtin.Int1, -1, loc {{.*}} // CHECK-NEXT: %13 = struct $Bool (%12 : $Builtin.Int1), loc {{.*}} _ = L_OR_TRUE_B // CHECK-NEXT: %14 = integer_literal $Builtin.Int1, 0, loc {{.*}} // CHECK-NEXT: %15 = struct $Bool (%14 : $Builtin.Int1), loc {{.*}} _ = L_OR_FALSE_B }
apache-2.0
0112bf2a3d7d731b3b8612d27c89c881
49.864865
118
0.530287
3.121061
false
false
false
false
weiyanwu84/MLSwiftBasic
Demo/MLSwiftBasic/Demo/Demo4ViewController.swift
9
1401
// github: https://github.com/MakeZL/MLSwiftBasic // author: @email <[email protected]> // // Demo4ViewController.swift // MLSwiftBasic // // Created by 张磊 on 15/7/6. // Copyright (c) 2015年 MakeZL. All rights reserved. // import UIKit class Demo4ViewController: MBBaseVisualViewController,UITableViewDataSource,UITableViewDelegate{ override func viewDidLoad() { super.viewDidLoad() self.setNavBarViewBackgroundColor(UIColor(rgba: "ff9814")) // 设置是否要渐变 self.setNavBarGradient(true) self.setupTableView() } func setupTableView(){ var tableView = UITableView(frame: self.view.frame, style: .Plain) tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.dataSource = self tableView.delegate = self self.view.insertSubview(tableView, atIndex: 0) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "cell" var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = "Test \(indexPath.row)" return cell } }
mit
34f569ec349fd3a8fec61da2da97137a
31.880952
135
0.685735
4.618729
false
false
false
false
VincentPuget/PhoneList
PhoneList/class/Utils/Const.swift
1
619
// // Const.swift // PhoneList // // Created by Vincent PUGET on 16/09/2016. // Copyright © 2016 Vincent PUGET. All rights reserved. // struct Const { struct App { static let NAME:String = "PhoneList"; static let DEBUG:Bool = true; } struct Webservice { // static let URL: String = "http://phonelist.jpm-next.com" // static let PHONE_ENDPOINT: String = "/index.php" static let URL: String = "https://adam.jpm-next.com" static let PHONE_ENDPOINT: String = "/apps/fetch" static let identifier: String = "APPPhonelist" static let password: String = "JPMASJPMAS"; } }
mit
5cb9a8787e7af0eef6ac1643b66252a6
23.72
62
0.645631
3.340541
false
false
false
false
acediac/BananasSwift
Common/AAPLGameLevel.swift
1
44946
// // AAPLGameLevel.swift // BananasSwift // // Created by Andrew on 22/04/2015. // Copyright (c) 2015 Machina Venefici. All rights reserved. // /* Abstract: This class manages most of the game logic, including setting up the scene and keeping score. */ import Foundation import SceneKit import SpriteKit struct AAPLCategoryBitMasks { static let ShadowReceiverCategory = 0x0000_0002 } // Bitmasks for Physics categories struct GameCollisionCategory { static let Ground = 0x00000002 static let Banana = 0x00000004 static let Player = 0x00000008 static let Lava = 0x00000010 static let Coin = 0x00000020 static let Coconut = 0x00000040 static let NoCollide = 0x00000080 } struct NodeCategory { static let Torch = 0x00000002 static let Lava = 0x00000004 static let Lava2 = 0x00000008 } let BANANA_SCALE_LARGE: CGFloat = 0.5 * 10/4 let BANANA_SCALE: CGFloat = 0.5 class AAPLGameLevel : NSObject, AAPLGameUIState { var playerCharacter: AAPLPlayerCharacter? var monkeyCharacter: AAPLMonkeyCharacter? var camera: SCNNode? var bananas: Set<SCNNode>? var largeBananas: Set<SCNNode>? var coconuts: Set<SCNNode>? var hitByLavaReset: Bool = false var timeAlongPath: CGFloat = 0 // AAPLGameUIState protocol var score: Int = 0 var coinsCollected: Int = 0 var bananasCollected: Int = 0 var secondsRemaining: NSTimeInterval = 120 var scoreLabelLocation: CGPoint = CGPoint() var rootNode: SCNNode! var sunLight: SCNNode! var pathPositions: [SCNVector3] = [] var bananaCollectable: SCNNode? var largeBananaCollectable: SCNNode? // var monkeyProtoObject: AAPLSkinnedCharacter // var coconutProtoObject: SCNNode? // var palmTreeProtoObject: SCNNode? var monkeys: [AAPLMonkeyCharacter]? var _bananaIdleAction: SCNAction? var bananaIdleAction: SCNAction { get { if (self._bananaIdleAction == nil) { let rotateAction = SCNAction.rotateByX(0, y: CGFloat(M_PI_2), z: 0, duration: 1.0) rotateAction.timingMode = SCNActionTimingMode.EaseInEaseOut let reversed = rotateAction.reversedAction() self._bananaIdleAction = SCNAction.sequence([rotateAction, reversed]) } return self._bananaIdleAction! } } var _hoverAction: SCNAction! var hoverAction: SCNAction! { get { if (self._hoverAction == nil) { let floatAction: SCNAction = SCNAction.moveByX(0, y: 10.0, z: 0, duration: 1.0) let floatAction2: SCNAction = floatAction.reversedAction() floatAction.timingMode = SCNActionTimingMode.EaseInEaseOut floatAction2.timingMode = SCNActionTimingMode.EaseInEaseOut self._hoverAction = SCNAction.sequence([floatAction, floatAction2]) } return self._hoverAction } } private var _lightOffsetFromCharacter: SCNVector3 = SCNVector3() private var _screenSpaceplayerPosition: SCNVector3 = SCNVector3() private var _worldSpaceLabelScorePosition: SCNVector3 = SCNVector3() override init() { self.rootNode = nil super.init() } func isHighEnd() -> Bool { // TODO: return true on OSX, iPad Air, iPhone 5s+ return true; } // MARK: Pathing functions func setupPathColliders() { // Collect all the nodes that start with path_ under the dummy_front object // Set those objects as Physics category groun and create a static concave mesh collider // This simulation will use these as the ground to walk on if let front = self.rootNode?.childNodeWithName("dummy_front", recursively: true) { front.enumerateChildNodesUsingBlock({ (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in if let _cname = child.name where _cname.hasPrefix("path_") { // the geometry is attached to the first child node of the node named path_* if let path: SCNNode = child.childNodes.first as? SCNNode { path.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Static, shape: SCNPhysicsShape(geometry: path.geometry!, options: [SCNPhysicsShapeTypeKey : SCNPhysicsShapeTypeConcavePolyhedron])) path.physicsBody!.categoryBitMask = GameCollisionCategory.Ground } } }) } } func collectSortedPathNodes() -> [SCNNode] { // Gather all the children under the dummy_master // Sort left to right, in the world // ASSUME: rootNode exists with name "dummy_master" let pathNodes: SCNNode = self.rootNode!.childNodeWithName("dummy_master", recursively: true)! let sortedNodes: [SCNNode] = pathNodes.childNodes.sorted( { (obj1: AnyObject, obj2: AnyObject) -> Bool in let dummy1: SCNNode = obj1 as! SCNNode let dummy2: SCNNode = obj2 as! SCNNode if (dummy1.position.x < dummy2.position.x) { return true // obj1 is ordered before obj2 } return false } ) as! [SCNNode] return sortedNodes } func convertPathNodesIntoPathPositions() { // Walk the path, sampling every little bit, creating a path to follow // We use this path to move along left to right and right to left var sortedNodes = [SCNNode]() sortedNodes = self.collectSortedPathNodes() self.pathPositions = [SCNVector3]() self.pathPositions.append(SCNVector3Make(0,0,0)) for d in sortedNodes { if let _name = d.name where _name.hasPrefix("dummy_path") { self.pathPositions.append(d.position) } } self.pathPositions.append(SCNVector3Make(0,0,0)) } func resamplePathPositions() { // Calc the phantom end control point var controlPointA: SCNVector3 = self.pathPositions[self.pathPositions.count - 2] var controlPointB: SCNVector3 = self.pathPositions[self.pathPositions.count - 3] var controlPoint: SCNVector3 = SCNVector3() controlPoint.x = controlPointA.x + (controlPointA.x - controlPointB.x) controlPoint.y = controlPointA.y + (controlPointA.y - controlPointB.y) controlPoint.z = controlPointA.z + (controlPointA.z - controlPointB.z) self.pathPositions[self.pathPositions.count - 1] = controlPoint // Calc the phantom begin control point controlPointA = self.pathPositions[1] controlPointB = self.pathPositions[2] controlPoint.x = controlPointA.x + (controlPointA.x - controlPointB.x) controlPoint.y = controlPointA.y + (controlPointA.y - controlPointB.y) controlPoint.z = controlPointA.z + (controlPointA.z - controlPointB.z) self.pathPositions[0] = controlPoint var newPath = [SCNVector3]() var lastPosition: SCNVector3 = SCNVector3() let minDistanceBetweenPoints: CGFloat = 10.0 let steps: Int = 10000 for i in 0 ..< steps { let t: CGFloat = CGFloat(i) / CGFloat(steps) var currentPosition: SCNVector3 = self.locationAlongPath(t) if (i == 0) { newPath.append(currentPosition) lastPosition = currentPosition } else { let dist: CGFloat = CGFloat(GLKVector3Distance(SCNVector3ToGLKVector3(currentPosition), SCNVector3ToGLKVector3(lastPosition))) if (dist > minDistanceBetweenPoints) { newPath.append(currentPosition) lastPosition = currentPosition } } } // Last Step - Return path postition array for our pathing system to query self.pathPositions = newPath } func calculatePathPositions() { self.setupPathColliders() self.convertPathNodesIntoPathPositions() self.resamplePathPositions() } /*! Given a relative percent along the path, return back the world location vector */ func locationAlongPath(percent: CGFloat) -> SCNVector3 { if (self.pathPositions.count <= 3) { return SCNVector3Make(0,0,0) } let numSections: Int = self.pathPositions.count - 3 var dist = CGFloat(percent) * CGFloat(numSections) // If dist is negative, casting to UInt will wrap it around to a huge number, and we will select the end of the section instead let currentPointIndex = Int(min(UInt(floor(dist)), UInt(numSections - 1))) dist -= CGFloat(currentPointIndex) let a: GLKVector3 = SCNVector3ToGLKVector3(self.pathPositions[currentPointIndex]) let b: GLKVector3 = SCNVector3ToGLKVector3(self.pathPositions[currentPointIndex + 1]) let c: GLKVector3 = SCNVector3ToGLKVector3(self.pathPositions[currentPointIndex + 2]) let d: GLKVector3 = SCNVector3ToGLKVector3(self.pathPositions[currentPointIndex + 3]) var location:SCNVector3 = SCNVector3() location.x = catmullRomValue(CGFloat(a.x), CGFloat(b.x), CGFloat(c.x), CGFloat(d.x), dist) location.y = catmullRomValue(CGFloat(a.y), CGFloat(b.y), CGFloat(c.y), CGFloat(d.y), dist) location.z = catmullRomValue(CGFloat(a.z), CGFloat(b.z), CGFloat(c.z), CGFloat(d.z), dist) return location } /*! Direction player facing given the current walking direction */ func getDirectionFromPosition(currentPosition: SCNVector3) -> SCNVector4 { let target:SCNVector3 = self.locationAlongPath(self.timeAlongPath - 0.05) let lookat: GLKMatrix4 = GLKMatrix4MakeLookAt(Float(currentPosition.x), Float(currentPosition.y), Float(currentPosition.z), Float(target.x), Float(target.y), Float(target.z), 0.0, 1.0, 0.0) let q: GLKQuaternion = GLKQuaternionMakeWithMatrix4(lookat) var angle: CGFloat = CGFloat(GLKQuaternionAngle(q)) if (self.playerCharacter!.walkDirection == .Left) { angle -= CGFloat(M_PI) } return SCNVector4Make(0, 1, 0, angle) } /* Helper method for getting main player's direction */ func getPlayerDirectionFromCurrentPosition() -> SCNVector4 { return self.getDirectionFromPosition(self.playerCharacter!.position) } /*! Create an action that pulses the opacity of a node */ func pulseAction() -> SCNAction { let duration: NSTimeInterval = 8.0 / 6.0 let pulseAction: SCNAction = SCNAction.repeatActionForever( SCNAction.sequence([SCNAction.fadeOpacityTo(0.3, duration: duration), SCNAction.fadeOpacityTo(0.5, duration: duration), SCNAction.fadeOpacityTo(1.0, duration: duration), SCNAction.fadeOpacityTo(0.7, duration: duration), SCNAction.fadeOpacityTo(0.4, duration: duration), SCNAction.fadeOpacityTo(0.8, duration: duration)])) return pulseAction } /*! Create a simple point light */ func torchLight() -> SCNLight { let light: SCNLight = SCNLight() light.type = SCNLightTypeOmni light.color = SKColor.orangeColor() light.attenuationStartDistance = 350 light.attenuationEndDistance = 400 light.attenuationFalloffExponent = 1 return light } func animateDynamicNodes() { var dynamicNodesWithVertColorAnimation: [SCNNode] = [] self.rootNode.enumerateChildNodesUsingBlock { (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in if let _pnode = child.parentNode, _name = _pnode.name, nodeIsVine = _name.rangeOfString("vine") { if let _geometry = child.geometry where _geometry.geometrySourcesForSemantic(SCNGeometrySourceSemanticColor) != nil { dynamicNodesWithVertColorAnimation.append(child) } } } // Animate the dynamic node let shaderCode: String = "uniform float timeOffset;\n" + "#pragma body\n" + "float speed = 20.05;\n" + "_geometry.position.xyz += (speed * sin(u_time + timeOffset) * _geometry.color.rgb);\n" for dynamicNode: SCNNode in dynamicNodesWithVertColorAnimation { dynamicNode.geometry?.shaderModifiers = [SCNShaderModifierEntryPointGeometry : shaderCode] let explodeAnimation: CABasicAnimation = CABasicAnimation(keyPath: "timeOffset") explodeAnimation.duration = 2.0 explodeAnimation.repeatCount = FLT_MAX explodeAnimation.autoreverses = true explodeAnimation.toValue = AAPLRandomPercent() explodeAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) dynamicNode.geometry?.addAnimation(explodeAnimation, forKey: "sway") } } func collideWithLava() { if (hitByLavaReset == true) { return } self.playerCharacter?.inRunAnimation = false AAPLGameSimulation.sim.playSound("ack.caf") //Blink for a second let blinkOffAction = SCNAction.fadeOutWithDuration(0.15) let blinkOnAction = SCNAction.fadeInWithDuration(0.15) let cycle = SCNAction.sequence([blinkOffAction, blinkOnAction]) let repeatCycle = SCNAction.repeatAction(cycle, count: 7) self.hitByLavaReset = true self.playerCharacter?.runAction(repeatCycle, completionHandler: { () -> Void in self.timeAlongPath = 0 self.playerCharacter?.position = self.locationAlongPath(self.timeAlongPath) self.playerCharacter?.rotation = self.getPlayerDirectionFromCurrentPosition() self.hitByLavaReset = false }) } func moveCharacterAlongPathWith(deltaTime: NSTimeInterval, currentState: AAPLGameState) { if self.playerCharacter?.isRunning == true { if currentState == .InGame { var currWalkSpeed = self.playerCharacter!.walkSpeed if self.playerCharacter!.isJumping == true { currWalkSpeed += self.playerCharacter!.jumpBoost } self.timeAlongPath += CGFloat(CGFloat(deltaTime) * currWalkSpeed * (self.playerCharacter?.walkDirection == .Right ? 1 : -1)) // limit how far the player can go in the left and right directions if (self.timeAlongPath < 0.0) { self.timeAlongPath = 0.0 } else if (self.timeAlongPath > 1.0) { self.timeAlongPath = 1.0 } let newPosition = self.locationAlongPath(self.timeAlongPath) self.playerCharacter!.position = SCNVector3Make(newPosition.x, self.playerCharacter!.position.y, newPosition.z) if (self.timeAlongPath >= 1.0) { self.doGameOver() } } else { self.playerCharacter?.inRunAnimation = false } } } func updateSunLightPosition() { var lightPos = _lightOffsetFromCharacter if let charPos = self.playerCharacter?.position { lightPos.x += charPos.x lightPos.y += charPos.y lightPos.z += charPos.z self.sunLight.position = lightPos } } // MARK: Creation /*! Create a torch node that has a particle effect and point light attached */ func createTorchNode() -> SCNNode { // Trying to create static var in func // The alternative is to have a static var at the class level struct torch { static var template: SCNNode! } if (torch.template == nil) { torch.template = SCNNode() let geometry: SCNGeometry = SCNBox(width: 20, height: 100, length: 20, chamferRadius: 0) geometry.firstMaterial!.diffuse.contents = SKColor.brownColor() torch.template.geometry = geometry let particleEmitter: SCNNode = SCNNode() particleEmitter.position = SCNVector3Make(0, 50, 0) let fire: SCNParticleSystem = SCNParticleSystem(named: "torch.scnp", inDirectory: "art.scnassets/level/effects") particleEmitter.addParticleSystem(fire) particleEmitter.light = self.torchLight() torch.template.addChildNode(particleEmitter) } return torch.template.clone() as! SCNNode } /* Helper Method for loading Swinging Torch */ func createSwingingTorch() { // Load the dae from disk if let torchSwing = AAPLGameSimulation.loadNodeWithName("dummy_master", fromSceneNamed: AAPLGameSimulation.pathForArtResource("level/torch.dae")) { // Attach to origin self.rootNode?.addChildNode(torchSwing) } } /* Create Lava Animation */ func createLavaAnimation() { // Find lava nodes in the scene let lavaNodes : [SCNNode] = self.rootNode?.childNodesPassingTest({ (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Bool in if let _cname = child.name where _cname.hasPrefix("lava_0") { return true } return false }) as! [SCNNode] // Add concave collider to each lava mesh for lava: SCNNode in lavaNodes { let childrenWithGeometry: [SCNNode] = lava.childNodesPassingTest({ (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Bool in if (child.geometry != nil) { stop.memory = true return true } return false }) as! [SCNNode] let lavaGeometry: SCNNode = childrenWithGeometry[0] lavaGeometry.physicsBody = SCNPhysicsBody(type: .Static, shape: SCNPhysicsShape(geometry: lavaGeometry.geometry!, options: [SCNPhysicsShapeTypeKey : SCNPhysicsShapeTypeConcavePolyhedron])) lavaGeometry.physicsBody?.categoryBitMask = GameCollisionCategory.Lava lavaGeometry.categoryBitMask = NodeCategory.Lava // UV animate the lava texture in the vertex shader let shaderCode = "uniform float speed;\n" + "#pragma body\n" + "_geometry.texcoords[0] += vec2(sin(_geometry.position.z+0.1 + u_time * 0.1) * 0.1, -1.0 * 0.05 * u_time);\n" lavaGeometry.geometry?.shaderModifiers = [SCNShaderModifierEntryPointGeometry : shaderCode] } } /*! Helper Method for creating a large banana Create model, Add particle system, Add persistent SKAction, Add / Setup collision */ func createLargeBanana() -> SCNNode? { if (self.largeBananaCollectable == nil) { if let _lbanana = AAPLGameSimulation.loadNodeWithName("banana", fromSceneNamed: AAPLGameSimulation.pathForArtResource("level/banana.dae")) { _lbanana.scale = SCNVector3Make(BANANA_SCALE_LARGE, BANANA_SCALE_LARGE, BANANA_SCALE_LARGE) let sphereGeometry = SCNSphere(radius: 100) let physicsShape = SCNPhysicsShape(geometry: sphereGeometry, options: nil) _lbanana.physicsBody = SCNPhysicsBody(type: .Kinematic, shape: physicsShape) // only collide with player and ground _lbanana.physicsBody?.collisionBitMask = GameCollisionCategory.Player | GameCollisionCategory.Ground // Declare self in the coin category _lbanana.physicsBody?.categoryBitMask = GameCollisionCategory.Coin // Rotate forever let rotateCoin = SCNAction.rotateByX(0, y: 8, z: 0, duration: 2.0) let repeat = SCNAction.repeatActionForever(rotateCoin) _lbanana.rotation = SCNVector4Make(0.0, 1.0, 0.0, CGFloat(M_PI_2)) _lbanana.runAction(repeat) self.largeBananaCollectable = _lbanana } } let node = self.largeBananaCollectable?.clone() as? SCNNode if let newSystem = AAPLGameSimulation.loadParticleSystemWithName("sparkle") { node?.addParticleSystem(newSystem) } return node } /*! Helper Method for creating a small banana */ func createBanana() -> SCNNode? { // Create model if (self.bananaCollectable == nil) { if let _banana = AAPLGameSimulation.loadNodeWithName("banana", fromSceneNamed: AAPLGameSimulation.pathForArtResource("level/banana.dae")) { _banana.scale = SCNVector3Make(BANANA_SCALE, BANANA_SCALE, BANANA_SCALE) let sphereGeometry = SCNSphere(radius: 40) let physicsShape = SCNPhysicsShape(geometry: sphereGeometry, options: nil) _banana.physicsBody = SCNPhysicsBody(type: .Kinematic, shape: physicsShape) // only collide with player and ground _banana.physicsBody!.collisionBitMask = GameCollisionCategory.Player | GameCollisionCategory.Ground // Declare self in the banana category _banana.physicsBody!.categoryBitMask = GameCollisionCategory.Banana // Rotate and Hover forever _banana.rotation = SCNVector4Make(0.5, 1.0, 0.5, CGFloat(-M_PI_2)) let idleHoverGroupAction = SCNAction.group([self.bananaIdleAction, self.hoverAction]) let repeatForeverAction = SCNAction.repeatActionForever(idleHoverGroupAction) _banana.runAction(repeatForeverAction) self.bananaCollectable = _banana } } return self.bananaCollectable?.clone() as? SCNNode } // CreateLevel func createLevel() -> SCNNode? { // // Load the level dae from disk // Setup and construct the level. ( Should really be done offline in an editor ). self.rootNode = SCNNode() // load level dae and add root children to the scene let scene: SCNScene? = SCNScene(named: "level.dae", inDirectory: AAPLGameSimulation.pathForArtResource("level/"), options: [SCNSceneSourceConvertToYUpKey : true]) for node: SCNNode in scene?.rootNode.childNodes as! [SCNNode] { self.rootNode.addChildNode(node) } // retrieve main camera self.camera = self.rootNode.childNodeWithName("camera_game", recursively: true) // create our path that the player character will follow self.calculatePathPositions() // sun/Moon light self.sunLight = self.rootNode.childNodeWithName("FDirect001", recursively: true) self.sunLight.eulerAngles = SCNVector3Make(CGFloat(7.1 * M_PI_4), CGFloat(M_PI_4), 0) self.sunLight.light?.shadowSampleCount = 1 _lightOffsetFromCharacter = SCNVector3Make(1500, 2000, 1000) // workaround directional light deserialization issue self.sunLight.light?.zNear = 100 self.sunLight.light?.zFar = 5000 self.sunLight.light?.orthographicScale = 1000 if (self.isHighEnd() == false) { // use blob shadows on low end devices self.sunLight.light?.shadowMode = SCNShadowMode.Modulated self.sunLight.light?.categoryBitMask = 0x2 self.sunLight.light?.orthographicScale = 60 self.sunLight.eulerAngles = SCNVector3Make(CGFloat(M_PI_2), 0, 0) _lightOffsetFromCharacter = SCNVector3Make(0, 2000, 0) self.sunLight.light?.gobo.contents = "art.scnassets/techniques/blobShadow.jpg" self.sunLight.light?.gobo.intensity = 0.5 let middle: SCNNode = self.rootNode.childNodeWithName("dummy_front", recursively: true)! middle.enumerateChildNodesUsingBlock({ (child:SCNNode!, stop:UnsafeMutablePointer<ObjCBool>) -> Void in child.categoryBitMask = 0x2 }) } // Torches let torchPos: [CGFloat] = [0, -1, 0.092467, -1, -1, 0.5, 0.7920, 0.953830] for i in 0 ..< 8 { if (torchPos[i] == -1) { continue } var location: SCNVector3 = self.locationAlongPath(torchPos[i]) location.y += 50 location.z += 150 let node: SCNNode = self.createTorchNode() node.position = location self.rootNode.addChildNode(node) } // After load, we add nodes that are dynamic / animated / not static self.createLavaAnimation() self.createSwingingTorch() self.animateDynamicNodes() // Create player character if let characterRoot = AAPLGameSimulation.loadNodeWithName(nil, fromSceneNamed: "art.scnassets/characters/explorer/explorer_skinned.dae") { self.playerCharacter = AAPLPlayerCharacter(characterNode: characterRoot) self.timeAlongPath = 0 self.playerCharacter!.position = self.locationAlongPath(self.timeAlongPath) self.playerCharacter!.rotation = self.getPlayerDirectionFromCurrentPosition() self.rootNode.addChildNode(self.playerCharacter!) } // Optimize lighting and shadows // only the character should cast shadows self.rootNode.enumerateChildNodesUsingBlock( { (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in child.castsShadow = false }) self.playerCharacter?.enumerateChildNodesUsingBlock( { (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in child.castsShadow = true }) // Add some monkeys to the scene self.addMonkeyAtPosition(SCNVector3Make(0, -30, -400), rotation: 0) self.addMonkeyAtPosition(SCNVector3Make(3211, 146, -400), rotation: CGFloat(-M_PI_4)) self.addMonkeyAtPosition(SCNVector3Make(5200, 330, 600), rotation: 0) // Volcano var oldVolcano = self.rootNode.childNodeWithName("volcano", recursively: true) let volcanoDaeName = AAPLGameSimulation.pathForArtResource("level/volcano_effects.dae") let newVolcano = AAPLGameSimulation.loadNodeWithName("dummy_master", fromSceneNamed: volcanoDaeName) if (newVolcano != nil) { oldVolcano?.addChildNode(newVolcano!) oldVolcano?.geometry = nil oldVolcano = newVolcano!.childNodeWithName("volcano", recursively: true) } oldVolcano = oldVolcano?.childNodes[0] as? SCNNode // Animate our dynamic volcano node let shaderCode = "uniform float speed;\n" + "_geometry.color = vec4(a_color.r, a_color.r, a_color.r, a_color.r);\n" + "_geometry.texcoords[0] += (vec2(0.0, 1.0) * 0.05 * u_time);\n" let fragmentShadeCode = "#pragma transparent\n" // dim background let back = self.rootNode.childNodeWithName("dummy_rear", recursively: true) back?.enumerateChildNodesUsingBlock({ (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in child.castsShadow = false if let _geometry = child.geometry { for material in _geometry.materials as! [SCNMaterial] { material.lightingModelName = SCNLightingModelConstant material.multiply.contents = SKColor(white: 0.3, alpha: 1.0) material.multiply.intensity = 1 } } }) // remove lighting from middle plane let middle = self.rootNode.childNodeWithName("dummy_middle", recursively: true) middle?.enumerateChildNodesUsingBlock({ (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in if let _geometry = child.geometry { for material in _geometry.materials as! [SCNMaterial] { material.lightingModelName = SCNLightingModelConstant } } }) if (newVolcano != nil) { newVolcano!.enumerateChildNodesUsingBlock({ (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in if let _geometry = child.geometry where child != oldVolcano { _geometry.firstMaterial?.lightingModelName = SCNLightingModelConstant _geometry.firstMaterial?.multiply.contents = SKColor.whiteColor() _geometry.shaderModifiers = [SCNShaderModifierEntryPointGeometry : shaderCode, SCNShaderModifierEntryPointFragment : fragmentShadeCode] } }) } if (self.isHighEnd() == false) { self.rootNode.enumerateChildNodesUsingBlock({ (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in if let _geometry = child.geometry { for m in _geometry.materials as! [SCNMaterial] { m.lightingModelName = SCNLightingModelConstant } } }) self.playerCharacter?.enumerateChildNodesUsingBlock({ (child: SCNNode!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in if let _geometry = child.geometry { for m in _geometry.materials as! [SCNMaterial] { m.lightingModelName = SCNLightingModelLambert } } }) } self.coconuts = [] return self.rootNode! } /*! Reset the game simulation for the start of the game or restart after you have completed the level. */ func resetLevel() { score = 0 secondsRemaining = 120 coinsCollected = 0 bananasCollected = 0 timeAlongPath = 0 self.playerCharacter?.position = self.locationAlongPath(timeAlongPath) self.playerCharacter?.rotation = self.getPlayerDirectionFromCurrentPosition() self.hitByLavaReset = false // Remove dynamic objects from the level SCNTransaction.begin() if let _coconuts = self.coconuts { for b in _coconuts { b.removeFromParentNode() } } if let _bananas = self.bananas { for b in _bananas { b.removeFromParentNode() } } if let _largeBananas = self.largeBananas { for b in _largeBananas { b.removeFromParentNode() } } SCNTransaction.commit() // Add dynamic objects to the level, like bananas and large bananas self.coconuts = [] self.bananas = [] for i in 0 ..< 10 { if let banana = self.createBanana() { self.rootNode.addChildNode(banana) var location = self.locationAlongPath(CGFloat((Float(i)+1.0)/20.0 - 0.01)) location.y += 50 banana.position = location self.bananas!.insert(banana) } } self.largeBananas = [] for i in 0 ..< 6 { if let largeBanana = self.createLargeBanana() { self.rootNode.addChildNode(largeBanana) var location = self.locationAlongPath(AAPLRandomPercent()) location.y += 50 largeBanana.position = location self.largeBananas!.insert(largeBanana) } } AAPLGameSimulation.sim.playMusic("music.caf") AAPLGameSimulation.sim.playMusic("night.caf") } /*! Given a world position and rotation, load the monkey dae and place it in the world */ func addMonkeyAtPosition(worldPos: SCNVector3, rotation: CGFloat) { if self.monkeys == nil { self.monkeys = [] } let palmTree = self.createMonkeyPalmTree() palmTree.position = worldPos palmTree.rotation = SCNVector4Make(0, 1, 0, rotation) self.rootNode.addChildNode(palmTree) if let monkey = palmTree.childNodeWithName("monkey", recursively: true) as? AAPLMonkeyCharacter { self.monkeys!.append(monkey) } } /*! Load the palm tree that the monkey is attached to */ func createMonkeyPalmTree() -> SCNNode { // Trying to create static var in func // The alternative is to have a static var at the class level struct tree { static var palmTreeProtoObject: SCNNode! } if (tree.palmTreeProtoObject == nil) { let palmTreeDae = AAPLGameSimulation.pathForArtResource("characters/monkey/monkey_palm_tree.dae") tree.palmTreeProtoObject = AAPLGameSimulation.loadNodeWithName("PalmTree", fromSceneNamed: palmTreeDae) } let palmTree = tree.palmTreeProtoObject.clone() as! SCNNode if let monkeyNode = AAPLGameSimulation.loadNodeWithName(nil, fromSceneNamed: "art.scnassets/characters/monkey/monkey_skinned.dae") { let monkey = AAPLMonkeyCharacter(characterRootNode: monkeyNode) monkey.createAnimations() palmTree.addChildNode(monkey) } return palmTree } /*! Change the game state to the postgame */ func doGameOver() { self.playerCharacter?.inRunAnimation = false AAPLGameSimulation.sim.gameState = AAPLGameState.PostGame } /*! Main game logic */ func update(deltaTime: NSTimeInterval, aRenderer: SCNSceneRenderer) { // Based on gamestate: // ingame: Move character if running // ingame: prevent movement of character past level bounds // ingame: perform logic for player char // any: move directional light with any player movement // ingame: update the coconuts kinematically // ingame: perform logic for each monkey // ingame: because our camera could have moved, update the transforms to fly // collected bananas from the player (world space) to score (screen space) let appDelegate = AAPLAppDelegate.sharedAppDelegate let currentState = AAPLGameSimulation.sim.gameState // Move character along path if walking self.moveCharacterAlongPathWith(deltaTime, currentState: currentState) // Based on the time along path, rotate the character to face correct direction self.playerCharacter?.rotation = self.getPlayerDirectionFromCurrentPosition() if (currentState == .InGame) { self.playerCharacter?.update(deltaTime) } // move the light self.updateSunLightPosition() if (currentState == .PreGame || currentState == .PostGame || currentState == .Paused) { return } // update Monkeys if let _monkeys = self.monkeys as [AAPLMonkeyCharacter]? { for monkey in _monkeys { monkey.update(deltaTime) } } // Update timer and check for Game Over secondsRemaining -= deltaTime if (secondsRemaining < 0.0) { self.doGameOver() } // update the player's SP position if (self.playerCharacter != nil) { let playerPosition = AAPLMatrix4GetPosition(self.playerCharacter!.worldTransform) _screenSpaceplayerPosition = appDelegate.scnView.projectPoint(playerPosition) // update the SP position of the score label let pt = self.scoreLabelLocation _worldSpaceLabelScorePosition = appDelegate.scnView.unprojectPoint( SCNVector3Make(pt.x, pt.y, _screenSpaceplayerPosition.z)) } } func collectBanana(banana: SCNNode) { // Flyoff the banana to the screen space position score label // Don't increment score until the banana hits the score label // ignore collisions banana.physicsBody = nil self.bananasCollected++ let variance = 60 let apexY: CGFloat = (_worldSpaceLabelScorePosition.y * 0.8) + CGFloat((Int(rand()) % variance) - (variance / 2)) _worldSpaceLabelScorePosition.z = banana.position.z let apex = SCNVector3Make( banana.position.x + 10.0 + CGFloat((Int(rand()) % variance) - (variance / 2)), apexY, banana.position.z) let startFlyOff = SCNAction.moveTo(apex, duration: 0.25) startFlyOff.timingMode = SCNActionTimingMode.EaseOut let duration: CGFloat = 0.25 let endFlyOff: SCNAction = SCNAction.customActionWithDuration(NSTimeInterval(duration), actionBlock: { (node: SCNNode!, elapsedTime: CGFloat) -> Void in let t = elapsedTime / duration let v = SCNVector3Make( apex.x + ((self._worldSpaceLabelScorePosition.x - apex.x) * t), apex.y + ((self._worldSpaceLabelScorePosition.y - apex.y) * t), apex.z + ((self._worldSpaceLabelScorePosition.z - apex.x) * t)) node.position = v }) endFlyOff.timingMode = SCNActionTimingMode.EaseInEaseOut let flyoffSequence: SCNAction = SCNAction.sequence([startFlyOff, endFlyOff]) banana.runAction(flyoffSequence, completionHandler: { () -> Void in self.bananas?.remove(banana) banana.removeFromParentNode() // Add to score self.score++ AAPLGameSimulation.sim.playSound("deposit.caf") if (self.bananas?.count == 0) { // Game Over self.doGameOver() } }) } func collectLargeBanana(largeBanana: SCNNode) { // When a player hits a large banana, explode it into smaller bananas // We explode into a predefined pattern: square, diamond, letterA, letterB // ignore collisions largeBanana.physicsBody = nil self.coinsCollected++ self.largeBananas?.remove(largeBanana) largeBanana.removeAllParticleSystems() largeBanana.removeFromParentNode() // Add to score self.score += 100 let square = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] let diamond = [ 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0 ] let letterA = [ 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0 ] let letterB = [ 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0 ] let choices = [square, diamond, letterA, letterB] let vertSpacing: CGFloat = 40 let spacing: CGFloat = 0.0075 let choice = choices[Int(rand()) % choices.count] for y in 0 ..< 5 { for x in 0 ..< 5 { let place = choice[y*5 + x] if place != 1 { continue } if let _banana = self.createBanana() { self.rootNode.addChildNode(_banana) _banana.position = largeBanana.position _banana.physicsBody?.categoryBitMask = GameCollisionCategory.NoCollide _banana.physicsBody?.collisionBitMask = GameCollisionCategory.Ground var endPoint = self.locationAlongPath(self.timeAlongPath + (spacing * CGFloat(x+1))) endPoint.y += vertSpacing * CGFloat(y + 1) let flyoff = SCNAction.moveTo(endPoint, duration: Double(AAPLRandomPercent()) * 0.25) flyoff.timingMode = SCNActionTimingMode.EaseInEaseOut // Prevent collision until the banana gets to the final resting spot _banana.runAction(flyoff, completionHandler: { () -> Void in _banana.physicsBody?.categoryBitMask = GameCollisionCategory.Banana _banana.physicsBody?.collisionBitMask = GameCollisionCategory.Ground | GameCollisionCategory.Player AAPLGameSimulation.sim.playSound("deposit.caf") }) self.bananas?.insert(_banana) } } } } func collideWithCoconut(coconut: SCNNode, contactPoint:SCNVector3) { // No more collisions, let it bounce away and fade out coconut.physicsBody?.collisionBitMask = 0 coconut.runAction( SCNAction.sequence([SCNAction.waitForDuration(1.0), SCNAction.fadeOutWithDuration(1.0), SCNAction.removeFromParentNode()])) { self.coconuts?.remove(coconut) } // Decrement Score var amountToDrop: Int = self.score / 10 switch amountToDrop { case amountToDrop where amountToDrop < 1: amountToDrop = 1 case amountToDrop where amountToDrop > 10: amountToDrop = 10 case amountToDrop where amountToDrop > self.score: amountToDrop = self.score default: break } self.score -= amountToDrop // Throw Bananas let spacing = 40 for x in 0 ..< amountToDrop { if let _banana = self.createBanana() { self.rootNode.addChildNode(_banana) _banana.position = contactPoint _banana.physicsBody?.categoryBitMask = GameCollisionCategory.NoCollide _banana.physicsBody?.collisionBitMask = GameCollisionCategory.Ground var endPoint = SCNVector3Make(0, 0, 0) endPoint.x -= CGFloat((spacing * x) + spacing) let flyoff = SCNAction.moveTo(endPoint, duration: Double(AAPLRandomPercent()) * 0.75) flyoff.timingMode = SCNActionTimingMode.EaseInEaseOut // Prevent collision until the banana gets to the final resting spot _banana.runAction(flyoff, completionHandler: { () -> Void in _banana.physicsBody?.categoryBitMask = GameCollisionCategory.Banana _banana.physicsBody?.collisionBitMask = GameCollisionCategory.Ground | GameCollisionCategory.Player }) self.bananas?.insert(_banana) } } } }
gpl-2.0
5128c01bee8b6d37b3dd2d6469440b0f
39.786751
197
0.579718
4.792195
false
false
false
false
FearfulFox/sacred-tiles
Sacred Tiles/Scoring.swift
1
1345
// // Scoring.swift // Sacred Tiles // // Created by Fox on 3/9/15. // Copyright (c) 2015 eCrow. All rights reserved. // import Foundation; struct BoardScore { struct score { var match: UInt = 0; var miss: UInt = 0; var skill: UInt = 0; func getTotal()->Int64{ let net: Int64 = Int64(match) - Int64(miss + skill); return net; } } static var scores: [score] = []; static func reset(){ BoardScore.scores = []; } } struct TotalScore { static var match: UInt = 0; static var miss: UInt = 0; static var skill: UInt = 0; static var peak: UInt = 0; static func getTotal()->Int64{ let net: Int64 = Int64(match) - Int64(miss + skill); return net; } static func reset(){ TotalScore.match = 0; TotalScore.miss = 0; TotalScore.skill = 0; TotalScore.peak = 0; } } struct Scoring { // Base points for a matching two tiles. static let match: UInt = 99; // Tile matching streak modifier. static let matchMod: Double = 0.05; // Base points for miss-matching a tile. static let miss: UInt = 40; // Modifier for every time a tile is miss-matched. static let missMod: Double = 0.15; }
gpl-2.0
add21c0c68a63d24123ccba05bd60a39
19.393939
64
0.543494
3.746518
false
false
false
false
badoo/Chatto
ChattoAdditions/sources/Chat Items/BaseMessage/BaseMessagePresenter.swift
1
11204
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import Chatto public protocol ViewModelBuilderProtocol { associatedtype ModelT: MessageModelProtocol associatedtype ViewModelT: MessageViewModelProtocol func canCreateViewModel(fromModel model: Any) -> Bool func createViewModel(_ model: ModelT) -> ViewModelT } public protocol BaseMessageInteractionHandlerProtocol { associatedtype MessageType associatedtype ViewModelType func userDidTapOnFailIcon(message: MessageType, viewModel: ViewModelType, failIconView: UIView) func userDidTapOnAvatar(message: MessageType, viewModel: ViewModelType) func userDidTapOnBubble(message: MessageType, viewModel: ViewModelType) func userDidDoubleTapOnBubble(message: MessageType, viewModel: ViewModelType) func userDidBeginLongPressOnBubble(message: MessageType, viewModel: ViewModelType) func userDidEndLongPressOnBubble(message: MessageType, viewModel: ViewModelType) func userDidSelectMessage(message: MessageType, viewModel: ViewModelType) func userDidDeselectMessage(message: MessageType, viewModel: ViewModelType) } open class BaseMessagePresenter<BubbleViewT, ViewModelBuilderT, InteractionHandlerT>: BaseChatItemPresenter<BaseMessageCollectionViewCell<BubbleViewT>> where ViewModelBuilderT: ViewModelBuilderProtocol, InteractionHandlerT: BaseMessageInteractionHandlerProtocol, InteractionHandlerT.MessageType == ViewModelBuilderT.ModelT, InteractionHandlerT.ViewModelType == ViewModelBuilderT.ViewModelT, BubbleViewT: UIView, BubbleViewT: MaximumLayoutWidthSpecificable, BubbleViewT: BackgroundSizingQueryable { public typealias CellT = BaseMessageCollectionViewCell<BubbleViewT> public typealias ModelT = ViewModelBuilderT.ModelT public typealias ViewModelT = ViewModelBuilderT.ViewModelT public init ( messageModel: ModelT, viewModelBuilder: ViewModelBuilderT, interactionHandler: InteractionHandlerT?, sizingCell: BaseMessageCollectionViewCell<BubbleViewT>, cellStyle: BaseMessageCollectionViewCellStyleProtocol) { self.messageModel = messageModel self.sizingCell = sizingCell self.viewModelBuilder = viewModelBuilder self.cellStyle = cellStyle self.interactionHandler = interactionHandler } public internal(set) var messageModel: ModelT { didSet { self.messageViewModel = self.createViewModel() } } open override var isItemUpdateSupported: Bool { /* By default, item updates are not supported. But this behaviour could be changed by the descendants. In this case, an update method checks item type, sets a new value for a message model and creates a new message view model. */ return false } open override func update(with chatItem: ChatItemProtocol) { assert(self.isItemUpdateSupported, "Updated is called on presenter which doesn't support updates: \(type(of: chatItem)).") guard let newMessageModel = chatItem as? ModelT else { assertionFailure("Unexpected type of the message: \(type(of: chatItem))."); return } self.messageModel = newMessageModel } public let sizingCell: BaseMessageCollectionViewCell<BubbleViewT> public let viewModelBuilder: ViewModelBuilderT public let interactionHandler: InteractionHandlerT? public let cellStyle: BaseMessageCollectionViewCellStyleProtocol public private(set) final lazy var messageViewModel: ViewModelT = self.createViewModel() open func createViewModel() -> ViewModelT { let viewModel = self.viewModelBuilder.createViewModel(self.messageModel) return viewModel } public final override func configureCell(_ cell: UICollectionViewCell, decorationAttributes: ChatItemDecorationAttributesProtocol?) { guard let cell = cell as? CellT else { assert(false, "Invalid cell given to presenter") return } guard let decorationAttributes = decorationAttributes as? ChatItemDecorationAttributes else { assert(false, "Expecting decoration attributes") return } self.decorationAttributes = decorationAttributes self.configureCell(cell, decorationAttributes: decorationAttributes, animated: false, additionalConfiguration: nil) } public var decorationAttributes: ChatItemDecorationAttributes! open func configureCell(_ cell: CellT, decorationAttributes: ChatItemDecorationAttributes, animated: Bool, additionalConfiguration: (() -> Void)?) { cell.performBatchUpdates({ () -> Void in self.messageViewModel.decorationAttributes = decorationAttributes.messageDecorationAttributes // just in case something went wrong while showing UIMenuController self.messageViewModel.isUserInteractionEnabled = true cell.baseStyle = self.cellStyle cell.messageViewModel = self.messageViewModel cell.allowRevealing = !decorationAttributes.messageDecorationAttributes.isShowingSelectionIndicator cell.onBubbleTapped = { [weak self] (cell) in guard let sSelf = self else { return } sSelf.onCellBubbleTapped() } cell.onBubbleDoubleTapped = { [weak self] (cell) in guard let sSelf = self else { return } sSelf.onCellBubbleDoubleTapped() } cell.onBubbleLongPressBegan = { [weak self] (cell) in guard let sSelf = self else { return } sSelf.onCellBubbleLongPressBegan() } cell.onBubbleLongPressEnded = { [weak self] (cell) in guard let sSelf = self else { return } sSelf.onCellBubbleLongPressEnded() } cell.onAvatarTapped = { [weak self] (cell) in guard let sSelf = self else { return } sSelf.onCellAvatarTapped() } cell.onFailedButtonTapped = { [weak self] (cell) in guard let sSelf = self else { return } sSelf.onCellFailedButtonTapped(cell.failedButton) } cell.onSelection = { [weak self] (cell) in guard let sSelf = self else { return } sSelf.onCellSelection() } additionalConfiguration?() }, animated: animated, completion: nil) } open override func heightForCell(maximumWidth width: CGFloat, decorationAttributes: ChatItemDecorationAttributesProtocol?) -> CGFloat { guard let decorationAttributes = decorationAttributes as? ChatItemDecorationAttributes else { assert(false, "Expecting decoration attributes") return 0 } self.configureCell(self.sizingCell, decorationAttributes: decorationAttributes, animated: false, additionalConfiguration: nil) return self.sizingCell.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height } open override var canCalculateHeightInBackground: Bool { return self.sizingCell.canCalculateSizeInBackground } open override func cellWillBeShown() { self.messageViewModel.willBeShown() } open override func cellWasHidden() { self.messageViewModel.wasHidden() } open override func shouldShowMenu() -> Bool { guard self.canShowMenu() else { return false } guard let cell = self.cell else { assert(false, "Investigate -> Fix or remove assert") return false } cell.bubbleView.isUserInteractionEnabled = false // This is a hack for UITextView, shouldn't harm to all bubbles NotificationCenter.default.addObserver(self, selector: #selector(BaseMessagePresenter.willShowMenu(_:)), name: UIMenuController.willShowMenuNotification, object: nil) return true } @objc func willShowMenu(_ notification: Notification) { NotificationCenter.default.removeObserver(self, name: UIMenuController.willShowMenuNotification, object: nil) guard let cell = self.cell, let menuController = notification.object as? UIMenuController else { assert(false, "Investigate -> Fix or remove assert") return } cell.bubbleView.isUserInteractionEnabled = true menuController.setMenuVisible(false, animated: false) menuController.setTargetRect(cell.bubbleView.bounds, in: cell.bubbleView) menuController.setMenuVisible(true, animated: true) } open func canShowMenu() -> Bool { // Override in subclass return false } open func onCellBubbleTapped() { self.interactionHandler?.userDidTapOnBubble(message: self.messageModel, viewModel: self.messageViewModel) } open func onCellBubbleDoubleTapped() { self.interactionHandler?.userDidDoubleTapOnBubble(message: self.messageModel, viewModel: self.messageViewModel) } open func onCellBubbleLongPressBegan() { self.interactionHandler?.userDidBeginLongPressOnBubble(message: self.messageModel, viewModel: self.messageViewModel) } open func onCellBubbleLongPressEnded() { self.interactionHandler?.userDidEndLongPressOnBubble(message: self.messageModel, viewModel: self.messageViewModel) } open func onCellAvatarTapped() { self.interactionHandler?.userDidTapOnAvatar(message: self.messageModel, viewModel: self.messageViewModel) } open func onCellFailedButtonTapped(_ failedButtonView: UIView) { self.interactionHandler?.userDidTapOnFailIcon(message: self.messageModel, viewModel: self.messageViewModel, failIconView: failedButtonView) } open func onCellSelection() { if self.messageViewModel.decorationAttributes.isSelected { self.interactionHandler?.userDidDeselectMessage(message: self.messageModel, viewModel: self.messageViewModel) } else { self.interactionHandler?.userDidSelectMessage(message: self.messageModel, viewModel: self.messageViewModel) } } }
mit
26a98c849be500b6d1d86741f232674e
44.918033
174
0.717155
5.546535
false
false
false
false
HowardLei/First-Proj
one/one/ViewController.swift
1
7102
// // ViewController.swift // one // // Created by jyz on 2017/10/20. // Copyright © 2017年 jyz. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //demo() //demo1() //demo3(x: nil, y: nil) //demo2() //demo4() //demo5() //demo6(name: "DB",age: 18) //demo7(x:"Arsenal",y:"NYC",z: 65) //demo8() //demo9() //demo10() //demo11() //demo12() //demo13() //demo14() demo15() } func demo() { let name: String?="NB" print(name ?? "" + "你好")//= print(name ?? ("" + "你好")) print((name ?? "") + "你好") print(name!) } func demo1() { let x: String?="1" let y: String = "FIFA" let z: String = "ok" print(x ?? y + z) print((x ?? y) + z) //print(x + y ?? z) 这个三目不一样,??只能用于一个可选项中的两个值的选择 } func demo3(x: Int?, y: Int?) { print((x ?? 0) + (y ?? 0)) } func demo2() { let x : String?="ManCity" print(x ?? "Arsenal") } func demo4() { let oName: String? = "Chelsea" let oAge: String? = "champion" let oNumber: Int? = 10 if let name = oName, let age = oAge,var number = oNumber { //这个分支中,name 和 age一定有值,不需要解包 number = 20 print(name + age + String(number))//加的时候注意是不是同类型,不是的话统一换成string } //重要if let/var 连用语法,目的就是判断值 //其中if let 判断对象值是否为nil //if var 在'{}'修改值 } func demo5() { let oName: String? = "Chelsea" let oAge: String? = "champion" guard let name = oName,let age = oAge else { print("nil") return } print(name + age) //在guard let连用语法中,正好与if let相反,作用域在'else{}'外,else里面才是判断对的输出 } func demo6(name:String?, age: Int?) { if let name = name, let age = age { print(name + String(age)) } guard let name = name, let age = age else { () return } print(name + String(age)) } func demo7(x:String?,y:String?,z:Int?) { if let name = x , let city = y , let number = z { print(name + city + String(number)) } guard let name = x , let city = y , let number = z else { print("nil") return } print(name + city + String(number)) } func demo8(){ //正序 for i in (0..<23){ print(i) } //反序 for i in (0..<23).reversed(){ print(i) } } func demo9() //字符串的数量 { let str = "hello world" print(str.lengthOfBytes(using: .utf8)) //返回指定编码对应的字节数量,其中在utf8中,一个汉字3个字符 print(str.characters.count) //字符串长度-返回字符个数 let ocStr = str as NSString //as是用来进行类型转换的 print(ocStr.length) } func demo10() -> () //为啥这要指括号 字符串的拼接 { let name = "Howard" let age = 18 let point = CGPoint(x: 100, y:200)//这个cgpoint又是什么鬼? let thing :Optional = "Boss" //在拼接字符串中,小心可选项,如果不用三目,会出现optional let str = "\(name) \(age) \(point) \(thing ?? "")" //本身是用来 ??用于防止使用!,用三目来进行运算 print(str) } func demo11() -> () //为啥前面不加demo不报错? { let h = 19 let m = 26 let s = 02 let dateStr = "\(h):\(m):\(s)" let dateStr1 = String(format: "%02d:%02d:%02d",h , m, s) //使用格式字符串将其格式化 print(dateStr1) print(dateStr) } func demo12() //关于字符串的子串, { //1.用NSString作为中转,再取子串 let str = "running" let ocStr = str as NSString let s1 = ocStr.substring(with: NSMakeRange(2, 3)) let s4 = ocStr.substring(with: NSMakeRange(0, 4))//从第n-1个开始计算,不要搞混了 print(s1) print(s4) print(str.characters.count) //2.直接用swift3.0方法取(容易出现问题,知道有这回事就行) //语法:str.substring(from:"".endIndex) let s2 = str.substring(from: "run".endIndex) let s3 = str.substring(from: "abc".endIndex) print(str.startIndex)//这个代码print出来会显示position = 0 print(str.endIndex)//这个代码print出来会显示position = 7,因为running一共7个数字,这是取到最后一位 print(s2) print(s3) } func demo13() { let array = [1, 2, 3, 4, 5] //标准Int数组 print(array) let array1 = ["Arsenal", "ManCity", "Chelsea"] print(array1) //这两个都是经过swift自动推导的结果,'[]'内的数据都是同种数据类型。 //混合数组:开发的时候几乎不用,因为数组是靠下标索引 //在swift中,一般混合数组都是[anyObject]->任意对象 //在swift中,一个类可以没有任何‘父类’ //CG 结构体 这是用来干嘛的? let p = CGPoint(x: 10, y: 300) let array3 = [p] print(array3) } func demo14() //数组的遍历 { let array = ["east", "west", "north"] //1.按照下标遍历 啥叫下标遍历? for i in 0..<array.count { print(array[i]) } //2.利用for in 遍历元素 for s in array { print(s) } //3.用enum block遍历,同时遍历下标和内容 for e in array.enumerated() { //enumerated 本意是枚举 print("\(e.offset) \(e.element)") //for后面是啥就是啥.offset 啥.element } //4.遍历下标和内容2 for (n, s) in array.enumerated() { print("\(n) \(s)") } //5.反序遍历 直接在array后加.reversed() for s in array.reversed() { print(s) } //如果带序号的 print("--这是正确的") for e in array.enumerated().reversed() { print("\(e.offset) \(e.element)") } print("____序号不对") for s in array.reversed().enumerated() { print("\(s.offset) \(s.element)") } } func demo15() // { var array = [Int]() //数组的初始化,如果不初始化,就没法对数组进行修改 array.append(2) //为什么只能追加一个? print(array) array } }
apache-2.0
5d38664572b432a9d4655951419039d6
26.243119
85
0.480384
3.198169
false
false
false
false
smart23033/boostcamp_iOS_bipeople
Bipeople/Bipeople/AppDelegate.swift
1
7169
// // AppDelegate.swift // Bipeople // // Created by BluePotato on 2017. 8. 7.. // Copyright © 2017년 BluePotato. All rights reserved. // import UIKit import RealmSwift import GoogleMaps import GooglePlaces @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { static let GOOGLE_API_KEY = "AIzaSyDHNdS74dfE2fMYP4CLMJ9wfipk4XZB7dw" var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { print(Realm.Configuration.defaultConfiguration.fileURL ?? "No path for realm") // FOR DEBUG UIApplication.shared.isStatusBarHidden = false // RealmHelper.deleteAll() // FOR DEBUG updatePublicPlaceInfoFromNetwork() /** * Add Google Map API Key */ GMSServices.provideAPIKey(AppDelegate.GOOGLE_API_KEY) GMSPlacesClient.provideAPIKey(AppDelegate.GOOGLE_API_KEY) // Override point for customization after application launch. let tabBarController = window!.rootViewController as! UITabBarController let navControllers = tabBarController.childViewControllers as! [UINavigationController] changeTheme(navigationControllers: navControllers) /* FOR DEBUG: 더미데이터 삽입 시작 */ // for i in 0 ..< 30 { // let record = Record(departure: "departure \(i)", // arrival: "arrival \(i)", // distance: Double(arc4random_uniform(1000)) / Double(10), // ridingTime: Double(arc4random_uniform(1000)) / Double(10), // restTime: Double(arc4random_uniform(1000)) / Double(10), // averageSpeed: Double(arc4random_uniform(1000)) / Double(10), // maximumSpeed: Double(arc4random_uniform(1000)) / Double(10), // calories: Double(arc4random_uniform(1000)) / Double(10)) // // RealmHelper.add(data: record) // } /* FOR DEBUG: 더미데이터 삽입 끝 */ 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } //MARK: ChangeTheme extension AppDelegate { func changeTheme(navigationControllers: [UINavigationController]) { UIApplication.shared.statusBarStyle = .lightContent UIApplication.shared.delegate?.window??.tintColor = UIColor.primary navigationControllers.forEach { (nvc) in nvc.topViewController?.navigationController?.navigationBar.isTranslucent = false nvc.topViewController?.navigationController?.navigationBar.barTintColor = UIColor.primary nvc.topViewController?.navigationController?.navigationBar.tintColor = .white nvc.topViewController?.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] } } } //MARK: GetPlaceInfo extension AppDelegate { func updatePublicPlaceInfoFromNetwork() { RealmHelper.deleteTable(of: PublicPlace.self) PublicPlace.fetchList(apiURL: .toiletURL, PublicToilet.self, success: { response in let toilets = response.searchPublicToiletPOIService.row.map { toilet -> PublicPlace in let place = PublicPlace() place.lat = toilet.y_Wgs84 place.lng = toilet.x_Wgs84 place.placeType = .toilet place.title = "공중 화장실" place.address = toilet.fName return place } let realm = try! Realm() try! realm.write { realm.add(toilets) } }) { error in print("Error in", error) // FOR DEBUG } PublicPlace.fetchList(apiURL : .wifiURL, PublicWiFi.self, success: { response in let wifis = response.publicWiFiPlaceInfo.row.map { wifi -> PublicPlace in let place = PublicPlace() place.lat = wifi.INSTL_Y place.lng = wifi.INSTL_X place.placeType = .wifi place.title = "공공 Wifi" place.address = wifi.PLACE_NAME return place } let realm = try! Realm() try! realm.write { realm.add(wifis) } }) { error in print("Error in", error) // FOR DEBUG } PublicPlace.fetchList(apiURL : .storeURL, PublicStore.self, success: { response in let stores = response.geoInfoBikeConvenientFacilitiesWGS.row.map { store -> PublicPlace in let place = PublicPlace() place.lat = Double(store.LAT) ?? 0.0 place.lng = Double(store.LNG) ?? 0.0 place.placeType = .store(StoreType(rawValue: store.CLASS.rawValue) ?? .none) place.title = store.CLASS.rawValue place.address = store.ADDRESS return place } let realm = try! Realm() try! realm.write { realm.add(stores) } }) { error in print("Error in", error) // FOR DEBUG } } }
mit
e05508ff6f8320ccb201c7b4f3d4eefe
39.214689
285
0.610565
5.066192
false
false
false
false
Takanu/Pelican
Sources/Pelican/API/Request/Request+Payments.swift
1
2731
// // Request+Payments.swift // Pelican // // Created by Takanu Kyriako on 18/12/2017. // import Foundation extension TelegramRequest { /** NOT YET FINISHED ! ! ! Use this method to send invoices. - parameter prices: An array of costs involved in the transaction (eg. product price, taxes, discounts). */ static public func sendInvoice(title: String, description: String, payload: String, providerToken: String, startParameter: String, currency: String, prices: [String: Int], chatID: String) -> TelegramRequest { let request = TelegramRequest() request.query = [ "title": title, "description": description, "payload": payload, "provider_token": providerToken, "start_parameter": startParameter, "currency": currency, "prices": prices, "chat_id": Int(chatID) ] // Set the query request.method = "sendInvoice" return request } /** NOT YET FINISHED ! ! ! If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. */ static public func answerShippingQuery(shippingQueryID: String, acceptShippingAddress: Bool, shippingOptionsFIXME: [String]?, errorMessage: String?) -> TelegramRequest { let request = TelegramRequest() request.query = [ "shipping_query_id": shippingQueryID, "ok": acceptShippingAddress, "shipping_options": shippingOptionsFIXME, ] if errorMessage != nil { request.query["error_message"] = errorMessage } // Set the query request.method = "answerShippingQuery" return request } /** Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. - note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. */ static public func answerPreCheckoutQuery(preCheckoutQueryID: String, acceptPaymentQuery: Bool, errorMessage: String?) -> TelegramRequest { let request = TelegramRequest() request.query = [ "pre_checkout_query_id": preCheckoutQueryID, "ok": acceptPaymentQuery, ] if errorMessage != nil { request.query["error_message"] = errorMessage } // Set the query request.method = "answerPreCheckoutQuery" return request } }
mit
bacf9a6cf752c90a9fdf8237ed3db527
28.053191
252
0.659099
4.119155
false
false
false
false
WhisperSystems/Signal-iOS
Signal/test/util/FTS/GRDBFullTextSearcherTest.swift
1
26437
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import XCTest @testable import Signal @testable import SignalMessaging // TODO: We might be able to merge this with OWSFakeContactsManager. @objc class GRDBFullTextSearcherContactsManager: NSObject, ContactsManagerProtocol { func displayName(for address: SignalServiceAddress, transaction: SDSAnyReadTransaction) -> String { return self.displayName(for: address) } func displayName(for address: SignalServiceAddress) -> String { if address == aliceRecipient { return "Alice" } else if address == bobRecipient { return "Bob Barker" } else { return "" } } public func displayName(for signalAccount: SignalAccount) -> String { return "Fake name" } public func displayName(for thread: TSThread, transaction: SDSAnyReadTransaction) -> String { return "Fake name" } public func displayNameWithSneakyTransaction(thread: TSThread) -> String { return "Fake name" } func signalAccounts() -> [SignalAccount] { return [] } func isSystemContact(phoneNumber: String) -> Bool { return true } func isSystemContact(address: SignalServiceAddress) -> Bool { return true } func isSystemContact(withSignalAccount recipientId: String) -> Bool { return true } func compare(signalAccount left: SignalAccount, with right: SignalAccount) -> ComparisonResult { owsFailDebug("if this method ends up being used by the tests, we should provide a better implementation.") return .orderedAscending } func cnContact(withId contactId: String?) -> CNContact? { return nil } func avatarData(forCNContactId contactId: String?) -> Data? { return nil } func avatarImage(forCNContactId contactId: String?) -> UIImage? { return nil } } private let bobRecipient = SignalServiceAddress(phoneNumber: "+49030183000") private let aliceRecipient = SignalServiceAddress(phoneNumber: "+12345678900") // MARK: - class GRDBFullTextSearcherTest: SignalBaseTest { // MARK: - Dependencies var searcher: FullTextSearcher { return FullTextSearcher.shared } private var tsAccountManager: TSAccountManager { return TSAccountManager.sharedInstance() } // MARK: - Test Life Cycle override func tearDown() { super.tearDown() SDSDatabaseStorage.shouldLogDBQueries = true } override func setUp() { super.setUp() // Replace this singleton. SSKEnvironment.shared.contactsManager = GRDBFullTextSearcherContactsManager() self.write { transaction in let bookModel = TSGroupModel(title: "Book Club", members: [aliceRecipient, bobRecipient], groupAvatarData: nil, groupId: Randomness.generateRandomBytes(kGroupIdLength)) let bookClubGroupThread = TSGroupThread.getOrCreateThread(with: bookModel, transaction: transaction) self.bookClubThread = ThreadViewModel(thread: bookClubGroupThread, transaction: transaction) let snackModel = TSGroupModel(title: "Snack Club", members: [aliceRecipient], groupAvatarData: nil, groupId: Randomness.generateRandomBytes(kGroupIdLength)) let snackClubGroupThread = TSGroupThread.getOrCreateThread(with: snackModel, transaction: transaction) self.snackClubThread = ThreadViewModel(thread: snackClubGroupThread, transaction: transaction) let aliceContactThread = TSContactThread.getOrCreateThread(withContactAddress: aliceRecipient, transaction: transaction) self.aliceThread = ThreadViewModel(thread: aliceContactThread, transaction: transaction) let bobContactThread = TSContactThread.getOrCreateThread(withContactAddress: bobRecipient, transaction: transaction) self.bobEmptyThread = ThreadViewModel(thread: bobContactThread, transaction: transaction) let helloAlice = TSOutgoingMessage(in: aliceContactThread, messageBody: "Hello Alice", attachmentId: nil) helloAlice.anyInsert(transaction: transaction) let goodbyeAlice = TSOutgoingMessage(in: aliceContactThread, messageBody: "Goodbye Alice", attachmentId: nil) goodbyeAlice.anyInsert(transaction: transaction) let helloBookClub = TSOutgoingMessage(in: bookClubGroupThread, messageBody: "Hello Book Club", attachmentId: nil) helloBookClub.anyInsert(transaction: transaction) let goodbyeBookClub = TSOutgoingMessage(in: bookClubGroupThread, messageBody: "Goodbye Book Club", attachmentId: nil) goodbyeBookClub.anyInsert(transaction: transaction) let bobsPhoneNumber = TSOutgoingMessage(in: bookClubGroupThread, messageBody: "My phone number is: 321-321-4321", attachmentId: nil) bobsPhoneNumber.anyInsert(transaction: transaction) let bobsFaxNumber = TSOutgoingMessage(in: bookClubGroupThread, messageBody: "My fax is: 222-333-4444", attachmentId: nil) bobsFaxNumber.anyInsert(transaction: transaction) } } // MARK: - Fixtures var bookClubThread: ThreadViewModel! var snackClubThread: ThreadViewModel! var aliceThread: ThreadViewModel! var bobEmptyThread: ThreadViewModel! // MARK: Tests private func AssertEqualThreadLists(_ left: [ThreadViewModel], _ right: [ThreadViewModel], file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(left.count, right.count, file: file, line: line) guard left.count != right.count else { return } // Only bother comparing uniqueIds. let leftIds = left.map { $0.threadRecord.uniqueId } let rightIds = right.map { $0.threadRecord.uniqueId } XCTAssertEqual(leftIds, rightIds, file: file, line: line) } func testSearchByGroupName() { var threads: [ThreadViewModel] = [] // No Match threads = searchConversations(searchText: "asdasdasd") XCTAssert(threads.isEmpty) // Partial Match threads = searchConversations(searchText: "Book") XCTAssertEqual(1, threads.count) AssertEqualThreadLists([bookClubThread], threads) threads = searchConversations(searchText: "Snack") XCTAssertEqual(1, threads.count) AssertEqualThreadLists([snackClubThread], threads) // Multiple Partial Matches threads = searchConversations(searchText: "Club") XCTAssertEqual(2, threads.count) AssertEqualThreadLists([bookClubThread, snackClubThread], threads) // Match Name Exactly threads = searchConversations(searchText: "Book Club") XCTAssertEqual(1, threads.count) AssertEqualThreadLists([bookClubThread], threads) } func testSearchContactByNumber() { var threads: [ThreadViewModel] = [] // No match threads = searchConversations(searchText: "+5551239999") XCTAssertEqual(0, threads.count) // Exact match threads = searchConversations(searchText: aliceRecipient.phoneNumber!) XCTAssertEqual(3, threads.count) AssertEqualThreadLists([bookClubThread, aliceThread, snackClubThread], threads) // Partial match threads = searchConversations(searchText: "+123456") XCTAssertEqual(3, threads.count) AssertEqualThreadLists([bookClubThread, aliceThread, snackClubThread], threads) // Prefixes threads = searchConversations(searchText: "12345678900") XCTAssertEqual(3, threads.count) AssertEqualThreadLists([bookClubThread, aliceThread, snackClubThread], threads) threads = searchConversations(searchText: "49") XCTAssertEqual(1, threads.count) AssertEqualThreadLists([bookClubThread], threads) threads = searchConversations(searchText: "1-234-56") XCTAssertEqual(3, threads.count) AssertEqualThreadLists([bookClubThread, aliceThread, snackClubThread], threads) threads = searchConversations(searchText: "123456") XCTAssertEqual(3, threads.count) AssertEqualThreadLists([bookClubThread, aliceThread, snackClubThread], threads) threads = searchConversations(searchText: "1.234.56") XCTAssertEqual(3, threads.count) AssertEqualThreadLists([bookClubThread, aliceThread, snackClubThread], threads) threads = searchConversations(searchText: "1 234 56") XCTAssertEqual(3, threads.count) AssertEqualThreadLists([bookClubThread, aliceThread, snackClubThread], threads) } func testSearchContactByNumberWithoutCountryCode() { var threads: [ThreadViewModel] = [] // Phone Number formatting should be forgiving threads = searchConversations(searchText: "234.56") XCTAssertEqual(3, threads.count) AssertEqualThreadLists([bookClubThread, aliceThread, snackClubThread], threads) threads = searchConversations(searchText: "234 56") XCTAssertEqual(3, threads.count) AssertEqualThreadLists([bookClubThread, aliceThread, snackClubThread], threads) } func testSearchConversationByContactByName() { var threads: [ThreadViewModel] = [] threads = searchConversations(searchText: "Alice") XCTAssertEqual(3, threads.count) AssertEqualThreadLists([bookClubThread, aliceThread, snackClubThread], threads) threads = searchConversations(searchText: "Bob") XCTAssertEqual(1, threads.count) AssertEqualThreadLists([bookClubThread], threads) threads = searchConversations(searchText: "Barker") XCTAssertEqual(1, threads.count) AssertEqualThreadLists([bookClubThread], threads) threads = searchConversations(searchText: "Bob B") XCTAssertEqual(1, threads.count) AssertEqualThreadLists([bookClubThread], threads) } func testSearchMessageByBodyContent() { var resultSet: HomeScreenSearchResultSet = .empty resultSet = getResultSet(searchText: "Hello Alice") XCTAssertEqual(1, resultSet.messages.count) AssertEqualThreadLists([aliceThread], resultSet.messages.map { $0.thread }) resultSet = getResultSet(searchText: "Hello") XCTAssertEqual(2, resultSet.messages.count) AssertEqualThreadLists([aliceThread, bookClubThread], resultSet.messages.map { $0.thread }) } func testSearchEdgeCases() { var resultSet: HomeScreenSearchResultSet = .empty resultSet = getResultSet(searchText: "Hello Alice") XCTAssertEqual(1, resultSet.messages.count) XCTAssertEqual(["Hello Alice"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "hello alice") XCTAssertEqual(1, resultSet.messages.count) XCTAssertEqual(["Hello Alice"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "Hel") XCTAssertEqual(2, resultSet.messages.count) XCTAssertEqual(["Hello Alice", "Hello Book Club"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "Hel Ali") XCTAssertEqual(1, resultSet.messages.count) XCTAssertEqual(["Hello Alice"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "Hel Ali Alic") XCTAssertEqual(1, resultSet.messages.count) XCTAssertEqual(["Hello Alice"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "Ali Hel") XCTAssertEqual(1, resultSet.messages.count) XCTAssertEqual(["Hello Alice"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "CLU") XCTAssertEqual(2, resultSet.messages.count) XCTAssertEqual(["Goodbye Book Club", "Hello Book Club"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "hello !@##!@#!$^@!@#! alice") XCTAssertEqual(1, resultSet.messages.count) XCTAssertEqual(["Hello Alice"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "3213 phone") XCTAssertEqual(1, resultSet.messages.count) XCTAssertEqual(["My phone number is: 321-321-4321"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "PHO 3213") XCTAssertEqual(1, resultSet.messages.count) XCTAssertEqual(["My phone number is: 321-321-4321"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "fax") XCTAssertEqual(1, resultSet.messages.count) XCTAssertEqual(["My fax is: 222-333-4444"], bodies(forMessageResults: resultSet.messages)) resultSet = getResultSet(searchText: "fax 2223") XCTAssertEqual(1, resultSet.messages.count) XCTAssertEqual(["My fax is: 222-333-4444"], bodies(forMessageResults: resultSet.messages)) } // MARK: - More Tests func testModelLifecycle1() { var thread: TSGroupThread! = nil self.write { transaction in let groupModel = TSGroupModel(title: "Lifecycle", members: [aliceRecipient, bobRecipient], groupAvatarData: nil, groupId: Randomness.generateRandomBytes(kGroupIdLength)) thread = TSGroupThread.getOrCreateThread(with: groupModel, transaction: transaction) } let message1 = TSOutgoingMessage(in: thread, messageBody: "This world contains glory and despair.", attachmentId: nil) let message2 = TSOutgoingMessage(in: thread, messageBody: "This world contains hope and despair.", attachmentId: nil) XCTAssertEqual(0, getResultSet(searchText: "GLORY").messages.count) XCTAssertEqual(0, getResultSet(searchText: "HOPE").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DESPAIR").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DEFEAT").messages.count) self.write { transaction in message1.anyInsert(transaction: transaction) message2.anyInsert(transaction: transaction) } XCTAssertEqual(1, getResultSet(searchText: "GLORY").messages.count) XCTAssertEqual(1, getResultSet(searchText: "HOPE").messages.count) XCTAssertEqual(2, getResultSet(searchText: "DESPAIR").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DEFEAT").messages.count) self.write { transaction in message1.update(withMessageBody: "This world contains glory and defeat.", transaction: transaction) } XCTAssertEqual(1, getResultSet(searchText: "GLORY").messages.count) XCTAssertEqual(1, getResultSet(searchText: "HOPE").messages.count) XCTAssertEqual(1, getResultSet(searchText: "DESPAIR").messages.count) XCTAssertEqual(1, getResultSet(searchText: "DEFEAT").messages.count) self.write { transaction in message1.anyRemove(transaction: transaction) } XCTAssertEqual(0, getResultSet(searchText: "GLORY").messages.count) XCTAssertEqual(1, getResultSet(searchText: "HOPE").messages.count) XCTAssertEqual(1, getResultSet(searchText: "DESPAIR").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DEFEAT").messages.count) self.write { transaction in message2.anyRemove(transaction: transaction) } XCTAssertEqual(0, getResultSet(searchText: "GLORY").messages.count) XCTAssertEqual(0, getResultSet(searchText: "HOPE").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DESPAIR").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DEFEAT").messages.count) } func testModelLifecycle2() { self.write { transaction in let groupModel = TSGroupModel(title: "Lifecycle", members: [aliceRecipient, bobRecipient], groupAvatarData: nil, groupId: Randomness.generateRandomBytes(kGroupIdLength)) let thread = TSGroupThread.getOrCreateThread(with: groupModel, transaction: transaction) let message1 = TSOutgoingMessage(in: thread, messageBody: "This world contains glory and despair.", attachmentId: nil) let message2 = TSOutgoingMessage(in: thread, messageBody: "This world contains hope and despair.", attachmentId: nil) message1.anyInsert(transaction: transaction) message2.anyInsert(transaction: transaction) } XCTAssertEqual(1, getResultSet(searchText: "GLORY").messages.count) XCTAssertEqual(1, getResultSet(searchText: "HOPE").messages.count) XCTAssertEqual(2, getResultSet(searchText: "DESPAIR").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DEFEAT").messages.count) self.write { transaction in TSInteraction.anyRemoveAllWithInstantation(transaction: transaction) } XCTAssertEqual(0, getResultSet(searchText: "GLORY").messages.count) XCTAssertEqual(0, getResultSet(searchText: "HOPE").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DESPAIR").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DEFEAT").messages.count) } func testModelLifecycle3() { self.write { transaction in let groupModel = TSGroupModel(title: "Lifecycle", members: [aliceRecipient, bobRecipient], groupAvatarData: nil, groupId: Randomness.generateRandomBytes(kGroupIdLength)) let thread = TSGroupThread.getOrCreateThread(with: groupModel, transaction: transaction) let message1 = TSOutgoingMessage(in: thread, messageBody: "This world contains glory and despair.", attachmentId: nil) let message2 = TSOutgoingMessage(in: thread, messageBody: "This world contains hope and despair.", attachmentId: nil) message1.anyInsert(transaction: transaction) message2.anyInsert(transaction: transaction) } XCTAssertEqual(1, getResultSet(searchText: "GLORY").messages.count) XCTAssertEqual(1, getResultSet(searchText: "HOPE").messages.count) XCTAssertEqual(2, getResultSet(searchText: "DESPAIR").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DEFEAT").messages.count) self.write { transaction in TSInteraction.anyRemoveAllWithoutInstantation(transaction: transaction) } XCTAssertEqual(0, getResultSet(searchText: "GLORY").messages.count) XCTAssertEqual(0, getResultSet(searchText: "HOPE").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DESPAIR").messages.count) XCTAssertEqual(0, getResultSet(searchText: "DEFEAT").messages.count) } func testDiacritics() { self.write { transaction in let groupModel = TSGroupModel(title: "Lifecycle", members: [aliceRecipient, bobRecipient], groupAvatarData: nil, groupId: Randomness.generateRandomBytes(kGroupIdLength)) let thread = TSGroupThread.getOrCreateThread(with: groupModel, transaction: transaction) TSOutgoingMessage(in: thread, messageBody: "NOËL and SØRINA and ADRIÁN and FRANÇOIS and NUÑEZ and Björk.", attachmentId: nil).anyInsert(transaction: transaction) } XCTAssertEqual(1, getResultSet(searchText: "NOËL").messages.count) XCTAssertEqual(1, getResultSet(searchText: "noel").messages.count) XCTAssertEqual(1, getResultSet(searchText: "SØRINA").messages.count) // I guess Ø isn't a diacritical mark but a separate letter. XCTAssertEqual(0, getResultSet(searchText: "sorina").messages.count) XCTAssertEqual(1, getResultSet(searchText: "ADRIÁN").messages.count) XCTAssertEqual(1, getResultSet(searchText: "adrian").messages.count) XCTAssertEqual(1, getResultSet(searchText: "FRANÇOIS").messages.count) XCTAssertEqual(1, getResultSet(searchText: "francois").messages.count) XCTAssertEqual(1, getResultSet(searchText: "NUÑEZ").messages.count) XCTAssertEqual(1, getResultSet(searchText: "nunez").messages.count) XCTAssertEqual(1, getResultSet(searchText: "Björk").messages.count) XCTAssertEqual(1, getResultSet(searchText: "Bjork").messages.count) } private func AssertValidResultSet(query: String, expectedResultCount: Int, file: StaticString = #file, line: UInt = #line) { // For these simple test cases, the snippet should contain the entire query. let expectedSnippetContent: String = query let resultSet = getResultSet(searchText: query) XCTAssertEqual(expectedResultCount, resultSet.messages.count, file: file, line: line) for result in resultSet.messages { guard let snippet = result.snippet else { XCTFail("Missing snippet.", file: file, line: line) continue } XCTAssertTrue(snippet.lowercased().contains(expectedSnippetContent.lowercased()), file: file, line: line) } } func testSnippets() { var thread: TSGroupThread! = nil self.write { transaction in let groupModel = TSGroupModel(title: "Lifecycle", members: [aliceRecipient, bobRecipient], groupAvatarData: nil, groupId: Randomness.generateRandomBytes(kGroupIdLength)) thread = TSGroupThread.getOrCreateThread(with: groupModel, transaction: transaction) } let message1 = TSOutgoingMessage(in: thread, messageBody: "This world contains glory and despair.", attachmentId: nil) let message2 = TSOutgoingMessage(in: thread, messageBody: "This world contains hope and despair.", attachmentId: nil) AssertValidResultSet(query: "GLORY", expectedResultCount: 0) AssertValidResultSet(query: "HOPE", expectedResultCount: 0) AssertValidResultSet(query: "DESPAIR", expectedResultCount: 0) AssertValidResultSet(query: "DEFEAT", expectedResultCount: 0) self.write { transaction in message1.anyInsert(transaction: transaction) message2.anyInsert(transaction: transaction) } AssertValidResultSet(query: "GLORY", expectedResultCount: 1) AssertValidResultSet(query: "HOPE", expectedResultCount: 1) AssertValidResultSet(query: "DESPAIR", expectedResultCount: 2) AssertValidResultSet(query: "DEFEAT", expectedResultCount: 0) } // MARK: - Perf func testPerf() { // Logging queries is expensive and affects the results of this test. // This is restored in tearDown(). SDSDatabaseStorage.shouldLogDBQueries = false let aliceE164 = "+13213214321" let aliceUuid = UUID() tsAccountManager.registerForTests(withLocalNumber: aliceE164, uuid: aliceUuid) let string1 = "krazy" let string2 = "kat" let messageCount: UInt = 100 Bench(title: "Populate Index", memorySamplerRatio: 1) { _ in self.write { transaction in let groupModel = TSGroupModel(title: "Perf", members: [aliceRecipient, bobRecipient], groupAvatarData: nil, groupId: Randomness.generateRandomBytes(kGroupIdLength)) let thread = TSGroupThread.getOrCreateThread(with: groupModel, transaction: transaction) TSOutgoingMessage(in: thread, messageBody: string1, attachmentId: nil).anyInsert(transaction: transaction) for _ in 0...messageCount { let message = TSOutgoingMessage(in: thread, messageBody: UUID().uuidString, attachmentId: nil) message.anyInsert(transaction: transaction) message.update(withMessageBody: UUID().uuidString, transaction: transaction) } TSOutgoingMessage(in: thread, messageBody: string2, attachmentId: nil).anyInsert(transaction: transaction) } } Bench(title: "Search", memorySamplerRatio: 1) { _ in self.read { transaction in let finder = FullTextSearchFinder() let getMatchCount = { (searchText: String) -> UInt in var count: UInt = 0 finder.enumerateObjects(searchText: searchText, transaction: transaction) { (match, snippet, _) in Logger.verbose("searchText: \(searchText), match: \(match), snippet: \(snippet)") count += 1 } return count } XCTAssertEqual(1, getMatchCount(string1)) XCTAssertEqual(1, getMatchCount(string2)) XCTAssertEqual(0, getMatchCount(UUID().uuidString)) } } } // MARK: - Helpers func bodies<T>(forMessageResults messageResults: [ConversationSearchResult<T>]) -> [String] { var result = [String]() self.read { transaction in for messageResult in messageResults { guard let messageId = messageResult.messageId else { owsFailDebug("message result missing message id") continue } guard let interaction = TSInteraction.anyFetch(uniqueId: messageId, transaction: transaction) else { owsFailDebug("couldn't load interaction for message result") continue } guard let message = interaction as? TSMessage else { owsFailDebug("invalid message for message result") continue } guard let messageBody = message.body else { owsFailDebug("message result missing message body") continue } result.append(messageBody) } } return result.sorted() } private func searchConversations(searchText: String) -> [ThreadViewModel] { let results = getResultSet(searchText: searchText) return results.conversations.map { $0.thread } } private func getResultSet(searchText: String) -> HomeScreenSearchResultSet { var results: HomeScreenSearchResultSet! self.read { transaction in results = self.searcher.searchForHomeScreen(searchText: searchText, transaction: transaction) } return results } }
gpl-3.0
8fcce512b2a3ffb7b022f949412ad779
43.261307
181
0.681502
4.881581
false
false
false
false
poetmountain/MotionMachine
Examples/MotionExamples/MasterViewController.swift
1
4582
// // MasterViewController.swift // MotionExamples // // Created by Brett Walker on 6/1/16. // Copyright © 2016 Poet & Mountain, LLC. All rights reserved. // import UIKit enum ExampleTypes: Int { case basic = 0 case group = 1 case sequence = 2 case contiguousSequence = 3 case physics = 4 case additive = 5 case dynamic = 6 } class MasterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var tableView: UITableView! var examples = [String]() var uiCreated: Bool = false let CELL_IDENTIFIER = "Cell" convenience init() { self.init(nibName: nil, bundle: nil) examples = ["Motion", "Group", "Sequence", "Sequence (Contiguous)", "Physics", "Additive", "Additive (Multiple)" ] } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() title = "Examples" self.view.backgroundColor = UIColor.white } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if (!uiCreated) { setupUI() uiCreated = true } } // MARK: - Private methods private func setupUI() { tableView = UITableView.init() tableView.dataSource = self tableView.delegate = self tableView.clipsToBounds = true tableView.estimatedRowHeight = 44.0 tableView.register(UITableViewCell.self, forCellReuseIdentifier: CELL_IDENTIFIER) self.view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false var margins : UILayoutGuide if #available(iOS 11.0, *) { margins = view.safeAreaLayoutGuide } else { margins = view.layoutMarginsGuide } tableView.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true tableView.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true } // MARK: - Table View func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return examples.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CELL_IDENTIFIER, for: indexPath) cell.accessoryType = .disclosureIndicator let label_text = examples[(indexPath as NSIndexPath).row] cell.textLabel!.text = label_text return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let index = ExampleTypes(rawValue: (indexPath as NSIndexPath).row) if let type = index { var vc: UIViewController switch type { case .basic: vc = BasicMotionViewController() case .group: vc = GroupMotionViewController() case .sequence: vc = SequenceViewController() case .contiguousSequence: vc = SequenceContiguousViewController() case .physics: vc = PhysicsMotionViewController() case .additive: vc = AdditiveViewController() case .dynamic: vc = DynamicViewController() } tableView.deselectRow(at: indexPath, animated: true) vc.title = examples[(indexPath as NSIndexPath).row] navigationController?.pushViewController(vc, animated: true) } } }
mit
1af9389227987cb043747a67296d9371
27.277778
100
0.555337
5.858056
false
false
false
false
feighter09/Cloud9
SoundCloud Pro/TracksTableViewController.swift
1
8403
// // TracksTableViewController.swift // SoundCloud Pro // // Created by Austin Feight on 7/11/15. // Copyright © 2015 Lost in Flight. All rights reserved. // import UIKit import Bond let kStreamCellIdentifier = "streamCell" let kStreamPlaylistMinimum = 1 @objc protocol TracksTableViewControllerDelegate: NSObjectProtocol { optional func tracksTableControllerDidTriggerRefresh(tracksTableController: TracksTableViewController) optional func tracksTableControllerDidScrollToEnd(tracksTableController: TracksTableViewController) optional func tracksTableController(tracksTableController: TracksTableViewController, didDeleteTrack track: Track) } class TracksTableViewController: UITableViewController { /// The tracks shown. Automatically updates tableView if set with `=` var tracks: [Track] = [] { didSet { tableView.reloadData() pullToRefresh?.finishedLoading() tableView.infiniteScrollingView?.stopAnimating() } } // Options var tracksPlayOnSelect = true var pullToRefreshEnabled = false var infiniteScrollingEnabled = false var swipeToDeleteEnabled = false var showLoadingCell = false { didSet { tableView.reloadData() } } weak var delegate: TracksTableViewControllerDelegate? // Internals var listenerId = 0 private var pullToRefresh: BOZPongRefreshControl? private var trackToAddToPlaylist: Track? deinit { UserPreferences.listeners.removeListener(self) } } // MARK: - Interface extension TracksTableViewController { func addToView(view: UIView, inViewController viewController: UIViewController, withDelegate delegate: TracksTableViewControllerDelegate?) { self.delegate = delegate view.addSubview(tableView) viewController.addChildViewController(self) didMoveToParentViewController(viewController) } } // MARK: - Life Cycle extension TracksTableViewController { override func viewDidLoad() { super.viewDidLoad() initTable() UserPreferences.listeners.addListener(self) } private func initTable() { tableView.registerNib(StreamCell.nib, forCellReuseIdentifier: kStreamCellIdentifier) tableView.registerNib(LoadingCell.nib, forCellReuseIdentifier: kLoadingCellIdentifier) tableView.delegate = self setupTableViewAppearance() setupPullToRefreshAndInfiniteScrollingIfNecessary() } private func setupTableViewAppearance() { tableView.estimatedRowHeight = 97 tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorInset = UIEdgeInsetsZero tableView.tableFooterView = UIView(frame: CGRectZero) } private func setupPullToRefreshAndInfiniteScrollingIfNecessary() { if pullToRefreshEnabled { pullToRefresh = BOZPongRefreshControl.attachToScrollView(tableView, withRefreshTarget: self, andRefreshAction: "refreshTracks") pullToRefresh!.backgroundColor = .secondaryColor } if infiniteScrollingEnabled { tableView.addInfiniteScrollingWithActionHandler { () -> Void in self.delegate?.tracksTableControllerDidScrollToEnd?(self) } let activityIndicator = tableView.infiniteScrollingView.valueForKey("activityIndicatorView") as! UIActivityIndicatorView activityIndicator.color = .secondaryColor } } func refreshTracks() { delegate?.tracksTableControllerDidTriggerRefresh?(self) } } // MARK: - User Preferences Listener extension TracksTableViewController: UserPreferencesListener { func downvoteStatusChangedForTrack(track: Track, downvoted: Bool) { if tracks.contains(track) { removeTrack(track) } } } // MARK: - Stream Cell Delegate extension TracksTableViewController: StreamCellDelegate { func streamCell(streamCell: StreamCell, didTapAddToPlaylist track: Track) { showAddToPlaylistWithTrack(track) } func streamCell(streamCell: StreamCell, didTapMoreWithTrack track: Track) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Add to playlist", style: .Default, handler: { (action) -> Void in self.showAddToPlaylistWithTrack(track) })) alert.addAction(UIAlertAction(title: "Save locally (coming soon)", style: .Default, handler: nil)) alert.addAction(UIAlertAction(title: "Cancel", style: .Destructive, handler: nil)) presentViewController(alert, animated: true, completion: nil) } private func showAddToPlaylistWithTrack(track: Track) { let playlistPicker = PlaylistPickerViewController() playlistPicker.track = track playlistPicker.delegate = self navigationController!.presentViewController(UINavigationController(rootViewController: playlistPicker), animated: true, completion: nil) } } // MARK: - Playlist Picker Delegate extension TracksTableViewController: PlaylistPickerDelegate { func playlistPickerDidTapDone(playlistPicker: PlaylistPickerViewController) { dismissPlaylistPicker() } func playlistPickerDidTapCancel(playlistPicker: PlaylistPickerViewController) { dismissPlaylistPicker() } private func dismissPlaylistPicker() { navigationController!.dismissViewControllerAnimated(true, completion: nil) } } // MARK: - Table View Data Source extension TracksTableViewController { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tracks.count + (showLoadingCell ? 1 : 0) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if showLoadingCellForIndexPath(indexPath) { let cell = tableView.dequeueReusableCellWithIdentifier(kLoadingCellIdentifier, forIndexPath: indexPath) as! LoadingCell cell.animate() return cell } let cell = tableView.dequeueReusableCellWithIdentifier(kStreamCellIdentifier, forIndexPath: indexPath) as! StreamCell let trackIndex = showLoadingCell ? indexPath.row - 1 : indexPath.row cell.track = tracks[trackIndex] cell.playsOnSelection = tracksPlayOnSelect cell.delegate = self return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let track = tracks[indexPath.row] removeTrack(track) } } override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return tableView.editing || swipeToDeleteEnabled ? .Delete : .None } } // MARK: - Table View Delegate extension TracksTableViewController { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { addStreamToPlaylistAfterTrackWithIndex(indexPath.row) } private func addStreamToPlaylistAfterTrackWithIndex(index: Int) { if index + 1 >= tracks.count { return } let start = index + 1 let tracksToAdd = Array(tracks[start ..< tracks.count]) AudioPlayer.sharedPlayer.addTracksToPlaylist(tracksToAdd, clearExisting: true) // TODO: Handle end of stream } } // MARK: - Scroll Delegate for Pong Refresh extension TracksTableViewController { override func scrollViewDidScroll(scrollView: UIScrollView) { pullToRefresh?.scrollViewDidScroll() } override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { pullToRefresh?.scrollViewDidEndDragging() } } // MARK: - Helpers extension TracksTableViewController { private func removeTrack(track: Track) { tableView.beginUpdates() let indexPath = NSIndexPath(forRow: tracks.indexOf(track)!, inSection: 0) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Right) tracks.removeAtIndex(indexPath.row) // mix between track / index of is bleh, there for deleting duplicates, // don't wanna delete both tableView.endUpdates() delegate?.tracksTableController?(self, didDeleteTrack: track) } private func showLoadingCellForIndexPath(indexPath: NSIndexPath) -> Bool { return showLoadingCell && indexPath.row == 0 } }
lgpl-3.0
c12c4461a414fac2ccd4af1481ef01b5
30.00738
140
0.738515
5.231631
false
false
false
false
XueSeason/Awesome-CNodeJS
Awesome-CNodeJS/Awesome-CNodeJS/Models/Topic.swift
1
1242
// // Topic.swift // Awesome-CNodeJS // // Created by 薛纪杰 on 16/1/1. // Copyright © 2016年 XueSeason. All rights reserved. // import Foundation struct Author { let loginName: String? let avatarUrl: String? init(json: JSON) { self.loginName = json["author"].string self.avatarUrl = json["avatar_url"].string } } class Topic { let id: String? let authorId: String? let tab: String? let content: String? let title: String? let lastReplyAt: String? let good: Bool? let top: Bool? let replyCount: Int? let visitCount: Int? let createAt: String? let author: Author? init(json: JSON) { self.id = json["id"].string self.authorId = json["author_id"].string self.tab = json["tab"].string self.content = json["content"].string self.title = json["title"].string self.lastReplyAt = json["last_reply_at"].string self.good = json["good"].bool self.top = json["top"].bool self.replyCount = json["reply_count"].int self.visitCount = json["visit_count"].int self.createAt = json["create_at"].string self.author = Author(json: json["author"]) } }
mit
3dc4371c087aef45f85f6a5a6e2b707d
23.66
55
0.593674
3.658754
false
false
false
false
ncalexan/firefox-ios
Storage/ThirdParty/SwiftData.swift
1
61450
/* 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/. */ /* * This is a heavily modified version of SwiftData.swift by Ryan Fowler * This has been enhanced to support custom files, correct binding, versioning, * and a streaming results via Cursors. The API has also been changed to use NSError, Cursors, and * to force callers to request a connection before executing commands. Database creation helpers, savepoint * helpers, image support, and other features have been removed. */ // SwiftData.swift // // Copyright (c) 2014 Ryan Fowler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import Shared import XCGLogger private let DatabaseBusyTimeout: Int32 = 3 * 1000 private let log = Logger.syncLogger enum SQLiteDBConnectionCreatedResult { case success case failure case needsRecovery } // SQLite standard error codes when the DB file is locked, busy or the disk is // full. These error codes indicate that any issues with writing to the database // are temporary and we should not wipe out and re-create the database file when // we encounter them. enum SQLiteDBRecoverableError: Int { case Busy = 5 case Locked = 6 case ReadOnly = 8 case IOErr = 10 case Full = 13 } /** * Handle to a SQLite database. * Each instance holds a single connection that is shared across all queries. */ open class SwiftData { let filename: String let schema: Schema let files: FileAccessor static var EnableWAL = true static var EnableForeignKeys = true /// Used to keep track of the corrupted databases we've logged. static var corruptionLogsWritten = Set<String>() /// Used for testing. static var ReuseConnections = true /// For thread-safe access to the shared connection. fileprivate let sharedConnectionQueue: DispatchQueue /// Shared connection to this database. fileprivate var sharedConnection: ConcreteSQLiteDBConnection? fileprivate var key: String? fileprivate var prevKey: String? /// A simple state flag to track whether we should accept new connection requests. /// If a connection request is made while the database is closed, a /// FailedSQLiteDBConnection will be returned. fileprivate(set) var closed = false init(filename: String, key: String? = nil, prevKey: String? = nil, schema: Schema, files: FileAccessor) { self.filename = filename self.key = key self.prevKey = prevKey self.schema = schema self.files = files self.sharedConnectionQueue = DispatchQueue(label: "SwiftData queue: \(filename)", attributes: []) // Ensure that multi-thread mode is enabled by default. // See https://www.sqlite.org/threadsafe.html assert(sqlite3_threadsafe() == 2) } fileprivate func getSharedConnection() -> ConcreteSQLiteDBConnection? { var connection: ConcreteSQLiteDBConnection? sharedConnectionQueue.sync { if self.closed { log.warning(">>> Database is closed for \(self.filename)") return } if self.sharedConnection == nil { log.debug(">>> Creating shared SQLiteDBConnection for \(self.filename) on thread \(Thread.current).") self.sharedConnection = ConcreteSQLiteDBConnection(filename: self.filename, flags: SwiftData.Flags.readWriteCreate.toSQL(), key: self.key, prevKey: self.prevKey, schema: self.schema, files: self.files) } connection = self.sharedConnection } return connection } /** * The real meat of all the execute methods. This is used internally to open and * close a database connection and run a block of code inside it. */ func withConnection(_ flags: SwiftData.Flags, synchronous: Bool=true, cb: @escaping (_ db: SQLiteDBConnection) -> NSError?) -> NSError? { /** * We use a weak reference here instead of strongly retaining the connection because we don't want * any control over when the connection deallocs. If the only owner of the connection (SwiftData) * decides to dealloc it, we should respect that since the deinit method of the connection is tied * to the app lifecycle. This is to prevent background disk access causing springboard crashes. */ weak var conn = getSharedConnection() let queue = self.sharedConnectionQueue if synchronous { var error: NSError? = nil queue.sync { /** * By the time this dispatch block runs, it is possible the user has backgrounded the app * and the connection has been dealloc'ed since we last grabbed the reference */ guard let connection = SwiftData.ReuseConnections ? conn : ConcreteSQLiteDBConnection(filename: filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey, schema: self.schema, files: self.files) else { error = cb(FailedSQLiteDBConnection()) ?? NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not create a connection"]) return } error = cb(connection) } return error } queue.async { guard let connection = SwiftData.ReuseConnections ? conn : ConcreteSQLiteDBConnection(filename: self.filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey, schema: self.schema, files: self.files) else { let _ = cb(FailedSQLiteDBConnection()) return } let _ = cb(connection) } return nil } func transaction(_ transactionClosure: @escaping (_ connection: SQLiteDBConnection) -> Bool) -> NSError? { return self.transaction(synchronous: true, transactionClosure: transactionClosure) } /** * Helper for opening a connection, starting a transaction, and then running a block of code inside it. * The code block can return true if the transaction should be committed. False if we should roll back. */ func transaction(synchronous: Bool=true, transactionClosure: @escaping (_ connection: SQLiteDBConnection) -> Bool) -> NSError? { return withConnection(SwiftData.Flags.readWriteCreate, synchronous: synchronous) { connection in connection.transaction(transactionClosure) } } /// Don't use this unless you know what you're doing. The deinitializer /// should be used to achieve refcounting semantics. func forceClose() { sharedConnectionQueue.sync { self.closed = true self.sharedConnection = nil } } /// Reopens a database that had previously been force-closed. /// Does nothing if this database is already open. func reopenIfClosed() { sharedConnectionQueue.sync { self.closed = false } } public enum Flags { case readOnly case readWrite case readWriteCreate fileprivate func toSQL() -> Int32 { switch self { case .readOnly: return SQLITE_OPEN_READONLY case .readWrite: return SQLITE_OPEN_READWRITE case .readWriteCreate: return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE } } } } /** * Wrapper class for a SQLite statement. * This class helps manage the statement lifecycle. By holding a reference to the SQL connection, we ensure * the connection is never deinitialized while the statement is active. This class is responsible for * finalizing the SQL statement once it goes out of scope. */ private class SQLiteDBStatement { var pointer: OpaquePointer? fileprivate let connection: ConcreteSQLiteDBConnection init(connection: ConcreteSQLiteDBConnection, query: String, args: [Any?]?) throws { self.connection = connection let status = sqlite3_prepare_v2(connection.sqliteDB, query, -1, &pointer, nil) if status != SQLITE_OK { throw connection.createErr("During: SQL Prepare \(query)", status: Int(status)) } if let args = args, let bindError = bind(args) { throw bindError } } /// Binds arguments to the statement. fileprivate func bind(_ objects: [Any?]) -> NSError? { let count = Int(sqlite3_bind_parameter_count(pointer)) if count < objects.count { return connection.createErr("During: Bind", status: 202) } if count > objects.count { return connection.createErr("During: Bind", status: 201) } for (index, obj) in objects.enumerated() { var status: Int32 = SQLITE_OK // Doubles also pass obj as Int, so order is important here. if obj is Double { status = sqlite3_bind_double(pointer, Int32(index+1), obj as! Double) } else if obj is Int { status = sqlite3_bind_int(pointer, Int32(index+1), Int32(obj as! Int)) } else if obj is Bool { status = sqlite3_bind_int(pointer, Int32(index+1), (obj as! Bool) ? 1 : 0) } else if obj is String { typealias CFunction = @convention(c) (UnsafeMutableRawPointer?) -> Void let transient = unsafeBitCast(-1, to: CFunction.self) status = sqlite3_bind_text(pointer, Int32(index+1), (obj as! String).cString(using: String.Encoding.utf8)!, -1, transient) } else if obj is Data { status = sqlite3_bind_blob(pointer, Int32(index+1), ((obj as! Data) as NSData).bytes, -1, nil) } else if obj is Date { let timestamp = (obj as! Date).timeIntervalSince1970 status = sqlite3_bind_double(pointer, Int32(index+1), timestamp) } else if obj is UInt64 { status = sqlite3_bind_double(pointer, Int32(index+1), Double(obj as! UInt64)) } else if obj == nil { status = sqlite3_bind_null(pointer, Int32(index+1)) } if status != SQLITE_OK { return connection.createErr("During: Bind", status: Int(status)) } } return nil } func close() { if nil != self.pointer { sqlite3_finalize(self.pointer) self.pointer = nil } } deinit { if nil != self.pointer { sqlite3_finalize(self.pointer) } } } public protocol SQLiteDBConnection { var lastInsertedRowID: Int { get } var numberOfRowsModified: Int { get } var version: Int { get } func executeChange(_ sqlStr: String) -> NSError? func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> func transaction(_ transactionClosure: @escaping (_ connection: SQLiteDBConnection) -> Bool) -> NSError? func interrupt() func checkpoint() func checkpoint(_ mode: Int32) func vacuum() -> NSError? func setVersion(_ version: Int) -> NSError? } // Represents a failure to open. class FailedSQLiteDBConnection: SQLiteDBConnection { var lastInsertedRowID: Int = 0 var numberOfRowsModified: Int = 0 var version: Int = 0 fileprivate func fail(_ str: String) -> NSError { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: str]) } func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? { return self.fail("Non-open connection; can't execute change.") } func executeChange(_ sqlStr: String) -> NSError? { return self.fail("Non-open connection; can't execute change.") } func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { return Cursor<T>(err: self.fail("Non-open connection; can't execute query.")) } func transaction(_ transactionClosure: @escaping (_ connection: SQLiteDBConnection) -> Bool) -> NSError? { return self.fail("Non-open connection; can't start transaction.") } func interrupt() {} func checkpoint() {} func checkpoint(_ mode: Int32) {} func vacuum() -> NSError? { return self.fail("Non-open connection; can't vacuum.") } func setVersion(_ version: Int) -> NSError? { return self.fail("Non-open connection; can't set user_version.") } } open class ConcreteSQLiteDBConnection: SQLiteDBConnection { open var lastInsertedRowID: Int { return Int(sqlite3_last_insert_rowid(sqliteDB)) } open var numberOfRowsModified: Int { return Int(sqlite3_changes(sqliteDB)) } open var version: Int { return pragma("user_version", factory: IntFactory) ?? 0 } fileprivate var sqliteDB: OpaquePointer? fileprivate let filename: String fileprivate let schema: Schema fileprivate let files: FileAccessor fileprivate let debug_enabled = false init?(filename: String, flags: Int32, key: String? = nil, prevKey: String? = nil, schema: Schema, files: FileAccessor) { log.debug("Opening connection to \(filename).") self.filename = filename self.schema = schema self.files = files func doOpen() -> Bool { if let failure = openWithFlags(flags) { log.warning("Opening connection to \(filename) failed: \(failure).") return false } if key == nil && prevKey == nil { do { try self.prepareCleartext() } catch { return false } } else { do { try self.prepareEncrypted(flags, key: key, prevKey: prevKey) } catch { return false } } return true } // If we cannot even open the database file, return `nil` to force SwiftData // into using a `FailedSQLiteDBConnection` so we can retry opening again later. if !doOpen() { log.error("Cannot open a database connection to \(filename).") SentryIntegration.shared.sendWithStacktrace(message: "Cannot open a database connection to \(filename).", tag: "SwiftData", severity: .error) return nil } // Now that we've successfully opened a connection to the database file, call // `prepareSchema()`. If it succeeds, our work here is done. If it returns // `.failure`, this means there was a temporary error preventing us from initing // the schema (e.g. SQLITE_BUSY, SQLITE_LOCK, SQLITE_FULL); so we return `nil` to // force SwiftData into using a `FailedSQLiteDBConnection` to retry preparing the // schema again later. However, if it returns `.needsRecovery`, this means there // was a permanent error preparing the schema and we need to move the current // database file to a backup location and start over with a brand new one. switch self.prepareSchema() { case .success: log.debug("Database succesfully created or updated.") case .failure: log.error("Failed to create or update the database schema.") SentryIntegration.shared.sendWithStacktrace(message: "Failed to create or update the database schema.", tag: "SwiftData", severity: .error) return nil case .needsRecovery: log.error("Database schema cannot be created or updated due to an unrecoverable error.") SentryIntegration.shared.sendWithStacktrace(message: "Database schema cannot be created or updated due to an unrecoverable error.", tag: "SwiftData", severity: .error) // We need to close this new connection before we can move the database file to // its backup location. If we cannot even close the connection, something has // gone really wrong. In that case, bail out and return `nil` to force SwiftData // into using a `FailedSQLiteDBConnection` so we can retry again later. if let error = self.closeCustomConnection(immediately: true) { log.error("Cannot close the database connection to begin recovery. \(error.localizedDescription)") SentryIntegration.shared.sendWithStacktrace(message: "Cannot close the database connection to begin recovery. \(error.localizedDescription)", tag: "SwiftData", severity: .error) return nil } // Move the current database file to its backup location. self.moveDatabaseFileToBackupLocation() // If we cannot open the *new* database file (which shouldn't happen), return // `nil` to force SwiftData into using a `FailedSQLiteDBConnection` so we can // retry opening again later. if !doOpen() { log.error("Cannot re-open a database connection to the new database file to begin recovery.") SentryIntegration.shared.sendWithStacktrace(message: "Cannot re-open a database connection to the new database file to begin recovery.", tag: "SwiftData", severity: .error) return nil } // Notify the world that we re-created the database schema. This allows us to // reset Sync and start over in the case of corruption. defer { let baseFilename = URL(fileURLWithPath: self.filename).lastPathComponent NotificationCenter.default.post(name: NotificationDatabaseWasRecreated, object: baseFilename) } // Now that we've got a brand new database file, let's call `prepareSchema()` on // it to re-create the schema. Again, if this fails (it shouldn't), return `nil` // to force SwiftData into using a `FailedSQLiteDBConnection` so we can retry // again later. if self.prepareSchema() != .success { log.error("Cannot re-create the schema in the new database file to complete recovery.") SentryIntegration.shared.sendWithStacktrace(message: "Cannot re-create the schema in the new database file to complete recovery.", tag: "SwiftData", severity: .error) return nil } } } deinit { log.debug("deinit: closing connection on thread \(Thread.current).") self.closeCustomConnection() } fileprivate func setKey(_ key: String?) -> NSError? { sqlite3_key(sqliteDB, key ?? "", Int32((key ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil as Args?) if cursor.status != .success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid key"]) } return nil } fileprivate func reKey(_ oldKey: String?, newKey: String?) -> NSError? { sqlite3_key(sqliteDB, oldKey ?? "", Int32((oldKey ?? "").characters.count)) sqlite3_rekey(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) // Check that the new key actually works sqlite3_key(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil as Args?) if cursor.status != .success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Rekey failed"]) } return nil } public func setVersion(_ version: Int) -> NSError? { return executeChange("PRAGMA user_version = \(version)") } public func interrupt() { log.debug("Interrupt") sqlite3_interrupt(sqliteDB) } fileprivate func pragma<T: Equatable>(_ pragma: String, expected: T?, factory: @escaping (SDRow) -> T, message: String) throws { let cursorResult = self.pragma(pragma, factory: factory) if cursorResult != expected { log.error("\(message): \(cursorResult.debugDescription), \(expected.debugDescription)") throw NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "PRAGMA didn't return expected output: \(message)."]) } } fileprivate func pragma<T>(_ pragma: String, factory: @escaping (SDRow) -> T) -> T? { let cursor = executeQueryUnsafe("PRAGMA \(pragma)", factory: factory, withArgs: [] as Args) defer { cursor.close() } return cursor[0] } fileprivate func prepareShared() { if SwiftData.EnableForeignKeys { let _ = pragma("foreign_keys=ON", factory: IntFactory) } // Retry queries before returning locked errors. sqlite3_busy_timeout(self.sqliteDB, DatabaseBusyTimeout) } fileprivate func prepareEncrypted(_ flags: Int32, key: String?, prevKey: String? = nil) throws { // Setting the key needs to be the first thing done with the database. if let _ = setKey(key) { if let err = closeCustomConnection(immediately: true) { log.error("Couldn't close connection: \(err). Failing to open.") throw err } if let err = openWithFlags(flags) { log.error("Error opening database with flags. Error code: \(err.code), \(err)") SentryIntegration.shared.sendWithStacktrace(message: "Error opening database with flags. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error) throw err } if let err = reKey(prevKey, newKey: key) { // Note: Don't log the error here as it may contain sensitive data. log.error("Unable to encrypt database.") SentryIntegration.shared.sendWithStacktrace(message: "Unable to encrypt database.", tag: "SwiftData", severity: .error) throw err } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") try pragma("journal_mode=WAL", expected: "wal", factory: StringFactory, message: "WAL journal mode set") } self.prepareShared() } fileprivate func prepareCleartext() throws { // If we just created the DB -- i.e., no tables have been created yet -- then // we can set the page size right now and save a vacuum. // // For where these values come from, see Bug 1213623. // // Note that sqlcipher uses cipher_page_size instead, but we don't set that // because it needs to be set from day one. let desiredPageSize = 32 * 1024 let _ = pragma("page_size=\(desiredPageSize)", factory: IntFactory) let currentPageSize = pragma("page_size", factory: IntFactory) // This has to be done without WAL, so we always hop into rollback/delete journal mode. if currentPageSize != desiredPageSize { try pragma("journal_mode=DELETE", expected: "delete", factory: StringFactory, message: "delete journal mode set") try pragma("page_size=\(desiredPageSize)", expected: nil, factory: IntFactory, message: "Page size set") log.info("Vacuuming to alter database page size from \(currentPageSize ?? 0) to \(desiredPageSize).") if let err = self.vacuum() { log.error("Vacuuming failed: \(err).") } else { log.debug("Vacuuming succeeded.") } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") let desiredPagesPerJournal = 16 let desiredCheckpointSize = desiredPagesPerJournal * desiredPageSize let desiredJournalSizeLimit = 3 * desiredCheckpointSize /* * With whole-module-optimization enabled in Xcode 7.2 and 7.2.1, the * compiler seems to eagerly discard these queries if they're simply * inlined, causing a crash in `pragma`. * * Hackily hold on to them. */ let journalModeQuery = "journal_mode=WAL" let autoCheckpointQuery = "wal_autocheckpoint=\(desiredPagesPerJournal)" let journalSizeQuery = "journal_size_limit=\(desiredJournalSizeLimit)" try withExtendedLifetime(journalModeQuery, { try pragma(journalModeQuery, expected: "wal", factory: StringFactory, message: "WAL journal mode set") }) try withExtendedLifetime(autoCheckpointQuery, { try pragma(autoCheckpointQuery, expected: desiredPagesPerJournal, factory: IntFactory, message: "WAL autocheckpoint set") }) try withExtendedLifetime(journalSizeQuery, { try pragma(journalSizeQuery, expected: desiredJournalSizeLimit, factory: IntFactory, message: "WAL journal size limit set") }) } self.prepareShared() } // Creates the database schema in a new database. fileprivate func createSchema() -> Bool { log.debug("Trying to create schema \(self.schema.name) at version \(self.schema.version)") if !schema.create(self) { // If schema couldn't be created, we'll bail without setting the `PRAGMA user_version`. log.debug("Creation failed.") return false } if let error = setVersion(schema.version) { log.error("Unable to update the schema version; \(error.localizedDescription)") } return true } // Updates the database schema in an existing database. fileprivate func updateSchema() -> Bool { log.debug("Trying to update schema \(self.schema.name) from version \(self.version) to \(self.schema.version)") if !schema.update(self, from: self.version) { // If schema couldn't be updated, we'll bail without setting the `PRAGMA user_version`. log.debug("Updating failed.") return false } if let error = setVersion(schema.version) { log.error("Unable to update the schema version; \(error.localizedDescription)") } return true } // Drops the database schema from an existing database. fileprivate func dropSchema() -> Bool { log.debug("Trying to drop schema \(self.schema.name)") if !self.schema.drop(self) { // If schema couldn't be dropped, we'll bail without setting the `PRAGMA user_version`. log.debug("Dropping failed.") return false } if let error = setVersion(0) { log.error("Unable to reset the schema version; \(error.localizedDescription)") } return true } // Checks if the database schema needs created or updated and acts accordingly. // Calls to this function will be serialized to prevent race conditions when // creating or updating the schema. fileprivate func prepareSchema() -> SQLiteDBConnectionCreatedResult { SentryIntegration.shared.addAttributes(["dbSchema.\(schema.name).version": schema.version]) // Get the current schema version for the database. let currentVersion = self.version // If the current schema version for the database matches the specified // `Schema` version, no further action is necessary and we can bail out. // NOTE: This assumes that we always use *ONE* `Schema` per database file // since SQLite can only track a single value in `PRAGMA user_version`. if currentVersion == schema.version { log.debug("Schema \(self.schema.name) already exists at version \(self.schema.version). Skipping additional schema preparation.") return .success } // Set an attribute for Sentry to include with any future error/crash // logs to indicate what schema version we're coming from and going to. SentryIntegration.shared.addAttributes(["dbUpgrade.\(self.schema.name).from": currentVersion, "dbUpgrade.\(self.schema.name).to": self.schema.version]) // This should not ever happen since the schema version should always be // increasing whenever a structural change is made in an app update. guard currentVersion <= schema.version else { log.error("Schema \(self.schema.name) cannot be downgraded from version \(currentVersion) to \(self.schema.version).") SentryIntegration.shared.sendWithStacktrace(message: "Schema \(self.schema.name) cannot be downgraded from version \(currentVersion) to \(self.schema.version).", tag: "SwiftData", severity: .error) return .failure } log.debug("Schema \(self.schema.name) needs created or updated from version \(currentVersion) to \(self.schema.version).") var success = true if let error = transaction({ connection -> Bool in log.debug("Create or update \(self.schema.name) version \(self.schema.version) on \(Thread.current.description).") // If `PRAGMA user_version` is zero, check if we can safely create the // database schema from scratch. if connection.version == 0 { // Query for the existence of the `tableList` table to determine if we are // migrating from an older DB version. let sqliteMasterCursor = connection.executeQueryUnsafe("SELECT COUNT(*) AS number FROM sqlite_master WHERE type = 'table' AND name = 'tableList'", factory: IntFactory, withArgs: [] as Args) let tableListTableExists = sqliteMasterCursor[0] == 1 sqliteMasterCursor.close() // If the `tableList` table doesn't exist, we can simply invoke // `createSchema()` to create a brand new DB from scratch. if !tableListTableExists { log.debug("Schema \(self.schema.name) doesn't exist. Creating.") success = self.createSchema() return success } } log.info("Attempting to update schema from version \(currentVersion) to \(self.schema.version).") SentryIntegration.shared.send(message: "Attempting to update schema from version \(currentVersion) to \(self.schema.version).", tag: "SwiftData", severity: .info) // If we can't create a brand new schema from scratch, we must // call `updateSchema()` to go through the update process. if self.updateSchema() { log.debug("Updated schema \(self.schema.name).") success = true return success } // If we failed to update the schema, we'll drop everything from the DB // and create everything again from scratch. Assuming our schema upgrade // code is correct, this *shouldn't* happen. If it does, log it to Sentry. log.error("Update failed for schema \(self.schema.name) from version \(currentVersion) to \(self.schema.version). Dropping and re-creating.") SentryIntegration.shared.sendWithStacktrace(message: "Update failed for schema \(self.schema.name) from version \(currentVersion) to \(self.schema.version). Dropping and re-creating.", tag: "SwiftData", severity: .error) // If we can't even drop the schema here, something has gone really wrong, so // return `false` which should force us into recovery. if !self.dropSchema() { log.error("Unable to drop schema \(self.schema.name) from version \(currentVersion).") SentryIntegration.shared.sendWithStacktrace(message: "Unable to drop schema \(self.schema.name) from version \(currentVersion).", tag: "SwiftData", severity: .error) success = false return success } // Try to re-create the schema. If this fails, we are out of options and we'll // return `false` which should force us into recovery. success = self.createSchema() return success }) { // If we got an error trying to get a transaction, then we either bail out early and return // `.failure` if we think we can retry later or return `.needsRecovery` if the error is not // recoverable. log.error("Unable to get a transaction: \(error.localizedDescription)") SentryIntegration.shared.sendWithStacktrace(message: "Unable to get a transaction: \(error.localizedDescription)", tag: "SwiftData", severity: .error) // Check if the error we got is recoverable (e.g. SQLITE_BUSY, SQLITE_LOCK, SQLITE_FULL). // If so, just return `.failure` so we can retry preparing the schema again later. if let _ = SQLiteDBRecoverableError(rawValue: error.code) { return .failure } // Otherwise, this is a non-recoverable error and we return `.needsRecovery` so the database // file can be backed up and a new one will be created. return .needsRecovery } // If any of our operations inside the transaction failed, this also means we need to go through // the recovery process to re-create the database from scratch. if !success { return .needsRecovery } // No error means we're all good! \o/ return .success } fileprivate func moveDatabaseFileToBackupLocation() { let baseFilename = URL(fileURLWithPath: filename).lastPathComponent // Attempt to make a backup as long as the database file still exists. if files.exists(baseFilename) { log.warning("Couldn't create or update schema \(self.schema.name). Attempting to move \(baseFilename) to another location.") SentryIntegration.shared.sendWithStacktrace(message: "Couldn't create or update schema \(self.schema.name). Attempting to move \(baseFilename) to another location.", tag: "SwiftData", severity: .warning) // Note that a backup file might already exist! We append a counter to avoid this. var bakCounter = 0 var bak: String repeat { bakCounter += 1 bak = "\(baseFilename).bak.\(bakCounter)" } while files.exists(bak) do { try files.move(baseFilename, toRelativePath: bak) let shm = baseFilename + "-shm" let wal = baseFilename + "-wal" log.debug("Moving \(shm) and \(wal)…") if files.exists(shm) { log.debug("\(shm) exists.") try files.move(shm, toRelativePath: bak + "-shm") } if files.exists(wal) { log.debug("\(wal) exists.") try files.move(wal, toRelativePath: bak + "-wal") } log.debug("Finished moving database \(baseFilename) successfully.") } catch let error as NSError { log.error("Unable to move \(baseFilename) to another location. \(error)") SentryIntegration.shared.sendWithStacktrace(message: "Unable to move \(baseFilename) to another location. \(error)", tag: "SwiftData", severity: .error) } } else { // No backup was attempted since the database file did not exist. log.error("The database file \(baseFilename) has been deleted while previously in use.") SentryIntegration.shared.sendWithStacktrace(message: "The database file \(baseFilename) has been deleted while previously in use.", tag: "SwiftData", severity: .info) } } public func checkpoint() { self.checkpoint(SQLITE_CHECKPOINT_FULL) } /** * Blindly attempts a WAL checkpoint on all attached databases. */ public func checkpoint(_ mode: Int32) { guard sqliteDB != nil else { log.warning("Trying to checkpoint a nil DB!") return } log.debug("Running WAL checkpoint on \(self.filename) on thread \(Thread.current).") sqlite3_wal_checkpoint_v2(sqliteDB, nil, mode, nil, nil) log.debug("WAL checkpoint done on \(self.filename).") } public func vacuum() -> NSError? { return self.executeChange("VACUUM") } /// Creates an error from a sqlite status. Will print to the console if debug_enabled is set. /// Do not call this unless you're going to return this error. fileprivate func createErr(_ description: String, status: Int) -> NSError { var msg = SDError.errorMessageFromCode(status) if debug_enabled { log.debug("SwiftData Error -> \(description)") log.debug(" -> Code: \(status) - \(msg)") } if let errMsg = String(validatingUTF8: sqlite3_errmsg(sqliteDB)) { msg += " " + errMsg if debug_enabled { log.debug(" -> Details: \(errMsg)") } } return NSError(domain: "org.mozilla", code: status, userInfo: [NSLocalizedDescriptionKey: msg]) } /// Open the connection. This is called when the db is created. You should not call it yourself. fileprivate func openWithFlags(_ flags: Int32) -> NSError? { let status = sqlite3_open_v2(filename.cString(using: String.Encoding.utf8)!, &sqliteDB, flags, nil) if status != SQLITE_OK { return createErr("During: Opening Database with Flags", status: Int(status)) } return nil } /// Closes a connection. This is called via deinit. Do not call this yourself. @discardableResult fileprivate func closeCustomConnection(immediately: Bool=false) -> NSError? { log.debug("Closing custom connection for \(self.filename) on \(Thread.current).") // TODO: add a lock here? let db = self.sqliteDB self.sqliteDB = nil // Don't bother trying to call sqlite3_close multiple times. guard db != nil else { log.warning("Connection was nil.") return nil } var status = sqlite3_close(db) if status != SQLITE_OK { log.error("Got status \(status) while attempting to close.") SentryIntegration.shared.sendWithStacktrace(message: "Got status \(status) while attempting to close.", tag: "SwiftData", severity: .error) if immediately { return createErr("During: closing database with flags", status: Int(status)) } // Note that if we use sqlite3_close_v2, this will still return SQLITE_OK even if // there are outstanding prepared statements status = sqlite3_close_v2(db) if status != SQLITE_OK { // Based on the above comment regarding sqlite3_close_v2, this shouldn't happen. log.error("Got status \(status) while attempting to close_v2.") SentryIntegration.shared.sendWithStacktrace(message: "Got status \(status) while attempting to close_v2.", tag: "SwiftData", severity: .error) return createErr("During: closing database with flags", status: Int(status)) } } log.debug("Closed \(self.filename).") return nil } open func executeChange(_ sqlStr: String) -> NSError? { return self.executeChange(sqlStr, withArgs: nil) } /// Executes a change on the database. open func executeChange(_ sqlStr: String, withArgs args: Args?) -> NSError? { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } // Close, not reset -- this isn't going to be reused. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) SentryIntegration.shared.sendWithStacktrace(message: "SQLITE_CORRUPT for DB \(filename), \(error)", tag: "SwiftData", severity: .error) } let message = "SQL error. Error code: \(error.code), \(error) for SQL \(String(sqlStr.characters.prefix(500)))." log.error(message) SentryIntegration.shared.sendWithStacktrace(message: message, tag: "SwiftData", severity: .error) return error } let status = sqlite3_step(statement!.pointer) if status != SQLITE_DONE && status != SQLITE_OK { error = createErr("During: SQL Step \(sqlStr)", status: Int(status)) } return error } public func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> { return self.executeQuery(sqlStr, factory: factory, withArgs: nil) } /// Queries the database. /// Returns a cursor pre-filled with the complete result set. public func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } // Close, not reset -- this isn't going to be reused, and the FilledSQLiteCursor // consumes everything. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) SentryIntegration.shared.sendWithStacktrace(message: "SQLITE_CORRUPT for DB \(filename), \(error)", tag: "SwiftData", severity: .error) } let message = "SQL error. Error code: \(error.code), \(error) for SQL \(String(sqlStr.characters.prefix(500)))." log.error(message) SentryIntegration.shared.sendWithStacktrace(message: message, tag: "SwiftData", severity: .error) return Cursor<T>(err: error) } return FilledSQLiteCursor<T>(statement: statement!, factory: factory) } func writeCorruptionInfoForDBNamed(_ dbFilename: String, toLogger logger: XCGLogger) { DispatchQueue.global(qos: DispatchQoS.default.qosClass).sync { guard !SwiftData.corruptionLogsWritten.contains(dbFilename) else { return } logger.error("Corrupt DB detected! DB filename: \(dbFilename)") let dbFileSize = ("file://\(dbFilename)".asURL)?.allocatedFileSize() ?? 0 logger.error("DB file size: \(dbFileSize) bytes") logger.error("Integrity check:") let args: [Any?]? = nil let messages = self.executeQueryUnsafe("PRAGMA integrity_check", factory: StringFactory, withArgs: args) defer { messages.close() } if messages.status == CursorStatus.success { for message in messages { logger.error(message) } logger.error("----") } else { logger.error("Couldn't run integrity check: \(messages.statusMessage).") } // Write call stack. logger.error("Call stack: ") for message in Thread.callStackSymbols { logger.error(" >> \(message)") } logger.error("----") // Write open file handles. let openDescriptors = FSUtils.openFileDescriptors() logger.error("Open file descriptors: ") for (k, v) in openDescriptors { logger.error(" \(k): \(v)") } logger.error("----") SwiftData.corruptionLogsWritten.insert(dbFilename) } } /** * Queries the database. * Returns a live cursor that holds the query statement and database connection. * Instances of this class *must not* leak outside of the connection queue! */ public func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } if let error = error { return Cursor(err: error) } return LiveSQLiteCursor(statement: statement!, factory: factory) } public func transaction(_ transactionClosure: @escaping (_ connection: SQLiteDBConnection) -> Bool) -> NSError? { if let err = executeChange("BEGIN EXCLUSIVE") { log.error("BEGIN EXCLUSIVE failed. Error code: \(err.code), \(err)") SentryIntegration.shared.sendWithStacktrace(message: "BEGIN EXCLUSIVE failed. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error) return err } if transactionClosure(self) { log.verbose("Op in transaction succeeded. Committing.") if let err = executeChange("COMMIT") { log.error("COMMIT failed. Rolling back. Error code: \(err.code), \(err)") SentryIntegration.shared.sendWithStacktrace(message: "COMMIT failed. Rolling back. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error) if let rollbackErr = executeChange("ROLLBACK") { log.error("ROLLBACK after failed COMMIT failed. Error code: \(rollbackErr.code), \(rollbackErr)") SentryIntegration.shared.sendWithStacktrace(message: "ROLLBACK after failed COMMIT failed. Error code: \(rollbackErr.code), \(rollbackErr)", tag: "SwiftData", severity: .error) } return err } } else { log.error("Op in transaction failed. Rolling back.") SentryIntegration.shared.sendWithStacktrace(message: "Op in transaction failed. Rolling back.", tag: "SwiftData", severity: .error) if let err = executeChange("ROLLBACK") { log.error("ROLLBACK after failed op in transaction failed. Error code: \(err.code), \(err)") SentryIntegration.shared.sendWithStacktrace(message: "ROLLBACK after failed op in transaction failed. Error code: \(err.code), \(err)", tag: "SwiftData", severity: .error) return err } } return nil } } /// Helper for queries that return a single integer result. func IntFactory(_ row: SDRow) -> Int { return row[0] as! Int } /// Helper for queries that return a single String result. func StringFactory(_ row: SDRow) -> String { return row[0] as! String } /// Wrapper around a statement for getting data from a row. This provides accessors for subscript indexing /// and a generator for iterating over columns. open class SDRow: Sequence { // The sqlite statement this row came from. fileprivate let statement: SQLiteDBStatement // The columns of this database. The indices of these are assumed to match the indices // of the statement. fileprivate let columnNames: [String] fileprivate init(statement: SQLiteDBStatement, columns: [String]) { self.statement = statement self.columnNames = columns } // Return the value at this index in the row fileprivate func getValue(_ index: Int) -> Any? { let i = Int32(index) let type = sqlite3_column_type(statement.pointer, i) var ret: Any? = nil switch type { case SQLITE_NULL, SQLITE_INTEGER: //Everyone expects this to be an Int. On Ints larger than 2^31 this will lose information. ret = Int(truncatingBitPattern: sqlite3_column_int64(statement.pointer, i)) case SQLITE_TEXT: if let text = sqlite3_column_text(statement.pointer, i) { return String(cString: text) } case SQLITE_BLOB: if let blob = sqlite3_column_blob(statement.pointer, i) { let size = sqlite3_column_bytes(statement.pointer, i) ret = Data(bytes: blob, count: Int(size)) } case SQLITE_FLOAT: ret = Double(sqlite3_column_double(statement.pointer, i)) default: log.warning("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil") } return ret } // Accessor getting column 'key' in the row subscript(key: Int) -> Any? { return getValue(key) } // Accessor getting a named column in the row. This (currently) depends on // the columns array passed into this Row to find the correct index. subscript(key: String) -> Any? { get { if let index = columnNames.index(of: key) { return getValue(index) } return nil } } // Allow iterating through the row. public func makeIterator() -> AnyIterator<Any> { let nextIndex = 0 return AnyIterator() { if nextIndex < self.columnNames.count { return self.getValue(nextIndex) } return nil } } } /// Helper for pretty printing SQL (and other custom) error codes. private struct SDError { fileprivate static func errorMessageFromCode(_ errorCode: Int) -> String { switch errorCode { case -1: return "No error" // SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html case 0: return "Successful result" case 1: return "SQL error or missing database" case 2: return "Internal logic error in SQLite" case 3: return "Access permission denied" case 4: return "Callback routine requested an abort" case 5: return "The database file is busy" case 6: return "A table in the database is locked" case 7: return "A malloc() failed" case 8: return "Attempt to write a readonly database" case 9: return "Operation terminated by sqlite3_interrupt()" case 10: return "Some kind of disk I/O error occurred" case 11: return "The database disk image is malformed" case 12: return "Unknown opcode in sqlite3_file_control()" case 13: return "Insertion failed because database is full" case 14: return "Unable to open the database file" case 15: return "Database lock protocol error" case 16: return "Database is empty" case 17: return "The database schema changed" case 18: return "String or BLOB exceeds size limit" case 19: return "Abort due to constraint violation" case 20: return "Data type mismatch" case 21: return "Library used incorrectly" case 22: return "Uses OS features not supported on host" case 23: return "Authorization denied" case 24: return "Auxiliary database format error" case 25: return "2nd parameter to sqlite3_bind out of range" case 26: return "File opened that is not a database file" case 27: return "Notifications from sqlite3_log()" case 28: return "Warnings from sqlite3_log()" case 100: return "sqlite3_step() has another row ready" case 101: return "sqlite3_step() has finished executing" // Custom SwiftData errors // Binding errors case 201: return "Not enough objects to bind provided" case 202: return "Too many objects to bind provided" // Custom connection errors case 301: return "A custom connection is already open" case 302: return "Cannot open a custom connection inside a transaction" case 303: return "Cannot open a custom connection inside a savepoint" case 304: return "A custom connection is not currently open" case 305: return "Cannot close a custom connection inside a transaction" case 306: return "Cannot close a custom connection inside a savepoint" // Index and table errors case 401: return "At least one column name must be provided" case 402: return "Error extracting index names from sqlite_master" case 403: return "Error extracting table names from sqlite_master" // Transaction and savepoint errors case 501: return "Cannot begin a transaction within a savepoint" case 502: return "Cannot begin a transaction within another transaction" // Unknown error default: return "Unknown error" } } } /// Provides access to the result set returned by a database query. /// The entire result set is cached, so this does not retain a reference /// to the statement or the database connection. private class FilledSQLiteCursor<T>: ArrayCursor<T> { fileprivate init(statement: SQLiteDBStatement, factory: (SDRow) -> T) { var status = CursorStatus.success var statusMessage = "" let data = FilledSQLiteCursor.getValues(statement, factory: factory, status: &status, statusMessage: &statusMessage) super.init(data: data, status: status, statusMessage: statusMessage) } /// Return an array with the set of results and release the statement. fileprivate class func getValues(_ statement: SQLiteDBStatement, factory: (SDRow) -> T, status: inout CursorStatus, statusMessage: inout String) -> [T] { var rows = [T]() var count = 0 status = CursorStatus.success statusMessage = "Success" var columns = [String]() let columnCount = sqlite3_column_count(statement.pointer) for i in 0..<columnCount { let columnName = String(cString: sqlite3_column_name(statement.pointer, i)) columns.append(columnName) } while true { let sqlStatus = sqlite3_step(statement.pointer) if sqlStatus != SQLITE_ROW { if sqlStatus != SQLITE_DONE { // NOTE: By setting our status to failure here, we'll report our count as zero, // regardless of how far we've read at this point. status = CursorStatus.failure statusMessage = SDError.errorMessageFromCode(Int(sqlStatus)) } break } count += 1 let row = SDRow(statement: statement, columns: columns) let result = factory(row) rows.append(result) } return rows } } /// Wrapper around a statement to help with iterating through the results. private class LiveSQLiteCursor<T>: Cursor<T> { fileprivate var statement: SQLiteDBStatement! // Function for generating objects of type T from a row. fileprivate let factory: (SDRow) -> T // Status of the previous fetch request. fileprivate var sqlStatus: Int32 = 0 // Number of rows in the database // XXX - When Cursor becomes an interface, this should be a normal property, but right now // we can't override the Cursor getter for count with a stored property. fileprivate var _count: Int = 0 override var count: Int { get { if status != .success { return 0 } return _count } } fileprivate var position: Int = -1 { didSet { // If we're already there, shortcut out. if oldValue == position { return } var stepStart = oldValue // If we're currently somewhere in the list after this position // we'll have to jump back to the start. if position < oldValue { sqlite3_reset(self.statement.pointer) stepStart = -1 } // Now step up through the list to the requested position for _ in stepStart..<position { sqlStatus = sqlite3_step(self.statement.pointer) } } } init(statement: SQLiteDBStatement, factory: @escaping (SDRow) -> T) { self.factory = factory self.statement = statement // The only way I know to get a count. Walk through the entire statement to see how many rows there are. var count = 0 self.sqlStatus = sqlite3_step(statement.pointer) while self.sqlStatus != SQLITE_DONE { count += 1 self.sqlStatus = sqlite3_step(statement.pointer) } sqlite3_reset(statement.pointer) self._count = count super.init(status: .success, msg: "success") } // Helper for finding all the column names in this statement. fileprivate lazy var columns: [String] = { // This untangles all of the columns and values for this row when its created let columnCount = sqlite3_column_count(self.statement.pointer) var columns = [String]() for i: Int32 in 0 ..< columnCount { let columnName = String(cString: sqlite3_column_name(self.statement.pointer, i)) columns.append(columnName) } return columns }() override subscript(index: Int) -> T? { get { if status != .success { return nil } self.position = index if self.sqlStatus != SQLITE_ROW { return nil } let row = SDRow(statement: statement, columns: self.columns) return self.factory(row) } } override func close() { statement = nil super.close() } }
mpl-2.0
3aa3aea11d9094d1a89cf324d12299a5
41.348725
232
0.609198
4.897816
false
false
false
false
shvets/WebAPI
Tests/WebAPITests/MuzArbuzAPITests.swift
1
1955
import XCTest @testable import WebAPI class MuzArbuzAPITests: XCTestCase { var subject = MuzArbuzAPI() // func testGetAlbums() throws { // let result = try subject.getAlbums() // // print(result as Any) // } // // func testGetAlbumContainer() throws { // let result = try subject.getAlbums(params: ["parent_id": "14485"]) // // print(result["items"] as Any) // } // // func testGetAlbumsByYearRange() throws { // let result = try subject.getAlbums(params: ["year__gte": "2014", "year__lte": "2015"]) // // print(result["items"] as Any) // } // // func testGetArtistTracks() throws { // let result = try subject.getTracks(params: ["artists": "1543"]) // // print(result["items"] as Any) // } // // func testGetAlbumTracks() throws { // let result = try subject.getTracks(params: ["album": "14486"]) // // print(result["items"] as Any) // } // // func testGetCollectionTracks() throws { // let result = try subject.getTracks(params: ["collection__id": "115"]) // // print(result["items"] as Any) // } // // func testGetArtists() throws { // let result = try subject.getArtists() // // print(result["items"] as Any) // } // // func testGetArtistAnnotated() throws { // let result = try subject.getArtistAnnotated(params: ["title__istartswith": "b"]) // // print(result["items"] as Any) // } // // func testGetCollections() throws { // let result = try subject.getCollections() // // print(result["items"] as Any) // } // // func testGetGenres() throws { // let result = try subject.getGenres() // // print(result["items"] as Any) // print((result["items"] as! [Any]).count) // } // // func testGetAlbumsByGenre() throws { // let result = try subject.getAlbums(params: ["genre__in": "1"]) // // print(result["items"] as Any) // } // // func testSearch() throws { // let result = try subject.search("макаревич") // // print(result as Any) // } }
mit
5eb82858f1a847ce7bab623bb94668d8
23.024691
92
0.6074
3.0938
false
true
false
false
russelhampton05/MenMew
App Prototypes/App_Prototype_A_001/RegisterViewController.swift
1
7071
// // RegisterViewController.swift // App_Prototype_Alpha_001 // // Created by Jon Calanio on 9/28/16. // Copyright © 2016 Jon Calanio. All rights reserved. // import UIKit import Firebase class RegisterViewController: UIViewController, UITextFieldDelegate { //IBOutlets @IBOutlet var registerLabel: UILabel! @IBOutlet var nameLabel: UILabel! @IBOutlet var emailLabel: UILabel! @IBOutlet var passwordLabel: UILabel! @IBOutlet var reenterLabel: UILabel! @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var confirmPasswordField: UITextField! @IBOutlet weak var confirmRegisterButton: UIButton! @IBOutlet var cancelButton: UIButton! @IBOutlet var nameLine: UIView! @IBOutlet var emailLine: UIView! @IBOutlet var passwordLine: UIView! @IBOutlet var reenterLine: UIView! override func viewDidLoad() { super.viewDidLoad() usernameField.delegate = self emailField.delegate = self passwordField.delegate = self confirmPasswordField.delegate = self confirmRegisterButton.isEnabled = false emailField.keyboardType = UIKeyboardType.emailAddress passwordField.isSecureTextEntry = true confirmPasswordField.isSecureTextEntry = true usernameField.autocorrectionType = UITextAutocorrectionType.no emailField.autocorrectionType = UITextAutocorrectionType.no passwordField.autocorrectionType = UITextAutocorrectionType.no confirmPasswordField.autocorrectionType = UITextAutocorrectionType.no loadTheme() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(_ textField: UITextField) -> Bool { let nextTag = textField.tag + 1 let nextResponder = textField.superview?.viewWithTag(nextTag) if nextResponder != nil { nextResponder?.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } func textFieldDidEndEditing(_ textField: UITextField) { if self.usernameField.text != "" && self.passwordField.text != "" && self.confirmPasswordField.text != "" { confirmRegisterButton.isEnabled = true } } @IBAction func registerButtonPressed(_ sender: AnyObject) { if !self.emailField.hasText || !self.usernameField.hasText || !self.passwordField.hasText { showPopup(message: "Please enter your name, email and password.", isRegister: false) } else if self.passwordField.text != self.confirmPasswordField.text { showPopup(message: "Password entries do not match.", isRegister: false) self.passwordField.text = "" self.confirmPasswordField.text = "" } else { FIRAuth.auth()?.createUser(withEmail: self.emailField.text!, password: self.passwordField.text!, completion: {(user, error) in if error == nil { //Create associated entry on Firebase let newUser = User(id: (user?.uid)!, email: (user?.email)!, name: self.usernameField.text!, ticket: nil, image: nil, theme: "Salmon", touchEnabled: true, notifications: true) UserManager.UpdateUser(user: newUser) currentUser = newUser self.emailField.text = "" self.passwordField.text = "" self.confirmPasswordField.text = "" self.showPopup(message: "Thank you for registering, " + self.usernameField.text! + "!", isRegister: true) self.usernameField.text = "" } else { self.showPopup(message: (error?.localizedDescription)!, isRegister: false) } }) } } @IBAction func cancelButtonPressed(_ sender: Any) { performSegue(withIdentifier: "UnwindToLoginSegue", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "QRScanSegue" { _ = segue.destination as! QRViewController } } func showPopup(message: String, isRegister: Bool) { let loginPopup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Popup") as! PopupViewController if isRegister { loginPopup.register = true } self.addChildViewController(loginPopup) loginPopup.view.frame = self.view.frame self.view.addSubview(loginPopup.view) loginPopup.didMove(toParentViewController: self) loginPopup.addMessage(context: message) } func loadTheme() { currentTheme = Theme.init(type: "Salmon") UIView.animate(withDuration: 0.8, animations: { () -> Void in //Background and Tint self.view.backgroundColor = currentTheme!.primary! self.view.tintColor = currentTheme!.highlight! //Labels self.registerLabel.textColor = currentTheme!.highlight! self.emailLine.backgroundColor = currentTheme!.highlight! self.passwordLine.backgroundColor = currentTheme!.highlight! self.nameLine.backgroundColor = currentTheme!.highlight! self.reenterLine.backgroundColor = currentTheme!.highlight! self.nameLabel.textColor = currentTheme!.highlight! self.emailLabel.textColor = currentTheme!.highlight! self.passwordLabel.textColor = currentTheme!.highlight! self.reenterLabel.textColor = currentTheme!.highlight! //Fields self.usernameField.textColor = currentTheme!.highlight! self.usernameField.tintColor = currentTheme!.highlight! self.emailField.textColor = currentTheme!.highlight! self.emailField.tintColor = currentTheme!.highlight! self.passwordField.textColor = currentTheme!.highlight! self.passwordField.tintColor = currentTheme!.highlight! self.confirmPasswordField.textColor = currentTheme!.highlight! self.confirmPasswordField.tintColor = currentTheme!.highlight! //Buttons self.confirmRegisterButton.backgroundColor = currentTheme!.highlight! self.confirmRegisterButton.setTitleColor(currentTheme!.primary!, for: .normal) self.cancelButton.backgroundColor = currentTheme!.highlight! self.cancelButton.setTitleColor(currentTheme!.primary!, for: .normal) }) } }
mit
eb036264db48d57420e5a226b07e0f4c
38.943503
194
0.625318
5.651479
false
false
false
false
hacktoolkit/GitHubBrowser-iOS
GitHubBrowser/viewControllers/OrganizationDetailsViewController.swift
1
6887
// // OrganizationDetails.swift // GitHubBrowser // // Created by Jonathan Tsai on 9/27/14. // Copyright (c) 2014 Hacktoolkit. All rights reserved. // import UIKit class OrganizationDetailsViewController: GitHubBrowserTableViewController, GitHubOrganizationDelegate { let organizationName = "hacktoolkit" var locationLabel: UILabel! var nameLabel: UILabel! var organization: GitHubOrganization! var organizationImageView: UIImageView! var activityIndicatorView: UIActivityIndicatorView! override init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() let screen = screenRect() let tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: CGRectGetWidth(screen), height: 100) ) tableHeaderView.backgroundColor = UIColor( white: 0, alpha: 0.1 ) self.mainTableView.tableHeaderView = tableHeaderView let imageViewWidth = CGRectGetHeight(tableHeaderView.frame) - 20 organizationImageView = UIImageView(frame: CGRect(x: 10, y: 10, width: imageViewWidth, height: imageViewWidth) ) organizationImageView.backgroundColor = UIColor( white: 0, alpha: 0.7 ) activityIndicatorView = UIActivityIndicatorView( activityIndicatorStyle: UIActivityIndicatorViewStyle.White ) organizationImageView.addSubview( activityIndicatorView ) activityIndicatorView.frame = CGRect( x: (CGRectGetWidth(organizationImageView.frame) - CGRectGetWidth(activityIndicatorView.frame)) * 0.5, y: (CGRectGetHeight(organizationImageView.frame) - CGRectGetHeight(activityIndicatorView.frame)) * 0.5, width: CGRectGetWidth(activityIndicatorView.frame), height: CGRectGetHeight(activityIndicatorView.frame) ) activityIndicatorView.startAnimating() tableHeaderView.addSubview(organizationImageView) nameLabel = UILabel(frame: CGRect( x: CGRectGetMinX(organizationImageView.frame) + CGRectGetWidth(organizationImageView.frame) + 10, y: CGRectGetMinY(organizationImageView.frame), width: CGRectGetWidth(screen), height: imageViewWidth * 0.5 ) ) nameLabel.font = UIFont.boldSystemFontOfSize(22) tableHeaderView.addSubview(nameLabel) locationLabel = UILabel(frame: CGRect( x: CGRectGetMinX(nameLabel.frame), y: CGRectGetMaxY(nameLabel.frame), width: CGRectGetWidth(nameLabel.frame), height: CGRectGetHeight(nameLabel.frame) ) ) locationLabel.font = UIFont.systemFontOfSize(15) locationLabel.textColor = UIColor(white: 0, alpha: 0.5) tableHeaderView.addSubview(locationLabel) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) var org = GitHubOrganization(name: organizationName, onInflated: { (org: GitHubResource) -> () in if let org = org as? GitHubOrganization { self.organization = org self.organization.delegate = self self.locationLabel.text = self.organization.location self.nameLabel.text = self.organization.name if self.title == nil { self.title = self.organization.name } dispatch_async(dispatch_get_main_queue(), { if self.organization.avatarUrl != nil { var test = UIImage(data: NSData(contentsOfURL: NSURL(string: self.organization.avatarUrl) ) ) self.organizationImageView.image = test self.activityIndicatorView.stopAnimating() } }); } }) org.getRepositories { (repositories: [GitHubRepository]) -> () in } self.mainTableView.reloadData() } let repo1 = GitHubRepository(repositoryDict: [ "description": "Description", "name": "Repo 1" ]) // Methods func objects() -> [GitHubRepository] { if self.organization != nil { return self.organization.repositories } // return [repo1] return [GitHubRepository]() } func objectAtIndexPath(indexPath: NSIndexPath) -> GitHubRepository { return objects()[indexPath.row] } // Protocols // Protocols - UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let reuseIdentifier = "ReuseIdentifier" let tableViewCell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: reuseIdentifier ) let repository = objectAtIndexPath(indexPath) let nameLabel = UILabel(frame: CGRect( x: 15, y: 22, width: 300, height: 27 ) ) nameLabel.font = UIFont.boldSystemFontOfSize(18) nameLabel.text = repository.name tableViewCell.contentView.addSubview(nameLabel) let descLabel = UILabel(frame: CGRect( x: 15, y: 22 + 27, width: 300, height: 22 ) ) descLabel.text = repository.description descLabel.textColor = self.locationLabel.textColor tableViewCell.contentView.addSubview(descLabel) return tableViewCell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects().count } // Protocols - UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let repository = objectAtIndexPath(indexPath) let vc = RepositoryDetailsViewController( repository: repository ) println(repository.name) navigationController?.pushViewController(vc, animated: true) tableView.deselectRowAtIndexPath(indexPath, animated: true) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 88 } // Protocols - GitHubOrganizationDelegate func didFinishFetching() { self.mainTableView.reloadData() } }
mit
73f8af044abade37e3195b7f7e6a65cf
34.137755
79
0.603746
5.710614
false
false
false
false
SwiftKit/Reactant
Source/Core/Component/ComponentDelegate.swift
2
5202
// // ComponentDelegate.swift // Reactant // // Created by Filip Dolnik on 09.11.16. // Copyright © 2016 Brightify. All rights reserved. // import RxSwift // COMPONENT and ACTION cannot have restriction to StateType because then it is impossible to use `ComponentWithDelegate` (associatedtype cannot be used with where). public final class ComponentDelegate<STATE, ACTION, COMPONENT: Component> { public var stateDisposeBag = DisposeBag() public var observableState: Observable<STATE> { return observableStateSubject } public var previousComponentState: STATE? = nil public var componentState: STATE { get { if let state = stateStorage { return state } else { fatalError("ComponentState accessed before stored!") } } set { previousComponentState = stateStorage stateStorage = newValue observableStateBeforeUpdate.onNext(newValue) needsUpdate = true observableStateSubject.onNext(newValue) } } public var action: Observable<ACTION> { return actionSubject } /** * Variable which is used internally by Reactant to call `Component.update()`. * * It's automatically set to false when the view is not shown. You can set it to `true` manually * if you need `Component.update()` called even if the view is not shown. * - NOTE: See `canUpdate`. * - WARNING: This variable shouldn't be changed by hand, it's used for syncing Reactant and calling `Component.update()`. */ public var needsUpdate: Bool = false { didSet { if needsUpdate && canUpdate { let componentStateBeforeUpdate = componentState update() observableStateAfterUpdate.onNext(componentStateBeforeUpdate) } } } /// Variable which controls whether the `Component.update()` method is called when `Component.componentState` is changed. public var canUpdate: Bool = false { didSet { if canUpdate && needsUpdate { let componentStateBeforeUpdate = componentState update() observableStateAfterUpdate.onNext(componentStateBeforeUpdate) } } } /// The Component which owns the current Component. public weak var ownerComponent: COMPONENT? { didSet { needsUpdate = stateStorage != nil } } public var actions: [Observable<ACTION>] = [] { didSet { actionsDisposeBag = DisposeBag() Observable.from(actions).merge().subscribe(onNext: perform).disposed(by: actionsDisposeBag) } } /** * Get-only variable through which you can safely check whether `Component.componentState` is set. * * Useful for guarding `Component.componentState` access when not in `Component.update()` */ public var hasComponentState: Bool { return stateStorage != nil } private let observableStateSubject = ReplaySubject<STATE>.create(bufferSize: 1) private let observableStateBeforeUpdate = PublishSubject<STATE>() private let observableStateAfterUpdate = PublishSubject<STATE>() private let actionSubject = PublishSubject<ACTION>() private var stateStorage: STATE? = nil private var actionsDisposeBag = DisposeBag() public init() { // If the model is Void, we set it so caller does not have to. if let voidState = Void() as? STATE { componentState = voidState } } deinit { observableStateSubject.onCompleted() actionSubject.onCompleted() observableStateBeforeUpdate.onCompleted() observableStateAfterUpdate.onCompleted() } public func perform(action: ACTION) { actionSubject.onNext(action) } public func observeState(_ when: ObservableStateEvent) -> Observable<STATE> { switch when { case .beforeUpdate: return observableStateBeforeUpdate case .afterUpdate: return observableStateAfterUpdate } } private func update() { guard stateStorage != nil else { #if DEBUG fatalError("ComponentState not set before needsUpdate and canUpdate were set! ComponentState \(STATE.self), component \(type(of: ownerComponent))") #else print("WARNING: ComponentState not set before needsUpdate and canUpdate were set. This is usually developer error by not calling `setComponentState` on Component that needs non-Void componentState. ComponentState \(STATE.self), component \(type(of: ownerComponent))") return #endif } needsUpdate = false #if DEBUG precondition(ownerComponent != nil, "Update called when ownerComponent is nil. Probably wasn't set in init of the component.") #endif if ownerComponent?.needsUpdate() == true { stateDisposeBag = DisposeBag() ownerComponent?.update() } } }
mit
b566bf0d31e76663719770808fbe8feb
32.993464
283
0.629302
5.190619
false
false
false
false
ReactiveKit/Bond
Sources/Bond/Observable Collections/Signal+ChangesetProtocol.swift
1
12860
// // The MIT License (MIT) // // Copyright (c) 2018 DeclarativeHub/Bond // // 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 ReactiveKit extension SignalProtocol where Element: ChangesetProtocol { /// When working with a changeset that calculates patch lazily, /// you can use this method to calculate the patch in advance. /// Observer will then have patch available in O(1). public func precalculatePatch() -> Signal<Element, Error> { return map { changeset in _ = changeset.patch return changeset } } /// When working with a changeset that calculates diff lazily, /// you can use this method to calculate the diff in advance. /// Observer will then have diff available in O(1). public func precalculateDiff() -> Signal<Element, Error> { return map { changeset in _ = changeset.diff return changeset } } } extension SignalProtocol where Element: Collection, Element.Index: Strideable { /// Generate the diff between previous and current collection using the provided diff generator function. public func diff(generateDiff: @escaping (Element, Element) -> OrderedCollectionChangeset<Element>.Diff) -> Signal<OrderedCollectionChangeset<Element>, Error> { return Signal { observer in var collection: Element? return self.observe { event in switch event { case .next(let element): let newCollection = element if let collection = collection { let diff = generateDiff(collection, newCollection) observer.receive(OrderedCollectionChangeset(collection: newCollection, patch: [], diff: diff)) } else { observer.receive(OrderedCollectionChangeset(collection: newCollection, patch: [])) } collection = newCollection case .failed(let error): observer.receive(completion: .failure(error)) case .completed: observer.receive(completion: .finished) } } } } } extension SignalProtocol where Element: TreeProtocol { /// Generate the diff between previous and current tree using the provided diff generator function. public func diff(generateDiff: @escaping (Element, Element) -> TreeChangeset<Element>.Diff) -> Signal<TreeChangeset<Element>, Error> { return Signal { observer in var collection: Element? return self.observe { event in switch event { case .next(let element): let newCollection = element if let collection = collection { let diff = generateDiff(collection, newCollection) observer.receive(TreeChangeset(collection: newCollection, patch: [], diff: diff)) } else { observer.receive(TreeChangeset(collection: newCollection, patch: [])) } collection = newCollection case .failed(let error): observer.receive(completion: .failure(error)) case .completed: observer.receive(completion: .finished) } } } } } extension SignalProtocol where Element: OrderedCollectionChangesetProtocol, Element.Collection.Index: Hashable { /// - complexity: Each event sorts the collection O(nlogn). public func sortedCollection(by areInIncreasingOrder: @escaping (Element.Collection.Element, Element.Collection.Element) -> Bool) -> Signal<OrderedCollectionChangeset<[Element.Collection.Element]>, Error> { var previousIndexMap: [Element.Collection.Index: Int] = [:] return map { (event: Element) -> OrderedCollectionChangeset<[Element.Collection.Element]> in let indices = event.collection.indices let elementsWithIndices = Swift.zip(event.collection, indices) let sortedElementsWithIndices = elementsWithIndices.sorted(by: { (a, b) -> Bool in return areInIncreasingOrder(a.0, b.0) }) let sortedElements = sortedElementsWithIndices.map { $0.0 } let indexMap = sortedElementsWithIndices.map { $0.1 }.enumerated().reduce([Element.Collection.Index: Int](), { (indexMap, new) -> [Element.Collection.Index: Int] in return indexMap.merging([new.element: new.offset], uniquingKeysWith: { $1 }) }) let diff = event.diff.transformingIndices(fromIndexMap: previousIndexMap, toIndexMap: indexMap) previousIndexMap = indexMap return OrderedCollectionChangeset( collection: sortedElements, diff: diff ) } } } extension SignalProtocol where Element: OrderedCollectionChangesetProtocol, Element.Collection.Index: Hashable, Element.Collection.Element: Comparable { /// - complexity: Each event sorts collection O(nlogn). public func sortedCollection() -> Signal<OrderedCollectionChangeset<[Element.Collection.Element]>, Error> { return sortedCollection(by: <) } } extension SignalProtocol where Element: UnorderedCollectionChangesetProtocol, Element.Collection.Index: Hashable { /// - complexity: Each event sorts the collection O(nlogn). public func sortedCollection(by areInIncreasingOrder: @escaping (Element.Collection.Element, Element.Collection.Element) -> Bool) -> Signal<OrderedCollectionChangeset<[Element.Collection.Element]>, Error> { var previousIndexMap: [Element.Collection.Index: Int] = [:] return map { (event: Element) -> OrderedCollectionChangeset<[Element.Collection.Element]> in let indices = event.collection.indices let elementsWithIndices = Swift.zip(event.collection, indices) let sortedElementsWithIndices = elementsWithIndices.sorted(by: { (a, b) -> Bool in return areInIncreasingOrder(a.0, b.0) }) let sortedElements = sortedElementsWithIndices.map { $0.0 } let indexMap = sortedElementsWithIndices.map { $0.1 }.enumerated().reduce([Element.Collection.Index: Int](), { (indexMap, new) -> [Element.Collection.Index: Int] in return indexMap.merging([new.element: new.offset], uniquingKeysWith: { $1 }) }) let diff = event.diff.transformingIndices(fromIndexMap: previousIndexMap, toIndexMap: indexMap) previousIndexMap = indexMap return OrderedCollectionChangeset( collection: sortedElements, diff: OrderedCollectionDiff(inserts: diff.inserts, deletes: diff.deletes, updates: diff.updates, moves: []) ) } } } extension SignalProtocol where Element: UnorderedCollectionChangesetProtocol, Element.Collection.Index: Hashable, Element.Collection.Element: Comparable { /// - complexity: Each event sorts collection O(nlogn). public func sortedCollection() -> Signal<OrderedCollectionChangeset<[Element.Collection.Element]>, Error> { return sortedCollection(by: <) } } extension SignalProtocol where Element: OrderedCollectionChangesetProtocol, Element.Collection.Index == Int { /// - complexity: Each event transforms collection O(n). Use `lazyMapCollection` if you need on-demand mapping. public func mapCollection<U>(_ transform: @escaping (Element.Collection.Element) -> U) -> Signal<OrderedCollectionChangeset<[U]>, Error> { return map { (event: Element) -> OrderedCollectionChangeset<[U]> in return OrderedCollectionChangeset( collection: event.collection.map(transform), diff: event.diff ) } } /// - complexity: O(1). public func lazyMapCollection<U>(_ transform: @escaping (Element.Collection.Element) -> U) -> Signal<OrderedCollectionChangeset<LazyMapCollection<Element.Collection, U>>, Error> { return map { (event: Element) -> OrderedCollectionChangeset<LazyMapCollection<Element.Collection, U>> in return OrderedCollectionChangeset( collection: event.collection.lazy.map(transform), diff: event.diff ) } } /// - complexity: Each event transforms collection O(n). public func filterCollection(_ isIncluded: @escaping (Element.Collection.Element) -> Bool) -> Signal<OrderedCollectionChangeset<[Element.Collection.Element]>, Error> { var previousIndexMap: [Int: Int] = [:] return map { (event: Element) -> OrderedCollectionChangeset<[Element.Collection.Element]> in let collection = event.collection var filtered: [Element.Collection.Element] = [] var indexMap: [Int: Int] = [:] filtered.reserveCapacity(collection.count) indexMap.reserveCapacity(collection.count) var iterator = 0 for (index, element) in collection.enumerated() { if isIncluded(element) { filtered.append(element) indexMap[index] = iterator iterator += 1 } } let diff = event.diff.transformingIndices(fromIndexMap: previousIndexMap, toIndexMap: indexMap) previousIndexMap = indexMap return OrderedCollectionChangeset( collection: filtered, diff: diff ) } } } extension OrderedCollectionDiff where Index: Hashable { public func transformingIndices<NewIndex>(fromIndexMap: [Index: NewIndex], toIndexMap: [Index: NewIndex]) -> OrderedCollectionDiff<NewIndex> { var inserts = self.inserts.compactMap { toIndexMap[$0] } var deletes = self.deletes.compactMap { fromIndexMap[$0] } let moves = self.moves.compactMap { (move: (from: Index, to: Index)) -> (from: NewIndex, to: NewIndex)? in if let mappedFrom = fromIndexMap[move.from], let mappedTo = toIndexMap[move.to] { return (from: mappedFrom, to: mappedTo) } else { return nil } } var updates: [NewIndex] = [] for index in self.updates { if let mappedIndex = toIndexMap[index] { if let _ = fromIndexMap[index] { updates.append(mappedIndex) } else { inserts.append(mappedIndex) } } else if let mappedIndex = fromIndexMap[index] { deletes.append(mappedIndex) } } return OrderedCollectionDiff<NewIndex>(inserts: inserts, deletes: deletes, updates: updates, moves: moves) } } extension UnorderedCollectionDiff where Index: Hashable { public func transformingIndices<NewIndex>(fromIndexMap: [Index: NewIndex], toIndexMap: [Index: NewIndex]) -> UnorderedCollectionDiff<NewIndex> { var inserts = self.inserts.compactMap { toIndexMap[$0] } var deletes = self.deletes.compactMap { fromIndexMap[$0] } var updates: [NewIndex] = [] for index in self.updates { if let mappedIndex = toIndexMap[index] { if let _ = fromIndexMap[index] { updates.append(mappedIndex) } else { inserts.append(mappedIndex) } } else if let mappedIndex = fromIndexMap[index] { deletes.append(mappedIndex) } } return UnorderedCollectionDiff<NewIndex>(inserts: inserts, deletes: deletes, updates: updates) } }
mit
d5fc882286ad677ebac1e7de91b9d558
44.441696
210
0.634759
4.930982
false
false
false
false
antitypical/Manifold
Manifold/Term.swift
1
1815
// Copyright © 2015 Rob Rix. All rights reserved. public indirect enum Term: Equatable, Hashable, IntegerLiteralConvertible, NilLiteralConvertible, StringLiteralConvertible, TermContainerType { case In(Set<Name>, Scoping<Term>) public init(_ scoping: Scoping<Term>) { switch scoping { case let .Variable(name): self = .Variable(name) case let .Abstraction(name, scope): self = .Abstraction(name, scope) case let .Identity(body): self = Term(body) } } public init(_ expression: Expression<Term>) { self = .In(expression.foldMap { $0.freeVariables }, .Identity(expression)) } // MARK: Hashable public var hashValue: Int { return cata { switch $0 { case let .Identity(.Type(n)): return (Int.max - 59) ^ n case let .Variable(n): return (Int.max - 83) ^ n.hashValue case let .Identity(.Application(a, b)): return (Int.max - 95) ^ a ^ b case let .Identity(.Lambda(t, b)): return (Int.max - 179) ^ t ^ b case let .Identity(.Embedded(_, _, type)): return (Int.max - 189) ^ type case .Identity(.Implicit): return (Int.max - 257) case let .Abstraction(name, term): return (Int.max - 279) ^ name.hashValue ^ term.hashValue } } } // MARK: IntegerLiteralConvertible public init(integerLiteral value: Int) { self = .Variable(.Local(value)) } // MARK: NilLiteralConvertible public init(nilLiteral: ()) { self.init(.Implicit) } // MARK: StringLiteralConvertible public init(stringLiteral value: String) { self = .Variable(.Global(value)) } // MARK: TermContainerType public var out: Scoping<Term> { switch self { case let .In(_, f): return f } } } public func == (left: Term, right: Term) -> Bool { return left.freeVariables == right.freeVariables && Scoping.equal(==)(left.out, right.out) }
mit
ab152f2b91ea6772b55f525dfdd8606d
21.395062
143
0.655458
3.298182
false
false
false
false
dropbox/SwiftyDropbox
Source/SwiftyDropbox/Shared/Handwritten/OAuth/OAuthConstants.swift
1
846
/// /// Copyright (c) 2020 Dropbox, Inc. All rights reserved. /// import Foundation /// Contains the keys of URL queries and responses in auth flow. enum OAuthConstants { static let codeChallengeKey = "code_challenge" static let codeChallengeMethodKey = "code_challenge_method" static let tokenAccessTypeKey = "token_access_type" static let responseTypeKey = "response_type" static let scopeKey = "scope" static let includeGrantedScopesKey = "include_granted_scopes" static let stateKey = "state" static let extraQueryParamsKey = "extra_query_params" static let oauthCodeKey = "oauth_code" static let oauthTokenKey = "oauth_token" static let oauthSecretKey = "oauth_token_secret" static let uidKey = "uid" static let errorKey = "error" static let errorDescription = "error_description" }
mit
8b12ebc645ecc74031373e1058e6d5c6
35.782609
65
0.723404
4.126829
false
false
false
false
opentable/CocoaLumberjack
Classes/CocoaLumberjack.swift
1
4593
// Software License Agreement (BSD License) // // Copyright (c) 2014-2015, Deusty, LLC // All rights reserved. // // Redistribution and use of this software in source and binary forms, // with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Neither the name of Deusty nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission of Deusty, LLC. import Foundation import CocoaLumberjack extension DDLogFlag { public static func fromLogLevel(logLevel: DDLogLevel) -> DDLogFlag { return DDLogFlag(logLevel.rawValue) } ///returns the log level, or the lowest equivalant. public func toLogLevel() -> DDLogLevel { if let ourValid = DDLogLevel(rawValue: self.rawValue) { return ourValid } else { let logFlag = self if logFlag & .Verbose == .Verbose { return .Verbose } else if logFlag & .Debug == .Debug { return .Debug } else if logFlag & .Info == .Info { return .Info } else if logFlag & .Warning == .Warning { return .Warning } else if logFlag & .Error == .Error { return .Error } else { return .Off } } } } extension DDMultiFormatter { public var formatterArray: [DDLogFormatter] { return self.formatters as [DDLogFormatter] } } public var defaultDebugLevel = DDLogLevel.Verbose public func resetDefaultDebugLevel() { defaultDebugLevel = DDLogLevel.Verbose } public func SwiftLogMacro(isAsynchronous: Bool, level: DDLogLevel, flag flg: DDLogFlag, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, tag: AnyObject? = nil, #string: @autoclosure () -> String) { if level.rawValue & flg.rawValue != 0 { // Tell the DDLogMessage constructor to copy the C strings that get passed to it. Using string interpolation to prevent integer overflow warning when using StaticString.stringValue let logMessage = DDLogMessage(message: string(), level: level, flag: flg, context: context, file: "\(file)", function: "\(function)", line: line, tag: tag, options: .CopyFile | .CopyFunction, timestamp: nil) DDLog.log(isAsynchronous, message: logMessage) } } public func DDLogDebug(logText: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, asynchronous async: Bool = true) { SwiftLogMacro(async, level, flag: .Debug, file: file, function: function, line: line, string: logText) } public func DDLogInfo(logText: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, asynchronous async: Bool = true) { SwiftLogMacro(async, level, flag: .Info, file: file, function: function, line: line, string: logText) } public func DDLogWarn(logText: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, asynchronous async: Bool = true) { SwiftLogMacro(async, level, flag: .Warning, file: file, function: function, line: line, string: logText) } public func DDLogVerbose(logText: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, asynchronous async: Bool = true) { SwiftLogMacro(async, level, flag: .Verbose, file: file, function: function, line: line, string: logText) } public func DDLogError(logText: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, asynchronous async: Bool = false) { SwiftLogMacro(async, level, flag: .Error, file: file, function: function, line: line, string: logText) } /// Analogous to the C preprocessor macro THIS_FILE public func CurrentFileName(fileName: StaticString = __FILE__) -> String { // Using string interpolation to prevent integer overflow warning when using StaticString.stringValue return "\(fileName)".lastPathComponent.stringByDeletingPathExtension }
bsd-3-clause
ee1473bee82dbd4259ee70add16ee86c
49.472527
259
0.682996
4.429122
false
false
false
false
djtone/VIPER
VIPER-SWIFT/Classes/Common/Categories/NSCalendar+CalendarAdditions.swift
2
7060
// // NSCalendar+CalendarAdditions.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/5/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation extension NSCalendar { class func gregorianCalendar() -> NSCalendar { return NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! } func dateWithYear(year: Int, month: Int, day: Int) -> NSDate { let components = NSDateComponents() components.year = year components.month = month components.day = day components.hour = 12 return dateFromComponents(components)! } func dateForTomorrowRelativeToToday(today: NSDate) -> NSDate { let tomorrowComponents = NSDateComponents() tomorrowComponents.day = 1 return dateByAddingComponents(tomorrowComponents, toDate: today, options: nil)! } func dateForEndOfWeekWithDate(date: NSDate) -> NSDate { let daysRemainingThisWeek = daysRemainingInWeekWithDate(date) let remainingDaysComponent = NSDateComponents() remainingDaysComponent.day = daysRemainingThisWeek return dateByAddingComponents(remainingDaysComponent, toDate: date, options: nil)! } func dateForBeginningOfDay(date: NSDate) -> NSDate { let newComponent = components((NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay), fromDate: date) let newDate = dateFromComponents(newComponent) return newDate! } func dateForEndOfDay(date: NSDate) -> NSDate { let components = NSDateComponents() components.day = 1 let toDate = dateForBeginningOfDay(date) let nextDay = dateByAddingComponents(components, toDate: toDate, options: nil) let endDay = nextDay!.dateByAddingTimeInterval(-1) return nextDay! } func daysRemainingInWeekWithDate(date: NSDate) -> Int { let weekdayComponent = components(NSCalendarUnit.CalendarUnitWeekday, fromDate: date) let daysRange = rangeOfUnit(NSCalendarUnit.CalendarUnitWeekday, inUnit: NSCalendarUnit.CalendarUnitWeekOfYear, forDate: date) let daysPerWeek = daysRange.length let daysRemaining = daysPerWeek - weekdayComponent.weekday return daysRemaining } func dateForEndOfFollowingWeekWithDate(date: NSDate) -> NSDate { let endOfWeek = dateForEndOfWeekWithDate(date) let nextWeekComponent = NSDateComponents() nextWeekComponent.weekOfYear = 1 let followingWeekDate = dateByAddingComponents(nextWeekComponent, toDate: endOfWeek, options: nil) return followingWeekDate! } func isDate(date: NSDate, beforeYearMonthDay: NSDate) -> Bool { let comparison = compareYearMonthDay(date, toYearMonthDay: beforeYearMonthDay) let result = comparison == NSComparisonResult.OrderedAscending return result } func isDate(date: NSDate, equalToYearMonthDay: NSDate) -> Bool { let comparison = compareYearMonthDay(date, toYearMonthDay: equalToYearMonthDay) let result = comparison == NSComparisonResult.OrderedSame return result } func isDate(date: NSDate, duringSameWeekAsDate: NSDate) -> Bool { let dateComponents = components(NSCalendarUnit.CalendarUnitWeekOfYear, fromDate: date) let duringSameWeekComponents = components(NSCalendarUnit.CalendarUnitWeekOfYear, fromDate: duringSameWeekAsDate) let result = dateComponents.weekOfMonth == duringSameWeekComponents.weekOfMonth return result } func isDate(date: NSDate, duringWeekAfterDate: NSDate) -> Bool { let nextWeek = dateForEndOfFollowingWeekWithDate(duringWeekAfterDate) let dateComponents = components(NSCalendarUnit.CalendarUnitWeekOfYear, fromDate: date) let nextWeekComponents = components(NSCalendarUnit.CalendarUnitWeekOfYear, fromDate: nextWeek) let result = dateComponents.weekOfYear == nextWeekComponents.weekOfYear return result } func compareYearMonthDay(date: NSDate, toYearMonthDay: NSDate) -> NSComparisonResult { let dateComponents = yearMonthDayComponentsFromDate(date) let yearMonthDayComponents = yearMonthDayComponentsFromDate(toYearMonthDay) var result = compareInteger(dateComponents.year, right: yearMonthDayComponents.year) if result == NSComparisonResult.OrderedSame { result = compareInteger(dateComponents.month, right: yearMonthDayComponents.month) if result == NSComparisonResult.OrderedSame { result = compareInteger(dateComponents.day, right: yearMonthDayComponents.day) } } return result } func yearMonthDayComponentsFromDate(date: NSDate) -> NSDateComponents { let newComponents = components((NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay), fromDate: date) return newComponents } func compareInteger(left: Int, right: Int) -> NSComparisonResult { var result = NSComparisonResult.OrderedDescending if left == right { result = NSComparisonResult.OrderedSame } else if left < right { result = NSComparisonResult.OrderedAscending } else { result = NSComparisonResult.OrderedDescending } return result } func nearTermRelationForDate(date: NSDate, relativeToToday: NSDate) -> NearTermDateRelation { var relation = NearTermDateRelation.OutOfRange let dateForTomorrow = dateForTomorrowRelativeToToday(relativeToToday) let isDateBeforeYearMonthDay = isDate(date, beforeYearMonthDay: relativeToToday) let isDateEqualToYearMonthDay = isDate(date, equalToYearMonthDay: relativeToToday) let isDateEqualToYearMonthDayRelativeToTomorrow = isDate(date, equalToYearMonthDay: dateForTomorrow) let isDateDuringSameWeekAsDate = isDate(date, duringSameWeekAsDate: relativeToToday) let isDateDuringSameWeekAfterDate = isDate(date, duringWeekAfterDate: relativeToToday) if isDateBeforeYearMonthDay { relation = NearTermDateRelation.OutOfRange } else if isDateEqualToYearMonthDay { relation = NearTermDateRelation.Today } else if isDateEqualToYearMonthDayRelativeToTomorrow { let isRelativeDateDuringSameWeek = isDate(relativeToToday, duringSameWeekAsDate: date) if isRelativeDateDuringSameWeek { relation = NearTermDateRelation.Tomorrow } else { relation = NearTermDateRelation.NextWeek } } else if isDateDuringSameWeekAsDate { relation = NearTermDateRelation.LaterThisWeek } else if isDateDuringSameWeekAfterDate { relation = NearTermDateRelation.NextWeek } return relation } }
mit
1d3fd73ac2238698b6d07d40a5017031
42.319018
157
0.698442
5.494163
false
false
false
false
zhaobin19918183/zhaobinCode
FamilyShop/FamilyShop/HomeViewController/HomeViewController.swift
1
3651
// // HomeViewController.swift // FamilyShop // // Created by Zhao.bin on 16/9/26. // Copyright © 2016年 Zhao.bin. All rights reserved. // import UIKit import Alamofire import AlamofireImage import AVFoundation class HomeViewController: UIViewController { weak var bookListEntity : BookListEntity? var EndDic:NSDictionary! var EndArray:NSArray! var avAudioPlayer:AVAudioPlayer! var TestViewController:testViewController! override func viewDidLoad() { super.viewDidLoad() //alamofireUploadFile() let webView = UIWebView(frame:self.view.bounds) let url = NSURL(string: "https://www.baidu.com") let request = NSURLRequest(url: url as! URL) webView.loadRequest(request as URLRequest) self.view.addSubview(webView) netWorkStatusType() TestViewController = testViewController() self.addChildViewController(TestViewController) } func initAVAudioPlayer(){ do{ try self.avAudioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: Bundle.main.path(forResource: "Stream", ofType: "mp3")!) as URL) self.avAudioPlayer.play() }catch let error as NSError{ print(error.localizedDescription) } } func netWorkStatusType() { let manager = NetWorkManager.networkStateJudgement() print(manager.SuccessOrError,manager.type) } func coreDataArray() { print(BookListDAO.SearchAllDataEntity().count) for dic in BookListDAO.SearchAllDataEntity() { let dicBookList = dic as! BookListEntity print(dicBookList.date! as String) } } func alamofireRequest() { Alamofire.request("http://op.juhe.cn/onebox/basketball/nba?dtype=&=&key=a77b663959938859a741024f8cbb11ac").responseJSON { (data) in let dic = data.result.value as! [String:AnyObject] let arr = dic["result"]?["list"] as! NSArray self.EndDic = arr.object(at: 0) as! NSDictionary // self.EndArray = self.EndDic.value(forKey: "tr") as! NSArray! } } func alamofireUploadFile() { let image : UIImage = UIImage(named:"屏幕快照 2016-09-02 下午12.40.08.png")! let imageData = UIImagePNGRepresentation(image) let parameters = ["name":"Adis4"] NetWorkManager.alamofireUploadFile(url: "http://127.0.0.1:8000/blog/home", parameters: parameters, data:imageData!, withName: "image", fileName: "zhaobin.png") } func bengkui() { let image : UIImage = UIImage(named:"屏幕快照 2016-09-02 下午12.40.08.png")! let imageData = UIImagePNGRepresentation(image) let parameters = ["name":"zhaobin", "date": "2011-10-11", "address" : "address","number" : "111111111111111111","email" : "[email protected]"] NetWorkManager.alamofireUploadFile(url: "http://127.0.0.1:8000/blog/wxSmall", parameters: parameters, data:imageData!, withName: "image", fileName: "zhaobin.png") } // let image : UIImage = UIImage(named:"屏幕快照 2016-09-02 下午12.40.08.png")! // let imageData = UIImagePNGRepresentation(image) // let parameters = ["name":"zhaobin", "date": "2011-10-11", "address" : "address","number" : "111111111111111111","email" : "[email protected]"] // NetWorkManager.alamofireUploadFile(url: "http://127.0.0.1:8000/polls/wxSmall", parameters: parameters, data:imageData!, withName: "image", fileName: "zhaobin.png") //} }
gpl-3.0
26d142f33553c2d31533e27d02b303cb
35.484848
174
0.636213
3.921824
false
true
false
false
TheHolyGrail/Historian
ELCacheExample/ELCacheExample/ImageCollectionVC.swift
2
2438
// // ImageCollectionVC.swift // ELCacheExample // // Created by Sam Grover on 12/28/15. // Copyright © 2015 WalmartLabs. All rights reserved. // import UIKit import ELCache class ImageCollectionVC : UICollectionViewController { var allImages: [String]? let ItemCount = 100 override func viewDidLoad() { collectionView?.registerClass(ImageCell.self, forCellWithReuseIdentifier: "ImageClass") buildImageURLs() } func buildImageURLs() { var images = [String]() for _ in 1...ItemCount { images.append(randomFillMurrayURL()) } allImages = images } // All images are the same but with differing URLs func randomHTTPBinURL() -> String { let baseURL = "http://httpbin.org/image/jpeg" let maxDimension = 100 let number = abs(random() % maxDimension) return baseURL + "?" + String(number) } // Gets cached properly func randomPlaceholdItURL() -> String { let baseURL = "http://placehold.it/" let maxDimension = 500 let width = abs(random() % maxDimension) let height = abs(random() % maxDimension) return baseURL + String(width) + "x" + String(height) + "/000.jpg" } // Doesn't get cached in NSURLCache for some reason func randomFillMurrayURL() -> String { let baseURL = "http://fillmurray.com/" let maxDimension = 500 let width = abs(random() % maxDimension) let height = abs(random() % maxDimension) return baseURL + String(width) + "/" + String(height) } } // UICollectionViewDataSource extension ImageCollectionVC { override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return ItemCount } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) if let imageCell = cell as? ImageCell, let anImageURLString = allImages?[indexPath.item] { if let URL = NSURL(string: anImageURLString) { imageCell.imageView.setImageAt(URL) { (_,_) in } } } return cell } } // UICollectionViewDelegate extension ImageCollectionVC { }
mit
43cfdd3c17ba1e2a6acf820f03bf6e38
29.4625
139
0.636438
4.816206
false
false
false
false
keith/radars
NSDocumentSwiftAnnotations/NSDocumentSwiftAnnotations/Document.swift
1
1873
import Cocoa final class Document: NSDocument { override func makeWindowControllers() { let windowController = NSStoryboard(name: "Main", bundle: nil) .instantiateController(withIdentifier: "WindowController") as! NSWindowController self.addWindowController(windowController) } override func canClose(withDelegate delegate: Any, shouldClose shouldCloseSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) { // Passing both arguments works fine as expected // super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: contextInfo) // Passing nil for either the selctor, or the context crashes super.canClose(withDelegate: delegate, shouldClose: nil, contextInfo: contextInfo) // super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: nil) // If you wanted to do anything with delegate, perhaps actually calling the selector, you'd have to // do something like this: // typealias Function = @convention(c) // (NSObject, Selector, NSDocument, Bool, UnsafeMutableRawPointer) -> Void // // // Here you need to cast the delegate to an NSObject(Protocol), so that you can send messages to it // guard let selector = shouldCloseSelector, let context = contextInfo, // let object = delegate as? NSObject, let objcClass = objc_getClass(object.className) as? AnyClass, // let method = class_getMethodImplementation(objcClass, selector) else // { // super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: contextInfo) // return // } // // let function = unsafeBitCast(method, to: Function.self) // function(object, selector, self, true, context) } }
mit
bc64f91f4f24f7d7198e17c441b965ca
48.289474
112
0.684997
5.075881
false
false
false
false
devpunk/cartesian
cartesian/Controller/Main/CParent.swift
1
9793
import UIKit class CParent:UIViewController { enum TransitionVertical:CGFloat { case fromTop = -1 case fromBottom = 1 case none = 0 } enum TransitionHorizontal:CGFloat { case fromLeft = -1 case fromRight = 1 case none = 0 } private(set) weak var viewParent:VParent! private var barHidden:Bool = false private let kStatusBarStyle:UIStatusBarStyle = UIStatusBarStyle.default init() { super.init(nibName:nil, bundle:nil) } required init?(coder:NSCoder) { return nil } override func viewDidLoad() { super.viewDidLoad() let controllerDraw:CDrawList = CDrawList() mainController(controller:controllerDraw) MSession.sharedInstance.loadSession() } override func loadView() { let viewParent:VParent = VParent(controller:self) self.viewParent = viewParent view = viewParent } override var preferredStatusBarStyle:UIStatusBarStyle { return kStatusBarStyle } override var prefersStatusBarHidden:Bool { return barHidden } //MARK: private private func slide(controller:CController, left:CGFloat) { guard let currentController:CController = childViewControllers.last as? CController, let newView:VView = controller.view as? VView, let currentView:VView = currentController.view as? VView else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) viewParent.slide( currentView:currentView, newView:newView, left:left) { controller.endAppearanceTransition() currentController.endAppearanceTransition() currentController.removeFromParentViewController() } } //MARK: public func hideBar(barHidden:Bool) { self.barHidden = barHidden setNeedsStatusBarAppearanceUpdate() } func slideTo(horizontal:TransitionHorizontal, controller:CController) { let left:CGFloat = -viewParent.bounds.maxX * horizontal.rawValue slide(controller:controller, left:left) } func mainController(controller:CController) { addChildViewController(controller) guard let newView:VView = controller.view as? VView else { return } viewParent.mainView(view:newView) } func push( controller:CController, horizontal:TransitionHorizontal = TransitionHorizontal.none, vertical:TransitionVertical = TransitionVertical.none, background:Bool = true, completion:(() -> ())? = nil) { let width:CGFloat = viewParent.bounds.maxX let height:CGFloat = viewParent.bounds.maxY let left:CGFloat = width * horizontal.rawValue let top:CGFloat = height * vertical.rawValue guard let currentController:CController = childViewControllers.last as? CController, let newView:VView = controller.view as? VView else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) viewParent.panRecognizer.isEnabled = true viewParent.push( newView:newView, left:left, top:top, background:background) { controller.endAppearanceTransition() currentController.endAppearanceTransition() completion?() } } func animateOver(controller:CController) { guard let currentController:CController = childViewControllers.last as? CController, let newView:VView = controller.view as? VView else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) viewParent.animateOver( newView:newView) { controller.endAppearanceTransition() currentController.endAppearanceTransition() } } func removeBetweenFirstAndLast() { var controllers:Int = childViewControllers.count - 1 while controllers > 1 { controllers -= 1 guard let controller:CController = childViewControllers[controllers] as? CController, let view:VView = controller.view as? VView else { continue } controller.beginAppearanceTransition(false, animated:false) view.removeFromSuperview() controller.endAppearanceTransition() controller.removeFromParentViewController() } } func removeAllButLast() { var controllers:Int = childViewControllers.count - 1 while controllers > 0 { controllers -= 1 guard let controller:CController = childViewControllers[controllers] as? CController, let view:VView = controller.view as? VView else { continue } controller.beginAppearanceTransition(false, animated:false) view.removeFromSuperview() controller.endAppearanceTransition() controller.removeFromParentViewController() } } func pop( horizontal:TransitionHorizontal = TransitionHorizontal.none, vertical:TransitionVertical = TransitionVertical.none, completion:(() -> ())? = nil) { let width:CGFloat = viewParent.bounds.maxX let height:CGFloat = viewParent.bounds.maxY let left:CGFloat = width * horizontal.rawValue let top:CGFloat = height * vertical.rawValue let controllers:Int = childViewControllers.count if controllers > 1 { guard let currentController:CController = childViewControllers[controllers - 1] as? CController, let previousController:CController = childViewControllers[controllers - 2] as? CController, let currentView:VView = currentController.view as? VView else { return } currentController.beginAppearanceTransition(false, animated:true) previousController.beginAppearanceTransition(true, animated:true) viewParent.pop( currentView:currentView, left:left, top:top) { previousController.endAppearanceTransition() currentController.endAppearanceTransition() currentController.removeFromParentViewController() completion?() if self.childViewControllers.count > 1 { self.viewParent.panRecognizer.isEnabled = true } else { self.viewParent.panRecognizer.isEnabled = false } } } } func popSilent(removeIndex:Int) { let controllers:Int = childViewControllers.count if controllers > removeIndex { guard let removeController:CController = childViewControllers[removeIndex] as? CController, let removeView:VView = removeController.view as? VView else { return } removeView.pushBackground?.removeFromSuperview() removeView.removeFromSuperview() removeController.removeFromParentViewController() if childViewControllers.count < 2 { self.viewParent.panRecognizer.isEnabled = false } } } func dismissAnimateOver(completion:(() -> ())?) { guard let currentController:CController = childViewControllers.last as? CController, let currentView:VView = currentController.view as? VView else { return } currentController.removeFromParentViewController() guard let previousController:CController = childViewControllers.last as? CController else { return } currentController.beginAppearanceTransition(false, animated:true) previousController.beginAppearanceTransition(true, animated:true) viewParent.dismissAnimateOver( currentView:currentView) { currentController.endAppearanceTransition() previousController.endAppearanceTransition() completion?() } } }
mit
2195ef36f38fa128737365392ae9ce5e
27.385507
107
0.558052
6.430072
false
false
false
false
biohazardlover/ByTrain
ByTrain/Entities/Train.swift
1
9251
import SwiftyJSON public struct Train { public var train_no: String? /// 车次 public var station_train_code: String? public var start_station_telecode: String? /// 出发站 public var start_station_name: String? public var end_station_telecode: String? /// 到达站 public var end_station_name: String? public var from_station_telecode: String? public var from_station_name: String? public var to_station_telecode: String? public var to_station_name: String? /// 出发时间 public var start_time: String? /// 到达时间 public var arrive_time: String? public var day_difference: String? public var train_class_name: String? /// 历时 public var lishi: String? public var canWebBuy: String? public var lishiValue: String? /// 余票信息 public var yp_info: String? public var control_train_day: String? public var start_train_date: String? public var seat_feature: String? public var yp_ex: String? public var train_seat_feature: String? public var seat_types: String? public var location_code: String? public var from_station_no: String? public var to_station_no: String? public var control_day: String? public var sale_time: String? public var is_support_card: String? public var gg_num: String? /// 高级软卧 public var gr_num: String? /// 其他 public var qt_num: String? /// 软卧 public var rw_num: String? /// 软座 public var rz_num: String? /// 特等座 public var tz_num: String? /// 无座 public var wz_num: String? public var yb_num: String? /// 硬卧 public var yw_num: String? /// 硬座 public var yz_num: String? /// 二等座 public var ze_num: String? /// 一等座 public var zy_num: String? /// 商务座 public var swz_num: String? public var secretStr: String? public var buttonTextInfo: String? public var distance: String? public var fromStation: Station? public var toStation: Station? public var departureDate: Date? public var businessClassSeatType: SeatType public var specialClassSeatType: SeatType public var firstClassSeatType: SeatType public var secondClassSeatType: SeatType public var premiumSoftRoometteType: SeatType public var softRoometteType: SeatType public var hardRoometteType: SeatType public var softSeatType: SeatType public var hardSeatType: SeatType public var noSeatType: SeatType public var otherType: SeatType public var allSeatTypes: [SeatType] public var duration: String? { if let durationInMinutes = Int(lishiValue ?? "") { let days = durationInMinutes / (60 * 24) let hours = (durationInMinutes % (60 * 24)) / 60 let minutes = (durationInMinutes % (60 * 24)) % 60 var duration = "" if days > 0 { duration += "\(days)天" } if hours > 0 { duration += "\(hours)小时" } duration += "\(minutes)分" return duration } return nil } /// yyyy-MM-dd public var departureDateString: String? { if let start_train_date = start_train_date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyyMMdd" if let departureDate = dateFormatter.date(from: start_train_date) { dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.string(from: departureDate) } } return nil } public var availableSeatTypes: [SeatType] { let availableSeatTypes = allSeatTypes.filter { (seatType) -> Bool in return seatType.leftSeats != "--" } return availableSeatTypes } public var highlightedSeatType: SeatType? { for seatType in availableSeatTypes.reversed() { if seatType.leftSeats != "无" { return seatType } } return availableSeatTypes.last } public init() { businessClassSeatType = SeatType(identifier: SeatTypeIdentifierBusinessClassSeat) specialClassSeatType = SeatType(identifier: SeatTypeIdentifierSpecialClassSeat) firstClassSeatType = SeatType(identifier: SeatTypeIdentifierFirstClassSeat) secondClassSeatType = SeatType(identifier: SeatTypeIdentifierSecondClassSeat) premiumSoftRoometteType = SeatType(identifier: SeatTypeIdentifierPremiumSoftRoomette) softRoometteType = SeatType(identifier: SeatTypeIdentifierSoftRoomette) hardRoometteType = SeatType(identifier: SeatTypeIdentifierHardRoomette) softSeatType = SeatType(identifier: SeatTypeIdentifierSoftSeat) hardSeatType = SeatType(identifier: SeatTypeIdentifierHardSeat) noSeatType = SeatType(identifier: SeatTypeIdentifierNoSeat) otherType = SeatType(identifier: SeatTypeIdentifierOther) allSeatTypes = [businessClassSeatType, specialClassSeatType, firstClassSeatType, secondClassSeatType, premiumSoftRoometteType, softRoometteType, hardRoometteType, softSeatType, hardSeatType, noSeatType, otherType] } } extension Train: Equatable { public static func ==(lhs: Train, rhs: Train) -> Bool { return lhs.train_no == rhs.train_no } } extension Train: ResponseObjectSerializable { init?(response: HTTPURLResponse, representation: Any) { guard let representation = representation as? JSON else { return nil } self.init() let queryLeftNewDTO = representation["queryLeftNewDTO"] train_no = queryLeftNewDTO["train_no"].string station_train_code = queryLeftNewDTO["station_train_code"].string start_station_telecode = queryLeftNewDTO["start_station_telecode"].string start_station_name = queryLeftNewDTO["start_station_name"].string end_station_telecode = queryLeftNewDTO["end_station_telecode"].string end_station_name = queryLeftNewDTO["end_station_name"].string from_station_telecode = queryLeftNewDTO["from_station_telecode"].string from_station_name = queryLeftNewDTO["from_station_name"].string to_station_telecode = queryLeftNewDTO["to_station_telecode"].string to_station_name = queryLeftNewDTO["to_station_name"].string start_time = queryLeftNewDTO["start_time"].string arrive_time = queryLeftNewDTO["arrive_time"].string day_difference = queryLeftNewDTO["day_difference"].string train_class_name = queryLeftNewDTO["train_class_name"].string lishi = queryLeftNewDTO["lishi"].string canWebBuy = queryLeftNewDTO["canWebBuy"].string lishiValue = queryLeftNewDTO["lishiValue"].string yp_info = queryLeftNewDTO["yp_info"].string control_train_day = queryLeftNewDTO["control_train_day"].string start_train_date = queryLeftNewDTO["start_train_date"].string seat_feature = queryLeftNewDTO["seat_feature"].string yp_ex = queryLeftNewDTO["yp_ex"].string train_seat_feature = queryLeftNewDTO["train_seat_feature"].string seat_types = queryLeftNewDTO["seat_types"].string location_code = queryLeftNewDTO["location_code"].string from_station_no = queryLeftNewDTO["from_station_no"].string to_station_no = queryLeftNewDTO["to_station_no"].string control_day = queryLeftNewDTO["control_day"].string sale_time = queryLeftNewDTO["sale_time"].string is_support_card = queryLeftNewDTO["is_support_card"].string gg_num = queryLeftNewDTO["gg_num"].string gr_num = queryLeftNewDTO["gr_num"].string qt_num = queryLeftNewDTO["qt_num"].string rw_num = queryLeftNewDTO["rw_num"].string rz_num = queryLeftNewDTO["rz_num"].string tz_num = queryLeftNewDTO["tz_num"].string wz_num = queryLeftNewDTO["wz_num"].string yb_num = queryLeftNewDTO["yb_num"].string yw_num = queryLeftNewDTO["yw_num"].string yz_num = queryLeftNewDTO["yz_num"].string ze_num = queryLeftNewDTO["ze_num"].string zy_num = queryLeftNewDTO["zy_num"].string swz_num = queryLeftNewDTO["swz_num"].string secretStr = representation["secretStr"].string buttonTextInfo = representation["buttonTextInfo"].string businessClassSeatType.leftSeats = swz_num specialClassSeatType.leftSeats = tz_num firstClassSeatType.leftSeats = zy_num secondClassSeatType.leftSeats = ze_num premiumSoftRoometteType.leftSeats = gr_num softRoometteType.leftSeats = rw_num hardRoometteType.leftSeats = yw_num softSeatType.leftSeats = rz_num hardSeatType.leftSeats = yz_num noSeatType.leftSeats = wz_num otherType.leftSeats = qt_num } }
mit
9c10dd202038f8f7664c52341aad5237
32.606618
221
0.640958
3.941785
false
false
false
false
Egibide-DAM/swift
02_ejemplos/06_tipos_personalizados/02_clases_estructuras/02_instanciacion.playground/Contents.swift
1
254
struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } let someResolution = Resolution() let someVideoMode = VideoMode()
apache-2.0
807ad13666d329c82a54d7c557f6011d
17.142857
33
0.665354
4.031746
false
false
false
false
apple/swift-nio-ssl
Sources/NIOSSL/ObjectIdentifier.swift
1
7054
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// @_implementationOnly import CNIOBoringSSL @_implementationOnly import CNIOBoringSSLShims /// A representation of an ASN.1 Object Identifier (OID) public struct NIOSSLObjectIdentifier { private enum Storage { final class Deallocator { var reference: OpaquePointer! init(takeOwnershipOf reference: OpaquePointer!) { self.reference = reference } deinit { CNIOBoringSSL_ASN1_OBJECT_free(self.reference) } } case owned(Deallocator) case borrowed(reference: OpaquePointer!, owner: AnyObject) init(takeOwnershipOf reference: OpaquePointer!) { self = .owned(.init(takeOwnershipOf: reference)) } init(borrowing reference: OpaquePointer!, owner: AnyObject) { self = .borrowed(reference: reference, owner: owner) } /// All operations accessing `reference` need to be implemented while guaranteeing that we still have a reference to the memory owner. /// Otherwise `reference` could already be freed. This would result in undefined behaviour as we access a dangling pointer. /// This method guarantees that `reference` is valid during execution of `body`. internal func withReference<Result>( _ body: (OpaquePointer?) throws -> Result ) rethrows -> Result { try withExtendedLifetime(self) { switch self { case .owned(let deallocator): return try body(deallocator.reference) case .borrowed(let reference, _): return try body(reference) } } } } private let storage: Storage /// Creates a Object Identifier (OID) from its textual dotted representation (e.g. `1.2.3`) /// /// - Parameter string: textual dotted representation of an OID public init?(_ string: String) { let result = string.withCString { string in // If no_name (the last parameter of CNIOBoringSSL_OBJ_txt2obj) is 0 then long names and // short names will be interpreted as well as numerical forms. // If no_name is 1 only the numerical form is acceptable. // source: https://www.openssl.org/docs/manmaster/man3/OBJ_txt2obj.html CNIOBoringSSL_OBJ_txt2obj(string, 1) } guard let reference = result else { return nil } self.storage = .init(takeOwnershipOf: reference) } /// Creates an Object Identifier (OID) from an OpenSSL reference. /// /// - Note: initialising an ``NIOSSLObjectIdentifier`` takes ownership of the reference and will free it after the reference count drops to zero /// - Parameter reference: reference to a valid OpenSSL OID aka OBJ internal init(takingOwnershipOf reference: OpaquePointer!) { self.storage = .init(takeOwnershipOf: reference) } /// Creates an Object Identifier (OID) from an OpenSSL reference. /// - Note: initialising an ``NIOSSLObjectIdentifier`` with *this* constructor does **not** take ownership of the memory. Instead ``NIOSSLObjectIdentifier`` keeps a reference to the owning object which it will retain for the lifetime of itself. /// - Parameters /// - reference: reference to a valid OpenSSL OID aka OBJ /// - owner: owner of the memory `reference` is pointing to which it will retain. internal init(borrowing reference: OpaquePointer!, owner: AnyObject) { self.storage = .init(borrowing: reference, owner: owner) } /// Creates a copy of an Object Identifier (OID) from an OpenSSL reference /// - Parameter reference: reference to a valid OpenSSL OID aka OBJ internal init(copyOf reference: OpaquePointer!) { self.init(takingOwnershipOf: CNIOBoringSSL_OBJ_dup(reference)) } } // NIOSSLObjectIdentifier is immutable and therefore Sendable extension NIOSSLObjectIdentifier: @unchecked Sendable {} extension NIOSSLObjectIdentifier: Equatable { public static func == (lhs: NIOSSLObjectIdentifier, rhs: NIOSSLObjectIdentifier) -> Bool { lhs.storage.withReference { lhsReference in rhs.storage.withReference { rhsReference in CNIOBoringSSL_OBJ_cmp(lhsReference, rhsReference) == 0 } } } } extension NIOSSLObjectIdentifier: Hashable { public func hash(into hasher: inout Hasher) { self.storage.withReference { reference in let length = CNIOBoringSSL_OBJ_length(reference) let data = CNIOBoringSSL_OBJ_get0_data(reference) let buffer = UnsafeRawBufferPointer(start: data, count: length) hasher.combine(bytes: buffer) } } } extension NIOSSLObjectIdentifier: LosslessStringConvertible { public var description: String { self.storage.withReference { reference in var failed = false let oid = String(customUnsafeUninitializedCapacity: 80) { buffer in // OBJ_obj2txt() is awkward and messy to use: it doesn't follow the convention of other OpenSSL functions where the buffer can be set to NULL to determine the amount of data that should be written. Instead buf must point to a valid buffer and buf_len should be set to a positive value. A buffer length of 80 should be more than enough to handle any OID encountered in practice. // source: https://linux.die.net/man/3/obj_obj2txt let result = buffer.withMemoryRebound(to: CChar.self) { buffer in // If no_name (the last argument of CNIOBoringSSL_OBJ_obj2txt) is 0 then // if the object has a long or short name then that will be used, // otherwise the numerical form will be used. // If no_name is 1 then the numerical form will always be used. // source: https://www.openssl.org/docs/manmaster/man3/OBJ_obj2txt.html CNIOBoringSSL_OBJ_obj2txt(buffer.baseAddress, Int32(buffer.count), reference, 1) } guard result >= 0 else { // result of -1 indicates an error failed = true return 0 } return Int(result) } guard !failed else { return "failed to convert OID to string" } return oid } } }
apache-2.0
0747acc66a445b34070232a1f7b9db85
44.217949
393
0.617806
5.01707
false
false
false
false
gmilos/swift
test/SILOptimizer/inout_deshadow_integration.swift
3
3062
// RUN: %target-swift-frontend %s -emit-sil | %FileCheck %s // This is an integration check for the inout-deshadow pass, verifying that it // deshadows the inout variables in certain cases. These test should not be // very specific (as they are running the parser, silgen and other sil // diagnostic passes), they should just check the inout shadow got removed. // CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_dead // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_trivial_type_dead(a: inout Int) { } // CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_returned // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_trivial_type_returned(a: inout Int) -> Int { return a } // CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_trivial_type_stored(a: inout Int) { a = 12 } // CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored_returned // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_trivial_type_stored_returned(a: inout Int) -> Int { a = 12 return a } // CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_dead // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_nontrivial_type_dead(a: inout String) { } // CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_returned // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_nontrivial_type_returned(a: inout String) -> String { return a } // CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_nontrivial_type_stored(a: inout String) { a = "x" } // CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored_returned // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_nontrivial_type_stored_returned(a: inout String) -> String { a = "x" return a } // Use an external function so inout deshadowing cannot see its body. @_silgen_name("takesNoEscapeClosure") func takesNoEscapeClosure(fn : () -> Int) struct StructWithMutatingMethod { var x = 42 // We should be able to deshadow this. The closure is capturing self, but it // is itself noescape. mutating func mutatingMethod() { takesNoEscapeClosure { x = 42; return x } } mutating func testStandardLibraryOperators() { if x != 4 || x != 0 { testStandardLibraryOperators() } } } // CHECK-LABEL: sil hidden @_TFV26inout_deshadow_integration24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(method) (@inout StructWithMutatingMethod) -> () { // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } // CHECK-LABEL: sil hidden @_TFV26inout_deshadow_integration24StructWithMutatingMethod28testStandardLibraryOperators{{.*}} : $@convention(method) (@inout StructWithMutatingMethod) -> () { // CHECK-NOT: alloc_box $<τ_0_0> { var τ_0_0 } <StructWithMutatingMethod> // CHECK-NOT: alloc_stack $StructWithMutatingMethod // CHECK: }
apache-2.0
eb7dd4cc8a4adb328322becd878f01b5
28.142857
187
0.699346
3.574766
false
false
false
false