repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
karwa/swift-corelibs-foundation | Foundation/NSAffineTransform.swift | 3 | 9862 | // 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
//
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
public struct NSAffineTransformStruct {
public var m11: CGFloat
public var m12: CGFloat
public var m21: CGFloat
public var m22: CGFloat
public var tX: CGFloat
public var tY: CGFloat
public init() {
self.init(m11: CGFloat(), m12: CGFloat(), m21: CGFloat(), m22: CGFloat(), tX: CGFloat(), tY: CGFloat())
}
public init(m11: CGFloat, m12: CGFloat, m21: CGFloat, m22: CGFloat, tX: CGFloat, tY: CGFloat) {
(self.m11, self.m12, self.m21, self.m22) = (m11, m12, m21, m22)
(self.tX, self.tY) = (tX, tY)
}
}
public class NSAffineTransform : NSObject, NSCopying, NSSecureCoding {
public func encodeWithCoder(_ aCoder: NSCoder) {
NSUnimplemented()
}
public func copyWithZone(_ zone: NSZone) -> AnyObject {
return NSAffineTransform(transform: self)
}
// Necessary because `NSObject.copy()` returns `self`.
public override func copy() -> AnyObject {
return copyWithZone(nil)
}
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
public static func supportsSecureCoding() -> Bool {
return true
}
// Initialization
public convenience init(transform: NSAffineTransform) {
self.init()
transformStruct = transform.transformStruct
}
public override init() {
transformStruct = NSAffineTransformStruct(
m11: CGFloat(1.0), m12: CGFloat(),
m21: CGFloat(), m22: CGFloat(1.0),
tX: CGFloat(), tY: CGFloat()
)
}
// Translating
public func translateXBy(_ deltaX: CGFloat, yBy deltaY: CGFloat) {
let translation = NSAffineTransformStruct.translation(tX: deltaX, tY: deltaY)
transformStruct = translation.concat(transformStruct)
}
// Rotating
public func rotateByDegrees(_ angle: CGFloat) {
let rotation = NSAffineTransformStruct.rotation(degrees: angle)
transformStruct = rotation.concat(transformStruct)
}
public func rotateByRadians(_ angle: CGFloat) {
let rotation = NSAffineTransformStruct.rotation(radians: angle)
transformStruct = rotation.concat(transformStruct)
}
// Scaling
public func scaleBy(_ scale: CGFloat) {
scaleXBy(scale, yBy: scale)
}
public func scaleXBy(_ scaleX: CGFloat, yBy scaleY: CGFloat) {
let scale = NSAffineTransformStruct.scale(sX: scaleX, sY: scaleY)
transformStruct = scale.concat(transformStruct)
}
// Inverting
public func invert() {
if let inverse = transformStruct.inverse {
transformStruct = inverse
}
else {
preconditionFailure("NSAffineTransform: Transform has no inverse")
}
}
// Transforming with transform
public func appendTransform(_ transform: NSAffineTransform) {
transformStruct = transformStruct.concat(transform.transformStruct)
}
public func prependTransform(_ transform: NSAffineTransform) {
transformStruct = transform.transformStruct.concat(transformStruct)
}
// Transforming points and sizes
public func transformPoint(_ aPoint: NSPoint) -> NSPoint {
return transformStruct.applied(toPoint: aPoint)
}
public func transformSize(_ aSize: NSSize) -> NSSize {
return transformStruct.applied(toSize: aSize)
}
// Transform Struct
public var transformStruct: NSAffineTransformStruct
}
/**
NSAffineTransformStruct represents an affine transformation matrix of the following form:
[ m11 m12 0 ]
[ m21 m22 0 ]
[ tX tY 1 ]
*/
private extension NSAffineTransformStruct {
/**
Creates an affine transformation matrix from translation values.
The matrix takes the following form:
[ 1 0 0 ]
[ 0 1 0 ]
[ tX tY 1 ]
*/
static func translation(tX: CGFloat, tY: CGFloat) -> NSAffineTransformStruct {
return NSAffineTransformStruct(
m11: CGFloat(1.0), m12: CGFloat(),
m21: CGFloat(), m22: CGFloat(1.0),
tX: tX, tY: tY
)
}
/**
Creates an affine transformation matrix from scaling values.
The matrix takes the following form:
[ sX 0 0 ]
[ 0 sY 0 ]
[ 0 0 1 ]
*/
static func scale(sX: CGFloat, sY: CGFloat) -> NSAffineTransformStruct {
return NSAffineTransformStruct(
m11: sX, m12: CGFloat(),
m21: CGFloat(), m22: sY,
tX: CGFloat(), tY: CGFloat()
)
}
/**
Creates an affine transformation matrix from rotation value (angle in radians).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
static func rotation(radians angle: CGFloat) -> NSAffineTransformStruct {
let α = Double(angle)
let sine = CGFloat(sin(α))
let cosine = CGFloat(cos(α))
return NSAffineTransformStruct(
m11: cosine, m12: sine,
m21: -sine, m22: cosine,
tX: CGFloat(), tY: CGFloat()
)
}
/**
Creates an affine transformation matrix from a rotation value (angle in degrees).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
static func rotation(degrees angle: CGFloat) -> NSAffineTransformStruct {
let α = Double(angle) * M_PI / 180.0
return rotation(radians: CGFloat(α))
}
/**
Creates an affine transformation matrix by combining the receiver with `transformStruct`.
That is, it computes `T * M` and returns the result, where `T` is the receiver's and `M` is
the `transformStruct`'s affine transformation matrix.
The resulting matrix takes the following form:
[ m11_T m12_T 0 ] [ m11_M m12_M 0 ]
T * M = [ m21_T m22_T 0 ] [ m21_M m22_M 0 ]
[ tX_T tY_T 1 ] [ tX_M tY_M 1 ]
[ (m11_T*m11_M + m12_T*m21_M) (m11_T*m12_M + m12_T*m22_M) 0 ]
= [ (m21_T*m11_M + m22_T*m21_M) (m21_T*m12_M + m22_T*m22_M) 0 ]
[ (tX_T*m11_M + tY_T*m21_M + tX_M) (tX_T*m12_M + tY_T*m22_M + tY_M) 1 ]
*/
func concat(_ transformStruct: NSAffineTransformStruct) -> NSAffineTransformStruct {
let (t, m) = (self, transformStruct)
return NSAffineTransformStruct(
m11: (t.m11 * m.m11) + (t.m12 * m.m21), m12: (t.m11 * m.m12) + (t.m12 * m.m22),
m21: (t.m21 * m.m11) + (t.m22 * m.m21), m22: (t.m21 * m.m12) + (t.m22 * m.m22),
tX: (t.tX * m.m11) + (t.tY * m.m21) + m.tX,
tY: (t.tX * m.m12) + (t.tY * m.m22) + m.tY
)
}
/**
Applies the affine transformation to `toPoint` and returns the result.
The resulting point takes the following form:
[ x' y' 1 ] = [ x y 1 ] * T
[ m11 m12 0 ]
= [ x y 1 ] * [ m21 m22 0 ]
[ tX tY 1 ]
= [ (x*m11 + y*m21 + tX) (x*m12 + y*m22 + tY) 1 ]
*/
func applied(toPoint p: NSPoint) -> NSPoint {
let x = (p.x * m11) + (p.y * m21) + tX
let y = (p.x * m12) + (p.y * m22) + tY
return NSPoint(x: x, y: y)
}
/**
Applies the affine transformation to `toSize` and returns the result.
The resulting size takes the following form:
[ w' h' 0 ] = [ w h 0] * T
[ m11 m12 0 ]
= [ w h 0 ] [ m21 m22 0 ]
[ tX tY 1 ]
= [ (w*m11 + h*m21) (w*m12 + h*m22) 0 ]
Note: Translation has no effect on the size.
*/
func applied(toSize s: NSSize) -> NSSize {
let w = (m11 * s.width) + (m12 * s.height)
let h = (m21 * s.width) + (m22 * s.height)
return NSSize(width: w, height: h)
}
/**
Returns the inverse affine transformation matrix or `nil` if it has no inverse.
The receiver's affine transformation matrix can be divided into matrix sub-block as
[ M 0 ]
[ t 1 ]
where `M` represents the linear map and `t` the translation vector.
The inversion can then be calculated as
[ inv(M) 0 ]
[ -t*inv(M) 1 ]
if `M` is invertible.
*/
var inverse: NSAffineTransformStruct? {
// Calculate determinant of M: det(M)
let det = (m11 * m22) - (m12 * m21)
if det == CGFloat() {
return nil
}
// Calculate the inverse of M: inv(M)
let (invM11, invM12) = ( m22 / det, -m12 / det)
let (invM21, invM22) = (-m21 / det, m11 / det)
// Calculate -t*inv(M)
let invTX = (-tX * invM11) + (-tY * invM21)
let invTY = (-tX * invM12) + (-tY * invM22)
return NSAffineTransformStruct(
m11: invM11, m12: invM12,
m21: invM21, m22: invM22,
tX: invTX, tY: invTY
)
}
}
| apache-2.0 | 78ee6975947aa50f035e287302cfa262 | 30.977273 | 111 | 0.547365 | 3.900594 | false | false | false | false |
coach-plus/ios | Pods/Eureka/Source/Rows/TriplePickerInputRow.swift | 1 | 6923 | //
// TriplePickerInputRow.swift
// Eureka
//
// Created by Mathias Claassen on 5/10/18.
// Copyright © 2018 Xmartlabs. All rights reserved.
//
import Foundation
import UIKit
open class TriplePickerInputCell<A, B, C> : _PickerInputCell<Tuple3<A, B, C>> where A: Equatable, B: Equatable, C: Equatable {
private var pickerRow: _TriplePickerInputRow<A, B, C>! { return row as? _TriplePickerInputRow<A, B, C> }
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func update() {
super.update()
if let selectedValue = pickerRow.value, let indexA = pickerRow.firstOptions().index(of: selectedValue.a),
let indexB = pickerRow.secondOptions(selectedValue.a).index(of: selectedValue.b),
let indexC = pickerRow.thirdOptions(selectedValue.a, selectedValue.b).index(of: selectedValue.c){
picker.selectRow(indexA, inComponent: 0, animated: true)
picker.selectRow(indexB, inComponent: 1, animated: true)
picker.selectRow(indexC, inComponent: 2, animated: true)
}
}
open override func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
open override func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return pickerRow.firstOptions().count
} else if component == 1 {
return pickerRow.secondOptions(pickerRow.selectedFirst()).count
} else {
return pickerRow.thirdOptions(pickerRow.selectedFirst(), pickerRow.selectedSecond()).count
}
}
open override func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return pickerRow.displayValueForFirstRow(pickerRow.firstOptions()[row])
} else if component == 1 {
return pickerRow.displayValueForSecondRow(pickerRow.secondOptions(pickerRow.selectedFirst())[row])
} else {
return pickerRow.displayValueForThirdRow(pickerRow.thirdOptions(pickerRow.selectedFirst(), pickerRow.selectedSecond())[row])
}
}
open override func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
let a = pickerRow.firstOptions()[row]
if let value = pickerRow.value {
guard value.a != a else {
return
}
let b: B = pickerRow.secondOptions(a).contains(value.b) ? value.b : pickerRow.secondOptions(a)[0]
let c: C = pickerRow.thirdOptions(a, b).contains(value.c) ? value.c : pickerRow.thirdOptions(a, b)[0]
pickerRow.value = Tuple3(a: a, b: b, c: c)
pickerView.reloadComponent(1)
pickerView.reloadComponent(2)
if b != value.b {
pickerView.selectRow(0, inComponent: 1, animated: true)
}
if c != value.c {
pickerView.selectRow(0, inComponent: 2, animated: true)
}
} else {
let b = pickerRow.secondOptions(a)[0]
pickerRow.value = Tuple3(a: a, b: b, c: pickerRow.thirdOptions(a, b)[0])
pickerView.reloadComponent(1)
pickerView.reloadComponent(2)
pickerView.selectRow(0, inComponent: 1, animated: true)
pickerView.selectRow(0, inComponent: 2, animated: true)
}
} else if component == 1 {
let a = pickerRow.selectedFirst()
let b = pickerRow.secondOptions(a)[row]
if let value = pickerRow.value {
guard value.b != b else {
return
}
if pickerRow.thirdOptions(a, b).contains(value.c) {
pickerRow.value = Tuple3(a: a, b: b, c: value.c)
pickerView.reloadComponent(2)
update()
return
} else {
pickerRow.value = Tuple3(a: a, b: b, c: pickerRow.thirdOptions(a, b)[0])
}
} else {
pickerRow.value = Tuple3(a: a, b: b, c: pickerRow.thirdOptions(a, b)[0])
}
pickerView.reloadComponent(2)
pickerView.selectRow(0, inComponent: 2, animated: true)
} else {
let a = pickerRow.selectedFirst()
let b = pickerRow.selectedSecond()
pickerRow.value = Tuple3(a: a, b: b, c: pickerRow.thirdOptions(a, b)[row])
}
update()
}
}
open class _TriplePickerInputRow<A: Equatable, B: Equatable, C: Equatable> : Row<TriplePickerInputCell<A, B, C>>, NoValueDisplayTextConformance {
open var noValueDisplayText: String? = nil
/// Options for first component. Will be called often so should be O(1)
public var firstOptions: (() -> [A]) = {[]}
/// Options for second component given the selected value from the first component. Will be called often so should be O(1)
public var secondOptions: ((A) -> [B]) = {_ in []}
/// Options for third component given the selected value from the first and second components. Will be called often so should be O(1)
public var thirdOptions: ((A, B) -> [C]) = {_, _ in []}
/// Modify the displayed values for the first picker row.
public var displayValueForFirstRow: ((A) -> (String)) = { a in return String(describing: a) }
/// Modify the displayed values for the second picker row.
public var displayValueForSecondRow: ((B) -> (String)) = { b in return String(describing: b) }
/// Modify the displayed values for the third picker row.
public var displayValueForThirdRow: ((C) -> (String)) = { c in return String(describing: c) }
required public init(tag: String?) {
super.init(tag: tag)
}
func selectedFirst() -> A {
return value?.a ?? firstOptions()[0]
}
func selectedSecond() -> B {
return value?.b ?? secondOptions(selectedFirst())[0]
}
}
/// A generic row where the user can pick an option from a picker view displayed in the keyboard area
public final class TriplePickerInputRow<A, B, C>: _TriplePickerInputRow<A, B, C>, RowType where A: Equatable, B: Equatable, C: Equatable {
required public init(tag: String?) {
super.init(tag: tag)
self.displayValueFor = { [weak self] tuple in
guard let tuple = tuple else {
return self?.noValueDisplayText
}
return String(describing: tuple.a) + ", " + String(describing: tuple.b) + ", " + String(describing: tuple.c)
}
}
}
| mit | 38ec47c37e87d57179595a2b1bc3b314 | 42.810127 | 145 | 0.602572 | 4.451447 | false | false | false | false |
huangxinping/XPKit-swift | Source/Extensions/UIKit/UITextView+XPKit.swift | 1 | 4487 | //
// UITextView+XPKit.swift
// XPKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2016 Fabrizio Brancati. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
/// This extesion adds some useful functions to UITextView
public extension UITextView {
// MARK: - Init functions -
/**
Create an UITextView and set some parameters
- parameter frame: TextView's frame
- parameter text: TextView's text
- parameter font: TextView's text font
- parameter size: TextView's text size
- parameter color: TextView's text color
- parameter alignment: TextView's text alignment
- parameter dataDetectorTypes: TextView's data detector types
- parameter editable: Set if TextView is editable
- parameter selectable: Set if TextView is selectable
- parameter returnType: TextField's return key type
- parameter keyboardType: TextField's keyboard type
- parameter secure: Set if the TextField is secure or not
- parameter autoCapitalization: TextField's text capitalization
- parameter keyboardAppearance: TextField's keyboard appearence
- parameter enablesReturnKeyAutomatically: Set if the TextField has to automatically enables the return key
- parameter autoCorrectionType: TextField's auto correction type
- parameter delegate: TextField's delegate. Set nil if it has no delegate
- returns: Returns the created UITextView
*/
public convenience init(frame: CGRect, text: String, font: FontName, size: CGFloat, color: UIColor, alignment: NSTextAlignment, dataDetectorTypes: UIDataDetectorTypes, editable: Bool, selectable: Bool, returnType: UIReturnKeyType, keyboardType: UIKeyboardType, secure: Bool, autoCapitalization: UITextAutocapitalizationType, keyboardAppearance: UIKeyboardAppearance, enablesReturnKeyAutomatically: Bool, autoCorrectionType: UITextAutocorrectionType, delegate: UITextViewDelegate?) {
self.init(frame: frame)
self.text = text
self.autocorrectionType = autoCorrectionType
self.textAlignment = alignment
self.keyboardType = keyboardType
self.autocapitalizationType = autoCapitalization
self.textColor = color
self.returnKeyType = returnType
self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically
self.secureTextEntry = secure
self.keyboardAppearance = keyboardAppearance
self.font = UIFont(fontName: font, size: size)
self.delegate = delegate
self.dataDetectorTypes = dataDetectorTypes
self.editable = editable
self.selectable = selectable
}
// MARK: - Instance functions -
/**
Paste the pasteboard text to UITextField
*/
public func pasteFromPasteboard() {
self.text = UIPasteboard.stringFromPasteboard()
}
/**
Copy UITextField text to pasteboard
*/
public func copyToPasteboard() {
guard let textToCopy = self.text else {
return
}
UIPasteboard.copyToPasteboard(textToCopy)
}
}
| mit | 0f3471d9b867be840849bdfadab71bc1 | 46.231579 | 486 | 0.671718 | 5.566998 | false | false | false | false |
insidegui/AppleEvents | Dependencies/swift-protobuf/Tests/SwiftProtobufTests/Test_Unknown_proto2.swift | 3 | 9939 | // Tests/SwiftProtobufTests/Test_Unknown_proto2.swift - Exercise unknown field handling for proto2 messages
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Proto2 messages preserve unknown fields when decoding and recoding binary
/// messages, but drop unknown fields when decoding and recoding JSON format.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
import SwiftProtobuf
/*
* Verify that unknown fields are correctly preserved by
* proto2 messages.
*/
class Test_Unknown_proto2: XCTestCase, PBTestHelpers {
typealias MessageTestType = ProtobufUnittest_TestEmptyMessage
/// Verify that json decode ignores the provided fields but otherwise succeeds
func assertJSONIgnores(_ json: String, file: XCTestFileArgType = #file, line: UInt = #line) {
do {
var options = JSONDecodingOptions()
options.ignoreUnknownFields = true
let empty = try ProtobufUnittest_TestEmptyMessage(jsonString: json, options: options)
do {
let json = try empty.jsonString()
XCTAssertEqual("{}", json, file: file, line: line)
} catch let e {
XCTFail("Recoding empty threw error \(e)", file: file, line: line)
}
} catch {
XCTFail("Error decoding into an empty message \(json)", file: file, line: line)
}
}
// Binary PB coding preserves unknown fields for proto2
func testBinaryPB() {
func assertRecodes(_ protobufBytes: [UInt8], file: XCTestFileArgType = #file, line: UInt = #line) {
do {
let empty = try ProtobufUnittest_TestEmptyMessage(serializedData: Data(bytes: protobufBytes))
do {
let pb = try empty.serializedData()
XCTAssertEqual(Data(bytes: protobufBytes), pb, file: file, line: line)
} catch {
XCTFail("Recoding empty failed", file: file, line: line)
}
} catch {
XCTFail("Decoding threw error \(protobufBytes)", file: file, line: line)
}
}
func assertFails(_ protobufBytes: [UInt8], file: XCTestFileArgType = #file, line: UInt = #line) {
XCTAssertThrowsError(try ProtobufUnittest_TestEmptyMessage(serializedData: Data(bytes: protobufBytes)), file: file, line: line)
}
// Well-formed input should decode/recode as-is; malformed input should fail to decode
assertFails([0]) // Invalid field number
assertFails([0, 0])
assertFails([1]) // Invalid field number
assertFails([2]) // Invalid field number
assertFails([3]) // Invalid field number
assertFails([4]) // Invalid field number
assertFails([5]) // Invalid field number
assertFails([6]) // Invalid field number
assertFails([7]) // Invalid field number
assertFails([8]) // Varint field #1 but no varint body
assertRecodes([8, 0])
assertFails([8, 128]) // Truncated varint
assertRecodes([9, 0, 0, 0, 0, 0, 0, 0, 0])
assertFails([9, 0, 0, 0, 0, 0, 0, 0]) // Truncated 64-bit field
assertFails([9, 0, 0, 0, 0, 0, 0])
assertFails([9, 0, 0, 0, 0, 0])
assertFails([9, 0, 0, 0, 0])
assertFails([9, 0, 0, 0])
assertFails([9, 0, 0])
assertFails([9, 0])
assertFails([9])
assertFails([10]) // Length-delimited field but no length
assertRecodes([10, 0]) // Valid 0-length field
assertFails([10, 1]) // Length 1 but truncated
assertRecodes([10, 1, 2]) // Length 1 with 1 byte
assertFails([10, 2, 1]) // Length 2 truncated
assertFails([11]) // Start group #1 but no end group
assertRecodes([11, 12]) // Start/end group #1
assertFails([12]) // Bare end group
assertRecodes([13, 0, 0, 0, 0])
assertFails([13, 0, 0, 0])
assertFails([13, 0, 0])
assertFails([13, 0])
assertFails([13])
assertFails([14])
assertFails([15])
assertRecodes([248, 255, 255, 255, 15, 0]) // Maximum field number
assertFails([128, 128, 128, 128, 16, 0]) // Out-of-range field number
assertFails([248, 255, 255, 255, 127, 0]) // Out-of-range field number
}
// JSON coding drops unknown fields for both proto2 and proto3
func testJSON() {
// Unknown fields should be ignored if they are well-formed JSON
assertJSONIgnores("{\"unknown\":7}")
assertJSONIgnores("{\"unknown\":null}")
assertJSONIgnores("{\"unknown\":false}")
assertJSONIgnores("{\"unknown\":true}")
assertJSONIgnores("{\"unknown\": 7.0}")
assertJSONIgnores("{\"unknown\": -3.04}")
assertJSONIgnores("{\"unknown\": -7.0e-55}")
assertJSONIgnores("{\"unknown\": 7.308e+8}")
assertJSONIgnores("{\"unknown\": \"hi!\"}")
assertJSONIgnores("{\"unknown\": []}")
assertJSONIgnores("{\"unknown\": [3, 4, 5]}")
assertJSONIgnores("{\"unknown\": [[3], [4], [5, [6, [7], 8, null, \"no\"]]]}")
assertJSONIgnores("{\"unknown\": [3, {}, \"5\"]}")
assertJSONIgnores("{\"unknown\": {}}")
assertJSONIgnores("{\"unknown\": {\"foo\": 1}}")
assertJSONIgnores("{\"unknown\": 7, \"also_unknown\": 8}")
assertJSONIgnores("{\"unknown\": 7, \"unknown\": 8}") // ???
// Badly formed JSON should fail to decode, even in unknown sections
var options = JSONDecodingOptions()
options.ignoreUnknownFields = true
assertJSONDecodeFails("{\"unknown\": 1e999}", options: options)
assertJSONDecodeFails("{\"unknown\": \"hi!\"", options: options)
assertJSONDecodeFails("{\"unknown\": \"hi!}", options: options)
assertJSONDecodeFails("{\"unknown\": qqq }", options: options)
assertJSONDecodeFails("{\"unknown\": { }", options: options)
assertJSONDecodeFails("{\"unknown\": [ }", options: options)
assertJSONDecodeFails("{\"unknown\": { ]}", options: options)
assertJSONDecodeFails("{\"unknown\": ]}", options: options)
assertJSONDecodeFails("{\"unknown\": null true}", options: options)
assertJSONDecodeFails("{\"unknown\": nulll }", options: options)
assertJSONDecodeFails("{\"unknown\": nul }", options: options)
assertJSONDecodeFails("{\"unknown\": Null }", options: options)
assertJSONDecodeFails("{\"unknown\": NULL }", options: options)
assertJSONDecodeFails("{\"unknown\": True }", options: options)
assertJSONDecodeFails("{\"unknown\": False }", options: options)
assertJSONDecodeFails("{\"unknown\": nan }", options: options)
assertJSONDecodeFails("{\"unknown\": NaN }", options: options)
assertJSONDecodeFails("{\"unknown\": Infinity }", options: options)
assertJSONDecodeFails("{\"unknown\": infinity }", options: options)
assertJSONDecodeFails("{\"unknown\": Inf }", options: options)
assertJSONDecodeFails("{\"unknown\": inf }", options: options)
assertJSONDecodeFails("{\"unknown\": 1}}", options: options)
assertJSONDecodeFails("{\"unknown\": {1, 2}}", options: options)
assertJSONDecodeFails("{\"unknown\": 1.2.3.4.5}", options: options)
assertJSONDecodeFails("{\"unknown\": -.04}", options: options)
assertJSONDecodeFails("{\"unknown\": -19.}", options: options)
assertJSONDecodeFails("{\"unknown\": -9.3e+}", options: options)
assertJSONDecodeFails("{\"unknown\": 1 2 3}", options: options)
assertJSONDecodeFails("{\"unknown\": { true false }}", options: options)
assertJSONDecodeFails("{\"unknown\"}", options: options)
assertJSONDecodeFails("{\"unknown\": }", options: options)
assertJSONDecodeFails("{\"unknown\", \"a\": 1}", options: options)
}
func assertUnknownFields(_ message: Message, _ bytes: [UInt8], line: UInt = #line) {
XCTAssertEqual(message.unknownFields.data, Data(bytes: bytes), line: line)
}
func test_MessageNoStorageClass() throws {
var msg1 = ProtobufUnittest_Msg2NoStorage()
assertUnknownFields(msg1, [])
try msg1.merge(serializedData: Data(bytes: [24, 1])) // Field 3, varint
assertUnknownFields(msg1, [24, 1])
var msg2 = msg1
assertUnknownFields(msg2, [24, 1])
assertUnknownFields(msg1, [24, 1])
try msg2.merge(serializedData: Data([34, 1, 52])) // Field 4, length delimted
assertUnknownFields(msg2, [24, 1, 34, 1, 52])
assertUnknownFields(msg1, [24, 1])
try msg1.merge(serializedData: Data([61, 7, 0, 0, 0])) // Field 7, 32-bit value
assertUnknownFields(msg2, [24, 1, 34, 1, 52])
assertUnknownFields(msg1, [24, 1, 61, 7, 0, 0, 0])
}
func test_MessageUsingStorageClass() throws {
var msg1 = ProtobufUnittest_Msg2UsesStorage()
assertUnknownFields(msg1, [])
try msg1.merge(serializedData: Data(bytes: [24, 1])) // Field 3, varint
assertUnknownFields(msg1, [24, 1])
var msg2 = msg1
assertUnknownFields(msg2, [24, 1])
assertUnknownFields(msg1, [24, 1])
try msg2.merge(serializedData: Data([34, 1, 52])) // Field 4, length delimted
assertUnknownFields(msg2, [24, 1, 34, 1, 52])
assertUnknownFields(msg1, [24, 1])
try msg1.merge(serializedData: Data([61, 7, 0, 0, 0])) // Field 7, 32-bit value
assertUnknownFields(msg2, [24, 1, 34, 1, 52])
assertUnknownFields(msg1, [24, 1, 61, 7, 0, 0, 0])
}
}
| bsd-2-clause | 27800ee9e79e01c5bc89cdeb2e7de00b | 47.014493 | 139 | 0.595231 | 4.688208 | false | true | false | false |
remind101/AutoGraph | AutoGraph/WebSocketClient.swift | 1 | 14793 | import Foundation
import Starscream
import Alamofire
import JSONValueRX
public typealias WebSocketConnected = (Result<Void, Error>) -> Void
public protocol WebSocketClientDelegate: class {
func didReceive(event: WebSocketEvent)
func didReceive(error: Error)
func didChangeConnection(state: WebSocketClient.State)
}
private let kAttemptReconnectCount = 3
/// The unique key for a subscription request. A combination of OperationName + variables.
public typealias SubscriptionID = String
public struct Subscriber: Hashable {
let uuid = UUID() // Disambiguates between multiple different subscribers of same subscription.
let subscriptionID: SubscriptionID
let serializableRequest: SubscriptionRequestSerializable // Needed on reconnect.
init(subscriptionID: String, serializableRequest: SubscriptionRequestSerializable) {
self.subscriptionID = subscriptionID
self.serializableRequest = serializableRequest
}
public static func == (lhs: Subscriber, rhs: Subscriber) -> Bool {
return lhs.uuid == rhs.uuid
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.uuid)
}
}
open class WebSocketClient {
public enum State: Equatable {
case connected(receivedAck: Bool)
case reconnecting
case disconnected
var isConnected: Bool {
guard case .connected = self else { return false }
return true
}
}
// Reference type because it's used as a mutable dictionary within a dictionary.
final class SubscriptionSet: Sequence {
var set: [Subscriber : SubscriptionResponseHandler]
init(set: [Subscriber : SubscriptionResponseHandler]) {
self.set = set
}
func makeIterator() -> Dictionary<Subscriber, SubscriptionResponseHandler>.Iterator {
return set.makeIterator()
}
}
public var webSocket: WebSocket
public weak var delegate: WebSocketClientDelegate?
public private(set) var state: State = .disconnected {
didSet {
self.delegate?.didChangeConnection(state: state)
}
}
public let subscriptionSerializer = SubscriptionResponseSerializer()
internal var queuedSubscriptions = [Subscriber : WebSocketConnected]()
internal var subscriptions = [SubscriptionID: SubscriptionSet]()
internal var attemptReconnectCount = kAttemptReconnectCount
internal var connectionAckWorkItem: DispatchWorkItem?
public init(url: URL) throws {
let request = try WebSocketClient.connectionRequest(url: url)
self.webSocket = WebSocket(request: request)
self.webSocket.delegate = self
}
deinit {
self.webSocket.forceDisconnect()
self.webSocket.delegate = nil
}
public func authenticate(token: String?, headers: [String: String]?) {
var headers = headers ?? [:]
if let token = token {
headers["Authorization"] = "Bearer \(token)"
}
headers.forEach { (key, value) in
self.webSocket.request.setValue(value, forHTTPHeaderField: key)
}
}
public func setValue(_ value: String?, forHTTPHeaderField field: String) {
self.webSocket.request.setValue(value, forHTTPHeaderField: field)
}
private var fullDisconnect = false
public func disconnect() {
self.fullDisconnect = true
self.disconnectAndPossiblyReconnect(force: true)
}
public func disconnectAndPossiblyReconnect(force: Bool = false) {
guard self.state != .disconnected, !force else {
return
}
// TODO: Possible return something to the user if this fails?
if let payload = try? GraphQLWSProtocol.connectionTerminate.serializedSubscriptionPayload() {
self.write(payload)
}
self.webSocket.disconnect()
}
/// Subscribe to a Subscription, will automatically connect a websocket if it is not connected or disconnected.
public func subscribe<R: Request>(request: SubscriptionRequest<R>, responseHandler: SubscriptionResponseHandler) -> Subscriber {
// If we already have a subscription for that key then just add the subscriber to the set for that key with a callback.
// Otherwise if connected send subscription and add to subscriber set.
// Otherwise queue it and it will be added after connecting.
let subscriber = Subscriber(subscriptionID: request.subscriptionID, serializableRequest: request)
let connectionCompletionBlock: WebSocketConnected = self.connectionCompletionBlock(subscriber: subscriber, responseHandler: responseHandler)
guard !self.state.isConnected else {
connectionCompletionBlock(.success(()))
return subscriber
}
self.queuedSubscriptions[subscriber] = connectionCompletionBlock
self.webSocket.connect()
return subscriber
}
func connectionCompletionBlock(subscriber: Subscriber, responseHandler: SubscriptionResponseHandler) -> WebSocketConnected {
return { [weak self] (result) in
guard let self = self else { return }
// If we already have a subscription for that key then just add the subscriber to the set for that key with a callback.
// Otherwise if connected send subscription and add to subscriber set.
if let subscriptionSet = self.subscriptions[subscriber.subscriptionID] {
subscriptionSet.set[subscriber] = responseHandler
}
else {
self.subscriptions[subscriber.subscriptionID] = SubscriptionSet(set: [subscriber : responseHandler])
do {
try self.sendSubscription(request: subscriber.serializableRequest)
}
catch let e {
responseHandler.didReceive(error: e)
}
}
}
}
public func unsubscribeAll<R: Request>(request: SubscriptionRequest<R>) throws {
let id = request.subscriptionID
self.queuedSubscriptions = self.queuedSubscriptions.filter { (key, _) -> Bool in
return key.subscriptionID == id
}
if let subscriber = self.subscriptions.removeValue(forKey: id)?.set.first?.key {
try self.unsubscribe(subscriber: subscriber)
}
}
public func unsubscribe(subscriber: Subscriber) throws {
// Write the unsubscribe, and only remove our subscriptions for that subscriber.
self.queuedSubscriptions.removeValue(forKey: subscriber)
self.subscriptions.removeValue(forKey: subscriber.subscriptionID)
let stopPayload = try GraphQLWSProtocol.stop.serializedSubscriptionPayload(id: subscriber.subscriptionID)
self.write(stopPayload)
}
func write(_ message: String) {
self.webSocket.write(string: message, completion: nil)
}
func sendSubscription(request: SubscriptionRequestSerializable) throws {
let subscriptionPayload = try request.serializedSubscriptionPayload()
guard case .connected(receivedAck: true) = self.state else {
throw WebSocketError.webSocketNotConnected(subscriptionPayload: subscriptionPayload)
}
self.write(subscriptionPayload)
self.resendSubscriptionIfNoConnectionAck()
}
/// Attempts to reconnect and re-subscribe with multiplied backoff up to 30 seconds. Returns the delay.
func reconnect() -> DispatchTimeInterval? {
guard self.state != .reconnecting, !self.fullDisconnect else { return nil }
if self.attemptReconnectCount > 0 {
self.attemptReconnectCount -= 1
}
self.state = .reconnecting
let delayInSeconds = DispatchTimeInterval.seconds(min(abs(kAttemptReconnectCount - self.attemptReconnectCount) * 10, 30))
DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { [weak self] in
guard let self = self else { return }
self.performReconnect()
}
return delayInSeconds
}
func didConnect() throws {
self.state = .connected(receivedAck: false)
self.attemptReconnectCount = kAttemptReconnectCount
let connectedPayload = try GraphQLWSProtocol.connectionInit.serializedSubscriptionPayload()
self.write(connectedPayload)
}
/// Takes all subscriptions and puts them back on the queue, used for reconnection.
func requeueAllSubscribers() {
for (_, subscriptionSet) in self.subscriptions {
for (subscriber, subscriptionResponseHandler) in subscriptionSet {
self.queuedSubscriptions[subscriber] = connectionCompletionBlock(subscriber: subscriber, responseHandler: subscriptionResponseHandler)
}
}
self.subscriptions.removeAll(keepingCapacity: true)
}
private func reset() {
self.disconnect()
self.subscriptions.removeAll()
self.queuedSubscriptions.removeAll()
self.attemptReconnectCount = kAttemptReconnectCount
self.state = .disconnected
}
private func resendSubscriptionIfNoConnectionAck() {
self.connectionAckWorkItem?.cancel()
self.connectionAckWorkItem = nil
guard case let .connected(receivedAck) = self.state, receivedAck == false else {
return
}
let connectionAckWorkItem = DispatchWorkItem { [weak self] in
self?.performReconnect()
}
self.connectionAckWorkItem = connectionAckWorkItem
DispatchQueue.main.asyncAfter(deadline: .now() + 60, execute: connectionAckWorkItem)
}
private func subscribeQueuedSubscriptions() {
let queuedSubscriptions = self.queuedSubscriptions
self.queuedSubscriptions.removeAll()
queuedSubscriptions.forEach { (_, connected: WebSocketConnected) in
connected(.success(()))
}
}
private func performReconnect() {
// Requeue all so they don't get error callbacks on disconnect and they get re-subscribed on connect.
self.requeueAllSubscribers()
self.disconnectAndPossiblyReconnect()
self.webSocket.connect()
}
}
// MARK: - Class Method
extension WebSocketClient {
class func connectionRequest(url: URL) throws -> URLRequest {
var defaultHeders = [String: String]()
defaultHeders["Sec-WebSocket-Protocol"] = "graphql-ws"
defaultHeders["Origin"] = url.absoluteString
return try URLRequest(url: url, method: .get, headers: HTTPHeaders(defaultHeders))
}
}
// MARK: - WebSocketDelegate
extension WebSocketClient: WebSocketDelegate {
// This is called on the Starscream callback queue, which defaults to Main.
public func didReceive(event: WebSocketEvent, client: WebSocket) {
self.delegate?.didReceive(event: event)
do {
switch event {
case .disconnected:
self.state = .disconnected
if !self.fullDisconnect {
_ = self.reconnect()
}
self.fullDisconnect = false
case .cancelled:
_ = self.reconnect()
case .binary(let data):
let subscriptionResponse = try self.subscriptionSerializer.serialize(data: data)
self.didReceive(subscriptionResponse: subscriptionResponse)
case let .text(text):
try self.processWebSocketTextEvent(text: text)
case .connected:
try self.didConnect()
case let .reconnectSuggested(shouldReconnect):
if shouldReconnect {
_ = self.reconnect()
}
case .viabilityChanged: //let .viabilityChanged(isViable):
// TODO: if `isViable` is false then we need to pause sending and wait for x seconds for it to return.
// if it doesn't return to `isViable` true then reconnect.
break
case let .error(error):
if let error = error {
self.delegate?.didReceive(error: error)
}
_ = self.reconnect()
case .ping, .pong: // We just ignore these for now.
break
}
}
catch let error {
self.delegate?.didReceive(error: error)
}
}
func processWebSocketTextEvent(text: String) throws {
guard let data = text.data(using: .utf8) else {
throw ResponseSerializerError.failedToConvertTextToData(text)
}
let json = try JSONValue.decode(data)
guard case let .string(typeValue) = json["type"] else {
return
}
let graphQLWSProtocol = GraphQLWSProtocol(rawValue: typeValue)
switch graphQLWSProtocol {
case .connectionAck:
self.state = .connected(receivedAck: true)
self.connectionAckWorkItem?.cancel()
self.connectionAckWorkItem = nil
self.subscribeQueuedSubscriptions()
case .connectionKeepAlive:
self.subscribeQueuedSubscriptions()
case .data:
let subscriptionResponse = try self.subscriptionSerializer.serialize(text: text)
self.didReceive(subscriptionResponse: subscriptionResponse)
case .error:
throw ResponseSerializerError.webSocketError(text)
case .complete:
guard case let .string(id) = json["id"] else {
return
}
self.subscriptions.removeValue(forKey: id)
self.queuedSubscriptions = self.queuedSubscriptions.filter { $0.key.subscriptionID == id }
case .unknownResponse,
.connectionInit,
.connectionTerminate,
.connectionError,
.start,
.stop,
.none:
break
}
}
func didReceive(subscriptionResponse: SubscriptionResponse) {
let id = subscriptionResponse.id
guard let subscriptionSet = self.subscriptions[id] else {
print("WARNING: Recieved a subscription response for a subscription that AutoGraph is no longer subscribed to. SubscriptionID: \(subscriptionResponse.id)")
return
}
subscriptionSet.forEach { (_, value: SubscriptionResponseHandler) in
value.didReceive(subscriptionResponse: subscriptionResponse)
}
}
}
| mit | 9287c926f88063a783b225646d3ff2bb | 37.826772 | 167 | 0.637802 | 5.530093 | false | false | false | false |
lotosbin/SharpSwift | SharpSwift/SharpSwift/test.swift | 2 | 917 | // Converted with SharpSwift - https://github.com/matthewsot/SharpSwift
import Something.Else;
class anotherClass {
public static func something<T: IEnumerable<string>, IEnumerator<bool>>() -> Void {
return;
}
}
class test: ASCIIEncoding {
var something: String = "123";
init(something: String) {
var m = anotherClass();
let constant: String = "123";
var intArray: List<Int> = [ 1, 2, 3 ].ToList();
var strArray: [String] = [ "hi", "bye", "why" ];
for str in strArray {
}
for var i = 0; i < 10; i++ {
var md = i;
}
switch constant {
case "123":
var f = 1;
var mdf = 3;
case "456":
case "754":
var d = 2;
case "643":
var c = 3;
default:
}
}
}
| mit | 68f3a5c5938e37f7d3022ca15b2c694d | 23.131579 | 87 | 0.453653 | 4.004367 | false | false | false | false |
naddison36/book-review-ios | BooksManager.swift | 1 | 5150 | //
// GoogleBooks.swift
// BookReview
//
// Created by Nicholas Addison on 22/07/2015.
// Copyright (c) 2015 Nicholas Addison. All rights reserved.
//
import Foundation
import Parse
import Alamofire
import SwiftyJSON
class BooksManager
{
static let sharedInstance = BooksManager()
func getBook(isbn: String, callback: (error: NSError?, book: PFObject?)->() )
{
Alamofire.request(
GoogleBookRouter.SearchByISBN(isbn: isbn) )
.responseJSON
{
request, response, json, error in
if let error = error
{
NSLog("Failed to call Google Books API: " + error.description)
//FIXME:- wrap Alamofire error before returning
callback(error: error, book: nil)
return
}
else if let json: AnyObject = json
{
// convert into a SwiftJSON struct
let json = JSON(json)
NSLog("Successfully called Google Books API. JSON: " + json.description)
if let items = json["items"].array
{
if let firstItem = items.first
{
let book = PFObject(className: "books")
book["ISBN"] = isbn
if let title = firstItem["volumeInfo","title"].string
{
if let subtitle = firstItem["volumeInfo","subtitle"].string
{
book["title"] = title + ", " + subtitle
}
else
{
book["title"] = title
}
}
else
{
println(firstItem["volumeInfo","title"].error)
}
if let authors = firstItem["volumeInfo","authors"].array
where authors.count > 0
{
book["author"] = authors.first!.string
}
else
{
println(firstItem["volumeInfo","author"].error)
}
if let publisher = firstItem["volumeInfo","publisher"].string
{
book["publisher"] = publisher
}
else
{
println(firstItem["volumeInfo","publisher"].error)
}
if let publishedDate = firstItem["volumeInfo","publishedDate"].string
{
book["publishedDate"] = publishedDate
}
else
{
println(firstItem["volumeInfo","publishedDate"].error)
}
if let description = firstItem["volumeInfo","description"].string
{
NSLog("description \(description)")
book["description"] = description
}
else
{
println(firstItem["volumeInfo","description"].error)
}
if let smallThumbnailURL = firstItem["volumeInfo","imageLinks","smallThumbnail"].string
{
NSLog("small thumbnail \(smallThumbnailURL)")
book["smallThumbnailURL"] = smallThumbnailURL
}
else
{
println(firstItem["volumeInfo","imageLinks","smallThumbnail"].error)
}
callback(error: nil, book: book)
return
}
}
else
{
NSLog("Failed to parse Google Books API")
}
}
else
{
NSLog("Failed to call Google Books API. No JSON data was returned")
}
}
}
} | mit | 42848dcb088da33f25b9812c97564af9 | 38.930233 | 115 | 0.334757 | 8.046875 | false | false | false | false |
AndrejJurkin/nova-osx | Nova/data/firebase/News.swift | 1 | 1493 | //
// Copyright 2017 Andrej Jurkin.
//
// 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.
//
//
// News.swift
// Nova
//
// Created by Andrej Jurkin on 12/30/17.
//
import Foundation
import RealmSwift
import ObjectMapper
class News: RealmObject, Mappable {
dynamic var id: Int = 0
dynamic var title: String = ""
dynamic var subtitle: String = ""
dynamic var link: String = ""
dynamic var imageUrl: String = ""
dynamic var buttonTitle: String = ""
dynamic var hidden: Bool = false
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
self.id <- map["id"]
self.title <- map["title"]
self.subtitle <- map["subtitle"]
self.link <- map["link"]
self.imageUrl <- map["imageUrl"]
self.buttonTitle <- map["buttonTitle"]
self.hidden <- map["hidden"]
}
override static func primaryKey() -> String? {
return "id"
}
}
| apache-2.0 | 44f33e7a836d6e0330544246388c2c11 | 26.648148 | 76 | 0.636973 | 4.06812 | false | false | false | false |
tredds/pixelthoughts | PixelThoughts/ViewController.swift | 1 | 4923 | //
// ViewController.swift
// PixelThoughts
//
// Created by Victor Tatarasanu on 12/14/15.
// Copyright © 2015 Victor Tatarasanu. All rights reserved.
//
import UIKit
import SpriteKit
import AVFoundation
class ViewController: UIViewController, ResultsControllerSelection, StarViewAnimation {
@IBOutlet weak var message: UILabel!
@IBOutlet weak var button: UIButton!
let duration = 60.0
let stars = StarsView()
lazy var star : StarView = {
let star = StarView()
star.delegate = self
return star
}()
var player : AVAudioPlayer?
var mainMessage = "Put a stressful thought in the star"
var endingMessage = "Hope you feel a little less stressed and a little more connected"
var messages = DataProvider.sharedInstance().messegesProvider.messages()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(stars)
self.view.addSubview(star)
self.view.sendSubviewToBack(stars)
self.setupConstraints()
let player : AVAudioPlayer
do {
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "m4a")!)
try player = AVAudioPlayer(contentsOfURL: url, fileTypeHint:"m4a")
player.numberOfLoops = -1
player.play()
self.player = player
} catch {
print("error")
}
}
override weak var preferredFocusedView: UIView? {
return nil
}
@IBAction func showSearch(sender: AnyObject) {
let results = ResultsController()
results.delegate = self
let searchController = UISearchController.init(searchResultsController: results)
searchController.searchResultsUpdater = results
searchController.hidesNavigationBarDuringPresentation = false
let searchPlaceholderText = NSLocalizedString("Enter keyword (e.g. work)", comment: "")
searchController.searchBar.placeholder = searchPlaceholderText
self.presentViewController(searchController, animated: true, completion: { () -> Void in
})
}
//MARK: ResultsControllerSelection
func resultsControllerSelectionSelect(string: String) {
self.star.update(text: string, animated: true)
self.setupMovingScene()
}
//MARK: StarViewAnimation
func starViewEndedScaleAnimation()
{
self.setupEndingScene()
}
//MARK: Private
func setupMovingScene() {
self.star.start(duration: duration)
self.message.animate(titles: messages, duration: duration)
self.button.hidden = true
}
func setupEndingScene() {
self.button.hidden = false
self.message.text = self.endingMessage
self.star.reload()
}
func setupConstraints() {
stars.translatesAutoresizingMaskIntoConstraints = false
star.translatesAutoresizingMaskIntoConstraints = false
let xCenterConstraint = NSLayoutConstraint(item: self.view, attribute: .CenterX, relatedBy: .Equal, toItem: stars, attribute: .CenterX, multiplier: 1, constant: 0)
self.view.addConstraint(xCenterConstraint)
let yCenterConstraint = NSLayoutConstraint(item: self.view, attribute: .CenterY, relatedBy: .Equal, toItem: stars, attribute: .CenterY, multiplier: 1, constant: 0)
self.view.addConstraint(yCenterConstraint)
let heightConstraint = NSLayoutConstraint(item: self.view, attribute: .Height, relatedBy: .Equal, toItem: stars, attribute: .Height, multiplier: 1, constant: 0)
self.view.addConstraint(heightConstraint)
let widthConstraint = NSLayoutConstraint(item: self.view, attribute: .Width, relatedBy: .Equal, toItem: stars, attribute: .Width, multiplier: 1, constant: 0)
self.view.addConstraint(widthConstraint)
let starXCenterConstraint = NSLayoutConstraint(item: self.view, attribute: .CenterX, relatedBy: .Equal, toItem: star, attribute: .CenterX, multiplier: 1, constant: 0)
self.view.addConstraint(starXCenterConstraint)
let starYCenterConstraint = NSLayoutConstraint(item: self.view, attribute: .CenterY, relatedBy: .Equal, toItem: star, attribute: .CenterY, multiplier: 1, constant: 0)
self.view.addConstraint(starYCenterConstraint)
let starHeightConstraint = NSLayoutConstraint(item: star, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 0.5, constant: 0)
self.view.addConstraint(starHeightConstraint)
let starWidthConstraint = NSLayoutConstraint(item: star, attribute: .Width, relatedBy: .Equal, toItem: star, attribute: .Height, multiplier: 1, constant: 0)
self.view.addConstraint(starWidthConstraint)
}
}
| mit | 73c7c5c756bb0d5f35667616b7a27f27 | 36.572519 | 174 | 0.666802 | 4.971717 | false | false | false | false |
ykyouhei/KYShutterButton | KYShutterButton/Classes/KYShutterButton.swift | 1 | 13222 | /*
The MIT License (MIT)
Copyright (c) 2015 Kyohei Yamaguchi
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
@objc
@IBDesignable
open class KYShutterButton: UIButton {
@objc
public enum ShutterType: Int {
case normal, slowMotion, timeLapse
}
@objc
public enum ButtonState: Int {
case normal, recording
}
private let _kstartAnimateDuration: CFTimeInterval = 0.5
/**************************************************************************/
// MARK: - Properties
/**************************************************************************/
@objc
@IBInspectable var typeRaw: Int = 0 {
didSet {
if let type = ShutterType(rawValue: typeRaw) {
self.shutterType = type
} else {
self.shutterType = .normal
}
}
}
@objc
@IBInspectable public var buttonColor: UIColor = UIColor.red {
didSet {
_circleLayer.fillColor = buttonColor.cgColor
}
}
@objc
@IBInspectable public var arcColor: UIColor = UIColor.white {
didSet {
_arcLayer.strokeColor = arcColor.cgColor
}
}
@objc
@IBInspectable public var progressColor: UIColor = UIColor.white {
didSet {
_progressLayer.strokeColor = progressColor.cgColor
_rotateLayer.strokeColor = progressColor.cgColor
}
}
@objc
@IBInspectable public var rotateAnimateDuration: Float = 5 {
didSet {
_recordingRotateAnimation.duration = TimeInterval(rotateAnimateDuration)
_recordingAnimation.duration = TimeInterval(rotateAnimateDuration*2)
}
}
@objc
public var buttonState: ButtonState = .normal {
didSet {
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = _circleLayer.path
animation.duration = 0.15
switch buttonState {
case .normal:
if shutterType == .timeLapse {
p_removeTimeLapseAnimations()
}
animation.toValue = _circlePath.cgPath
_circleLayer.add(animation, forKey: "path-anim")
_circleLayer.path = _circlePath.cgPath
case .recording:
animation.toValue = _roundRectPath.cgPath
_circleLayer.add(animation, forKey: "path-anim")
_circleLayer.path = _roundRectPath.cgPath
if shutterType == .timeLapse {
p_addTimeLapseAnimations()
}
}
}
}
@objc
public var shutterType: ShutterType = .normal {
didSet {
updateLayers()
}
}
private var _arcWidth: CGFloat {
return bounds.width * 0.09090
}
private var _arcMargin: CGFloat {
return bounds.width * 0.03030
}
lazy private var _circleLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.path = self._circlePath.cgPath
layer.fillColor = self.buttonColor.cgColor
return layer
}()
lazy private var _arcLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.path = self._arcPath.cgPath
layer.fillColor = UIColor.clear.cgColor
layer.strokeColor = self.arcColor.cgColor
layer.lineWidth = self._arcWidth
return layer
}()
lazy private var _progressLayer: CAShapeLayer = {
let layer = CAShapeLayer()
let path = self.p_arcPathWithProgress(1.0, clockwise: true)
layer.path = path.cgPath
layer.fillColor = UIColor.clear.cgColor
layer.strokeColor = self.progressColor.cgColor
layer.lineWidth = self._arcWidth/1.5
return layer
}()
lazy private var _rotateLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.strokeColor = self.progressColor.cgColor
layer.lineWidth = 1
layer.path = self._rotatePath.cgPath
layer.frame = self.bounds
return layer
}()
private var _circlePath: UIBezierPath {
let side = self.bounds.width - self._arcWidth*2 - self._arcMargin*2
return UIBezierPath(
roundedRect: CGRect(x: bounds.width/2 - side/2, y: bounds.width/2 - side/2, width: side, height: side),
cornerRadius: side/2
)
}
private var _arcPath: UIBezierPath {
return UIBezierPath(
arcCenter: CGPoint(x: self.bounds.midX, y: self.bounds.midY),
radius: self.bounds.width/2 - self._arcWidth/2,
startAngle: -.pi/2,
endAngle: .pi*2 - .pi/2,
clockwise: true
)
}
private var _roundRectPath: UIBezierPath {
let side = bounds.width * 0.4242
return UIBezierPath(
roundedRect: CGRect(x: bounds.width/2 - side/2, y: bounds.width/2 - side/2, width: side, height: side),
cornerRadius: side * 0.107
)
}
private var _rotatePath: UIBezierPath {
let path = UIBezierPath()
path.move(to: CGPoint(x: self.bounds.width/2, y: 0))
path.addLine(to: CGPoint(x: self.bounds.width/2, y: self._arcWidth))
return path
}
private var _startProgressAnimation: CAKeyframeAnimation {
let frameCount = 60
var paths = [CGPath]()
var times = [CGFloat]()
for i in 1...frameCount {
let animationProgress = 1/CGFloat(frameCount) * CGFloat(i) - 0.01
paths.append(self.p_arcPathWithProgress(animationProgress, clockwise: false).cgPath)
times.append(CGFloat(i)*0.1)
}
let animation = CAKeyframeAnimation(keyPath: "path")
animation.duration = _kstartAnimateDuration
animation.values = paths
return animation
}
private var _startRotateAnimation: CABasicAnimation {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = 0
animation.toValue = CGFloat.pi*2
animation.duration = _kstartAnimateDuration
return animation
}
private var _recordingAnimation: CAKeyframeAnimation {
let frameCount = 60
var paths = [CGPath]()
for i in 1...frameCount {
let animationProgress = 1/CGFloat(frameCount) * CGFloat(i)
paths.append(self.p_arcPathWithProgress(animationProgress).cgPath)
}
for i in 1...frameCount {
let animationProgress = 1/CGFloat(frameCount) * CGFloat(i) - 0.01
paths.append(self.p_arcPathWithProgress(animationProgress, clockwise: false).cgPath)
}
let animation = CAKeyframeAnimation(keyPath: "path")
animation.duration = TimeInterval(rotateAnimateDuration*2)
animation.values = paths
animation.beginTime = CACurrentMediaTime() + _kstartAnimateDuration
animation.repeatCount = Float.infinity
animation.calculationMode = kCAAnimationDiscrete
return animation
}
private var _recordingRotateAnimation: CABasicAnimation {
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.fromValue = 0
animation.toValue = CGFloat.pi*2
animation.duration = TimeInterval(rotateAnimateDuration)
animation.repeatCount = Float.infinity
animation.beginTime = CACurrentMediaTime() + _kstartAnimateDuration
return animation
}
/**************************************************************************/
// MARK: - initialize
/**************************************************************************/
@objc
public convenience init(frame: CGRect, shutterType: ShutterType, buttonColor: UIColor) {
self.init(frame: frame)
self.shutterType = shutterType
self.buttonColor = buttonColor
}
/**************************************************************************/
// MARK: - Override
/**************************************************************************/
@objc
override open var isHighlighted: Bool {
didSet {
_circleLayer.opacity = isHighlighted ? 0.5 : 1.0
}
}
@objc
open override func layoutSubviews() {
super.layoutSubviews()
if _arcLayer.superlayer != layer {
layer.addSublayer(_arcLayer)
} else {
_arcLayer.path = _arcPath.cgPath
_arcLayer.lineWidth = _arcWidth
}
if _progressLayer.superlayer != layer {
layer.addSublayer(_progressLayer)
} else {
_progressLayer.path = p_arcPathWithProgress(1).cgPath
_progressLayer.lineWidth = _arcWidth/1.5
}
if _rotateLayer.superlayer != layer {
layer.insertSublayer(_rotateLayer, at: 0)
} else {
_rotateLayer.path = _rotatePath.cgPath
_rotateLayer.frame = self.bounds
}
if _circleLayer.superlayer != layer {
layer.addSublayer(_circleLayer)
} else {
switch buttonState {
case .normal: _circleLayer.path = _circlePath.cgPath
case .recording: _circleLayer.path = _roundRectPath.cgPath
}
}
if shutterType == .timeLapse && buttonState == .recording {
p_removeTimeLapseAnimations()
p_addTimeLapseAnimations()
}
updateLayers()
}
@objc
open override func setTitle(_ title: String?, for state: UIControlState) {
super.setTitle("", for: state)
}
/**************************************************************************/
// MARK: - Method
/**************************************************************************/
private func p_addTimeLapseAnimations() {
_progressLayer.add(_startProgressAnimation, forKey: "start-anim")
_rotateLayer.add(_startRotateAnimation, forKey: "rotate-anim")
_progressLayer.add(_recordingAnimation, forKey: "recording-anim")
_rotateLayer.add(_recordingRotateAnimation, forKey: "recordingRotate-anim")
_progressLayer.path = p_arcPathWithProgress(1.0).cgPath
}
private func p_removeTimeLapseAnimations() {
_progressLayer.removeAllAnimations()
_rotateLayer.removeAllAnimations()
}
private func p_arcPathWithProgress(_ progress: CGFloat, clockwise: Bool = true) -> UIBezierPath {
let diameter = 2*CGFloat.pi*(self.bounds.width/2 - self._arcWidth/3)
let startAngle = clockwise ?
-CGFloat.pi/2 :
-CGFloat.pi/2 + CGFloat.pi*(540/diameter)/180
let endAngle = clockwise ?
CGFloat.pi*2*progress - CGFloat.pi/2 :
CGFloat.pi*2*progress - CGFloat.pi/2 + CGFloat.pi*(540/diameter)/180
let path = UIBezierPath(
arcCenter: CGPoint(x: self.bounds.midX, y: self.bounds.midY),
radius: self.bounds.width/2 - self._arcWidth/3,
startAngle: startAngle,
endAngle: endAngle,
clockwise: clockwise
)
return path
}
private func updateLayers() {
switch shutterType {
case .normal:
_arcLayer.lineDashPattern = nil
_progressLayer.isHidden = true
case .slowMotion:
_arcLayer.lineDashPattern = [1, 1]
_progressLayer.isHidden = true
case .timeLapse:
let diameter = CGFloat.pi*(self.bounds.width/2 - self._arcWidth/2)
let progressDiameter = 2*CGFloat.pi*(self.bounds.width/2 - self._arcWidth/3)
_arcLayer.lineDashPattern = [1, NSNumber(value: (diameter/10 - 1).native)]
_progressLayer.lineDashPattern = [1, NSNumber(value: (progressDiameter/60 - 1).native)]
_progressLayer.isHidden = false
}
}
}
| mit | 56007b3aca9aa55b45d9c1b4027ef798 | 34.543011 | 115 | 0.570186 | 5.106991 | false | false | false | false |
kzin/swift-testing | swift-testing/Pods/Mockingjay/Mockingjay/NSURLSessionConfiguration.swift | 4 | 1884 | //
// NSURLSessionConfiguration.swift
// Mockingjay
//
// Created by Kyle Fuller on 01/03/2015.
// Copyright (c) 2015 Cocode. All rights reserved.
//
import Foundation
let swizzleDefaultSessionConfiguration: Void = {
let defaultSessionConfiguration = class_getClassMethod(URLSessionConfiguration.self, #selector(getter: URLSessionConfiguration.default))
let mockingjayDefaultSessionConfiguration = class_getClassMethod(URLSessionConfiguration.self, #selector(URLSessionConfiguration.mockingjayDefaultSessionConfiguration))
method_exchangeImplementations(defaultSessionConfiguration, mockingjayDefaultSessionConfiguration)
let ephemeralSessionConfiguration = class_getClassMethod(URLSessionConfiguration.self, #selector(getter: URLSessionConfiguration.ephemeral))
let mockingjayEphemeralSessionConfiguration = class_getClassMethod(URLSessionConfiguration.self, #selector(URLSessionConfiguration.mockingjayEphemeralSessionConfiguration))
method_exchangeImplementations(ephemeralSessionConfiguration, mockingjayEphemeralSessionConfiguration)
}()
extension URLSessionConfiguration {
/// Swizzles NSURLSessionConfiguration's default and ephermeral sessions to add Mockingjay
public class func mockingjaySwizzleDefaultSessionConfiguration() {
_ = swizzleDefaultSessionConfiguration
}
class func mockingjayDefaultSessionConfiguration() -> URLSessionConfiguration {
let configuration = mockingjayDefaultSessionConfiguration()
configuration.protocolClasses = [MockingjayProtocol.self] as [AnyClass] + configuration.protocolClasses!
return configuration
}
class func mockingjayEphemeralSessionConfiguration() -> URLSessionConfiguration {
let configuration = mockingjayEphemeralSessionConfiguration()
configuration.protocolClasses = [MockingjayProtocol.self] as [AnyClass] + configuration.protocolClasses!
return configuration
}
}
| mit | eea2ae5552e546ac3d23398c7acdcfce | 48.578947 | 174 | 0.834926 | 6.430034 | false | true | false | false |
bustoutsolutions/siesta | Source/Siesta/Support/Siesta-ObjC.swift | 1 | 15666 | //
// Siesta-ObjC.swift
// Siesta
//
// Created by Paul on 2015/7/14.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
// swiftlint:disable identifier_name type_name missing_docs
import Foundation
/*
Glue for using Siesta from Objective-C.
Siesta follows a Swift-first design approach. It uses the full expressiveness of the
language to make everything feel “Swift native,” both in interface and implementation.
This means many Siesta APIs can’t simply be marked @objc, and require a separate
compatibility layer. Rather than sprinkle that mess throughout the code, it’s all
quarrantined here.
Features exposed to Objective-C:
* Resource path navigation (child, relative, etc.)
* Resource state
* Observers
* Request / load
* Request completion callbacks
* UI components
Some things are not exposed in the compatibility layer, and must be done in Swift:
* Subclassing Service
* Custom ResponseTransformers
* Custom NetworkingProviders
* Logging config
* Just about anything else configuration-related
*/
// MARK: - Because Swift structs aren’t visible to Obj-C
// (Why not just make Entity<Any> and RequestError classes and avoid all these
// shenanigans? Because Swift’s lovely mutable/immutable struct handling lets Resource
// expose the full struct to Swift clients sans copying, yet still force mutations to
// happen via overrideLocalData() so that observers always know about changes.)
@objc(BOSEntity)
public class _objc_Entity: NSObject
{
@objc public var content: AnyObject
@objc public var contentType: String
@objc public var charset: String?
@objc public var etag: String?
fileprivate var headers: [String:String]
@objc public private(set) var timestamp: TimeInterval = 0
@objc public init(content: AnyObject, contentType: String, headers: [String:String])
{
self.content = content
self.contentType = contentType
self.headers = headers
}
@objc public convenience init(content: AnyObject, contentType: String)
{ self.init(content: content, contentType: contentType, headers: [:]) }
internal init(_ entity: Entity<Any>)
{
self.content = entity.content as AnyObject
self.contentType = entity.contentType
self.charset = entity.charset
self.etag = entity.etag
self.headers = entity.headers
}
@objc public func header(_ key: String) -> String?
{ headers[key.lowercased()] }
@objc public override var description: String
{ debugStr(Entity<Any>.convertedFromObjc(self)) }
}
extension Entity
{
static func convertedFromObjc(_ entity: _objc_Entity) -> Entity<Any>
{
Entity<Any>(content: entity.content, contentType: entity.contentType, charset: entity.charset, headers: entity.headers)
}
}
@objc(BOSError)
public class _objc_Error: NSObject
{
@objc public var httpStatusCode: Int
@objc public var cause: NSError?
@objc public var userMessage: String
@objc public var entity: _objc_Entity?
@objc public let timestamp: TimeInterval
internal init(_ error: RequestError)
{
self.httpStatusCode = error.httpStatusCode ?? -1
self.cause = error.cause as NSError?
self.userMessage = error.userMessage
self.timestamp = error.timestamp
if let errorData = error.entity
{ self.entity = _objc_Entity(errorData) }
}
}
extension Service
{
@objc(resourceWithAbsoluteURL:)
public final func _objc_resourceWithAbsoluteURL(absoluteURL url: URL?) -> Resource
{ resource(absoluteURL: url) }
@objc(resourceWithAbsoluteURLString:)
public final func _objc_resourceWithAbsoluteURLString(absoluteURL url: String?) -> Resource
{ resource(absoluteURL: url) }
}
extension Resource
{
@objc(latestData)
public var _objc_latestData: _objc_Entity?
{
if let latestData = latestData
{ return _objc_Entity(latestData) }
else
{ return nil }
}
@objc(latestError)
public var _objc_latestError: _objc_Error?
{
if let latestError = latestError
{ return _objc_Error(latestError) }
else
{ return nil }
}
@objc(jsonDict)
public var _objc_jsonDict: NSDictionary
{ jsonDict as NSDictionary }
@objc(jsonArray)
public var _objc_jsonArray: NSArray
{ jsonArray as NSArray }
@objc(text)
public var _objc_text: String
{ text }
@objc(overrideLocalData:)
public func _objc_overrideLocalData(_ entity: _objc_Entity)
{ overrideLocalData(with: Entity<Any>.convertedFromObjc(entity)) }
@objc(withParams:)
public func _objc_withParams(_ params: [String:NSObject]) -> Resource
{
withParams(
params.mapValues
{
switch $0
{
case let string as String:
return string
case is NSNull:
return nil
default:
fatalError("Received parameter value that is neither string nor null: \($0)")
}
})
}
}
// MARK: - Because Swift closures aren’t exposed as Obj-C blocks
@objc(BOSRequest)
public class _objc_Request: NSObject
{
fileprivate let request: Request
fileprivate init(_ request: Request)
{ self.request = request }
@objc public func onCompletion(_ objcCallback: @escaping @convention(block) (_objc_Entity?, _objc_Error?) -> Void) -> _objc_Request
{
request.onCompletion
{
switch $0.response
{
case .success(let entity):
objcCallback(_objc_Entity(entity), nil)
case .failure(let error):
objcCallback(nil, _objc_Error(error))
}
}
return self
}
@objc public func onSuccess(_ objcCallback: @escaping @convention(block) (_objc_Entity) -> Void) -> _objc_Request
{
request.onSuccess { entity in objcCallback(_objc_Entity(entity)) }
return self
}
@objc public func onNewData(_ objcCallback: @escaping @convention(block) (_objc_Entity) -> Void) -> _objc_Request
{
request.onNewData { entity in objcCallback(_objc_Entity(entity)) }
return self
}
@objc public func onNotModified(_ objcCallback: @escaping @convention(block) () -> Void) -> _objc_Request
{
request.onNotModified(objcCallback)
return self
}
@objc public func onFailure(_ objcCallback: @escaping @convention(block) (_objc_Error) -> Void) -> _objc_Request
{
request.onFailure { error in objcCallback(_objc_Error(error)) }
return self
}
@objc public func onProgress(_ objcCallback: @escaping @convention(block) (Float) -> Void) -> _objc_Request
{
request.onProgress { p in objcCallback(Float(p)) }
return self
}
@objc public func cancel()
{ request.cancel() }
@objc public override var description: String
{ debugStr(request) }
}
extension Resource
{
@objc(load)
public func _objc_load() -> _objc_Request
{ _objc_Request(load()) }
@objc(loadIfNeeded)
public func _objc_loadIfNeeded() -> _objc_Request?
{
if let req = loadIfNeeded()
{ return _objc_Request(req) }
else
{ return nil }
}
}
// MARK: - Because Swift enums aren’t exposed to Obj-C
@objc(BOSResourceObserver)
public protocol _objc_ResourceObserver
{
func resourceChanged(_ resource: Resource, event: String)
@objc optional func resourceRequestProgress(_ resource: Resource, progress: Double)
@objc optional func stoppedObservingResource(_ resource: Resource)
}
private class _objc_ResourceObserverGlue: ResourceObserver, CustomDebugStringConvertible
{
var resource: Resource?
var objcObserver: _objc_ResourceObserver
init(objcObserver: _objc_ResourceObserver)
{ self.objcObserver = objcObserver }
deinit
{
if let resource = resource
{ objcObserver.stoppedObservingResource?(resource) }
}
func resourceChanged(_ resource: Resource, event: ResourceEvent)
{
if case .observerAdded = event
{ self.resource = resource }
objcObserver.resourceChanged(resource, event: event._objc_stringForm)
}
func resourceRequestProgress(_ resource: Resource, progress: Double)
{ objcObserver.resourceRequestProgress?(resource, progress: progress) }
var observerIdentity: AnyHashable
{ ObjectIdentifier(objcObserver) }
var debugDescription: String
{ debugStr(objcObserver) }
}
extension ResourceEvent
{
public var _objc_stringForm: String
{
if case .newData(let source) = self
{ return "NewData(\(source.description.capitalized))" }
else
{ return String(describing: self).capitalized }
}
}
extension Resource
{
@objc(addObserver:)
public func _objc_addObserver(_ observerAndOwner: _objc_ResourceObserver & AnyObject) -> Self
{ addObserver(_objc_ResourceObserverGlue(objcObserver: observerAndOwner), owner: observerAndOwner) }
@objc(addObserver:owner:)
public func _objc_addObserver(_ objcObserver: _objc_ResourceObserver, owner: AnyObject) -> Self
{ addObserver(_objc_ResourceObserverGlue(objcObserver: objcObserver), owner: owner) }
@objc(addObserverWithOwner:callback:)
public func _objc_addObserver(owner: AnyObject, block: @escaping @convention(block) (Resource, String) -> Void) -> Self
{
addObserver(owner: owner)
{ block($0, $1._objc_stringForm) }
}
}
extension Resource
{
private func _objc_wrapRequest(
_ methodString: String,
closure: (RequestMethod) -> Request)
-> _objc_Request
{
guard let method = RequestMethod(rawValue: methodString.lowercased()) else
{
return _objc_Request(
Resource.failedRequest(
returning: RequestError(
userMessage: NSLocalizedString("Cannot create request", comment: "userMessage"),
cause: _objc_Error.Cause.InvalidRequestMethod(method: methodString))))
}
return _objc_Request(closure(method))
}
private func _objc_wrapJSONRequest(
_ methodString: String,
_ maybeJson: NSObject?,
closure: (RequestMethod, JSONConvertible) -> Request)
-> _objc_Request
{
guard let json = maybeJson as? JSONConvertible else
{
return _objc_Request(
Resource.failedRequest(
returning: RequestError(
userMessage: NSLocalizedString("Cannot send request", comment: "userMessage"),
cause: RequestError.Cause.InvalidJSONObject())))
}
return _objc_wrapRequest(methodString) { closure($0, json) }
}
private static func apply(requestMutation: (@convention(block) (NSMutableURLRequest) -> Void)?, to request: inout URLRequest)
{
let mutableReq = (request as NSURLRequest).mutableCopy() as! NSMutableURLRequest
requestMutation?(mutableReq)
request = mutableReq as URLRequest
}
@objc(requestWithMethod:requestMutation:)
public func _objc_request(
_ method: String,
requestMutation: (@convention(block) (NSMutableURLRequest) -> Void)?)
-> _objc_Request
{
_objc_wrapRequest(method)
{
request($0)
{ Resource.apply(requestMutation: requestMutation, to: &$0) }
}
}
@objc(requestWithMethod:)
public func _objc_request(_ method: String)
-> _objc_Request
{
_objc_wrapRequest(method)
{ request($0) }
}
@objc(requestWithMethod:data:contentType:requestMutation:)
public func _objc_request(
_ method: String,
data: Data,
contentType: String,
requestMutation: (@convention(block) (NSMutableURLRequest) -> Void)?)
-> _objc_Request
{
_objc_wrapRequest(method)
{
request($0, data: data, contentType: contentType)
{ Resource.apply(requestMutation: requestMutation, to: &$0) }
}
}
@objc(requestWithMethod:text:)
public func _objc_request(
_ method: String,
text: String)
-> _objc_Request
{
_objc_wrapRequest(method)
{ request($0, text: text) }
}
@objc(requestWithMethod:text:contentType:encoding:requestMutation:)
public func _objc_request(
_ method: String,
text: String,
contentType: String,
encoding: UInt = String.Encoding.utf8.rawValue,
requestMutation: (@convention(block) (NSMutableURLRequest) -> Void)?)
-> _objc_Request
{
_objc_wrapRequest(method)
{
request($0, text: text, contentType: contentType, encoding: String.Encoding(rawValue: encoding))
{ Resource.apply(requestMutation: requestMutation, to: &$0) }
}
}
@objc(requestWithMethod:json:)
public func _objc_request(
_ method: String,
json: NSObject?)
-> _objc_Request
{
_objc_wrapJSONRequest(method, json)
{ request($0, json: $1) }
}
@objc(requestWithMethod:json:contentType:requestMutation:)
public func _objc_request(
_ method: String,
json: NSObject?,
contentType: String,
requestMutation: (@convention(block) (NSMutableURLRequest) -> Void)?)
-> _objc_Request
{
_objc_wrapJSONRequest(method, json)
{
request($0, json: $1, contentType: contentType)
{ Resource.apply(requestMutation: requestMutation, to: &$0) }
}
}
@objc(requestWithMethod:urlEncoded:requestMutation:)
public func _objc_request(
_ method: String,
urlEncoded params: [String:String],
requestMutation: (@convention(block) (NSMutableURLRequest) -> Void)?)
-> _objc_Request
{
_objc_wrapRequest(method)
{
request($0, urlEncoded: params)
{ Resource.apply(requestMutation: requestMutation, to: &$0) }
}
}
@objc(loadUsingRequest:)
public func _objc_load(using req: _objc_Request) -> _objc_Request
{
load(using: req.request)
return req
}
}
extension _objc_Error
{
public enum Cause
{
/// Request method specified as a string does not match any of the values in the RequestMethod enum.
public struct InvalidRequestMethod: Error
{
public let method: String
}
}
}
| mit | fcaf530c9c3e3ff8d0eb1a710e12c385 | 30.806911 | 135 | 0.594862 | 4.815077 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/VideoMediaDownloader.swift | 1 | 16030 | //
// VideoMediaDownloader.swift
// Slide for Reddit
//
// Created by Carlos Crane on 11/7/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import Alamofire
import AVFoundation
import SDWebImage
import UIKit
class VideoMediaDownloader {
var request: DownloadRequest?
var baseURL: String
var videoType: VideoMediaViewController.VideoType
var progressBar = UIProgressView()
var alertView: UIAlertController?
var ready = false
init(urlToLoad: URL) {
self.baseURL = urlToLoad.absoluteString
self.videoType = VideoMediaViewController.VideoType.fromPath(baseURL)
if urlToLoad.absoluteString.contains("HLSPlaylist.m3u8") {
let qualityList = ["1080", "720", "480", "360", "240", "96"]
getQualityURL(urlToLoad: urlToLoad.absoluteString, qualityList: qualityList)
} else {
ready = true
}
}
func getQualityURL(urlToLoad: String, qualityList: [String]) {
if qualityList.isEmpty {
BannerUtil.makeBanner(text: "Error finding video URL", color: GMColor.red500Color(), seconds: 5, context: self.parent ?? nil, top: false, callback: nil)
} else {
testQuality(urlToLoad: urlToLoad, quality: qualityList.first ?? "") { (success, url) in
if success {
self.ready = true
self.baseURL = url
self.doDownload()
} else {
var newList = qualityList
newList.remove(at: 0)
self.getQualityURL(urlToLoad: urlToLoad, qualityList: newList)
}
}
}
}
func testQuality(urlToLoad: String, quality: String, completion: @escaping(_ success: Bool, _ url: String) -> Void) {
Alamofire.request(urlToLoad.replacingOccurrences(of: "HLSPlaylist.m3u8", with: "DASH_\(quality)"), method: .get).responseString { response in
if response.response?.statusCode == 200 {
completion(response.response?.statusCode ?? 0 == 200, urlToLoad.replacingOccurrences(of: "HLSPlaylist.m3u8", with: "DASH_\(quality)"))
} else {
Alamofire.request(urlToLoad.replacingOccurrences(of: "HLSPlaylist.m3u8", with: "DASH_\(quality).mp4"), method: .get).responseString { response in
completion(response.response?.statusCode ?? 0 == 200, urlToLoad.replacingOccurrences(of: "HLSPlaylist.m3u8", with: "DASH_\(quality).mp4"))
}
}
}
}
var completion: ((_ fileURL: URL?) -> Void)!
weak var parent: UIViewController!
func getVideoWithCompletion(completion: @escaping (_ fileURL: URL?) -> Void, parent: UIViewController) {
self.completion = completion
self.parent = parent
if ready {
doDownload()
}
}
func doDownload() {
if !ready || completion == nil || parent == nil {
return
}
print(baseURL)
alertView = UIAlertController(title: "Downloading...", message: "Your video is downloading", preferredStyle: .alert)
alertView!.addCancelButton()
parent.present(alertView!, animated: true, completion: {
let margin: CGFloat = 8.0
let rect = CGRect.init(x: margin, y: 72.0, width: (self.alertView?.view.frame.width)! - margin * 2.0, height: 2.0)
self.progressBar = UIProgressView(frame: rect)
self.progressBar.progress = 0
self.progressBar.tintColor = ColorUtil.accentColorForSub(sub: "")
self.alertView?.view.addSubview(self.progressBar)
})
if FileManager.default.fileExists(atPath: getKeyFromURL()) {
alertView?.dismiss(animated: true, completion: {
self.completion(URL(fileURLWithPath: self.getKeyFromURL()))
})
} else {
request = Alamofire.download(URL(string: baseURL)!, method: .get, to: { (_, _) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
return (URL(fileURLWithPath: self.videoType == .REDDIT ? self.getKeyFromURL().replacingOccurrences(of: ".mp4", with: "video.mp4") : self.getKeyFromURL()), [.createIntermediateDirectories])
}).downloadProgress() { progress in
DispatchQueue.main.async {
let countBytes = ByteCountFormatter()
countBytes.allowedUnits = [.useMB]
countBytes.countStyle = .file
let fileSize = countBytes.string(fromByteCount: Int64(progress.totalUnitCount))
self.alertView?.title = "Downloading... (\(fileSize))"
self.progressBar.setProgress(Float(progress.fractionCompleted), animated: true)
}
}.responseData { response in
switch response.result {
case .failure(let error):
print(error)
self.alertView?.dismiss(animated: true, completion: {
BannerUtil.makeBanner(text: "Error downloading video", color: GMColor.red500Color(), seconds: 5, context: self.parent ?? nil, top: false, callback: nil)
})
case .success:
if self.videoType == .REDDIT {
self.downloadRedditAudio()
} else {
DispatchQueue.main.async {
self.alertView?.dismiss(animated: true, completion: {
self.completion(URL(fileURLWithPath: self.getKeyFromURL()))
})
}
}
}
}
}
}
func getKeyFromURL() -> String {
let disallowedChars = CharacterSet.urlPathAllowed.inverted
var key = self.baseURL.components(separatedBy: disallowedChars).joined(separator: "_")
key = key.replacingOccurrences(of: ":", with: "")
key = key.replacingOccurrences(of: "/", with: "")
key = key.replacingOccurrences(of: ".gifv", with: ".mp4")
key = key.replacingOccurrences(of: ".gif", with: ".mp4")
key = key.replacingOccurrences(of: ".", with: "")
if key.length > 200 {
key = key.substring(0, length: 200)
}
return SDImageCache.shared.diskCachePath + "/" + key + ".mp4"
}
func downloadRedditAudio() {
let key = getKeyFromURL()
var toLoadAudio = self.baseURL
toLoadAudio = toLoadAudio.substring(0, length: toLoadAudio.lastIndexOf("/") ?? toLoadAudio.length)
toLoadAudio += "/DASH_audio.mp4"
let finalUrl = URL.init(fileURLWithPath: key)
let localUrlV = URL.init(fileURLWithPath: key.replacingOccurrences(of: ".mp4", with: "video.mp4"))
let localUrlAudio = URL.init(fileURLWithPath: key.replacingOccurrences(of: ".mp4", with: "audio.mp4"))
print(localUrlAudio)
self.request = Alamofire.download(toLoadAudio, method: .get, to: { (_, _) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
return (localUrlAudio, [.removePreviousFile, .createIntermediateDirectories])
}).downloadProgress() { progress in
DispatchQueue.main.async {
let countBytes = ByteCountFormatter()
countBytes.allowedUnits = [.useMB]
countBytes.countStyle = .file
let fileSize = countBytes.string(fromByteCount: Int64(progress.totalUnitCount))
self.alertView?.title = "Downloading audio... (\(fileSize))"
self.progressBar.setProgress(Float(progress.fractionCompleted), animated: true)
}
}
.responseData { response2 in
if (response2.error as NSError?)?.code == NSURLErrorCancelled {
return
}
if response2.response!.statusCode != 200 {
do {
try FileManager.init().copyItem(at: localUrlV, to: finalUrl)
DispatchQueue.main.async {
self.alertView?.dismiss(animated: true, completion: {
self.completion(URL(fileURLWithPath: self.getKeyFromURL()))
})
}
} catch {
DispatchQueue.main.async {
self.alertView?.dismiss(animated: true, completion: {
self.completion(URL(fileURLWithPath: self.getKeyFromURL()))
})
}
}
} else { //no errors
self.mergeFilesWithUrl(videoUrl: localUrlV, audioUrl: localUrlAudio, savePathUrl: finalUrl) {
DispatchQueue.main.async {
self.alertView?.dismiss(animated: true, completion: {
self.completion(URL(fileURLWithPath: self.getKeyFromURL()))
})
}
}
}
}
}
func format(sS: String, _ hls: Bool = false) -> String {
var s = sS
if s.hasSuffix("v") && !s.contains("streamable.com") {
s = s.substring(0, length: s.length - 1)
} else if s.contains("gfycat") && (!s.contains("mp4") && !s.contains("webm")) {
if s.contains("-size_restricted") {
s = s.replacingOccurrences(of: "-size_restricted", with: "")
}
}
if (s.contains(".webm") || s.contains(".gif")) && !s.contains(".gifv") && s.contains(
"imgur.com") {
s = s.replacingOccurrences(of: ".gifv", with: ".mp4")
s = s.replacingOccurrences(of: ".gif", with: ".mp4")
s = s.replacingOccurrences(of: ".webm", with: ".mp4")
}
if s.endsWith("/") {
s = s.substring(0, length: s.length - 1)
}
if s.contains("v.redd.it") && !s.contains("DASH") && !s.contains("HLSPlaylist.m3u8") {
if s.endsWith("/") {
s = s.substring(0, length: s.length - 2)
}
s += "/DASH_9_6_M"
}
if hls && !s.contains("HLSPlaylist.m3u8") {
if s.contains("v.redd.it") && s.contains("DASH") {
if s.endsWith("/") {
s = s.substring(0, length: s.length - 2)
}
s = s.substring(0, length: s.lastIndexOf("/")!)
s += "/HLSPlaylist.m3u8"
} else if s.contains("v.redd.it") {
if s.endsWith("/") {
s = s.substring(0, length: s.length - 2)
}
if !s.contains("HLSPlaylist") {
s += "/HLSPlaylist.m3u8"
}
}
}
return s
}
func formatUrl(sS: String, _ vreddit: Bool = false) -> String {
return format(sS: sS, vreddit)
}
func getLastPathSegment(_ path: String) -> String {
var inv = path
if inv.endsWith("/") {
inv = inv.substring(0, length: inv.length - 1)
}
let slashindex = inv.lastIndexOf("/")!
print("Index is \(slashindex)")
inv = inv.substring(slashindex + 1, length: inv.length - slashindex - 1)
return inv
}
func getTimeFromString(_ time: String) -> Int {
var timeAdd = 0
for s in time.components(separatedBy: CharacterSet(charactersIn: "hms")) {
print(s)
if !s.isEmpty {
if time.contains(s + "s") {
timeAdd += Int(s)!
} else if time.contains(s + "m") {
timeAdd += 60 * Int(s)!
} else if time.contains(s + "h") {
timeAdd += 3600 * Int(s)!
}
}
}
if timeAdd == 0 && Int(time) != nil {
timeAdd += Int(time)!
}
return timeAdd
}
//From https://stackoverflow.com/a/39100999/3697225
func mergeFilesWithUrl(videoUrl: URL, audioUrl: URL, savePathUrl: URL, completion: @escaping () -> Void) {
let mixComposition: AVMutableComposition = AVMutableComposition()
var mutableCompositionVideoTrack: [AVMutableCompositionTrack] = []
var mutableCompositionAudioTrack: [AVMutableCompositionTrack] = []
let totalVideoCompositionInstruction: AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction()
//start merge
let aVideoAsset: AVAsset = AVAsset(url: videoUrl)
let aAudioAsset: AVAsset = AVAsset(url: audioUrl)
mutableCompositionVideoTrack.append(mixComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)!)
mutableCompositionAudioTrack.append(mixComposition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)!)
let aVideoAssetTrack: AVAssetTrack = aVideoAsset.tracks(withMediaType: AVMediaType.video)[0]
let aAudioAssetTrack: AVAssetTrack = aAudioAsset.tracks(withMediaType: AVMediaType.audio)[0]
do {
try mutableCompositionVideoTrack[0].insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: aVideoAssetTrack.timeRange.duration), of: aVideoAssetTrack, at: CMTime.zero)
//In my case my audio file is longer then video file so i took videoAsset duration
//instead of audioAsset duration
try mutableCompositionAudioTrack[0].insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: aVideoAssetTrack.timeRange.duration), of: aAudioAssetTrack, at: CMTime.zero)
//Use this instead above line if your audiofile and video file's playing durations are same
// try mutableCompositionAudioTrack[0].insertTimeRange(CMTimeRangeMake(kCMTimeZero, aVideoAssetTrack.timeRange.duration), ofTrack: aAudioAssetTrack, atTime: kCMTimeZero)
} catch {
print(error.localizedDescription)
}
totalVideoCompositionInstruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: aVideoAssetTrack.timeRange.duration)
let mutableVideoComposition: AVMutableVideoComposition = AVMutableVideoComposition()
mutableVideoComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
mutableVideoComposition.renderSize = aVideoAssetTrack.naturalSize
// playerItem = AVPlayerItem(asset: mixComposition)
// player = AVPlayer(playerItem: playerItem!)
//
//
// AVPlayerVC.player = player
do {
try FileManager.default.removeItem(at: savePathUrl)
} catch {
print(error.localizedDescription)
}
//find your video on this URl
let assetExport: AVAssetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)!
assetExport.outputFileType = AVFileType.mp4
assetExport.outputURL = savePathUrl
assetExport.exportAsynchronously { () -> Void in
switch assetExport.status {
case AVAssetExportSession.Status.completed:
completion()
print("success")
case AVAssetExportSession.Status.failed:
print("failed \(assetExport.error?.localizedDescription ?? "")")
case AVAssetExportSession.Status.cancelled:
print("cancelled \(assetExport.error?.localizedDescription ?? "")")
default:
print("complete")
}
}
}
}
| apache-2.0 | f6137f7460341bb8dd25125ec45b41ae | 45.731778 | 204 | 0.562293 | 5.101528 | false | false | false | false |
noremac/Layout | Playground.playground/Contents.swift | 1 | 1981 | import Layout
import PlaygroundSupport
import SwiftUI
import UIKit
class MyViewController: UIViewController {
let image: UIView = {
let view = UIView()
view.backgroundColor = .red
return view
}()
let badge: UIView = {
let view = UIView()
view.backgroundColor = .green
return view
}()
let titleLabel: UILabel = {
let label = UILabel()
label.text = "Title!"
label.font = .preferredFont(forTextStyle: .headline)
label.numberOfLines = 0
return label
}()
let summaryLabel: UILabel = {
let label = UILabel()
label.text = "Summary!"
label.textColor = .secondaryLabel
label.numberOfLines = 0
return label
}()
let timeLabel: UILabel = {
let label = UILabel()
label.text = "30 minutes"
label.textColor = .secondaryLabel
return label
}()
let playButton: UIButton = {
let view = UIButton(type: .system)
view.setImage(UIImage(systemName: "play"), for: .normal)
return view
}()
override func loadView() {
view = UIStackView.vertical(spacing: 10) {
image
.overlay {
badge.constraints {
AlignEdges([.bottom, .trailing], insets: 8)
Size(width: 20, height: 20)
}
}
.constraints {
AspectRatio(3 / 2)
}
UIStackView.vertical(spacing: 10) {
titleLabel
summaryLabel
.spacingAfter(20)
UIStackView.horizontal {
timeLabel
HorizontalSpacer()
playButton
}
}
.padding(.horizontal, insets: 8)
VerticalSpacer()
}
}
}
PlaygroundPage.current.liveView = MyViewController()
| mit | af174f2225151f8baa73db2fd66c5855 | 24.397436 | 67 | 0.501767 | 5.442308 | false | false | false | false |
kaideyi/KDYSample | KYWebo/KYWebo/Bizs/Home/View/WbProfileView.swift | 1 | 2433 | //
// WbProfileView.swift
// KYWebo
//
// Created by kaideyi on 2017/8/13.
// Copyright © 2017年 mac. All rights reserved.
//
import UIKit
import YYKit
/// 个人资料视图
class WbProfileView: UIView {
// MARK: -
lazy var avatarIamge: UIImageView = {
let avatar = UIImageView()
avatar.contentMode = .scaleAspectFill
return avatar
}()
lazy var nameLabel: YYLabel = {
let name = YYLabel()
name.displaysAsynchronously = true
name.ignoreCommonProperties = true
name.fadeOnAsynchronouslyDisplay = false
name.fadeOnHighlight = false
name.textVerticalAlignment = .center
name.lineBreakMode = .byClipping
return name
}()
lazy var sourceLabel: YYLabel = {
let source = YYLabel()
source.displaysAsynchronously = true
source.ignoreCommonProperties = true
source.fadeOnAsynchronouslyDisplay = false
source.fadeOnHighlight = false
return source
}()
// MARK: - Life Cycle
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews() {
self.addSubview(avatarIamge)
self.addSubview(nameLabel)
sourceLabel.highlightTapAction = { (containerView, text, range, rect) in
// 点击事件处理,代理到控制器中
// ...
}
self.addSubview(sourceLabel)
avatarIamge.snp.makeConstraints { (make) in
make.top.left.equalTo(self).inset(UIEdgeInsetsMake(kCellPadding, kCellPadding, 0, 0))
make.size.equalTo(CGSize(width: kCellAvatorWidth, height: kCellAvatorWidth))
}
nameLabel.snp.makeConstraints { (make) in
make.top.equalTo(avatarIamge.snp.top)
make.left.equalTo(avatarIamge.snp.right).offset(kCellInsetPadding)
make.size.equalTo(CGSize(width: kCellNameWidth, height: 22))
}
sourceLabel.snp.makeConstraints { (make) in
make.top.equalTo(nameLabel.snp.bottom)
make.left.equalTo(avatarIamge.snp.right).offset(kCellInsetPadding)
make.size.equalTo(CGSize(width: kCellNameWidth, height: 18))
}
}
}
| mit | d58d7cba85203aaf17f02c5171e21266 | 27.117647 | 97 | 0.602929 | 4.543726 | false | false | false | false |
malt03/RealmBrowser | RealmBrowser/Classes/RealmPropertiesTableViewController.swift | 1 | 7791 | //
// RealmPropertiesTableViewController.swift
// Pods
//
// Created by Koji Murata on 2016/07/15.
//
//
import UIKit
import RealmSwift
final class RealmPropertiesTableViewController: UITableViewController {
@IBOutlet private var keyboardAccessoryView: UIToolbar!
@IBAction private func endEditing() {
view.endEditing(true)
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
view.endEditing(true)
}
private var changeNotNilProperty: Property?
private var object: Object!
private var showDatePickerSections = Set<Int>()
private var composed = false
private var properties: [Property] {
return object.objectSchema.properties
}
private func propertyAt(_ indexPath: IndexPath) -> Property? {
if indexPath.row != 0 { return nil }
return properties[indexPath.section]
}
func prepare(_ object: Object, composed: Bool) {
self.composed = composed
self.object = object
title = composed ? "Compose \(object.objectSchema.className)" : object.primaryValueText
}
override func viewWillAppear(_ animated: Bool) {
tableView.reloadData()
super.viewWillAppear(animated)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let property = propertyAt(indexPath) else {
tableView.deselectRow(at: indexPath, animated: true)
return
}
switch property.type {
case .double, .float, .int, .string, .bool:
guard let cell = tableView.cellForRow(at: indexPath) as? RealmPropertiesValueTableViewCell else { break }
cell.tap()
case .object:
if let value = object[property.name] as? Object {
let vc = storyboard?.instantiateViewController(withIdentifier: "RealmPropertiesTableViewController") as! RealmPropertiesTableViewController
vc.prepare(value, composed: false)
navigationController?.pushViewController(vc, animated: true)
return
}
case .date:
let dateIndexPath = IndexPath(row: 1, section: (indexPath as NSIndexPath).section)
if showDatePickerSections.contains((indexPath as NSIndexPath).section) {
showDatePickerSections.remove((indexPath as NSIndexPath).section)
tableView.deleteRows(at: [dateIndexPath], with: .fade)
} else {
showDatePickerSections.insert((indexPath as NSIndexPath).section)
tableView.insertRows(at: [dateIndexPath], with: .fade)
}
case .any, .array, .data, .linkingObjects:
break
}
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return try! properties[section].name.snakeCaseString.stringByReplacing("_") { _ in " " }
}
override func numberOfSections(in tableView: UITableView) -> Int {
return properties.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1 + (properties[section].isOptional ? 1 : 0) + (showDatePickerSections.contains(section) ? 1 : 0)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let propertyIndexPath = IndexPath(row: 0, section: (indexPath as NSIndexPath).section)
let property = propertyAt(propertyIndexPath)!
switch (indexPath as NSIndexPath).row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! RealmPropertiesValueTableViewCell
cell.prepare(object, property: property, composed: composed, keyboardAccessoryView: keyboardAccessoryView) { [weak self] (value) in
guard let s = self,
let cellForNil = s.tableView.cellForRow(at: IndexPath(row: 1, section: indexPath.section)) as? RealmPropertiesIsNilTableViewCell ??
s.tableView.cellForRow(at: IndexPath(row: 2, section: indexPath.section)) as? RealmPropertiesIsNilTableViewCell else
{
return
}
cellForNil.updateNil(isNotNil: true)
}
return cell
case 1:
if showDatePickerSections.contains((indexPath as NSIndexPath).section) {
return createDateCell(indexPath, property: property)
}
return createIsNilCell(indexPath, property: property)
case 2:
return createIsNilCell(indexPath, property: property)
default:
return UITableViewCell()
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
private func createIsNilCell(_ indexPath: IndexPath, property: Property) -> RealmPropertiesIsNilTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "isNil", for: indexPath) as! RealmPropertiesIsNilTableViewCell
cell.prepare(object: object, property: property) { [weak self] (isNotNil) in
guard let s = self else { return }
s.updateIsNotNil(isNotNil, property: property, indexPath: IndexPath(row: 0, section: indexPath.section))
}
return cell
}
private func createDateCell(_ indexPath: IndexPath, property: Property) -> DatePickingTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "datePicker", for: indexPath) as! DatePickingTableViewCell
cell.prepare(object: object, property: property) { [weak self] in
guard let s = self else { return }
guard let cellForValue = s.tableView.cellForRow(at: IndexPath(row: 0, section: indexPath.section)) as? RealmPropertiesValueTableViewCell else { return }
cellForValue.updateValue(s.object, property: property, composed: s.composed, animated: true)
if let cellForNil = s.tableView.cellForRow(at: IndexPath(row: 2, section: indexPath.section)) as? RealmPropertiesIsNilTableViewCell {
cellForNil.updateNil(isNotNil: true)
}
}
return cell
}
private func updateIsNotNil(_ isNotNil: Bool, property: Property, indexPath: IndexPath) {
let value: AnyObject?
if isNotNil {
switch property.type {
case .any: value = "" as AnyObject?
case .array: value = [] as AnyObject?
case .bool: value = false as AnyObject?
case .data: value = Data() as AnyObject?
case .date: value = Date() as AnyObject?
case .double: value = Double(0) as AnyObject?
case .float: value = Float(0) as AnyObject?
case .int: value = Int(0) as AnyObject?
case .string: value = "" as AnyObject?
case .object:
changeNotNilProperty = property
performSegue(withIdentifier: "selectChild", sender: nil)
return
default: return
}
} else {
value = nil
}
try! Realm().write {
object.setValue(value, forKeyPath: property.name)
}
let cell = tableView.cellForRow(at: indexPath) as! RealmPropertiesValueTableViewCell
cell.updateValue(object, property: property, composed: composed, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? RealmObjectsTableViewController,
let property = changeNotNilProperty,
let className = property.objectClassName
{
for schema in try! Realm().schema.objectSchema {
if schema.className == className {
vc.prepare(objectSchema: schema)
vc.selectChild(property: property) { [weak self] (object) in
guard let s = self else { return }
try! Realm().write {
s.object.setValue(object, forKeyPath: property.name)
}
}
}
}
}
}
}
| mit | 7c6724f490e361a8293a7bab4595d599 | 37.955 | 158 | 0.691182 | 4.716102 | false | false | false | false |
abbeycode/Nimble | Tests/NimbleTests/SynchronousTests.swift | 31 | 4892 | import Foundation
import XCTest
import Nimble
final class SynchronousTest: XCTestCase, XCTestCaseProvider {
static var allTests: [(String, (SynchronousTest) -> () throws -> Void)] {
return [
("testFailAlwaysFails", testFailAlwaysFails),
("testUnexpectedErrorsThrownFails", testUnexpectedErrorsThrownFails),
("testToMatchesIfMatcherReturnsTrue", testToMatchesIfMatcherReturnsTrue),
("testToProvidesActualValueExpression", testToProvidesActualValueExpression),
("testToProvidesAMemoizedActualValueExpression", testToProvidesActualValueExpression),
("testToProvidesAMemoizedActualValueExpressionIsEvaluatedAtMatcherControl", testToProvidesAMemoizedActualValueExpressionIsEvaluatedAtMatcherControl),
("testToMatchAgainstLazyProperties", testToMatchAgainstLazyProperties),
("testToNotMatchesIfMatcherReturnsTrue", testToNotMatchesIfMatcherReturnsTrue),
("testToNotProvidesActualValueExpression", testToNotProvidesActualValueExpression),
("testToNotProvidesAMemoizedActualValueExpression", testToNotProvidesAMemoizedActualValueExpression),
("testToNotProvidesAMemoizedActualValueExpressionIsEvaluatedAtMatcherControl", testToNotProvidesAMemoizedActualValueExpressionIsEvaluatedAtMatcherControl),
("testToNotNegativeMatches", testToNotNegativeMatches),
("testNotToMatchesLikeToNot", testNotToMatchesLikeToNot),
]
}
class Error: Swift.Error {}
let errorToThrow = Error()
private func doThrowError() throws -> Int {
throw errorToThrow
}
func testFailAlwaysFails() {
failsWithErrorMessage("My error message") {
fail("My error message")
}
failsWithErrorMessage("fail() always fails") {
fail()
}
}
func testUnexpectedErrorsThrownFails() {
failsWithErrorMessage("unexpected error thrown: <\(errorToThrow)>") {
expect { try self.doThrowError() }.to(equal(1))
}
failsWithErrorMessage("unexpected error thrown: <\(errorToThrow)>") {
expect { try self.doThrowError() }.toNot(equal(1))
}
}
func testToMatchesIfMatcherReturnsTrue() {
expect(1).to(MatcherFunc { _, _ in true })
expect {1}.to(MatcherFunc { _, _ in true })
}
func testToProvidesActualValueExpression() {
var value: Int?
expect(1).to(MatcherFunc { expr, _ in value = try expr.evaluate(); return true })
expect(value).to(equal(1))
}
func testToProvidesAMemoizedActualValueExpression() {
var callCount = 0
expect { callCount += 1 }.to(MatcherFunc { expr, _ in
_ = try expr.evaluate()
_ = try expr.evaluate()
return true
})
expect(callCount).to(equal(1))
}
func testToProvidesAMemoizedActualValueExpressionIsEvaluatedAtMatcherControl() {
var callCount = 0
expect { callCount += 1 }.to(MatcherFunc { expr, _ in
expect(callCount).to(equal(0))
_ = try expr.evaluate()
return true
})
expect(callCount).to(equal(1))
}
func testToMatchAgainstLazyProperties() {
expect(ObjectWithLazyProperty().value).to(equal("hello"))
expect(ObjectWithLazyProperty().value).toNot(equal("world"))
expect(ObjectWithLazyProperty().anotherValue).to(equal("world"))
expect(ObjectWithLazyProperty().anotherValue).toNot(equal("hello"))
}
// repeated tests from to() for toNot()
func testToNotMatchesIfMatcherReturnsTrue() {
expect(1).toNot(MatcherFunc { _, _ in false })
expect {1}.toNot(MatcherFunc { _, _ in false })
}
func testToNotProvidesActualValueExpression() {
var value: Int?
expect(1).toNot(MatcherFunc { expr, _ in value = try expr.evaluate(); return false })
expect(value).to(equal(1))
}
func testToNotProvidesAMemoizedActualValueExpression() {
var callCount = 0
expect { callCount += 1 }.toNot(MatcherFunc { expr, _ in
_ = try expr.evaluate()
_ = try expr.evaluate()
return false
})
expect(callCount).to(equal(1))
}
func testToNotProvidesAMemoizedActualValueExpressionIsEvaluatedAtMatcherControl() {
var callCount = 0
expect { callCount += 1 }.toNot(MatcherFunc { expr, _ in
expect(callCount).to(equal(0))
_ = try expr.evaluate()
return false
})
expect(callCount).to(equal(1))
}
func testToNotNegativeMatches() {
failsWithErrorMessage("expected to not match, got <1>") {
expect(1).toNot(MatcherFunc { _, _ in true })
}
}
func testNotToMatchesLikeToNot() {
expect(1).notTo(MatcherFunc { _, _ in false })
}
}
| apache-2.0 | a6655181d7887b56aba272a1749eabb3 | 37.21875 | 167 | 0.646157 | 5.681765 | false | true | false | false |
mateuszfidosBLStream/MFCircleDialPad | MFCircleDialPad/MFDialPadItem.swift | 1 | 1330 | //
// DialPadItem.swift
// CircleDialPad
//
// Created by Mateusz Fidos on 23.05.2016.
// Copyright © 2016 mateusz.fidos. All rights reserved.
//
import Foundation
import UIKit
public typealias ItemActionClosure = () -> ()
public protocol MFDialPadItemDelegate : class
{
func didTapItem(item:MFDialPadItem)
}
public protocol MFDialPadItemProtocol
{
init(text:String?, backgroundColor:UIColor?, image:UIImage?, radius:CGFloat)
}
public enum MFDialPadItemState : Int
{
case MFDialPadItemStateDefault = 0, MFDialPadItemStateValid, MFDialPadItemStateInvalid
}
public class MFDialPadItem: MFDialPadItemProtocol
{
let text:String?
let customImage:UIImage?
let radius:CGFloat
var action:ItemActionClosure!
var backgroundColor:UIColor?
var itemTag:Int?
weak var delegate:MFDialPadItemDelegate?
required public init(text:String?, backgroundColor:UIColor?, image:UIImage?, radius:CGFloat)
{
self.text = text
self.backgroundColor = backgroundColor
self.customImage = image
self.radius = radius
self.action = {
self.performAction()
}
}
private func performAction()
{
if ((self.delegate != nil) && (self.itemTag != nil))
{
self.delegate!.didTapItem(self)
}
}
} | mit | 964f21003d2f1223a23fe6b11d4f2f3b | 21.542373 | 96 | 0.674944 | 4.273312 | false | false | false | false |
dreamsxin/swift | test/Frontend/embed-bitcode.swift | 9 | 698 | // REQUIRES: CPU=x86_64
// REQUIRES: rdar23493035
// RUN: %target-swift-frontend -c -module-name someModule -embed-bitcode-marker -o %t.o %s
// RUN: llvm-objdump -macho -section="__LLVM,__bitcode" %t.o | FileCheck -check-prefix=MARKER %s
// RUN: llvm-objdump -macho -section="__LLVM,__swift_cmdline" %t.o | FileCheck -check-prefix=MARKER-CMD %s
// This file tests Mach-O file output, but Linux variants do not produce Mach-O
// files.
// UNSUPPORTED: OS=linux-gnu
// UNSUPPORTED: OS=linux-gnueabihf
// UNSUPPORTED: OS=freebsd
// MARKER: Contents of (__LLVM,__bitcode) section
// MARKER-NEXT: 00
// MARKER-CMD: Contents of (__LLVM,__swift_cmdline) section
// MARKER-CMD-NEXT: 00
func test() {
}
| apache-2.0 | 1dcc112e9376b117b9a722831ae082c6 | 35.736842 | 106 | 0.696275 | 3.07489 | false | true | false | false |
dreamsxin/swift | test/Interpreter/SDK/Reflection_KVO.swift | 4 | 1097 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// rdar://problem/19060227
import Foundation
class ObservedValue: NSObject {
dynamic var amount = 0
}
class ValueObserver: NSObject {
private var observeContext = 0
let observedValue: ObservedValue
init(value: ObservedValue) {
observedValue = value
super.init()
observedValue.addObserver(self, forKeyPath: "amount", options: .new, context: &observeContext)
}
deinit {
observedValue.removeObserver(self, forKeyPath: "amount")
}
override func observeValue(forKeyPath keyPath: String?, of object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>?) {
if context == &observeContext {
if let change_ = change {
if let amount = change_[NSKeyValueChangeNewKey as String] as? Int {
print("Observed value updated to \(amount)")
}
}
}
}
}
let value = ObservedValue()
value.amount = 42
let observer = ValueObserver(value: value)
// CHECK: updated to 43
value.amount += 1
// CHECK: amount: 43
dump(value)
| apache-2.0 | 171be62c8b95e5a2aa2c12ac06e3e83d | 22.340426 | 150 | 0.700091 | 3.903915 | false | false | false | false |
PJayRushton/TeacherTools | TeacherTools/ThemeCollectionViewCell.swift | 1 | 1568 | //
// ThemeCollectionViewCell.swift
// TeacherTools
//
// Created by Parker Rushton on 12/3/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import UIKit
class ThemeCollectionViewCell: UICollectionViewCell, AutoReuseIdentifiable {
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var topImageView: UIImageView!
@IBOutlet weak var topLabel: UILabel!
@IBOutlet weak var firstNameLabel: UILabel!
@IBOutlet var otherLabels: [UILabel]!
@IBOutlet weak var grayView: UIView!
@IBOutlet weak var lockImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
mainView.layer.cornerRadius = 5
}
func update(with theme: Theme, isLocked: Bool = true, isSelected: Bool) {
mainView.layer.borderColor = isSelected ? UIColor.appleBlue.cgColor : UIColor.darkGray.cgColor
mainView.layer.borderWidth = isSelected ? 4 : 1
mainImageView.image = theme.mainImage.image
topImageView.image = theme.borderImage.image
topLabel.text = theme.name
firstNameLabel.backgroundColor = theme.tintColor
firstNameLabel.font = theme.font(withSize: 13)
for label in otherLabels {
label.textColor = theme.textColor
label.font = theme.font(withSize: 11)
}
topLabel.font = theme.font(withSize: 15)
grayView.backgroundColor = isLocked ? UIColor.darkGray.withAlphaComponent(0.6) : UIColor.clear
lockImageView.isHidden = !isLocked
}
}
| mit | c47826aaf050dd2214e34c08dc9719aa | 34.613636 | 102 | 0.69113 | 4.677612 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/ClientTests/Wallpaper/WallpaperURLProviderTests.swift | 2 | 1516 | // 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 XCTest
@testable import Client
class WallpaperURLProviderTests: XCTestCase {
let testURL = WallpaperURLProvider.testURL
func testMetadataURL() {
let subject = WallpaperURLProvider()
let expectedURL = URL(string: "\(testURL)/metadata/\(subject.currentMetadataEndpoint)/wallpapers.json")
do {
let actualURL = try subject.url(for: .metadata)
XCTAssertEqual(actualURL,
expectedURL,
"The metadata url builder is returning the wrong url.")
} catch {
XCTFail("The url provider failed to provide any url: \(error.localizedDescription)")
}
}
func testPathURL() {
let subject = WallpaperURLProvider()
let path = "path/to"
let image = "imageName"
let expectedURL = URL(string: "\(testURL)/ios/\(path)/\(image).jpg")
do {
let actualURL = try subject.url(for: .image(named: image, withFolderName: path))
XCTAssertEqual(actualURL,
expectedURL,
"The image url builder is returning the wrong url.")
} catch {
XCTFail("The url provider failed to provide any url: \(error.localizedDescription)")
}
}
}
| mpl-2.0 | 55c2db11b703219215f29104773242b6 | 32.688889 | 111 | 0.604881 | 4.874598 | false | true | false | false |
luowei/Swift-Samples | LWPickerLabel/AreaPicker/LWPickerLabel.swift | 1 | 8383 | //
// LWPickerLabel.swift
// LWPickerLabel
//
// Created by luowei on 16/8/5.
// Copyright © 2016年 wodedata. All rights reserved.
//
import UIKit
class LWPickerLabel: UILabel {
lazy var _inputView: LWAreaPickerView? = {
guard let inputV = LWAreaPickerView.loadFromNibNamed("LWAreaPickerView") as? LWAreaPickerView as LWAreaPickerView? else{return nil}
inputV.responder = self
return inputV
}()
// MARK: - Override
override var inputView: UIView? {
get { return _inputView }
// set {
// guard let v = newValue as? LWAreaPickerView as LWAreaPickerView? else{ return }
// _inputView = v
// }
}
override func awakeFromNib() {
self.userInteractionEnabled = true
let gesture = UITapGestureRecognizer(target: self, action: #selector(LWPickerLabel.tapSelf(_:)))
gesture.numberOfTapsRequired = 1
self.addGestureRecognizer(gesture)
}
override func canBecomeFirstResponder() -> Bool {
return self.enabled
}
override func resignFirstResponder() -> Bool {
return super.resignFirstResponder()
}
func tapSelf(sender: AnyObject) {
self.becomeFirstResponder()
}
}
class LWAreaPickerView: UIView {
// @IBOutlet weak var dataSource: UIPickerViewDataSource?
// @IBOutlet weak var delegate: UIPickerViewDelegate?
@IBOutlet weak var topNavView: UIView!
@IBOutlet weak var pickView: UIPickerView!
weak var responder: UIResponder?
var addressService: LWAddressService?
var provinceData:[LWAddress]?
var cityData:[LWAddress]?
var areaData:[LWAddress]?
var townData:[LWAddress]?
var selProvinceRow:Int = 0
var selCityRow:Int = 0
var selAreaRow:Int = 0
var selTownRow:Int = 0
override func awakeFromNib() {
super.awakeFromNib()
guard let service = try? LWAddressService.open() as LWAddressService? else{ return }
addressService = service
}
@IBAction func close(){
responder?.resignFirstResponder()
}
}
//MARK: - UIPickerViewDataSource 实现
extension LWAreaPickerView: UIPickerViewDataSource{
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 4
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var count = 0
switch component {
case 0:
provinceData = addressService?.provinceList()
if let provinces = provinceData {
count = provinces.count
}
print("province:\(provinceData?.count)")
case 1:
guard let provinceRow = selProvinceRow as Int? else{break}
//let provinceRow = self.pickView.selectedRowInComponent(component - 1)
guard let provinces = provinceData where provinces.count > 0 else{break}
guard let provinceId = provinces[provinceRow].ownId as String? else{break}
cityData = addressService?.cityList(provinceId)
if let cities = cityData {
count = cities.count
}
case 2:
guard let cityRow = selCityRow as Int? else{break}
//let cityRow = self.pickView.selectedRowInComponent(component - 1)
guard let cities = cityData where cities.count > 0 else{break}
guard let cityId = cities[cityRow].ownId as String? else{break}
areaData = addressService?.areaList(cityId)
if let areas = areaData {
count = areas.count
}
case 3:
guard let areaRow = selAreaRow as Int? else{break}
//let areaRow = self.pickView.selectedRowInComponent(component - 1)
print("========areaRow:\(areaRow) areaData:\(areaData)")
guard let areas = areaData where areas.count > 0 else{break}
guard let areaId = areas[areaRow].ownId as String? else{break}
townData = addressService?.townList(areaId)
if let towns = townData {
count = towns.count
}
print("town:\(townData?.count)")
default:break
}
return count
}
}
//MARK: - UIPickerViewDelegate 实现
extension LWAreaPickerView: UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return self.bounds.width / 4
}
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 30
}
// func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
// guard let data = pickerData as [LWAddress]? else{ return nil}
//
// return data[row].name
// }
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//self.delegate?.pickerLabel(self, didSelectRow: row, inComponent: component)
}
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
let rowView: UIView
if let view = view {
rowView = view
}else{
guard let rowV = LWPickerRow.loadFromNibNamed("LWPickerRow") as? LWPickerRow as LWPickerRow? else{return UIView()}
switch component {
case 0:
provinceData = addressService?.provinceList()
if let provinces = provinceData where provinces.count > 0 {
//rowV.backgroundColor = UIColor.lightGrayColor()
rowV.textLabel.text = provinces[row].name
rowV.textLabel.preferredMaxLayoutWidth = CGRectGetWidth(rowV.textLabel.frame)
}else{
return UIView()
}
case 1:
let provinceRow = self.pickView.selectedRowInComponent(component - 1)
guard let provinces = provinceData where provinces.count > 0 else{return UIView()}
guard let provinceId = provinces[provinceRow].ownId as String? else{return UIView()}
cityData = addressService?.cityList(provinceId)
if let cities = cityData where cities.count > 0 {
//rowV.backgroundColor = UIColor.brownColor()
rowV.textLabel.text = cities[row].name
rowV.textLabel.preferredMaxLayoutWidth = CGRectGetWidth(rowV.textLabel.frame)
}else{
return UIView()
}
case 2:
let cityRow = self.pickView.selectedRowInComponent(component - 1)
guard let cities = cityData where cities.count > 0 else{return UIView()}
guard let cityId = cities[cityRow].ownId as String? else{return UIView()}
areaData = addressService?.areaList(cityId)
if let areas = areaData where areas.count > 0 {
//rowV.backgroundColor = UIColor.greenColor()
rowV.textLabel.text = areas[row].name
rowV.textLabel.preferredMaxLayoutWidth = CGRectGetWidth(rowV.textLabel.frame)
}else{
return UIView()
}
case 3:
let areaRow = self.pickView.selectedRowInComponent(component - 1)
guard let areas = areaData where areas.count > 0 else{return UIView()}
guard let areaId = areas[areaRow].ownId as String? else{return UIView()}
townData = addressService?.townList(areaId)
if let towns = townData where towns.count > 0 {
//rowV.backgroundColor = UIColor.blueColor()
rowV.textLabel.text = towns[row].name
rowV.textLabel.preferredMaxLayoutWidth = CGRectGetWidth(rowV.textLabel.frame)
}else{
return UIView()
}
default:break
}
rowView = rowV
}
return rowView
}
}
//MARK: LWPickerRow 实现
class LWPickerRow: UIView {
@IBOutlet weak var textLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
} | apache-2.0 | fdfadda7b2712fa603a5a12e212de812 | 35.386957 | 139 | 0.59859 | 5.152709 | false | false | false | false |
acalvomartinez/RandomUser | RandomUser/Location.swift | 1 | 601 | //
// Location.swift
// RandomUser
//
// Created by Antonio Calvo on 28/06/2017.
// Copyright © 2017 Random User Inc. All rights reserved.
//
import Foundation
struct Location {
let street: String
let city: String
let state: String
}
extension Location: JSONDecodable {
init?(dictionary: JSONDictionary) {
guard
let street = dictionary["street"] as? String,
let city = dictionary["city"] as? String,
let state = dictionary["state"] as? String
else {
return nil
}
self.street = street
self.city = city
self.state = state
}
}
| apache-2.0 | 4e1b11362d7e232b3d72c5d489764757 | 18.354839 | 58 | 0.633333 | 3.921569 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015 | 03-Single View App/Swift 1/BMI-Challenge 3.1 Solution/BMI/ViewController.swift | 4 | 4310 | //
// ViewController.swift
// BMI
//
// Created by Nicholas Outram on 30/12/2014.
// Copyright (c) 2014 Plymouth University. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
let listOfWeightsInKg = Array(80...240).map( { Double($0) * 0.5 } )
let listOfHeightsInM = Array(140...220).map( { Double($0) * 0.01 } )
var weight : Double?
var height : Double?
var bmi : Double? {
get {
if (weight != nil) && (height != nil) {
return weight! / (height! * height!)
} else {
return nil
}
}
}
@IBOutlet weak var bmiLabel: UILabel!
@IBOutlet weak var heightTextField: UITextField!
@IBOutlet weak var weightTextField: UITextField!
@IBOutlet weak var heightPickerView: UIPickerView!
@IBOutlet weak var weightPickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
updateUI()
return true
}
func updateUI() {
if let val = self.bmi {
self.bmiLabel.text = String(format: "%4.1f", val)
} else {
self.bmiLabel.text = "----"
}
}
// func textFieldDidEndEditing(textField: UITextField) {
//
// let conv = { NSNumberFormatter().numberFromString($0)?.doubleValue }
//
// switch (textField) {
//
// case self.weightTextField:
// self.weight = conv(textField.text)
//
// case self.heightTextField:
// self.height = conv(textField.text)
//
// default:
// println("Error");
//
// }
//
// updateUI()
//
// }
// SOLUTION TO CHALLENGE
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let conv = { NSNumberFormatter().numberFromString($0)?.doubleValue }
var newString = NSMutableString(string: textField.text)
newString.replaceCharactersInRange(range, withString: string)
switch (textField) {
case self.weightTextField:
self.weight = conv(newString)
case self.heightTextField:
self.height = conv(newString)
default:
break
}
updateUI()
return true
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch (pickerView) {
case self.heightPickerView:
return listOfHeightsInM.count
case self.weightPickerView:
return listOfWeightsInKg.count
default:
return 0
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
switch (pickerView) {
case self.heightPickerView:
return String(format: "%4.2f", listOfHeightsInM[row])
case self.weightPickerView:
return String(format: "%4.1f", listOfWeightsInKg[row])
default:
return ""
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch (pickerView) {
case self.heightPickerView:
let h : Double = self.listOfHeightsInM[row]
self.height = h
case self.weightPickerView:
let w : Double = self.listOfWeightsInKg[row]
self.weight = w
default:
println("Error");
}
updateUI()
}
}
| mit | 9f2cb6f86ed371d527aeecbcd5379432 | 26.806452 | 132 | 0.555916 | 4.942661 | false | false | false | false |
StachkaConf/ios-app | StachkaIOS/StachkaIOS/Classes/User Stories/Talks/Feed/View/FeedViewController.swift | 1 | 3786 | //
// FeedViewController.swift
// StachkaIOS
//
// Created by m.rakhmanov on 26.03.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
import RxDataSources
class FeedViewController: UIViewController {
typealias FeedDataSource = RxCustomTableViewDelegateDataSource<PresentationSectionModel>
enum Constants {
static let title = "Расписание"
static let filterButtonTitle = "Фильтры"
}
fileprivate var indexPublisher: PublishSubject<IndexPath> = PublishSubject()
fileprivate var indexSelecter: PublishSubject<IndexPath> = PublishSubject()
fileprivate var filterSelecter: PublishSubject<Void> = PublishSubject()
var viewModel: FeedViewModel?
private let disposeBag = DisposeBag()
private let dataSource = FeedDataSource()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = Constants.title
setupTabBar()
setupNavigationBar()
setupTableView()
setupBindings()
}
private func setupTableView() {
tableView.register(PresentationCell.self)
dataSource.configureCell = { (dataSource: TableViewSectionedDataSource<PresentationSectionModel>,
tableView: UITableView,
indexPath: IndexPath,
item: PresentationCellViewModel) in
let cell = tableView.dequeueCell(item.associatedCell)
cell.configure(with: item)
return cell as! UITableViewCell
}
dataSource.configureCellHeight = { item, tableView, _ in
if let heightCell = item.associatedCell as? ConfigurableStaticHeightCell.Type {
return heightCell.cellHeight
}
return 0
}
dataSource.titleForHeaderInSection = { (dataSource: TableViewSectionedDataSource<PresentationSectionModel>,
index: Int) in
let sectionModel = dataSource[index]
return sectionModel.timeString
}
}
private func setupTabBar() {
tabBarItem = UITabBarItem(title: Constants.title, image: UIImage.TabBar.calendar, selectedImage: UIImage.TabBar.calendar)
}
private func setupNavigationBar() {
let barButtonItem = UIBarButtonItem(title: Constants.filterButtonTitle, style: .plain, target: nil, action: nil)
navigationItem.rightBarButtonItem = barButtonItem
}
private func setupBindings() {
navigationItem.rightBarButtonItem?.rx
.tap
.bindTo(self.filterSelecter)
.disposed(by: disposeBag)
tableView.rx
.willDisplayCell
.map { $0.indexPath }
.bindTo(self.indexPublisher)
.disposed(by: disposeBag)
tableView.rx
.itemSelected
.bindTo(self.indexSelecter)
.disposed(by: disposeBag)
viewModel?
.presentations
.bindTo(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableView.rx
.setDelegate(dataSource)
.disposed(by: disposeBag)
}
}
extension FeedViewController: ModuleOutputProvider {
var moduleOutput: ModuleOutput? {
return viewModel as? ModuleOutput
}
}
extension FeedViewController: FeedView {
var indexSelected: Observable<IndexPath> {
return indexSelecter.asObservable()
}
var indexDisplayed: Observable<IndexPath> {
return indexPublisher.asObservable()
}
var filterSelected: Observable<Void> {
return filterSelecter.asObservable()
}
}
| mit | f73e50561701b99e40cf8527cb65f649 | 29.885246 | 129 | 0.637473 | 5.53304 | false | false | false | false |
LYM-mg/DemoTest | 其他功能/SwiftyDemo/SwiftyDemo/Extesion/Category(扩展)/UIColor+Extension.swift | 3 | 4828 | //
// UIColor+Extension.swift
// chart2
//
// Created by i-Techsys.com on 16/11/23.
// Copyright © 2016年 i-Techsys. All rights reserved.
/*
1. 关键字static和class的区别:
在方法的func关键字之前加上关键字static或者class都可以用于指定类方法.
不同的是用class关键字指定的类方法可以被子类重写, 如下:
override class func work() {
print("Teacher: University Teacher")
}
但是用static关键字指定的类方法是不能被子类重写的, 根据报错信息: Class method overrides a 'final' class method.
我们可以知道被static指定的类方法包含final关键字的特性--防止被重写.
*/
import UIKit
// MARK: - 自定义颜色和随机颜色
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) {
let r = r/255.0
let g = g/255.0
let b = b/255.0
self.init(red: r, green: g, blue: b, alpha: a)
}
static func randomColor() -> UIColor {
let r = CGFloat(arc4random_uniform(256))
let g = CGFloat(arc4random_uniform(256))
let b = CGFloat(arc4random_uniform(256))
return colorWithCustom(r: r, g: g, b: b)
}
static func colorWithCustom(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
let r = r/255.0
let g = g/255.0
let b = b/255.0
return UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
}
// MARK: - 16进制转UIColor
extension UIColor {
/**
16进制转UIColor
- parameter hex: 16进制颜色字符串
- returns: 转换后的颜色
*/
static func colorHex(hex: String) -> UIColor {
return proceesHex(hex: hex,alpha: 1.0)
}
/**
16进制转UIColor,
- parameter hex: 16进制颜色字符串
- parameter alpha: 透明度
- returns: 转换后的颜色
*/
static func colorHexWithAlpha(hex: String, alpha: CGFloat) -> UIColor {
return proceesHex(hex: hex, alpha: alpha)
}
/** 主要逻辑 */
fileprivate static func proceesHex(hex: String, alpha: CGFloat) -> UIColor{
/** 如果传入的字符串为空 */
if hex.isEmpty {
return UIColor.clear
}
/** 传进来的值。 去掉了可能包含的空格、特殊字符, 并且全部转换为大写 */
let whitespace = NSCharacterSet.whitespacesAndNewlines
var hHex = (hex.trimmingCharacters(in: whitespace)).uppercased()
/** 如果处理过后的字符串少于6位 */
if hHex.characters.count < 6 {
return UIColor.clear
}
/** 开头是用0x开始的 或者 开头是以##开始的 */
if hHex.hasPrefix("0X") || hHex.hasPrefix("##") {
hHex = String(hHex.characters.dropFirst(2))
}
/** 开头是以#开头的 */
if hHex.hasPrefix("#") {
hHex = (hHex as NSString).substring(from: 1)
}
/** 截取出来的有效长度是6位, 所以不是6位的直接返回 */
if hHex.characters.count != 6 {
return UIColor.clear
}
/** R G B */
var range = NSMakeRange(0, 2)
/** R */
let rHex = (hHex as NSString).substring(with: range)
/** G */
range.location = 2
let gHex = (hHex as NSString).substring(with: range)
/** B */
range.location = 4
let bHex = (hHex as NSString).substring(with: range)
/** 类型转换 */
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rHex).scanHexInt32(&r)
Scanner(string: gHex).scanHexInt32(&g)
Scanner(string: bHex).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
}
// convenience init(hex string: String) {
// var hex = string.hasPrefix("#") ? String(string.characters.dropFirst()) : string
//
// guard hex.characters.count == 3 || hex.characters.count == 6
// else {
// self.init(white: 1.0, alpha: 0.0)
// return
// }
//
// if hex.characters.count == 3 {
// for (index, char) in hex.characters.enumerated() {
// hex.insert(char, at: hex.index(hex.startIndex, offsetBy: index * 2))
// }
// }
//
// self.init(
// red: CGFloat((Int(hex, radix: 16)! >> 16) & 0xFF) / 255.0,
// green: CGFloat((Int(hex, radix: 16)! >> 8) & 0xFF) / 255.0,
// blue: CGFloat((Int(hex, radix: 16)!) & 0xFF) / 255.0, alpha: 1.0)
// }
}
| mit | f62a6dc28f7800dfd1ffbe810414a794 | 28.376712 | 114 | 0.53439 | 3.610269 | false | false | false | false |
tryolabs/TLSphinx | TLSphinx/Decoder.swift | 1 | 8296 | //
// Decoder.swift
// TLSphinx
//
// Created by Bruno Berisso on 5/29/15.
// Copyright (c) 2015 Bruno Berisso. All rights reserved.
//
import Foundation
import AVFoundation
import Sphinx
fileprivate enum SpeechStateEnum : CustomStringConvertible {
case silence
case speech
case utterance
var description: String {
get {
switch(self) {
case .silence:
return "Silence"
case .speech:
return "Speech"
case .utterance:
return "Utterance"
}
}
}
}
fileprivate extension AVAudioPCMBuffer {
func toData() -> Data {
let channels = UnsafeBufferPointer(start: int16ChannelData, count: 1)
let ch0Data = Data(bytes: UnsafeMutablePointer<int16>(channels[0]),
count: Int(frameCapacity * format.streamDescription.pointee.mBytesPerFrame))
return ch0Data
}
}
public enum DecodeErrors : Error {
case CantReadSpeachFile(String)
case CantSetAudioSession(NSError)
case CantStartAudioEngine(NSError)
case CantAddWordsWhileDecodeingSpeech
case CantConvertAudioFormat
}
public final class Decoder {
fileprivate var psDecoder: OpaquePointer?
fileprivate var engine: AVAudioEngine!
fileprivate var speechState: SpeechStateEnum
public init?(config: Config) {
speechState = .silence
psDecoder = config.cmdLnConf.flatMap(ps_init)
if psDecoder == nil {
return nil
}
}
deinit {
let refCount = ps_free(psDecoder)
assert(refCount == 0, "Can't free decoder because it's shared among instances")
}
@discardableResult fileprivate func process_raw(_ data: Data) -> CInt {
let dataLenght = data.count / 2
let numberOfFrames = data.withUnsafeBytes { (bytes : UnsafePointer<Int16>) -> Int32 in
ps_process_raw(psDecoder, bytes, dataLenght, SFalse32, SFalse32)
}
let hasSpeech = in_speech()
switch (speechState) {
case .silence where hasSpeech:
speechState = .speech
case .speech where !hasSpeech:
speechState = .utterance
case .utterance where !hasSpeech:
speechState = .silence
default:
break
}
return numberOfFrames
}
fileprivate func in_speech() -> Bool {
return ps_get_in_speech(psDecoder) == STrue
}
@discardableResult fileprivate func start_utt() -> Bool {
return ps_start_utt(psDecoder) == 0
}
@discardableResult fileprivate func end_utt() -> Bool {
return ps_end_utt(psDecoder) == 0
}
fileprivate func get_hyp() -> Hypothesis? {
var score: int32 = 0
guard let string = ps_get_hyp(psDecoder, &score) else {
return nil
}
if let text = String(validatingUTF8: string) {
return Hypothesis(text: text, score: Int(score))
} else {
return nil
}
}
fileprivate func hypotesisForSpeech (inFile fileHandle: FileHandle) -> Hypothesis? {
start_utt()
let hypothesis = fileHandle.reduceChunks(2048, initial: nil, reducer: {
(data: Data, partialHyp: Hypothesis?) -> Hypothesis? in
process_raw(data)
var resultantHyp = partialHyp
if speechState == .utterance {
end_utt()
resultantHyp = partialHyp + get_hyp()
start_utt()
}
return resultantHyp
})
end_utt()
//Process any pending speech
if speechState == .speech {
return hypothesis + get_hyp()
} else {
return hypothesis
}
}
public func decodeSpeech (atPath filePath: String, complete: @escaping (Hypothesis?) -> ()) throws {
guard let fileHandle = FileHandle(forReadingAtPath: filePath) else {
throw DecodeErrors.CantReadSpeachFile(filePath)
}
DispatchQueue.global().async {
let hypothesis = self.hypotesisForSpeech(inFile:fileHandle)
fileHandle.closeFile()
DispatchQueue.main.async {
complete(hypothesis)
}
}
}
public func startDecodingSpeech (_ utteranceComplete: @escaping (Hypothesis?) -> ()) throws {
do {
if #available(iOS 10.0, *) {
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .voiceChat, options: [])
} else {
try AVAudioSession.sharedInstance().setCategory(.playAndRecord)
}
} catch let error as NSError {
print("Error setting the shared AVAudioSession: \(error)")
throw DecodeErrors.CantSetAudioSession(error)
}
engine = AVAudioEngine()
let input = engine.inputNode
let mixer = AVAudioMixerNode()
engine.attach(mixer)
engine.connect(input, to: mixer, format: input.outputFormat(forBus: 0))
// We forceunwrap this because the docs for AVAudioFormat specify that this constructor return nil when the channels
// are grater than 2.
let formatIn = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16000, channels: 1, interleaved: false)!
let formatOut = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16000, channels: 1, interleaved: false)!
guard let bufferMapper = AVAudioConverter(from: formatIn, to: formatOut) else {
// Returns nil if the format conversion is not possible.
throw DecodeErrors.CantConvertAudioFormat
}
mixer.installTap(onBus: 0, bufferSize: 2048, format: formatIn, block: {
[unowned self] (buffer: AVAudioPCMBuffer!, time: AVAudioTime!) in
guard let sphinxBuffer = AVAudioPCMBuffer(pcmFormat: formatOut, frameCapacity: buffer.frameCapacity) else {
// Returns nil in the following cases:
// - if the format has zero bytes per frame (format.streamDescription->mBytesPerFrame == 0)
// - if the buffer byte capacity (frameCapacity * format.streamDescription->mBytesPerFrame)
// cannot be represented by an uint32_t
print("Can't create PCM buffer")
return
}
// This is needed because the 'frameLenght' default value is 0 (since iOS 10) and cause the 'convert' call
// to faile with an error (Error Domain=NSOSStatusErrorDomain Code=-50 "(null)")
// More here: http://stackoverflow.com/questions/39714244/avaudioconverter-is-broken-in-ios-10
sphinxBuffer.frameLength = sphinxBuffer.frameCapacity
do {
try bufferMapper.convert(to: sphinxBuffer, from: buffer)
} catch(let error as NSError) {
print(error)
return
}
let audioData = sphinxBuffer.toData()
self.process_raw(audioData)
print("Process: \(buffer.frameLength) frames - \(audioData.count) bytes - sample time: \(time.sampleTime)")
if self.speechState == .utterance {
self.end_utt()
let hypothesis = self.get_hyp()
DispatchQueue.main.async {
utteranceComplete(hypothesis)
}
self.start_utt()
}
})
start_utt()
do {
try engine.start()
} catch let error as NSError {
end_utt()
print("Can't start AVAudioEngine: \(error)")
throw DecodeErrors.CantStartAudioEngine(error)
}
}
public func stopDecodingSpeech () {
engine.stop()
engine = nil
}
public func add(words:Array<(word: String, phones: String)>) throws {
guard engine == nil || !engine.isRunning else {
throw DecodeErrors.CantAddWordsWhileDecodeingSpeech
}
for (word,phones) in words {
let update = words.last?.word == word ? STrue32 : SFalse32
ps_add_word(psDecoder, word, phones, update)
}
}
}
| mit | 26c016a3bc22f27a620de21e2c000475 | 30.071161 | 124 | 0.586789 | 4.868545 | false | false | false | false |
LYM-mg/DemoTest | 其他功能/MGBookViews/MGBookViews/可控定时器/TestViewController.swift | 1 | 3012 | //
// TestViewController.swift
// MGBookViews
//
// Created by i-Techsys.com on 2017/8/19.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
class TestViewController: UIViewController {
@IBOutlet weak var timecountDown10: UIButton!
@IBOutlet weak var timecountDown30: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// 10秒的倒计时⏳
@IBAction func countDown(_ sender: UIButton) {
TimeCountDownManager.manager.scheduledCountDownWith("button1", timeInteval: 10, countingDown: { (timeInterval) in
MGLog(timeInterval)
sender.titleLabel?.text = "剩余\(Int(timeInterval))s"
sender.isEnabled = false
}) { (timeInterval) in // 倒计时为0执行操作
sender.isEnabled = true
}
}
// 30秒的倒计时⏳
@IBAction func countDown2(_ sender: UIButton) {
TimeCountDownManager.manager.scheduledCountDownWith("button2", timeInteval: 30, countingDown: { (timeInterval) in
sender.titleLabel?.text = "剩余\(Int(timeInterval))s"
sender.isEnabled = false
}) { (timeInterval) in
sender.isEnabled = true
}
}
// 暂停按钮的点击 (30秒的倒计时⏳)
@IBAction func pauseOne(_ sender: UIButton) {
if TimeCountDownManager.manager.pauseOneTask(key: "button2") {
}else {
MGLog("没有该task")
}
}
// 恢复按钮的点击 (30秒的倒计时⏳)
@IBAction func continueTIme(_ sender: UIButton) {
if TimeCountDownManager.manager.suspendOneTask(key: "button2") {
}else {
MGLog("定时器未启动")
MGLog("没有该task")
}
}
// 停止一个定时器 (30秒的倒计时⏳)
@IBAction func stopOneTask(_ sender: UIButton) {
if TimeCountDownManager.manager.cancelOneTask("button2") {
timecountDown30.titleLabel?.text = "点击倒计时30"
timecountDown30.isEnabled = true
}else {
MGLog("没有找到该定时器")
}
}
// 全部暂停(所有倒计时⏳)
@IBAction func allPause(_ sender: UIButton) {
TimeCountDownManager.manager.pauseAllTask()
}
// 全部停止(所有倒计时⏳)
@IBAction func stopAll(_ sender: AnyObject) {
timecountDown30.titleLabel?.text = "点击倒计时30"
timecountDown30.isEnabled = true
timecountDown10.titleLabel?.text = "点击倒计时10"
timecountDown10.isEnabled = true
TimeCountDownManager.manager.cancelAllTask()
}
// 全部继续(所有倒计时⏳)
@IBAction func allContinue(_ sender: UIButton) {
TimeCountDownManager.manager.suspendAllTask()
}
deinit {
print("deinit")
}
}
| mit | 82ad816468a1ff4520f38bfb47a5e942 | 27.427083 | 121 | 0.60022 | 4.423015 | false | false | false | false |
HarrisLee/Utils | BackgroundAudioMode-master/BackgroundModeDemo/BackgroundModeDemo/HintTool/HintTool.swift | 1 | 3197 | //
// HintTool.swift
// Mara
//
// Created by 周际航 on 2016/11/28.
// Copyright © 2016年 com.maramara. All rights reserved.
//
import UIKit
class HintTool {
private var hintView: UIView?
static let shared = HintTool()
static func hint(_ message: String) {
self.shared.showHintView(hintView: self.hintView(with: message))
}
private func showHintView(hintView: UIView) {
guard let window = UIApplication.shared.delegate?.window else {return}
guard self.hintView == nil else {return}
window!.addSubview(hintView)
window!.bringSubview(toFront: hintView)
self.hintView = hintView
// 消失
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
[weak self] in
UIView.animate(withDuration: 0.5, animations: {
[weak self] in
self?.hintView?.alpha = 0.5
}, completion: { (finished) in
self?.hintView?.removeFromSuperview()
self?.hintView = nil
})
}
}
private static func hintView(with message: String) -> UIView {
let minWidth = 180.0
let maxWidth = 260.0
let padding = 10.0
let font = UIFont.systemFont(ofSize: 14)
let messageSize = message.ext_size(withBoundingSize: CGSize(width: maxWidth-2*padding, height: 0) , font: font)
let labelFrame = CGRect(x: 0, y: 0, width: CGFloat(ceilf(Float(messageSize.width))), height: CGFloat(ceilf(Float(messageSize.height))))
let viewFrame = CGRect(x: 0, y: 0, width: max(minWidth, Double(messageSize.width) + padding*2), height: Double(messageSize.height) + padding*2)
let hintView = UIView()
hintView.isUserInteractionEnabled = false
hintView.backgroundColor = UIColor(white: 0, alpha: 0.7)
hintView.layer.cornerRadius = 8
hintView.layer.masksToBounds = true
hintView.frame = viewFrame
hintView.center = CGPoint(x: CGFloat(ceilf(Float(UIScreen.main.bounds.size.width*0.5))), y: CGFloat(ceilf(Float(UIScreen.main.bounds.size.height-100.0))))
let hintLabel = UILabel()
hintView.addSubview(hintLabel)
hintView.isUserInteractionEnabled = false
hintLabel.text = message
hintLabel.textColor = UIColor.white
hintLabel.textAlignment = .center
hintLabel.font = font
hintLabel.preferredMaxLayoutWidth = messageSize.width
hintLabel.numberOfLines = 0
hintLabel.frame = labelFrame
hintLabel.center = CGPoint(x: CGFloat(ceilf(Float(hintView.bounds.size.width*0.5))), y: CGFloat(ceilf(Float(hintView.bounds.size.height*0.5))))
return hintView
}
}
extension String {
func ext_size(withBoundingSize boundingSize: CGSize, font: UIFont) -> CGSize {
let option = NSStringDrawingOptions.usesLineFragmentOrigin
let attributes = [NSFontAttributeName : font]
let contentSize = self.boundingRect(with: boundingSize, options: option, attributes: attributes, context: nil).size
return contentSize
}
}
| mit | fd3f53a7fa0061c35b80824e970c30ac | 35.597701 | 162 | 0.630025 | 4.516312 | false | false | false | false |
cliffpanos/True-Pass-iOS | iOSApp/CheckInWatchKitApp Extension/Primary Controllers/InterfaceController.swift | 1 | 3892 | //
// InterfaceController.swift
// TruePassWatchKitApp Extensionn
//
// Created by Cliff Panos on 4/15/17.
// Copyright © 2017 Clifford Panos. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: ManagedInterfaceController {
@IBOutlet var interfaceTable: WKInterfaceTable!
@IBOutlet var noPassesLabel: WKInterfaceLabel!
static var staticTable: WKInterfaceTable?
static var staticNoPassesLabel: WKInterfaceLabel?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
WC.initialViewController = self
InterfaceController.staticTable = interfaceTable
InterfaceController.staticNoPassesLabel = noPassesLabel
self.addMenuItem(with: .resume, title: "Refresh", action: #selector(refreshAllPasses))
}
static func updatetable() {
guard let table = InterfaceController.staticTable else { return }
print("Actually updating table")
table.setNumberOfRows(WC.passes.count, withRowType: "passCell")
for index in 0..<WC.passes.count {
let cell = table.rowController(at: index) as! PassCell
cell.decorate(for: WC.passes[index])
}
staticNoPassesLabel?.setHidden(table.numberOfRows > 0)
}
//By default will add the item to the bottom of the table
static func addTableItem(atIndex index: Int = staticTable?.numberOfRows ?? 0) {
guard let table = InterfaceController.staticTable else { return }
let indexSet = IndexSet(integer: index)
table.insertRows(at: indexSet, withRowType: "passCell")
let cell = table.rowController(at: index) as! PassCell
cell.decorate(for: WC.passes[index])
staticNoPassesLabel?.setHidden(table.numberOfRows > 0)
}
static func removeTableItem(atIndex index: Int) {
guard let table = InterfaceController.staticTable else { return }
let indexSet = IndexSet(integer: index)
if table.rowController(at: index) != nil {
table.removeRows(at: indexSet)
} //else the index is not valid
staticNoPassesLabel?.setHidden(table.numberOfRows > 0)
}
@objc func refreshAllPasses() {
WC.passes = [] //Necessary?
WC.requestPassesFromiOS()
}
override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
self.presentController(withName: "passDetailController", context: WC.passes[rowIndex])
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
if WC.passes.count == 0 {
print("Interface Controller awake is requesting passes")
noPassesLabel.setHidden(false)
WC.requestPassesFromiOS() //Begins the recursive pass request calls
} else {
noPassesLabel.setHidden(true)
}
}
}
//Mark: - Handle Notifications
extension InterfaceController {
//override func handleAction
}
class PassCell: NSObject {
@IBOutlet var imageView: WKInterfaceImage!
@IBOutlet var guestName: WKInterfaceLabel!
func decorate(for pass: Pass) {
if let imageData = pass.image {
let image = UIImage(data: imageData)
self.imageView.setImage(image)
} else {
self.imageView.setImage(#imageLiteral(resourceName: "ModernContactEmpty"))
}
let components = pass.name.components(separatedBy: " ")
if components.count > 1 && !components[1].isEmptyOrWhitespace() {
guestName.setText("\(components[0]) \(components[1][0]).")
} else {
guestName.setText(pass.name)
}
}
}
| apache-2.0 | 210c1c82c34c842f6038413e82e40e87 | 29.637795 | 94 | 0.636854 | 4.975703 | false | false | false | false |
alexey-kubas-appus/Circular-PickerView | demo/CircularPickerViewSwift/ViewController.swift | 1 | 1261 | //
// ViewController.swift
// CircularPickerViewSwift
//
// Created by Sergey Sokoltsov on 12/14/16.
// Copyright © 2016 Sergey Sokoltsov. All rights reserved.
//
import UIKit
import Foundation
import AppusCircularPickerView
class ViewController: UIViewController {
@IBOutlet weak var circularPicker : AppusCircularPickerView?
@IBOutlet weak var valueLabel : UILabel?
@IBOutlet weak var lineWidthStepper : UIStepper?
@IBOutlet weak var lineWidthLabel : UILabel?
override func viewDidLoad() {
super.viewDidLoad()
valueLabel?.text = String(format:"%.2f", circularPicker!.currentValue)
lineWidthLabel?.text = String(format:"%i", NSInteger(circularPicker!.lineWidth))
lineWidthStepper?.value = Double(circularPicker!.lineWidth)
}
@IBAction func switchChanged(sender: UISwitch) {
circularPicker?.autocomplete = sender.isOn
}
@IBAction func circularPickerValueChanged(_ sender: AppusCircularPickerView) {
valueLabel?.text = String(format:"%.2f", sender.currentValue)
}
@IBAction func lineWidthChanged(sender: UIStepper) {
lineWidthLabel?.text = String(format:"%i", NSInteger(sender.value))
circularPicker?.lineWidth = Float(sender.value)
}
}
| apache-2.0 | 9fbee2fe350a3157e43c7fa88060f96c | 30.5 | 88 | 0.711905 | 4.581818 | false | false | false | false |
robocopklaus/sportskanone | Sportskanone/ViewModels/SignUpViewModel.swift | 1 | 1504 | //
// SignUpViewModel.swift
// Sportskanone
//
// Created by Fabian Pahl on 25/03/2017.
// Copyright © 2017 21st digital GmbH. All rights reserved.
//
import ReactiveSwift
import ReactiveCocoa
import Result
final class SignUpViewModel<Store: StoreType> {
// Inputs
let username = MutableProperty<String>("")
// Outputs
let greeting = Property(value: "SignUp.IntroLabel.Text".localized)
let usernamePlaceholder = Property(value: "SignUp.Username.Placeholder".localized)
let text = Property(value: "SignUp.Intro.Text".localized)
let signUpButtonTitle = Property(value: "SignUp.Button.Submit.Title".localized.uppercased())
let logoName = "Logo"
let validatedUsername: Property<String>
let isUsernameValid: Property<Bool>
// Actions
lazy var signUpAction: Action<Void, Void, AnyError> = {
return Action(enabledIf: self.isUsernameValid, { [unowned self] _ in
return self.store.signUpUser(withName: self.validatedUsername.value)
})
}()
fileprivate let store: Store
init(store: Store) {
self.store = store
let validation = username.signal
.map { $0.trimmingCharacters(in: CharacterSet.letters.inverted) }
.map { $0.characters.count < 9 ? $0 : $0.substring(to: $0.index($0.startIndex, offsetBy: 9)) }
validatedUsername = Property(initial: "", then:validation)
isUsernameValid = Property(initial: false, then: validatedUsername.signal.map { $0.characters.count > 2 })
}
}
| mit | 3f04f45abd5c2b0e9c405be9bae25328 | 30.978723 | 116 | 0.689953 | 4.062162 | false | false | false | false |
geasscode/TodoList | ToDoListApp/ToDoListApp/controllers/SideBarTableViewController.swift | 1 | 4998 | //
// SideBarTableViewController.swift
// ToDoListApp
//
// Created by desmond on 12/8/14.
// Copyright (c) 2014 Phoenix. All rights reserved.
//
import UIKit
class SideBarTableViewController: UITableViewController {
let testData = ["First","Second","third","Fourth","Fiveth"]
var selectedMenuItem : Int = 0
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()
// Customize apperance of table view
tableView.contentInset = UIEdgeInsetsMake(64.0, 0, 0, 0) //
tableView.separatorStyle = .None
tableView.backgroundColor = UIColor.clearColor()
tableView.scrollsToTop = false
// Preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
// tableView.selectRowAtIndexPath(NSIndexPath(forRow: selectedMenuItem, inSection: 0), animated: false, scrollPosition: .Middle)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 52
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// let row = indexPath.row
// println("current Row is \(row)")
NSNotificationCenter.defaultCenter().postNotificationName("sideBarDateSort", object: indexPath)
}
/*
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return testData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CELL")
cell!.backgroundColor = UIColor.clearColor()
cell!.textLabel.textColor = UIColor.darkGrayColor()
let selectedBackgroundView = UIView(frame: CGRectMake(0, 0, cell!.frame.size.width, cell!.frame.size.height))
selectedBackgroundView.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.2)
cell!.selectedBackgroundView = selectedBackgroundView
}
cell!.textLabel.text = testData[indexPath.row]
return cell!
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO 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 NO 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 | 6d437c5e6912a715977c76af1cb71477 | 34.956835 | 157 | 0.672669 | 5.641084 | false | false | false | false |
lfaoro/Cast | Carthage/Checkouts/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift | 1 | 6567 | //
// SerialQueueScheduler.swift
// Rx
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// This is a scheduler that wraps dispatch queue.
// It can wrap both serial and concurrent dispatch queues.
//
// It is extemely important that this scheduler is serial, because
// certain operator perform optimizations that rely on that property.
//
// Because there is no way of detecting is passed dispatch queue serial or
// concurrent, for every queue that is being passed, worst case (concurrent)
// will be assumed, and internal serial proxy dispatch queue will be created.
//
// This scheduler can also be used with internal serial queue alone.
// In case some customization need to be made on it before usage,
// internal serial queue can be customized using `serialQueueConfiguration`
// callback.
//
public class SerialDispatchQueueScheduler: Scheduler, PeriodicScheduler {
public typealias TimeInterval = NSTimeInterval
public typealias Time = NSDate
private let serialQueue : dispatch_queue_t
public var now : NSDate {
get {
return NSDate()
}
}
// leeway for scheduling timers
var leeway: Int64 = 0
init(serialQueue: dispatch_queue_t) {
self.serialQueue = serialQueue
}
// Creates new serial queue named `name` for internal scheduler usage
public convenience init(internalSerialQueueName: String) {
self.init(internalSerialQueueName: internalSerialQueueName, serialQueueConfiguration: { _ -> Void in })
}
// Creates new serial queue named `name` for internal scheduler usage
public convenience init(internalSerialQueueName: String, serialQueueConfiguration: (dispatch_queue_t) -> Void) {
let queue = dispatch_queue_create(internalSerialQueueName, DISPATCH_QUEUE_SERIAL)
serialQueueConfiguration(queue)
self.init(serialQueue: queue)
}
public convenience init(queue: dispatch_queue_t, internalSerialQueueName: String) {
let serialQueue = dispatch_queue_create(internalSerialQueueName, DISPATCH_QUEUE_SERIAL)
dispatch_set_target_queue(serialQueue, queue)
self.init(serialQueue: serialQueue)
}
// Convenience init for scheduler that wraps one of the global concurrent dispatch queues.
//
// DISPATCH_QUEUE_PRIORITY_DEFAULT
// DISPATCH_QUEUE_PRIORITY_HIGH
// DISPATCH_QUEUE_PRIORITY_LOW
public convenience init(globalConcurrentQueuePriority: DispatchQueueSchedulerPriority) {
self.init(globalConcurrentQueuePriority: globalConcurrentQueuePriority, internalSerialQueueName: "rx.global_dispatch_queue.serial.\(globalConcurrentQueuePriority)")
}
public convenience init(globalConcurrentQueuePriority: DispatchQueueSchedulerPriority, internalSerialQueueName: String) {
var priority: Int = 0
switch globalConcurrentQueuePriority {
case .High:
priority = DISPATCH_QUEUE_PRIORITY_HIGH
case .Default:
priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
case .Low:
priority = DISPATCH_QUEUE_PRIORITY_LOW
}
self.init(queue: dispatch_get_global_queue(priority, UInt(0)), internalSerialQueueName: internalSerialQueueName)
}
class func convertTimeIntervalToDispatchInterval(timeInterval: NSTimeInterval) -> Int64 {
return Int64(timeInterval * Double(NSEC_PER_SEC))
}
class func convertTimeIntervalToDispatchTime(timeInterval: NSTimeInterval) -> dispatch_time_t {
return dispatch_time(DISPATCH_TIME_NOW, convertTimeIntervalToDispatchInterval(timeInterval))
}
public final func schedule<StateType>(state: StateType, action: (/*ImmediateScheduler,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> {
return self.scheduleInternal(state, action: action)
}
func scheduleInternal<StateType>(state: StateType, action: (/*ImmediateScheduler,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> {
let cancel = SingleAssignmentDisposable()
dispatch_async(self.serialQueue) {
if cancel.disposed {
return
}
_ = ensureScheduledSuccessfully(action(/*self,*/ state).map { disposable in
cancel.disposable = disposable
})
}
return success(cancel)
}
public final func scheduleRelative<StateType>(state: StateType, dueTime: NSTimeInterval, action: (/*Scheduler<NSTimeInterval, NSDate>,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> {
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.serialQueue)
let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchTime(dueTime)
let compositeDisposable = CompositeDisposable()
dispatch_source_set_timer(timer, dispatchInterval, DISPATCH_TIME_FOREVER, 0)
dispatch_source_set_event_handler(timer, {
if compositeDisposable.disposed {
return
}
ensureScheduledSuccessfully(action(/*self,*/ state).map { disposable in
compositeDisposable.addDisposable(disposable)
})
})
dispatch_resume(timer)
compositeDisposable.addDisposable(AnonymousDisposable {
dispatch_source_cancel(timer)
})
return success(compositeDisposable)
}
public func schedulePeriodic<StateType>(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> RxResult<Disposable> {
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.serialQueue)
let initial = MainScheduler.convertTimeIntervalToDispatchTime(startAfter)
let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchInterval(period)
var timerState = state
let validDispatchInterval = dispatchInterval < 0 ? 0 : UInt64(dispatchInterval)
dispatch_source_set_timer(timer, initial, validDispatchInterval, 0)
let cancel = AnonymousDisposable {
dispatch_source_cancel(timer)
}
dispatch_source_set_event_handler(timer, {
if cancel.disposed {
return
}
timerState = action(timerState)
})
dispatch_resume(timer)
return success(cancel)
}
} | mit | ceccef8113c096f723dcb48b5a72ce83 | 39.54321 | 202 | 0.680067 | 5.360816 | false | false | false | false |
koscida/Kos_AMAD_Spring2015 | Spring_16/IGNORE_work/projects/kos_project_2/kos_project_2/GameViewController.swift | 1 | 4030 | //
// GameViewController.swift
// kos_project_2
//
// Created by Brittany Kos on 3/30/16.
// Copyright (c) 2016 Brittany Kos. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create a new scene
let scene = SCNScene(named: "art.scnassets/ship.scn")!
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
// create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLightTypeOmni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
scene.rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
ambientLightNode.light!.color = UIColor.darkGrayColor()
scene.rootNode.addChildNode(ambientLightNode)
// retrieve the ship node
let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
// animate the 3d object
ship.runAction(SCNAction.repeatActionForever(SCNAction.rotateByX(0, y: 2, z: 0, duration: 1)))
// retrieve the SCNView
let scnView = self.view as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
scnView.backgroundColor = UIColor.blackColor()
// add a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
scnView.addGestureRecognizer(tapGesture)
}
func handleTap(gestureRecognize: UIGestureRecognizer) {
// retrieve the SCNView
let scnView = self.view as! SCNView
// check what nodes are tapped
let p = gestureRecognize.locationInView(scnView)
let hitResults = scnView.hitTest(p, options: nil)
// check that we clicked on at least one object
if hitResults.count > 0 {
// retrieved the first clicked object
let result: AnyObject! = hitResults[0]
// get its material
let material = result.node!.geometry!.firstMaterial!
// highlight it
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
// on completion - unhighlight
SCNTransaction.setCompletionBlock {
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
material.emission.contents = UIColor.blackColor()
SCNTransaction.commit()
}
material.emission.contents = UIColor.redColor()
SCNTransaction.commit()
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| gpl-3.0 | e3a606fd09b4d7d14fc0a41d68151078 | 31.24 | 102 | 0.5933 | 5.612813 | false | false | false | false |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/NCFittingFleetsViewController.swift | 2 | 3604 | //
// NCFittingFleetsViewController.swift
// Neocom
//
// Created by Artem Shimanski on 27.02.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import EVEAPI
import Futures
class NCFittingFleetsViewController: NCTreeViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.register([Prototype.NCDefaultTableViewCell.default])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
updateToolbar()
}
@IBAction func onDelete(_ sender: UIBarButtonItem) {
guard let selected = treeController?.selectedNodes().compactMap ({($0 as? NCFleetRow)?.object}) else {return}
guard !selected.isEmpty else {return}
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: String(format: NSLocalizedString("Delete %d Fleets", comment: ""), selected.count), style: .destructive) { [weak self] _ in
selected.forEach { object in
object.managedObjectContext?.delete(object)
}
if let context = selected.first?.managedObjectContext, context.hasChanges {
try? context.save()
}
self?.updateToolbar()
})
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil))
present(controller, animated: true, completion: nil)
controller.popoverPresentationController?.barButtonItem = sender
}
//MARK: - TreeControllerDelegate
override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
super.treeController(treeController, didSelectCellWithNode: node)
updateToolbar()
}
override func treeController(_ treeController: TreeController, didDeselectCellWithNode node: TreeNode) {
super.treeController(treeController, didDeselectCellWithNode: node)
updateToolbar()
}
func treeController(_ treeController: TreeController, didCollapseCellWithNode node: TreeNode) {
updateToolbar()
}
func treeControllerDidUpdateContent(_ treeController: TreeController) {
updateToolbar()
tableView.backgroundView = (treeController.content?.children.count ?? 0) > 0 ? nil : NCTableViewBackgroundLabel(text: NSLocalizedString("No Results", comment: ""))
}
func treeController(_ treeController: TreeController, editActionsForNode node: TreeNode) -> [UITableViewRowAction]? {
guard let node = node as? NCFleetRow else {return nil}
let deleteAction = UITableViewRowAction(style: .destructive, title: NSLocalizedString("Delete", comment: "")) { _,_ in
guard let context = NCStorage.sharedStorage?.viewContext else {return}
let fleet = node.object
context.delete(fleet)
if context.hasChanges {
try? context.save()
}
}
return [deleteAction]
}
override func content() -> Future<TreeNode?> {
guard let context = NCStorage.sharedStorage?.viewContext else {return .init(nil)}
let request = NSFetchRequest<NCFleet>(entityName: "Fleet")
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
let root = FetchedResultsNode(resultsController: controller, objectNode: NCFleetRow.self)
return .init(root)
}
private func updateToolbar() {
toolbarItems?.last?.isEnabled = treeController?.selectedNodes().isEmpty == false
}
}
| lgpl-2.1 | bfcb61b92a4f5b64907581ae17555ca1 | 33.980583 | 167 | 0.752706 | 4.459158 | false | false | false | false |
fhisa/FormulaStyleConstraint | SwiftyLayout/SwiftyLayout/ConstraintTerm.swift | 2 | 638 | //
// ConstraintTerm.swift
// SwiftyLayout
//
// Created by fhisa on 2015/08/13.
// Copyright (c) 2015 Hisakuni Fujimoto. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import AppKit
#endif
public struct ConstraintTerm
{
let view: AnyObject?
let attribute: NSLayoutAttribute
var multiplier: CGFloat
var constant: CGFloat
public init(
view v: AnyObject? = nil,
attribute a: NSLayoutAttribute = .notAnAttribute,
multiplier m: CGFloat = 1.0,
constant c: CGFloat = 0.0)
{
view = v
attribute = a
multiplier = m
constant = c
}
}
| mit | daa6e5a6d00a5813ab824435550b005b | 18.333333 | 62 | 0.612853 | 3.9875 | false | false | false | false |
samnm/material-components-ios | components/NavigationBar/examples/NavigationBarTypicalUseExample.swift | 3 | 2746 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents.MaterialNavigationBar
open class NavigationBarTypicalUseSwiftExample: NavigationBarTypicalUseExample {
override open func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
title = "Navigation Bar (Swift)"
navBar = MDCNavigationBar()
navBar!.observe(navigationItem)
navBar!.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
let mutator = MDCNavigationBarTextColorAccessibilityMutator()
mutator.mutate(navBar!)
view.addSubview(navBar!)
navBar!.translatesAutoresizingMaskIntoConstraints = false
#if swift(>=3.2)
if #available(iOS 11.0, *) {
self.view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: self.navBar!.topAnchor).isActive = true
} else {
NSLayoutConstraint(item: self.topLayoutGuide,
attribute: .bottom,
relatedBy: .equal,
toItem: self.navBar,
attribute: .top,
multiplier: 1,
constant: 0).isActive = true
}
#else
NSLayoutConstraint(item: self.topLayoutGuide,
attribute: .bottom,
relatedBy: .equal,
toItem: self.navBar,
attribute: .top,
multiplier: 1,
constant: 0).isActive = true
#endif
let viewBindings = ["navBar": navBar!]
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[navBar]|",
options: [],
metrics: nil,
views: viewBindings))
self.setupExampleViews()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override open var prefersStatusBarHidden: Bool {
return true
}
}
| apache-2.0 | e402ae06056c997ea7eaf1ad6b6f556b | 33.325 | 107 | 0.608521 | 5.525151 | false | false | false | false |
rayshen/PaperSwitch | PaperSwitchDemo/PaperSwitchDemo/ViewController.swift | 1 | 3566 | // ViewController.swift
//
// Copyright (c) 26/11/14 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak private var connectContactsLabel: UILabel!
@IBOutlet weak private var phone1ImageView: UIImageView!
@IBOutlet weak private var paperSwitch1: RAMPaperSwitch!
@IBOutlet weak private var allowDiscoveryLabel: UILabel!
@IBOutlet weak private var phone2ImageView: UIImageView!
@IBOutlet weak private var paperSwitch2: RAMPaperSwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setupPaperSwitch()
self.navigationController?.navigationBarHidden = true
}
private func setupPaperSwitch() {
self.paperSwitch1.animationDidStartClosure = {(onAnimation: Bool) in
self.animateLabel(self.connectContactsLabel, onAnimation: onAnimation, duration: self.paperSwitch1.duration)
self.animateImageView(self.phone1ImageView, onAnimation: onAnimation, duration: self.paperSwitch1.duration)
}
self.paperSwitch2.animationDidStartClosure = {(onAnimation: Bool) in
self.animateLabel(self.self.allowDiscoveryLabel, onAnimation: onAnimation, duration: self.paperSwitch2.duration)
self.animateImageView(self.phone2ImageView, onAnimation: onAnimation, duration: self.paperSwitch2.duration)
}
}
private func animateLabel(label: UILabel, onAnimation: Bool, duration: NSTimeInterval) {
UIView.transitionWithView(label, duration: duration, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
label.textColor = onAnimation ? UIColor.whiteColor() : UIColor(red: 31/255.0, green: 183/255.0, blue: 252/255.0, alpha: 1)
}, completion:nil)
}
private func animateImageView(imageView: UIImageView, onAnimation: Bool, duration: NSTimeInterval) {
UIView.transitionWithView(imageView, duration: duration, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
imageView.image = UIImage(named: onAnimation ? "img_phone_on" : "img_phone_off")
}, completion:nil)
}
}
// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com
| mit | 5ee1b9b5bbfe3b7e0d0017878cd3ef65 | 43.025 | 135 | 0.713799 | 4.708556 | false | false | false | false |
themonki/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Utils/UIColor+Utils.swift | 3 | 3493 | //
// UIColor+Utils.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 4/20/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
extension UIColor {
static func by(r: Int, g: Int, b: Int, a: CGFloat = 1) -> UIColor {
let d = CGFloat(255)
return UIColor(red: CGFloat(r) / d, green: CGFloat(g) / d, blue: CGFloat(b) / d, alpha: a)
}
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
static let darkDefault = UIColor(white: 45.0/255.0, alpha: 1)
static let grayText = UIColor(white: 160.0/255.0, alpha: 1)
static let facebookDarkBlue = UIColor.by(r: 59, g: 89, b: 152)
static let dimmedLightBackground = UIColor(white: 100.0/255.0, alpha: 0.3)
static let dimmedDarkBackground = UIColor(white: 50.0/255.0, alpha: 0.3)
static let pinky = UIColor(rgb: 0xE91E63)
static let amber = UIColor(rgb: 0xFFC107)
static let satCyan = UIColor(rgb: 0x00BCD4)
static let darkText = UIColor(rgb: 0x212121)
static let redish = UIColor(rgb: 0xFF5252)
static let darkSubText = UIColor(rgb: 0x757575)
static let greenGrass = UIColor(rgb: 0x4CAF50)
static let darkChatMessage = UIColor(red: 48, green: 47, blue: 48)
}
struct EKColor {
struct BlueGray {
static let c50 = UIColor(rgb: 0xeceff1)
static let c100 = UIColor(rgb: 0xcfd8dc)
static let c200 = UIColor(rgb: 0xb0bec5)
static let c300 = UIColor(rgb: 0x90a4ae)
static let c400 = UIColor(rgb: 0x78909c)
static let c500 = UIColor(rgb: 0x607d8b)
static let c600 = UIColor(rgb: 0x546e7a)
static let c700 = UIColor(rgb: 0x455a64)
static let c800 = UIColor(rgb: 0x37474f)
static let c900 = UIColor(rgb: 0x263238)
}
struct Netflix {
static let light = UIColor(rgb: 0x485563)
static let dark = UIColor(rgb: 0x29323c)
}
struct Gray {
static let a800 = UIColor(rgb: 0x424242)
static let mid = UIColor(rgb: 0x616161)
static let light = UIColor(white: 230.0/255.0, alpha: 1)
}
struct Purple {
static let a300 = UIColor(rgb: 0xba68c8)
static let a400 = UIColor(rgb: 0xab47bc)
static let a700 = UIColor(rgb: 0xaa00ff)
static let deep = UIColor(rgb: 0x673ab7)
}
struct BlueGradient {
static let light = UIColor(red: 100, green: 172, blue: 196)
static let dark = UIColor(red: 27, green: 47, blue: 144)
}
struct Yellow {
static let a700 = UIColor(rgb: 0xffd600)
}
struct Teal {
static let a700 = UIColor(rgb: 0x00bfa5)
static let a600 = UIColor(rgb: 0x00897b)
}
struct Orange {
static let a50 = UIColor(rgb: 0xfff3e0)
}
struct LightBlue {
static let a700 = UIColor(rgb: 0x0091ea)
}
struct LightPink {
static let first = UIColor(rgb: 0xff9a9e)
static let last = UIColor(rgb: 0xfad0c4)
}
}
| apache-2.0 | 7d0cdf819347738d00e5f98151487cf0 | 31.95283 | 116 | 0.601489 | 3.292177 | false | false | false | false |
lzwjava/leanchat-ios | LeanChatSwift/LeanChatSwift/ViewController.swift | 2 | 1265 | //
// ViewController.swift
// LeanChatSwift
//
// Created by lzw on 15/11/17.
// Copyright © 2015年 LeanCloud. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var clientIdTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func login(sender: AnyObject) {
if let clientId = clientIdTextField.text {
if (clientId.characters.count > 0) {
CDChatManager.sharedManager().openWithClientId(clientId, callback: { (result: Bool, error: NSError!) -> Void in
if (error == nil) {
let tabbarC = UITabBarController()
let chatListVC = ChatListViewController()
let nav = UINavigationController(rootViewController: chatListVC)
tabbarC.addChildViewController(nav)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window?.rootViewController = tabbarC
}
})
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | f30199dea17b40ca53f124b2ef6cc56c | 29.780488 | 127 | 0.577655 | 5.510917 | false | false | false | false |
GEOSwift/GEOSwift | Sources/GEOSwift/Codable/Geometry+Codable.swift | 2 | 1973 | extension Geometry: Codable {
enum CodingKeys: CodingKey {
case type
}
public init(from decoder: Decoder) throws {
let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
let singleValueContainer = try decoder.singleValueContainer()
switch try keyedContainer.geoJSONType(forKey: .type) {
case .point:
self = try singleValueContainer.decode(Point.self).geometry
case .multiPoint:
self = try singleValueContainer.decode(MultiPoint.self).geometry
case .lineString:
self = try singleValueContainer.decode(LineString.self).geometry
case .multiLineString:
self = try singleValueContainer.decode(MultiLineString.self).geometry
case .polygon:
self = try singleValueContainer.decode(Polygon.self).geometry
case .multiPolygon:
self = try singleValueContainer.decode(MultiPolygon.self).geometry
case .geometryCollection:
self = try singleValueContainer.decode(GeometryCollection.self).geometry
case .feature, .featureCollection:
throw GEOSwiftError.mismatchedGeoJSONType
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case let .point(point):
try container.encode(point)
case let .multiPoint(multiPoint):
try container.encode(multiPoint)
case let .lineString(lineString):
try container.encode(lineString)
case let .multiLineString(multiLineString):
try container.encode(multiLineString)
case let .polygon(polygon):
try container.encode(polygon)
case let .multiPolygon(multiPolygon):
try container.encode(multiPolygon)
case let .geometryCollection(geometryCollection):
try container.encode(geometryCollection)
}
}
}
| mit | 814ce2f058dbc16bf4fb1fcbcd7bafe8 | 40.104167 | 84 | 0.658895 | 5.465374 | false | false | false | false |
LetItPlay/iOSClient | blockchainapp/AppUI.swift | 1 | 2926 | import UIKit
struct AppColor {
struct Title {
static let light = UIColor.white
static let dark = UIColor.black
static let gray = UIColor.init(white: 74.0/255, alpha: 1)
static let lightGray = UIColor.init(white: 155.0/255, alpha: 1)
}
struct Element {
static let tomato = UIColor.init(redInt: 243, greenInt: 71, blueInt: 36, alpha: 1)
static let subscribe = UIColor.red
static let redBlur = UIColor.init(redInt: 255, greenInt: 102, blueInt: 102, alpha: 0.6)
static let tagColor = UIColor.init(redInt: 31, greenInt: 60, blueInt: 74, alpha: 1)
}
}
struct AppFont {
struct Title {
static let big = UIFont.systemFont(ofSize: 24, weight: .regular)
static let section = UIFont.systemFont(ofSize: 20, weight: .bold)
static let mid = UIFont.systemFont(ofSize: 18, weight: .medium)
static let midBold = UIFont.systemFont(ofSize: 18, weight: .bold)
static let sml = UIFont.systemFont(ofSize: 14, weight: .bold)
static let info = UIFont.systemFont(ofSize: 12, weight: .medium)
}
struct Button {
static let mid = UIFont.systemFont(ofSize: 16, weight: .medium)
}
struct Text {
static let mid = UIFont.systemFont(ofSize: 14, weight: .regular)
static let descr = UIFont.systemFont(ofSize: 14, weight: .medium)
}
}
extension UIColor {
convenience init(redInt: Int, greenInt: Int, blueInt: Int, alpha: CGFloat) {
self.init(red: CGFloat(redInt) / 255,
green: CGFloat(greenInt) / 255,
blue: CGFloat(blueInt) / 255,
alpha: alpha)
}
func img(size: CGSize = CGSize.init(width: 1, height: 1)) -> UIImage {
let rect = CGRect.init(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(self.cgColor)
context!.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
static func gradImg(colors: [UIColor], vector: CGPoint = CGPoint.init(x: 0, y: 1)) -> UIImage? {
let layer = CAGradientLayer.init()
layer.colors = colors
layer.startPoint = CGPoint.zero
layer.endPoint = vector
UIGraphicsBeginImageContextWithOptions(CGSize.init(width: 20, height: 20), false, 0)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
layer.render(in: context)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
func circle(diameter: CGFloat) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(CGSize(width: diameter, height: diameter), false, 0)
guard let ctx = UIGraphicsGetCurrentContext() else {
return nil
}
ctx.saveGState()
let rect = CGRect(x: 0, y: 0, width: diameter, height: diameter)
ctx.setFillColor(self.cgColor)
ctx.fillEllipse(in: rect)
ctx.restoreGState()
let img = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return img
}
}
| mit | 14700848c445a1537363e70f2a4a3d4e | 31.511111 | 97 | 0.706083 | 3.648379 | false | false | false | false |
austinzheng/swift | stdlib/public/core/SwiftNativeNSArray.swift | 2 | 10354 | //===--- SwiftNativeNSArray.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// __ContiguousArrayStorageBase supplies the implementation of the
// _NSArrayCore API (and thus, NSArray the API) for our
// _ContiguousArrayStorage<T>. We can't put this implementation
// directly on _ContiguousArrayStorage because generic classes can't
// override Objective-C selectors.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
/// Returns `true` iff the given `index` is valid as a position, i.e. `0
/// ≤ index ≤ count`.
@usableFromInline @_transparent
internal func _isValidArrayIndex(_ index: Int, count: Int) -> Bool {
return (index >= 0) && (index <= count)
}
/// Returns `true` iff the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@usableFromInline @_transparent
internal func _isValidArraySubscript(_ index: Int, count: Int) -> Bool {
return (index >= 0) && (index < count)
}
/// An `NSArray` with Swift-native reference counting and contiguous
/// storage.
///
/// NOTE: older runtimes called this
/// _SwiftNativeNSArrayWithContiguousStorage. The two must coexist, so
/// it was renamed. The old name must not be used in the new runtime.
@_fixed_layout
@usableFromInline
internal class __SwiftNativeNSArrayWithContiguousStorage
: __SwiftNativeNSArray { // Provides NSArray inheritance and native refcounting
@inlinable
@nonobjc internal override init() {}
@inlinable
deinit {}
// Operate on our contiguous storage
internal func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
_internalInvariantFailure(
"Must override withUnsafeBufferOfObjects in derived classes")
}
}
// Implement the APIs required by NSArray
extension __SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
@objc internal var count: Int {
return withUnsafeBufferOfObjects { $0.count }
}
@objc(objectAtIndex:)
internal func objectAt(_ index: Int) -> AnyObject {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArraySubscript(index, count: objects.count),
"Array index out of range")
return objects[index]
}
}
@objc internal func getObjects(
_ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange
) {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArrayIndex(range.location, count: objects.count),
"Array index out of range")
_precondition(
_isValidArrayIndex(
range.location + range.length, count: objects.count),
"Array index out of range")
if objects.isEmpty { return }
// These objects are "returned" at +0, so treat them as pointer values to
// avoid retains. Copy bytes via a raw pointer to circumvent reference
// counting while correctly aliasing with all other pointer types.
UnsafeMutableRawPointer(aBuffer).copyMemory(
from: objects.baseAddress! + range.location,
byteCount: range.length * MemoryLayout<AnyObject>.stride)
}
}
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
var enumerationState = state.pointee
if enumerationState.state != 0 {
return 0
}
return withUnsafeBufferOfObjects {
objects in
enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr
enumerationState.itemsPtr =
AutoreleasingUnsafeMutablePointer(objects.baseAddress)
enumerationState.state = 1
state.pointee = enumerationState
return objects.count
}
}
@objc(copyWithZone:)
internal func copy(with _: _SwiftNSZone?) -> AnyObject {
return self
}
}
/// An `NSArray` whose contiguous storage is created and filled, upon
/// first access, by bridging the elements of a Swift `Array`.
///
/// Ideally instances of this class would be allocated in-line in the
/// buffers used for Array storage.
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
@objc internal final class __SwiftDeferredNSArray
: __SwiftNativeNSArrayWithContiguousStorage {
// This stored property should be stored at offset zero. We perform atomic
// operations on it.
//
// Do not access this property directly.
@nonobjc
internal var _heapBufferBridged_DoNotUse: AnyObject?
// When this class is allocated inline, this property can become a
// computed one.
@usableFromInline
@nonobjc
internal let _nativeStorage: __ContiguousArrayStorageBase
@nonobjc
internal var _heapBufferBridgedPtr: UnsafeMutablePointer<AnyObject?> {
return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(
to: Optional<AnyObject>.self)
}
internal var _heapBufferBridged: _BridgingBufferStorage? {
if let ref =
_stdlib_atomicLoadARCRef(object: _heapBufferBridgedPtr) {
return unsafeBitCast(ref, to: _BridgingBufferStorage.self)
}
return nil
}
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal init(_nativeStorage: __ContiguousArrayStorageBase) {
self._nativeStorage = _nativeStorage
}
internal func _destroyBridgedStorage(_ hb: _BridgingBufferStorage?) {
if let bridgedStorage = hb {
let buffer = _BridgingBuffer(bridgedStorage)
let count = buffer.count
buffer.baseAddress.deinitialize(count: count)
}
}
deinit {
_destroyBridgedStorage(_heapBufferBridged)
}
internal override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
while true {
var buffer: UnsafeBufferPointer<AnyObject>
// If we've already got a buffer of bridged objects, just use it
if let bridgedStorage = _heapBufferBridged {
let bridgingBuffer = _BridgingBuffer(bridgedStorage)
buffer = UnsafeBufferPointer(
start: bridgingBuffer.baseAddress, count: bridgingBuffer.count)
}
// If elements are bridged verbatim, the native buffer is all we
// need, so return that.
else if let buf = _nativeStorage._withVerbatimBridgedUnsafeBuffer(
{ $0 }
) {
buffer = buf
}
else {
// Create buffer of bridged objects.
let objects = _nativeStorage._getNonVerbatimBridgingBuffer()
// Atomically store a reference to that buffer in self.
if !_stdlib_atomicInitializeARCRef(
object: _heapBufferBridgedPtr, desired: objects.storage!) {
// Another thread won the race. Throw out our buffer.
_destroyBridgedStorage(
unsafeDowncast(objects.storage!, to: _BridgingBufferStorage.self))
}
continue // Try again
}
defer { _fixLifetime(self) }
return try body(buffer)
}
}
/// Returns the number of elements in the array.
///
/// This override allows the count to be read without triggering
/// bridging of array elements.
@objc
internal override var count: Int {
if let bridgedStorage = _heapBufferBridged {
return _BridgingBuffer(bridgedStorage).count
}
// Check if elements are bridged verbatim.
return _nativeStorage._withVerbatimBridgedUnsafeBuffer { $0.count }
?? _nativeStorage._getNonVerbatimBridgedCount()
}
}
#else
// Empty shim version for non-objc platforms.
@usableFromInline
@_fixed_layout
internal class __SwiftNativeNSArrayWithContiguousStorage {
@inlinable
internal init() {}
@inlinable
deinit {}
}
#endif
/// Base class of the heap buffer backing arrays.
///
/// NOTE: older runtimes called this _ContiguousArrayStorageBase. The
/// two must coexist, so it was renamed. The old name must not be used
/// in the new runtime.
@usableFromInline
@_fixed_layout
internal class __ContiguousArrayStorageBase
: __SwiftNativeNSArrayWithContiguousStorage {
@usableFromInline
final var countAndCapacity: _ArrayBody
@inlinable
@nonobjc
internal init(_doNotCallMeBase: ()) {
_internalInvariantFailure("creating instance of __ContiguousArrayStorageBase")
}
#if _runtime(_ObjC)
internal override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
if let result = try _withVerbatimBridgedUnsafeBuffer(body) {
return result
}
_internalInvariantFailure(
"Can't use a buffer of non-verbatim-bridged elements as an NSArray")
}
/// If the stored type is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
internal func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
_internalInvariantFailure(
"Concrete subclasses must implement _withVerbatimBridgedUnsafeBuffer")
}
@nonobjc
internal func _getNonVerbatimBridgedCount() -> Int {
_internalInvariantFailure(
"Concrete subclasses must implement _getNonVerbatimBridgedCount")
}
internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer {
_internalInvariantFailure(
"Concrete subclasses must implement _getNonVerbatimBridgingBuffer")
}
#endif
@inlinable
internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
_internalInvariantFailure(
"Concrete subclasses must implement canStoreElements(ofDynamicType:)")
}
/// A type that every element in the array is.
@inlinable
internal var staticElementType: Any.Type {
_internalInvariantFailure(
"Concrete subclasses must implement staticElementType")
}
@inlinable
deinit {
_internalInvariant(
self !== _emptyArrayStorage, "Deallocating empty array storage?!")
}
}
| apache-2.0 | 6bd358e92e8fa2cf56c7bcb9c8b21b27 | 30.64526 | 82 | 0.690568 | 5.107601 | false | false | false | false |
nevercry/VideoMarks | VideoMarks/VideoMarksTVC.swift | 1 | 10874 | //
// VideoMarksTVC.swift
// VideoMarks
//
// Created by nevercry on 6/8/16.
// Copyright © 2016 nevercry. All rights reserved.
//
import UIKit
import CoreData
import AVKit
import AVFoundation
import StoreKit
class VideoMarksTVC: UITableViewController {
var dataController: DataController?
var fetchedResultsController: NSFetchedResultsController<Video>!
var memCache = NSCache<NSString,NSString>()
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupViews()
self.registerNotification()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func setupViews() {
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
self.clearsSelectionOnViewWillAppear = true
self.navigationItem.title = NSLocalizedString("Video Marks", comment: "影签")
self.navigationItem.rightBarButtonItem = editButtonItem
self.tableView.allowsSelectionDuringEditing = true
self.tableView.estimatedRowHeight = 70
self.tableView.rowHeight = UITableViewAutomaticDimension
self.refreshControl?.addTarget(self, action: #selector(refreshData), for: .valueChanged)
self.tableView.register(UINib(nibName: "VideoMarkCell", bundle: nil), forCellReuseIdentifier: VideoMarksConstants.VideoMarkCellID)
if let _ = dataController {
initializeFetchedResultsController()
} else {
fatalError("Error no dataController ")
}
// Check for force touch feature, and add force touch/previewing capability.
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: view)
}
}
func registerNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(refreshData), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
// 注册CoreData完成初始化后的通知
NotificationCenter.default.addObserver(self, selector: #selector(coreDataStackComplete), name: VideoMarksConstants.CoreDataStackCompletion, object: nil)
}
/**
CoreStack 完成初始化
*/
func coreDataStackComplete() {
refetchResultAndUpdate()
updateVideoMarksFromExtension()
}
/**
初始化FetchedResultsController
*/
func initializeFetchedResultsController() {
let request = NSFetchRequest<Video>(entityName: "Video")
let createAtSort = NSSortDescriptor(key: "createAt", ascending: false)
request.sortDescriptors = [createAtSort]
let moc = self.dataController!.managedObjectContext
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: "VideoCache")
fetchedResultsController.delegate = self
}
/**
获取数据并更新
*/
func refetchResultAndUpdate() {
do {
try fetchedResultsController.performFetch()
} catch {
fatalError("Failed to initialize FetchedResultsController: \(error)")
}
tableView.reloadData()
}
/**
刷新数据
*/
func refreshData() {
updateVideoMarksFromExtension()
self.refreshControl?.endRefreshing()
}
/**
编辑视频
*/
func editVideo() {
self.setEditing(!isEditing, animated: true)
}
/**
从Group UserDefault 里提取保存的VideoMarks数据
*/
func updateVideoMarksFromExtension() {
let groupDefaults = UserDefaults.init(suiteName: VideoMarksConstants.appGroupID)!
if let savedMarksData = groupDefaults.object(forKey: "savedMarks") as? Data {
if let savedMarks = try! JSONSerialization.jsonObject(with: savedMarksData, options: .allowFragments) as? NSArray {
let batchSize = 500; //can be set 100-10000 objects depending on individual object size and available device memory
var i = 1;
for mark in savedMarks {
let _ = Video(videoInfo: mark as! [String:String], context: dataController!.managedObjectContext)
if 0 == (i % batchSize) {
dataController!.saveContext()
dataController!.managedObjectContext.reset()
refetchResultAndUpdate()
}
i += 1
}
dataController!.saveContext()
groupDefaults.removeObject(forKey: "savedMarks")
groupDefaults.synchronize()
}
} else {
tableView.reloadData()
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let destVC = segue.destination as? VideoDetailTVC {
if let video = sender as? Video {
destVC.video = video
}
}
}
}
// MARK: - Table view data source and Delegate
extension VideoMarksTVC {
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return VideoMarksConstants.VideoMarkCellRowHeight
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController.fetchedObjects?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: VideoMarksConstants.VideoMarkCellID, for: indexPath)
// Set up the cell
configureCell(cell as! VideoMarkCell, indexPath: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let video = fetchedResultsController.fetchedObjects![(indexPath as NSIndexPath).row]
if !isEditing {
PlayerController.sharedInstance.playVideo(video.player, inViewController: self)
} else {
performSegue(withIdentifier: "Show Video Detail", sender: video)
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction.init(style: .destructive, title: NSLocalizedString("Delete", comment: "删除")) { (action, indexPath) in
let videoMark = self.fetchedResultsController.fetchedObjects![(indexPath as NSIndexPath).row]
self.dataController?.managedObjectContext.delete(videoMark)
self.dataController?.saveContext()
}
let shareAction = UITableViewRowAction(style: .normal, title: NSLocalizedString("Share", comment: "分享")) { (action, indexPath) in
let videoMark = self.fetchedResultsController.fetchedObjects![(indexPath as NSIndexPath).row]
let url = URL(string: videoMark.url)!
let actVC = UIActivityViewController.init(activityItems: [url], applicationActivities: [OpenSafariActivity()])
actVC.modalPresentationStyle = .popover
if let presenter = actVC.popoverPresentationController {
presenter.sourceView = tableView.cellForRow(at: indexPath)
presenter.sourceRect = CGRect(x: tableView.bounds.width, y: 0, width: 0, height: 44)
}
self.present(actVC, animated: true, completion: nil)
}
shareAction.backgroundColor = UIColor.gray
return [deleteAction,shareAction]
}
// MARK: 设置cell
/**
初始化Cell
- parameter cell: 需要初始化的Cell
- parameter indexPath: cell在tableView中的indexPath
*/
func configureCell(_ cell: VideoMarkCell, indexPath: IndexPath) {
let video = fetchedResultsController.fetchedObjects![(indexPath as NSIndexPath).row]
// Populate cell from the NSManagedObject instance
cell.configFor(video: video)
}
}
// MARK:- NSFetchedResultsControllerDelegate
extension VideoMarksTVC: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
guard let updateIndex = indexPath, let updateCell = self.tableView.cellForRow(at: updateIndex) as? VideoMarkCell else { return }
configureCell(updateCell, indexPath: updateIndex)
case .move:
tableView.deleteRows(at: [indexPath!], with: .fade)
tableView.insertRows(at: [newIndexPath!], with: .fade)
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
// MARK: - 3D Touch
extension VideoMarksTVC: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
self.navigationController?.show(viewControllerToCommit, sender: nil)
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location),
let cell = tableView.cellForRow(at: indexPath),
let video = fetchedResultsController.fetchedObjects?[(indexPath as NSIndexPath).row],
let storyboard = self.storyboard else { return nil }
previewingContext.sourceRect = cell.frame
let videDetailTVC = storyboard.instantiateViewController(withIdentifier: "VideoDetailTVC") as! VideoDetailTVC
videDetailTVC.video = video
return videDetailTVC
}
}
| mit | fa59b1d05e1894e1ec9fa2419f400c4c | 39.250936 | 200 | 0.664092 | 5.683236 | false | false | false | false |
y0ke/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AAAuthViewController.swift | 2 | 3737 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
public class AAAuthViewController: AAViewController {
public let nextBarButton = UIButton()
private var keyboardHeight: CGFloat = 0
override public func viewDidLoad() {
super.viewDidLoad()
nextBarButton.setTitle(AALocalized("NavigationNext"), forState: .Normal)
nextBarButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
nextBarButton.setBackgroundImage(Imaging.roundedImage(UIColor(red: 94, green: 142, blue: 192), radius: 4), forState: .Normal)
nextBarButton.setBackgroundImage(Imaging.roundedImage(UIColor(red: 94, green: 142, blue: 192).alpha(0.7), radius: 4), forState: .Highlighted)
nextBarButton.addTarget(self, action: #selector(AAAuthViewController.nextDidTap), forControlEvents: .TouchUpInside)
view.addSubview(nextBarButton)
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
layoutNextBar()
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Forcing initial layout before keyboard show to avoid weird animations
layoutNextBar()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AAAuthViewController.keyboardWillAppearInt(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AAAuthViewController.keyboardWillDisappearInt(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
private func layoutNextBar() {
nextBarButton.frame = CGRectMake(view.width - 95, view.height - 44 - keyboardHeight + 6, 85, 32)
}
func keyboardWillAppearInt(notification: NSNotification) {
let dict = notification.userInfo!
let rect = dict[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue
let orientation = UIApplication.sharedApplication().statusBarOrientation
let frameInWindow = self.view.superview!.convertRect(view.bounds, toView: nil)
let windowBounds = view.window!.bounds
let keyboardTop: CGFloat = windowBounds.size.height - rect.height
let heightCoveredByKeyboard: CGFloat
if AADevice.isiPad {
if orientation == .LandscapeLeft || orientation == .LandscapeRight {
heightCoveredByKeyboard = frameInWindow.maxY - keyboardTop - 52 /*???*/
} else if orientation == .Portrait || orientation == .PortraitUpsideDown {
heightCoveredByKeyboard = CGRectGetMaxY(frameInWindow) - keyboardTop
} else {
heightCoveredByKeyboard = 0
}
} else {
heightCoveredByKeyboard = rect.height
}
keyboardHeight = max(0, heightCoveredByKeyboard)
layoutNextBar()
keyboardWillAppear(keyboardHeight)
}
func keyboardWillDisappearInt(notification: NSNotification) {
keyboardHeight = 0
layoutNextBar()
keyboardWillDisappear()
}
public func keyboardWillAppear(height: CGFloat) {
}
public func keyboardWillDisappear() {
}
override public func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
keyboardHeight = 0
layoutNextBar()
}
/// Call this method when authentication successful
public func onAuthenticated() {
ActorSDK.sharedActor().didLoggedIn()
}
public func nextDidTap() {
}
} | agpl-3.0 | f0d9f4d290d19e4edca745acc1d85a45 | 36.009901 | 185 | 0.664169 | 5.922345 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/InputPasteboardParser.swift | 1 | 9057 | //
// InputPasteboardParser.swift
// Telegram-Mac
//
// Created by keepcoder on 02/11/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TelegramCore
import SwiftSignalKit
import Postbox
import TGUIKit
class InputPasteboardParser: NSObject {
public class func getPasteboardUrls(_ pasteboard: NSPasteboard, context: AccountContext) -> Signal<[URL], NoError> {
let items = pasteboard.pasteboardItems
if let items = items, !items.isEmpty {
var files:[URL] = []
for item in items {
let path = item.string(forType: NSPasteboard.PasteboardType(rawValue: "public.file-url"))
if let path = path, let url = URL(string: path) {
files.append(url)
}
// if let type = item.availableType(from: [.html]), let data = item.data(forType: type) {
// let attributed = NSAttributedString(html: data, documentAttributes: nil)
// if let attributed = attributed, let attachment = attributed.attribute(.attachment, at: 0, effectiveRange: nil) as? NSTextAttachment {
//
// if let fileWrapper = attachment.fileWrapper, let fileName = fileWrapper.preferredFilename, fileWrapper.isRegularFile {
// if let data = fileWrapper.regularFileContents {
// let url = URL(fileURLWithPath: NSTemporaryDirectory() + "\(arc4random())_" + fileName)
// do {
// try data.write(to: url)
// files.append(url)
// } catch {
//
// }
//
// }
// }
// }
// }
}
var image:NSImage? = nil
if files.isEmpty {
if let images = pasteboard.readObjects(forClasses: [NSImage.self], options: nil) as? [NSImage], !images.isEmpty {
image = images[0]
}
}
files = files.filter { path -> Bool in
if let size = fileSize(path.path) {
let exceed = fileSizeLimitExceed(context: context, fileSize: size)
return exceed
}
return false
}
if !files.isEmpty {
return .single(files)
} else if let image = image {
return putToTemp(image: image, compress: false) |> map {[URL(fileURLWithPath: $0)]} |> deliverOnMainQueue
}
}
return .single([])
}
public class func canProccessPasteboard(_ pasteboard:NSPasteboard, context: AccountContext) -> Bool {
let items = pasteboard.pasteboardItems
if let items = items, !items.isEmpty {
var files:[URL] = []
for item in items {
let path = item.string(forType: NSPasteboard.PasteboardType(rawValue: "public.file-url"))
if let path = path, let url = URL(string: path) {
files.append(url)
}
}
var image:NSImage? = nil
if files.isEmpty {
if let images = pasteboard.readObjects(forClasses: [NSImage.self], options: nil) as? [NSImage], !images.isEmpty {
image = images[0]
}
}
if let _ = items[0].types.firstIndex(of: NSPasteboard.PasteboardType(rawValue: "com.apple.traditional-mac-plain-text")) {
return true
}
let previous = files.count
files = files.filter { path -> Bool in
if let size = fileSize(path.path) {
let exceed = fileSizeLimitExceed(context: context, fileSize: size)
return exceed
}
return false
}
let afterSizeCheck = files.count
if afterSizeCheck == 0 && previous != afterSizeCheck {
return false
}
if !files.isEmpty {
return false
} else if let _ = image {
return false
}
}
return true
}
public class func proccess(pasteboard:NSPasteboard, chatInteraction:ChatInteraction, window:Window) -> Bool {
let items = pasteboard.pasteboardItems
if let items = items, !items.isEmpty {
var files:[URL] = []
for item in items {
let path = item.string(forType: NSPasteboard.PasteboardType(rawValue: "public.file-url"))
if let path = path, let url = URL(string: path) {
files.append(url)
}
}
var image:NSImage? = nil
if files.isEmpty {
if let images = pasteboard.readObjects(forClasses: [NSImage.self], options: nil) as? [NSImage], !images.isEmpty {
if let representation = images[0].representations.first as? NSPDFImageRep {
let url = URL(fileURLWithPath: NSTemporaryDirectory() + "ios_scan_\(arc4random()).pdf")
try? representation.pdfRepresentation.write(to: url)
files.append(url)
image = nil
} else {
image = images[0]
}
}
}
if let _ = items[0].types.firstIndex(of: NSPasteboard.PasteboardType(rawValue: "com.microsoft.appbundleid")) {
return true
}
let previous = files.count
var exceedSize: Int64?
files = files.filter { path -> Bool in
if let size = fileSize(path.path) {
let exceed = fileSizeLimitExceed(context: chatInteraction.context, fileSize: size)
if exceed {
exceedSize = size
}
return exceed
}
return false
}
let afterSizeCheck = files.count
if afterSizeCheck == 0 && previous != afterSizeCheck {
showFileLimit(context: chatInteraction.context, fileSize: exceedSize)
return false
}
if let peer = chatInteraction.presentation.peer, let permissionText = permissionText(from: peer, for: .banSendMedia) {
if !files.isEmpty || image != nil {
alert(for: mainWindow, info: permissionText)
return false
}
}
if files.count == 1, let editState = chatInteraction.presentation.interfaceState.editState, editState.canEditMedia {
_ = (Sender.generateMedia(for: MediaSenderContainer(path: files[0].path, isFile: false), account: chatInteraction.context.account, isSecretRelated: chatInteraction.peerId.namespace == Namespaces.Peer.SecretChat) |> deliverOnMainQueue).start(next: { [weak chatInteraction] media, _ in
chatInteraction?.update({$0.updatedInterfaceState({$0.updatedEditState({$0?.withUpdatedMedia(media)})})})
})
return false
} else if let image = image, let editState = chatInteraction.presentation.interfaceState.editState, editState.canEditMedia {
_ = (putToTemp(image: image) |> mapToSignal {Sender.generateMedia(for: MediaSenderContainer(path: $0, isFile: false), account: chatInteraction.context.account, isSecretRelated: chatInteraction.peerId.namespace == Namespaces.Peer.SecretChat) } |> deliverOnMainQueue).start(next: { [weak chatInteraction] media, _ in
chatInteraction?.update({$0.updatedInterfaceState({$0.updatedEditState({$0?.withUpdatedMedia(media)})})})
})
return false
}
if !files.isEmpty {
chatInteraction.showPreviewSender(files, true, nil)
return false
} else if let image = image {
_ = (putToTemp(image: image, compress: false) |> deliverOnMainQueue).start(next: { (path) in
chatInteraction.showPreviewSender([URL(fileURLWithPath: path)], true, nil)
})
return false
}
}
return true
}
}
| gpl-2.0 | 4b9809ccf67fb9e93ab3691fbc35f495 | 38.545852 | 330 | 0.494148 | 5.515225 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | Pod/Classes/Sources.Api/ContactUid.swift | 1 | 3877 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Structure representing the internal unique identifier data elements of a contact.
@author Francisco Javier Martin Bueno
@since v2.0
@version 1.0
*/
public class ContactUid : APIBean {
/**
The id of the Contact
*/
var contactId : String?
/**
Default constructor
@since v2.0
*/
public override init() {
super.init()
}
/**
Constructor used by implementation to set the Contact id.
@param contactId Internal unique contact id.
@since v2.0
*/
public init(contactId: String) {
super.init()
self.contactId = contactId
}
/**
Returns the contact id
@return Contactid Internal unique contact id.
@since v2.0
*/
public func getContactId() -> String? {
return self.contactId
}
/**
Set the id of the Contact
@param contactId Internal unique contact id.
@since v2.0
*/
public func setContactId(contactId: String) {
self.contactId = contactId
}
/**
JSON Serialization and deserialization support.
*/
public struct Serializer {
public static func fromJSON(json : String) -> ContactUid {
let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
return fromDictionary(dict!)
}
static func fromDictionary(dict : NSDictionary) -> ContactUid {
let resultObject : ContactUid = ContactUid()
if let value : AnyObject = dict.objectForKey("contactId") {
if "\(value)" as NSString != "<null>" {
resultObject.contactId = (value as! String)
}
}
return resultObject
}
public static func toJSON(object: ContactUid) -> String {
let jsonString : NSMutableString = NSMutableString()
// Start Object to JSON
jsonString.appendString("{ ")
// Fields.
object.contactId != nil ? jsonString.appendString("\"contactId\": \"\(JSONUtil.escapeString(object.contactId!))\"") : jsonString.appendString("\"contactId\": null")
// End Object to JSON
jsonString.appendString(" }")
return jsonString as String
}
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| apache-2.0 | 865e38172c2c81d2dcf4357b4090c6f3 | 28.580153 | 176 | 0.582452 | 5.11889 | false | false | false | false |
merlos/iOS-Open-GPX-Tracker | OpenGpxTracker/CoreDataAlertView.swift | 1 | 1131 | //
// CoreDataAlertView.swift
// OpenGpxTracker
//
// Created by Vincent on 25/6/19.
//
import UIKit
/// To display Core Data alert action sheet anywhere when needed.
///
/// It should display anywhere possible, in case if a gpx file loads too long when file recovery with previous session's file is too big.
struct CoreDataAlertView {
/// shows the action sheet that prompts user on what to do with recovered data.
func showActionSheet(_ alertController: UIAlertController) {
guard let appDelegate = UIApplication.shared.delegate else { return }
guard let rootVC = appDelegate.window!?.rootViewController else { return }
if let popoverController = alertController.popoverPresentationController {
guard let view = rootVC.view else { return }
popoverController.sourceView = view
popoverController.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
popoverController.permittedArrowDirections = []
}
rootVC.present(alertController, animated: true, completion: nil)
}
}
| gpl-3.0 | 40fbbc4b23fdb3b04b5174bcd68b4edd | 36.7 | 137 | 0.687003 | 4.982379 | false | false | false | false |
josepvaleriano/iOS-practices | PetCens/PetCens/NuevoRViewController.swift | 1 | 8597 | //
// NuevoRViewController.swift
// PetCens
//
// Created by Jan Zelaznog on 15/10/16.
// Copyright © 2016 JanZelaznog. All rights reserved.
//
import UIKit
class NuevoRViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
var estados:NSArray?
var municipios:NSArray?
var colonias:NSArray?
var conexion:NSURLConnection?
var datosRecibidos:NSMutableData?
var solcecito:LoadingView?
@IBOutlet weak var txtNombre: UITextField!
@IBOutlet weak var txtApels: UITextField!
@IBOutlet weak var txtFechaNac: UITextField!
@IBOutlet weak var txtCalleNo: UITextField!
@IBOutlet weak var txtColonia: UITextField!
@IBOutlet weak var txtMunicipio: UITextField!
@IBOutlet weak var txtEstado: UITextField!
@IBOutlet weak var pickerFN: UIDatePicker!
@IBOutlet weak var pickerEstados: UIPickerView!
@IBOutlet weak var pickerMuns: UIPickerView!
@IBOutlet weak var pickerCols: UIPickerView!
@IBAction func pickerDateChanged(sender: AnyObject) {
let formato = NSDateFormatter()
formato.dateFormat = "dd-MM-yyyy"
let fechaString = formato.stringFromDate(self.pickerFN.date)
self.txtFechaNac.text = fechaString
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerEstados.isEqual(pickerView) {
return estados!.count
}
else if pickerMuns.isEqual(pickerView) {
return municipios!.count
}
else {
return colonias!.count
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerEstados.isEqual(pickerView) {
return (estados![row].valueForKey("nombreEstado") as! String)
}
else if pickerMuns.isEqual(pickerView) {
return (municipios![row] as! String)
}
else {
return (colonias![row] as! String)
} }
func subeBajaPicker(elPicker:UIView, subeObaja:Bool) {
var elFrame:CGRect = elPicker.frame
UIView.animateWithDuration(0.5) {
if subeObaja {
elFrame.origin.y = CGRectGetMaxY(self.txtFechaNac.frame)
elPicker.hidden = false
}
else {
elFrame.origin.y = CGRectGetMaxY(self.view.frame)
}
elPicker.frame = elFrame
}
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField.isEqual(self.txtNombre) ||
textField.isEqual(self.txtApels) ||
textField.isEqual(self.txtCalleNo) {
self.ocultaPickers()
return true
}
else {
self.txtNombre.resignFirstResponder()
self.txtApels.resignFirstResponder()
self.txtCalleNo.resignFirstResponder()
if textField.isEqual(self.txtFechaNac) {
self.subeBajaPicker(self.pickerFN, subeObaja: true)
}
// TODO: otros pickers
return false
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.txtNombre.delegate = self
self.txtApels.delegate = self
self.txtFechaNac.delegate = self
self.txtCalleNo.delegate = self
self.txtColonia.delegate = self
self.txtMunicipio.delegate = self
self.txtEstado.delegate = self
self.pickerFN.hidden = true
self.pickerEstados.delegate = self
self.pickerEstados.dataSource = self
self.estados = NSArray()
// Inicializar con datos temporales
self.municipios = ["no", "si", "talvez"]//NSArray()
self.colonias = NSArray()
/// toDO: revisar si este es el mejor momento para cargar el WS
self.consultaEstados()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.ocultaPickers()
}
func ocultaPickers () {
var unFrame:CGRect
unFrame = self.pickerFN.frame
self.pickerFN.frame = CGRectMake(unFrame.origin.x, CGRectGetMaxY(self.view.frame), unFrame.size.width, unFrame.size.height)
self.pickerFN.hidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func consultaEstados() {
if ConnectionManager.hayConexion() {
if !ConnectionManager.esConexionWiFi() {
// Si hay conexion, pero es celular, preguntar al usuario
// si quiere descargar el contenido
// ......
}
let urlString = "http://edg3.mx/webservicessepomex/WMRegresaEstados.php"
let laURL = NSURL(string: urlString)!
let elRequest = NSURLRequest(URL: laURL)
self.datosRecibidos = NSMutableData(capacity: 0)
self.conexion = NSURLConnection(request: elRequest, delegate: self)
if self.conexion == nil {
self.datosRecibidos = nil
self.conexion = nil
print ("No se puede acceder al WS Estados")
}
}
else {
print ("no hay conexion a internet ")
}
}
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
self.datosRecibidos = nil
self.conexion = nil
print ("No se puede acceder al WS Estados: Error del server")
}
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) { // Ya se logrò la conexion, preparando para recibir datos
self.datosRecibidos?.length = 0
}
func connection(connection: NSURLConnection, didReceiveData data: NSData) { // Se recibiò un paquete de datos. guardarlo con los demàs
self.datosRecibidos?.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection){
do {
let arregloRecibido = try NSJSONSerialization.JSONObjectWithData(self.datosRecibidos!, options: .AllowFragments) as! NSArray
self.estados = arregloRecibido
self.pickerEstados.reloadAllComponents()
}
catch {
print ("Error al recibir webservice de Estados")
}
}
// MARK: - UIPickerView DataSource & Delegate
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// El picker solo tiene un component, entonces "component" no se usa
if pickerView.isEqual(self.pickerEstados) {
self.txtEstado.text = (estados![row].valueForKey("nombreEstado") as! String)
let codigoEstado = (estados![row].valueForKey("c_estado") as! String)
// Invocar el otro WS para llenar el picker de municipios
SOAPManager.instance.consultaMunicipios(codigoEstado)
//selector es el identificador del metodo
//Nos subcribimos al notification center
NSNotificationCenter.defaultCenter().addObserver(
self, selector: #selector(NuevoRViewController.municipiosResponse(_:)),
name: "WMRegresaMunicipios", object: nil)
solcecito = LoadingView.loadingInView(self.view, mensaje: "Buscando municipios ...")
NSNotificationCenter.defaultCenter().addObserver(
self, selector: #selector(NuevoRViewController.removeSolecito(_:)),
name: "WMRegresaMunicipiosError", object: nil)
}
}
func municipiosResponse(notif: NSNotification){
self.municipios = (notif.userInfo! ["WMRegresaMunicipios"] as! NSArray)
self.pickerMuns.reloadAllComponents()
//una vez llegada la notificacion nos des subcribimios con self todas las notificaciones incluso el teclado
//NSNotificationCenter.defaultCenter().removeObserver(self)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "WMRegresaMunicipios", object: nil)
}
func removeSolecito(notif: NSNotification) {
//NSNotificationCenter.defaultCenter().removeObserver(self)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "WMRegresaMunicipiosError", object: nil)
self.solcecito?.performSelector(#selector(LoadingView.removeLoadingInView), withObject: nil, afterDelay: 1.0)
}
}
| mit | ff56351a8704f7a4f257cf5794bf2bbc | 39.533019 | 152 | 0.640056 | 4.680283 | false | false | false | false |
MLSDev/AppRouter | Tests/Instantiations/AppRouterInstantiationsTests.swift | 1 | 1984 | //
// AppRouterInstantiationsTests.swift
// AppRouter
//
// Created by Prokhor Kharchenko on 6/23/16.
// Copyright © 2016 Artem Antihevich. All rights reserved.
//
import XCTest
@testable import AppRouter
class AppRouterInstantiationsTests: XCTestCase {
func testInstantiateFromStoryboardWithStoryboardName() {
let controller = AppRouterInstantiationsTestsViewController.instantiate(storyboardName: "AppRouterInstantiationsTests")!
controller.viewDidLoadExpectation = expectation(description: "viewDidLoad should be called")
_ = controller.view
waitForExpectations(timeout: 1, handler: nil)
}
func testInstantiateFromStoryboardWithDefaultParameters() {
let controller = StoryboardWithInitialViewController.instantiate()!
controller.viewDidLoadExpectation = expectation(description: "viewDidLoad should be called")
_ = controller.view
waitForExpectations(timeout: 1, handler: nil)
}
func testInstantiateFromStoryboardWithInitialParameter() {
let controller = StoryboardWithInitialViewController.instantiate(initial: true)!
controller.viewDidLoadExpectation = expectation(description: "viewDidLoad should be called")
_ = controller.view
waitForExpectations(timeout: 1, handler: nil)
}
func testInstantiateFromStoryboardInitialSkippingNavigation() {
let controller = StoryboardWithInitialNavigationViewController.instantiate(initial: true)!
controller.viewDidLoadExpectation = expectation(description: "viewDidLoad should be called")
_ = controller.view
waitForExpectations(timeout: 1, handler: nil)
}
func testInstantiateFromXib() {
let controller = XibWithViewController.instantiateFromXib()
controller?.viewDidLoadExpectation = expectation(description: "viewDidLoad should be called")
_ = controller?.view
waitForExpectations(timeout: 1, handler: nil)
}
}
| mit | 6b75dc42adb9dd09e6f1e88400233388 | 40.3125 | 128 | 0.735754 | 5.617564 | false | true | false | false |
hooman/swift | validation-test/Sema/type_checker_crashers_fixed/sr13856.swift | 11 | 1007 | // RUN: %target-typecheck-verify-swift
protocol OptionalType {
associatedtype Wrapped
var wrapped: Wrapped? { get }
}
protocol DefaultsBridge {
associatedtype T
}
protocol DefaultsSerializable {
typealias T = Bridge.T
associatedtype Bridge: DefaultsBridge
}
protocol DefaultsKeyStore {}
struct DefaultsKeys: DefaultsKeyStore {}
struct DefaultsKey<ValueType> {}
@dynamicMemberLookup
struct DefaultsAdapter<KeyStore: DefaultsKeyStore> {
@available(*, unavailable)
subscript(dynamicMember member: String) -> Never {
fatalError()
}
subscript<T: DefaultsSerializable>(keyPath: KeyPath<KeyStore, DefaultsKey<T>>) -> T.T where T.T == T {
get { fatalError() }
set { fatalError() }
}
subscript<T: DefaultsSerializable>(dynamicMember keyPath: KeyPath<KeyStore, DefaultsKey<T>>) -> T.T where T: OptionalType, T.T == T {
get { fatalError() }
set { fatalError() }
}
}
var Defaults = DefaultsAdapter<DefaultsKeys>()
Defaults[\.missingKey] = "" // expected-error {{}}
| apache-2.0 | ae6424fad612d23af46dd9cd9abe9c48 | 22.97619 | 135 | 0.713009 | 4.266949 | false | false | false | false |
braintree/braintree_ios | UnitTests/BraintreeSEPADirectDebitTests/SEPADirectDebitAPI_Tests.swift | 1 | 5484 | import XCTest
import BraintreeTestShared
@testable import BraintreeCore
@testable import BraintreeSEPADirectDebit
class SEPADirectDebitAPI_Tests: XCTestCase {
var billingAddress = BTPostalAddress()
var sepaDirectDebitRequest = BTSEPADirectDebitRequest()
var successApprovalURL: String = ""
var mockAPIClient : MockAPIClient = MockAPIClient(authorization: "development_client_key")!
var mockCreateMandateResult = CreateMandateResult(json:
BTJSON(
value: [
"message": [
"body": [
"sepaDebitAccount": [
"approvalUrl": "https://api.test19.stage.paypal.com/directdebit/mandate/authorize?cart_id=1JH42426EL748934W&auth_code=C21_A.AAdcUj4loKRxLtfw336KxbGY7dA7UsLJQTpZU3cE2h49eKkhN1OjFcLxxxzOGVzRiwOzGLlS_cS2BU4ZLKjMnR6lZSG2iQ",
"last4": "1234",
"merchantOrPartnerCustomerId": "a-customer-id",
"bankReferenceToken": "a-bank-reference-token",
"mandateType": "ONE_OFF"
]
]
]
]
)
)
override func setUp() {
billingAddress.streetAddress = "Kantstraße 70"
billingAddress.extendedAddress = "#170"
billingAddress.locality = "Freistaat Sachsen"
billingAddress.region = "Annaberg-buchholz"
billingAddress.postalCode = "09456"
billingAddress.countryCodeAlpha2 = "FR"
sepaDirectDebitRequest.accountHolderName = "John Doe"
sepaDirectDebitRequest.iban = "FR891751244434203564412313"
sepaDirectDebitRequest.customerID = "A0E243A0A200491D929D"
sepaDirectDebitRequest.mandateType = .oneOff
sepaDirectDebitRequest.billingAddress = billingAddress
sepaDirectDebitRequest.merchantAccountID = "eur_pwpp_multi_account_merchant_account"
successApprovalURL = """
https://api.test19.stage.paypal.com/directdebit/mandate/authorize?cart_id=1JH42426EL748934W&auth_code=C21_A.AAdcUj4loKRxLtfw336KxbGY7dA7UsLJQTpZU3cE2h49eKkhN1OjFcLxxxzOGVzRiwOzGLlS_cS2BU4ZLKjMnR6lZSG2iQ
"""
}
func testCreateMandate_onSuccessfulHttpResponse_returnsCreateMandateResult() {
let api = SEPADirectDebitAPI(apiClient: mockAPIClient)
mockAPIClient.cannedResponseBody = BTJSON(
value: [
"message": [
"body": [
"sepaDebitAccount": [
"approvalUrl": successApprovalURL,
"last4": "2313",
"merchantOrPartnerCustomerId": "A0E243A0A200491D929D",
"bankReferenceToken": "QkEtWDZDQkpCUU5TWENDVw",
"mandateType": "ONE_OFF"
]
]
]
]
)
api.createMandate(sepaDirectDebitRequest: sepaDirectDebitRequest) { result, error in
if error != nil {
XCTFail("This request should be successful.")
} else if result != nil {
XCTAssertEqual(result?.ibanLastFour, "2313")
XCTAssertEqual(result?.approvalURL, self.successApprovalURL)
XCTAssertEqual(result?.bankReferenceToken, "QkEtWDZDQkpCUU5TWENDVw")
XCTAssertEqual(result?.customerID, "A0E243A0A200491D929D")
XCTAssertEqual(result?.mandateType, BTSEPADirectDebitMandateType.oneOff.description)
}
}
}
func testCreateMandate_onNoBodyReturned_returnsError() {
let api = SEPADirectDebitAPI(apiClient: mockAPIClient)
mockAPIClient.cannedResponseError = SEPADirectDebitError.noBodyReturned as NSError
api.createMandate(sepaDirectDebitRequest: sepaDirectDebitRequest) { result, error in
if error != nil, let error = error as NSError? {
XCTAssertEqual(error.domain, SEPADirectDebitError.errorDomain)
XCTAssertEqual(error.code, SEPADirectDebitError.noBodyReturned.errorCode)
XCTAssertEqual(error.localizedDescription, SEPADirectDebitError.noBodyReturned.localizedDescription)
} else if result != nil {
XCTFail("This request should fail.")
}
}
}
func testTokenize_onSuccessfulHttpResponse_returnsSEPADirectDebitNonce() {
let api = SEPADirectDebitAPI(apiClient: mockAPIClient)
let json = BTJSON(
value: [
"nonce": "a-fake-payment-method-nonce",
"details": [
"ibanLastChars": "1234",
"merchantOrPartnerCustomerId": "a-customer-id",
"mandateType": "RECURRENT"
]
]
)
mockAPIClient.cannedResponseBody = json
api.tokenize(createMandateResult: mockCreateMandateResult) { nonce, error in
if error != nil {
XCTFail("This request should be successful.")
} else if nonce != nil {
XCTAssertEqual(nonce?.nonce, "a-fake-payment-method-nonce")
XCTAssertEqual(nonce?.ibanLastFour, "1234")
XCTAssertEqual(nonce?.customerID, "a-customer-id")
XCTAssertEqual(nonce?.mandateType?.description, "RECURRENT")
}
}
}
}
| mit | 08cadac893f38500d0b2294d26dcdd95 | 43.942623 | 248 | 0.599125 | 4.694349 | false | true | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/ElasticLoadBalancing/ElasticLoadBalancing_Error.swift | 1 | 6997 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for ElasticLoadBalancing
public struct ElasticLoadBalancingErrorType: AWSErrorType {
enum Code: String {
case accessPointNotFoundException = "LoadBalancerNotFound"
case certificateNotFoundException = "CertificateNotFound"
case dependencyThrottleException = "DependencyThrottle"
case duplicateAccessPointNameException = "DuplicateLoadBalancerName"
case duplicateListenerException = "DuplicateListener"
case duplicatePolicyNameException = "DuplicatePolicyName"
case duplicateTagKeysException = "DuplicateTagKeys"
case invalidConfigurationRequestException = "InvalidConfigurationRequest"
case invalidEndPointException = "InvalidInstance"
case invalidSchemeException = "InvalidScheme"
case invalidSecurityGroupException = "InvalidSecurityGroup"
case invalidSubnetException = "InvalidSubnet"
case listenerNotFoundException = "ListenerNotFound"
case loadBalancerAttributeNotFoundException = "LoadBalancerAttributeNotFound"
case operationNotPermittedException = "OperationNotPermitted"
case policyNotFoundException = "PolicyNotFound"
case policyTypeNotFoundException = "PolicyTypeNotFound"
case subnetNotFoundException = "SubnetNotFound"
case tooManyAccessPointsException = "TooManyLoadBalancers"
case tooManyPoliciesException = "TooManyPolicies"
case tooManyTagsException = "TooManyTags"
case unsupportedProtocolException = "UnsupportedProtocol"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize ElasticLoadBalancing
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The specified load balancer does not exist.
public static var accessPointNotFoundException: Self { .init(.accessPointNotFoundException) }
/// The specified ARN does not refer to a valid SSL certificate in AWS Identity and Access Management (IAM) or AWS Certificate Manager (ACM). Note that if you recently uploaded the certificate to IAM, this error might indicate that the certificate is not fully available yet.
public static var certificateNotFoundException: Self { .init(.certificateNotFoundException) }
/// A request made by Elastic Load Balancing to another service exceeds the maximum request rate permitted for your account.
public static var dependencyThrottleException: Self { .init(.dependencyThrottleException) }
/// The specified load balancer name already exists for this account.
public static var duplicateAccessPointNameException: Self { .init(.duplicateAccessPointNameException) }
/// A listener already exists for the specified load balancer name and port, but with a different instance port, protocol, or SSL certificate.
public static var duplicateListenerException: Self { .init(.duplicateListenerException) }
/// A policy with the specified name already exists for this load balancer.
public static var duplicatePolicyNameException: Self { .init(.duplicatePolicyNameException) }
/// A tag key was specified more than once.
public static var duplicateTagKeysException: Self { .init(.duplicateTagKeysException) }
/// The requested configuration change is not valid.
public static var invalidConfigurationRequestException: Self { .init(.invalidConfigurationRequestException) }
/// The specified endpoint is not valid.
public static var invalidEndPointException: Self { .init(.invalidEndPointException) }
/// The specified value for the schema is not valid. You can only specify a scheme for load balancers in a VPC.
public static var invalidSchemeException: Self { .init(.invalidSchemeException) }
/// One or more of the specified security groups do not exist.
public static var invalidSecurityGroupException: Self { .init(.invalidSecurityGroupException) }
/// The specified VPC has no associated Internet gateway.
public static var invalidSubnetException: Self { .init(.invalidSubnetException) }
/// The load balancer does not have a listener configured at the specified port.
public static var listenerNotFoundException: Self { .init(.listenerNotFoundException) }
/// The specified load balancer attribute does not exist.
public static var loadBalancerAttributeNotFoundException: Self { .init(.loadBalancerAttributeNotFoundException) }
/// This operation is not allowed.
public static var operationNotPermittedException: Self { .init(.operationNotPermittedException) }
/// One or more of the specified policies do not exist.
public static var policyNotFoundException: Self { .init(.policyNotFoundException) }
/// One or more of the specified policy types do not exist.
public static var policyTypeNotFoundException: Self { .init(.policyTypeNotFoundException) }
/// One or more of the specified subnets do not exist.
public static var subnetNotFoundException: Self { .init(.subnetNotFoundException) }
/// The quota for the number of load balancers has been reached.
public static var tooManyAccessPointsException: Self { .init(.tooManyAccessPointsException) }
/// The quota for the number of policies for this load balancer has been reached.
public static var tooManyPoliciesException: Self { .init(.tooManyPoliciesException) }
/// The quota for the number of tags that can be assigned to a load balancer has been reached.
public static var tooManyTagsException: Self { .init(.tooManyTagsException) }
/// The specified protocol or signature version is not supported.
public static var unsupportedProtocolException: Self { .init(.unsupportedProtocolException) }
}
extension ElasticLoadBalancingErrorType: Equatable {
public static func == (lhs: ElasticLoadBalancingErrorType, rhs: ElasticLoadBalancingErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension ElasticLoadBalancingErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | cf483df2ff59008c78d849c512aa5208 | 57.308333 | 279 | 0.736601 | 5.526856 | false | false | false | false |
Tantalum73/XJodel | XJodel/XJodel/ComposeJodelViewController.swift | 1 | 9117 | //
// ComposeJodelViewController.swift
// XJodel
//
// Created by Andreas Neusüß on 11.03.16.
// Copyright © 2016 Cocoawah. All rights reserved.
//
import Cocoa
protocol ComposeJodelCompletionProtocol : class {
func postJodelWithMessage(_ jodelMessage: String, color: JodelColor)
func commentJodelWithMessage(_ jodelMessage: String, color: JodelColor)
}
protocol ComposeJodelDragAndDropProtocol : class {
func dragDidEnterView()
func dragDidExitView()
func dragDidFinishWithImage(_ image: NSImage)
}
class ComposeJodelViewController: NSViewController {
@IBOutlet weak var composeTextField: NSTextField!
@IBOutlet weak var backgroundView: JodelCellBackgroundView!
@IBOutlet weak var postJodelButton: NSButton!
@IBOutlet weak var dropIndicatorImageView: NSImageView! {
didSet {
dropIndicatorImageView.alphaValue = 0
}
}
@IBOutlet weak var droppedImageImageView: NSImageView! {
didSet {
droppedImageImageView.alphaValue = 0
//Prevent the image view from blocking drag and drop by unregister it. If this line is missing, drag and drop will only be possible outside of this image view because image views support their own drag and drop logic.
droppedImageImageView.unregisterDraggedTypes()
}
}
/// Boolean whose value indicates whether the new composed jodel is a comment to another jodel.
var jodelBack = false
/// Delegate of this ViewController, conforming to ComposeJodelCompletionProtocol. It is responsible for making calls to the network API and handlin network errors.
weak var delegate : ComposeJodelCompletionProtocol?
/// Color of the jodel.
var jodelColor = JodelColor.randomColor()
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
backgroundView.color = NSColor(hex: self.jodelColor.rawValue)
if let view = view as? ComposerView {
view.dragAndDropDelegate = self
}
}
fileprivate func performCommentOnJodel() {
guard let validText = validTextForJodelMessage() else {return}
delegate?.commentJodelWithMessage(validText, color: jodelColor)
}
fileprivate func performComposingJodel() {
guard let validText = validTextForJodelMessage() else {return}
delegate?.postJodelWithMessage(validText, color: jodelColor)
}
fileprivate func validTextForJodelMessage() -> String? {
let newJodelsText = composeTextField.stringValue
guard newJodelsText.characters.count <= 240 else {
print("Jodels must be 240 characters long at max!")
return nil
}
return newJodelsText
}
@IBAction func postJodelButtonPressed(_ sender: NSButton) {
//perform network operation by calling delegate
if jodelBack {
performCommentOnJodel()
}
else {
performComposingJodel()
}
dismissViewController(self)
}
@IBAction func cancelButtonPressed(_ sender: AnyObject) {
if let text = validTextForJodelMessage() , !text.isEmpty {
let alert = NSAlert()
alert.addButton(withTitle: NSLocalizedString("CONTINUE_BUTTON_KEY", comment: "Title of button that says 'Continue' as the user is continuing composing or commenting when this button is pressed."))
alert.addButton(withTitle: NSLocalizedString("DISCARD_BUTTON_KEY", comment: "Title of button that says 'Discard'. The text that the user has entered will be disCarded"))
alert.messageText = NSLocalizedString("MESSAGE_TEXT_DISCARD_JODEL", comment: "Message of the ealert that asks the user if he really wants to dismiss the currently inserted text.")
alert.informativeText = NSLocalizedString("INFORMATIVE_TEXT_DISCARD_JODEL", comment: "Informative text of the ealert that asks the user if he really wants to dismiss the currently inserted text.")
let userHasClickedOnCancel = alert.runModal()
if userHasClickedOnCancel == NSAlertFirstButtonReturn {
//cancel clicked
}
else {
//discard clicked
dismiss(self)
}
}
else {
dismiss(self)
}
}
}
extension ComposeJodelViewController : ComposeJodelDragAndDropProtocol {
func dragDidEnterView() {
Swift.print("drag did enter, showing a imageview or something...")
//Add hint to drop image here.
composeTextField.isHidden = true
animateDropIndicatorImageViewToVisible(true)
}
func dragDidFinishWithImage(_ image: NSImage) {
Swift.print("Dragging ended, image received.")
//Present the image in an image view, remove hint to drop image there.
animateDropIndicatorImageViewToVisible(false)
showDroppedImage(image)
}
func dragDidExitView() {
//Hide indicators that item can be dropped, remove hint to drop here
composeTextField.stringValue = ""
composeTextField.isHidden = false
animateDropIndicatorImageViewToVisible(false)
}
fileprivate func animateDropIndicatorImageViewToVisible(_ visible: Bool) {
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = 0.3
self.dropIndicatorImageView.animator().alphaValue = visible ? 1 : 0
}) { () -> Void in
}
}
fileprivate func showDroppedImage(_ image: NSImage) {
droppedImageImageView.image = image
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = 0.3
self.droppedImageImageView.animator().alphaValue = 1
}) { () -> Void in
}
}
}
class ComposerView : NSView
{
@IBOutlet var cTextField: NSTextField!
weak var dragAndDropDelegate : ComposeJodelDragAndDropProtocol?
required init?(coder: NSCoder) {
super.init(coder: coder)
self.register(forDraggedTypes: [NSFilenamesPboardType])
Swift.print("Registered for types")
}
/**
Method that should handle the drop data
- parameter sender: <#sender description#>
- returns: <#return value description#>
*/
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
Swift.print("Perform Drag Operation")
if NSImage.canInit(with: sender.draggingPasteboard()) {
if let image = NSImage(pasteboard: sender.draggingPasteboard()) {
dragAndDropDelegate?.dragDidFinishWithImage(image)
}
}
return true
//reson for change: the file only works, if the image came from a image on disk. If the user draggs from, lets say fotos app or safari, we will not get an URL.
// if let filePaths = sender.draggingPasteboard().propertyListForType(NSFilenamesPboardType) as? [String],first = filePaths.first
// {
// Swift.print(filePaths.first)
// let image = NSImage(contentsOfFile: first)
// //TODO: Send notification
//
// }else{
// Swift.print("Could not get file Paths")
// }
// return true
}
override func draggingEnded(_ sender: NSDraggingInfo?) {
Swift.print("Dragging ended")
}
/**
Determing if we accept dragged item.
- parameter sender: <#sender description#>
- returns: <#return value description#>
*/
override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
Swift.print("Preparing for drag operation")
//only accepting images.
return NSImage.canInit(with: sender.draggingPasteboard())
}
/**
Method called whenever a drag enters our drop zone
- parameter sender: <#sender description#>
- returns: <#return value description#>
*/
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
Swift.print("Dragging entered")
dragAndDropDelegate?.dragDidEnterView()
return NSDragOperation.copy
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
// Swift.print("Dragging Updated!")
return NSDragOperation.copy
}
/**
Method called whenever a drag exits our drop zone
- parameter sender: <#sender description#>
*/
override func draggingExited(_ sender: NSDraggingInfo?) {
Swift.print("Dragging exited")
dragAndDropDelegate?.dragDidExitView()
}
override func concludeDragOperation(_ sender: NSDraggingInfo?) {
Swift.print("Draging concluded")
}
}
| mit | f4318b3ec8339375723ed4dd1d650b01 | 32.262774 | 229 | 0.631227 | 5.383343 | false | false | false | false |
xiabob/NavigationTransitionDemo | NavigationTransitionDemo/NavigationTransitionDemo/LargeImageVC.swift | 1 | 3055 | //
// LargeImageVC.swift
// NavigationTransitionDemo
//
// Created by xiabob on 17/2/10.
// Copyright © 2017年 xiabob. All rights reserved.
//
import UIKit
class LargeImageVC: UIViewController {
internal lazy var cover: UIControl = {
let cover = UIControl(frame: CGRect(x: 0, y: 0, width: 67*2, height: 96*2))
cover.layer.borderWidth = 4
cover.layer.borderColor = UIColor.white.cgColor
cover.center = CGPoint(x: 80, y: 240)
cover.layer.contents = UIImage(named: "cover")?.cgImage
return cover
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationItem.title = "详情"
view.layer.contents = UIImage(named: "cover")?.cgImage
view.addSubview(cover)
navigationController?.attach(to: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension LargeImageVC: UIViewPushAnimationTransitionType {
func transitionDurationForPush(from viewController: UIViewController) -> TimeInterval {
return 0.25
}
func animationTypeForPush(from viewController: UIViewController) -> PushAnimationType {
return .mask(cover.frame)
}
}
extension LargeImageVC: UIViewPopAnimationTransitionType {
func transitionDurationForPop(to viewController: UIViewController) -> TimeInterval {
if viewController is DetailViewController {
return 0.35
}
return 0.25
}
func animationTypeForPop(to viewController: UIViewController) -> PopAnimationType {
if viewController is DetailViewController {
return .custom
}
return .system
}
func customAnimationForPop(to viewController: UIViewController, using transitionContext: UIViewControllerContextTransitioning, in popTransitioning: NavigationPopAnimationTransitioning) {
if let viewController = viewController as? DetailViewController {
UIView.animate(withDuration: 0.25, animations: {
self.cover.center = viewController.cover.center
}, completion: { (finished) in
if !transitionContext.transitionWasCancelled {
popTransitioning.maskAnimateTransition(using: transitionContext, in: self.cover.frame)
} else {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
})
}
}
}
extension LargeImageVC: UIViewInteractivePopAnimationTransitionType {
func useInteractiveAnimation() -> Bool {
return true
}
func interactiveTransitionDurationForPop(to viewController: UIViewController) -> TimeInterval {
return 0.25
}
func interactiveAnimationTypeForPop(to viewController: UIViewController) -> InteractivePopAnimationType {
return .stackScale
}
}
| mit | 230057a5c2cbe79854f9213a41aada85 | 31.425532 | 190 | 0.663714 | 5.385159 | false | false | false | false |
venticake/RetricaImglyKit-iOS | RetricaImglyKit/Classes/Frontend/Views/ProgressView.swift | 1 | 5294 | // This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import UIKit
/**
* A `ProgressView` is an activity indicator that is shown on top of all other views in a HUD style
* and temporarily blocks all user interaction with other views.
*/
@available(iOS 8, *)
@objc(IMGLYProgressView) public class ProgressView: NSObject {
/// The main container view of the progress view.
public var overlayView = UIView(frame: CGRect(x: 0, y: 0, width: 202, height: 200))
/// The background view that is being animated in.
public var backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: 202, height: 142))
/// The image view that holds the spinner.
public var imageView = UIImageView(frame: CGRect(x: 101 - 22, y: 29, width: 44, height: 44))
/// The label that contains the loading message.
public var label = UILabel(frame: CGRect(x: 0, y: 82, width: 202, height: 44))
/// The duration of one rotation of the spinner.
public var animationDuration = 0.3
/// The text that should be displayed in the progress view.
public var text: String {
get {
return label.text!
}
set {
label.text = newValue
}
}
private var keepRotating = true
/// A shared instance for convenience.
public static let sharedView = ProgressView()
/**
:nodoc:
*/
public override init() {
super.init()
commonInit()
}
private func commonInit() {
overlayView.addSubview(backgroundView)
configureBackground()
imageView.image = UIImage(named: "imgly_spinner", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)
configureLabel()
backgroundView.transform = CGAffineTransformMakeScale(3, 3)
backgroundView.alpha = 0.0
}
private func configureBackground() {
backgroundView.addSubview(imageView)
backgroundView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.8)
backgroundView.layer.cornerRadius = 4
}
private func configureLabel() {
label.textAlignment = .Center
label.textColor = UIColor.whiteColor()
label.font = UIFont.systemFontOfSize(14)
label.text = ""
backgroundView.addSubview(label)
}
/**
Presents the activity indicator with the given message.
- parameter message: The message to present.
*/
public func showWithMessage(message: String) {
text = message
if overlayView.superview == nil {
addOverlayViewToWindow()
updateOverlayFrame()
}
startAnimation()
UIView.animateWithDuration(0.25, delay: 0, options: [.CurveEaseInOut], animations: {
self.backgroundView.alpha = 1
self.backgroundView.transform = CGAffineTransformMakeScale(1, 1)
}, completion: nil)
}
/**
Hides the activity indicator.
*/
public func hide() {
UIView.animateWithDuration(0.25, delay: 0, options: [.CurveEaseInOut], animations: {
self.backgroundView.alpha = 0
self.backgroundView.transform = CGAffineTransformMakeScale(3, 3)
}, completion: { finished in
if finished {
self.stopAnimation()
self.overlayView.removeFromSuperview()
}
})
}
private func addOverlayViewToWindow() {
let frontToBackWindows = UIApplication.sharedApplication().windows.reverse()
for window in frontToBackWindows {
let windowOnMainScreen = window.screen == UIScreen.mainScreen()
let windowIsVisible = !window.hidden && window.alpha > 0
let windowLevelNormal = window.windowLevel == UIWindowLevelNormal
if windowOnMainScreen && windowIsVisible && windowLevelNormal {
window.addSubview(overlayView)
break
}
}
}
private func updateOverlayFrame() {
overlayView.frame = UIScreen.mainScreen().bounds
let center = CGPoint(x:overlayView.frame.size.width * 0.5, y:overlayView.frame.size.height * 0.4)
backgroundView.center = center
}
private func startAnimation() {
keepRotating = true
keepAnimating()
}
private func keepAnimating() {
UIView.animateWithDuration(animationDuration, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, CGFloat(M_PI_2))
}) { (finished) -> Void in
if finished {
if self.keepRotating {
self.keepAnimating()
}
}
}
}
private func stopAnimation() {
keepRotating = false
}
}
| mit | cf0eb723bb0a1ecbf28a5dd0ee6f5eeb | 34.059603 | 136 | 0.632225 | 4.929236 | false | false | false | false |
zhanggaoqiang/SwiftLearn | Swift语法/Swift字面量/Swift字面量/main.swift | 1 | 815 | //
// main.swift
// Swift字面量
//
// Created by zgq on 16/4/21.
// Copyright © 2016年 zgq. All rights reserved.
//
import Foundation
//所谓的字面量,就是指像特定的数字,字符串或者是布尔值这样,能够直截了当的指出自己的类型并为变量赋值的值
let aNumber=3//整形字面量
let AString="Hello"//字符串字面量
let aBool = true //布尔值字面量
//整形字面量
let decima=17//十进制表示
let hex=0x11//十六进制表示
//浮点型字面量
//除非特别指定,浮点型字面量的默认推到类型为Swift标准库中的Double,表示64位浮点数
//布尔型字面量
//布尔型字面量的默认类型是Bool
//布尔值字面量有三个值,它们是Swift的关键字
//true表示真,false表示假,nil表示没有值
| mit | 23c42ca9b8a5f8f0854af6dbf14bd40b | 13.967742 | 53 | 0.739224 | 2.15814 | false | false | false | false |
Esri/arcgis-runtime-tutorials-ios | Geocoding Tutorial/swift/MyFirstMapApp/ViewController.swift | 4 | 5555 | /*
Copyright 2014 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import ArcGIS
class ViewController: UIViewController, AGSMapViewLayerDelegate, UISearchBarDelegate, AGSLocatorDelegate {
@IBOutlet weak var mapView: AGSMapView!
var graphicLayer:AGSGraphicsLayer!
var locator:AGSLocator!
var calloutTemplate:AGSCalloutTemplate!
override func prefersStatusBarHidden() -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Add a basemap tiled layer
let url = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer")
let tiledLayer = AGSTiledMapServiceLayer(URL: url)
self.mapView.addMapLayer(tiledLayer, withName: "Basemap Tiled Layer")
//Set the map view's layer delegate
self.mapView.layerDelegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: map view layer delegate methods
func mapViewDidLoad(mapView: AGSMapView!) {
//do something now that the map is loaded
//for example, show the current location on the map
mapView.locationDisplay.startDataSource()
}
//MARK: search bar delegate methods
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
//Hide the keyboard
searchBar.resignFirstResponder()
if self.graphicLayer == nil {
//Add a graphics layer to the map. This layer will hold geocoding results
self.graphicLayer = AGSGraphicsLayer()
self.mapView.addMapLayer(self.graphicLayer, withName:"Results")
//Assign a simple renderer to the layer to display results as pushpins
let pushpin = AGSPictureMarkerSymbol(imageNamed: "BluePushpin.png")
pushpin.offset = CGPointMake(9, 16)
pushpin.leaderPoint = CGPointMake(-9, 11)
let renderer = AGSSimpleRenderer(symbol: pushpin)
self.graphicLayer.renderer = renderer
}
else {
//Clear out previous results if we already have a graphics layer
self.graphicLayer.removeAllGraphics()
}
if self.locator == nil {
//Create the AGSLocator pointing to the geocode service on ArcGIS Online
//Set the delegate so that we are informed through AGSLocatorDelegate methods
let url = NSURL(string: "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer")
self.locator = AGSLocator(URL: url)
self.locator.delegate = self
}
//Set the parameters
let params = AGSLocatorFindParameters()
params.text = searchBar.text
params.outFields = ["*"]
params.outSpatialReference = self.mapView.spatialReference
params.location = AGSPoint(x: 0, y: 0, spatialReference: nil)
//Kick off the geocoding operation
//This will invoke the geocode service on a background thread
self.locator.findWithParameters(params)
}
//MARK: AGSLocator delegate methods
func locator(locator: AGSLocator!, operation op: NSOperation!, didFind results: [AnyObject]!) {
if results == nil || results.count == 0 {
//show alert if we didn't get results
UIAlertView(title: "No Results", message: "No Results Found", delegate: nil, cancelButtonTitle: "OK").show()
}
else {
//Create a callout template if we haven't done so already
if self.calloutTemplate == nil {
self.calloutTemplate = AGSCalloutTemplate()
self.calloutTemplate.titleTemplate = "${Match_addr}"
self.calloutTemplate.detailTemplate = "${DisplayY}\u{00b0} ${DisplayX}\u{00b0}"
//Assign the callout template to the layer so that all graphics within this layer
//display their information in the callout in the same manner
self.graphicLayer.calloutDelegate = self.calloutTemplate
}
//Add a graphic for each result
for result in results as! [AGSLocatorFindResult] {
self.graphicLayer.addGraphic(result.graphic)
}
//Zoom in to the results
let extent = self.graphicLayer.fullEnvelope.mutableCopy() as! AGSMutableEnvelope
extent.expandByFactor(1.5)
self.mapView.zoomToEnvelope(extent, animated: true)
}
}
func locator(locator: AGSLocator!, operation op: NSOperation!, didFailLocationsForAddress error: NSError!) {
UIAlertView(title: "Locator Failed", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK").show()
}
}
| apache-2.0 | 850dd44a33f1c3f8f8d47e125a718066 | 39.547445 | 128 | 0.646445 | 5.162639 | false | false | false | false |
egnwd/ic-bill-hack | quick-split/Pods/MondoKit/MondoKit/MondoAPIOAuth.swift | 2 | 6197 | //
// MondoAPIOAuth.swift
// MondoKit
//
// Created by Mike Pollard on 23/01/2016.
// Copyright © 2016 Mike Pollard. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class OAuthViewController : UIViewController {
private var webView : UIWebView!
private var mondoApi : MondoAPI
private var onCompletion : (success : Bool, error : ErrorType?) -> Void
private var state : String?
init(mondoApi : MondoAPI, onCompletion : (success : Bool, error : ErrorType?) -> Void) {
self.mondoApi = mondoApi
self.onCompletion = onCompletion
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
webView = UIWebView()
webView.delegate = self
view = webView
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let uuid = NSUUID()
state = uuid.UUIDString
if let state = state {
var url = MondoAPI.AUTHRoot + "?client_id=" + mondoApi.clientId!
url = url + "&redirect_uri=" + MondoAPI.AUTHRedirectUri
url = url + "&response_type=code"
url = url + "&state=" + state
if let url = NSURL(string: url) {
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
}
}
}
extension OAuthViewController : UIWebViewDelegate {
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let url = request.URL where url.scheme == MondoAPI.AUTHRedirectScheme {
let queryParams = url.queryParams
if let state = queryParams["state"], code = queryParams["code"] where state == self.state {
MondoAPI.instance.authorizeFromCode(code, completion: onCompletion)
return false
}
}
return true
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
onCompletion(success: false, error: error)
}
}
extension MondoAPI {
private static let AUTHRoot = "https://auth.getmondo.co.uk/"
private static let AUTHRedirectScheme = "mondoapi"
private static let AUTHRedirectUri = AUTHRedirectScheme + "://success"
/// Only to be used for development purposes to access your own account.
public func authorizeFromUsername(userName: String, andPassword password: String, completion: (success: Bool, error: ErrorType?) -> Void) -> Void {
let parameters = [
"grant_type": "password",
"client_id": clientId!,
"client_secret": clientSecret!,
"username" : userName,
"password" : password
]
apiOperationQueue.addOperation(authorizeOperationWithParameters(parameters, completion: completion))
}
func reauthorizeOperationFromRefreshToken(refreshToken: String, completion: (success: Bool, error: ErrorType?) -> Void) -> MondoAPIOperation {
let parameters = [
"grant_type": "refresh_token",
"client_id": clientId!,
"client_secret": clientSecret!,
"refresh_token" : refreshToken
]
return authorizeOperationWithParameters(parameters, completion: completion)
}
func authorizeFromCode(code : String, completion: (success: Bool, error: ErrorType?) -> Void) -> Void {
let parameters = [
"grant_type": "authorization_code",
"client_id": clientId!,
"client_secret": clientSecret!,
"redirect_uri" : MondoAPI.AUTHRedirectUri,
"code" : code
]
apiOperationQueue.addOperation(authorizeOperationWithParameters(parameters, completion: completion))
}
private func authorizeOperationWithParameters(parameters: [String:String], completion: (success: Bool, error: ErrorType?) -> Void) -> MondoAPIOperation {
let operation = MondoAPIOperation(method: .POST, urlString: MondoAPI.APIRoot+"oauth2/token", parameters: parameters) { (json, error) in
var success : Bool = false
var anyError : ErrorType?
defer {
self.dispatchCompletion() {
completion(success: success, error: anyError)
}
}
guard error == nil else { anyError = error; return }
if let json = json,
_ = json["user_id"].string,
accessToken = json["access_token"].string,
expiresIn = json["expires_in"].int {
let refreshToken = json["refresh_token"].string
self.authData = AuthData(createdAt: NSDate(), accessToken: accessToken, expiresIn: expiresIn, refreshToken: refreshToken)
self.authData!.storeInKeychain(self.keychain)
success = true
}
else {
anyError = MondoAPIError.Unknown
}
}
return operation
}
}
extension NSURL {
var queryParams : [String : String] {
get {
var params = [String: String]()
if let queryString = self.query {
for part in queryString.componentsSeparatedByString("&") {
let split = part.componentsSeparatedByString("=")
guard split.count == 2 else { continue }
if let key = split[0].stringByRemovingPercentEncoding, value = split[1].stringByRemovingPercentEncoding {
params[key] = value
}
}
}
return params
}
}
}
| mit | 0d929ee02f2f642ce61cf96b8835b8c8 | 31.610526 | 157 | 0.558909 | 5.44464 | false | false | false | false |
DrippApp/Dripp-iOS | Dripp/ShowerCell.swift | 1 | 823 | //
// ShowerCell.swift
// Dripp
//
// Created by Henry Saniuk on 1/31/16.
// Copyright © 2016 Henry Saniuk. All rights reserved.
//
import UIKit
class ShowerCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var duration: UILabel!
@IBOutlet weak var recommended: UILabel!
@IBOutlet weak var photo: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
photo.layer.borderWidth = 1
photo.layer.borderColor = UIColor.lightGrayColor().CGColor
photo.layer.cornerRadius = photo.frame.height/2
photo.layer.masksToBounds = false
photo.clipsToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| mit | 5073a737638d0a7abac2c4f063c2ab4b | 24.6875 | 66 | 0.653285 | 4.326316 | false | false | false | false |
kineticobservations/k2HelperTools | SKShapeNode+Extensions.swift | 1 | 1533 | //
// SKShapeNode+Extensions.swift
// Reef Battle
//
// Created by Kathryne Engel on 6/21/17.
// Copyright © 2017 Lawson & Dawson LLC. All rights reserved.
//
import SpriteKit
extension SKShapeNode {
func generateTexture() -> SKTexture? {
guard let path = self.path else { return nil }
let frameRect = CGRect(x: 0, y: 0,
width: path.boundingBox.width + lineWidth,
height: path.boundingBox.height + lineWidth)
var transform = CGAffineTransform.init(translationX: lineWidth * 0.5,
y: lineWidth * 0.5)
guard let newPath = path.copy(using: &transform) else { return nil }
// context parameters: (size:opaque:scale)
UIGraphicsBeginImageContextWithOptions(frameRect.size, false, 0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
context.clip(to: frameRect)
context.setFillColor(fillColor.cgColor)
context.setStrokeColor(strokeColor.cgColor)
context.setLineWidth(lineWidth)
context.addPath(newPath)
context.drawPath(using: .fillStroke)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return SKTexture(image: image)
}
func generateSprite() -> SKSpriteNode? {
return SKSpriteNode(texture: generateTexture())
}
}
| mit | c28726e0991c400ccba8d21e9ca50323 | 33.044444 | 89 | 0.601828 | 5.123746 | false | false | false | false |
mownier/photostream | Photostream/Modules/Post Like/Interactor/PostLikeInteractor.swift | 1 | 4245 | //
// PostLikeInteractor.swift
// Photostream
//
// Created by Mounir Ybanez on 20/01/2017.
// Copyright © 2017 Mounir Ybanez. All rights reserved.
//
protocol PostLikeInteractorInput: BaseModuleInteractorInput {
func fetchNew(postId: String, limit: UInt)
func fetchNext(postId: String, limit: UInt)
func follow(userId: String)
func unfollow(userId: String)
}
protocol PostLikeInteractorOutput: BaseModuleInteractorOutput {
func didFetchNew(data: [PostLikeData])
func didFetchNext(data: [PostLikeData])
func didFetchNew(error: PostServiceError)
func didFetchNext(error: PostServiceError)
func didFollow(error: UserServiceError?, userId: String)
func didUnfollow(error: UserServiceError?, userId: String)
}
protocol PostLikeInteractorInterface: BaseModuleInteractor {
var postService: PostService! { set get }
var userService: UserService! { set get }
var offset: String? { set get }
var isFetching: Bool { set get }
init(postService: PostService, userService: UserService)
func fetch(postId: String, limit: UInt)
}
class PostLikeInteractor: PostLikeInteractorInterface {
typealias Output = PostLikeInteractorOutput
weak var output: Output?
var postService: PostService!
var userService: UserService!
var offset: String?
var isFetching: Bool = false
required init(postService: PostService, userService: UserService) {
self.postService = postService
self.userService = userService
}
func fetch(postId: String, limit: UInt) {
guard output != nil, offset != nil, !isFetching else {
return
}
isFetching = true
postService.fetchLikes(id: postId, offset: offset!, limit: limit, callback: {
[weak self] result in
self?.didFinishFetching(result: result)
})
}
fileprivate func didFinishFetching(result: PostServiceLikeResult) {
guard result.error == nil else {
didFetch(error: result.error!)
return
}
guard let likes = result.likes, likes.count > 0 else {
didFetch(data: [PostLikeData](), nextOffset: result.nextOffset)
return
}
var data = [PostLikeData]()
for like in likes {
var item = PostLikeDataItem()
item.avatarUrl = like.avatarUrl
item.displayName = like.displayName
item.userId = like.id
item.isFollowing = result.following != nil && result.following![like.id] != nil
if let isMe = result.following?[like.id] {
item.isMe = isMe
}
data.append(item)
}
didFetch(data: data, nextOffset: result.nextOffset)
}
fileprivate func didFetch(error: PostServiceError) {
if let offset = offset {
if offset.isEmpty {
output?.didFetchNew(error: error)
} else {
output?.didFetchNext(error: error)
}
}
isFetching = false
}
fileprivate func didFetch(data: [PostLikeData], nextOffset: String?) {
if let offset = offset {
if offset.isEmpty {
output?.didFetchNew(data: data)
} else {
output?.didFetchNext(data: data)
}
}
isFetching = false
offset = nextOffset
}
}
extension PostLikeInteractor: PostLikeInteractorInput {
func fetchNew(postId: String, limit: UInt) {
offset = ""
fetch(postId: postId, limit: limit)
}
func fetchNext(postId: String, limit: UInt) {
fetch(postId: postId, limit: limit)
}
func follow(userId: String) {
userService.follow(id: userId) { [weak self] error in
self?.output?.didFollow(error: error, userId: userId)
}
}
func unfollow(userId: String) {
userService.unfollow(id: userId) { [weak self] error in
self?.output?.didUnfollow(error: error, userId: userId)
}
}}
| mit | afb10267885b6694810d1099c9ddbfde | 27.293333 | 91 | 0.589774 | 4.900693 | false | false | false | false |
CSullivan102/LearnApp | LearnKit/SmallModalTransition/SmallModalAnimator.swift | 1 | 2643 | //
// SmallModalAnimator.swift
// Learn
//
// Created by Christopher Sullivan on 8/31/15.
// Copyright © 2015 Christopher Sullivan. All rights reserved.
//
import UIKit
public class SmallModalAnimator: NSObject, UIViewControllerAnimatedTransitioning {
private let duration: NSTimeInterval = 0.6
private let damping: CGFloat = 0.9
private let initialSpringVelocity: CGFloat = 10.0
private let delay: NSTimeInterval = 0.0
private let animationOptions = UIViewAnimationOptions.CurveEaseOut
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let presentedView = transitionContext.viewForKey(UITransitionContextToViewKey) else {
return
}
let presentedViewCenter = presentedView.center
presentedView.center = CGPoint(x: presentedViewCenter.x, y: -presentedView.bounds.size.height)
transitionContext.containerView()?.addSubview(presentedView)
UIView.animateWithDuration(transitionDuration(transitionContext),
delay: delay,
usingSpringWithDamping: damping,
initialSpringVelocity: initialSpringVelocity,
options: animationOptions,
animations: {
presentedView.center = presentedViewCenter
}) {
_ in
self.finishTransition(transitionContext)
}
}
private func finishTransition(transitionContext: UIViewControllerContextTransitioning) {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
public class SmallModalDismissalAnimator: SmallModalAnimator {
override public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let presentedView = transitionContext.viewForKey(UITransitionContextFromViewKey) else {
return
}
UIView.animateWithDuration(duration,
delay: delay,
usingSpringWithDamping: damping,
initialSpringVelocity: initialSpringVelocity,
options: animationOptions,
animations: {
presentedView.center = CGPoint(x: presentedView.center.x, y: -presentedView.bounds.size.height)
}) { _ in
presentedView.removeFromSuperview()
self.finishTransition(transitionContext)
}
}
}
| mit | 5332bad9d7cd9f4d9cad934799a00d0c | 36.742857 | 112 | 0.668812 | 6.671717 | false | false | false | false |
benlangmuir/swift | test/decl/protocol/special/coding/struct_codable_member_type_lookup.swift | 4 | 22839 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// A top-level CodingKeys type to fall back to in lookups below.
public enum CodingKeys : String, CodingKey {
case topLevel
}
// MARK: - Synthesized CodingKeys Enum
// Structs which get synthesized Codable implementations should have visible
// CodingKey enums during member type lookup.
struct SynthesizedStruct : Codable {
let value: String = "foo"
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'value' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{3-6=var}}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared public because its parameter uses a private type}}
internal func qualifiedBar(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared internal because its parameter uses a private type}}
fileprivate func qualifiedBaz(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
private func qualifiedQux(_ key: SynthesizedStruct.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.value) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared public because its parameter uses a private type}}
internal func qualifiedBar(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared internal because its parameter uses a private type}}
fileprivate func qualifiedBaz(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
private func qualifiedQux(_ key: SynthesizedStruct.CodingKeys) {}
// Unqualified lookups should find the SynthesizedStruct's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.value) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
// MARK: - No CodingKeys Enum
// Structs which don't get synthesized Codable implementations should expose the
// appropriate CodingKeys type.
struct NonSynthesizedStruct : Codable { // expected-note 4 {{'NonSynthesizedStruct' declared here}}
// No synthesized type since we implemented both methods.
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should clearly fail -- we shouldn't get a synthesized
// type here.
public func qualifiedFoo(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of struct 'struct_codable_member_type_lookup.NonSynthesizedStruct'}}
internal func qualifiedBar(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of struct 'struct_codable_member_type_lookup.NonSynthesizedStruct'}}
fileprivate func qualifiedBaz(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of struct 'struct_codable_member_type_lookup.NonSynthesizedStruct'}}
private func qualifiedQux(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of struct 'struct_codable_member_type_lookup.NonSynthesizedStruct'}}
// Unqualified lookups should find the public top-level CodingKeys type.
public func unqualifiedFoo(_ key: CodingKeys) { print(CodingKeys.topLevel) }
internal func unqualifiedBar(_ key: CodingKeys) { print(CodingKeys.topLevel) }
fileprivate func unqualifiedBaz(_ key: CodingKeys) { print(CodingKeys.topLevel) }
private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.topLevel) }
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
qux(CodingKeys.nested)
}
}
// MARK: - Explicit CodingKeys Enum
// Structs which explicitly define their own CodingKeys types should have
// visible CodingKey enums during member type lookup.
struct ExplicitStruct : Codable {
let value: String = "foo"
public enum CodingKeys {
case a
case b
case c
}
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: ExplicitStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExplicitStruct.CodingKeys) {}
fileprivate func qualifiedBaz(_ key: ExplicitStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExplicitStruct.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: ExplicitStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExplicitStruct.CodingKeys) {}
fileprivate func qualifiedBaz(_ key: ExplicitStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExplicitStruct.CodingKeys) {}
// Unqualified lookups should find the ExplicitStruct's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
// MARK: - CodingKeys Enums in Extensions
// Structs which get a CodingKeys type in an extension should be able to see
// that type during member type lookup.
struct ExtendedStruct : Codable {
let value: String = "foo"
// Don't get an auto-synthesized type.
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: ExtendedStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExtendedStruct.CodingKeys) {}
fileprivate func qualifiedBaz(_ key: ExtendedStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExtendedStruct.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: ExtendedStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExtendedStruct.CodingKeys) {}
fileprivate func qualifiedBaz(_ key: ExtendedStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExtendedStruct.CodingKeys) {}
// Unqualified lookups should find the ExtendedStruct's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
extension ExtendedStruct {
enum CodingKeys : String, CodingKey {
case a, b, c
}
}
struct A {
struct Inner : Codable {
var value: Int = 42
func foo() {
print(CodingKeys.value) // Not found on A.CodingKeys or top-level type.
}
}
}
extension A {
enum CodingKeys : String, CodingKey {
case a
}
}
struct B : Codable {
// So B conforms to Codable using CodingKeys.b below.
var b: Int = 0
struct Inner {
var value: Int = 42
func foo() {
print(CodingKeys.b) // Not found on top-level type.
}
}
}
extension B {
enum CodingKeys : String, CodingKey {
case b
}
}
struct C : Codable {
struct Inner : Codable {
var value: Int = 42
func foo() {
print(CodingKeys.value) // Not found on C.CodingKeys or top-level type.
}
}
}
extension C.Inner {
enum CodingKeys : String, CodingKey {
case value
}
}
struct GenericCodableStruct<T : Codable> : Codable {}
func foo(_: GenericCodableStruct<Int>.CodingKeys) // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
// https://github.com/apple/swift/issues/49435
struct S_49435 {
struct Nested : Codable {}
let Nested: Nested // Don't crash with a coding key that is the same as a nested type name
}
// Don't crash if we have a static property with the same name as an ivar that
// we will encode. We check the actual codegen in a SILGen test.
struct StaticInstanceNameDisambiguation : Codable {
static let version: Float = 0.42
let version: Int = 42
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'version' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{3-6=var}}
}
| apache-2.0 | 1649bc13f32793b5c99cbff8d27eb00f | 33.08806 | 197 | 0.695521 | 4.74922 | false | false | false | false |
yemeksepeti/YSForms | YSForms/YSForms/YSFormValidator.swift | 1 | 1722 | //
// YSFormValidator.swift
//
//
// Created by Cem Olcay on 25/06/15.
//
//
import UIKit
protocol YSFormValidatable {
var failMessage: String { get }
func validate (text: String) -> Bool
}
class YSFormRegexValidator: YSFormValidatable {
var regexRule = ""
var failMessage = ""
init (regexRule: String, failMessage: String) {
self.regexRule = regexRule
self.failMessage = failMessage
}
func validate (text: String) -> Bool {
let test = NSPredicate(format: "SELF MATCHES %@", regexRule)
return test.evaluateWithObject(text)
}
}
class YSFormRequiredValidator: YSFormValidatable {
var failMessage = ""
init (failMessage: String) {
self.failMessage = failMessage
}
func validate (text: String) -> Bool {
return count(text) > 0
}
}
enum YSFormValidator {
case Email
case Phone
case Required (failMessage: String)
func isValid (text: String, success: (() -> Void)?, fail: ((String) -> Void)?) {
var validator: YSFormValidatable!
switch self {
case .Email:
validator = YSFormRegexValidator(regexRule: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}", failMessage: "Email not valid")
case .Phone:
validator = YSFormRegexValidator(regexRule: "^\\d{10}$", failMessage: "Phone not valid")
case .Required (let message):
validator = YSFormRequiredValidator(failMessage: message)
}
if validator.validate(text) {
success? ()
} else {
fail? (validator.failMessage)
}
}
}
| mit | b0a48ce356b9f87645e04979060fe6b9 | 21.96 | 139 | 0.566783 | 4.404092 | false | false | false | false |
ivanbruel/Maya | Pod/Classes/MayaCalendarView.swift | 1 | 11824 | //
// MayaCalendarView.swift
// Pods
//
// Created by Ivan Bruel on 01/03/16.
//
//
import UIKit
public class MayaCalendarView: UIView {
private var backButton: UIButton = UIButton(type: .System)
private var forwardButton: UIButton = UIButton(type: .System)
private var monthLabel: UILabel = UILabel(frame: .zero)
private var collectionView: UICollectionView
private var collectionViewFlowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
public var dataSource: MayaCalendarDataSource? {
didSet {
reloadData()
}
}
public var delegate: MayaCalendarDelegate?
@IBOutlet public var ibDataSource: AnyObject? {
get { return dataSource }
set { dataSource = newValue as? MayaCalendarDataSource }
}
@IBOutlet public var ibDelegate: AnyObject? {
get { return delegate }
set { delegate = newValue as? MayaCalendarDelegate }
}
@IBInspectable public var monthFont: UIFont = .boldSystemFontOfSize(18) {
didSet {
monthLabel.font = monthFont
}
}
@IBInspectable public var weekdayFont: UIFont = .systemFontOfSize(15) {
didSet {
reloadData()
}
}
@IBInspectable public var dayFont: UIFont = .systemFontOfSize(16) {
didSet {
reloadData()
}
}
@IBInspectable public var weekdayTextColor: UIColor = UIColor.blackColor() {
didSet {
reloadData()
}
}
@IBInspectable public var backButtonImage: UIImage? = MayaButtonImage.leftArrowImage {
didSet {
backButton.setImage(backButtonImage, forState: .Normal)
}
}
@IBInspectable public var forwardButtonImage: UIImage? = MayaButtonImage.rightArrowImage {
didSet {
forwardButton.setImage(forwardButtonImage, forState: .Normal)
}
}
@IBInspectable public var headerHeight: CGFloat = 44 {
didSet {
setupButtonConstraints()
}
}
public var currentMonth: MayaMonth {
get {
return _currentMonth
}
set {
_currentMonth = newValue
scrollToMonth(_currentMonth)
}
}
private var _currentMonth: MayaMonth = MayaMonth(date: NSDate()) {
didSet {
if currentMonth.compare(firstMonth) == .OrderedAscending {
firstMonth = currentMonth
} else if currentMonth.compare(lastMonth) == .OrderedDescending {
lastMonth = currentMonth
}
UIView.transitionWithView(monthLabel, duration: 0.25, options: .TransitionCrossDissolve,
animations: { () -> Void in
self.monthLabel.text = self.dataSource?.calendarMonthName?(self.currentMonth) ??
self.currentMonth.name
}, completion: nil)
backButton.enabled = currentMonth.numberOfMonthsUntil(firstMonth) != 0
forwardButton.enabled = currentMonth.numberOfMonthsUntil(lastMonth) != 0
}
}
public var firstMonth: MayaMonth = MayaMonth(date: NSDate()) {
didSet {
reloadData()
}
}
public var lastMonth: MayaMonth = MayaMonth(date: NSDate()).monthWithOffset(12) {
didSet {
reloadData()
}
}
public var weekdays: [String] = ["su", "mo", "tu", "we", "th", "fr", "sa"] {
didSet {
reloadData()
}
}
override public var frame: CGRect {
didSet {
collectionViewFlowLayout.invalidateLayout()
}
}
override public init(frame: CGRect) {
collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewFlowLayout)
super.init(frame: frame)
setupViews()
}
required public init?(coder aDecoder: NSCoder) {
collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewFlowLayout)
super.init(coder: aDecoder)
setupViews()
}
override public func layoutSubviews() {
collectionViewFlowLayout.invalidateLayout()
collectionView.reloadData()
scrollToMonth(_currentMonth)
}
}
// MARK: Setup
extension MayaCalendarView {
private func setupViews() {
setupButtons()
setupMonthLabel()
setupCollectionView()
}
private func setupButtons() {
backButton.setImage(MayaButtonImage.leftArrowImage, forState: .Normal)
backButton.tintColor = UIColor.blackColor()
backButton.addTarget(self, action: #selector(MayaCalendarView.backClick),
forControlEvents: .TouchUpInside)
backButton.translatesAutoresizingMaskIntoConstraints = false
addSubview(backButton)
forwardButton.setImage(MayaButtonImage.rightArrowImage, forState: .Normal)
forwardButton.tintColor = UIColor.blackColor()
forwardButton.addTarget(self, action: #selector(MayaCalendarView.forwardClick),
forControlEvents: .TouchUpInside)
forwardButton.translatesAutoresizingMaskIntoConstraints = false
addSubview(forwardButton)
backButton.enabled = currentMonth.numberOfMonthsUntil(firstMonth) != 0
forwardButton.enabled = currentMonth.numberOfMonthsUntil(lastMonth) != 0
}
private func setupButtonConstraints() {
removeConstraints(backButton)
removeConstraints(forwardButton)
addConstraints(NSLayoutConstraint
.constraintsWithVisualFormat("H:|-0-[backButton(44)]",
options: [.AlignAllLeading], metrics: nil,
views: ["backButton": backButton]))
addConstraints(NSLayoutConstraint
.constraintsWithVisualFormat("V:|-0-[backButton(\(headerHeight))]",
options: [.AlignAllLeading], metrics: nil,
views: ["backButton": backButton]))
addConstraints(NSLayoutConstraint
.constraintsWithVisualFormat("H:[forwardButton(44)]-0-|",
options: [.AlignAllLeading], metrics: nil,
views: ["forwardButton": forwardButton]))
addConstraints(NSLayoutConstraint
.constraintsWithVisualFormat("V:|-0-[forwardButton(\(headerHeight))]",
options: [.AlignAllLeading], metrics: nil,
views: ["forwardButton": forwardButton]))
addConstraints(NSLayoutConstraint
.constraintsWithVisualFormat("H:[backButton]-8-[monthLabel]-8-[forwardButton]",
options: NSLayoutFormatOptions(rawValue: 0), metrics: nil,
views: ["monthLabel": monthLabel, "forwardButton": forwardButton,
"backButton": backButton]))
addConstraint(NSLayoutConstraint(item: monthLabel, attribute: .CenterY, relatedBy: .Equal,
toItem: backButton, attribute: .CenterY, multiplier: 1, constant: 0))
}
private func setupMonthLabel() {
monthLabel.font = monthFont
monthLabel.textAlignment = .Center
monthLabel.text = dataSource?.calendarMonthName?(currentMonth) ?? currentMonth.name
monthLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(monthLabel)
setupButtonConstraints()
}
private func setupCollectionView() {
collectionViewFlowLayout.sectionInset = UIEdgeInsetsZero
collectionViewFlowLayout.minimumLineSpacing = 0
collectionViewFlowLayout.minimumInteritemSpacing = 0
collectionView.collectionViewLayout = collectionViewFlowLayout
collectionViewFlowLayout.scrollDirection = .Horizontal
collectionView.showsHorizontalScrollIndicator = false
collectionView.pagingEnabled = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.clearColor()
collectionView.registerNib(UINib(nibName: "MayaCalendarMonthCollectionViewCell",
bundle: NSBundle(forClass: MayaCalendarView.self)),
forCellWithReuseIdentifier: "MayaCalendarMonthCollectionViewCell")
collectionView.translatesAutoresizingMaskIntoConstraints = false
addSubview(collectionView)
addConstraints(NSLayoutConstraint
.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|",
options: NSLayoutFormatOptions(rawValue: 0), metrics: nil,
views: ["collectionView": collectionView]))
addConstraints(NSLayoutConstraint
.constraintsWithVisualFormat("V:[monthLabel]-0-[collectionView]-0-|",
options: NSLayoutFormatOptions(rawValue: 0), metrics: nil,
views: ["monthLabel": monthLabel, "collectionView": collectionView]))
}
public func reloadData() {
monthLabel.text = dataSource?.calendarMonthName?(currentMonth) ?? currentMonth.name
collectionView.reloadData()
}
}
// MARK: Actions
extension MayaCalendarView {
@IBAction func backClick() {
scrollToMonth(currentMonth.previousMonth)
}
@IBAction func forwardClick() {
scrollToMonth(currentMonth.nextMonth)
}
private func scrollToMonth(month: MayaMonth) {
let index = firstMonth.numberOfMonthsUntil(month)
guard index <= firstMonth.numberOfMonthsUntil(lastMonth) && index >= 0 else {
return
}
let indexPath = NSIndexPath(forItem: index, inSection: 0)
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally,
animated: true)
}
}
// MARK: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
extension MayaCalendarView: UICollectionViewDataSource, UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout {
public func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView
.dequeueReusableCellWithReuseIdentifier("MayaCalendarMonthCollectionViewCell",
forIndexPath: indexPath)
if let cell = cell as? MayaCalendarMonthCollectionViewCell {
let month = monthForIndexPath(indexPath)
cell.viewModel = MayaMonthViewModel(month: month, weekdays: weekdays,
weekdayTextColor: weekdayTextColor, weekdayFont: weekdayFont, dayFont: dayFont,
dataSource: dataSource, dayClicked: dayClicked)
}
return cell
}
public func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return firstMonth.numberOfMonthsUntil(lastMonth) + 1
}
public func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: bounds.size.width, height: bounds.size.height - 44)
}
public func scrollViewDidScroll(scrollView: UIScrollView) {
let month = monthForIndexPath(NSIndexPath(forItem: currentPage(), inSection: 0))
if month != _currentMonth {
_currentMonth = month
delegate?.calendarDidChangeMonth?(_currentMonth)
}
}
}
// MARK: Helpers
extension MayaCalendarView {
private func dayClicked(date: MayaDate) {
if date.compare(currentMonth.firstDate) == .OrderedAscending {
scrollToMonth(currentMonth.previousMonth)
} else if date.compare(currentMonth.lastDate) == .OrderedDescending {
scrollToMonth(currentMonth.nextMonth)
}
delegate?.calendarDidSelectDate?(date)
}
private func monthForIndexPath(indexPath: NSIndexPath) -> MayaMonth {
if indexPath.row == 0 {
return firstMonth
}
return firstMonth.monthWithOffset(indexPath.item)
}
private func currentPage() -> Int {
let currentPage = self.collectionView.contentOffset.x / self.collectionView.frame.size.width
return Int(round(currentPage))
}
private func removeConstraints(view: UIView) {
var list = [NSLayoutConstraint]()
if let superview = view.superview {
for constraint in superview.constraints {
if constraint.firstItem as? UIView == view || constraint.secondItem as? UIView == view {
list.append(constraint)
}
}
view.superview?.removeConstraints(list)
view.removeConstraints(view.constraints)
}
}
} | mit | 6b5c41b5c0bd46100e535a56ea5ca346 | 32.498584 | 121 | 0.697818 | 5.548569 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK | BridgeAppSDKTests/SBAOnboardingManagerTests.swift | 1 | 22303 | //
// SBAOnboardingManagerTests.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import XCTest
import BridgeAppSDK
class SBAOnboardingManagerTests: ResourceTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testCreateManager() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")
XCTAssertNotNil(manager)
XCTAssertNotNil(manager?.sections)
guard let sections = manager?.sections else { return }
XCTAssertEqual(sections.count, 8)
}
func testShouldInclude() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")!
let expectedNonNil: [SBAOnboardingSectionBaseType : [SBAOnboardingTaskType]] = [
.login: [.login],
.eligibility: [.signup],
.consent: [.login, .signup, .reconsent],
.registration: [.signup],
.passcode: [.login, .signup, .reconsent],
.emailVerification: [.signup],
.permissions: [.login, .signup],
.profile: [.signup],
.completion: [.login, .signup]]
for sectionType in SBAOnboardingSectionBaseType.all {
let include = expectedNonNil[sectionType]
XCTAssertNotNil(include, "\(sectionType)")
if include != nil {
for taskType in SBAOnboardingTaskType.all {
let expectedShouldInclude = include!.contains(taskType)
let section: NSDictionary = ["onboardingType": sectionType.rawValue]
let shouldInclude = manager.shouldInclude(section: section, onboardingTaskType: taskType)
XCTAssertEqual(shouldInclude, expectedShouldInclude, "\(sectionType) \(taskType)")
}
}
}
}
func testShouldInclude_HasPasscode() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")!
manager._hasPasscode = true
// Check that if the passcode has been set that it is not included
for taskType in SBAOnboardingTaskType.all {
let section: NSDictionary = ["onboardingType": SBAOnboardingSectionBaseType.passcode.rawValue]
let shouldInclude = manager.shouldInclude(section: section, onboardingTaskType: taskType)
XCTAssertFalse(shouldInclude, "\(taskType)")
}
}
func testShouldInclude_HasRegistered() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")!
// If the user has registered and this is a completion of the registration
// then only include email verification and those sections AFTER verification
// However, if the user is being reconsented then include the reconsent section
manager.mockAppDelegate.mockCurrentUser.isRegistered = true
manager._hasPasscode = true
let taskTypes: [SBAOnboardingTaskType] = [.signup, .reconsent]
let expectedNonNil: [SBAOnboardingSectionBaseType : [SBAOnboardingTaskType]] = [
.login: [.login],
// eligibility should *not* be included in registration if the user is at the email verification step
.eligibility: [],
// consent should *not* be included in registration if the user is at the email verification step
.consent: [.login, .reconsent],
// registration should *not* be included in registration if the user is at the email verification step
.registration: [],
// passcode should *not* be included in registration if the user is at the email verification step
// and has already set the passcode
.passcode: [],
.emailVerification: [.signup],
.permissions: [.login, .signup],
.profile: [.signup],
.completion: [.login, .signup]]
for sectionType in SBAOnboardingSectionBaseType.all {
let include = expectedNonNil[sectionType]
XCTAssertNotNil(include, "\(sectionType)")
if include != nil {
for taskType in taskTypes {
let expectedShouldInclude = include!.contains(taskType)
let section: NSDictionary = ["onboardingType": sectionType.rawValue]
let shouldInclude = manager.shouldInclude(section: section, onboardingTaskType: taskType)
XCTAssertEqual(shouldInclude, expectedShouldInclude, "\(sectionType) \(taskType)")
}
}
}
}
func testSortOrder() {
let inputSections = [
["onboardingType" : "customWelcome"],
["onboardingType" : "consent"],
["onboardingType" : "passcode"],
["onboardingType" : "emailVerification"],
["onboardingType" : "registration"],
["onboardingType" : "login"],
["onboardingType" : "eligibility"],
["onboardingType" : "profile"],
["onboardingType" : "permissions"],
["onboardingType" : "completion"],
["onboardingType" : "customEnd"],]
let input: NSDictionary = ["sections" : inputSections];
guard let sections = SBAOnboardingManager(dictionary: input).sections else {
XCTAssert(false, "failed to create onboarding manager sections")
return
}
let expectedOrder = ["customWelcome",
"login",
"eligibility",
"consent",
"registration",
"passcode",
"emailVerification",
"permissions",
"profile",
"completion",
"customEnd",]
let actualOrder = sections.sba_mapAndFilter({ $0.onboardingSectionType?.identifier })
XCTAssertEqual(actualOrder, expectedOrder)
}
func testEligibilitySection() {
guard let steps = checkOnboardingSteps( .base(.eligibility), .signup) else { return }
let expectedSteps: [ORKStep] = [SBAToggleFormStep(identifier: "inclusionCriteria"),
SBAInstructionStep(identifier: "ineligibleInstruction"),
SBAInstructionStep(identifier: "eligibleInstruction")]
XCTAssertEqual(steps.count, expectedSteps.count)
for (idx, expectedStep) in expectedSteps.enumerated() {
if idx < steps.count {
XCTAssertEqual(steps[idx].identifier, expectedStep.identifier)
let stepClass = NSStringFromClass(steps[idx].classForCoder)
let expectedStepClass = NSStringFromClass(expectedStep.classForCoder)
XCTAssertEqual(stepClass, expectedStepClass)
}
}
}
func testPasscodeSection() {
guard let steps = checkOnboardingSteps( .base(.passcode), .signup) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? ORKPasscodeStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "passcode")
XCTAssertEqual(step.passcodeType, ORKPasscodeType.type4Digit)
XCTAssertEqual(step.title, "Identification")
XCTAssertEqual(step.text, "Select a 4-digit passcode. Setting up a passcode will help provide quick and secure access to this application.")
}
func testLoginSection() {
guard let steps = checkOnboardingSteps( .base(.login), .login) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? SBALoginStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "login")
}
func testRegistrationSection() {
guard let steps = checkOnboardingSteps( .base(.registration), .signup) else { return }
XCTAssertEqual(steps.count, 2)
guard let step1 = steps.first as? SBASinglePermissionStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step1.identifier, "healthKitPermissions")
guard let step2 = steps.last as? SBARegistrationStep else {
XCTAssert(false, "\(String(describing: steps.last)) not of expected type")
return
}
XCTAssertEqual(step2.identifier, "registration")
}
func testEmailVerificationSection() {
guard let steps = checkOnboardingSteps( .base(.emailVerification), .signup) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? SBAEmailVerificationStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "emailVerification")
}
func testProfileSection() {
guard let steps = checkOnboardingSteps( .base(.profile), .signup) else { return }
XCTAssertEqual(steps.count, 3)
for step in steps {
XCTAssertTrue(step is SBAProfileFormStep)
}
}
func testPermissionsSection() {
guard let steps = checkOnboardingSteps( .base(.permissions), .signup) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? SBAPermissionsStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "permissions")
}
func testCreateTask_Login() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
guard let task = manager.createTask(for: .login) else {
XCTAssert(false, "Created task is nil")
return
}
let expectedCount = 4
XCTAssertEqual(task.steps.count, expectedCount)
guard task.steps.count == expectedCount else {
XCTAssert(false, "Exit early b/c step count doesn't match expected")
return
}
var ii = 0
XCTAssertTrue(task.steps[ii] is SBALoginStep)
XCTAssertEqual(task.steps[ii].identifier, "login")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "consent")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is ORKPasscodeStep)
XCTAssertEqual(task.steps[ii].identifier, "passcode")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAPermissionsStep)
XCTAssertEqual(task.steps[ii].identifier, "permissions")
}
func testCreateTask_SignUp_Row0() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
guard let task = manager.createTask(for: .signup, tableRow: 0) else {
XCTAssert(false, "Created task is nil")
return
}
let expectedCount = 7
XCTAssertEqual(task.steps.count, expectedCount)
guard task.steps.count == expectedCount else {
XCTAssert(false, "Exit early b/c step count doesn't match expected")
return
}
var ii = 0
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "eligibility")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "consent")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "registration")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is ORKPasscodeStep)
XCTAssertEqual(task.steps[ii].identifier, "passcode")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAEmailVerificationStep)
XCTAssertEqual(task.steps[ii].identifier, "emailVerification")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAPermissionsStep)
XCTAssertEqual(task.steps[ii].identifier, "permissions")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "profile")
}
func testCreateTask_SignUp_Row2() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
guard let task = manager.createTask(for: .signup, tableRow: 2) else {
XCTAssert(false, "Created task is nil")
return
}
let expectedCount = 5
XCTAssertEqual(task.steps.count, expectedCount)
guard task.steps.count == expectedCount else {
XCTAssert(false, "Exit early b/c step count doesn't match expected")
return
}
var ii = 0
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "registration")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is ORKPasscodeStep)
XCTAssertEqual(task.steps[ii].identifier, "passcode")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAEmailVerificationStep)
XCTAssertEqual(task.steps[ii].identifier, "emailVerification")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAPermissionsStep)
XCTAssertEqual(task.steps[ii].identifier, "permissions")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "profile")
}
func testSignupState() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
let eligibilityState1 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState1, .current)
let consentState1 = manager.signupState(for: 1)
XCTAssertEqual(consentState1, .locked)
let registrationState1 = manager.signupState(for: 2)
XCTAssertEqual(registrationState1, .locked)
let profileState1 = manager.signupState(for: 3)
XCTAssertEqual(profileState1, .locked)
// For any step in the consent flow except the last, then the consent is the current section
manager.sharedUser.onboardingStepIdentifier = "eligibility.eligibleInstruction"
let eligibilityState2 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState2, .completed)
let consentState2 = manager.signupState(for: 1)
XCTAssertEqual(consentState2, .current)
let registrationState2 = manager.signupState(for: 2)
XCTAssertEqual(registrationState2, .locked)
let profileState2 = manager.signupState(for: 3)
XCTAssertEqual(profileState2, .locked)
// Once we enter the consent flow then that becomes the current section
manager.sharedUser.onboardingStepIdentifier = "consent.consentVisual"
let eligibilityState3 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState3, .completed)
let consentState3 = manager.signupState(for: 1)
XCTAssertEqual(consentState3, .current)
let registrationState3 = manager.signupState(for: 2)
XCTAssertEqual(registrationState3, .locked)
let profileState3 = manager.signupState(for: 3)
XCTAssertEqual(profileState3, .locked)
// For any step in the consent flow except the last, then the consent is the current section
manager.sharedUser.onboardingStepIdentifier = "consent.consentCompletion"
let eligibilityState4 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState4, .completed)
let consentState4 = manager.signupState(for: 1)
XCTAssertEqual(consentState4, .completed)
let registrationState4 = manager.signupState(for: 2)
XCTAssertEqual(registrationState4, .current)
let profileState4 = manager.signupState(for: 3)
XCTAssertEqual(profileState4, .locked)
// Set the steps to the registration section
manager.sharedUser.onboardingStepIdentifier = "registration.registration"
let eligibilityState5 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState5, .completed)
let consentState5 = manager.signupState(for: 1)
XCTAssertEqual(consentState5, .completed)
let registrationState5 = manager.signupState(for: 2)
XCTAssertEqual(registrationState5, .current)
let profileState5 = manager.signupState(for: 3)
XCTAssertEqual(profileState5, .locked)
// For registration, there isn't a completion step and the final step is email verification
// so the current section remains the email verification *until* login is verified
manager.sharedUser.isRegistered = true
manager.sharedUser.isLoginVerified = false
manager.sharedUser.isConsentVerified = false
manager.sharedUser.onboardingStepIdentifier = "emailVerification"
let eligibilityState6 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState6, .completed)
let consentState6 = manager.signupState(for: 1)
XCTAssertEqual(consentState6, .completed)
let registrationState6 = manager.signupState(for: 2)
XCTAssertEqual(registrationState6, .current)
let profileState6 = manager.signupState(for: 3)
XCTAssertEqual(profileState6, .locked)
// Once login and consent are verified, then ready for the profile section
manager.sharedUser.isLoginVerified = true
manager.sharedUser.isConsentVerified = true
let eligibilityState7 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState7, .completed)
let consentState7 = manager.signupState(for: 1)
XCTAssertEqual(consentState7, .completed)
let registrationState7 = manager.signupState(for: 2)
XCTAssertEqual(registrationState7, .completed)
let profileState7 = manager.signupState(for: 3)
XCTAssertEqual(profileState7, .current)
manager.sharedUser.onboardingStepIdentifier = "SBAOnboardingCompleted"
let eligibilityState8 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState8, .completed)
let consentState8 = manager.signupState(for: 1)
XCTAssertEqual(consentState8, .completed)
let registrationState8 = manager.signupState(for: 2)
XCTAssertEqual(registrationState8, .completed)
let profileState8 = manager.signupState(for: 3)
XCTAssertEqual(profileState8, .completed)
}
func checkOnboardingSteps(_ sectionType: SBAOnboardingSectionType, _ taskType: SBAOnboardingTaskType) -> [ORKStep]? {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")
let section = manager?.section(for: sectionType)
XCTAssertNotNil(section, "sectionType:\(sectionType) taskType:\(taskType)")
guard section != nil else { return nil}
let steps = manager?.steps(for: section!, with: taskType)
XCTAssertNotNil(steps, "sectionType:\(sectionType) taskType:\(taskType)")
return steps
}
}
class MockOnboardingManager: SBAOnboardingManager {
var mockAppDelegate:MockAppInfoDelegate = MockAppInfoDelegate()
override var sharedAppDelegate: SBAAppInfoDelegate {
get { return mockAppDelegate }
set {}
}
var _hasPasscode = false
override var hasPasscode: Bool {
return _hasPasscode
}
}
| bsd-3-clause | ca5ddbc9b0dabdf09fa93c0176f99a40 | 39.771481 | 148 | 0.627881 | 5.392166 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-422/SafeRide/Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift | 6 | 5533 | //
// ChaCha20.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 25/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
final public class ChaCha20: BlockCipher {
public enum Error: ErrorType {
case MissingContext
}
static let blockSize = 64 // 512 / 8
private let stateSize = 16
private var context:Context?
final private class Context {
var input:[UInt32] = [UInt32](count: 16, repeatedValue: 0)
deinit {
for i in 0..<input.count {
input[i] = 0x00;
}
}
}
public init?(key:[UInt8], iv:[UInt8]) {
if let c = contextSetup(iv: iv, key: key) {
context = c
} else {
return nil
}
}
public func encrypt(bytes:[UInt8]) throws -> [UInt8] {
guard context != nil else {
throw Error.MissingContext
}
return try encryptBytes(bytes)
}
public func decrypt(bytes:[UInt8]) throws -> [UInt8] {
return try encrypt(bytes)
}
private final func wordToByte(input:[UInt32] /* 64 */) -> [UInt8]? /* 16 */ {
if (input.count != stateSize) {
return nil;
}
var x = input
for _ in 0..<10 {
quarterround(&x[0], &x[4], &x[8], &x[12])
quarterround(&x[1], &x[5], &x[9], &x[13])
quarterround(&x[2], &x[6], &x[10], &x[14])
quarterround(&x[3], &x[7], &x[11], &x[15])
quarterround(&x[0], &x[5], &x[10], &x[15])
quarterround(&x[1], &x[6], &x[11], &x[12])
quarterround(&x[2], &x[7], &x[8], &x[13])
quarterround(&x[3], &x[4], &x[9], &x[14])
}
var output = [UInt8]()
output.reserveCapacity(16)
for i in 0..<16 {
x[i] = x[i] &+ input[i]
output.appendContentsOf(x[i].bytes().reverse())
}
return output;
}
private func contextSetup(iv iv:[UInt8], key:[UInt8]) -> Context? {
let ctx = Context()
let kbits = key.count * 8
if (kbits != 128 && kbits != 256) {
return nil
}
// 4 - 8
for i in 0..<4 {
let start = i * 4
ctx.input[i + 4] = wordNumber(key[start..<(start + 4)])
}
var addPos = 0;
switch (kbits) {
case 256:
addPos += 16
// sigma
ctx.input[0] = 0x61707865 //apxe
ctx.input[1] = 0x3320646e //3 dn
ctx.input[2] = 0x79622d32 //yb-2
ctx.input[3] = 0x6b206574 //k et
default:
// tau
ctx.input[0] = 0x61707865 //apxe
ctx.input[1] = 0x3620646e //6 dn
ctx.input[2] = 0x79622d31 //yb-1
ctx.input[3] = 0x6b206574 //k et
break;
}
// 8 - 11
for i in 0..<4 {
let start = addPos + (i*4)
let bytes = key[start..<(start + 4)]
ctx.input[i + 8] = wordNumber(bytes)
}
// iv
ctx.input[12] = 0
ctx.input[13] = 0
ctx.input[14] = wordNumber(iv[0..<4])
ctx.input[15] = wordNumber(iv[4..<8])
return ctx
}
private final func encryptBytes(message:[UInt8]) throws -> [UInt8] {
guard let ctx = context else {
throw Error.MissingContext
}
var c:[UInt8] = [UInt8](count: message.count, repeatedValue: 0)
var cPos:Int = 0
var mPos:Int = 0
var bytes = message.count
while (true) {
if let output = wordToByte(ctx.input) {
ctx.input[12] = ctx.input[12] &+ 1
if (ctx.input[12] == 0) {
ctx.input[13] = ctx.input[13] &+ 1
/* stopping at 2^70 bytes per nonce is user's responsibility */
}
if (bytes <= ChaCha20.blockSize) {
for i in 0..<bytes {
c[i + cPos] = message[i + mPos] ^ output[i]
}
return c
}
for i in 0..<ChaCha20.blockSize {
c[i + cPos] = message[i + mPos] ^ output[i]
}
bytes -= ChaCha20.blockSize
cPos += ChaCha20.blockSize
mPos += ChaCha20.blockSize
}
}
}
private final func quarterround(inout a:UInt32, inout _ b:UInt32, inout _ c:UInt32, inout _ d:UInt32) {
a = a &+ b
d = rotateLeft((d ^ a), 16) //FIXME: WAT? n:
c = c &+ d
b = rotateLeft((b ^ c), 12);
a = a &+ b
d = rotateLeft((d ^ a), 8);
c = c &+ d
b = rotateLeft((b ^ c), 7);
}
}
// MARK: - Cipher
extension ChaCha20: CipherProtocol {
public func cipherEncrypt(bytes:[UInt8]) throws -> [UInt8] {
return try self.encrypt(bytes)
}
public func cipherDecrypt(bytes: [UInt8]) throws -> [UInt8] {
return try self.decrypt(bytes)
}
}
// MARK: Helpers
/// Change array to number. It's here because arrayOfBytes is too slow
private func wordNumber(bytes:ArraySlice<UInt8>) -> UInt32 {
var value:UInt32 = 0
for i:UInt32 in 0..<4 {
let j = bytes.startIndex + Int(i)
value = value | UInt32(bytes[j]) << (8 * i)
}
return value}
| gpl-3.0 | add192f008d586ebcc5884dca319d503 | 26.665 | 107 | 0.460148 | 3.748645 | false | false | false | false |
GrantOMeter/server | Sources/libgrumpy/MiddleWare/ErrorMiddleware.swift | 2 | 2683 | //
// Copyright 2016-2017 Oliver Guntli
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
//
import HTTP
import Vapor
import Foundation
/// Handles the various Abort errors that are handled by the Vapors AbortMiddleware
/// To stop this and revert back to the default configuration, just remove
/// the ErrorMiddle from the Droplet's `middleware` array
class ErrorMiddleware: Middleware {
init() { }
/// Respond to a given request chaining to the next
/// parameter request: request to process
/// parameter chain: next responder to pass request to
/// throws: an error on failure
/// returns: a valid response
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
do {
return try next.respond(to: request)
} catch let error as AbortError {
return try ErrorMiddleware.errorResponse(request, error)
} catch {
return try ErrorMiddleware.errorResponse(request, .internalServerError, error.localizedDescription)
}
}
/// This is for custom error messages
/// - parameter request: The request to process
/// - parameter status: The http status to return as response
/// - parameter message: The message that should be displayed eg "Page not found"
/// - returns: a response containing the http status and a message
static func errorResponse(_ request: Request, _ status: Status, _ message: String) throws -> Response {
let error = Abort.custom(status: status, message: message)
return try errorResponse(request, error)
}
/// The general approach to error messages.
/// Error pages are also handled here
/// - parameter request: The request to process
/// - parameter error: An abort error that should be returned as response message
/// - returns: a response containing the http status and a message
static func errorResponse(_ request: Request, _ error: AbortError) throws -> Response {
if request.accept.prefers("html") {
return ErrorView.shared.makeResponse(error.status, error.message)
}
let json = try JSON(node: [
"error": true,
"message": "\(error.message)",
"code": error.code,
])
let data = try json.makeBytes()
let response = Response(status: error.status, body: .data(data))
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response
}
}
| mpl-2.0 | 2acc001571a27288fee804bc87d7ffc4 | 38.455882 | 111 | 0.656355 | 4.657986 | false | false | false | false |
apatronl/Left | Left/Services/FavoritesManager.swift | 1 | 1738 | //
// FavoritesManager.swift
// Left
//
// Created by Alejandrina Patron on 3/4/16.
// Copyright © 2016 Ale Patrón. All rights reserved.
//
import Foundation
class FavoritesManager {
// Singleton
static let shared = FavoritesManager()
private var favoriteRecipes = [RecipeItem]()
func addRecipe(recipe: RecipeItem) {
favoriteRecipes.append(recipe)
save()
}
func deleteRecipeAtIndex(index: Int) {
favoriteRecipes.remove(at: index)
save()
}
func recipeAtIndex(index: Int) -> RecipeItem? {
return favoriteRecipes[index]
}
func recipeCount() -> Int {
return favoriteRecipes.count
}
func archivePath() -> String? {
let directoryList = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if let documentsPath = directoryList.first {
return documentsPath + "/Favorites"
}
assertionFailure("Could not determine where to save file.")
return nil
}
func save() {
if let theArchivePath = archivePath() {
if NSKeyedArchiver.archiveRootObject(favoriteRecipes, toFile: theArchivePath) {
print("We saved!")
} else {
assertionFailure("Could not save to \(theArchivePath)")
}
}
}
func unarchivedSavedItems() {
if let theArchivePath = archivePath() {
if FileManager.default.fileExists(atPath: theArchivePath) {
favoriteRecipes = NSKeyedUnarchiver.unarchiveObject(withFile: theArchivePath) as! [RecipeItem]
}
}
}
init() {
unarchivedSavedItems()
}
}
| mit | 9b80d897e5ec638db8a2df7bde68969f | 25.30303 | 110 | 0.599078 | 5.18209 | false | false | false | false |
Resoulte/DYZB | DYZB/DYZB/Classes/Home/View/DYAmuseCollectionCell.swift | 1 | 1726 | //
// DYAmuseCollectionCell.swift
// DYZB
//
// Created by ma c on 16/11/7.
// Copyright © 2016年 shifei. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
class DYAmuseCollectionCell: UICollectionViewCell {
var groups : [DYAnchorGroupItem]? {
didSet {
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "DYCollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let itemW = collectionView.bounds.width / 4
let itemH = collectionView.bounds.height / 2
layout.itemSize = CGSize(width: itemW, height: itemH)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
}
}
extension DYAmuseCollectionCell : UICollectionViewDataSource
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! DYCollectionGameCell
// cell.backgroundColor = UIColor.randomColor()
cell.baseItem = groups?[indexPath.item]
cell.clipsToBounds = true
return cell
}
}
| mit | a938ef555916a3d3f6d12007f0fc58b2 | 28.20339 | 128 | 0.671503 | 5.452532 | false | false | false | false |
wl879/SwiftyCss | SwiftyCss/SwiftyCss/CAStyle/Listener.swift | 1 | 4513 | //
// Listener.swift
// SwiftyCss
//
// Created by Wang Liang on 2017/5/3.
// Copyright © 2017年 Wang Liang. All rights reserved.
//
import UIKit
import SwiftyNode
import SwiftyBox
class Listener: NSObject {
private var cache = [String: WeakArray<NSObject>]()
final func has(target: NSObject, key: String) -> Bool {
if cache[key] != nil {
for i in (0 ..< cache[key]!.count).reversed() {
if cache[key]![i] != nil {
if cache[key]![i]! === target {
return true
}
}
}
}
return false
}
final func add(target: NSObject, key: String, options: NSKeyValueObservingOptions = [], context: UnsafeMutableRawPointer? = nil ) -> Bool{
if self.has(target: target, key: key) {
return false
}else if cache[key] == nil {
cache[key] = WeakArray<NSObject>()
}
cache[key]!.append( target )
target.addObserver( self, forKeyPath: key, options: options, context: context)
return true
}
final func remove(target: NSObject, key: String, context: UnsafeMutableRawPointer? = nil) -> Bool {
if self.has(target: target, key: key) {
target.removeObserver(self, forKeyPath: key, context: context)
return true
}
return false
}
}
class ListenerWindow: Listener {
override final func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath, let window = object as? CALayer else {
return
}
switch keyPath {
case "bounds":
Css.refresh(window, async: true)
default:
break
}
}
}
class ListenerCALayer: Listener {
override final func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath, let layer = object as? CALayer, let styler = layer.value(forKey: "_node_style_") as? CAStyler else {
return
}
if styler.disable || styler.status.contains(.updating) {
return
}
switch keyPath {
case "sublayers":
if styler.status.contains(.inactive) || styler.status.contains(.lazy) {
return
}
let old = styler._oldSublayers
let count = layer.sublayers?.count ?? 0
if count > old {
for sub in layer.sublayers! {
if sub.cssStyler.disable {
continue
}
if sub.cssStyler.status.contains(.inactive) {
#if DEBUG
debug.begin(tag: "watch")
#endif
sub.cssStyler.refresh(spread: true)
#if DEBUG
debug.end(tag: "watch", sub.cssStyler)
#endif
}
}
}else if count > 0 {
styler.setStatus( .checkChild )
}
styler._oldSublayers = count
case "bounds":
if styler.status.contains(.inactive) || styler.status.contains(.lazy) {
return
}
guard let new = change?[.newKey] as? CGRect, let old = change?[.oldKey] as? CGRect else {
return
}
if new.size == old.size {
return
}
if styler.property["float"] != nil {
layer.superlayer?.cssStyler.setStatus( .rankFloatChild )
}else if !styler.hooks.isEmpty {
styler.setStatus( .checkHookChild )
}
case "hidden":
guard let hidden = change?[.newKey] as? Bool, layer.superlayer != nil else {
return
}
if !hidden {
styler.setStatus( .needRefresh )
}else{
if styler.property["float"] != nil {
layer.superlayer?.cssStyler.setStatus( .rankFloatChild )
}
}
default:
break
}
#if DEBUG
debug.log(tag: "listen", keyPath, styler.status, styler)
#endif
}
}
| mit | 0289c5fe98041fcc5ffb13fcff713d9c | 31.919708 | 157 | 0.5 | 4.96696 | false | false | false | false |
ivanbruel/SwipeIt | SwipeIt/Extensions/UIImage+Scale/UIImage+Scale.swift | 1 | 946 | //
// UIImage+Scale.swift
// SwipeIt
//
// Created by Ivan Bruel on 25/08/16.
// Copyright © 2016 Faber Ventures. All rights reserved.
//
import UIKit
import AVFoundation
extension UIImage {
func scaleToSizeWithAspectFill(size: CGSize) -> UIImage {
let ratio = self.size.ratio
let maxSize = max(size.width, size.height)
let width = ratio > 1 ? maxSize * ratio : maxSize
let height = ratio > 1 ? maxSize : maxSize * ratio
return scaleToSizeWithAspectFit(CGSize(width: width, height: height))
}
func scaleToSizeWithAspectFit(size: CGSize) -> UIImage {
let scaledRect = AVMakeRectWithAspectRatioInsideRect(self.size,
CGRect(origin: .zero, size: size))
UIGraphicsBeginImageContextWithOptions(size, false, 0)
drawInRect(scaledRect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| mit | d17c62b5470480fed99e7de5aaba16f6 | 29.483871 | 91 | 0.677249 | 4.565217 | false | false | false | false |
Teleglobal/MHQuickBlockLib | MHQuickBlockLib/Classes/ChatPushNotification.swift | 1 | 5001 | //
// AppPushNotification.swift
// Pods
//
// Created by Muhammad Adil on 8/8/16.
//
//
import Quickblox
// http://quickblox.com/developers/SimpleSample-messages_users-ios#Sending_Push_Notifications
extension AppMessenger {
/**
*
*
*/
public func unregisterForChatNotifications(
deviceId: UInt,
successBlock: ((QBResponse) -> Void)?,
errorBlock: qb_response_block_t?) {
QBRequest.deleteSubscription(withID: deviceId,
successBlock: { (response) in
successBlock!(response)
}, errorBlock: { (error) in
errorBlock!(error)
})
}
/**
*
*
*/
public func registerForChatNotifications(
deviceIdentifier: String,
deviceToken: Data,
successBlock: ((QBResponse, [QBMSubscription]?) -> Void)?,
errorBlock: qb_response_block_t?) {
let subscription: QBMSubscription! = QBMSubscription()
subscription.notificationChannel = .APNS
subscription.deviceUDID = deviceIdentifier
subscription.deviceToken = deviceToken
QBRequest.createSubscription(subscription,
successBlock: { (response: QBResponse!, objects: [QBMSubscription]?) -> Void in
successBlock!(response, objects)
//
}, errorBlock: { (response: QBResponse!) -> Void in
errorBlock!(response)
})
}
/**
*
*
*/
public func sendUniversalPushNotificationToUsers(users : [String],
_ message: String,
_ dialogId: String,
_ sound: String = "ringtone.wav") {
let event = QBMEvent()
event.notificationType = .push
event.usersIDs = users.joined(separator: ",")
event.type = .oneShot
var dictPush = ["message" : message,
"ios_sound" : sound,
"qbNotificationType" : "2",
"dialog_id" : dialogId,
"user_id" : "\(Messenger.chatAuthServiceManager.currentUser()!.id)"] as [String : Any]
if sound == "ringtone.wav" {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm"
let currentDate = dateFormatter.string(from: Date())
dictPush["timestamp"] = currentDate
dictPush["qbNotificationType"] = "1"
}
do {
let data = try JSONSerialization.data(withJSONObject: dictPush,
options: .prettyPrinted)
event.message = String(data: data,
encoding: .utf8)
QBRequest.createEvent(event,
successBlock: { (response, events) in },
errorBlock: { (error) in})
} catch _ {
}
}
/**
*
*
*/
public func sendPushNotificationToiOSUsers(users : [String],
_ message: String) {
let aps : [String : String] = [QBMPushMessageSoundKey : "default",
QBMPushMessageAlertKey : message]
let payLoad_ : [String : Any] = [QBMPushMessageApsKey : aps]
let pushMessage = QBMPushMessage(payload: payLoad_ as! [String : String])
QBRequest.sendPush(pushMessage,
toUsers: users.joined(separator: ","),
successBlock: { (response, event) in },
errorBlock: { (error) in })
}
public func sendVOIPPushNotifcationToUsers(users : [String],
_ message: String) {
let aps : [String : String] = [QBMPushMessageSoundKey : "default",
QBMPushMessageAlertKey : message]
let payLoad_ : [String : Any] = [QBMPushMessageApsKey : aps]
let pushMessage = QBMPushMessage(payload: payLoad_ as! [String : String])
QBRequest.sendVoipPush(pushMessage, toUsers: users.joined(separator: ","), successBlock: { (response, event) in
}) { (error) in
}
}
}
| mit | a6f6900b38a31ef850f0fa214be83664 | 31.901316 | 119 | 0.453109 | 5.748276 | false | false | false | false |
clappr/clappr-ios | Tests/Clappr_Tests/Classes/Plugin/Container/PosterPluginTests.swift | 1 | 5636 | import Quick
import Nimble
@testable import Clappr
class PosterPluginTests: QuickSpec {
override func spec() {
describe(".PosterPlugin") {
var core: Core!
var layerComposer: LayerComposer!
let options = [
kSourceUrl: "http://globo.com/video.mp4",
kPosterUrl: "http://clappr.io/poster.png",
]
beforeEach {
layerComposer = LayerComposer()
Loader.shared.register(plugins: [PosterPlugin.self])
}
afterEach {
layerComposer = nil
Loader.shared.resetPlugins()
}
context("when core has no options") {
it("hides itself") {
core = CoreFactory.create(with: [:], layerComposer: layerComposer)
core.render()
let posterPlugin = self.getPosterPlugin(core)
expect(posterPlugin.view.isHidden).to(beTrue())
}
}
context("when core doesnt have posterUrl option") {
it("hides itself") {
core = CoreFactory.create(with: ["anotherOption": true], layerComposer: layerComposer)
core.render()
let posterPlugin = self.getPosterPlugin(core)
expect(posterPlugin.view.isHidden).to(beTrue())
}
}
context("when core has posterUrl option") {
it("it renders itself") {
core = CoreFactory.create(with: options, layerComposer: layerComposer)
core.render()
let posterPlugin = self.getPosterPlugin(core)
expect(posterPlugin.view.superview).to(equal(core.overlayView))
}
}
context("when changes the activePlayback") {
var posterPlugin: PosterPlugin!
beforeEach {
core = CoreFactory.create(with: [:], layerComposer: layerComposer)
}
context("to NoOpPlayback") {
beforeEach {
core.activeContainer?.playback = NoOpPlayback(options: [:])
posterPlugin = self.getPosterPlugin(core)
}
it("hides itself") {
expect(posterPlugin.view.isHidden).toEventually(beTrue())
}
it("isNoOpPlayback is true") {
expect(posterPlugin.activePlayback).to(beAKindOf(NoOpPlayback.self))
}
context("and change again to another playback") {
beforeEach {
core.activeContainer?.playback = AVFoundationPlayback(options: [:])
posterPlugin = self.getPosterPlugin(core)
}
it("hides itself") {
expect(posterPlugin.view.isHidden).toEventually(beTrue())
}
}
}
context("to another a playback diferent from NoOpPlayback") {
beforeEach {
core.activeContainer?.playback = AVFoundationPlayback(options: [:])
posterPlugin = self.getPosterPlugin(core)
}
it("reveal itself") {
expect(posterPlugin.view.isHidden).toEventually(beFalse())
}
it("isNoOpPlayback is false") {
expect(posterPlugin).toNot(beAKindOf(NoOpPlayback.self))
}
}
}
describe("Playback Events") {
var posterPlugin: PosterPlugin!
beforeEach {
core = CoreFactory.create(with: options, layerComposer: layerComposer)
core.load()
posterPlugin = self.getPosterPlugin(core)
}
context("when playback trigger a play event") {
it("hides itself") {
core.activeContainer?.playback?.trigger(Event.playing.rawValue)
expect(posterPlugin.view.isHidden).to(beTrue())
}
}
context("when playback trigger a end event") {
it("do not reveal itself") {
core.activeContainer?.playback?.trigger(Event.playing.rawValue)
core.activeContainer?.playback?.trigger(Event.didComplete.rawValue)
expect(posterPlugin.view.isHidden).to(beTrue())
}
}
}
context("When play button is pressed") {
it("starts the video at the beginning") {
let core = CoreStub()
core.render()
let posterPlugin = self.getPosterPlugin(core)
posterPlugin.playTouched()
expect(core.playbackMock?.didCallPlay).to(beTrue())
expect(core.playbackMock?.didCallSeek).to(beTrue())
expect(core.playbackMock?.didCallSeekWithValue).to(equal(0))
}
}
}
}
private func getPosterPlugin(_ core: Core?) -> PosterPlugin {
return core?.plugins.first { $0.pluginName == PosterPlugin.name } as! PosterPlugin
}
}
| bsd-3-clause | 26e20872157ff79b23fdf11d839bfe7e | 35.36129 | 106 | 0.477466 | 6.166302 | false | false | false | false |
joshc89/DeclarativeLayout | DeclarativeLayout/Protocols/AnchoredObject.swift | 1 | 5312 | //
// AnchoredObject.swift
// DeclarativeLayout
//
// Created by Josh Campion on 16/07/2016.
// Copyright © 2016 Josh Campion. All rights reserved.
//
import UIKit
/// Public typealias allowing properties on an `AnchoredObject`s such as UIView and UILayoutGuide to be observed.
public typealias AnchoredNSObject = AnchoredObject & NSObjectProtocol
/**
Protocol definig the required properties of an object to be part of a constraint based layout system using `Layout`.
`UIView` and `UILayoutGuide` both conform to this protocol so they can be used interchangably in a `Layout`.
*/
public protocol AnchoredObject {
// MARK: X-Axis Anchors
/// A layout anchor representing the left edge of the layout guide’s frame.
var leftAnchor: NSLayoutXAxisAnchor { get }
/// A layout anchor representing the leading edge of the layout guide’s frame.
var leadingAnchor: NSLayoutXAxisAnchor { get }
/// A layout anchor representing the horizontal center of the layout guide’s frame.
var centerXAnchor: NSLayoutXAxisAnchor { get }
/// A layout anchor representing the trailing edge of the layout guide’s frame.
var trailingAnchor: NSLayoutXAxisAnchor { get }
/// A layout anchor representing the right edge of the layout guide’s frame.
var rightAnchor: NSLayoutXAxisAnchor { get }
// MARK: Y-Axis Anchors
/// A layout anchor representing the top edge of the layout guide’s frame.
var topAnchor: NSLayoutYAxisAnchor { get }
/// A layout anchor representing the vertical center of the layout guide’s frame.
var centerYAnchor: NSLayoutYAxisAnchor { get }
/// A layout anchor representing the bottom edge of the layout guide’s frame.
var bottomAnchor: NSLayoutYAxisAnchor { get }
// MARK: Dimension Anchors
/// A layout anchor representing the width of the layout guide’s frame.
var widthAnchor: NSLayoutDimension { get }
/// A layout anchor representing the height of the layout guide’s frame.
var heightAnchor: NSLayoutDimension { get }
}
public extension AnchoredObject {
// MARK: Convenience Constraint Creators
/**
Creates constraints aligning self to another `AnchoredObject` at each edge using leading and trailing over left and right.
- parameter to: The other object to align this object's edges to.
- parameter withInsets: The constants to set for each edge constraint. Default value is zeros.
- returns: An array of created constraints in the order top, leading, bottom, trailing.
*/
public func constraintsAligningEdges(to:AnchoredObject, withInsets:UIEdgeInsets = .zero) -> [NSLayoutConstraint] {
return [
topAnchor.constraint( equalTo: to.topAnchor, constant: withInsets.top),
leadingAnchor.constraint( equalTo: to.leadingAnchor, constant: withInsets.left),
bottomAnchor.constraint( equalTo: to.bottomAnchor, constant: -withInsets.bottom),
trailingAnchor.constraint( equalTo: to.trailingAnchor, constant: -withInsets.right),
]
}
/**
Creates constraints aligning the center of self to the center of another `AnchoredObject`. Optionally creates greater than or equal to constraints against the leading and top edges to prevent overflow.
- parameter on: The other object to align this object's center with.
- parameter withOffset: The amount off center this view should be. Default value is zeros.
- parameter xBuffer: If not nil, this is the minimum distance from the leading edge of `on`. This can be used to prevent horizontal overflow. Default values is 0.
- parameter yBuffer: If not nil, this is the minimum distance from the top edge of `on`. This can be used to prevent vertical overflow. Default values is 0.
- returns: An array of created constraints in the order centerX, centerY, xBuffer, yBuffer.
*/
public func constraintsCentering(on: AnchoredObject, withOffset:CGPoint = CGPoint.zero, xBuffer:CGFloat? = 0, yBuffer:CGFloat? = 0) -> [NSLayoutConstraint] {
return [
centerXAnchor.constraint( equalTo: on.centerXAnchor, constant: withOffset.x),
centerYAnchor.constraint( equalTo: on.centerYAnchor, constant: withOffset.y),
xBuffer.flatMap { self.leadingAnchor.constraint(greaterThanOrEqualTo: on.leadingAnchor, constant: $0) },
yBuffer.flatMap { self.topAnchor.constraint(greaterThanOrEqualTo: on.topAnchor, constant: $0) }
].flatMap { $0 }
}
/**
Creates constraints to size self to a given size.
- parameter to: The size to constrain self to.
- paramter priority: The priority of the size constraints. Default value is 1000.
*/
public func constraintsSizing(to:CGSize, priority:UILayoutPriority = 1000) -> [NSLayoutConstraint] {
let constraints = [
widthAnchor.constraint(equalToConstant: to.width),
heightAnchor.constraint(equalToConstant: to.height)
]
if priority < 1000 {
constraints.forEach { $0.priority = priority }
}
return constraints.flatMap { $0 }
}
}
| mit | f2c417b5dec8081fd30a0fb1897d3ca3 | 40.992063 | 206 | 0.689284 | 5.092397 | false | false | false | false |
juheon0615/GhostHandongSwift | HandongAppSwift/MenuItemView.swift | 3 | 2783 | //
// MenuItemView.swift
// HandongAppSwift
//
// Created by csee on 2015. 2. 19..
// Copyright (c) 2015년 GHOST. All rights reserved.
//
import Foundation
import UIKit
class MenuItemView: UIView {
init(margin: Double, yPos: Double, item: StoreDetailModel.Menu) {
let screenWidth = Double(UIScreen.mainScreen().applicationFrame.width)
let width = screenWidth - 2 * margin
var newHeight: CGFloat = 0
super.init(frame: CGRect(x: margin, y: yPos, width: width, height: 1))
let menuWidth = (super.frame.width / 3) * 2
let priceWidth = (super.frame.width / 3)
let menuLabel = UILabel(frame: CGRect(x: 0, y: 0, width: menuWidth, height: 30))
let priceLabel = UILabel(frame: CGRect(x: 0 + menuWidth, y: 0, width: priceWidth, height: 30))
// set TEXT
menuLabel.text = item.name
priceLabel.text = item.price
// set FONT SIZE
menuLabel.font = UIFont(name: menuLabel.font.fontName, size: 14)
priceLabel.font = UIFont(name: priceLabel.font.fontName, size: 14)
// set Properties
menuLabel.numberOfLines = 0
menuLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
menuLabel.sizeToFit()
var newBound = menuLabel.frame
newBound.size.width = menuWidth
menuLabel.frame = newBound
priceLabel.textAlignment = NSTextAlignment.Right
priceLabel.numberOfLines = 0
priceLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
priceLabel.sizeToFit()
newBound = priceLabel.frame
newBound.size.width = priceWidth
priceLabel.frame = newBound
super.addSubview(menuLabel)
super.addSubview(priceLabel)
newHeight += (menuLabel.frame.height > priceLabel.frame.height ? menuLabel.frame.height : priceLabel.frame.height)
newHeight += 2 // margin
if item.set != "" {
let setLabel = UILabel(frame: CGRect(x: 0, y: Double(newHeight), width: Double(menuWidth), height: 10))
setLabel.text = item.set
setLabel.font = UIFont(name: setLabel.font.fontName, size: 13)
setLabel.numberOfLines = 0
setLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
setLabel.setTranslatesAutoresizingMaskIntoConstraints(true)
setLabel.sizeToFit()
super.addSubview(setLabel)
newHeight += setLabel.frame.height
}
self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: newHeight)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
} | mit | 58935236f0505bebfaaf6a551c937e17 | 35.605263 | 122 | 0.618123 | 4.67395 | false | false | false | false |
jay18001/brickkit-ios | Example/Source/Examples/Layout/SizeClassesBrickViewController.swift | 1 | 1751 | //
// SizeClassesBrickViewController.swift
// BrickKit
//
// Created by Ruben Cagnie on 9/20/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import UIKit
import BrickKit
class SizeClassesBrickViewController: BrickViewController {
override class var brickTitle: String {
return "Size Classes"
}
override class var subTitle: String {
return "Example for size classes"
}
var sizeClassFull: SizeClassBrick!
var sizeClassHalf: SizeClassBrick!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .brickBackground
self.registerBrickClass(SizeClassBrick.self)
self.registerBrickClass(TestBrick.self)
sizeClassFull = SizeClassBrick("Full", width: .ratio(ratio: 1), backgroundColor: .brickSection)
sizeClassFull.color = .brickGray3
sizeClassFull.text = "Should be 100px Height"
sizeClassHalf = SizeClassBrick("Half", width: .ratio(ratio: 0.5), backgroundColor: .brickSection)
sizeClassHalf.color = .brickGray5
let section = BrickSection("Size Classes", bricks: [
sizeClassFull,
sizeClassHalf
], inset: 10, edgeInsets: UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20))
self.setSection(section)
updateLabels()
}
func updateLabels() {
let isCompact = self.traitCollection.horizontalSizeClass == .compact
if isCompact {
sizeClassFull.text = "COMPACT - SHOULD BE 100px"
sizeClassHalf.text = "COMPACT - SHOULD BE 100px"
} else {
sizeClassFull.text = "REGULAR - SHOULD BE 150px"
sizeClassHalf.text = "REGULAR - SHOULD BE 150px"
}
}
}
| apache-2.0 | 897efb3532c0d092d82a96854efaf6fc | 27.225806 | 105 | 0.649714 | 4.755435 | false | false | false | false |
Codigami/CFAlertViewController | CFAlertViewController/Cells/CFAlertTitleSubtitleTableViewCell.swift | 1 | 4581 | //
// CFAlertTitleSubtitleTableViewCell.swift
// CFAlertViewControllerDemo
//
// Created by Shivam Bhalla on 1/19/17.
// Copyright © 2017 Codigami Inc. All rights reserved.
//
import UIKit
public class CFAlertTitleSubtitleTableViewCell: UITableViewCell {
// MARK: - Declarations
// MARK: - Variables
// MARK: Public
public static func identifier() -> String {
return String(describing: CFAlertTitleSubtitleTableViewCell.self)
}
@IBOutlet public var titleLabel: UILabel?
@IBOutlet public var subtitleLabel: UILabel?
public var contentTopMargin: CGFloat = 0.0 {
didSet {
// Update Constraint
titleLabelTopConstraint?.constant = contentTopMargin
subtitleLabelTopConstraint?.constant = (titleLabelTopConstraint?.constant)!
layoutIfNeeded()
}
}
public var contentBottomMargin: CGFloat = 0.0 {
didSet {
// Update Constraint
titleLabelBottomConstraint?.constant = contentBottomMargin
subtitleLabelBottomConstraint?.constant = (titleLabelBottomConstraint?.constant)!
layoutIfNeeded()
}
}
public var contentLeadingSpace: CGFloat = 0.0 {
didSet {
// Update Constraint Values
titleLeadingSpaceConstraint?.constant = contentLeadingSpace
subtitleLeadingSpaceConstraint?.constant = (titleLeadingSpaceConstraint?.constant)!
layoutIfNeeded()
}
}
// MARK: Private
@IBOutlet private weak var titleLabelTopConstraint: NSLayoutConstraint?
@IBOutlet private weak var titleLeadingSpaceConstraint: NSLayoutConstraint?
@IBOutlet private weak var titleLabelBottomConstraint: NSLayoutConstraint?
@IBOutlet private weak var titleSubtitleVerticalSpacingConstraint: NSLayoutConstraint?
@IBOutlet private weak var subtitleLabelTopConstraint: NSLayoutConstraint?
@IBOutlet private weak var subtitleLeadingSpaceConstraint: NSLayoutConstraint?
@IBOutlet private weak var subtitleLabelBottomConstraint: NSLayoutConstraint?
// MARK: Initialization Methods
public override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
basicInitialisation()
}
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// Initialization code
basicInitialisation()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
internal func basicInitialisation() {
// Reset Text and Color
titleLabel?.text = nil
subtitleLabel?.text = nil
// Set Content Leading Space
contentLeadingSpace = 20.0;
}
// MARK: - Layout Methods
override public func layoutSubviews() {
super.layoutIfNeeded()
contentView.setNeedsLayout()
contentView.layoutIfNeeded()
}
// MARK: Helper Methods
public func setTitle(_ title: String?, titleColor: UIColor?, subtitle: String?, subtitleColor: UIColor?, alignment: NSTextAlignment) {
// Set Cell Text Fonts & Colors
titleLabel?.text = title
titleLabel?.textColor = titleColor
titleLabel?.textAlignment = alignment
subtitleLabel?.text = subtitle
subtitleLabel?.textColor = subtitleColor
subtitleLabel?.textAlignment = alignment
// Update Constraints
var titleCharCount = 0
if let count = titleLabel?.text?.count {
titleCharCount = count
}
var subtitleCharCount = 0
if let count = subtitleLabel?.text?.count {
subtitleCharCount = count
}
if (titleCharCount <= 0 && subtitleCharCount <= 0) || subtitleCharCount <= 0 {
titleLabelBottomConstraint?.isActive = true
subtitleLabelTopConstraint?.isActive = false
titleSubtitleVerticalSpacingConstraint?.constant = 0.0
}
else if titleCharCount <= 0 {
titleLabelBottomConstraint?.isActive = false
subtitleLabelTopConstraint?.isActive = true
titleSubtitleVerticalSpacingConstraint?.constant = 0.0
}
else {
titleLabelBottomConstraint?.isActive = false
subtitleLabelTopConstraint?.isActive = false
titleSubtitleVerticalSpacingConstraint?.constant = 5.0
}
}
}
| mit | 7e0c8bca56e3ff0a87947a35bc47e4bb | 33.179104 | 138 | 0.650218 | 6.155914 | false | false | false | false |
Electrode-iOS/ELReachability | ELReachability/NetworkStatus.swift | 2 | 6145 | //
// NetworkStatus.swift
// ELReachability
//
// Created by Sam Grover on 8/13/15.
// Copyright © 2015 WalmartLabs. All rights reserved.
//
import Foundation
import SystemConfiguration
@_silgen_name("objc_startMonitoring")
internal func objc_startMonitoring(_: SCNetworkReachability, _: @convention(block)()->Void) -> ObjCBool
@_silgen_name("objc_stopMonitoring")
internal func objc_stopMonitoring(_: SCNetworkReachability) -> ObjCBool
/// The network connection enumeration describes the possible connection types that can be identified.
public enum NetworkConnection {
case cellular, wifi
init?(flags: SCNetworkReachabilityFlags) {
if !flags.contains(.reachable) {
return nil
}
// Check that this is not an oddity as per https://github.com/tonymillion/Reachability/blob/master/Reachability.m
if flags.contains(.connectionRequired) || flags.contains(.transientConnection) {
return nil
}
if flags.contains(.isWWAN) {
self = .cellular
} else {
self = .wifi
}
}
}
public struct NetworkStatusInterpreter {
/// The actual flags reported by the system. This is used to compute if the network is reachable.
public let flags: SCNetworkReachabilityFlags
/// The network connection type, or `nil` if the network is not reachable. Note: This property may give false negatives.
public let connection: NetworkConnection?
internal init(flags: SCNetworkReachabilityFlags) {
self.flags = flags
self.connection = NetworkConnection(flags: flags)
}
/// Returns `true` when the network is reachable. `false` otherwise.
public var isReachable: Bool {
return connection != nil
}
/// Returns `true` when the network is reachable via a cellular connection. `false` otherwise. Note: This check may give false negatives.
public var isCellular: Bool {
return connection == .cellular
}
/// Returns `true` when the network is reachable via a WiFi connection. `false` otherwise. Note: This check may give false negatives.
public var isWiFi: Bool {
return connection == .wifi
}
}
public typealias NetworkStatusCallbackClosure = (_ networkStatusInterpreter: NetworkStatusInterpreter) -> Void
@objc(ELNetworkStatus)
public final class NetworkStatus: NSObject {
fileprivate let reachability: SCNetworkReachability
// MARK: Class methods
/**
This method can be used to set up a `NetworkStatus` instance to check if the internet is reachable.
- returns: The `NetworkStatus` object.
*/
public class func networkStatusForInternetConnection() -> NetworkStatus? {
var zeroAddress = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let reachabilityRef = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1, { (ptr) -> SCNetworkReachability? in
return SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, ptr)
})
}
if let reachabilityRef = reachabilityRef {
return NetworkStatus(reachability: reachabilityRef)
} else {
return nil
}
}
init(reachability: SCNetworkReachability) {
self.reachability = reachability
}
deinit {
stopNetworkStatusMonitoring()
}
// MARK: Asynchronous API methods
/**
Call this method to set up a callback for being notified when the network status changes. When you're done, call `stopNetworkStatusMonitoring`.
Use this if you want notification of changes. For synchronous checks, see `isReachable`.
- parameter callback: The closure that will be called when reachability changes.
- returns: `true` if the monitoring was set up. `false` otherwise.
*/
public func startNetworkStatusMonitoring(_ callback: @escaping NetworkStatusCallbackClosure) -> Bool {
let monitoringStarted = objc_startMonitoring(reachability) { () -> Void in
var flags = SCNetworkReachabilityFlags(rawValue:0)
SCNetworkReachabilityGetFlags(self.reachability, &flags)
callback(NetworkStatusInterpreter(flags: flags))
}
return monitoringStarted.boolValue
}
/**
Call this method to remove any callback associated with an instance.
*/
public func stopNetworkStatusMonitoring() {
_ = objc_stopMonitoring(reachability)
}
// MARK: Synchronous API methods
/// The current network connection type, or `nil` if the network is not reachable.
public var connection: NetworkConnection? {
return self.networkStatusInterpreter.connection
}
/// Returns `true` when the network is reachable. `false` otherwise. Calls corresponding method in `NetworkStatusInterpreter`.
public func isReachable() -> Bool {
return self.networkStatusInterpreter.isReachable
}
/// Returns `true` when the network is reachable via a cellular connection. `false` otherwise. Calls corresponding method in `NetworkStatusInterpreter`.
public func isCellular() -> Bool {
return self.networkStatusInterpreter.isCellular
}
/// Returns `true` when the network is reachable via a WiFi connection. `false` otherwise. Calls corresponding method in `NetworkStatusInterpreter`.
public func isWiFi() -> Bool {
return self.networkStatusInterpreter.isWiFi
}
// MARK: Utilities
// All synchronous APIs go through here.
fileprivate var networkStatusInterpreter: NetworkStatusInterpreter {
var flags = SCNetworkReachabilityFlags(rawValue:0)
if SCNetworkReachabilityGetFlags(reachability, &flags) {
return NetworkStatusInterpreter(flags: flags)
} else {
return NetworkStatusInterpreter(flags: SCNetworkReachabilityFlags(rawValue:0))
}
}
}
| mit | 908a5a083b851cc2479ccea10538e557 | 36.236364 | 178 | 0.68929 | 5.019608 | false | false | false | false |
TENDIGI/Obsidian-UI-iOS | src/CharacterLabel.swift | 1 | 6387 | //
// CharacterLabel.swift
// Alfredo
//
// Created by Eric Kunz on 10/26/15.
// Copyright © 2015 TENDIGI, LLC. All rights reserved.
//
import Foundation
import QuartzCore
open class CharacterLabel: UILabel, NSLayoutManagerDelegate {
var oldCharacterTextLayers = [CATextLayer]()
var newCharacterTextLayers = [CATextLayer]()
let textStorage = NSTextStorage(string: "")
let textContainer = NSTextContainer()
let layoutManager = NSLayoutManager()
var characterTextLayers = [CATextLayer]()
override open var lineBreakMode: NSLineBreakMode {
get {
return super.lineBreakMode
}
set {
textContainer.lineBreakMode = newValue
super.lineBreakMode = newValue
}
}
override open var numberOfLines: Int {
get {
return super.numberOfLines
}
set {
textContainer.maximumNumberOfLines = newValue
super.numberOfLines = newValue
}
}
override open var bounds: CGRect {
get {
return super.bounds
}
set {
textContainer.size = newValue.size
super.bounds = newValue
}
}
override open var text: String! {
get {
return super.text
}
set {
let wordRange = NSRange(location: 0, length: newValue.utf16.count)
let attributedText = NSMutableAttributedString(string: newValue)
attributedText.addAttribute(NSAttributedStringKey.foregroundColor, value: self.textColor, range: wordRange)
attributedText.addAttribute(NSAttributedStringKey.font, value: self.font, range: wordRange)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = self.textAlignment
attributedText.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: wordRange)
self.attributedText = attributedText
}
}
override open var attributedText: NSAttributedString! {
get {
return super.attributedText
}
set {
if textStorage.string == newValue.string {
return
}
cleanOutOldCharacterTextLayers()
oldCharacterTextLayers = characterTextLayers
textStorage.setAttributedString(newValue)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupLayoutManager()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayoutManager()
}
override open func awakeFromNib() {
super.awakeFromNib()
setupLayoutManager()
}
func setupLayoutManager() {
if !textStorage.layoutManagers.isEmpty {
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
textContainer.size = bounds.size
textContainer.maximumNumberOfLines = numberOfLines
textContainer.lineBreakMode = lineBreakMode
layoutManager.delegate = self
}
}
open func layoutManager(_ layoutManager: NSLayoutManager, didCompleteLayoutFor textContainer: NSTextContainer?, atEnd layoutFinishedFlag: Bool) {
calculateTextLayers()
}
func calculateTextLayers() {
characterTextLayers.removeAll(keepingCapacity: false)
let attributedText = textStorage.string
let wordRange = NSRange(location: 0, length: attributedText.characters.count)
let attributedString = self.internalAttributedText()
let layoutRect = layoutManager.usedRect(for: textContainer)
// for var index = wordRange.location; index < wordRange.length+wordRange.location; index += 0 {
// let glyphRange = NSRange(location: index, length: 1)
// let characterRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange:nil)
// let textContainer = layoutManager.textContainer(forGlyphAt: index, effectiveRange: nil)
// var glyphRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer!)
// let location = layoutManager.location(forGlyphAt: index)
// let kerningRange = layoutManager.range(ofNominallySpacedGlyphsContaining: index)
//
// if kerningRange.length > 1 && kerningRange.location == index {
// if !characterTextLayers.isEmpty {
// let previousLayer = characterTextLayers[characterTextLayers.endIndex-1]
// var frame = previousLayer.frame
// frame.size.width += glyphRect.maxX-frame.maxX
// previousLayer.frame = frame
// }
// }
//
//
// glyphRect.origin.y += location.y-(glyphRect.height/2)+(self.bounds.size.height/2)-(layoutRect.size.height/2)
//
//
// let textLayer = CATextLayer(frame: glyphRect, string: (attributedString?.attributedSubstring(from: characterRange))!)
// initialTextLayerAttributes(textLayer)
//
// layer.addSublayer(textLayer)
// characterTextLayers.append(textLayer)
//
// index += characterRange.length
// }
}
func initialTextLayerAttributes(_ textLayer: CATextLayer) {
}
func internalAttributedText() -> NSMutableAttributedString! {
let wordRange = NSRange(location: 0, length: textStorage.string.characters.count)
let attributedText = NSMutableAttributedString(string: textStorage.string)
attributedText.addAttribute(NSAttributedStringKey.foregroundColor, value: self.textColor.cgColor, range:wordRange)
attributedText.addAttribute(NSAttributedStringKey.font, value: self.font, range:wordRange)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = self.textAlignment
attributedText.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range: wordRange)
return attributedText
}
func cleanOutOldCharacterTextLayers() {
//Remove all text layers from the superview
for textLayer in oldCharacterTextLayers {
textLayer.removeFromSuperlayer()
}
//clean out the text layer
oldCharacterTextLayers.removeAll(keepingCapacity: false)
}
}
| mit | 1722de90e4af86b6bce9042e87fa2da6 | 33.518919 | 149 | 0.652834 | 5.601754 | false | false | false | false |
ben-ng/swift | test/ClangImporter/MixedSource/resolve-cross-language.swift | 1 | 1789 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource) -emit-module -emit-objc-header -o %t %S/Inputs/resolve-cross-language/Base.swift -disable-objc-attr-requires-foundation-module
// RUN: cp %S/Inputs/resolve-cross-language/Base-module.map %t/module.map
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource) -typecheck -I %t -F %S/Inputs/resolve-cross-language %s -verify
// REQUIRES: objc_interop
import Base
import BaseUser
// Sanity check.
useBaseClass(getBaseClass())
useBaseClassObjC(getBaseClassObjC())
useBaseProtoObjC(getBaseProtoObjC())
var be: BaseEnum = getBaseEnum()
useBaseEnum(be)
be = getBaseClass().baseEnumMethod(be)
be = AnotherClass().getEnum()
var beo: BaseEnumObjC = getBaseEnumObjC()
useBaseEnumObjC(beo)
var se: SwiftEnum = getRenamedEnum()
useRenamedEnum(se)
se = getBaseClass().renamedEnumMethod(se)
se = AnotherClass().getSwiftEnum()
var seo: SwiftEnumObjC = getRenamedEnumObjC()
useRenamedEnumObjC(seo)
// Check type resolution.
useBaseClass(getBaseClassObjC())
useBaseClassObjC(getBaseClass())
getBaseClass().categoryMethod()
useBaseProto(getBaseProtoObjC())
let p: BaseProto = UserClass()
useBaseProtoObjC(p)
getBaseClass().extensionMethod()
be = BaseEnum.Zim
be = BaseEnum.Zang
be = BaseEnum.Zung
var beRaw: CShort = be.rawValue
beo = BaseEnumObjC.zippity
beo = BaseEnumObjC.doo
beo = BaseEnumObjC.dah
var beoRaw: CUnsignedChar = beo.rawValue
se = SwiftEnum.Quux
se = SwiftEnum.Corge
se = SwiftEnum.Grault
var seRaw: CShort = se.rawValue
seo = SwiftEnumObjC.quux
seo = SwiftEnumObjC.corge
seo = SwiftEnumObjC.grault
var seoRaw: CUnsignedChar = seo.rawValue
// Make sure we're actually parsing stuff.
useBaseClass() // expected-error{{missing argument for parameter #1}}
| apache-2.0 | ba36f5c4c5ce8e5122f16ca06be5eb2a | 26.106061 | 197 | 0.766909 | 3.356473 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/SideScrollingCollectionViewCell.swift | 1 | 12407 | import UIKit
internal struct CellArticle {
let articleURL: URL?
let title: String?
let titleHTML: String?
let description: String?
let imageURL: URL?
}
public protocol SideScrollingCollectionViewCellDelegate: class {
func sideScrollingCollectionViewCell(_ sideScrollingCollectionViewCell: SideScrollingCollectionViewCell, didSelectArticleWithURL articleURL: URL)
}
public protocol SubCellProtocol {
func deselectSelectedSubItems(animated: Bool)
}
public class SideScrollingCollectionViewCell: CollectionViewCell, SubCellProtocol {
static let articleCellIdentifier = "ArticleRightAlignedImageCollectionViewCell"
var theme: Theme = Theme.standard
public weak var selectionDelegate: SideScrollingCollectionViewCellDelegate?
public let imageView = UIImageView()
public let titleLabel = UILabel()
public let subTitleLabel = UILabel()
public let descriptionLabel = UILabel()
internal var flowLayout: UICollectionViewFlowLayout? {
return collectionView.collectionViewLayout as? UICollectionViewFlowLayout
}
internal let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
internal let prototypeCell = ArticleRightAlignedImageCollectionViewCell()
var semanticContentAttributeOverride: UISemanticContentAttribute = .unspecified {
didSet {
titleLabel.semanticContentAttribute = semanticContentAttributeOverride
subTitleLabel.semanticContentAttribute = semanticContentAttributeOverride
descriptionLabel.semanticContentAttribute = semanticContentAttributeOverride
collectionView.semanticContentAttribute = semanticContentAttributeOverride
}
}
internal var articles: [CellArticle] = []
override open func setup() {
titleLabel.isOpaque = true
subTitleLabel.isOpaque = true
descriptionLabel.isOpaque = true
imageView.isOpaque = true
addSubview(titleLabel)
addSubview(subTitleLabel)
addSubview(descriptionLabel)
addSubview(imageView)
addSubview(collectionView)
addSubview(prototypeCell)
wmf_configureSubviewsForDynamicType()
//Setup the prototype cell with placeholder content so we can get an accurate height calculation for the collection view that accounts for dynamic type changes
prototypeCell.configure(with: CellArticle(articleURL: nil, title: "Lorem", titleHTML: "Lorem", description: "Ipsum", imageURL: nil), semanticContentAttribute: .forceLeftToRight, theme: self.theme, layoutOnly: true)
prototypeCell.isHidden = true
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
titleLabel.numberOfLines = 1
subTitleLabel.numberOfLines = 1
descriptionLabel.numberOfLines = 0
flowLayout?.scrollDirection = .horizontal
collectionView.register(ArticleRightAlignedImageCollectionViewCell.self, forCellWithReuseIdentifier: SideScrollingCollectionViewCell.articleCellIdentifier)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.alwaysBounceHorizontal = true
super.setup()
}
override open func reset() {
super.reset()
imageView.wmf_reset()
}
public var isImageViewHidden = false {
didSet {
imageView.isHidden = isImageViewHidden
setNeedsLayout()
}
}
public let imageViewHeight: CGFloat = 170
public let spacing: CGFloat = 6
override public func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
let layoutMargins = calculatedLayoutMargins
var origin = CGPoint(x: layoutMargins.left, y: layoutMargins.top)
let widthToFit = size.width - layoutMargins.left - layoutMargins.right
if !isImageViewHidden {
if (apply) {
imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: imageViewHeight)
}
origin.y += imageViewHeight
}
if titleLabel.wmf_hasAnyText {
origin.y += spacing
origin.y += titleLabel.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: round(0.4 * spacing), apply: apply)
}
if subTitleLabel.wmf_hasAnyText {
origin.y += 0
origin.y += subTitleLabel.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: spacing, apply: apply)
}
origin.y += spacing
origin.y += descriptionLabel.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: spacing, apply: apply)
let collectionViewSpacing: CGFloat = 10
var height = prototypeCell.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: 2*collectionViewSpacing, apply: false)
if articles.count == 0 {
height = 0
}
if (apply) {
flowLayout?.itemSize = CGSize(width: max(250, round(0.45*size.width)), height: height - 2*collectionViewSpacing)
flowLayout?.minimumInteritemSpacing = collectionViewSpacing
flowLayout?.minimumLineSpacing = 15
flowLayout?.sectionInset = UIEdgeInsets(top: collectionViewSpacing, left: collectionViewSpacing, bottom: collectionViewSpacing, right: collectionViewSpacing)
collectionView.frame = CGRect(x: 0, y: origin.y, width: size.width, height: height)
if semanticContentAttributeOverride == .forceRightToLeft {
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: layoutMargins.right - collectionViewSpacing)
} else {
collectionView.contentInset = UIEdgeInsets(top: 0, left: layoutMargins.left - collectionViewSpacing, bottom: 0, right: 0)
}
collectionView.reloadData()
collectionView.layoutIfNeeded()
resetContentOffset()
deselectSelectedSubItems(animated: false)
}
origin.y += height
origin.y += layoutMargins.bottom
return CGSize(width: size.width, height: origin.y)
}
public func resetContentOffset() {
let x: CGFloat = semanticContentAttributeOverride == .forceRightToLeft ? collectionView.contentSize.width - collectionView.bounds.size.width + collectionView.contentInset.right : -collectionView.contentInset.left
collectionView.contentOffset = CGPoint(x: x, y: 0)
}
public func deselectSelectedSubItems(animated: Bool) {
guard let selectedIndexPaths = collectionView.indexPathsForSelectedItems else {
return
}
for indexPath in selectedIndexPaths {
collectionView.deselectItem(at: indexPath, animated: animated)
}
}
override public func updateBackgroundColorOfLabels() {
super.updateBackgroundColorOfLabels()
titleLabel.backgroundColor = labelBackgroundColor
subTitleLabel.backgroundColor = labelBackgroundColor
descriptionLabel.backgroundColor = labelBackgroundColor
}
}
extension SideScrollingCollectionViewCell: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedArticle = articles[indexPath.item]
guard let articleURL = selectedArticle.articleURL else {
return
}
selectionDelegate?.sideScrollingCollectionViewCell(self, didSelectArticleWithURL:articleURL)
}
}
extension SideScrollingCollectionViewCell: UICollectionViewDataSource {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return articles.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SideScrollingCollectionViewCell.articleCellIdentifier, for: indexPath)
guard let articleCell = cell as? ArticleRightAlignedImageCollectionViewCell else {
return cell
}
let articleForCell = articles[indexPath.item]
articleCell.configure(with: articleForCell, semanticContentAttribute: semanticContentAttributeOverride, theme: self.theme, layoutOnly: false)
return articleCell
}
}
fileprivate extension ArticleRightAlignedImageCollectionViewCell {
func configure(with cellArticle: CellArticle, semanticContentAttribute: UISemanticContentAttribute, theme: Theme, layoutOnly: Bool) {
apply(theme: theme)
backgroundColor = .clear
setBackgroundColors(theme.colors.subCellBackground, selected: theme.colors.midBackground)
backgroundView?.layer.cornerRadius = 3
backgroundView?.layer.masksToBounds = true
selectedBackgroundView?.layer.cornerRadius = 3
selectedBackgroundView?.layer.masksToBounds = true
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowOpacity = 1.0
layer.shadowRadius = 3
layer.shadowColor = theme.colors.shadow.cgColor
layer.masksToBounds = false
titleLabel.backgroundColor = backgroundView?.backgroundColor
descriptionLabel.backgroundColor = backgroundView?.backgroundColor
titleTextStyle = .subheadline
descriptionTextStyle = .footnote
imageViewDimension = 40
isSaveButtonHidden = true
layoutMargins = UIEdgeInsets(top: 9, left: 10, bottom: 9, right: 10)
isImageViewHidden = layoutOnly || cellArticle.imageURL == nil
titleHTML = cellArticle.titleHTML ?? cellArticle.title
descriptionLabel.text = cellArticle.description
articleSemanticContentAttribute = semanticContentAttribute
if let imageURL = cellArticle.imageURL {
isImageViewHidden = false
if !layoutOnly {
imageView.wmf_setImage(with: imageURL, detectFaces: true, onGPU: true, failure: { (error) in }, success: { })
}
} else {
isImageViewHidden = true
}
updateFonts(with: traitCollection)
setNeedsLayout()
}
}
extension SideScrollingCollectionViewCell {
public func subItemIndex(at point: CGPoint) -> Int { // NSNotFound for not found
let collectionViewFrame = collectionView.frame
guard collectionViewFrame.contains(point) else {
return NSNotFound
}
let pointInCollectionViewCoordinates = convert(point, to: collectionView)
guard let indexPath = collectionView.indexPathForItem(at: pointInCollectionViewCoordinates) else {
return NSNotFound
}
return indexPath.item
}
public func viewForSubItem(at index: Int) -> UIView? {
guard index != NSNotFound, index >= 0, index < collectionView.numberOfItems(inSection: 0) else {
return nil
}
guard let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) else {
return nil
}
return cell
}
}
extension SideScrollingCollectionViewCell: Themeable {
public func apply(theme: Theme) {
self.theme = theme
imageView.alpha = theme.imageOpacity
setBackgroundColors(theme.colors.paperBackground, selected: theme.colors.midBackground)
titleLabel.textColor = theme.colors.primaryText
subTitleLabel.textColor = theme.colors.secondaryText
descriptionLabel.textColor = theme.colors.primaryText
collectionView.backgroundColor = theme.colors.paperBackground
descriptionLabel.textColor = theme.colors.primaryText
updateSelectedOrHighlighted()
collectionView.reloadData()
if #available(iOSApplicationExtension 11.0, *) {
imageView.accessibilityIgnoresInvertColors = true
}
}
}
| mit | b5a14a2cfea7ea1f91ba42a6a87303e5 | 42.381119 | 222 | 0.69888 | 6.058105 | false | false | false | false |
AV8R-/SwiftUtils | JsonTools/JsonTools.swift | 1 | 4223 | //
// PropertyToJsonConvertion.swift
// UltimateGuitar
//
// Created by admin on 1/16/17.
//
//
import Foundation
import CoreData
func mapReflection<T, U>(x: T, transform: (Mirror) -> U) -> U {
let mirror = Mirror(reflecting: x)
return transform(mirror)
}
func objectToJsonMap(mirror: Mirror) -> [String: Any] {
var result = [String: Any]()
mirror.children.forEach {
switch $0.value {
case Optional<Any>.some(let data) where data is NSData: print("WARNING: " + String(describing: $0.label) + " is serialized!")
case is NSData: print("WARNING: " + String(describing: $0.label) + " is serialized!")
case Optional<Any>.none: break
case Optional<Any>.some(let x):
print(x)
switch x {
case is Int16, is Int32, is Int64, is Int, is Double, is Float, is String, is Bool: result[$0.label ?? ""] = x
default: result[$0.label ?? ""] = anyToJson(x)
}
case is Int, is Double, is Float, is String: result[$0.label ?? ""] = $0.value
default: result[$0.label ?? ""] = anyToJson($0.value)
}
}
return result
}
func anyToJson(_ object: Any) -> Any {
//Arrays
if let numericArray = object as? [Numeric] { return numericArray.propsToJson() }
if let strictValues = object as? [StrictType] { return strictValues.propsToJson() }
if let managedArray = object as? [NSManagedObject] { return managedArray.propsToJson() }
if let array = object as? [Any] { return array.propsToJson() }
if let dictionary = object as? [AnyHashable: Any] {
var ans = [String: Any]()
dictionary.forEach {
// if let stringable = $0 {
ans[String(describing: $0.0)] = anyToJson($0.1)
// }
}
return ans
}
//Objects
if let number = object as? Numeric { return number }
if let simple = object as? StrictType { return simple.string() }
if let managed = object as? NSManagedObject { return managed.propsToJson() }
if object is NSNull {
print("hello, kitty")
}
return mapReflection(x: object, transform: objectToJsonMap)
}
extension Swift.Collection {
func mapReflection<U>(transform: @escaping (Mirror) -> U) -> [U] {
return map { transform(Mirror(reflecting: $0)) }
}
func propsToJson() -> [Any] {
return compactMap {
let extra = ($0 as? ExtraJsonConvertable)?.extraJsonFields() ?? [:]
let json = anyToJson($0)
if let dic = json as? [String: Any] {
return dic + extra
} else {
return nil
}
}
}
}
extension Swift.Collection where Iterator.Element: NSManagedObject {
func propsToJson() -> [Any] {
return compactMap {
let extra = ($0 as? ExtraJsonConvertable)?.extraJsonFields() ?? [:]
let json = anyToJson($0)
if let dic = json as? [String: Any] {
return dic + extra
} else {
return nil
}
}
}
}
extension Swift.Collection where Iterator.Element == Numeric {
func propsToJson() -> [Any] {
switch first {
case is NSNumber: return compactMap { ($0 as! NSNumber).intValue }
default: return self as! [Any]
}
}
}
extension Swift.Collection where Iterator.Element == StrictType {
func propsToJson() -> [Any] {
return self as! [Any]
}
}
extension NSManagedObject {
func propsToJson() -> [String: Any] {
let allKeys = NSDictionary(dictionary: entity.attributesByName).allKeys as! [String]
var dict = [String: Any]()
dictionaryWithValues(forKeys: allKeys).filter { !($0.1 is Data) && !($0.1 is NSNull) }.forEach {
if $0.1 is StrictType {
dict[$0.0] = $0.1
} else {
dict[$0.0] = anyToJson($0.1)
}
}
if let extra = self as? ExtraJsonConvertable {
return dict + extra.extraJsonFields()
} else {
return dict
}
}
}
//MARK: Костыли
protocol ExtraJsonConvertable {
func extraJsonFields() -> [String: Any]
}
| mit | 3beeadd6317343d08002828d25855915 | 30.462687 | 133 | 0.565228 | 4.042186 | false | false | false | false |
Swerfvalk/SwerfvalkExtensionKit | Source/DateExtension.swift | 1 | 6007 | //
// DateExtension.swift
// SwerfvalkExtensionKit
//
// Created by 萧宇 on 18/08/2017.
// Copyright © 2017 Swerfvalk. All rights reserved.
//
import Foundation
public var kSecondsOfAMinute: Int { return 60 }
public var kSecondsOfAnHour: Int { return 60 * kSecondsOfAMinute }
public var kSecondsOfADay: Int { return 24 * kSecondsOfAnHour }
public var kSecondsOfAWeek: Int { return 7 * kSecondsOfADay }
public var kSecondsOfHalfMonth: Int { return 15 * kSecondsOfADay }
public var kSecondsOfAMonth: Int { return 30 * kSecondsOfADay }
public var kSecondsOfHalfYear: Int { return 182 * kSecondsOfADay }
public var kSecondsOfAYear: Int { return 365 * kSecondsOfADay }
public extension Date {
private var components: DateComponents {
return Calendar.current.dateComponents([.second, .minute, .hour, .day, .month, .year, .weekday, .weekOfMonth, .weekOfYear, .weekdayOrdinal], from: self)
}
public var second: Int { return components.second ?? 0 }
public var minute: Int { return components.minute ?? 0 }
public var hour: Int { return components.hour ?? 0 }
public var day: Int { return components.day ?? 0 }
public var month: Int { return components.month ?? 0 }
public var year: Int { return components.year ?? 0 }
public var weekday: Int { return components.weekday ?? 0 }
public var weekDay: String {
switch weekday {
case 1:
return "星期日"
case 2:
return "星期一"
case 3:
return "星期二"
case 4:
return "星期三"
case 5:
return "星期四"
case 6:
return "星期五"
case 7:
return "星期六"
default:
return ""
}
}
public var weekOfMonth: Int { return components.weekOfMonth ?? 0 }
public var weekOfYear: Int { return components.weekOfYear ?? 0 }
public init(timestamp: String) {
self.init(timeIntervalSince1970: TimeInterval(timestamp)!)
}
public init(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) {
var dateComponents = DateComponents()
dateComponents.calendar = Calendar(identifier: .gregorian)
dateComponents.timeZone = TimeZone(secondsFromGMT: 8)
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.second = second
self.init(timeIntervalSince1970: (dateComponents.date?.timeIntervalSince1970)!)
}
public static func secondsToTime(_ seconds: Float) -> String {
let integerSeconds = seconds > 0 ? Int(seconds) : 0
let hour = integerSeconds / kSecondsOfAnHour
let minute = integerSeconds % kSecondsOfAnHour / kSecondsOfAMinute
let second = integerSeconds % kSecondsOfAMinute
var time = ""
time = hour > 0 ? time.appending("\(hour):") : ""
time = minute < 10 ? time.appending("0\(minute):") : time.appending("\(minute):")
time = second < 10 ? time.appending("0\(second)") : time.appending("\(second)")
return time
}
public func timeWithPrefix() -> String {
let prefix = 0 < self.hour && self.hour <= 12 ? "上午" : "下午"
return "\(prefix) \(self.hour):\(self.minute)"
}
public func timeWithSuffix() -> String {
let suffix = 0 < self.hour && self.hour <= 12 ? "AM" : "PM"
return "\(self.hour):\(self.minute) \(suffix)"
}
public func timeIntervalDescription() -> String {
let timeInterval = -Int(self.timeIntervalSinceNow)
switch timeInterval {
case 0..<kSecondsOfAMinute:
return "1分钟内"
case kSecondsOfAMinute..<kSecondsOfAnHour:
return "\(timeInterval / kSecondsOfAMinute)分钟前"
case kSecondsOfAnHour..<kSecondsOfADay:
return "\(timeInterval / kSecondsOfAnHour)小时前"
case kSecondsOfADay..<kSecondsOfAMonth:
return "\(timeInterval / kSecondsOfADay)天前"
case kSecondsOfAMonth..<kSecondsOfAYear:
return "\(timeInterval / kSecondsOfAMonth)个月前"
default:
return "\(timeInterval / kSecondsOfAYear)年前"
}
}
public func minutesDescription() -> String {
let dateFormatter = DateFormatter()
let aComponents = Calendar.current.dateComponents([.day, .month, .year], from: Date())
if self.year != aComponents.year {
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
} else if self.month != aComponents.month {
dateFormatter.dateFormat = "MM-dd HH:mm"
} else {
dateFormatter.dateFormat = "HH:mm"
}
return dateFormatter.string(from: self)
}
public func formattedDescription() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let aComponents = Calendar.current.dateComponents([.day, .month, .year], from: Date())
if self.year != aComponents.year {
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
return dateFormatter.string(from: self)
} else if self.month == aComponents.month, self.day == aComponents.day {
return dateFormatter.string(from: self)
} else if aComponents.day! - self.day == 1 {
return "昨天 \(dateFormatter.string(from: self))"
} else if aComponents.day! - self.day == 2 {
return "前天 \(dateFormatter.string(from: self))"
} else if aComponents.day! - self.day < 7 {
dateFormatter.dateFormat = "EEEE HH:mm"
return dateFormatter.string(from: self)
} else {
dateFormatter.dateFormat = "MM-dd HH:mm"
return dateFormatter.string(from: self)
}
}
}
| mit | 961b64e34c23b2fd67bc50cb5d2546e7 | 36.18239 | 160 | 0.608254 | 4.61875 | false | false | false | false |
nvelaborja/hackathon2017 | Overwatch MetaBuddy/Overwatch MetaBuddy/HybridTableViewController.swift | 1 | 3213 | //
// HybridTableViewController.swift
// Overwatch MetaBuddy
//
// Created by Nathan VelaBorja on 2/4/17.
// Copyright © 2017 Nathan VelaBorja. All rights reserved.
//
import UIKit
class HybridTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Hybrid Maps"
// 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 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
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?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 | 9544e37a93a225de554edfaf016edfd1 | 32.113402 | 136 | 0.67061 | 5.309091 | false | false | false | false |
tkremenek/swift | test/refactoring/FillStubs/basic.swift | 40 | 3705 | protocol P1 {
func foo()
func foo1()
}
class C1 : P1 {
func foo1() {}
}
class C2 : P1 {
func foo() {}
}
class C3 : P1 {}
protocol P2 {
associatedtype T1
associatedtype T2
func foo1()
}
class C4 : P2 {}
class C5 : P2 {
typealias T1 = Int
func foo1() {}
}
class C6 : P2 {
typealias T1 = Int
typealias T2 = Int
}
class C7 : P2 {
typealias T2 = Int
func foo1() {}
}
class C8 : P2 {
typealias T1 = Int
typealias T2 = Int
func foo1() {}
}
class C9 {}
extension C9 : P1 {}
extension C9 : P2 {}
class C10 {}
extension C10 : P1 {
func foo() {}
func foo1() {}
}
extension C10 : P2 {
typealias T1 = Int
typealias T2 = Int
func foo1() {}
}
class C11 {}
extension C11 : P1 {
func foo() {}
}
extension C11 : P2 {
typealias T1 = Int
typealias T2 = Int
}
class C12 {}
extension C12 : P1 {
func foo1() {}
}
extension C12 : P2 {
typealias T1 = Int
func foo1() {}
}
class C13 {}
extension C13 : P1 {
func foo() {}
func foo1() {}
}
extension C13 : P2 {
typealias T1 = Int
func foo1() {}
}
class C14 {}
extension C14 : P1 {
func foo() {}
}
extension C14 : P2 {
typealias T1 = Int
typealias T2 = Int
func foo1() {}
}
protocol P3 {
func foo3()
func foo4()
}
extension C14: P3 {
func foo3()
}
// RUN: %empty-directory(%t.result)
// RUN: %refactor -fill-stub -source-filename %s -pos=5:8 >> %t.result/P5-8.swift
// RUN: diff -u %S/Outputs/basic/P5-8.swift.expected %t.result/P5-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=8:8 >> %t.result/P8-8.swift
// RUN: diff -u %S/Outputs/basic/P8-8.swift.expected %t.result/P8-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=11:8 >> %t.result/P11-8.swift
// RUN: diff -u %S/Outputs/basic/P11-8.swift.expected %t.result/P11-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=18:8 >> %t.result/P18-8.swift
// RUN: diff -u %S/Outputs/basic/P18-8.swift.expected %t.result/P18-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=19:8 >> %t.result/P19-8.swift
// RUN: diff -u %S/Outputs/basic/P19-8.swift.expected %t.result/P19-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=23:8 >> %t.result/P23-8.swift
// RUN: diff -u %S/Outputs/basic/P23-8.swift.expected %t.result/P23-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=27:8 >> %t.result/P27-8.swift
// RUN: diff -u %S/Outputs/basic/P27-8.swift.expected %t.result/P27-8.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=38:12 >> %t.result/P38-12.swift
// RUN: diff -u %S/Outputs/basic/P38-12.swift.expected %t.result/P38-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=39:12 >> %t.result/P39-12.swift
// RUN: diff -u %S/Outputs/basic/P39-12.swift.expected %t.result/P39-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=51:12 >> %t.result/P51-12.swift
// RUN: diff -u %S/Outputs/basic/P51-12.swift.expected %t.result/P51-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=54:12 >> %t.result/P54-12.swift
// RUN: diff -u %S/Outputs/basic/P54-12.swift.expected %t.result/P54-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=59:12 >> %t.result/P59-12.swift
// RUN: diff -u %S/Outputs/basic/P59-12.swift.expected %t.result/P59-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=62:12 >> %t.result/P62-12.swift
// RUN: diff -u %S/Outputs/basic/P62-12.swift.expected %t.result/P62-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=71:12 >> %t.result/P71-12.swift
// RUN: diff -u %S/Outputs/basic/P71-12.swift.expected %t.result/P71-12.swift
// RUN: %refactor -fill-stub -source-filename %s -pos=88:12 >> %t.result/P88-12.swift
// RUN: diff -u %S/Outputs/basic/P88-12.swift.expected %t.result/P88-12.swift
| apache-2.0 | 00d451ee13a83e7c3bec0b86b1bc811f | 29.368852 | 85 | 0.654521 | 2.488247 | false | false | false | false |
evgenyneu/moa | Demo/ViewController.swift | 1 | 1791 | import UIKit
import moa
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let collectionViewDataSource = CollectionViewDataSource()
let flowLayout = UICollectionViewFlowLayout()
override func viewDidLoad() {
super.viewDidLoad()
// Log to console
Moa.logger = MoaConsoleLogger
// Maximum number of simultaneous image downloads. Default: 10.
Moa.settings.maximumSimultaneousDownloads = 5
// Timeout for image requests in seconds. This will cause a timeout if a resource is not able to be retrieved within a given timeout. Default timeout: 30 seconds.
Moa.settings.requestTimeoutSeconds = 10
collectionView.dataSource = collectionViewDataSource
setupCollectionViewLayout()
}
override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent; }
private func setupCollectionViewLayout() {
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
changeItemSize(UIScreen.main.bounds.width)
collectionView.setCollectionViewLayout(flowLayout, animated: false)
}
private func changeItemSize(_ screenWidth: CGFloat) {
let itemsInRow = Int(screenWidth / 150)
let itemSideSize = screenWidth / CGFloat(itemsInRow)
flowLayout.itemSize = CGSize(width: itemSideSize, height: itemSideSize)
}
override func viewWillTransition(to size: CGSize,
with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
changeItemSize(size.width)
}
@IBAction func onJosephSmitTapped(_ sender: AnyObject) {
if let url = URL(string: "http://en.wikipedia.org/wiki/Joseph_Smit") {
UIApplication.shared.openURL(url)
}
}
}
| mit | 022cc045b55b2600048c61945984582b | 32.166667 | 166 | 0.742602 | 5.191304 | false | false | false | false |
yinhaofrancis/SBHud | hud/FailureIndicateView.swift | 1 | 2773 | //
// FailureView.swift
// hud
//
// Created by hao yin on 27/03/2017.
// Copyright © 2017 hao yin. All rights reserved.
//
import UIKit
public class FailureIndicateView:baseIndicateView{
public override func didMoveToWindow() {
self.layer.addSublayer(shape)
shape.lineJoin = "round"
shape.lineCap = "round"
}
public override func start(contain: HudPlain) {
let a = CABasicAnimation(keyPath: "strokeEnd")
a.fromValue = 0
a.toValue = 1
a.duration = 1
self.shape.add(a, forKey: nil)
}
let shape:CAShapeLayer = CAShapeLayer()
public override func layoutSubviews() {
let w = min(self.bounds.width, self.bounds.height)
let frame = CGRect(x: 0, y: 0, width: w, height: w)
shape.frame = frame
shape.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
let r = self.drawFailure(rect: frame, isElement: self.isElement)
shape.path = r.path
shape.lineWidth = r.lineWidth
shape.fillColor = UIColor.clear.cgColor
shape.strokeColor = self.color.cgColor
}
func drawFailure(rect: CGRect = CGRect(x: 0, y: 0, width: 200, height: 200), isElement: Bool = false) ->(lineWidth:CGFloat,path:CGPath){
let seed: CGFloat = min(rect.width - (isElement ? 1 : 8) * 2, rect.height - (isElement ? 1 : 8) * 2)
let linewidth: CGFloat = seed / 20.0
let localseed: CGFloat = isElement ? 1 : 8
let pathRect = CGRect(x: localseed + linewidth / 2.0, y: localseed + linewidth / 2.0, width: seed - linewidth, height: seed - linewidth)
let frame = CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: rect.height)
let ovalPath = UIBezierPath(ovalIn: pathRect)
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: frame.minX + 0.27774 * frame.width, y: frame.minY + 0.27857 * frame.height))
bezier3Path.addCurve(to: CGPoint(x: frame.minX + 0.72322 * frame.width, y: frame.minY + 0.72405 * frame.height), controlPoint1: CGPoint(x: frame.minX + 0.72325 * frame.width, y: frame.minY + 0.72408 * frame.height), controlPoint2: CGPoint(x: frame.minX + 0.61185 * frame.width, y: frame.minY + 0.61268 * frame.height))
bezier3Path.move(to: CGPoint(x: frame.minX + 0.72500 * frame.width, y: frame.minY + 0.27678 * frame.height))
bezier3Path.addLine(to: CGPoint(x: frame.minX + 0.28000 * frame.width, y: frame.minY + 0.72178 * frame.height))
let conbine = UIBezierPath()
conbine.append(ovalPath)
conbine.append(bezier3Path)
return(linewidth,conbine.cgPath)
}
}
| mit | 41e48482f58a6e2180dd620fdb007c33 | 39.764706 | 326 | 0.611833 | 3.628272 | false | false | false | false |
prebid/prebid-mobile-ios | PrebidMobileTests/RenderingTests/Tests/PBMHTMLCreativeTest_Base.swift | 1 | 6690 | /* 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 XCTest
@testable import PrebidMobile
typealias PBMCreativeViewDelegateHandler = ((PBMAbstractCreative) -> Void)
class PBMHTMLCreativeTest_Base: XCTestCase, PBMCreativeViewDelegate {
let timeout: TimeInterval = 1
var htmlCreative: MockPBMHTMLCreative!
var transaction: PBMTransaction!
var mockCreativeModel: MockPBMCreativeModel!
var mockEventTracker: MockPBMAdModelEventTracker!
var mockModalManager: MockModalManager!
var mockWebView: MockPBMWebView!
var mockViewController: MockViewController!
override func setUp() {
super.setUp()
mockViewController = MockViewController()
//Set up MockServer
let serverConnection = ServerConnection(userAgentService: MockUserAgentService())
serverConnection.protocolClasses.append(MockServerURLProtocol.self)
//Set up creative model
mockCreativeModel = MockPBMCreativeModel(adConfiguration: AdConfiguration())
mockCreativeModel.width = 320
mockCreativeModel.height = 50
mockCreativeModel.html = "test"
mockEventTracker = MockPBMAdModelEventTracker(creativeModel: mockCreativeModel, serverConnection: serverConnection)
mockCreativeModel.eventTracker = mockEventTracker
//Set up HTML Creative
mockModalManager = MockModalManager()
mockWebView = MockPBMWebView()
htmlCreative = MockPBMHTMLCreative(
creativeModel: mockCreativeModel,
transaction:UtilitiesForTesting.createEmptyTransaction(),
webView: mockWebView,
sdkConfiguration: Prebid.mock
)
htmlCreative.downloadBlock = createLoader(connection: serverConnection)
htmlCreative.creativeViewDelegate = self
htmlCreative.modalManager = mockModalManager
//Simulate creativeFactory
htmlCreative.setupView()
//Simulate PBMBannerView.creativeReadyForImmediateDisplay:
//Add the view to the "PBMBannerView" (in this case, the viewController's view)
//Then call creative.display
guard let creativeView = htmlCreative.view else {
XCTFail("No View")
return
}
mockViewController.view.addSubview(creativeView)
htmlCreative.display(withRootViewController: mockViewController)
}
override func tearDown() {
htmlCreative = nil
mockCreativeModel = nil
mockModalManager = nil
mockWebView = nil
mockViewController = nil
super.tearDown()
}
// MARK: - CreativeViewDelegate
var creativeInterstitialDidLeaveAppHandler: PBMCreativeViewDelegateHandler?
func creativeInterstitialDidLeaveApp(_ creative: PBMAbstractCreative) {
creativeInterstitialDidLeaveAppHandler?(creative)
}
var creativeInterstitialDidCloseHandler: PBMCreativeViewDelegateHandler?
func creativeInterstitialDidClose(_ creative: PBMAbstractCreative) {
creativeInterstitialDidCloseHandler?(creative)
}
var creativeClickthroughDidCloseHandler: PBMCreativeViewDelegateHandler?
func creativeClickthroughDidClose(_ creative: PBMAbstractCreative) {
creativeClickthroughDidCloseHandler?(creative)
}
var creativeReadyToReimplantHandler: PBMCreativeViewDelegateHandler?
func creativeReady(toReimplant creative: PBMAbstractCreative) {
creativeReadyToReimplantHandler?(creative)
}
var creativeMraidDidCollapseHandler: PBMCreativeViewDelegateHandler?
func creativeMraidDidCollapse(_ creative: PBMAbstractCreative) {
creativeMraidDidCollapseHandler?(creative)
}
var creativeMraidDidExpandHandler: PBMCreativeViewDelegateHandler?
func creativeMraidDidExpand(_ creative: PBMAbstractCreative) {
creativeMraidDidExpandHandler?(creative)
}
var creativeDidCompleteHandler: PBMCreativeViewDelegateHandler?
func creativeDidComplete(_ creative: PBMAbstractCreative) {
creativeDidCompleteHandler?(creative)
}
var creativeWasClickedHandler: ((PBMAbstractCreative) -> Void)?
func creativeWasClicked(_ creative: PBMAbstractCreative) {
creativeWasClickedHandler?(creative)
}
func videoCreativeDidComplete(_ creative: PBMAbstractCreative) {}
func creativeDidDisplay(_ creative: PBMAbstractCreative) {}
func creativeViewWasClicked(_ creative: PBMAbstractCreative) {}
func creativeFullScreenDidFinish(_ creative: PBMAbstractCreative) {}
// MARK: - Utilities
/**
Setup an expectation and associated, mocked `PBMWebView` to fulfill that expectation.
- parameters:
- shouldFulfill: Whether or not the expecation is expected to fulfill
- message: If `shouldFulfill`, the error message to check against
- action: If `shouldFulfill`, the action to check against
*/
func mraidErrorExpectation(shouldFulfill: Bool, message expectedMessage: String? = nil, action expectedAction: PBMMRAIDAction? = nil, file: StaticString = #file, line: UInt = #line) {
let exp = expectation(description: "Should \(shouldFulfill ? "" : "not ")call webview with an MRAID error")
exp.isInverted = !shouldFulfill
mockWebView.mock_MRAID_error = { (actualMessage, actualAction) in
if shouldFulfill {
PBMAssertEq(actualMessage, expectedMessage, file: file, line: line)
PBMAssertEq(actualAction, expectedAction, file: file, line: line)
}
exp.fulfill()
}
}
func createLoader(connection: ServerConnectionProtocol) -> PBMCreativeFactoryDownloadDataCompletionClosure {
let result: PBMCreativeFactoryDownloadDataCompletionClosure = {url, completionBlock in
let downloader = PBMDownloadDataHelper(serverConnection:connection)
downloader.downloadData(for: url, completionClosure: { (data:Data?, error:Error?) in
completionBlock(data,error)
})
}
return result
}
}
| apache-2.0 | 2f26ce84cc914c0ada9e2c833b592b70 | 39.72561 | 187 | 0.710286 | 5.853637 | false | false | false | false |
thion/bialoszewski.app | bialoszewski/RecordIconLayer.swift | 1 | 2590 | //
// RecordIconLayer.swift
// bialoszewski
//
// Created by Kamil Nicieja on 03/08/14.
// Copyright (c) 2014 Kamil Nicieja. All rights reserved.
//
import QuartzCore
class RecordIconLayer: CALayer {
var startAngle: CGFloat!
var endAngle: CGFloat!
var fillColor: UIColor!
var strokeWidth: CGFloat!
var strokeColor: UIColor!
override init(layer: AnyObject) {
super.init(layer: layer)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawInContext(ctx: CGContextRef) {
var center: CGPoint = CGPointMake(bounds.size.width / 2, bounds.size.height / 2)
var radius: CGFloat = min(center.x, center.y)
CGContextBeginPath(ctx)
CGContextMoveToPoint(ctx, center.x, center.y)
var floated: Float = Float(startAngle)
var cosinus: CGFloat = CGFloat(cosf(floated))
var sinus: CGFloat = CGFloat(sinf(floated))
var p1: CGPoint = CGPointMake(center.x + radius * cosinus, center.y + radius * sinus)
CGContextAddLineToPoint(ctx, p1.x, p1.y)
var clockwise: Int = Int(startAngle > endAngle)
CGContextAddArc(ctx, center.x, center.y, radius, startAngle, endAngle, Int32(clockwise))
CGContextClosePath(ctx)
CGContextSetStrokeColorWithColor(ctx, strokeColor.CGColor)
CGContextSetFillColorWithColor(ctx, fillColor.CGColor)
CGContextSetLineWidth(ctx, strokeWidth)
CGContextSetLineCap(ctx, kCGLineCapButt)
CGContextDrawPath(ctx, kCGPathFillStroke)
CGContextBeginPath(ctx)
CGContextMoveToPoint(ctx, center.x, center.y)
CGContextAddLineToPoint(ctx, p1.x, p1.y)
CGContextAddArc(ctx, center.x, center.y, radius, startAngle, endAngle, Int32(clockwise))
CGContextEOClip(ctx)
var image: UIImage = UIImage(named: "Empty.png")
var mask: CGImageRef = image.CGImage
var imageRect: CGRect = CGRectMake(center.x, center.y, image.size.width, image.size.height)
CGContextTranslateCTM(ctx, 0, image.size.height)
CGContextScaleCTM(ctx, 1.0, -1.0)
CGContextTranslateCTM(ctx, imageRect.origin.x, imageRect.origin.y)
CGContextRotateCTM(ctx, rad(-90))
CGContextTranslateCTM(ctx, imageRect.size.width * -0.534, imageRect.size.height * -0.474)
CGContextDrawImage(ctx, self.bounds, mask)
}
func rad(degrees: Int) -> CGFloat {
return (CGFloat(degrees) / (180.0 / CGFloat(M_PI)))
}
}
| mit | 4f9bf1351ba744d35f6469dded237c5c | 32.636364 | 99 | 0.657529 | 4.190939 | false | false | false | false |
naokits/my-programming-marathon | IBDesignableDemo/IBDesignableDemo/CustomButton.swift | 1 | 690 | //
// CustomButton.swift
// IBDesignableDemo
//
// Created by Naoki Tsutsui on 1/29/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import UIKit
@IBDesignable
class CustomButton: UIButton {
@IBInspectable var textColor: UIColor?
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
}
| mit | 96d1c028a5bfcacb833f317e5205e920 | 18.685714 | 68 | 0.599419 | 4.784722 | false | false | false | false |
akio0911/til | 20201206/CombineInPractice/CombineInPractice/ViewController.swift | 1 | 2253 | //
// ViewController.swift
// CombineInPractice
//
// Created by akio0911 on 2020/12/06.
//
import UIKit
import Combine
private extension Notification.Name {
static let newTrickDownload = Notification.Name(rawValue: "newTrickDownload")
}
struct MagicTrick: Decodable {
static let placeholder = MagicTrick()
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let trickNamePublisher: NotificationCenter.Publisher
// = NotificationCenter.default.publisher(for: .newTrickDownload)
// 定義は以下のようになっている
// extension NotificationCenter {
// public struct Publisher : Publisher {
// public typealias Output = Notification
// public typealias Failure = Never
// let trickNamePublisher: Publishers.Map<NotificationCenter.Publisher, Data>
// = NotificationCenter.default.publisher(for: .newTrickDownload)
// .map({ notification in
// return notification.userInfo?["data"] as! Data
// })
// 定義は以下のようになっている
// public struct Map<Upstream, Output> : Publisher where Upstream : Publisher {
// public typealias Failure = Upstream.Failure
}
// let trickNamePublisher: Publishers.TryMap<NotificationCenter.Publisher, MagicTrick>
// = NotificationCenter.default.publisher(for: .newTrickDownload)
// .map({ notification in
// return notification.userInfo?["data"] as! Data
// })
// .tryMap { data -> MagicTrick in
// let decoder = JSONDecoder()
// return try decoder.decode(MagicTrick.self, from: data)
// }
let trickNamePublisher: Publishers.Catch<Publishers.Decode<Publishers.Map<NotificationCenter.Publisher, JSONDecoder.Input>, MagicTrick, JSONDecoder>, Just<MagicTrick>>
= NotificationCenter.default.publisher(for: .newTrickDownload)
.map({ notification in
return notification.userInfo?["data"] as! Data
})
.decode(type: MagicTrick.self, decoder: JSONDecoder())
.catch { error in
return Just(MagicTrick.placeholder)
}
}
| mit | 620782f051d29215ce4f45b126497a5b | 32.8 | 171 | 0.649977 | 4.664544 | false | false | false | false |
MadAppGang/SmartLog | iOS/Pods/CoreStore/Sources/SQLiteStore.swift | 2 | 17754 | //
// SQLiteStore.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// 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 CoreData
// MARK: - SQLiteStore
/**
A storage interface that is backed by an SQLite database.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was depending on CoreStore's default directories prior to 2.0.0, make sure to use the `SQLiteStore.legacy(...)` factory methods to create the `SQLiteStore` instead of using initializers directly.
*/
public final class SQLiteStore: LocalStorage {
/**
Initializes an SQLite store interface from the given SQLite file URL. When this instance is passed to the `DataStack`'s `addStorage()` methods, a new SQLite file will be created if it does not exist.
- parameter fileURL: the local file URL for the target SQLite persistent store. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter migrationMappingProviders: an array of `SchemaMappingProviders` that provides the complete mapping models for custom migrations. All lightweight inferred mappings and/or migration mappings provided by *xcmappingmodel files are automatically used as fallback (as `InferredSchemaMappingProvider`) and may be omitted from the array.
- parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.none`.
*/
public init(fileURL: URL, configuration: ModelConfiguration = nil, migrationMappingProviders: [SchemaMappingProvider] = [], localStorageOptions: LocalStorageOptions = nil) {
self.fileURL = fileURL
self.configuration = configuration
self.migrationMappingProviders = migrationMappingProviders
self.localStorageOptions = localStorageOptions
}
/**
Initializes an SQLite store interface from the given SQLite file name. When this instance is passed to the `DataStack`'s `addStorage()` methods, a new SQLite file will be created if it does not exist.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was depending on CoreStore's default directories prior to 2.0.0, make sure to use the `SQLiteStore.legacy(...)` factory methods to create the `SQLiteStore` instead of using initializers directly.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support/<bundle id>" directory (or the "Caches/<bundle id>" directory on tvOS). Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter migrationMappingProviders: an array of `SchemaMappingProviders` that provides the complete mapping models for custom migrations. All lightweight inferred mappings and/or migration mappings provided by *xcmappingmodel files are automatically used as fallback (as `InferredSchemaMappingProvider`) and may be omitted from the array.
- parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.None`.
*/
public init(fileName: String, configuration: ModelConfiguration = nil, migrationMappingProviders: [SchemaMappingProvider] = [], localStorageOptions: LocalStorageOptions = nil) {
self.fileURL = SQLiteStore.defaultRootDirectory
.appendingPathComponent(fileName, isDirectory: false)
self.configuration = configuration
self.migrationMappingProviders = migrationMappingProviders
self.localStorageOptions = localStorageOptions
}
/**
Initializes an `SQLiteStore` with an all-default settings: a `fileURL` pointing to a "<Application name>.sqlite" file in the "Application Support/<bundle id>" directory (or the "Caches/<bundle id>" directory on tvOS), a `nil` `configuration` pertaining to the "Default" configuration, a `migrationMappingProviders` set to empty, and `localStorageOptions` set to `.AllowProgresiveMigration`.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was depending on CoreStore's default directories prior to 2.0.0, make sure to use the `SQLiteStore.legacy(...)` factory methods to create the `SQLiteStore` instead of using initializers directly.
*/
public init() {
self.fileURL = SQLiteStore.defaultFileURL
self.configuration = nil
self.migrationMappingProviders = []
self.localStorageOptions = nil
}
/**
Initializes an SQLite store interface from the given SQLite file name. When this instance is passed to the `DataStack`'s `addStorage()` methods, a new SQLite file will be created if it does not exist.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was depending on CoreStore's default directories prior to 2.0.0, make sure to use the `SQLiteStore.legacy(...)` factory methods to create the `SQLiteStore` instead of using initializers directly.
- parameter legacyFileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter migrationMappingProviders: an array of `SchemaMappingProviders` that provides the complete mapping models for custom migrations. All lightweight inferred mappings and/or migration mappings provided by *xcmappingmodel files are automatically used as fallback (as `InferredSchemaMappingProvider`) and may be omitted from the array.
- parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.None`.
*/
public static func legacy(fileName: String, configuration: ModelConfiguration = nil, migrationMappingProviders: [SchemaMappingProvider] = [], localStorageOptions: LocalStorageOptions = nil) -> SQLiteStore {
return SQLiteStore(
fileURL: SQLiteStore.legacyDefaultRootDirectory
.appendingPathComponent(fileName, isDirectory: false),
configuration: configuration,
migrationMappingProviders: migrationMappingProviders,
localStorageOptions: localStorageOptions
)
}
/**
Initializes an `LegacySQLiteStore` with an all-default settings: a `fileURL` pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS), a `nil` `configuration` pertaining to the "Default" configuration, a `migrationMappingProviders` set to empty, and `localStorageOptions` set to `.AllowProgresiveMigration`.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was depending on CoreStore's default directories prior to 2.0.0, make sure to use the `SQLiteStore.legacy(...)` factory methods to create the `SQLiteStore` instead of using initializers directly.
*/
public static func legacy() -> SQLiteStore {
return SQLiteStore(
fileURL: SQLiteStore.legacyDefaultFileURL,
configuration: nil,
migrationMappingProviders: [],
localStorageOptions: nil
)
}
// MARK: StorageInterface
/**
The string identifier for the `NSPersistentStore`'s `type` property. For `SQLiteStore`s, this is always set to `NSSQLiteStoreType`.
*/
public static let storeType = NSSQLiteStoreType
/**
The configuration name in the model file
*/
public let configuration: ModelConfiguration
/**
The options dictionary for the `NSPersistentStore`. For `SQLiteStore`s, this is always set to
```
[NSSQLitePragmasOption: ["journal_mode": "WAL"]]
```
*/
public let storeOptions: [AnyHashable: Any]? = [NSSQLitePragmasOption: ["journal_mode": "WAL"]]
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func cs_didAddToDataStack(_ dataStack: DataStack) {
self.dataStack = dataStack
}
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func cs_didRemoveFromDataStack(_ dataStack: DataStack) {
self.dataStack = nil
}
// MAKR: LocalStorage
/**
The `NSURL` that points to the SQLite file
*/
public let fileURL: URL
/**
An array of `SchemaMappingProviders` that provides the complete mapping models for custom migrations.
*/
public let migrationMappingProviders: [SchemaMappingProvider]
/**
Options that tell the `DataStack` how to setup the persistent store
*/
public var localStorageOptions: LocalStorageOptions
/**
The options dictionary for the specified `LocalStorageOptions`
*/
public func dictionary(forOptions options: LocalStorageOptions) -> [AnyHashable: Any]? {
if options == .none {
return self.storeOptions
}
var storeOptions = self.storeOptions ?? [:]
if options.contains(.allowSynchronousLightweightMigration) {
storeOptions[NSMigratePersistentStoresAutomaticallyOption] = true
storeOptions[NSInferMappingModelAutomaticallyOption] = true
}
return storeOptions
}
/**
Called by the `DataStack` to perform actual deletion of the store file from disk. Do not call directly! The `sourceModel` argument is a hint for the existing store's model version. For `SQLiteStore`, this converts the database's WAL journaling mode to DELETE before deleting the file.
*/
public func cs_eraseStorageAndWait(metadata: [String: Any], soureModelHint: NSManagedObjectModel?) throws {
// TODO: check if attached to persistent store
func deleteFiles(storeURL: URL, extraFiles: [String] = []) throws {
let fileManager = FileManager.default
let extraFiles: [String] = [
storeURL.path.appending("-wal"),
storeURL.path.appending("-shm")
]
do {
let trashURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!)
.appendingPathComponent(Bundle.main.bundleIdentifier ?? "com.CoreStore.DataStack", isDirectory: true)
.appendingPathComponent("trash", isDirectory: true)
try fileManager.createDirectory(
at: trashURL,
withIntermediateDirectories: true,
attributes: nil
)
let temporaryFileURL = trashURL.appendingPathComponent(UUID().uuidString, isDirectory: false)
try fileManager.moveItem(at: storeURL, to: temporaryFileURL)
let extraTemporaryFiles = extraFiles.map { (extraFile) -> String in
let temporaryFile = trashURL.appendingPathComponent(UUID().uuidString, isDirectory: false).path
if let _ = try? fileManager.moveItem(atPath: extraFile, toPath: temporaryFile) {
return temporaryFile
}
return extraFile
}
DispatchQueue.global(qos: .background).async {
_ = try? fileManager.removeItem(at: temporaryFileURL)
extraTemporaryFiles.forEach({ _ = try? fileManager.removeItem(atPath: $0) })
}
}
catch {
try fileManager.removeItem(at: storeURL)
extraFiles.forEach({ _ = try? fileManager.removeItem(atPath: $0) })
}
}
let fileURL = self.fileURL
try autoreleasepool {
if let soureModel = soureModelHint ?? NSManagedObjectModel.mergedModel(from: nil, forStoreMetadata: metadata) {
let journalUpdatingCoordinator = NSPersistentStoreCoordinator(managedObjectModel: soureModel)
let store = try journalUpdatingCoordinator.addPersistentStore(
ofType: type(of: self).storeType,
configurationName: self.configuration,
at: fileURL,
options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]]
)
try journalUpdatingCoordinator.remove(store)
}
try deleteFiles(storeURL: fileURL)
}
}
// MARK: Internal
internal static let defaultRootDirectory: URL = cs_lazy {
#if os(tvOS)
let systemDirectorySearchPath = FileManager.SearchPathDirectory.cachesDirectory
#else
let systemDirectorySearchPath = FileManager.SearchPathDirectory.applicationSupportDirectory
#endif
let defaultSystemDirectory = FileManager.default.urls(
for: systemDirectorySearchPath,
in: .userDomainMask).first!
return defaultSystemDirectory.appendingPathComponent(
Bundle.main.bundleIdentifier ?? "com.CoreStore.DataStack",
isDirectory: true
)
}
internal static let defaultFileURL = SQLiteStore.defaultRootDirectory
.appendingPathComponent(
(Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String) ?? "CoreData",
isDirectory: false
)
.appendingPathExtension("sqlite")
internal static let legacyDefaultRootDirectory: URL = cs_lazy {
#if os(tvOS)
let systemDirectorySearchPath = FileManager.SearchPathDirectory.cachesDirectory
#else
let systemDirectorySearchPath = FileManager.SearchPathDirectory.applicationSupportDirectory
#endif
return FileManager.default.urls(
for: systemDirectorySearchPath,
in: .userDomainMask).first!
}
internal static let legacyDefaultFileURL = cs_lazy {
return SQLiteStore.legacyDefaultRootDirectory
.appendingPathComponent(DataStack.applicationName, isDirectory: false)
.appendingPathExtension("sqlite")
}
// MARK: Private
private weak var dataStack: DataStack?
// MARK: Obsoleted
@available(*, obsoleted: 3.1, message: "The `mappingModelBundles` argument of this method is ignored. Use the new SQLiteStore.init(fileURL:configuration:migrationMappingProviders:localStorageOptions:) initializer instead.")
public convenience init(fileURL: URL, configuration: ModelConfiguration = nil, mappingModelBundles: [Bundle], localStorageOptions: LocalStorageOptions = nil) {
fatalError()
}
@available(*, obsoleted: 3.1, message: "The `mappingModelBundles` argument of this method is ignored. Use the new SQLiteStore.init(fileName:configuration:migrationMappingProviders:localStorageOptions:) initializer instead.")
public convenience init(fileName: String, configuration: ModelConfiguration = nil, mappingModelBundles: [Bundle], localStorageOptions: LocalStorageOptions = nil) {
fatalError()
}
}
| mit | 58802ffcbd26b0ec4b13574d79a12b40 | 52.960486 | 395 | 0.6858 | 5.671885 | false | true | false | false |
spire-inc/Bond | Sources/UIKit/UIControl.swift | 6 | 2448 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// 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 ReactiveKit
import UIKit
public extension UIControl {
public func bnd_controlEvents(_ events: UIControlEvents) -> Signal1<Void> {
let _self = self
return Signal { [weak _self] observer in
guard let _self = _self else {
observer.completed()
return NonDisposable.instance
}
let target = BNDControlTarget(control: _self, events: events) {
observer.next()
}
return BlockDisposable {
target.unregister()
}
}.take(until: bnd_deallocated)
}
public var bnd_isEnabled: Bond<UIControl, Bool> {
return Bond(target: self) { $0.isEnabled = $1 }
}
}
@objc fileprivate class BNDControlTarget: NSObject
{
private weak var control: UIControl?
private let observer: () -> Void
private let events: UIControlEvents
fileprivate init(control: UIControl, events: UIControlEvents, observer: @escaping () -> Void) {
self.control = control
self.events = events
self.observer = observer
super.init()
control.addTarget(self, action: #selector(actionHandler), for: events)
}
@objc private func actionHandler() {
observer()
}
fileprivate func unregister() {
control?.removeTarget(self, action: nil, for: events)
}
deinit {
unregister()
}
}
| mit | c2d9154477994d3e4fec5540f7c22a02 | 30.384615 | 97 | 0.70098 | 4.302285 | false | false | false | false |
iamyuiwong/swift-common | org.yuiwong/org.yuiwong.Numeric.swift | 1 | 2127 | /* ========================================================================
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ======================================================================== */
import Foundation
extension org.yuiwong {
/**
* @name struct Numeric - numeric util struct
* @desc org.yuiwong.Numeric.*
*/
public struct Numeric {
/**
* @name toUInt64 - fromDouble
* @fail if double to large
*/
public static func toUInt64(fromDouble d: Double) -> UInt64? {
if (d > Double(UInt64.max)) {
return nil
}
return UInt64(d)
}
/**
* @name isGreaterThanUInt64Max - ofDouble - if double > UInt64.max
* @note @d should not NaN
*/
public static func isGreaterThanUInt64Max(ofDouble d: Double) -> Bool {
return ((Double.infinity == d) || (d > Double(UInt64.max)))
}
/**
* @name isLEInt64Max - ofDouble - if double <= Int64.max
* @note @d should not NaN
*/
public static func isLEInt64Max(ofDouble d: Double) -> Bool {
return (d <= Double(Int64.max))
}
/**
* @name isGEInt64Min - ofDouble - if double >= Int64.min
* @note @d should not NaN
*/
public static func isGEInt64Min(ofDouble d: Double) -> Bool {
return (d >= Double(Int64.min))
}
/**
* @name canCastToInt64 - chk double if valid
*/
public static func canCastToInt64(ofDouble d: Double) -> Bool {
if (d.isNaN) {
return false
}
if ((Double.infinity == d) || (-Double.infinity == d)) {
return false
}
return ((d >= Double(Int64.min)) && (d <= Double(Int64.max)))
}
}
}
| lgpl-3.0 | bee950b2cc299591ac52583e9afc8764 | 28.541667 | 78 | 0.624354 | 3.498355 | false | false | false | false |
eviathan/Vexed | Vexed/CrossFlag.swift | 1 | 4700 | //
// File.swift
// Vexed
//
// Created by Brian Williams on 09/08/2017.
// Copyright © 2017 Brian Williams. All rights reserved.
//
import Foundation
import UIKit
// TODO:
// • Add Diagonal Cross
// • Fix Overlay Cross
class CrossFlag : Flag {
var xOffset = CGFloat(1.0)
var yOffset = CGFloat(1.0)
var thickness = CGFloat(40.0)
var floatingScale = CGFloat(0.6)
var randomNumber = arc4random_uniform(4)
var isOffset: Bool { get { return randomNumber % 30 == 0 } }
var isDoubleLayered: Bool { get { return randomNumber % 3 == 0 && thickness > 80 } }
var isDoubleLayeredOffset: Bool { get { return randomNumber % 2 == 0 } }
var isFloating: Bool = false
var backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
var crossColor = UIColor.random()
func draw(rect: CGRect) -> CALayer {
let layer: CAShapeLayer = CAShapeLayer()
randomiseValues()
// Draw BG
layer.addSublayer(drawBackground(rect: rect, type:.Simple))
// Draw Cross
layer.addSublayer(drawCross(rect: rect))
return layer;
}
func randomiseValues(){
thickness = CGFloat(arc4random_uniform(100) + 40)
yOffset = isOffset ? CGFloat(0.5) : CGFloat(1.0)
}
func drawCross(rect: CGRect) -> CAShapeLayer{
let layer = CAShapeLayer()
drawStandardCross(rect: rect, layer: layer)
//drawCrossOverlay(rect: rect, layer: layer)
return layer
}
func drawStandardCross(rect: CGRect, layer: CAShapeLayer) {
let horizontal = CAShapeLayer()
if isFloating {
}
else {
horizontal.path = UIBezierPath(rect: CGRect(x: 0, y: ((rect.height * 0.5) - (thickness * 0.5)) * yOffset, width: rect.width, height: thickness)).cgPath
}
horizontal.fillColor = crossColor.cgColor
layer.addSublayer(horizontal)
let vertical = CAShapeLayer()
if isFloating {
}
else {
vertical.path = UIBezierPath(rect: CGRect(x: ((rect.width * 0.5) - (thickness * 0.5)) * xOffset, y: 0, width: thickness, height: rect.height)).cgPath
}
vertical.fillColor = crossColor.cgColor
layer.addSublayer(vertical)
}
func drawCrossOverlay(rect: CGRect, layer: CAShapeLayer){
if isDoubleLayered {
let crossColorB = UIColor.random().cgColor
let offsetMultiplier = CGFloat(0.6)
if !isDoubleLayeredOffset {
let horizontal = CAShapeLayer()
if isFloating {
}
else {
horizontal.path = UIBezierPath(rect: CGRect(x: 0, y: ((rect.height * 0.5) - (thickness * 0.5)) * yOffset, width: rect.width, height: thickness * offsetMultiplier)).cgPath
}
horizontal.fillColor = crossColorB
layer.addSublayer(horizontal)
let vertical = CAShapeLayer()
if isFloating {
}
else {
vertical.path = UIBezierPath(rect: CGRect(x: ((rect.width * 0.5) - (thickness * 0.5)) * xOffset, y: 0, width: thickness * offsetMultiplier, height: rect.height)).cgPath
}
vertical.fillColor = crossColorB
layer.addSublayer(vertical)
}
else {
let horizontal = CAShapeLayer()
if isFloating {
}
else {
horizontal.path = UIBezierPath(rect: CGRect(x: 0, y: ((rect.height * 0.5) - ((thickness * offsetMultiplier) * 0.5)) * yOffset, width: rect.width, height: thickness * offsetMultiplier)).cgPath
}
horizontal.fillColor = crossColorB
layer.addSublayer(horizontal)
let vertical = CAShapeLayer()
if isFloating {
}
else {
vertical.path = UIBezierPath(rect: CGRect(
x: ((rect.width * 0.5 * xOffset) - ((thickness * offsetMultiplier) * 0.5)),
y: 0,
width: thickness * offsetMultiplier,
height: rect.height)).cgPath
}
vertical.fillColor = crossColorB
layer.addSublayer(vertical)
}
}
}
}
| mit | 9d186a330b5584bbae330b674f1c74c9 | 32.297872 | 211 | 0.515868 | 4.952532 | false | false | false | false |
adonoho/XCGLogger | Sources/XCGLogger/LogFormatters/PrePostFixLogFormatter.swift | 6 | 3222 | //
// PrePostFixLogFormatter.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2016-09-20.
// Copyright © 2016 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
#if os(macOS)
import AppKit
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#endif
// MARK: - PrePostFixLogFormatter
/// A log formatter that will optionally add a prefix, and/or postfix string to a message
open class PrePostFixLogFormatter: LogFormatterProtocol, CustomDebugStringConvertible {
/// Internal cache of the prefix strings for each log level
internal var prefixStrings: [XCGLogger.Level: String] = [:]
/// Internal cache of the postfix strings codes for each log level
internal var postfixStrings: [XCGLogger.Level: String] = [:]
public init() {
}
/// Set the prefix/postfix strings for a specific log level.
///
/// - Parameters:
/// - prefix: A string to prepend to log messages.
/// - postfix: A string to postpend to log messages.
/// - level: The log level.
///
/// - Returns: Nothing
///
open func apply(prefix: String? = nil, postfix: String? = nil, to level: XCGLogger.Level? = nil) {
guard let level = level else {
guard prefix != nil || postfix != nil else { clearFormatting(); return }
// No level specified, so, apply to all levels
for level in XCGLogger.Level.allCases {
self.apply(prefix: prefix, postfix: postfix, to: level)
}
return
}
if let prefix = prefix {
prefixStrings[level] = prefix
}
else {
prefixStrings.removeValue(forKey: level)
}
if let postfix = postfix {
postfixStrings[level] = postfix
}
else {
postfixStrings.removeValue(forKey: level)
}
}
/// Clear all previously set colours. (Sets each log level back to default)
///
/// - Parameters: None
///
/// - Returns: Nothing
///
open func clearFormatting() {
prefixStrings = [:]
postfixStrings = [:]
}
// MARK: - LogFormatterProtocol
/// Apply some additional formatting to the message if appropriate.
///
/// - Parameters:
/// - logDetails: The log details.
/// - message: Formatted/processed message ready for output.
///
/// - Returns: message with the additional formatting
///
@discardableResult open func format(logDetails: inout LogDetails, message: inout String) -> String {
message = "\(prefixStrings[logDetails.level] ?? "")\(message)\(postfixStrings[logDetails.level] ?? "")"
return message
}
// MARK: - CustomDebugStringConvertible
open var debugDescription: String {
get {
var description: String = "\(extractTypeName(self)): "
for level in XCGLogger.Level.allCases {
description += "\n\t- \(level) > \(prefixStrings[level] ?? "None") | \(postfixStrings[level] ?? "None")"
}
return description
}
}
}
| mit | 650d0efeac40fb917c79ded4e38b5807 | 31.21 | 120 | 0.598261 | 4.581792 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.