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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chaosspeeder/YourGoals
|
YourGoals/Business/DataSource/CommittedTasksDataSource.swift
|
1
|
3399
|
//
// CommittedTasksDataSource.swift
// YourGoals
//
// Created by André Claaßen on 09.11.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
/// data source for the classical today view about all committed tasks for a day.
/// this includes tasks of the day before
class CommittedTasksDataSource: ActionableDataSource, ActionablePositioningProtocol {
enum Mode {
case activeTasksIncluded
case activeTasksNotIncluded
case doneTasksNotIncluced
}
let taskManager:TaskCommitmentManager
let switchProtocolProvider:TaskSwitchProtocolProvider
let mode: Mode
let manager: GoalsStorageManager
/// initialize the data source with the core data storage managenr
///
/// - Parameters:
/// - manager: core data storage manager
/// - mode: active tasks or done tasks included or not
init(manager: GoalsStorageManager, mode: Mode = .activeTasksIncluded) {
self.manager = manager
self.mode = mode
self.taskManager = TaskCommitmentManager(manager: manager)
self.switchProtocolProvider = TaskSwitchProtocolProvider(manager: manager)
}
// MARK: ActionableTableViewDataSource
/// this data source doesn't provide sections
func fetchSections(forDate date: Date, withBackburned backburnedGoals: Bool) throws -> [ActionableSection] {
return []
}
/// fetch the actionables for the date/time as Actionable time infos with start/end time and progress
///
/// - Parameters:
/// - date: date/time
/// - backburnedGoals: include backburned goals or not
/// - andSection: this is ignored
/// - Returns: actionable time infos
/// - Throws: core data exception
func fetchItems(forDate date: Date, withBackburned backburnedGoals: Bool, andSection: ActionableSection?) throws -> [ActionableItem] {
let committedTasks = try taskManager.committedTasksTodayAndFromThePast(forDate: date, backburnedGoals: backburnedGoals)
var tasks:[Task]!
switch mode {
case .activeTasksIncluded:
tasks = committedTasks
case .activeTasksNotIncluded:
tasks = committedTasks.filter { !$0.isProgressing(atDate: date) }
case .doneTasksNotIncluced:
tasks = committedTasks.filter { $0.getTaskState() != .done }
}
let calculator = TodayScheduleCalculator(manager: self.manager)
let timeInfos = try calculator.calculateTimeInfos(forTime: date, actionables: tasks)
return timeInfos
}
func positioningProtocol() -> ActionablePositioningProtocol? {
return self
}
func switchProtocol(forBehavior behavior: ActionableBehavior) -> ActionableSwitchProtocol? {
return self.switchProtocolProvider.switchProtocol(forBehavior: behavior)
}
// MARK: ActionablePositioningProtocol
func updatePosition(items: [ActionableItem], fromPosition: Int, toPosition: Int) throws {
let tasks = items.map { ($0.actionable as! Task) }
try self.taskManager.updateTaskPosition(tasks: tasks, fromPosition: fromPosition, toPosition: toPosition)
}
func moveIntoSection(item: ActionableItem, section: ActionableSection, toPosition: Int) throws {
assertionFailure("this method shouldn't be called")
}
}
|
lgpl-3.0
|
ffb8fc90b2ca6614ce73f568b64eda7e
| 36.711111 | 138 | 0.686506 | 4.760168 | false | false | false | false |
geekaurora/ReactiveListViewKit
|
Example/ReactiveListViewKitDemo/UI Layer/FeedList/HotUsers/HotUserCellCardView.swift
|
1
|
2580
|
//
// HotUserCellView.swift
// ReactiveListViewKit
//
// Created by Cheng Zhang on 3/4/17.
// Copyright © 2017 Cheng Zhang. All rights reserved.
//
import CZUtils
import ReactiveListViewKit
class HotUserCellCardView: CZNibLoadableView, CZFeedCellViewSizeCalculatable {
@IBOutlet var frameView: UIView?
@IBOutlet var contentView: UIView?
@IBOutlet var stackView: UIStackView?
@IBOutlet var portaitView: UIImageView?
@IBOutlet var nameLabel: UILabel?
@IBOutlet var detailsLabel: UILabel?
@IBOutlet var followButton: UIButton?
@IBOutlet var closeButton: UIButton?
private var viewModel: HotUserCellViewModel
var diffId: String {return viewModel.diffId}
var onAction: OnAction?
required init(viewModel: CZFeedViewModelable?, onAction: OnAction?) {
guard let viewModel = viewModel as? HotUserCellViewModel else {
fatalError("Incorrect ViewModel type.")
}
self.viewModel = viewModel
self.onAction = onAction
super.init(frame: .zero)
backgroundColor = .white
config(with: viewModel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Must call designated initializer `init(viewModel:onAction:)`")
}
func config(with viewModel: CZFeedViewModelable?) {
guard let viewModel = viewModel as? HotUserCellViewModel else {
fatalError("Incorrect ViewModel type.")
}
if let portraitUrl = viewModel.portraitUrl {
portaitView?.cz_setImage(with: portraitUrl)
portaitView?.roundToCircle()
}
detailsLabel?.text = viewModel.fullName
nameLabel?.text = ""
followButton?.roundCorner(2)
closeButton?.roundCorner(2)
frameView?.roundCorner(2)
}
func config(with viewModel: CZFeedViewModelable?, prevViewModel: CZFeedViewModelable?) {}
static func sizeThatFits(_ containerSize: CGSize, viewModel: CZFeedViewModelable) -> CGSize {
return CZFacadeViewHelper.sizeThatFits(containerSize,
viewModel: viewModel,
viewClass: HotUserCellCardView.self,
isHorizontal: true)
}
@IBAction func tappedFollow(_ sender: UIButton) {
onAction?(SuggestedUserAction.follow(user: viewModel.user))
}
@IBAction func tappedClose(_ sender: UIButton) {
onAction?(SuggestedUserAction.ignore(user: viewModel.user))
}
}
|
mit
|
6c1d562c6a77af33cdb15d8cecbb7ed4
| 33.386667 | 97 | 0.639395 | 5.096838 | false | false | false | false |
Teiki/Cafea1e-iOS
|
Cafea1e/HttpClient.swift
|
1
|
953
|
//
// HttpClient.swift
// Café à 1€
//
// Created by Antoine GALTIER on 03/06/2016.
// Copyright © 2016 Teiki. All rights reserved.
//
import Foundation
protocol HttpClientDelegate {
func onDataGet(data : NSData)
}
class HttpClient {
static func request(delegate : HttpClientDelegate, url : String){
let requestURL: NSURL = NSURL(string: url)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
delegate.onDataGet(data!)
} else {
//error
}
}
task.resume()
}
}
|
gpl-3.0
|
aa46595f328a24a776f6d914d75fbcd3
| 24.648649 | 82 | 0.580169 | 4.836735 | false | false | false | false |
chaosarts/ChaosMath.swift
|
ChaosMath/vec3.swift
|
1
|
10719
|
//
// vec3.swift
// ChaosMath
//
// Created by Fu Lam Diep on 07/10/2016.
// Copyright © 2016 Fu Lam Diep. All rights reserved.
//
import Foundation
public struct tvec3<T: ArithmeticScalarType> : VectorType {
public typealias ElementType = T
public typealias SelfType = tvec3<ElementType>
/*
+--------------------------------------------------------------------------
| Static properties
+--------------------------------------------------------------------------
*/
/// Provides the dimension of this vector struct
public static var dim : Int {
return 3
}
/// Provides the first vector of the standard base
public static var e1 : SelfType {
return SelfType(1, 0, 0)
}
/// Provides the second vector of the standard base
public static var e2 : SelfType {
return SelfType(0, 1, 0)
}
/// Provides the second vector of the standard base
public static var e3 : SelfType {
return SelfType(0, 0, 1)
}
/*
+--------------------------------------------------------------------------
| Stored properties
+--------------------------------------------------------------------------
*/
/// Provides the x value of the vector
public var x: ElementType = 0
/// Provides the y value of the vector
public var y: ElementType = 0
/// Provides the z component of the vector
public var z: ElementType = 0
/*
+--------------------------------------------------------------------------
| Derived properties
+--------------------------------------------------------------------------
*/
/// Returns the vector as array
public var array : Array<ElementType> {
return [x, y, z]
}
/*
+--------------------------------------------------------------------------
| Initializers
+--------------------------------------------------------------------------
*/
/// Initializes the vector
/// - parameter x: The x component of the vector
/// - parameter y: The y component of the vector
/// - parameter z: The z component of the vector
public init <ForeignType: ArithmeticScalarType>(_ x: ForeignType = 0, _ y: ForeignType = 0, _ z: ForeignType = 0) {
self.x = ElementType(x)
self.y = ElementType(y)
self.z = ElementType(z)
}
/// Initializes the vector with an other
/// - parameters vec: The vector to copy
public init<ForeignType: ArithmeticScalarType> (_ vec: tvec3<ForeignType>) {
self.x = ElementType(vec.x)
self.y = ElementType(vec.y)
self.z = ElementType(vec.z)
}
/// Initializes the vector with a vec2 for x and y and a scalar for z
/// - parameter vec:
/// - parameter z:
public init<V: ArithmeticScalarType, S: ArithmeticScalarType> (_ vec: tvec2<V>, _ z: S = 0) {
self.x = ElementType(vec.x)
self.y = ElementType(vec.y)
self.z = ElementType(z)
}
/// Initializes the vector with a vec2 for y and z and a scalar for x
/// - parameter vec:
/// - parameter z:
public init<S: ArithmeticScalarType, V: ArithmeticScalarType> (_ x: S, _ vec: tvec2<V>) {
self.x = ElementType(x)
self.y = ElementType(vec.x)
self.z = ElementType(vec.y)
}
/// Implementation of the ExpressibleByIntegerLiteral protocol
/// - parameter value
public init (integerLiteral value: Int) {
self.init(ElementType(value), ElementType(value), ElementType(value))
}
/// Initializes the vector with an array
public init (arrayLiteral elements: ElementType...) {
if (elements.count > 0) {x = elements[0]}
if (elements.count > 1) {y = elements[1]}
if (elements.count > 2) {z = elements[2]}
}
}
public typealias vec3i = tvec3<Int>
public typealias vec3f = tvec3<Float>
public typealias vec3d = tvec3<Double>
public typealias vec3 = vec3f
/*
+--------------------------------------------------------------------------
| Operators
+--------------------------------------------------------------------------
*/
/// Negates the vector
/// - parameter value: The vector to be negated
/// - returns: The negated vector
public prefix func -<T: ArithmeticScalarType> (value: tvec3<T>) -> tvec3<T> {
return tvec3<T>(-value.x, -value.y, -value.z)
}
/// Sum operator
/// - parameter left: Left operand
/// - parameter right: Right operand
/// - returns: The sum of both operands
public func +<T: ArithmeticScalarType> (left: tvec3<T>, right: tvec3<T>) -> tvec3<T> {
let a : T = left.x + right.x
let b : T = left.y + right.y
let c : T = left.z + right.z
return tvec3<T>(a, b, c)
}
/// Returns the difference vector
/// - parameter left: Left operand
/// - parameter right: Right operand
/// - returns: The difference of both operands
public func -<T: ArithmeticScalarType> (left: tvec3<T>, right: tvec3<T>) -> tvec3<T> {
return left + (-right)
}
/// Returns the component wise product
/// - parameter left: Left operand
/// - parameter right: Right operand
/// - returns: The difference of both operands
public func *<T: ArithmeticScalarType> (left: tvec3<T>, right: tvec3<T>) -> tvec3<T> {
return tvec3<T>(left.x * right.x, left.y * right.y, left.z * right.z)
}
/// Multiplies a scalar with a vecotr
public func *<S: ArithmeticScalarType, T: ArithmeticScalarType> (left: S, right: tvec3<T>) -> tvec3<T> {
return tvec3<T>(T(left) * right.x, T(left) * right.y, T(left) * right.z)
}
/// Multiplies a scalar with a vecotr
public func *<T: ArithmeticScalarType, S: ArithmeticScalarType> (left: tvec3<T>, right: S) -> tvec3<T> {
return tvec3<T>(left.x * T(right), left.y * T(right), left.z * T(right))
}
/// Devides the vector by a scalar
public func /<T: ArithmeticScalarType, S: ArithmeticScalarType> (left: tvec3<T>, right: S) -> tvec3<T> {
return tvec3<T>(left.x / T(right), left.y / T(right), left.z / T(right))
}
/// Compound division operator
/// - parameter left: The left side of the operation
/// - parameter right: The right side of the operation
public func +=<T: ArithmeticScalarType> (left: inout tvec3<T>, right: tvec3<T>) {
left = left + right
}
/// Compound division operator
/// - parameter left: The left side of the operation
/// - parameter right: The right side of the operation
public func -=<T: ArithmeticScalarType> (left: inout tvec3<T>, right: tvec3<T>) {
left = left - right
}
/// Compound division operator
/// - parameter left: The left side of the operation
/// - parameter right: The right side of the operation
public func *=<T: ArithmeticScalarType> (left: inout tvec3<T>, right: tvec3<T>) {
left = left * right
}
/// Compound division operator
/// - parameter left: The left side of the operation
/// - parameter right: The right side of the operation
public func *=<T: ArithmeticScalarType, S: ArithmeticScalarType> (left: inout tvec3<T>, right: S) {
left = left * right
}
/// Compound division operator
/// - parameter left: The left side of the operation
/// - parameter right: The right side of the operation
public func /=<T: ArithmeticScalarType, S: ArithmeticScalarType> (left: inout tvec3<T>, right: S) {
left = left / T(right)
}
/// Compares to vectors
public func ==<T: ArithmeticScalarType> (left: tvec3<T>, right: tvec3<T>) -> Bool {
return left.x == right.x && left.y == right.y && left.z == right.z
}
/*
+--------------------------------------------------------------------------
| Operators
+--------------------------------------------------------------------------
*/
/// Returns the dot product of two vectors
public func dot<T: ArithmeticScalarType> (_ left: tvec3<T>, _ right: tvec3<T>) -> T {
let a : T = left.x * right.x
let b : T = left.y * right.y
let c : T = left.z * right.z
return a + b + c
}
/// Returns the (left hand oriented) normal of the given vectors
/// - parameter left: The left operand (thumb)
/// - parameter right: The right operand (pointer)
/// - returns: The normal vector (middlefinger) which is othogonal to left and right
public func cross<T: ArithmeticScalarType> (_ left: tvec3<T>, _ right: tvec3<T>) -> tvec3<T> {
let x1 : T = left.y * right.z
let x2 : T = left.z * right.y
let x : T = x1 - x2
let y1 : T = left.z * right.x
let y2 : T = left.x * right.z
let y : T = y1 - y2
let z1 : T = left.x * right.y
let z2 : T = left.y * right.x
let z : T = z1 - z2
return tvec3<T>(x, y, z)
}
/// Calculates the determinant of three given vectors
/// - parameter x:
/// - parameter y:
/// - parameter z:
/// - returns: The determinant of the three vectors
public func determinant<T :ArithmeticScalarType> (_ x: tvec3<T>, _ y: tvec3<T>, _ z: tvec3<T>) -> T {
let a1 : T = x.x * y.y * z.z
let a2 : T = y.x * z.y * x.z
let a3 : T = z.x * x.y * y.z
let a : T = a1 + a2 + a3
let b1 : T = z.x * y.y * x.z
let b2 : T = y.x * x.y * z.z
let b3 : T = x.x * z.y * y.z
let b : T = b1 + b2 + b3
return a - b
}
/// Returns the magnitude of the vector
/// - parameter value: The vector to calculate the magnitude from
/// - returns: The magnitude of the vector
public func magnitude<T: ArithmeticIntType> (_ value: tvec3<T>) -> Float {
return dot(value, value).sqrt()
}
/// Returns the magnitude of the vector
/// - parameter value: The vector to calculate the magnitude from
/// - returns: The magnitude of the vector
public func magnitude<T: ArithmeticFloatType> (_ value: tvec3<T>) -> T {
return dot(value, value).sqrt()
}
/// Normalizes the vector
/// - parameter value: The vector to normalize
/// - returns: The normalized vector
public func normalize<T: ArithmeticIntType> (_ value: tvec3<T>) -> vec3f {
let l = magnitude(value)
return vec3f(value.x.toFloat() / l, value.y.toFloat() / l, value.z.toFloat() / l)
}
/// Normalizes the vector
/// - parameter value: The vector to normalize
/// - returns: The normalized vector
public func normalize<T: ArithmeticFloatType> (_ value: tvec3<T>) -> tvec3<T> {
return value / magnitude(value)
}
/// Calculates the angle between two vectors
/// - parameter left
/// - parameter right
/// - returns: The angle in radian
public func angle<T: ArithmeticIntType> (_ left: tvec3<T>, _ right: tvec3<T>) -> Float {
let value : Float = dot(left, right).toFloat() / (magnitude(left) * magnitude(right))
return acos(value)
}
/// Calculates the angle between two vectors
/// - parameter left
/// - parameter right
/// - returns: The angle in radian
public func angle<T: ArithmeticFloatType> (_ left: tvec3<T>, _ right: tvec3<T>) -> T {
let value : T = dot(left, right) / (magnitude(left) * magnitude(right))
return value.acos()
}
|
gpl-3.0
|
63375a16a9a5b39aff085d2ca30929d6
| 29.276836 | 119 | 0.581638 | 3.616059 | false | false | false | false |
dreamsxin/swift
|
stdlib/public/core/UnfoldSequence.swift
|
1
|
4821
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Returns a sequence formed from `first` and repeated lazy applications of
/// `next`.
///
/// The first element in the sequence is always `first`, and each successive
/// element is the result of invoking `next` with the previous element. The
/// sequence ends when `next` returns `nil`. If `next` never returns `nil`, the
/// sequence is infinite.
///
/// This function can be used to replace many cases that were previously handled
/// using C-style `for` loops.
///
/// Example:
///
/// // Walk the elements of a tree from a node up to the root
/// for node in sequence(first: leaf, next: { $0.parent }) {
/// // node is leaf, then leaf.parent, then leaf.parent.parent, etc.
/// }
///
/// // Iterate over all powers of two (ignoring overflow)
/// for value in sequence(first: 1, next: { $0 * 2 }) {
/// // value is 1, then 2, then 4, then 8, etc.
/// }
///
/// - Parameter first: The first element to be returned from the sequence.
/// - Parameter next: A closure that accepts the previous sequence element and
/// returns the next element.
/// - Returns: A sequence that starts with `first` and continues with every
/// value returned by passing the previous element to `next`.
///
/// - SeeAlso: `sequence(state:next:)`
public func sequence<T>(first: T, next: (T) -> T?) -> UnfoldFirstSequence<T> {
// The trivial implementation where the state is the next value to return
// has the downside of being unnecessarily eager (it evaluates `next` one
// step in advance). We solve this by using a boolean value to disambiguate
// between the first value (that's computed in advance) and the rest.
return sequence(state: (first, true), next: { (state: inout (T?, Bool)) -> T? in
switch state {
case (let value, true):
state.1 = false
return value
case (let value?, _):
let nextValue = next(value)
state.0 = nextValue
return nextValue
case (nil, _):
return nil
}
})
}
/// Returns a sequence formed from repeated lazy applications of `next` to a
/// mutable `state`.
///
/// The elements of the sequence are obtaned by invoking `next` with a mutable
/// state. The same state is passed to all invocations of `next`, so subsequent
/// calls will see any mutations made by previous calls. The sequence ends when
/// `next` returns `nil`. If `next` never returns `nil`, the sequence is
/// infinite.
///
/// This function can be used to replace many instances of `AnyIterator` that
/// wrap a closure.
///
/// Example:
///
/// // Interleave two sequences that yield the same element type
/// sequence(state: (false, seq1.makeIterator(), seq2.makeIterator()), next: { iters in
/// iters.0 = !iters.0
/// return iters.0 ? iters.1.next() : iters.2.next()
/// })
///
/// - Parameter state: The initial state that will be passed to the closure.
/// - Parameter next: A closure that accepts an `inout` state and returns the
/// next element of the sequence.
/// - Returns: A sequence that yields each successive value from `next`.
///
/// - SeeAlso: `sequence(first:next:)`
public func sequence<T, State>(state: State, next: (inout State) -> T?)
-> UnfoldSequence<T, State> {
return UnfoldSequence(_state: state, _next: next)
}
/// The return type of `sequence(first:next:)`.
public typealias UnfoldFirstSequence<T> = UnfoldSequence<T, (T?, Bool)>
/// A sequence whose elements are produced via repeated applications of a
/// closure to some mutable state.
///
/// The elements of the sequence are computed lazily and the sequence may
/// potentially be infinite in length.
///
/// Instances of `UnfoldSequence` are created with the functions
/// `sequence(first:next:)` and `sequence(state:next:)`.
///
/// - SeeAlso: `sequence(first:next:)`, `sequence(state:next:)`
public struct UnfoldSequence<Element, State> : Sequence, IteratorProtocol {
public mutating func next() -> Element? {
guard !_done else { return nil }
if let elt = _next(&_state) {
return elt
} else {
_done = true
return nil
}
}
internal init(_state: State, _next: (inout State) -> Element?) {
self._state = _state
self._next = _next
}
internal var _state: State
internal let _next: (inout State) -> Element?
internal var _done = false
}
|
apache-2.0
|
edb53f73c826908ad74510b589fa228d
| 37.261905 | 91 | 0.642813 | 4.00083 | false | false | false | false |
dreamsxin/swift
|
test/expr/cast/set_bridge.swift
|
3
|
3655
|
// RUN: %target-parse-verify-swift
// REQUIRES: objc_interop
// FIXME: Should go into the standard library.
public extension _ObjectiveCBridgeable {
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self {
var result: Self? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
class Root : Hashable {
var hashValue: Int {
return 0
}
}
func ==(x: Root, y: Root) -> Bool { return true }
class ObjC : Root {
var x = 0
}
class DerivesObjC : ObjC { }
struct BridgedToObjC : Hashable, _ObjectiveCBridgeable {
static func _isBridgedToObjectiveC() -> Bool {
return true
}
func _bridgeToObjectiveC() -> ObjC {
return ObjC()
}
static func _forceBridgeFromObjectiveC(
_ x: ObjC,
result: inout BridgedToObjC?
) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: ObjC,
result: inout BridgedToObjC?
) -> Bool {
return true
}
var hashValue: Int {
return 0
}
}
func ==(x: BridgedToObjC, y: BridgedToObjC) -> Bool { return true }
func testUpcastBridge() {
var setR = Set<Root>()
var setO = Set<ObjC>()
var setD = Set<DerivesObjC>()
var setB = Set<BridgedToObjC>()
// Upcast to object types.
setR = setB; _ = setR
setO = setB; _ = setO
// Upcast object to bridged type
setB = setO // expected-error{{cannot assign value of type 'Set<ObjC>' to type 'Set<BridgedToObjC>'}}
// Failed upcast
setD = setB // expected-error{{cannot assign value of type 'Set<BridgedToObjC>' to type 'Set<DerivesObjC>'}}
_ = setD
}
func testForcedDowncastBridge() {
let setR = Set<Root>()
let setO = Set<ObjC>()
let setD = Set<DerivesObjC>()
let setB = Set<BridgedToObjC>()
_ = setR as! Set<BridgedToObjC>
_ = setO as! Set<BridgedToObjC>
_ = setD as! Set<BridgedToObjC> // expected-error {{'ObjC' is not a subtype of 'DerivesObjC'}}
// expected-note @-1 {{in cast from type 'Set<DerivesObjC>' to 'Set<BridgedToObjC>'}}
// TODO: the diagnostic for the below two examples should indicate that 'as'
// should be used instead of 'as!'
_ = setB as! Set<Root> // expected-error {{'Root' is not a subtype of 'BridgedToObjC'}}
// expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<Root>'}}
_ = setB as! Set<ObjC> // expected-error {{'ObjC' is not a subtype of 'BridgedToObjC'}}
// expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<ObjC>'}}
_ = setB as! Set<DerivesObjC> // expected-error {{'DerivesObjC' is not a subtype of 'BridgedToObjC'}}
// expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<DerivesObjC>'}}
}
func testConditionalDowncastBridge() {
var setR = Set<Root>()
var setO = Set<ObjC>()
var setD = Set<DerivesObjC>()
var setB = Set<BridgedToObjC>()
if let s = setR as? Set<BridgedToObjC> { }
if let s = setO as? Set<BridgedToObjC> { }
if let s = setD as? Set<BridgedToObjC> { } // expected-error {{'ObjC' is not a subtype of 'DerivesObjC'}}
// expected-note @-1 {{in cast from type 'Set<DerivesObjC>' to 'Set<BridgedToObjC>'}}
if let s = setB as? Set<Root> { } // expected-error {{'Root' is not a subtype of 'BridgedToObjC'}}
// expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<Root>'}}
if let s = setB as? Set<ObjC> { } // expected-error {{'ObjC' is not a subtype of 'BridgedToObjC'}}
// expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<ObjC>'}}
if let s = setB as? Set<DerivesObjC> { } // expected-error {{'DerivesObjC' is not a subtype of 'BridgedToObjC'}}
// expected-note @-1 {{in cast from type 'Set<BridgedToObjC>' to 'Set<DerivesObjC>'}}
}
|
apache-2.0
|
1f2c03266e0b247a8019ae0901473378
| 30.508621 | 114 | 0.655267 | 3.569336 | false | false | false | false |
nasser0099/Express
|
Express/HttpMethod.swift
|
1
|
1114
|
//===--- HttpMethod.swift -------------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express.
//
//Swift Express 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.
//
//Swift Express 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 Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import Foundation
public enum HttpMethod : String {
case Any = "*"
case Get = "GET"
case Post = "POST"
case Put = "PUT"
case Delete = "DELETE"
case Patch = "PATCH"
}
|
gpl-3.0
|
54a3989d888f20f9270b7f8f503a4fba
| 34.967742 | 80 | 0.627469 | 4.565574 | false | false | false | false |
KrishMunot/swift
|
benchmark/single-source/ErrorHandling.swift
|
3
|
955
|
//===--- ErrorHandling.swift ----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
enum PizzaError : ErrorProtocol {
case Pepperoni, Olives, Anchovy
}
@inline(never)
func doSomething() throws -> String {
var sb = "pi"
for str in ["z","z","a","?","?","?"] {
sb += str
if sb == "pizza" {
throw PizzaError.Anchovy
}
}
return sb
}
@inline(never)
public func run_ErrorHandling(_ N: Int) {
for _ in 1...5000*N {
do {
try doSomething()
} catch _ {
}
}
}
|
apache-2.0
|
150517c30a00c7b742fc0ab641899c67
| 22.292683 | 80 | 0.548691 | 3.979167 | false | false | false | false |
ppoh71/motoRoutes
|
motoRoutes/motoRouteCamera.swift
|
1
|
8208
|
//
// ViewController.swift
// SimpleCamera
//
// Created by Simon Ng on 25/11/14.
// Copyright (c) 2014 AppCoda. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
class motoRouteCamera: UIViewController {
@IBOutlet weak var cameraButton:UIButton!
@IBOutlet weak var cancelButton:UIButton!
@IBOutlet weak var savedImage:UIImageView!
//Capture Session
let captureSession = AVCaptureSession()
//camera devices
var backFacingCamera:AVCaptureDevice?
var frontFacingCamera:AVCaptureDevice?
var currentDevice:AVCaptureDevice?
//output
var stillImageOutput:AVCaptureStillImageOutput?
var stillImage:UIImage?
//preview layer / input
var cameraPreviewLayer:AVCaptureVideoPreviewLayer?
//add gesture
var toggleCameraGestureRecognizer = UISwipeGestureRecognizer()
//zoo, gesture
var zoomInGestureRecognizer = UISwipeGestureRecognizer()
var zoomOutGestureRecognizer = UISwipeGestureRecognizer()
// model store
var imageURL:String?
var latitude:Double = 0
var longitude:Double = 0
var MediaObjects = [MediaMaster]()
override func viewDidLoad() {
super.viewDidLoad()
// Preset the session for taking photo in full resolution
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as! [AVCaptureDevice]
// Get the front and back-facing camera for taking photos
for device in devices {
if device.position == AVCaptureDevicePosition.back {
backFacingCamera = device
} else if device.position == AVCaptureDevicePosition.front {
frontFacingCamera = device
}
}
currentDevice = backFacingCamera
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: currentDevice)
// Configure the session with the output for capturing still images
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
// Configure the session with the input and the output devices
captureSession.addInput(captureDeviceInput)
captureSession.addOutput(stillImageOutput)
} catch {
print(error)
}
// Provide a camera preview
cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
view.layer.addSublayer(cameraPreviewLayer!)
cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
cameraPreviewLayer?.frame = view.layer.frame
// Bring the camera button to front
view.bringSubview(toFront: cameraButton)
view.bringSubview(toFront: cancelButton)
view.bringSubview(toFront: savedImage)
captureSession.startRunning()
// Toggle Camera recognizer
toggleCameraGestureRecognizer.direction = .up
toggleCameraGestureRecognizer.addTarget(self, action: #selector(motoRouteCamera.toggleCamera))
view.addGestureRecognizer(toggleCameraGestureRecognizer)
// Zoom In recognizer
zoomInGestureRecognizer.direction = .right
zoomInGestureRecognizer.addTarget(self, action: #selector(motoRouteCamera.zoomIn))
view.addGestureRecognizer(zoomInGestureRecognizer)
// Zoom Out recognizer
zoomOutGestureRecognizer.direction = .left
zoomOutGestureRecognizer.addTarget(self, action: #selector(motoRouteCamera.zoomOut))
view.addGestureRecognizer(zoomOutGestureRecognizer)
print("latitude: \(latitude) / longitude: \(longitude) ")
}
/*
* toolge camera by swipe up
*/
func toggleCamera() {
captureSession.beginConfiguration()
// Change the device based on the current camera
let newDevice = (currentDevice?.position == AVCaptureDevicePosition.back) ? frontFacingCamera : backFacingCamera
// Remove all inputs from the session
for input in captureSession.inputs {
captureSession.removeInput(input as! AVCaptureDeviceInput)
}
// Change to the new input
let cameraInput:AVCaptureDeviceInput
do {
cameraInput = try AVCaptureDeviceInput(device: newDevice)
} catch {
print(error)
return
}
if captureSession.canAddInput(cameraInput) {
captureSession.addInput(cameraInput)
}
currentDevice = newDevice
captureSession.commitConfiguration()
}
/*
* zooom in/put by swipe right/left
*/
func zoomIn() {
if let zoomFactor = currentDevice?.videoZoomFactor {
if zoomFactor < 5.0 {
let newZoomFactor = min(zoomFactor + 1.0, 5.0)
do {
try currentDevice?.lockForConfiguration()
currentDevice?.ramp(toVideoZoomFactor: newZoomFactor, withRate: 1.0)
currentDevice?.unlockForConfiguration()
} catch {
print(error)
}
}
}
}
func zoomOut() {
if let zoomFactor = currentDevice?.videoZoomFactor {
if zoomFactor > 1.0 {
let newZoomFactor = max(zoomFactor - 1.0, 1.0)
do {
try currentDevice?.lockForConfiguration()
currentDevice?.ramp(toVideoZoomFactor: newZoomFactor, withRate: 1.0)
currentDevice?.unlockForConfiguration()
} catch {
print(error)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
print("memory warning from camera ")
}
@IBAction func capture(_ sender: AnyObject) {
print("capture")
let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo)
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (imageDataSampleBuffer, error) -> Void in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
self.stillImage = UIImage(data: imageData!)
self.savedImage.image = self.stillImage
let timestampFilename = String(Int(Date().timeIntervalSince1970)) + "_routeimg.png"
let filenamePath = URL(fileReferenceLiteralResourceName: Utils.getDocumentsDirectory().appendingPathComponent(timestampFilename))
// let imgData = try! imageData?.write(to: filenamePath, options: [])
self.imageURL = String(describing: filenamePath) //assign for unwind seague
print("capture done")
//save to Media Object
let tmpMediaObject = MediaMaster()
tmpMediaObject.latitude = self.latitude
tmpMediaObject.longitude = self.longitude
tmpMediaObject.image = timestampFilename
tmpMediaObject.timestamp = Date()
self.MediaObjects.append(tmpMediaObject)
})
/** deubg testing on simulator **/
//save to Media Object
/*
let tmpMediaObject = MediaMaster()
tmpMediaObject.latitude = self.latitude
tmpMediaObject.longitude = self.longitude
tmpMediaObject.image = "1458236404.png"
tmpMediaObject.timestamp = NSDate()
self.MediaObjects.append(tmpMediaObject)
print("########capture for simulator")
*/
}
}
|
apache-2.0
|
adb28dcca66bc6003880e51a1eb08cc4
| 31.442688 | 143 | 0.608309 | 6.053097 | false | false | false | false |
Draveness/RbSwift
|
RbSwift/String/String+Conversions.swift
|
1
|
8484
|
//
// Conversions.swift
// SwiftPatch
//
// Created by draveness on 18/03/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
fileprivate let radix = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
fileprivate let integers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
// MARK: - Conversions
public extension String {
/// Returns the result of interpreting leading characters in str as an integer base (between 2 and 36),
/// default is 10, extraneous characters past the end of a valid number are ignored.
///
/// "0a".to_i(16) #=> 10
/// "0xa".to_i(16) #=> 0
/// "12".to_i #=> 12
/// "-1100101".to_i(2) #=> -101
/// "1100101".to_i(2) #=> 101
/// "1100101".to_i(8) #=> 294977
/// "1100101".to_i(10) #=> 1100101
/// "1100101".to_i(16) #=> 17826049
///
/// This method returns 0 when base is invalid.
///
/// "0a".to_i(1) #=> 0
/// "0a".to_i(37) #=> 0
///
/// If there is not a valid number at the start of str, 0 is returned.
///
/// "-".to_i #=> 0
/// "d-1".to_i #=> 0
/// "0a".to_i #=> 0
/// "hello".to_i #=> 0
/// "".to_i #=> 0
/// " ".to_i #=> 0
///
var to_i: Int {
return to_i(10)
}
/// Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x)
/// and returns the corresponding number. Zero is returned on error.
///
/// "-".to_hex #=> 0
/// "0xa".to_hex #=> 10
/// "-0xa".to_hex #=> -10
/// "a".to_hex #=> 10
///
var to_hex: Int {
let sign = isStartWith("-") ? -1 : 1
let str = isStartWith("-") ? self.substring(from: 1) : self
guard str.isStartWith("0x") else { return str.to_i(16) * sign }
return str.substring(from: 2).to_i(16) * sign
}
/// An alias to `String#to_hex` method.
///
/// "-".hex #=> 0
/// "0xa".hex #=> 10
/// "-0xa".hex #=> -10
/// "a".hex #=> 10
///
var hex: Int {
return to_hex
}
/// Treats leading characters of str as a string of octal digits (with an optional sign)
/// and returns the corresponding number.
///
/// "123".oct #=> 83
/// "-377".oct #=> -255
/// "377bad".oct #=> 255
///
/// Returns 0 if the conversion fails.
///
/// "bad".oct #=> 0
///
var oct: Int {
return to_i(8)
}
/// Return the Integer ordinal of a one-character string.
///
/// "a".ord #=> 97
/// "ab".ord #=> 97
/// "b".ord #=> 98
///
/// Return 0 if the receiver is an empty string.
///
/// "".ord #=> 0
///
var ord: UInt32 {
guard let first = self.unicodeScalars.first else { return 0 }
return first.value
}
/// Returns the result of interpreting leading characters in str as an integer base (between 2 and 36),
/// default is 10, extraneous characters past the end of a valid number are ignored.
///
/// "0a".to_i(16) #=> 10
/// "0xa".to_i(16) #=> 0
/// "12".to_i #=> 12
/// "-1100101".to_i(2) #=> -101
/// "1100101".to_i(2) #=> 101
/// "1100101".to_i(8) #=> 294977
/// "1100101".to_i(10) #=> 1100101
/// "1100101".to_i(16) #=> 17826049
///
/// This method returns 0 when base is invalid.
///
/// "0a".to_i(1) #=> 0
/// "0a".to_i(37) #=> 0
///
/// If there is not a valid number at the start of str, 0 is returned.
///
/// "-".to_i #=> 0
/// "d-1".to_i #=> 0
/// "0a".to_i #=> 0
/// "hello".to_i #=> 0
/// "".to_i #=> 0
/// " ".to_i #=> 0
///
/// - Parameter base: A int indicates the integer base
/// - Returns: A integer based on the integer base
func to_i(_ base: Int = 10) -> Int {
guard Array(2...36).contains(base) else { return 0 }
let nums = radix[0..<base]
var chars = self.chars
// deal with the sign
let sign = chars.first == "-" ? -1 : 1
if chars.first == "-" { chars.remove(at: 0) }
var result: String = ""
for char in chars {
guard nums.contains(char) else { break }
result.append(char)
}
var value = 0
for (index, bit) in result.reverse.chars.enumerated() {
value += Int(pow(Double(base), Double(index))) * nums.firstIndex(of: bit)!
}
return value * sign
}
/// An alias to `to_double` but returns `Float` instead.
var to_f: Float {
return to_double.to_f
}
/// Returns the result of interpreting leading characters in str as a double
/// Extraneous characters past the end of a valid number are ignored.
///
/// "0a".to_double #=> 0
/// "1100101.11".to_double #=> 1100101.11
/// "123.456".to_double #=> 123.456
/// "123.456ddddd".to_double #=> 123.456
/// ".456ddddd".to_double #=> 0.456
///
/// If there is not a valid number at the start of str, 0.0 is returned.
///
/// "-".to_double #=> 0
/// "d-1".to_double #=> 0
/// "0a".to_double #=> 0
/// "..12".to_double #=> 0
/// "hello".to_double #=> 0
///
var to_double: Double {
var chars = self.chars
// deal with the sign
let sign: Double = chars.first == "-" ? -1.0 : 1.0
if chars.first == "-" { chars.remove(at: 0) }
var hasDot = false
var integer: String = ""
var decimal: String = ""
for char in chars {
if char == "." {
if hasDot {
break
} else {
hasDot = true
continue
}
}
if integers.contains(char) {
if hasDot {
decimal.append(char)
} else {
integer.append(char)
}
} else {
break
}
}
if decimal.length > 0 {
return (integer.to_i.to_double + decimal.to_i.to_double / pow(10.0, decimal.length.to_double)) * sign
} else {
return integer.to_i.to_double * sign
}
}
/// Returns the result of interpreting the receiver in different standard.
/// This methods returns `nil`, if the receiver is not in Custom, ISO8601, RFC2822 or CTime form.
///
/// "Sun Mar 19 01:04:21 2017".to_datetime! #=> 2017-03-19 01:04:21 +0000
/// "2017-03-19 00:35:36 +0800".to_datetime! #=> 2017-03-19 00:35:36 +0800
///
/// - See Also: DateFormat
func to_datetime(locale: Locale = Locale.current) -> Date? {
return Date(str: self, locale: locale)
}
}
extension String {
/// Try to convert `self` to a `Regex` which used to match string or pass as parameter
/// into some methods.
public var to_regex: Regex {
return to_regex()
}
/// Returns a `Regex` with matching string literally.
public var literal: Regex {
return to_regex(true)
}
/// Try to convert `self` to a `Regex` which used to match string or pass as parameter
/// into some methods.
///
/// - Parameter literal: A bool indicate whether match the receiver literally
/// - Returns: A `Regex` struct contains the receiver as a pattern
public func to_regex(_ literal: Bool = false) -> Regex {
return Regex(self, literal: literal)
}
}
extension Character {
/// Try to convert `self` to a `Regex` which used to match string or pass as parameter
/// into some methods.
public var to_regex: Regex {
return String(self).to_regex
}
/// Returns a `Regex` with matching character literally.
public var literal: Regex {
return String(self).literal
}
}
|
mit
|
76aa6ab966208f75823b00ed41dbb167
| 32.007782 | 204 | 0.470117 | 3.452584 | false | false | false | false |
QQLS/YouTobe
|
YouTube/Class/Account/Model/BQAccountModel.swift
|
1
|
1480
|
//
// BQAccountModel.swift
// YouTube
//
// Created by xiupai on 2017/3/30.
// Copyright © 2017年 QQLS. All rights reserved.
//
import UIKit
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
final class BQPlayList: BQModelProtocol {
var numberOfVideos: Int?
var pic: String?
var title: String?
init?(map: Map) {
}
func mapping(map: Map) {
numberOfVideos <- map["numberOfVideos"]
pic <- map["pic"]
title <- map["title"]
}
}
final class BQAccountModel: BQModelProtocol {
var backgroundImage: String?
var name: String?
var playlists: [BQPlayList]?
var profilePic: String?
init(backgroundImage: String?, name: String?, profilePic: String?, playLists: [BQPlayList]?) {
self.backgroundImage = backgroundImage
self.name = name
self.profilePic = profilePic
self.playlists = playLists
}
init?(map: Map) {
}
func mapping(map: Map) {
backgroundImage <- map["backgroundImage"]
name <- map["name"]
playlists <- map["playlists"]
profilePic <- map["profilePic"]
}
class func fetchAccountInfo(with url: URL, complete: ((BQAccountModel?) -> Void)?) {
Alamofire.request(url, method: .get).responseObject { (response: DataResponse<BQAccountModel>) in
if let complete = complete {
complete(response.value)
}
}
}
}
|
apache-2.0
|
93317a7a79b1e48cefd23fde078500c3
| 22.822581 | 105 | 0.603927 | 4.344118 | false | false | false | false |
huangboju/Moots
|
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/MaskView/ShapeMaskLayer.swift
|
2
|
3096
|
//
// ShapeMaskLayer.swift
// UIScrollViewDemo
//
// Created by xiAo_Ju on 2018/12/4.
// Copyright © 2018 伯驹 黄. All rights reserved.
//
import UIKit
class ShapeMaskLayer: CAShapeLayer {
private lazy var overlayPath: UIBezierPath = {
let overlayPath = generateOverlayPath()
return overlayPath
}()
override init() {
super.init()
}
override init(layer: Any) {
super.init(layer: layer)
}
convenience init(rect: CGRect) {
self.init()
self.frame = rect
setUp()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSublayers() {
super.layoutSublayers()
refreshMask()
}
private lazy var transparentPaths: [UIBezierPath] = []
public var maskColor: UIColor = UIColor(white: 0, alpha: 0.5) {
didSet {
refreshMask()
}
}
public func addTransparentRect(_ rect: CGRect) {
let transparentPath = UIBezierPath(rect: rect)
addTransparentPath(transparentPath)
}
public func addTransparentRoundedRect(_ rect: CGRect, cornerRadius: CGFloat) {
let transparentPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
addTransparentPath(transparentPath)
}
public func addTransparentRoundedRect(_ rect: CGRect, byRoundingCorners corners: UIRectCorner, cornerRadii: CGSize) {
let transparentPath = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: cornerRadii)
addTransparentPath(transparentPath)
}
public func addTransparentOvalRect(_ rect: CGRect) {
let transparentPath = UIBezierPath(ovalIn: rect)
addTransparentPath(transparentPath)
}
public func reset() {
transparentPaths.removeAll()
refreshMask()
}
private func addTransparentPath(_ transparentPath: UIBezierPath) {
overlayPath.append(transparentPath)
transparentPaths.append(transparentPath)
path = overlayPath.cgPath
}
private func setUp() {
contentsScale = UIScreen.main.scale
backgroundColor = UIColor.clear.cgColor
path = overlayPath.cgPath
fillRule = .evenOdd
fillColor = maskColor.cgColor
}
private func generateOverlayPath() -> UIBezierPath {
let overlayPath = UIBezierPath(rect: bounds)
overlayPath.usesEvenOddFillRule = true
return overlayPath
}
private func currentOverlayPath() -> UIBezierPath {
let overlayPath = generateOverlayPath()
for transparentPath in transparentPaths {
overlayPath.append(transparentPath)
}
return overlayPath
}
private func refreshMask() {
overlayPath = currentOverlayPath()
path = overlayPath.cgPath
fillColor = maskColor.cgColor
}
}
|
mit
|
0894a62aece1e44adecdc902a18be833
| 24.957983 | 121 | 0.61541 | 5.200337 | false | false | false | false |
SirapatBoonyasiwapong/grader
|
Sources/App/Routes.swift
|
1
|
1487
|
import Vapor
import VaporRedisClient
import Redis
import Reswifq
final class Routes: RouteCollection {
let view: ViewRenderer
init(_ view: ViewRenderer) {
self.view = view
}
func build(_ builder: RouteBuilder) throws {
/// GET /
builder.get { req in
return Response(redirect: "/classes")
}
let loginController = LoginController(view)
builder.get("login", handler: loginController.loginForm)
builder.post("login", handler: loginController.login)
builder.get("register", handler: loginController.registerForm)
builder.post("register", handler: loginController.register)
builder.resource("events", EventsController(view))
builder.get("about") { req in
return try render("about", for: req, with: self.view)
}
let classesController = ClassesController(view)
builder.get("classes", handler: classesController.showClasses)
// builder.get("job") { request in
// let submission = try Submission.find(6)
// print("got submission")
// let job = SubmissionJob(submissionID: submission!.id!.int!)
// print("got job")
// try! Reswifq.defaultQueue.enqueue(job)
// print("queued")
//
// try Reswifq.defaultQueue.enqueue(DemoJob())
// return Response(status: .ok)
// }
}
}
|
mit
|
f04809651e06731d84ce78ab6e947746
| 29.979167 | 73 | 0.583726 | 4.478916 | false | false | false | false |
LYM-mg/DemoTest
|
其他功能/SwiftyDemo/SwiftyDemo/RightViewController.swift
|
1
|
6334
|
//
// RightViewController.swift
// SwiftyDemo
//
// Created by newunion on 2019/3/26.
// Copyright © 2019年 firestonetmt. All rights reserved.
//
import UIKit
class RightViewController: UIViewController {
fileprivate lazy var tableView: UITableView = { [unowned self] in
let tb = UITableView(frame: .zero, style: .plain)
tb.backgroundColor = UIColor.white
tb.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tb.dataSource = self
tb.delegate = self
// tb.estimatedRowHeight = 60 // 设置估算高度
// tb.rowHeight = UITableViewAutomaticDimension // 告诉tableView我们cell的高度是自动的
tb.register(Cell.self, forCellReuseIdentifier: "CellID")
return tb
}()
var headerView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.randomColor()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(self.rightClick))
self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
let headerView = UIView()
headerView.backgroundColor = UIColor.red
tableView.tableHeaderView = headerView
self.headerView = headerView
headerView.snp.makeConstraints { (make) in
make.left.right.equalTo(self.view)
make.width.equalTo(self.view.mg_width)
}
let btn = UIButton()
let lb = UILabel()
btn.backgroundColor = UIColor.randomColor()
btn.setTitle("傻瓜", for: .normal)
btn.addTarget(self, action: #selector(changeClick), for: .touchUpInside)
lb.backgroundColor = UIColor.randomColor()
lb.text = "你就是一个笨蛋,是吗?"
lb.numberOfLines = 0;
lb.tag = 100;
headerView.addSubview(btn)
headerView.addSubview(lb)
lb.snp.makeConstraints { (make) in
make.left.right.equalTo(headerView)
make.top.equalTo(headerView).offset(10)
make.bottom.equalTo(btn.snp.top).offset(-10)
}
btn.snp.makeConstraints { (make) in
make.left.right.equalTo(headerView)
make.bottom.equalTo(headerView).offset(-10)
}
}
deinit {
print("\(self) deinit")
}
@objc func changeClick() {
var str = "你就是一个笨蛋,是吗?不🙅♂️,我不是,你才是笨蛋!那你是一个傻瓜,笨笨哒,哈哈哈哈哈。不🙅♀️,我也不是一个傻瓜,我是一个可爱的人。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。如果全世界与你为敌的话,那么他就是我的敌人了。"
/// 随机数
let count = str.count
let randonNumber = Int(arc4random_uniform(UInt32(count-11))+11)
str = String(str.prefix(randonNumber))
print(str)
let lb: UILabel = self.tableView.tableHeaderView?.viewWithTag(100) as! UILabel
lb.text = str
// let height = self.headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
// self.tableView.tableHeaderView?.mg_height = height
UIView.animate(withDuration: 0.5) {
self.tableView.layoutIfNeeded()
self.tableView.tableHeaderView = self.headerView;
}
}
@objc func rightClick() {
self.navigationController?.pushViewController(TbaleViewContainTBController(), animated: true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.navigationController?.pushViewController(LeftViewController(), animated: true)
}
}
extension RightViewController:UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath)
cell.backgroundColor = UIColor.randomColor()
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
}
|
mit
|
f6279529e72fdf3d65b1a9a423daa515
| 39.991525 | 733 | 0.683275 | 3.241957 | false | false | false | false |
pushuhengyang/dyzb
|
DYZB/DYZB/Classes/Home首页/Mode/AnchorGroup.swift
|
1
|
831
|
//
// AnchorGroup.swift
// DYZB
//
// Created by xuwenhao on 16/11/15.
// Copyr ight © 2016年 xuwenhao. All rights reserved.
// 数据model
import UIKit
class AnchorGroup: NSObject {
var tag_name : String?
var icon_name : String?
lazy var archArry = [AnchorModel]()
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
override func setValue(_ value: Any?, forKey key: String) {
super.setValue(value, forKey: key);
if key == "room_list" {
let arry = value as? Array<Any>;
for dict in arry!{
let model = AnchorModel()
model.setValuesForKeys(dict as! [String : Any]);
self.archArry.append(model)
}
}
}
}
|
mit
|
48c2c2838ada3cc4286c3dd5e422eb4e
| 20.684211 | 72 | 0.525485 | 4.099502 | false | false | false | false |
shahabc/ProjectNexus
|
Mobile Buy SDK Sample Apps/Advanced App - ObjC/MessageExtension/IceCream+Image.swift
|
1
|
4343
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Extends `IceCream` to add methods to render the ice cream as a `UIImage`.
*/
import UIKit
extension IceCream {
private struct StickerProperties {
/// The desired size of an ice cream sticker image.
static let size = CGSize(width: 300.0, height: 300.0)
/**
The amount of padding to apply to a sticker when drawn with an opaque
background.
*/
static let opaquePadding = CGSize(width: 60.0, height: 10.0)
}
func renderSticker(opaque: Bool) -> UIImage? {
guard let partsImage = renderParts() else { return nil }
// Determine the size to draw as a sticker.
let outputSize: CGSize
let iceCreamSize: CGSize
if opaque {
// Scale the ice cream image to fit in the center of the sticker.
let scale = min((StickerProperties.size.width - StickerProperties.opaquePadding.width) / partsImage.size.height,
(StickerProperties.size.height - StickerProperties.opaquePadding.height) / partsImage.size.width)
iceCreamSize = CGSize(width: partsImage.size.width * scale, height: partsImage.size.height * scale)
outputSize = StickerProperties.size
}
else {
// Scale the ice cream to fit it's height into the sticker.
let scale = StickerProperties.size.width / partsImage.size.height
iceCreamSize = CGSize(width: partsImage.size.width * scale, height: partsImage.size.height * scale)
outputSize = iceCreamSize
}
// Scale the ice cream image to the correct size.
let renderer = UIGraphicsImageRenderer(size: outputSize)
let image = renderer.image { context in
let backgroundColor: UIColor
if opaque {
// Give the image a colored background.
backgroundColor = UIColor(red: 250.0 / 255.0, green: 225.0 / 255.0, blue: 235.0 / 255.0, alpha: 1.0)
}
else {
// Give the image a clear background
backgroundColor = UIColor.clear
}
// Draw the background
backgroundColor.setFill()
context.fill(CGRect(origin: CGPoint.zero, size: StickerProperties.size))
// Draw the scaled composited image.
var drawRect = CGRect.zero
drawRect.size = iceCreamSize
drawRect.origin.x = (outputSize.width / 2.0) - (iceCreamSize.width / 2.0)
drawRect.origin.y = (outputSize.height / 2.0) - (iceCreamSize.height / 2.0)
partsImage.draw(in: drawRect)
}
return image
}
/// Composites the valid ice cream parts into a single `UIImage`.
private func renderParts() -> UIImage? {
// Determine which parts to draw.
let allParts: [IceCreamPart?] = [topping, scoops, base]
let partImages = allParts.flatMap { $0?.stickerImage }
guard !partImages.isEmpty else { return nil }
// Calculate the size of the composited ice cream parts image.
var outputImageSize = CGSize.zero
outputImageSize.width = partImages.reduce(0) { largestWidth, image in
return max(largestWidth, image.size.width)
}
outputImageSize.height = partImages.reduce(0) { totalHeight, image in
return totalHeight + image.size.height
}
// Render the part images into a single composite image.
let renderer = UIGraphicsImageRenderer(size: outputImageSize)
let image = renderer.image { context in
// Draw each of the body parts in a vertica stack.
var nextYPosition = CGFloat(0.0)
for partImage in partImages {
var position = CGPoint.zero
position.x = outputImageSize.width / 2.0 - partImage.size.width / 2.0
position.y = nextYPosition
partImage.draw(at: position)
nextYPosition += partImage.size.height
}
}
return image
}
}
|
mit
|
8f078c2bab68ed44f49ca68d20a8f928
| 38.825688 | 125 | 0.586501 | 4.733915 | false | false | false | false |
yakirlee/Extersion
|
Helpers/NSData+Extension.swift
|
1
|
1466
|
//
// NSData+Extension.swift
// TSWeChat
//
// Created by Hilen on 11/25/15.
// Copyright © 2015 Hilen. All rights reserved.
//
import Foundation
extension NSData {
public var tokenString: String {
let characterSet: NSCharacterSet = NSCharacterSet(charactersInString:"<>")
let deviceTokenString: String = (self.description as NSString).stringByTrimmingCharactersInSet(characterSet).stringByReplacingOccurrencesOfString(" ", withString:"") as String
return deviceTokenString
}
class func dataFromJSONFile(fileName: String) -> NSData? {
if let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "json") {
do {
let data = try NSData(contentsOfURL: NSURL(fileURLWithPath: path), options: NSDataReadingOptions.DataReadingMappedIfSafe)
return data
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
} else {
print("Invalid filename/path.")
return nil
}
}
var MD5String: String {
let MD5Calculator = MD5(Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(self.bytes), count: self.length)))
let MD5Data = MD5Calculator.calculate()
let MD5String = NSMutableString()
for c in MD5Data {
MD5String.appendFormat("%02x", c)
}
return MD5String as String
}
}
|
mit
|
a71e5329309a015940fdc758225d31e0
| 33.093023 | 183 | 0.627986 | 5.069204 | false | false | false | false |
jopamer/swift
|
test/attr/attr_autoclosure.swift
|
1
|
6855
|
// RUN: %target-typecheck-verify-swift
// Simple case.
var fn : @autoclosure () -> Int = 4 // expected-error {{'@autoclosure' may only be used on parameters}} expected-error {{cannot convert value of type 'Int' to specified type '() -> Int'}}
@autoclosure func func1() {} // expected-error {{attribute can only be applied to types, not declarations}}
func func1a(_ v1 : @autoclosure Int) {} // expected-error {{@autoclosure attribute only applies to function types}}
func func2(_ fp : @autoclosure () -> Int) { func2(4)}
func func3(fp fpx : @autoclosure () -> Int) {func3(fp: 0)}
func func4(fp : @autoclosure () -> Int) {func4(fp: 0)}
func func6(_: @autoclosure () -> Int) {func6(0)}
// autoclosure + inout doesn't make sense.
func func8(_ x: inout @autoclosure () -> Bool) -> Bool { // expected-error {{'@autoclosure' may only be used on parameters}}
}
func func9(_ x: @autoclosure (Int) -> Bool) {} // expected-error {{argument type of @autoclosure parameter must be '()'}}
func func10(_ x: @autoclosure (Int, String, Int) -> Void) {} // expected-error {{argument type of @autoclosure parameter must be '()'}}
// <rdar://problem/19707366> QoI: @autoclosure declaration change fixit
let migrate4 : (@autoclosure() -> ()) -> ()
struct SomeStruct {
@autoclosure let property : () -> Int // expected-error {{attribute can only be applied to types, not declarations}}
init() {
}
}
class BaseClass {
@autoclosure var property : () -> Int // expected-error {{attribute can only be applied to types, not declarations}}
init() {}
}
class DerivedClass {
var property : () -> Int { get {} set {} }
}
protocol P1 {
associatedtype Element
}
protocol P2 : P1 {
associatedtype Element
}
func overloadedEach<O: P1>(_ source: O, _ closure: @escaping () -> ()) {
}
func overloadedEach<P: P2>(_ source: P, _ closure: @escaping () -> ()) {
}
struct S : P2 {
typealias Element = Int
func each(_ closure: @autoclosure () -> ()) {
// expected-note@-1{{parameter 'closure' is implicitly non-escaping}}
overloadedEach(self, closure) // expected-error {{passing non-escaping parameter 'closure' to function expecting an @escaping closure}}
}
}
struct AutoclosureEscapeTest {
@autoclosure let delayed: () -> Int // expected-error {{attribute can only be applied to types, not declarations}}
}
// @autoclosure(escaping)
// expected-error @+1 {{attribute can only be applied to types, not declarations}}
func func10(@autoclosure(escaping _: () -> ()) { } // expected-error{{expected parameter name followed by ':'}}
func func11(_: @autoclosure(escaping) @noescape () -> ()) { } // expected-error{{@escaping conflicts with @noescape}}
// expected-error@-1{{@autoclosure(escaping) has been removed; use @autoclosure @escaping instead}} {{28-38= @escaping}}
class Super {
func f1(_ x: @autoclosure(escaping) () -> ()) { }
// expected-error@-1{{@autoclosure(escaping) has been removed; use @autoclosure @escaping instead}} {{28-38= @escaping}}
func f2(_ x: @autoclosure(escaping) () -> ()) { } // expected-note {{potential overridden instance method 'f2' here}}
// expected-error@-1{{@autoclosure(escaping) has been removed; use @autoclosure @escaping instead}} {{28-38= @escaping}}
func f3(x: @autoclosure () -> ()) { }
}
class Sub : Super {
override func f1(_ x: @autoclosure(escaping)() -> ()) { }
// expected-error@-1{{@autoclosure(escaping) has been removed; use @autoclosure @escaping instead}} {{37-47= @escaping }}
override func f2(_ x: @autoclosure () -> ()) { } // expected-error{{does not override any method}} // expected-note{{type does not match superclass instance method with type '(@autoclosure @escaping () -> ()) -> ()'}}
override func f3(_ x: @autoclosure(escaping) () -> ()) { } // expected-error{{does not override any method}}
// expected-error@-1{{@autoclosure(escaping) has been removed; use @autoclosure @escaping instead}} {{37-47= @escaping}}
}
func func12_sink(_ x: @escaping () -> Int) { }
func func12a(_ x: @autoclosure () -> Int) {
// expected-note@-1{{parameter 'x' is implicitly non-escaping}}
func12_sink(x) // expected-error {{passing non-escaping parameter 'x' to function expecting an @escaping closure}}
}
func func12b(_ x: @autoclosure(escaping) () -> Int) {
// expected-error@-1{{@autoclosure(escaping) has been removed; use @autoclosure @escaping instead}} {{31-41= @escaping}}
func12_sink(x) // ok
}
func func12c(_ x: @autoclosure @escaping () -> Int) {
func12_sink(x) // ok
}
func func12d(_ x: @escaping @autoclosure () -> Int) {
func12_sink(x) // ok
}
class TestFunc12 {
var x: Int = 5
func foo() -> Int { return 0 }
func test() {
func12a(x + foo()) // okay
func12b(x + foo())
// expected-error@-1{{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{13-13=self.}}
// expected-error@-2{{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{17-17=self.}}
}
}
enum AutoclosureFailableOf<T> {
case Success(@autoclosure () -> T)
case Failure()
}
let _ : AutoclosureFailableOf<Int> = .Success(42)
let _ : (@autoclosure () -> ()) -> ()
let _ : (@autoclosure(escaping) () -> ()) -> ()
// expected-error@-1{{@autoclosure(escaping) has been removed; use @autoclosure @escaping instead}} {{22-32= @escaping}}
// escaping is the name of param type
let _ : (@autoclosure(escaping) -> ()) -> () // expected-error {{use of undeclared type 'escaping'}}
// expected-error@-1 {{argument type of @autoclosure parameter must be '()'}}
// Migration
// expected-error @+1 {{attribute can only be applied to types, not declarations}}
func migrateAC(@autoclosure _: () -> ()) { }
// expected-error @+1 {{attribute can only be applied to types, not declarations}}
func migrateACE(@autoclosure(escaping) _: () -> ()) { }
func takesAutoclosure(_ fn: @autoclosure () -> Int) {}
func takesThrowingAutoclosure(_: @autoclosure () throws -> Int) {}
func callAutoclosureWithNoEscape(_ fn: () -> Int) {
takesAutoclosure(1+1) // ok
}
func callAutoclosureWithNoEscape_2(_ fn: () -> Int) {
takesAutoclosure(fn()) // ok
}
func callAutoclosureWithNoEscape_3(_ fn: @autoclosure () -> Int) {
takesAutoclosure(fn()) // ok
}
// expected-error @+1 {{'@autoclosure' must not be used on variadic parameters}}
func variadicAutoclosure(_ fn: @autoclosure () -> ()...) {
for _ in fn {}
}
// rdar://41219750
// These are all arguably invalid; the autoclosure should have to be called.
// But as long as we allow them, we shouldn't crash.
func passNonThrowingToNonThrowingAC(_ fn: @autoclosure () -> Int) {
takesAutoclosure(fn)
}
func passNonThrowingToThrowingAC(_ fn: @autoclosure () -> Int) {
takesThrowingAutoclosure(fn)
}
func passThrowingToThrowingAC(_ fn: @autoclosure () throws -> Int) {
takesThrowingAutoclosure(fn)
}
|
apache-2.0
|
d8c023b756efeb3257c695042f10db92
| 37.728814 | 219 | 0.661707 | 3.762349 | false | false | false | false |
xiawuacha/DouYuzhibo
|
DouYuzhibo/DouYuzhibo/Classses/Home/Controller/common.swift
|
1
|
326
|
//
// common.swift
// DouYuzhibo
//
// Created by 汪凯 on 16/10/22.
// Copyright © 2016年 汪凯. All rights reserved.
//
import UIKit
let kStatusBarH : CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabbarH : CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
|
mit
|
e485ceceaee0cc1948ab49993c8fdcc7
| 17.529412 | 46 | 0.707937 | 3.247423 | false | false | false | false |
lorentey/GlueKit
|
Sources/TransactionalThing.swift
|
1
|
3350
|
//
// TransactionState.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-10-22.
// Copyright © 2015–2017 Károly Lőrentey.
//
internal class TransactionalSignal<Change: ChangeType>: Signal<Update<Change>> {
typealias Value = Update<Change>
var isInTransaction: Bool = false
public override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Value {
if self.isInTransaction {
// Make sure the new subscriber knows we're in the middle of a transaction.
sink.receive(.beginTransaction)
}
super.add(sink)
}
@discardableResult
public override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Value {
let old = super.remove(sink)
if self.isInTransaction {
// Wave goodbye by sending a virtual endTransaction that makes state management easier.
old.receive(.endTransaction)
}
return old
}
}
protocol TransactionalThing: class, SignalDelegate {
associatedtype Change: ChangeType
var _signal: TransactionalSignal<Change>? { get set }
var _transactionCount: Int { get set }
}
extension TransactionalThing {
var signal: TransactionalSignal<Change> {
if let signal = _signal { return signal }
let signal = TransactionalSignal<Change>()
signal.isInTransaction = _transactionCount > 0
signal.delegate = self
_signal = signal
return signal
}
func beginTransaction() {
_transactionCount += 1
if _transactionCount == 1, let signal = _signal {
signal.isInTransaction = true
signal.send(.beginTransaction)
}
}
func sendChange(_ change: Change) {
precondition(_transactionCount > 0)
_signal?.send(.change(change))
}
func sendIfConnected(_ change: @autoclosure () -> Change) {
if isConnected {
sendChange(change())
}
}
func endTransaction() {
precondition(_transactionCount > 0)
_transactionCount -= 1
if _transactionCount == 0, let signal = _signal {
signal.isInTransaction = false
signal.send(.endTransaction)
}
}
public func send(_ update: Update<Change>) {
switch update {
case .beginTransaction: beginTransaction()
case .change(let change): sendChange(change)
case .endTransaction: endTransaction()
}
}
var isInTransaction: Bool { return _transactionCount > 0 }
var isConnected: Bool { return _signal?.isConnected ?? false }
var isActive: Bool { return isInTransaction || isConnected }
var isInOuterMostTransaction: Bool { return _transactionCount == 1 } // Used by KVO
}
public class TransactionalSource<Change: ChangeType>: _AbstractSource<Update<Change>>, TransactionalThing {
internal var _signal: TransactionalSignal<Change>? = nil
internal var _transactionCount = 0
func activate() {
}
func deactivate() {
}
public override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Value {
signal.add(sink)
}
@discardableResult
public override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Value {
return signal.remove(sink)
}
}
|
mit
|
3cb18326b6edf53a33e16da1cd612324
| 29.117117 | 107 | 0.628477 | 4.74858 | false | false | false | false |
RogueAndy/ZSide-Swift
|
ZSide-Swift/ZSide-Swift/ViewControllers/ZSSideLeftViewController.swift
|
1
|
2255
|
//
// ZSSideLeftViewController.swift
// ZSide-Swift
//
// Created by dazhongge on 2016/12/26.
// Copyright © 2016年 dazhongge. All rights reserved.
//
import UIKit
class ZSSideLeftViewController: ZSBaseViewController, UITableViewDelegate, UITableViewDataSource {
private var buttonTable: UITableView!
private let buttonNames = ["第一个", "第二个", "第三个", "第四个", "第五个"]
override func loadInit() {
super.loadInit()
self.view.backgroundColor = UIColor.init(patternImage: UIImage(named: "leftimg")!)
}
override func loadViews() {
super.loadViews()
buttonTable = UITableView(frame: .zero)
buttonTable.delegate = self
buttonTable.dataSource = self
buttonTable.backgroundColor = .clear
let clearView = UIView()
clearView.backgroundColor = .clear
buttonTable.tableFooterView = clearView
self.view.addSubview(buttonTable)
}
override func loadLayout() {
super.loadLayout()
buttonTable.frame = CGRect.init(x: 0, y: 200, width: 300, height: 200)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return buttonNames.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 42
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
ZSSideManagerViewController.selectViewControllerOfIndex(index: indexPath.row)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "ZSSideLeftCell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? ZSSideLeftCell
if cell == nil {
cell = ZSSideLeftCell(style: .default, reuseIdentifier: identifier)
}
cell!.actionLabel.text = buttonNames[indexPath.row]
return cell!
}
}
|
mit
|
dc81eb6e65b978ab899ce046b0cf1b7d
| 25.771084 | 100 | 0.611611 | 4.982063 | false | false | false | false |
vector-im/vector-ios
|
RiotSwiftUI/Modules/Spaces/SpaceSettings/SpaceSettings/Service/MatrixSDK/SpaceSettingsService.swift
|
1
|
17172
|
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Combine
import MatrixSDK
@available(iOS 14.0, *)
class SpaceSettingsService: SpaceSettingsServiceProtocol {
// MARK: - Properties
var userDefinedAddress: String? {
didSet {
validateAddress()
}
}
// MARK: Private
private let session: MXSession
private var roomState: MXRoomState? {
didSet {
updateRoomProperties()
}
}
private let room: MXRoom?
private var roomEventListener: Any?
private var publicAddress: String? {
didSet {
validateAddress()
}
}
private var defaultAddress: String {
didSet {
validateAddress()
}
}
// MARK: Public
var displayName: String? {
room?.displayName
}
private(set) var spaceId: String
private(set) var roomProperties: SpaceSettingsRoomProperties? {
didSet {
roomPropertiesSubject.send(roomProperties)
}
}
private(set) var isLoadingSubject: CurrentValueSubject<Bool, Never>
private(set) var roomPropertiesSubject: CurrentValueSubject<SpaceSettingsRoomProperties?, Never>
private(set) var showPostProcessAlert: CurrentValueSubject<Bool, Never>
private(set) var addressValidationSubject: CurrentValueSubject<SpaceCreationSettingsAddressValidationStatus, Never>
var isAddressValid: Bool {
switch addressValidationSubject.value {
case .none, .valid:
return true
default:
return false
}
}
private var currentOperation: MXHTTPOperation?
private var addressValidationOperation: MXHTTPOperation?
private lazy var mediaUploader: MXMediaLoader = MXMediaManager.prepareUploader(withMatrixSession: session, initialRange: 0, andRange: 1.0)
// MARK: - Setup
init(session: MXSession, spaceId: String) {
self.session = session
self.spaceId = spaceId
self.room = session.room(withRoomId: spaceId)
self.isLoadingSubject = CurrentValueSubject(false)
self.showPostProcessAlert = CurrentValueSubject(false)
self.roomPropertiesSubject = CurrentValueSubject(self.roomProperties)
self.addressValidationSubject = CurrentValueSubject(.none("#"))
self.defaultAddress = ""
readRoomState()
}
deinit {
if let roomEventListener = self.roomEventListener {
self.room?.removeListener(roomEventListener)
}
currentOperation?.cancel()
addressValidationOperation?.cancel()
}
// MARK: - Public
func addressDidChange(_ newValue: String) {
userDefinedAddress = newValue
}
func trackSpace() {
Analytics.shared.exploringSpace = session.spaceService.getSpace(withId: spaceId)
}
// MARK: - Private
private func readRoomState() {
isLoadingSubject.send(true)
self.room?.state { [weak self] roomState in
self?.roomState = roomState
self?.isLoadingSubject.send(false)
}
roomEventListener = self.room?.listen(toEvents: { [weak self] event, direction, state in
self?.room?.state({ [weak self] roomState in
self?.roomState = roomState
})
})
}
private func visibility(with roomState: MXRoomState) -> SpaceSettingsVisibility {
switch roomState.joinRule {
case .public:
return .public
case .restricted:
return .restricted
default:
return .private
}
}
private func allowedParentIds(with roomState: MXRoomState) -> [String] {
var allowedParentIds: [String] = []
if roomState.joinRule == .restricted, let joinRuleEvent = roomState.stateEvents(with: .roomJoinRules)?.last {
let allowContent: [[String: String]] = joinRuleEvent.wireContent[kMXJoinRulesContentKeyAllow] as? [[String: String]] ?? []
allowedParentIds = allowContent.compactMap { allowDictionnary in
guard let type = allowDictionnary[kMXJoinRulesContentKeyType], type == kMXEventTypeStringRoomMembership else {
return nil
}
return allowDictionnary[kMXJoinRulesContentKeyRoomId]
}
}
return allowedParentIds
}
private func isField(ofType notification: String, editableWith powerLevels: MXRoomPowerLevels?) -> Bool {
guard let powerLevels = powerLevels else {
return false
}
let userPowerLevel = powerLevels.powerLevelOfUser(withUserID: self.session.myUserId)
return userPowerLevel >= powerLevels.minimumPowerLevel(forNotifications: notification, defaultPower: powerLevels.stateDefault)
}
private func validateAddress() {
addressValidationOperation?.cancel()
addressValidationOperation = nil
guard let userDefinedAddress = self.userDefinedAddress, !userDefinedAddress.isEmpty else {
let fullAddress = MXTools.fullLocalAlias(from: defaultAddress, with: session)
if let publicAddress = self.publicAddress, !publicAddress.isEmpty {
addressValidationSubject.send(.current(fullAddress))
} else if defaultAddress.isEmpty {
addressValidationSubject.send(.none(fullAddress))
} else {
validate(defaultAddress)
}
return
}
validate(userDefinedAddress)
}
private func validate(_ aliasLocalPart: String) {
let fullAddress = MXTools.fullLocalAlias(from: aliasLocalPart, with: session)
if let publicAddress = self.publicAddress, publicAddress == aliasLocalPart {
self.addressValidationSubject.send(.current(fullAddress))
return
}
addressValidationOperation = MXRoomAliasAvailabilityChecker.validate(aliasLocalPart: aliasLocalPart, with: session) { [weak self] result in
guard let self = self else { return }
self.addressValidationOperation = nil
switch result {
case .available:
self.addressValidationSubject.send(.valid(fullAddress))
case .invalid:
self.addressValidationSubject.send(.invalidCharacters(fullAddress))
case .notAvailable:
self.addressValidationSubject.send(.alreadyExists(fullAddress))
case .serverError:
self.addressValidationSubject.send(.none(fullAddress))
}
}
}
private func updateRoomProperties() {
guard let roomState = roomState else {
return
}
if let canonicalAlias = roomState.canonicalAlias {
let localAliasPart = MXTools.extractLocalAliasPart(from: canonicalAlias)
self.publicAddress = localAliasPart
self.defaultAddress = localAliasPart
} else {
self.publicAddress = nil
self.defaultAddress = MXTools.validAliasLocalPart(from: roomState.name)
}
self.roomProperties = SpaceSettingsRoomProperties(
name: roomState.name,
topic: roomState.topic,
address: self.defaultAddress,
avatarUrl: roomState.avatar,
visibility: visibility(with: roomState),
allowedParentIds: allowedParentIds(with: roomState),
isAvatarEditable: isField(ofType: kMXEventTypeStringRoomAvatar, editableWith: roomState.powerLevels),
isNameEditable: isField(ofType: kMXEventTypeStringRoomName, editableWith: roomState.powerLevels),
isTopicEditable: isField(ofType: kMXEventTypeStringRoomTopic, editableWith: roomState.powerLevels),
isAddressEditable: isField(ofType: kMXEventTypeStringRoomAliases, editableWith: roomState.powerLevels),
isAccessEditable: isField(ofType: kMXEventTypeStringRoomJoinRules, editableWith: roomState.powerLevels))
}
// MARK: - Post process
private var currentTaskIndex: Int = 0
private var tasks: [PostProcessTask] = []
private var lastError: Error?
private var completion: ((_ result: SpaceSettingsServiceCompletionResult) -> Void)?
private enum PostProcessTaskType: Equatable {
case updateName(String)
case updateTopic(String)
case updateAlias(String)
case uploadAvatar(UIImage)
}
private enum PostProcessTaskState: CaseIterable, Equatable {
case none
case started
case success
case failure
}
private struct PostProcessTask: Equatable {
let type: PostProcessTaskType
var state: PostProcessTaskState = .none
var isFinished: Bool {
return state == .failure || state == .success
}
static func == (lhs: PostProcessTask, rhs: PostProcessTask) -> Bool {
return lhs.type == rhs.type && lhs.state == rhs.state
}
}
func update(roomName: String, topic: String, address: String, avatar: UIImage?,
completion: ((_ result: SpaceSettingsServiceCompletionResult) -> Void)?) {
// First attempt
if self.tasks.isEmpty {
var tasks: [PostProcessTask] = []
if roomProperties?.name ?? "" != roomName {
tasks.append(PostProcessTask(type: .updateName(roomName)))
}
if roomProperties?.topic ?? "" != topic {
tasks.append(PostProcessTask(type: .updateTopic(topic)))
}
if roomProperties?.address ?? "" != address {
tasks.append(PostProcessTask(type: .updateAlias(address)))
}
if let avatarImage = avatar {
tasks.append(PostProcessTask(type: .uploadAvatar(avatarImage)))
}
self.tasks = tasks
} else {
// Retry -> restart failed tasks
self.tasks = tasks.map({ task in
if task.state == .failure {
return PostProcessTask(type: task.type, state: .none)
}
return task
})
}
self.isLoadingSubject.send(true)
self.completion = completion
self.lastError = nil
currentTaskIndex = -1
runNextTask()
}
private func runNextTask() {
currentTaskIndex += 1
guard currentTaskIndex < tasks.count else {
self.isLoadingSubject.send(false)
if let error = lastError {
showPostProcessAlert.send(true)
completion?(.failure(error))
} else {
completion?(.success)
}
return
}
let task = tasks[currentTaskIndex]
guard !task.isFinished else {
runNextTask()
return
}
switch task.type {
case .updateName(let roomName):
update(roomName: roomName)
case .updateTopic(let topic):
update(topic: topic)
case .updateAlias(let address):
update(canonicalAlias: address)
case .uploadAvatar(let image):
upload(avatar: image)
}
}
private func updateCurrentTaskState(with state: PostProcessTaskState) {
guard currentTaskIndex < tasks.count else {
return
}
tasks[currentTaskIndex].state = state
}
private func update(roomName: String) {
updateCurrentTaskState(with: .started)
currentOperation = room?.setName(roomName, completion: { [weak self] response in
guard let self = self else { return }
switch response {
case .success:
self.updateCurrentTaskState(with: .success)
case .failure(let error):
self.lastError = error
self.updateCurrentTaskState(with: .failure)
}
self.runNextTask()
})
}
private func update(topic: String) {
updateCurrentTaskState(with: .started)
currentOperation = room?.setTopic(topic, completion: { [weak self] response in
guard let self = self else { return }
switch response {
case .success:
self.updateCurrentTaskState(with: .success)
case .failure(let error):
self.lastError = error
self.updateCurrentTaskState(with: .failure)
}
self.runNextTask()
})
}
private func update(canonicalAlias: String) {
updateCurrentTaskState(with: .started)
currentOperation = room?.addAlias(MXTools.fullLocalAlias(from: canonicalAlias, with: session), completion: { [weak self] response in
guard let self = self else { return }
switch response {
case .success:
if let publicAddress = self.publicAddress {
self.currentOperation = self.room?.removeAlias(MXTools.fullLocalAlias(from: publicAddress, with: self.session), completion: { [weak self] response in
guard let self = self else { return }
self.setup(canonicalAlias: canonicalAlias)
})
} else {
self.setup(canonicalAlias: canonicalAlias)
}
case .failure(let error):
self.lastError = error
self.updateCurrentTaskState(with: .failure)
self.runNextTask()
}
})
}
private func setup(canonicalAlias: String) {
currentOperation = room?.setCanonicalAlias(MXTools.fullLocalAlias(from: canonicalAlias, with: session), completion: { [weak self] response in
guard let self = self else { return }
switch response {
case .success:
self.updateCurrentTaskState(with: .success)
case .failure(let error):
self.lastError = error
self.updateCurrentTaskState(with: .failure)
}
self.runNextTask()
})
}
private func upload(avatar: UIImage) {
updateCurrentTaskState(with: .started)
let avatarUp = MXKTools.forceImageOrientationUp(avatar)
mediaUploader.uploadData(avatarUp?.jpegData(compressionQuality: 0.5), filename: nil, mimeType: "image/jpeg",
success: { [weak self] (urlString) in
guard let self = self else { return }
guard let urlString = urlString else {
self.updateCurrentTaskState(with: .failure)
self.runNextTask()
return
}
guard let url = URL(string: urlString) else {
self.updateCurrentTaskState(with: .failure)
self.runNextTask()
return
}
self.setAvatar(withURL: url)
},
failure: { [weak self] (error) in
guard let self = self else { return }
self.lastError = error
self.updateCurrentTaskState(with: .failure)
self.runNextTask()
})
}
private func setAvatar(withURL url: URL) {
currentOperation = room?.setAvatar(url: url) { [weak self] (response) in
guard let self = self else { return }
switch response {
case .success:
self.updateCurrentTaskState(with: .success)
case .failure(let error):
self.lastError = error
self.updateCurrentTaskState(with: .failure)
}
self.runNextTask()
}
}
}
|
apache-2.0
|
a80c89cf9fa4311c85088fa79a1b8690
| 34.924686 | 169 | 0.574773 | 5.265869 | false | false | false | false |
steryokhin/AsciiArtPlayer
|
src/AsciiArtPlayer/AsciiArtPlayer/Classes/Core/Utils/AsciiArt/UIImage+Util.swift
|
1
|
4312
|
//
// UIImage+Util.swift
// SwiftAsciiArt
//
// Created by Joshua Smith on 4/26/15.
// Copyright (c) 2015 iJoshSmith. All rights reserved.
//
import AVFoundation
import Foundation
import UIKit
extension UIImage
{
class func imageOfSymbol(_ symbol: String, _ font: UIFont) -> UIImage
{
let
length = font.pointSize * 2,
size = CGSize(width: length, height: length),
rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
// Fill the background with white.
context?.setFillColor(UIColor.white.cgColor)
context?.fill(rect)
// Draw the character with black.
let nsString = NSString(string: symbol)
nsString.draw(at: rect.origin, withAttributes: [
NSFontAttributeName: font,
NSForegroundColorAttributeName: UIColor.black
])
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
func imageConstrainedToMaxSize(_ maxSize: CGSize) -> UIImage
{
let isTooBig =
size.width > maxSize.width ||
size.height > maxSize.height
if isTooBig
{
let
maxRect = CGRect(origin: CGPoint.zero, size: maxSize),
scaledRect = AVMakeRect(aspectRatio: self.size, insideRect: maxRect),
scaledSize = scaledRect.size,
targetRect = CGRect(origin: CGPoint.zero, size: scaledSize),
width = Int(scaledSize.width),
height = Int(scaledSize.height),
cgImage = self.cgImage,
bitsPerComp = cgImage?.bitsPerComponent,
compsPerPixel = 4, // RGBA
bytesPerRow = width * compsPerPixel,
colorSpace = cgImage?.colorSpace,
bitmapInfo = cgImage?.bitmapInfo,
context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: bitsPerComp!,
bytesPerRow: bytesPerRow,
space: colorSpace!,
bitmapInfo: (bitmapInfo?.rawValue)!)
if context != nil
{
context!.interpolationQuality = CGInterpolationQuality.low
context?.draw(cgImage!, in: targetRect)
if let scaledCGImage = context?.makeImage()
{
return UIImage(cgImage: scaledCGImage)
}
}
}
return self
}
func imageRotatedToPortraitOrientation() -> UIImage
{
let mustRotate = self.imageOrientation != .up
if mustRotate
{
let rotatedSize = CGSize(width: size.height, height: size.width)
UIGraphicsBeginImageContext(rotatedSize)
if let context = UIGraphicsGetCurrentContext()
{
// Perform the rotation and scale transforms around the image's center.
context.translateBy(x: rotatedSize.width/2, y: rotatedSize.height/2)
// Rotate the image upright.
let
degrees = self.degreesToRotate(),
radians = degrees * .pi / 180.0
context.rotate(by: CGFloat(radians))
// Flip the image on the Y axis.
context.scaleBy(x: 1.0, y: -1.0)
let
targetOrigin = CGPoint(x: -size.width/2, y: -size.height/2),
targetRect = CGRect(origin: targetOrigin, size: self.size)
context.draw(self.cgImage!, in: targetRect)
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return rotatedImage
}
}
return self
}
fileprivate func degreesToRotate() -> Double
{
switch self.imageOrientation
{
case .right: return 90
case .down: return 180
case .left: return -90
default: return 0
}
}
}
|
mit
|
b8a1c74ec2a695ede0ccb6bff7d8ad87
| 32.6875 | 87 | 0.537106 | 5.363184 | false | false | false | false |
nalexn/ViewInspector
|
Sources/ViewInspector/SwiftUI/DisclosureGroup.swift
|
1
|
3268
|
import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct DisclosureGroup: KnownViewType {
public static var typePrefix: String = "DisclosureGroup"
}
}
// MARK: - Extraction from SingleViewContent parent
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
public extension InspectableView where View: SingleViewContent {
func disclosureGroup() throws -> InspectableView<ViewType.DisclosureGroup> {
return try .init(try child(), parent: self)
}
}
// MARK: - Extraction from MultipleViewContent parent
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
public extension InspectableView where View: MultipleViewContent {
func disclosureGroup(_ index: Int) throws -> InspectableView<ViewType.DisclosureGroup> {
return try .init(try child(at: index), parent: self, index: index)
}
}
// MARK: - Content Extraction
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.DisclosureGroup: MultipleViewContent {
public static func children(_ content: Content) throws -> LazyGroup<Content> {
let view = try Inspector.attribute(label: "content", value: content.view)
return try Inspector.viewsInContainer(view: view, medium: content.medium)
}
}
// MARK: - Non Standard Children
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.DisclosureGroup: SupplementaryChildrenLabelView { }
// MARK: - Custom Attributes
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
public extension InspectableView where View == ViewType.DisclosureGroup {
func labelView() throws -> InspectableView<ViewType.ClassifiedView> {
return try View.supplementaryChildren(self).element(at: 0)
.asInspectableView(ofType: ViewType.ClassifiedView.self)
}
func isExpanded() throws -> Bool {
guard let external = try isExpandedBinding() else {
return try isExpandedState().wrappedValue
}
return external.wrappedValue
}
func expand() throws { try set(isExpanded: true) }
func collapse() throws { try set(isExpanded: false) }
private func set(isExpanded: Bool) throws {
if let external = try isExpandedBinding() {
external.wrappedValue = isExpanded
} else {
// @State mutation from outside is ignored by SwiftUI
// try isExpandedState().wrappedValue = isExpanded
// swiftlint:disable line_length
throw InspectionError.notSupported("You need to enable programmatic expansion by using `DisclosureGroup(isExpanded:, content:, label:`")
// swiftlint:enable line_length
}
}
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
private extension InspectableView where View == ViewType.DisclosureGroup {
func isExpandedState() throws -> State<Bool> {
return try Inspector
.attribute(path: "_isExpanded|state", value: content.view, type: State<Bool>.self)
}
func isExpandedBinding() throws -> Binding<Bool>? {
return try? Inspector
.attribute(path: "_isExpanded|binding", value: content.view, type: Binding<Bool>.self)
}
}
|
mit
|
c4d7d72326b558a349165168316c7273
| 33.041667 | 148 | 0.679621 | 4.440217 | false | false | false | false |
abunur/quran-ios
|
Quran/QuranDataSource.swift
|
1
|
3232
|
//
// QuranDataSource.swift
// Quran
//
// Created by Mohamed Afifi on 3/19/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
import GenericDataSources
class QuranDataSource: SegmentedDataSource {
private let dataSourceHandlers: [QuranDataSourceHandler]
private let dataSourceRepresentables: [AnyBasicDataSourceRepresentable<QuranPage>]
var onScrollViewWillBeginDragging: (() -> Void)?
private var selectedDataSourceHandler: QuranDataSourceHandler {
return dataSourceHandlers[selectedDataSourceIndex]
}
var selectedBasicDataSource: AnyBasicDataSourceRepresentable<QuranPage> {
return dataSourceRepresentables[selectedDataSourceIndex]
}
override var selectedDataSource: DataSource? {
didSet {
if oldValue !== selectedDataSource {
ds_reusableViewDelegate?.ds_reloadData()
}
}
}
init(dataSources: [AnyBasicDataSourceRepresentable<QuranPage>], handlers: [QuranDataSourceHandler]) {
assert(dataSources.count == handlers.count)
self.dataSourceHandlers = handlers
self.dataSourceRepresentables = dataSources
super.init()
for ds in dataSources {
add(ds.dataSource)
}
NotificationCenter.default.addObserver(self,
selector: #selector(applicationDidBecomeActive),
name: .UIApplicationDidBecomeActive,
object: nil)
handlers.forEach {
$0.onScrollViewWillBeginDragging = { [weak self] in
self?.onScrollViewWillBeginDragging?()
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func applicationDidBecomeActive() {
selectedDataSourceHandler.applicationDidBecomeActive()
}
func highlightSearchAyaht(_ ayat: Set<AyahNumber>) {
for (offset, ds) in dataSourceHandlers.enumerated() {
ds.highlightSearchAyaht(ayat, isActive: offset == selectedDataSourceIndex)
}
}
func highlightAyaht(_ ayat: Set<AyahNumber>) {
for (offset, ds) in dataSourceHandlers.enumerated() {
ds.highlightAyaht(ayat, isActive: offset == selectedDataSourceIndex)
}
}
func setItems(_ items: [QuranPage]) {
for ds in dataSourceRepresentables {
ds.items = items
}
ds_reusableViewDelegate?.ds_reloadData()
}
func invalidate() {
dataSourceHandlers.forEach { $0.invalidate() }
ds_reusableViewDelegate?.ds_reloadData()
}
}
|
gpl-3.0
|
cf00ad41a828d20f811a5f85504d6ca8
| 32.319588 | 105 | 0.651918 | 5.010853 | false | false | false | false |
crspybits/SMSyncServer
|
iOS/iOSTests/Code/AppDelegate.swift
|
1
|
7152
|
//
// AppDelegate.swift
// NetDb
//
// Created by Christopher Prince on 11/22/15.
// Copyright © 2015 Spastic Muffin, LLC. All rights reserved.
//
import UIKit
import SMCoreLib
import SMSyncServer
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private static let _sharingInvitationCode = SMPersistItemString(name: "AppDelegate.sharingInvitationCode", initialStringValue: "", persistType: .UserDefaults)
static var sharingInvitationCode:String? {
get {
return self._sharingInvitationCode.stringValue == "" ? nil : self._sharingInvitationCode.stringValue
}
set {
self._sharingInvitationCode.stringValue = newValue == nil ? "" : newValue!
}
}
private static let userSignInDisplayName = SMPersistItemString(name: "AppDelegate.userSignInDisplayName", initialStringValue: "", persistType: .UserDefaults)
// MARK: Users of SMSyncServer iOSTests client need to change the contents of this file.
private let smSyncServerClientPlist = "SMSyncServer-client.plist"
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let coreDataSession = CoreData(namesDictionary: [
CoreDataBundleModelName: "ClientAppModel",
CoreDataSqlliteBackupFileName: "~ClientAppModel.sqlite",
CoreDataSqlliteFileName: "ClientAppModel.sqlite"
]);
CoreData.registerSession(coreDataSession, forName: CoreDataTests.name)
let (serverURLString, cloudFolderPath, googleServerClientId) = SMSyncServer.getDataFromPlist(syncServerClientPlistFileName: smSyncServerClientPlist)
// This is the path on the cloud storage service (Google Drive for now) where the app's data will be synced
SMSyncServerUser.session.cloudFolderPath = cloudFolderPath
// Starting to establish account credentials-- user will also have to sign in to their specific account.
let googleSignIn = SMGoogleUserSignIn(serverClientID: googleServerClientId)
googleSignIn.delegate = self
SMUserSignInManager.session.addSignInAccount(googleSignIn, launchOptions:launchOptions)
let facebookSignIn = SMFacebookUserSignIn()
facebookSignIn.delegate = self
SMUserSignInManager.session.addSignInAccount(facebookSignIn, launchOptions:launchOptions)
// Setup the SMSyncServer (Node.js) server URL.
let serverURL = NSURL(string: serverURLString)
SMSyncServer.session.appLaunchSetup(withServerURL: serverURL!, andUserSignInLazyDelegate: SMUserSignInManager.session.lazyCurrentUser)
SMUserSignInManager.session.delegate = self
return true
}
func application(application: UIApplication,
openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if SMUserSignInManager.session.application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) {
return true
}
return false
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
extension AppDelegate : SMUserSignInAccountDelegate {
func smUserSignIn(userJustSignedIn userSignIn:SMUserSignInAccount) {
guard AppDelegate.userSignInDisplayName.stringValue == "" || AppDelegate.userSignInDisplayName.stringValue == userSignIn.displayNameI!
else {
Assert.badMojo(alwaysPrintThisString: "Yikes: Need to sign out of other sign-in (\(AppDelegate.userSignInDisplayName.stringValue))!")
return
}
AppDelegate.userSignInDisplayName.stringValue = userSignIn.displayNameI!
}
func smUserSignIn(userJustSignedOut userSignIn:SMUserSignInAccount) {
// In some non-fatal error cases, we can have userJustSignedOut called and we we'ren't officially signed in. E.g., when trying to sign in, but the sign in fails. SO, don't make this a fatal issue, just log a message.
if AppDelegate.userSignInDisplayName.stringValue != userSignIn.displayNameI! {
Log.error("Not currently signed into userSignIn.displayName!: \(userSignIn.displayNameI)")
}
AppDelegate.userSignInDisplayName.stringValue = ""
}
func smUserSignIn(activelySignedIn userSignIn:SMUserSignInAccount) -> Bool {
return AppDelegate.userSignInDisplayName.stringValue == userSignIn.displayNameI!
}
func smUserSignIn(getSharingInvitationCodeForUserSignIn userSignIn:SMUserSignInAccount) -> String? {
return AppDelegate.sharingInvitationCode
}
func smUserSignIn(resetSharingInvitationCodeForUserSignIn userSignIn:SMUserSignInAccount) {
AppDelegate.sharingInvitationCode = nil
}
func smUserSignIn(userSignIn userSignIn:SMUserSignInAccount, linkedAccountsForSharingUser:[SMLinkedAccount], selectLinkedAccount:(internalUserId:SMInternalUserId)->()) {
// What we really need to do here is to put up a UI and ask the user which linked account they want to use. For now, just choose the first.
selectLinkedAccount(internalUserId: linkedAccountsForSharingUser[0].internalUserId)
}
}
extension AppDelegate : SMUserSignInManagerDelegate {
func didReceiveSharingInvitation(manager:SMUserSignInManager, invitationCode: String, userName: String?) {
AppDelegate.sharingInvitationCode = invitationCode
}
}
|
gpl-3.0
|
6659f9893de44b3c3fa6c9daa3eeaf0f
| 49.359155 | 285 | 0.733604 | 5.193174 | false | false | false | false |
mikaelm1/Gradebook
|
Gradebook/LoginVC.swift
|
1
|
10635
|
//
// LoginVC.swift
// Gradebook
//
// Created by Mikael Mukhsikaroyan on 4/3/16.
// Copyright © 2016 msquared. All rights reserved.
//
import UIKit
import CoreData
import Firebase
import FBSDKCoreKit
import FBSDKLoginKit
class LoginVC: UIViewController, UITextFieldDelegate {
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var signUpButton: UIButton!
@IBOutlet weak var facebookButton: CustomButton!
@IBOutlet weak var udacityButton: CustomButton!
@IBOutlet weak var signInButton: CustomButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var emailField: UITextField!
var sharedContext: NSManagedObjectContext {
return CoreDataStackManager.sharedInstance().managedObjectContext
}
override func viewDidLoad() {
super.viewDidLoad()
emailField.delegate = self
passwordField.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
setUIEnabled(true)
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
getLastLoggedIn()
}
// MARK: - UI Methods
func setUIEnabled(enabled: Bool) {
signUpButton.enabled = enabled
facebookButton.enabled = enabled
udacityButton.enabled = enabled
signInButton.enabled = enabled
passwordField.enabled = enabled
emailField.enabled = enabled
if enabled {
signUpButton.alpha = 1.0
facebookButton.alpha = 1.0
udacityButton.alpha = 1.0
signInButton.alpha = 1.0
passwordField.alpha = 1.0
emailField.alpha = 1.0
showActivity(false)
} else {
signUpButton.alpha = 0.5
facebookButton.alpha = 0.5
udacityButton.alpha = 0.5
signInButton.alpha = 0.5
passwordField.alpha = 0.5
emailField.alpha = 0.5
showActivity(true)
}
}
func showActivity(state: Bool) {
if state {
activityIndicator.hidden = false
activityIndicator.startAnimating()
} else {
activityIndicator.hidden = true
activityIndicator.stopAnimating()
}
}
func sendAlert(message: String) {
let vc = UIAlertController(title: "Error", message: message, preferredStyle: .Alert)
vc.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action) in
self.emailField.becomeFirstResponder()
}))
presentViewController(vc, animated: true, completion: nil)
}
// MARK: - Helper Methods
func saveUserLogin(email: String) {
NSUserDefaults.standardUserDefaults().setObject(email, forKey: Constants.LAST_LOGGED_IN)
print("Saved user email")
}
func getLastLoggedIn() {
print("Inside getLastLoggedIn")
if let email = NSUserDefaults.standardUserDefaults().objectForKey(Constants.LAST_LOGGED_IN) as? String {
print("Last email: \(email)")
let student = getStudent(email)
print("Student: \(student.username)")
goToCoursesFor(student)
}
}
func getEmail() -> String? {
if let email = emailField.text where email != "" {
return email
}
return nil
}
func getPassword() -> String? {
if let password = passwordField.text where password != "" {
return password
}
return nil
}
func goToCoursesFor(student: Student) {
print("Inside goToCourse")
eraseTextFields()
let vc = storyboard?.instantiateViewControllerWithIdentifier("CoursesTableVC") as! CoursesTableVC
vc.student = student
let nc = UINavigationController(rootViewController: vc)
presentViewController(nc, animated: true, completion: nil)
}
func eraseTextFields() {
if emailField != nil && passwordField != nil {
emailField.text = ""
passwordField.text = ""
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
}
// MARK: - Fetch Request
func executeFetchForUser(username: String) -> [Student] {
let fetchRequest = NSFetchRequest(entityName: "Student")
do {
return try CoreDataStackManager.sharedInstance().managedObjectContext.executeFetchRequest(fetchRequest) as! [Student]
} catch {
return [Student]()
}
}
func getStudent(username: String) -> Student {
let students = executeFetchForUser(username)
print("Count of Students: \(students.count)")
if students.count >= 0 {
for student in students {
if student.username == username {
print("Found the student for the email")
return student
}
}
}
return createStudent(username)
}
func createStudent(username: String) -> Student {
let student = Student(username: username, context: sharedContext, courses: nil)
CoreDataStackManager.sharedInstance().saveContext()
return student
}
// MARK: - Actions
@IBAction func singUpPresed(sender: AnyObject) {
setUIEnabled(false)
if let email = getEmail(), let password = getPassword() {
setUIEnabled(false)
FirebaseClient.sharedInstance.createUser(email, password: password, completionHandler: { (success, error) in
if error != nil {
performUpdatesOnMain({
self.setUIEnabled(true)
self.sendAlert(error!)
})
} else {
performUpdatesOnMain({
self.setUIEnabled(true)
let student = self.getStudent(email)
self.saveUserLogin(email)
self.goToCoursesFor(student)
})
}
})
} else {
setUIEnabled(true)
sendAlert("Please enter an email and password in order to sign up.")
}
}
@IBAction func signInPressed(sender: AnyObject) {
setUIEnabled(false)
if let email = getEmail(), let password = getPassword() {
FirebaseClient.sharedInstance.attemptLogin(email, password: password, completionHandler: { (success, error) in
if error != nil {
performUpdatesOnMain({
self.setUIEnabled(true)
self.sendAlert(error!)
})
} else {
performUpdatesOnMain({
self.setUIEnabled(true)
self.saveUserLogin(email)
let student = self.getStudent(email)
self.goToCoursesFor(student)
})
}
})
} else {
setUIEnabled(true)
sendAlert("Please enter an email and password to sign in.")
}
}
@IBAction func udacityLoginPressed(sender: AnyObject) {
setUIEnabled(false)
if let email = getEmail(), let password = getPassword() {
UdacityCient.sharedInstance().authenticateUser(email, password: password, completionHandlerForLogin: { (success, error) in
if error != nil {
performUpdatesOnMain({
self.setUIEnabled(true)
self.sendAlert(error!)
})
} else {
performUpdatesOnMain({
self.setUIEnabled(true)
self.saveUserLogin(email)
let student = self.getStudent(email)
self.goToCoursesFor(student)
})
}
})
} else {
setUIEnabled(true)
sendAlert("Please enter an email and password to sign in.")
}
}
@IBAction func facebookLoginPressed(sender: AnyObject) {
setUIEnabled(false)
FirebaseClient.sharedInstance.attemptFacebookLogin(self) { (success, result, error) in
if error != nil {
performUpdatesOnMain({
self.setUIEnabled(true)
self.sendAlert(error!)
})
} else if success {
let email = result!["email"] as! String
performUpdatesOnMain({
self.setUIEnabled(true)
self.saveUserLogin(email)
let student = self.getStudent(email)
self.goToCoursesFor(student)
})
} else {
self.setUIEnabled(true)
print("Something weird has happened")
}
}
}
// MARK: TextField Delegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: Keyboard methods
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginVC.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginVC.keyboardWillHide), name: UIKeyboardWillHideNotification, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
topConstraint.constant = 10
}
func keyboardWillHide() {
topConstraint.constant = 100
}
}
|
mit
|
aaea75b540ff560627460625af77f348
| 31.519878 | 164 | 0.562159 | 5.605693 | false | false | false | false |
nathawes/swift
|
test/IRGen/enum_resilience.swift
|
9
|
22905
|
// RUN: %empty-directory(%t)
// RUN: %{python} %utils/chex.py < %s > %t/enum_resilience.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -disable-type-layout -emit-ir -enable-library-evolution -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift | %FileCheck %t/enum_resilience.swift --check-prefix=ENUM_RES
// RUN: %target-swift-frontend -disable-type-layout -emit-ir -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift | %FileCheck %t/enum_resilience.swift --check-prefix=ENUM_NOT_RES
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -disable-type-layout -module-name enum_resilience -I %t -emit-ir -enable-library-evolution %s | %FileCheck %t/enum_resilience.swift -DINT=i%target-ptrsize --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu
// RUN: %target-swift-frontend -module-name enum_resilience -I %t -emit-ir -enable-library-evolution -O %s
import resilient_enum
import resilient_struct
// ENUM_RES: @"$s14resilient_enum6MediumO8PamphletyA2CcACmFWC" = {{.*}}constant i32 0
// ENUM_RES: @"$s14resilient_enum6MediumO8PostcardyAC0A7_struct4SizeVcACmFWC" = {{.*}}constant i32 1
// ENUM_RES: @"$s14resilient_enum6MediumO5PaperyA2CmFWC" = {{.*}}constant i32 2
// ENUM_RES: @"$s14resilient_enum6MediumO6CanvasyA2CmFWC" = {{.*}}constant i32 3
// ENUM_NOT_RES-NOT: @"$s14resilient_enum6MediumO8PamphletyA2CcACmFWC" =
// ENUM_NOT_RES-NOT: @"$s14resilient_enum6MediumO8PostcardyAC0A7_struct4SizeVcACmFWC" =
// ENUM_NOT_RES-NOT: @"$s14resilient_enum6MediumO5PaperyA2CmFWC" =
// ENUM_NOT_RES-NOT: @"$s14resilient_enum6MediumO6CanvasyA2CmFWC" =
// CHECK: %T15enum_resilience5ClassC = type <{ %swift.refcounted }>
// CHECK: %T15enum_resilience9ReferenceV = type <{ %T15enum_resilience5ClassC* }>
// Public fixed layout struct contains a public resilient struct,
// cannot use spare bits
// CHECK: %T15enum_resilience6EitherO = type <{ [[REFERENCE_TYPE:\[(4|8) x i8\]]], [1 x i8] }>
// Public resilient struct contains a public resilient struct,
// can use spare bits
// CHECK: %T15enum_resilience15ResilientEitherO = type <{ [[REFERENCE_TYPE]] }>
// Internal fixed layout struct contains a public resilient struct,
// can use spare bits
// CHECK: %T15enum_resilience14InternalEitherO = type <{ [[REFERENCE_TYPE]] }>
// Public fixed layout struct contains a fixed layout struct,
// can use spare bits
// CHECK: %T15enum_resilience10EitherFastO = type <{ [[REFERENCE_TYPE]] }>
// CHECK: @"$s15enum_resilience24EnumWithResilientPayloadOMl" =
// CHECK-SAME: internal global { %swift.type*, i8* } zeroinitializer, align
// CHECK: @"$s15enum_resilience24EnumWithResilientPayloadOMn" = {{.*}}constant
// 0x00010052
// 0x0001 - InPlaceMetadataInitialization
// 0x 0040 - IsUnique
// 0x 0012 - Enum
// CHECK-SAME: <i32 0x0001_0052>,
// CHECK-SAME: @"$s15enum_resilience24EnumWithResilientPayloadOMl"
// CHECK-SAME: @"$s15enum_resilience24EnumWithResilientPayloadOMf", i32 0, i32 1)
// CHECK-SAME: @"$s15enum_resilience24EnumWithResilientPayloadOMr"
public class Class {}
public struct Reference {
public var n: Class
}
@frozen public enum Either {
case Left(Reference)
case Right(Reference)
}
public enum ResilientEither {
case Left(Reference)
case Right(Reference)
}
enum InternalEither {
case Left(Reference)
case Right(Reference)
}
@frozen public struct ReferenceFast {
public var n: Class
}
@frozen public enum EitherFast {
case Left(ReferenceFast)
case Right(ReferenceFast)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s15enum_resilience25functionWithResilientEnumy010resilient_A06MediumOAEF"(%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture %1)
public func functionWithResilientEnum(_ m: Medium) -> Medium {
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s14resilient_enum6MediumOMa"([[INT]] 0)
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// This is copying the +0 argument to be used as a return value.
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%initializeWithCopy]] = bitcast i8* [[WITNESS]]
// CHECK-arm64e-NEXT: ptrtoint i8** [[WITNESS_ADDR]] to i64
// CHECK-arm64e-NEXT: call i64 @llvm.ptrauth.blend.i64
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return m
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s15enum_resilience33functionWithIndirectResilientEnumy010resilient_A00E8ApproachOAEF"(%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture %1)
public func functionWithIndirectResilientEnum(_ ia: IndirectApproach) -> IndirectApproach {
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s14resilient_enum16IndirectApproachOMa"([[INT]] 0)
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// This is copying the +0 argument into the return slot.
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%initializeWithCopy]] = bitcast i8* [[WITNESS]]
// CHECK-arm64e-NEXT: ptrtoint i8** [[WITNESS_ADDR]] to i64
// CHECK-arm64e-NEXT: call i64 @llvm.ptrauth.blend.i64
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return ia
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s15enum_resilience31constructResilientEnumNoPayload010resilient_A06MediumOyF"
public func constructResilientEnumNoPayload() -> Medium {
// CHECK: [[TAG:%.*]] = load i32, i32* @"$s14resilient_enum6MediumO5PaperyA2CmFWC"
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s14resilient_enum6MediumOMa"([[INT]] 0)
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-16-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 16
// CHECK-32-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 14
// CHECK-64-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 13
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-arm64e-NEXT: ptrtoint i8** [[WITNESS_ADDR]] to i64
// CHECK-arm64e-NEXT: call i64 @llvm.ptrauth.blend.i64
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %0, i32 [[TAG]], %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return Medium.Paper
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s15enum_resilience29constructResilientEnumPayloady010resilient_A06MediumO0G7_struct4SizeVF"
public func constructResilientEnumPayload(_ s: Size) -> Medium {
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0)
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable*
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8
// CHECK-NEXT: [[WITNESS_FOR_SIZE:%size]] = load [[INT]], [[INT]]* [[WITNESS_ADDR]]
// CHECK-NEXT: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK-NEXT: call void @llvm.lifetime.start.p0i8({{(i32|i64)}} -1, i8* [[ALLOCA]])
// CHECK-NEXT: [[ENUM_STORAGE:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque*
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%initializeWithCopy]] = bitcast i8* [[WITNESS]] to %swift.opaque* (%swift.opaque*, %swift.opaque*, %swift.type*)*
// CHECK-arm64e-NEXT: ptrtoint i8** [[WITNESS_ADDR]] to i64
// CHECK-arm64e-NEXT: call i64 @llvm.ptrauth.blend.i64
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias [[ENUM_STORAGE]], %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%initializeWithTake]] = bitcast i8* [[WITNESS]] to %swift.opaque* (%swift.opaque*, %swift.opaque*, %swift.type*)*
// CHECK-arm64e-NEXT: ptrtoint i8** [[WITNESS_ADDR]] to i64
// CHECK-arm64e-NEXT: call i64 @llvm.ptrauth.blend.i64
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias %0, %swift.opaque* noalias [[ENUM_STORAGE]], %swift.type* [[METADATA]])
// CHECK-NEXT: [[TAG:%.*]] = load i32, i32* @"$s14resilient_enum6MediumO8PostcardyAC0A7_struct4SizeVcACmFWC"
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s14resilient_enum6MediumOMa"([[INT]] 0)
// CHECK-NEXT: [[METADATA2:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[METADATA_ADDR2:%.*]] = bitcast %swift.type* [[METADATA2]] to i8***
// CHECK-NEXT: [[VWT_ADDR2:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR2]], [[INT]] -1
// CHECK-NEXT: [[VWT2:%.*]] = load i8**, i8*** [[VWT_ADDR2]]
// CHECK-16-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT2]], i32 16
// CHECK-32-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT2]], i32 14
// CHECK-64-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT2]], i32 13
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%destructiveInjectEnumTag]] = bitcast i8* [[WITNESS]]
// CHECK-arm64e-NEXT: ptrtoint i8** [[WITNESS_ADDR]] to i64
// CHECK-arm64e-NEXT: call i64 @llvm.ptrauth.blend.i64
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %0, i32 [[TAG]], %swift.type* [[METADATA2]])
// CHECK-NEXT: [[STORAGE_ALLOCA:%.*]] = bitcast %swift.opaque* [[ENUM_STORAGE]] to i8*
// CHECK-NEXT: call void @llvm.lifetime.end.p0i8({{(i32|i64)}} -1, i8* [[STORAGE_ALLOCA]])
// CHECK-NEXT: ret void
return Medium.Postcard(s)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s15enum_resilience19resilientSwitchTestySi0c1_A06MediumOF"(%swift.opaque* noalias nocapture %0)
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s14resilient_enum6MediumOMa"([[INT]] 0)
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable*
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8
// CHECK: [[WITNESS_FOR_SIZE:%size]] = load [[INT]], [[INT]]* [[WITNESS_ADDR]]
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ENUM_STORAGE:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque*
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FN:%initializeWithCopy]] = bitcast i8* [[WITNESS]]
// CHECK: [[ENUM_COPY:%.*]] = call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias [[ENUM_STORAGE]], %swift.opaque* noalias %0, %swift.type* [[METADATA]])
// CHECK-16-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 14
// CHECK-32-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 12
// CHECK-64-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 11
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FN:%getEnumTag]] = bitcast i8* [[WITNESS]]
// CHECK: [[TAG:%.*]] = call i32 [[WITNESS_FN]](%swift.opaque* noalias [[ENUM_STORAGE]], %swift.type* [[METADATA]])
// CHECK: [[PAMPHLET_CASE_TAG:%.*]] = load i32, i32* @"$s14resilient_enum6MediumO8PamphletyA2CcACmFWC"
// CHECK: [[PAMPHLET_CASE:%.*]] = icmp eq i32 [[TAG]], [[PAMPHLET_CASE_TAG]]
// CHECK: br i1 [[PAMPHLET_CASE]], label %[[PAMPHLET_CASE_LABEL:.*]], label %[[PAPER_CHECK:.*]]
// CHECK: [[PAPER_CHECK]]:
// CHECK: [[PAPER_CASE_TAG:%.*]] = load i32, i32* @"$s14resilient_enum6MediumO5PaperyA2CmFWC"
// CHECK: [[PAPER_CASE:%.*]] = icmp eq i32 [[TAG]], [[PAPER_CASE_TAG]]
// CHECK: br i1 [[PAPER_CASE]], label %[[PAPER_CASE_LABEL:.*]], label %[[CANVAS_CHECK:.*]]
// CHECK: [[CANVAS_CHECK]]:
// CHECK: [[CANVAS_CASE_TAG:%.*]] = load i32, i32* @"$s14resilient_enum6MediumO6CanvasyA2CmFWC"
// CHECK: [[CANVAS_CASE:%.*]] = icmp eq i32 [[TAG]], [[CANVAS_CASE_TAG]]
// CHECK: br i1 [[CANVAS_CASE]], label %[[CANVAS_CASE_LABEL:.*]], label %[[DEFAULT_CASE:.*]]
// CHECK: [[PAPER_CASE_LABEL]]:
// CHECK: br label %[[END:.*]]
// CHECK: [[CANVAS_CASE_LABEL]]:
// CHECK: br label %[[END]]
// CHECK: [[PAMPHLET_CASE_LABEL]]:
// CHECK: swift_projectBox
// CHECK: br label %[[END]]
// CHECK: [[DEFAULT_CASE]]:
// CHeCK: call void %destroy
// CHECK: br label %[[END]]
// CHECK: [[END]]:
// CHECK: = phi [[INT]] [ 3, %[[DEFAULT_CASE]] ], [ {{.*}}, %[[PAMPHLET_CASE_LABEL]] ], [ 2, %[[CANVAS_CASE_LABEL]] ], [ 1, %[[PAPER_CASE_LABEL]] ]
// CHECK: ret
public func resilientSwitchTest(_ m: Medium) -> Int {
switch m {
case .Paper:
return 1
case .Canvas:
return 2
case .Pamphlet(let m):
return resilientSwitchTest(m)
default:
return 3
}
}
public func reabstraction<T>(_ f: (Medium) -> T) {}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s15enum_resilience25resilientEnumPartialApplyyySi0c1_A06MediumOXEF"(i8* %0, %swift.opaque* %1)
public func resilientEnumPartialApply(_ f: (Medium) -> Int) {
// CHECK: [[STACKALLOC:%.*]] = alloca i8
// CHECK: [[CONTEXT:%.*]] = bitcast i8* [[STACKALLOC]] to %swift.opaque*
// CHECK: call swiftcc void @"$s15enum_resilience13reabstractionyyx010resilient_A06MediumOXElF"(i8* bitcast ({{.*}} @"$s14resilient_enum6MediumOSiIgnd_ACSiIegnr_TRTA{{(\.ptrauth)?}}" to i8*), %swift.opaque* [[CONTEXT:%.*]], %swift.type* @"$sSiN")
reabstraction(f)
// CHECK: ret void
}
// CHECK-LABEL: define internal swiftcc void @"$s14resilient_enum6MediumOSiIgnd_ACSiIegnr_TRTA"(%TSi* noalias nocapture sret %0, %swift.opaque* noalias nocapture %1, %swift.refcounted* swiftself %2)
// Enums with resilient payloads from a different resilience domain
// require runtime metadata instantiation, just like generics.
public enum EnumWithResilientPayload {
case OneSize(Size)
case TwoSizes(Size, Size)
}
// Make sure we call a function to access metadata of enums with
// resilient layout.
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s15enum_resilience20getResilientEnumTypeypXpyF"()
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s15enum_resilience24EnumWithResilientPayloadOMa"([[INT]] 0)
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: ret %swift.type* [[METADATA]]
public func getResilientEnumType() -> Any.Type {
return EnumWithResilientPayload.self
}
// Public metadata accessor for our resilient enum
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s15enum_resilience24EnumWithResilientPayloadOMa"(
// CHECK: [[LOAD_METADATA:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s15enum_resilience24EnumWithResilientPayloadOMl", i32 0, i32 0), align
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[LOAD_METADATA]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s15enum_resilience24EnumWithResilientPayloadOMn" to %swift.type_descriptor*))
// CHECK-NEXT: [[RESPONSE_METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK-NEXT: [[RESPONSE_STATE:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT_METADATA:%.*]] = phi %swift.type* [ [[LOAD_METADATA]], %entry ], [ [[RESPONSE_METADATA]], %cacheIsNull ]
// CHECK-NEXT: [[RESULT_STATE:%.*]] = phi [[INT]] [ 0, %entry ], [ [[RESPONSE_STATE]], %cacheIsNull ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[RESULT_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[RESULT_STATE]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// Methods inside extensions of resilient enums fish out type parameters
// from metadata -- make sure we can do that
extension ResilientMultiPayloadGenericEnum {
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s14resilient_enum32ResilientMultiPayloadGenericEnumO0B11_resilienceE16getTypeParameterxmyF"(%swift.type* %"ResilientMultiPayloadGenericEnum<T>", %swift.opaque* noalias nocapture swiftself %0)
// CHECK: [[METADATA:%.*]] = bitcast %swift.type* %"ResilientMultiPayloadGenericEnum<T>" to %swift.type**
// CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[METADATA]], [[INT]] 2
// CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]]
public func getTypeParameter() -> T.Type {
return T.self
}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s15enum_resilience39constructExhaustiveWithResilientMembers010resilient_A011SimpleShapeOyF"(%T14resilient_enum11SimpleShapeO* noalias nocapture sret %0)
// CHECK: [[BUFFER:%.*]] = bitcast %T14resilient_enum11SimpleShapeO* %0 to %swift.opaque*
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0)
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: [[STORE_TAG:%.*]] = bitcast i8* {{%.+}} to void (%swift.opaque*, i32, i32, %swift.type*)*
// CHECK-arm64e-NEXT: ptrtoint i8** {{.*}} to i64
// CHECK-arm64e-NEXT: call i64 @llvm.ptrauth.blend.i64
// CHECK-NEXT: call void [[STORE_TAG]](%swift.opaque* noalias [[BUFFER]], i32 1, i32 1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
// CHECK-NEXT: {{^}$}}
public func constructExhaustiveWithResilientMembers() -> SimpleShape {
return .KleinBottle
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc { i{{64|32}}, i8 } @"$s15enum_resilience19constructFullyFixed010resilient_A00dE6LayoutOyF"()
// CHECK: ret { [[INT]], i8 } { [[INT]] 0, i8 1 }
// CHECK-NEXT: {{^}$}}
public func constructFullyFixed() -> FullyFixedLayout {
return .noPayload
}
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s15enum_resilience24EnumWithResilientPayloadOMr"(%swift.type* %0, i8* %1, i8** %2)
// CHECK: [[TUPLE_LAYOUT:%.*]] = alloca %swift.full_type_layout
// CHECK: [[SIZE_RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 319)
// CHECK-NEXT: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[SIZE_RESPONSE]], 0
// CHECK-NEXT: [[SIZE_STATE:%.*]] = extractvalue %swift.metadata_response [[SIZE_RESPONSE]], 1
// CHECK-NEXT: [[T0:%.*]] = icmp ule [[INT]] [[SIZE_STATE]], 63
// CHECK-NEXT: br i1 [[T0]], label %[[SATISFIED1:.*]], label
// CHECK: [[SATISFIED1]]:
// CHECK-NEXT: [[T0:%.*]] = bitcast %swift.type* [[SIZE_METADATA]] to i8***
// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], [[INT]] -1
// CHECK-NEXT: [[SIZE_VWT:%.*]] = load i8**, i8*** [[T1]],
// CHECK-NEXT: [[SIZE_LAYOUT_1:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8
// CHECK-NEXT: store i8** [[SIZE_LAYOUT_1]],
// CHECK-NEXT: getelementptr
// CHECK-NEXT: [[SIZE_LAYOUT_2:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8
// CHECK-NEXT: [[SIZE_LAYOUT_3:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8
// CHECK-NEXT: call swiftcc [[INT]] @swift_getTupleTypeLayout2(%swift.full_type_layout* [[TUPLE_LAYOUT]], i8** [[SIZE_LAYOUT_2]], i8** [[SIZE_LAYOUT_3]])
// CHECK-NEXT: [[T0:%.*]] = bitcast %swift.full_type_layout* [[TUPLE_LAYOUT]] to i8**
// CHECK-NEXT: store i8** [[T0]],
// CHECK: call void @swift_initEnumMetadataMultiPayload
// CHECK: phi %swift.type* [ [[SIZE_METADATA]], %entry ], [ null, %[[SATISFIED1]] ]
// CHECK: phi [[INT]] [ 63, %entry ], [ 0, %[[SATISFIED1]] ]
public protocol Prot {
}
private enum ProtGenEnumWithSize<T: Prot> {
case c1(s1: Size)
case c2(s2: Size)
}
// CHECK-LABEL: define linkonce_odr hidden %T15enum_resilience19ProtGenEnumWithSize33_59077B69D65A4A3BEE0C93708067D5F0LLO* @"$s15enum_resilience19ProtGenEnumWithSize33_59077B69D65A4A3BEE0C93708067D5F0LLOyxGAA0C0RzlWOh"(%T15enum_resilience19ProtGenEnumWithSize
// CHECK: ret %T15enum_resilience19ProtGenEnumWithSize33_59077B69D65A4A3BEE0C93708067D5F0LLO* %0
|
apache-2.0
|
ebb593ddb1dc102f740103e1fd2c6f45
| 56.550251 | 276 | 0.666536 | 3.310928 | false | false | false | false |
ratreya/lipika-ime
|
Application/MappingTable.swift
|
1
|
10380
|
/*
* LipikaApp is companion application for LipikaIME.
* Copyright (C) 2020 Ranganath Atreya
*
* 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.
*/
import SwiftUI
import AppKit
import Carbon.HIToolbox
import LipikaEngine_OSX
extension String {
static let hex = CharacterSet(charactersIn: "0123456789ABCDEF, ").inverted
func isHex() -> Bool {
return self.rangeOfCharacter(from: String.hex) == nil
}
}
class UnicodeTextField: NSTextField {
private func toHex() {
if !self.stringValue.isHex() {
self.stringValue = self.stringValue.unicodeScalars.map({$0.value}).map({String($0, radix: 16, uppercase: true)}).joined(separator: ", ")
}
}
private func toGlyph() {
if !self.stringValue.isEmpty && self.stringValue.isHex() {
self.stringValue = self.stringValue.components(separatedBy: ",").map({$0.trimmingCharacters(in: CharacterSet.whitespaces)}).map({String(UnicodeScalar(Int($0, radix: 16)!)!)}).joined()
}
}
override func doCommand(by selector: Selector) {
if selector == #selector(NSResponder.cancelOperation) {
toGlyph()
}
super.doCommand(by: selector)
}
override func becomeFirstResponder() -> Bool {
toHex()
return super.becomeFirstResponder()
}
override func textDidEndEditing(_ notification: Notification) {
toGlyph()
super.textDidEndEditing(notification)
}
}
struct MappingTable: NSViewControllerRepresentable {
@Binding var mappings: [[String]]
typealias NSViewControllerType = MappingTableController
func makeNSViewController(context: Context) -> MappingTableController {
return MappingTableController(self)
}
func updateNSViewController(_ nsViewController: MappingTableController, context: Context) {
if nsViewController.mappings != mappings {
nsViewController.mappings = mappings
nsViewController.table.reloadData()
}
}
}
class MappingTableController: NSViewController, NSTableViewDelegate, NSTableViewDataSource, NSTextFieldDelegate {
private var dragDropType = NSPasteboard.PasteboardType(rawValue: "private.table-row")
private let types = ["CONSONANT", "DEPENDENT", "DIGIT", "SIGN", "VOWEL"]
private var wrapper: MappingTable
var table = NSTableView()
var mappings: [[String]]
init(_ wrapper: MappingTable) {
self.wrapper = wrapper
self.mappings = wrapper.mappings
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
self.view = NSView()
view.autoresizesSubviews = true
let columns = [
(title: "Type", width: 150.0, tooltip: "Output character type"),
(title: "Key", width: 180.0, tooltip: "Mapping identifier"),
(title: "Scheme", width: 135.0, tooltip: "User input"),
(title: "Script", width: 140.0, tooltip: "Generated output")
]
for column in columns {
let tableColumn = NSTableColumn()
tableColumn.headerCell.title = column.title
tableColumn.headerCell.alignment = .center
tableColumn.identifier = NSUserInterfaceItemIdentifier(rawValue: column.title)
tableColumn.width = CGFloat(column.width)
tableColumn.headerToolTip = column.tooltip
table.addTableColumn(tableColumn)
}
table.allowsColumnResizing = false
table.allowsColumnSelection = false
table.allowsMultipleSelection = false
table.allowsColumnReordering = false
table.allowsEmptySelection = true
table.allowsTypeSelect = false
table.intercellSpacing = NSSize(width: 5, height: 7)
let menu = NSMenu(title: "Mappings")
menu.addItem(NSMenuItem(title: "Add Mapping", action: #selector(self.addMappingMenu(receiver:)), keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "Remove Mapping", action: #selector(self.removeMappingMenu(receiver:)), keyEquivalent: ""))
table.menu = menu
let scroll = NSScrollView()
scroll.documentView = table
scroll.hasVerticalScroller = true
scroll.autoresizingMask = [.height, .width]
scroll.borderType = .bezelBorder
view.addSubview(scroll)
}
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
table.registerForDraggedTypes([dragDropType])
}
// NSTableViewDelegate
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
switch tableColumn?.title {
case "Type":
let type = NSPopUpButton()
type.identifier = tableColumn!.identifier
type.addItems(withTitles: types)
type.target = self
type.action = #selector(self.onChange(receiver:))
return type
case "Key":
let key = NSTextField()
key.identifier = tableColumn!.identifier
key.delegate = self
return key
case "Scheme":
let scheme = NSTextField()
scheme.identifier = tableColumn!.identifier
scheme.delegate = self
return scheme
case "Script":
let script = UnicodeTextField()
script.identifier = tableColumn!.identifier
script.delegate = self
return script
default:
Logger.log.fatal("Unknown column title \(tableColumn!.title)")
fatalError()
}
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 25
}
func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] {
if edge == .leading {
return [NSTableViewRowAction(style: .regular, title: "Add", handler: { action, row in self.addMapping(at: row) })]
}
else {
return [NSTableViewRowAction(style: .destructive, title: "Remove", handler: { action, row in self.removeMapping(row: row) })]
}
}
// NSTableViewDataSource
func numberOfRows(in tableView: NSTableView) -> Int {
return mappings.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
switch tableColumn!.title {
case "Type":
return types.firstIndex(of: mappings[row][0])
case "Key":
return mappings[row][1]
case "Scheme":
return mappings[row][2]
case "Script":
return mappings[row][3]
default:
Logger.log.fatal("Unknown column title \(tableColumn!.title)")
fatalError()
}
}
func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? {
let item = NSPasteboardItem()
item.setString(String(row), forType: dragDropType)
return item
}
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
if dropOperation == .above {
return .move
}
return []
}
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
var oldIndexes = IndexSet()
info.enumerateDraggingItems(options: [], for: tableView, classes: [NSPasteboardItem.self], searchOptions: [:]) { dragItem, _, _ in
if let str = (dragItem.item as! NSPasteboardItem).string(forType: self.dragDropType), let index = Int(str) {
oldIndexes.insert(index)
}
}
mappings.move(fromOffsets: oldIndexes, toOffset: row)
updateWrapper()
table.reloadData()
return true
}
// Native API
func updateWrapper() {
if wrapper.mappings != self.mappings {
wrapper.mappings = self.mappings
}
}
@objc func onChange(receiver: Any) {
let row = table.row(for: receiver as! NSView)
if row == -1 {
// The view has changed under us
return
}
let column = table.column(for: receiver as! NSView)
switch column {
case 0:
mappings[row][0] = (receiver as! NSPopUpButton).titleOfSelectedItem!
case 1:
mappings[row][1] = (receiver as! NSTextField).stringValue
case 2:
mappings[row][2] = (receiver as! NSTextField).stringValue
case 3:
mappings[row][3] = (receiver as! NSTextField).stringValue
default:
Logger.log.fatal("Unknown column: \(column)")
fatalError()
}
updateWrapper()
}
func controlTextDidEndEditing(_ obj: Notification) {
onChange(receiver: obj.object!)
}
// Own API
@objc func addMappingMenu(receiver: Any) {
addMapping(at: table.clickedRow + 1)
}
@objc func removeMappingMenu(receiver: Any) {
removeMapping(row: table.clickedRow)
}
func addMapping(at: Int? = nil) {
let newRow = at ?? table.selectedRow + 1
mappings.insert([types[0], "", "", ""], at: newRow)
wrapper.mappings = self.mappings
table.reloadData()
table.selectRowIndexes(IndexSet.init(integer: newRow), byExtendingSelection: false)
table.scrollRowToVisible(table.selectedRow)
}
func removeMapping(row: Int? = nil) {
let selectedRow = row ?? table.selectedRow
mappings.remove(at: selectedRow)
wrapper.mappings = self.mappings
table.reloadData()
table.selectRowIndexes(IndexSet.init(integer: max(0, selectedRow - 1)), byExtendingSelection: false)
table.scrollRowToVisible(table.selectedRow)
}
}
|
gpl-3.0
|
485de870e40ab00b84fe416c967a4100
| 35.549296 | 195 | 0.617534 | 4.873239 | false | false | false | false |
DivineDominion/mac-licensing-fastspring-cocoafob
|
Trial-Expire-While-Running/MyNewApp/LicenseChangeBroadcaster.swift
|
1
|
2412
|
// Copyright (c) 2015-2019 Christian Tietze
//
// See the file LICENSE for copying permission.
import Foundation
public typealias UserInfo = [AnyHashable : Any]
extension Licensing {
public func userInfo() -> UserInfo {
switch self {
case let .trial(trialPeriod):
return [
"registered" : false,
"on_trial" : true,
"trial_start_date" : trialPeriod.startDate,
"trial_end_date" : trialPeriod.endDate,
]
case let .registered(license):
return [
"registered" : true,
"on_trial" : false,
"name" : license.name,
"licenseCode" : license.licenseCode
]
case .trialExpired:
return [
"registered" : false,
"on_trial" : false
]
}
}
public init?(fromUserInfo userInfo: UserInfo) {
guard let registered = userInfo["registered"] as? Bool else {
return nil
}
if !registered, let onTrial = userInfo["on_trial"] as? Bool {
if !onTrial {
self = .trialExpired
return
}
if let startDate = userInfo["trial_start_date"] as? Date,
let endDate = userInfo["trial_end_date"] as? Date {
self = .trial(TrialPeriod(startDate: startDate, endDate: endDate))
return
}
}
guard let name = userInfo["name"] as? String,
let licenseCode = userInfo["licenseCode"] as? String
else { return nil }
self = .registered(License(name: name, licenseCode: licenseCode))
}
}
extension Licensing {
public static let licenseChangedNotification: Notification.Name = Notification.Name(rawValue: "License Changed")
}
public class LicenseChangeBroadcaster {
let notificationCenter: NotificationCenter
public init(notificationCenter: NotificationCenter = .default) {
self.notificationCenter = notificationCenter
}
public func broadcast(_ licensing: Licensing) {
notificationCenter.post(
name: Licensing.licenseChangedNotification,
object: self,
userInfo: licensing.userInfo())
}
}
|
mit
|
746e537a22c1a9410747da7fc6756de2
| 28.060241 | 116 | 0.538143 | 5.198276 | false | false | false | false |
eytanbiala/On-The-Map
|
On The Map/TabViewController.swift
|
1
|
2908
|
//
// ViewController.swift
// On The Map
//
// Created by Eytan Biala on 4/26/16.
// Copyright © 2016 Udacity. All rights reserved.
//
import UIKit
class TabViewController: UITabBarController, UITabBarControllerDelegate, InfoPostingViewControllerDelegate {
var mapView : MapViewController!
var listView : ListViewController!
override func viewDidLoad() {
super.viewDidLoad()
tabBarController?.delegate = self
tabBar.translucent = false;
mapView = MapViewController();
listView = ListViewController();
viewControllers = [mapView, listView]
title = "On The Map"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .Plain, target: self, action: #selector(logout))
navigationItem.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: #selector(refresh)),
UIBarButtonItem(image: UIImage(named: "pin"), style: .Plain, target: self, action: #selector(addPin))
]
loadLocations()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
for (_, item) in self.viewControllers!.enumerate() {
item.viewWillAppear(animated)
}
}
func loadLocations() {
UdacityClient.getStudentLocations { (error, result) -> (Void) in
if result != nil {
if let results = result?["results"] as? Array<Dictionary<String, AnyObject>> {
Model.sharedInstance.setStudentLocations(results)
self.mapView.reload()
self.listView.reload()
return
}
}
let alert = UIAlertController(title: "Error", message: "Could not get student locations", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
func logout() {
self.view.alpha = 0.5
UdacityClient.logout { (error, result) -> (Void) in
Model.sharedInstance.signedInUser = nil
self.view.alpha = 1.0
self.dismissViewControllerAnimated(true, completion: nil)
}
}
func addPin() {
let story = UIStoryboard(name: "LoginViewController", bundle: NSBundle.mainBundle())
let vc = story.instantiateViewControllerWithIdentifier("InfoPostingViewController") as! InfoPostingViewController
vc.delegate = self
let nav = UINavigationController(rootViewController: vc)
self.presentViewController(nav, animated: true, completion: nil)
}
func refresh() {
loadLocations()
}
func didAddLocation(sender: InfoPostingViewController) {
refresh()
}
}
|
mit
|
f44687a8938164eef9f7c9db4f6c1da9
| 32.034091 | 147 | 0.621947 | 5.117958 | false | false | false | false |
HTWDD/HTWDresden-iOS
|
HTWDD/Components/Timetable/Main/Views/Week/TimetableLessonDetailsSelectionCell.swift
|
1
|
2277
|
//
// TimetableLessonDetailsSelectionCell.swift
// HTWDD
//
// Created by Chris Herlemann on 08.01.21.
// Copyright © 2021 HTW Dresden. All rights reserved.
//
class TimetableLessonDetailsSelectionCell: UITableViewCell, FromNibLoadable {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var lessonDetailsSelectionField: LessonDetailsSelectionField!
@IBOutlet weak var main: UIView!
weak var delegate: TimetableLessonDetailsCellDelegate?
var lessonElement: LessonDetailElements! {
didSet{
iconView.image = lessonElement.iconImage
iconView.tintColor = UIColor.htw.Icon.primary
lessonDetailsSelectionField.placeholder = lessonElement.placeholder
lessonDetailsSelectionField.selectionOptions = lessonElement.selectionOption
lessonDetailsSelectionField.selectionDelegate = self
}
}
override func awakeFromNib() {
super.awakeFromNib()
main.backgroundColor = UIColor.htw.cellBackground
self.selectionStyle = .none
}
func setup(model: CustomLesson, isEditable: Bool) {
lessonDetailsSelectionField.setup(isEditable: isEditable)
switch lessonElement! {
case .lessonType:
lessonDetailsSelectionField.text = model.type?.localizedDescription
case .weekrotation:
guard let week = model.week else { return }
lessonDetailsSelectionField.text = CalendarWeekRotation(rawValue: week)?.localizedDescription
case .day:
guard let day = model.day else { return }
lessonDetailsSelectionField.text = CalendarWeekDay(rawValue: day)?.localizedDescription
default: break
}
}
}
extension TimetableLessonDetailsSelectionCell: LessonDetailsSelectionFieldDelegate {
func done(_ selectionOptions: LessonDetailsOptions) {
switch selectionOptions {
case .lectureType(let selection): delegate?.changeValue(selection)
case .weekRotation(let selection): delegate?.changeValue(forElement: lessonElement, selection?.rawValue)
case .weekDay(let selection): delegate?.changeValue(forElement: lessonElement, selection?.rawValue)
}
}
}
|
gpl-2.0
|
d4e82af7021c5d9391999d831a3b9976
| 35.709677 | 112 | 0.691564 | 5.208238 | false | false | false | false |
kazedayo/GaldenApp
|
GaldenApp/Custom Classes/Device-Extension.swift
|
1
|
3427
|
//
// Device-Extension.swift
// GaldenApp
//
// Created by Kin Wa Lam on 10/11/2017.
// Copyright © 2017年 1080@galden. All rights reserved.
//
import UIKit
public extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone10,1", "iPhone10,4": return "iPhone 8"
case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3", "iPhone10,6": return "iPhone X"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad6,11", "iPad6,12": return "iPad 5"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch"
case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch"
case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation"
case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch"
case "AppleTV5,3": return "Apple TV"
case "AppleTV6,2": return "Apple TV 4K"
case "AudioAccessory1,1": return "HomePod"
case "i386", "x86_64": return "Simulator"
default: return identifier
}
}
}
|
mit
|
117dea2c28a5b924ef2329a619f5b88c
| 54.225806 | 97 | 0.460572 | 3.895336 | false | false | false | false |
fgengine/quickly
|
Quickly/Extensions/CGSize.swift
|
1
|
1398
|
//
// Quickly
//
public extension CGSize {
func wrap() -> CGSize {
return CGSize(
width: self.height,
height: self.width
)
}
func ceil() -> CGSize {
return CGSize(
width: self.width.ceil(),
height: self.height.ceil()
)
}
func lerp(_ to: CGSize, progress: CGFloat) -> CGSize {
return CGSize(
width: self.width.lerp(to.width, progress: progress),
height: self.height.lerp(to.height, progress: progress)
)
}
func aspectFit(size: CGSize) -> CGSize {
let iw = floor(self.width)
let ih = floor(self.height)
let bw = floor(size.width)
let bh = floor(size.height)
let fw = bw / iw
let fh = bh / ih
let sc = (fw < fh) ? fw : fh
let rw = iw * sc
let rh = ih * sc
return CGSize(
width: rw,
height: rh
)
}
func aspectFill(size: CGSize) -> CGSize {
let iw = floor(self.width)
let ih = floor(self.height)
let bw = floor(size.width)
let bh = floor(size.height)
let fw = bw / iw
let fh = bh / ih
let sc = (fw > fh) ? fw : fh
let rw = iw * sc
let rh = ih * sc
return CGSize(
width: rw,
height: rh
)
}
}
|
mit
|
f198ec86396bc283c511112ea2d6870b
| 22.3 | 67 | 0.464235 | 3.872576 | false | false | false | false |
KinoAndWorld/DailyMood
|
DailyMood/Model/AddDailyAnimator.swift
|
1
|
1539
|
//
// AddDailyAnimator.swift
// DailyMood
//
// Created by kino on 14-7-12.
// Copyright (c) 2014 kino. All rights reserved.
//
import UIKit
import CustomView
class AddDailyAnimator: NSObject , UIViewControllerAnimatedTransitioning{
func transitionDuration(transitionContext: UIViewControllerContextTransitioning!) -> NSTimeInterval{
return 0.55
}
// This method can only be a nop if the transition is interactive and not a percentDriven interactive transition.
func animateTransition(transitionContext: UIViewControllerContextTransitioning!){
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
transitionContext.containerView().addSubview(toVC.view)
toVC.view.alpha = 0.0
let bottomView:MainBottomView = fromVC.valueForKey("bottomView") as MainBottomView
UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
// fromVC.view.transform = CGAffineTransformMakeScale(0.1, 0.1)
bottomView.transform = CGAffineTransformMakeScale(5.0, 5.0)
toVC.view.alpha = 1
}, completion:{ isComplete in
// fromVC.view.transform = CGAffineTransformIdentity
bottomView.transform = CGAffineTransformIdentity
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
})
}
}
|
mit
|
8f75149dca5bd99b607372641dd28547
| 40.594595 | 118 | 0.720598 | 5.919231 | false | false | false | false |
sammyd/Concurrency-VideoSeries
|
projects/002_NSOperationQueue/002_DemoStarter/TiltShift.playground/Sources/UIImageExtensions.swift
|
6
|
4566
|
import UIKit
import Accelerate
extension UIImage {
public func applyBlurWithRadius(blurRadius: CGFloat, maskImage: UIImage? = nil) -> UIImage? {
// Check pre-conditions.
if (size.width < 1 || size.height < 1) {
print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)")
return nil
}
if self.CGImage == nil {
print("*** error: image must be backed by a CGImage: \(self)")
return nil
}
if maskImage != nil && maskImage!.CGImage == nil {
print("*** error: maskImage must be backed by a CGImage: \(maskImage)")
return nil
}
let __FLT_EPSILON__ = CGFloat(FLT_EPSILON)
let screenScale = UIScreen.mainScreen().scale
let imageRect = CGRect(origin: CGPointZero, size: size)
var effectImage = self
let hasBlur = blurRadius > __FLT_EPSILON__
if hasBlur {
func createEffectBuffer(context: CGContext) -> vImage_Buffer {
let data = CGBitmapContextGetData(context)
let width = vImagePixelCount(CGBitmapContextGetWidth(context))
let height = vImagePixelCount(CGBitmapContextGetHeight(context))
let rowBytes = CGBitmapContextGetBytesPerRow(context)
return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
}
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let effectInContext = UIGraphicsGetCurrentContext()!
CGContextScaleCTM(effectInContext, 1.0, -1.0)
CGContextTranslateCTM(effectInContext, 0, -size.height)
CGContextDrawImage(effectInContext, imageRect, self.CGImage)
var effectInBuffer = createEffectBuffer(effectInContext)
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let effectOutContext = UIGraphicsGetCurrentContext()!
var effectOutBuffer = createEffectBuffer(effectOutContext)
if hasBlur {
// A description of how to compute the box kernel width from the Gaussian
// radius (aka standard deviation) appears in the SVG spec:
// http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
//
// For larger values of 's' (s >= 2.0), an approximation can be used: Three
// successive box-blurs build a piece-wise quadratic convolution kernel, which
// approximates the Gaussian kernel to within roughly 3%.
//
// let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
//
// ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
//
let inputRadius = blurRadius * screenScale
var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5))
if radius % 2 != 1 {
radius += 1 // force radius to be odd so that the three box-blur methodology works.
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
effectImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIGraphicsEndImageContext()
}
// Set up output context.
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let outputContext = UIGraphicsGetCurrentContext()
CGContextScaleCTM(outputContext, 1.0, -1.0)
CGContextTranslateCTM(outputContext, 0, -size.height)
// Draw base image.
CGContextDrawImage(outputContext, imageRect, self.CGImage)
// Draw effect image.
if hasBlur {
CGContextSaveGState(outputContext)
if let image = maskImage {
//CGContextClipToMask(outputContext, imageRect, image.CGImage);
let effectCGImage = CGImageCreateWithMask(effectImage.CGImage, image.CGImage)
if let effectCGImage = effectCGImage {
effectImage = UIImage(CGImage: effectCGImage)
}
}
CGContextDrawImage(outputContext, imageRect, effectImage.CGImage)
CGContextRestoreGState(outputContext)
}
// Output image is ready.
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
}
|
mit
|
24932b1069b92c66de7f3ba4c0c2a367
| 38.025641 | 123 | 0.66382 | 5.045304 | false | false | false | false |
nestproject/Frank
|
Sources/Application.swift
|
1
|
1100
|
import Nest
import Inquiline
class Application {
var routes: [Route] = []
func call(_ request: RequestType) -> ResponseType {
let routes = self.routes.flatMap { route -> (String, Route.Handler)? in
if let match = route.match(request) {
return (route.method, match)
}
return nil
}
let route = routes.filter { method, _ in method == request.method }.first
if let (_, handler) = route {
return handler().asResponse()
}
if !routes.isEmpty {
return Response(.methodNotAllowed)
}
return Response(.notFound)
}
/// Register a route for the given method and path
func route(_ method: String, _ path: String, _ closure: @escaping (RequestType) -> ResponseConvertible) {
route(method) { request in
if path == request.path {
return { closure(request) }
}
return nil
}
}
/// Register a route using a matcher closure
func route(_ method: String, _ match: @escaping (RequestType) -> Route.Handler?) {
let route = Route(method: method, match: match)
routes.append(route)
}
}
|
bsd-2-clause
|
476e93c404f24254aeece82b89cc64ca
| 22.913043 | 107 | 0.621818 | 4.104478 | false | false | false | false |
tj---/ServiceHealth
|
HealthStatus/SettingsViewHelper.swift
|
1
|
2633
|
//
// ViewHelper.swift
// ServiceHealth
//
// Created by Trilok Jain on 12/15/14.
// Copyright (c) 2014 Trilok Jain. All rights reserved.
//
import Foundation
import Cocoa
class SettingsViewHelper: ViewHelper
{
var settFetcher: SettingsFetcher
init(cView: NSView, headingView: NSTextField, settFetcher: SettingsFetcher)
{
self.settFetcher = settFetcher
super.init(cView: cView, hView: headingView)
}
func formSettingsPane()
{
// 1. Set the Heading
self.heading.stringValue = Resources.getLString(Resources.settings_heading)
var currSettings = settFetcher.settings
var curr = Resources.y_max - Resources.std_height
// 2. Set the Launch on Startup setting
formCheckBox(0, y: curr, w: Resources.x_max, h: Resources.std_height, title: Resources.getLString(Resources.launch_on_startup), selector: "updateLaunchSettings:", enabled: AvailabilityUtil.isStartupLaunchEnabled())
// 3. Set the services to receive updates from
if(currSettings.providers.isEmpty)
{
// 3.a Set the Loading message
formTextView(0, y: Resources.y_max - Resources.std_height, w: Resources.x_max, h: Resources.std_height, text: Resources.getLString(Resources.res_loading))
}
else
{
// 3.b Set the available services and their subscription status
curr = curr - Resources.std_height
formTextView(0, y: curr, w: Resources.x_max, h: Resources.std_height, text: Resources.getLString(Resources.sel_services_updt), bgColor: NSColor(red: 0.92, green: 1.0, blue: 1.0, alpha:1.0))
for index in 0...(currSettings.providers.count - 1)
{
formCheckBox(0, y: curr - (index + 1)*Resources.std_height, w: 120, h: Resources.std_height, title:(currSettings.providers[index].serviceName),
selector: "updateSettings:", enabled: currSettings.providers[index].enabled)
}
}
}
@objc func updateLaunchSettings(sender: NSButton)
{
AvailabilityUtil.launchOnStartup(sender.state == 0 ? false : true)
}
// Right now, a save is attempted on each update to the checkBox, however, that should not be the case
@objc func updateSettings(sender: NSButton)
{
for provider in settFetcher.settings.providers
{
if(provider.serviceName == sender.title)
{
provider.enabled = sender.state == 0 ? false : true
}
}
// Now persist the updated values
settFetcher.writePreferences()
}
}
|
mit
|
1e7bc18d6864483d5f251f5d050c5522
| 39.507692 | 222 | 0.639575 | 4.038344 | false | false | false | false |
laurentVeliscek/AudioKit
|
AudioKit/Common/Playgrounds/Basics.playground/Pages/Stereo Operation.xcplaygroundpage/Contents.swift
|
1
|
874
|
//: ## Stereo Operation
//: ### This is an example of building a stereo sound generator.
import XCPlayground
import AudioKit
let generator = AKOperationGenerator(numberOfChannels: 2) { _ in
let slowSine = round(AKOperation.sineWave(frequency: 1) * 12) / 12
let vibrato = slowSine.scale(minimum: -1200, maximum: 1200)
let fastSine = AKOperation.sineWave(frequency: 10)
let volume = fastSine.scale(minimum: 0, maximum: 0.5)
let leftOutput = AKOperation.sineWave(frequency: 440 + vibrato,
amplitude: volume)
let rightOutput = AKOperation.sineWave(frequency: 220 + vibrato,
amplitude: volume)
return [leftOutput, rightOutput]
}
AudioKit.output = generator
AudioKit.start()
generator.start()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
|
mit
|
35d507222eb951d047756a2bde73bbf6
| 32.615385 | 71 | 0.667048 | 4.482051 | false | false | false | false |
klundberg/swift-corelibs-foundation
|
TestFoundation/TestNSNotificationQueue.swift
|
1
|
12315
|
// 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 DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSNotificationQueue : XCTestCase {
static var allTests : [(String, (TestNSNotificationQueue) -> () throws -> Void)] {
return [
("test_defaultQueue", test_defaultQueue),
("test_postNowToDefaultQueueWithoutCoalescing", test_postNowToDefaultQueueWithoutCoalescing),
("test_postNowToDefaultQueueWithCoalescing", test_postNowToDefaultQueueWithCoalescing),
("test_postNowToCustomQueue", test_postNowToCustomQueue),
("test_postNowForDefaultRunLoopMode", test_postNowForDefaultRunLoopMode),
// ("test_notificationQueueLifecycle", test_notificationQueueLifecycle),
("test_postAsapToDefaultQueue", test_postAsapToDefaultQueue),
("test_postAsapToDefaultQueueWithCoalescingOnNameAndSender", test_postAsapToDefaultQueueWithCoalescingOnNameAndSender),
("test_postAsapToDefaultQueueWithCoalescingOnNameOrSender", test_postAsapToDefaultQueueWithCoalescingOnNameOrSender),
("test_postIdleToDefaultQueue", test_postIdleToDefaultQueue),
]
}
func test_defaultQueue() {
let defaultQueue1 = NotificationQueue.defaultQueue()
XCTAssertNotNil(defaultQueue1)
let defaultQueue2 = NotificationQueue.defaultQueue()
XCTAssertEqual(defaultQueue1, defaultQueue2)
executeInBackgroundThread() {
let defaultQueueForBackgroundThread = NotificationQueue.defaultQueue()
XCTAssertNotNil(defaultQueueForBackgroundThread)
XCTAssertEqual(defaultQueueForBackgroundThread, NotificationQueue.defaultQueue())
XCTAssertNotEqual(defaultQueueForBackgroundThread, defaultQueue1)
}
}
func test_postNowToDefaultQueueWithoutCoalescing() {
let notificationName = Notification.Name(rawValue: "test_postNowWithoutCoalescing")
let dummyObject = NSObject()
let notification = Notification(name: notificationName, object: dummyObject)
var numberOfCalls = 0
let obs = NotificationCenter.defaultCenter().addObserverForName(notificationName, object: dummyObject, queue: nil) { notification in
numberOfCalls += 1
}
let queue = NotificationQueue.defaultQueue()
queue.enqueueNotification(notification, postingStyle: .postNow)
XCTAssertEqual(numberOfCalls, 1)
NotificationCenter.defaultCenter().removeObserver(obs)
}
func test_postNowToDefaultQueueWithCoalescing() {
let notificationName = Notification.Name(rawValue: "test_postNowToDefaultQueueWithCoalescingOnName")
let dummyObject = NSObject()
let notification = Notification(name: notificationName, object: dummyObject)
var numberOfCalls = 0
let obs = NotificationCenter.defaultCenter().addObserverForName(notificationName, object: dummyObject, queue: nil) { notification in
numberOfCalls += 1
}
let queue = NotificationQueue.defaultQueue()
queue.enqueueNotification(notification, postingStyle: .postNow)
queue.enqueueNotification(notification, postingStyle: .postNow)
queue.enqueueNotification(notification, postingStyle: .postNow)
// Coalescing doesn't work for the NSPostingStyle.PostNow. That is why we expect 3 calls here
XCTAssertEqual(numberOfCalls, 3)
NotificationCenter.defaultCenter().removeObserver(obs)
}
func test_postNowToCustomQueue() {
let notificationName = Notification.Name(rawValue: "test_postNowToCustomQueue")
let dummyObject = NSObject()
let notification = Notification(name: notificationName, object: dummyObject)
var numberOfCalls = 0
let notificationCenter = NotificationCenter()
let obs = notificationCenter.addObserverForName(notificationName, object: dummyObject, queue: nil) { notification in
numberOfCalls += 1
}
let notificationQueue = NotificationQueue(notificationCenter: notificationCenter)
notificationQueue.enqueueNotification(notification, postingStyle: .postNow)
XCTAssertEqual(numberOfCalls, 1)
NotificationCenter.defaultCenter().removeObserver(obs)
}
func test_postNowForDefaultRunLoopMode() {
let notificationName = Notification.Name(rawValue: "test_postNowToDefaultQueueWithCoalescingOnName")
let dummyObject = NSObject()
let notification = Notification(name: notificationName, object: dummyObject)
var numberOfCalls = 0
let obs = NotificationCenter.defaultCenter().addObserverForName(notificationName, object: dummyObject, queue: nil) { notification in
numberOfCalls += 1
}
let queue = NotificationQueue.defaultQueue()
let runLoop = RunLoop.current()
let endDate = Date(timeInterval: TimeInterval(0.05), since: Date())
let dummyTimer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: false) { _ in
guard let runLoopMode = runLoop.currentMode else {
return
}
// post 2 notifications for the NSDefaultRunLoopMode mode
queue.enqueueNotification(notification, postingStyle: .postNow, coalesceMask: [], forModes: [runLoopMode])
queue.enqueueNotification(notification, postingStyle: .postNow)
// here we post notification for the NSRunLoopCommonModes. It shouldn't have any affect, because the timer is scheduled in NSDefaultRunLoopMode.
// The notification queue will only post the notification to its notification center if the run loop is in one of the modes provided in the array.
queue.enqueueNotification(notification, postingStyle: .postNow, coalesceMask: [], forModes: [.commonModes])
}
runLoop.add(dummyTimer, forMode: .defaultRunLoopMode)
let _ = runLoop.run(mode: .defaultRunLoopMode, before: endDate)
XCTAssertEqual(numberOfCalls, 2)
NotificationCenter.defaultCenter().removeObserver(obs)
}
func test_postAsapToDefaultQueue() {
let notificationName = Notification.Name(rawValue: "test_postAsapToDefaultQueue")
let dummyObject = NSObject()
let notification = Notification(name: notificationName, object: dummyObject)
var numberOfCalls = 0
let obs = NotificationCenter.defaultCenter().addObserverForName(notificationName, object: dummyObject, queue: nil) { notification in
numberOfCalls += 1
}
let queue = NotificationQueue.defaultQueue()
queue.enqueueNotification(notification, postingStyle: .postASAP)
scheduleTimer(withInterval: 0.001) // run timer trigger the notifications
XCTAssertEqual(numberOfCalls, 1)
NotificationCenter.defaultCenter().removeObserver(obs)
}
func test_postAsapToDefaultQueueWithCoalescingOnNameAndSender() {
// Check coalescing on name and object
let notificationName = Notification.Name(rawValue: "test_postAsapToDefaultQueueWithCoalescingOnNameAndSender")
let notification = Notification(name: notificationName, object: NSObject())
var numberOfCalls = 0
let obs = NotificationCenter.defaultCenter().addObserverForName(notificationName, object: notification.object, queue: nil) { notification in
numberOfCalls += 1
}
let queue = NotificationQueue.defaultQueue()
queue.enqueueNotification(notification, postingStyle: .postASAP)
queue.enqueueNotification(notification, postingStyle: .postASAP)
queue.enqueueNotification(notification, postingStyle: .postASAP)
scheduleTimer(withInterval: 0.001)
XCTAssertEqual(numberOfCalls, 1)
NotificationCenter.defaultCenter().removeObserver(obs)
}
func test_postAsapToDefaultQueueWithCoalescingOnNameOrSender() {
// Check coalescing on name or sender
let notificationName = Notification.Name(rawValue: "test_postAsapToDefaultQueueWithCoalescingOnNameOrSender")
let notification1 = Notification(name: notificationName, object: NSObject())
var numberOfNameCoalescingCalls = 0
let obs1 = NotificationCenter.defaultCenter().addObserverForName(notificationName, object: notification1.object, queue: nil) { notification in
numberOfNameCoalescingCalls += 1
}
let notification2 = Notification(name: notificationName, object: NSObject())
var numberOfObjectCoalescingCalls = 0
let obs2 = NotificationCenter.defaultCenter().addObserverForName(notificationName, object: notification2.object, queue: nil) { notification in
numberOfObjectCoalescingCalls += 1
}
let queue = NotificationQueue.defaultQueue()
// #1
queue.enqueueNotification(notification1, postingStyle: .postASAP, coalesceMask: .CoalescingOnName, forModes: nil)
// #2
queue.enqueueNotification(notification2, postingStyle: .postASAP, coalesceMask: .CoalescingOnSender, forModes: nil)
// #3, coalesce with 1 & 2
queue.enqueueNotification(notification1, postingStyle: .postASAP, coalesceMask: .CoalescingOnName, forModes: nil)
// #4, coalesce with #3
queue.enqueueNotification(notification2, postingStyle: .postASAP, coalesceMask: .CoalescingOnName, forModes: nil)
// #5
queue.enqueueNotification(notification1, postingStyle: .postASAP, coalesceMask: .CoalescingOnSender, forModes: nil)
scheduleTimer(withInterval: 0.001)
// check that we received notifications #4 and #5
XCTAssertEqual(numberOfNameCoalescingCalls, 1)
XCTAssertEqual(numberOfObjectCoalescingCalls, 1)
NotificationCenter.defaultCenter().removeObserver(obs1)
NotificationCenter.defaultCenter().removeObserver(obs2)
}
func test_postIdleToDefaultQueue() {
let notificationName = Notification.Name(rawValue: "test_postIdleToDefaultQueue")
let dummyObject = NSObject()
let notification = Notification(name: notificationName, object: dummyObject)
var numberOfCalls = 0
let obs = NotificationCenter.defaultCenter().addObserverForName(notificationName, object: dummyObject, queue: nil) { notification in
numberOfCalls += 1
}
NotificationQueue.defaultQueue().enqueueNotification(notification, postingStyle: .postWhenIdle)
// add a timer to wakeup the runloop, process the timer and call the observer awaiting for any input sources/timers
scheduleTimer(withInterval: 0.001)
XCTAssertEqual(numberOfCalls, 1)
NotificationCenter.defaultCenter().removeObserver(obs)
}
func test_notificationQueueLifecycle() {
// check that notificationqueue is associated with current thread. when the thread is destroyed, the queue should be deallocated as well
weak var notificationQueue: NotificationQueue?
self.executeInBackgroundThread() {
notificationQueue = NotificationQueue(notificationCenter: NotificationCenter())
XCTAssertNotNil(notificationQueue)
}
XCTAssertNil(notificationQueue)
}
// MARK: Private
private func scheduleTimer(withInterval interval: TimeInterval) {
let e = expectation(description: "Timer")
let dummyTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { _ in
e.fulfill()
}
RunLoop.current().add(dummyTimer, forMode: .defaultRunLoopMode)
waitForExpectations(timeout: 0.1)
}
private func executeInBackgroundThread(_ operation: () -> Void) {
let e = expectation(description: "Background Execution")
let bgThread = Thread() {
operation()
e.fulfill()
}
bgThread.start()
waitForExpectations(timeout: 0.2)
}
}
|
apache-2.0
|
17359f87dcbdb69119f9b9a72a1b8e11
| 49.679012 | 158 | 0.710922 | 5.331169 | false | true | false | false |
jianghongbing/APIReferenceDemo
|
UIKit/UITextField/UITextField/CustomTextField.swift
|
1
|
2063
|
//
// CustomTextField.swift
// UITextField
//
// Created by pantosoft on 2017/8/8.
// Copyright © 2017年 jianghongbing. All rights reserved.
//
import UIKit
class CustomTextField: UITextField {
//1.设置borderRect
override func borderRect(forBounds bounds: CGRect) -> CGRect {
// let rect = super.borderRect(forBounds: bounds)
// print(#line, #function, rect)
// return rect
return CGRect(x: bounds.minX + 10, y: bounds.minY, width: bounds.width - 20, height: bounds.height)
}
//2.设置textRect
override func textRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.textRect(forBounds: bounds)
return rect
}
//3.设置placeholderRect
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.placeholderRect(forBounds: bounds)
return rect
}
//4.设置leftViewRect
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.leftViewRect(forBounds: bounds)
return rect
}
//5.设置rightViewRect
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.rightViewRect(forBounds: bounds)
return rect
}
//6.设置clearButtonRect
override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.clearButtonRect(forBounds: bounds)
return rect
}
//7.设置编辑区域
override func editingRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.editingRect(forBounds: bounds)
return rect
}
//8.设置textField的placeholder时,会触发该方法
override func drawText(in rect: CGRect) {
print(#line, #function, rect)
super.drawText(in: rect)
}
//9.直接设置textField的text而不是通过键盘输入的时候,会触发该方法
override func drawPlaceholder(in rect: CGRect) {
print(#line, #function, rect)
super.drawPlaceholder(in: rect)
}
}
|
mit
|
41d89bfc40d14faa760d7e8abbc51278
| 27.794118 | 107 | 0.643514 | 4.183761 | false | false | false | false |
mtransitapps/mtransit-for-ios
|
MonTransit/Source/Utils/Zip/ZipLoader.swift
|
1
|
1283
|
//
// ZipLoader.swift
// MonTransit
//
// Created by Thibault on 16-02-06.
// Copyright © 2016 Thibault. All rights reserved.
//
import UIKit
import zipzap
class ZipLoader {
private var mArchive:ZZArchive!
init(iZipFilePath:String) {
let wUrl = NSURL(fileURLWithPath: File.getDocumentTempFolderPath() + "\(iZipFilePath).zip")
mArchive = try! ZZArchive(URL: wUrl)
}
deinit {
mArchive = nil
}
func getDataFileFromZip(iFileName:String, iDocumentName:String, iSaveExtractedFile:Bool = false) -> String{
for wFile in mArchive.entries{
if wFile.fileName == "\(iDocumentName)/\(iFileName)"{
var wData:NSData
wData = try! wFile.newData()
let wDataString = NSString(data: wData, encoding:NSUTF8StringEncoding) as! String
if(iSaveExtractedFile){
File.createDirectory("\(iDocumentName)")
File.save(File.getDocumentFilePath() + "\(iDocumentName)/\(iFileName)", content: wDataString)
}
return NSString(data: wData, encoding:NSUTF8StringEncoding) as! String
}
}
return ""
}
}
|
apache-2.0
|
ad6f7fa52d66d6a0b34e9fa51500b5e2
| 26.869565 | 113 | 0.567863 | 4.405498 | false | false | false | false |
exponent/exponent
|
ios/vendored/sdk42/lottie-react-native/src/ios/LottieReactNative/ContainerView.swift
|
2
|
4384
|
import Lottie
class ContainerView: ABI42_0_0RCTView {
private var speed: CGFloat = 0.0
private var progress: CGFloat = 0.0
private var loop: LottieLoopMode = .playOnce
private var sourceJson: String = ""
private var resizeMode: String = ""
private var sourceName: String = ""
private var colorFilters: [NSDictionary] = []
@objc var onAnimationFinish: ABI42_0_0RCTBubblingEventBlock?
var animationView: AnimationView?
@objc func setSpeed(_ newSpeed: CGFloat) {
speed = newSpeed
if (newSpeed != 0.0) {
animationView?.animationSpeed = newSpeed
if (!(animationView?.isAnimationPlaying ?? true)) {
animationView?.play()
}
} else if (animationView?.isAnimationPlaying ?? false) {
animationView?.pause()
}
}
@objc func setProgress(_ newProgress: CGFloat) {
progress = newProgress
animationView?.currentProgress = progress
}
override func abi42_0_0ReactSetFrame(_ frame: CGRect) {
super.abi42_0_0ReactSetFrame(frame)
animationView?.abi42_0_0ReactSetFrame(frame)
}
@objc func setLoop(_ isLooping: Bool) {
loop = isLooping ? .loop : .playOnce
animationView?.loopMode = loop
}
@objc func setSourceJson(_ newSourceJson: String) {
sourceJson = newSourceJson
guard let data = sourceJson.data(using: String.Encoding.utf8),
let animation = try? JSONDecoder().decode(Animation.self, from: data) else {
if (ABI42_0_0RCT_DEBUG == 1) {
print("Unable to create the lottie animation object from the JSON source")
}
return
}
let starAnimationView = AnimationView()
starAnimationView.animation = animation
replaceAnimationView(next: starAnimationView)
}
@objc func setSourceName(_ newSourceName: String) {
if (newSourceName == sourceName) {
return
}
sourceName = newSourceName
let starAnimationView = AnimationView(name: sourceName)
replaceAnimationView(next: starAnimationView)
}
@objc func setResizeMode(_ resizeMode: String) {
switch (resizeMode) {
case "cover":
animationView?.contentMode = .scaleAspectFill
case "contain":
animationView?.contentMode = .scaleAspectFit
case "center":
animationView?.contentMode = .center
default: break
}
}
@objc func setColorFilters(_ newColorFilters: [NSDictionary]) {
colorFilters = newColorFilters
applyProperties()
}
func play(fromFrame: AnimationFrameTime? = nil, toFrame: AnimationFrameTime, completion: LottieCompletionBlock? = nil) {
animationView?.backgroundBehavior = .pauseAndRestore
animationView?.play(fromFrame: fromFrame, toFrame: toFrame, loopMode: self.loop, completion: completion);
}
func play(completion: LottieCompletionBlock? = nil) {
animationView?.backgroundBehavior = .pauseAndRestore
animationView?.play(completion: completion)
}
func reset() {
animationView?.currentProgress = 0;
animationView?.pause()
}
func pause() {
animationView?.pause()
}
func resume() {
play()
}
// MARK: Private
func replaceAnimationView(next: AnimationView) {
animationView?.removeFromSuperview()
let contentMode = animationView?.contentMode ?? .scaleAspectFit
animationView = next
addSubview(next)
animationView?.contentMode = contentMode
animationView?.abi42_0_0ReactSetFrame(frame)
applyProperties()
}
func applyProperties() {
animationView?.currentProgress = progress
animationView?.animationSpeed = speed
animationView?.loopMode = loop
if (colorFilters.count > 0) {
for filter in colorFilters {
let keypath: String = "\(filter.value(forKey: "keypath") as! String).**.Color"
let fillKeypath = AnimationKeypath(keypath: keypath)
let colorFilterValueProvider = ColorValueProvider(hexStringToColor(hex: filter.value(forKey: "color") as! String))
animationView?.setValueProvider(colorFilterValueProvider, keypath: fillKeypath)
}
}
}
}
|
bsd-3-clause
|
4e31447db03005d57bf6496fb2620250
| 31.716418 | 130 | 0.631843 | 4.892857 | false | false | false | false |
EasySwift/EasySwift
|
Carthage/Checkouts/IQKeyboardManager/Demo/Swift_Demo/ViewController/SettingsViewController.swift
|
2
|
26232
|
//
// SettingsViewController.swift
// Demo
//
// Created by Iftekhar on 26/08/15.
// Copyright (c) 2015 Iftekhar. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
class SettingsViewController: UITableViewController, OptionsViewControllerDelegate, ColorPickerTextFieldDelegate {
let sectionTitles = ["UIKeyboard handling",
"IQToolbar handling",
"UIKeyboard appearance overriding",
"Resign first responder handling",
"UISound handling",
"IQKeyboardManager Debug"]
let keyboardManagerProperties = [["Enable", "Keyboard Distance From TextField", "Prevent Showing Bottom Blank Space"],
["Enable AutoToolbar","Toolbar Manage Behaviour","Should Toolbar Uses TextField TintColor","Should Show TextField Placeholder","Placeholder Font","Toolbar Tint Color","Toolbar Done BarButtonItem Image","Toolbar Done Button Text"],
["Override Keyboard Appearance","UIKeyboard Appearance"],
["Should Resign On Touch Outside"],
["Should Play Input Clicks"],
["Debugging logs in Console"]]
let keyboardManagerPropertyDetails = [["Enable/Disable IQKeyboardManager","Set keyboard distance from textField","Prevent to show blank space between UIKeyboard and View"],
["Automatic add the IQToolbar on UIKeyboard","AutoToolbar previous/next button managing behaviour","Uses textField's tintColor property for IQToolbar","Add the textField's placeholder text on IQToolbar","UIFont for IQToolbar placeholder text","Override toolbar tintColor property","Replace toolbar done button text with provided image","Override toolbar done button text"],
["Override the keyboardAppearance for all UITextField/UITextView","All the UITextField keyboardAppearance is set using this property"],
["Resigns Keyboard on touching outside of UITextField/View"],
["Plays inputClick sound on next/previous/done click"],
["Setting enableDebugging to YES/No to turn on/off debugging mode"]]
var selectedIndexPathForOptions : IndexPath?
@IBAction func doneAction (_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
/** UIKeyboard Handling */
func enableAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().enable = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 0), with: UITableViewRowAnimation.fade)
}
func keyboardDistanceFromTextFieldAction (_ sender: UIStepper) {
IQKeyboardManager.sharedManager().keyboardDistanceFromTextField = CGFloat(sender.value)
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: UITableViewRowAnimation.none)
}
func preventShowingBottomBlankSpaceAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 0), with: UITableViewRowAnimation.fade)
}
/** IQToolbar handling */
func enableAutoToolbarAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().enableAutoToolbar = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 1), with: UITableViewRowAnimation.fade)
}
func shouldToolbarUsesTextFieldTintColorAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor = sender.isOn
}
func shouldShowTextFieldPlaceholder (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 1), with: UITableViewRowAnimation.fade)
}
func toolbarDoneBarButtonItemImage (_ sender: UISwitch) {
if sender.isOn {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage = UIImage(named:"IQButtonBarArrowDown")
} else {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage = nil
}
self.tableView.reloadSections(IndexSet(integer: 1), with: UITableViewRowAnimation.fade)
}
/** "Keyboard appearance overriding */
func overrideKeyboardAppearanceAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().overrideKeyboardAppearance = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 2), with: UITableViewRowAnimation.fade)
}
/** Resign first responder handling */
func shouldResignOnTouchOutsideAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = sender.isOn
}
/** Sound handling */
func shouldPlayInputClicksAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldPlayInputClicks = sender.isOn
}
/** Debugging */
func enableDebugging (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().enableDebugging = sender.isOn
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section)
{
case 0:
if IQKeyboardManager.sharedManager().enable == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 1:
if IQKeyboardManager.sharedManager().enableAutoToolbar == false {
return 1
} else if IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder == false {
return 4
} else {
let properties = keyboardManagerProperties[section]
return properties.count
}
case 2:
if IQKeyboardManager.sharedManager().overrideKeyboardAppearance == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 3,4,5:
let properties = keyboardManagerProperties[section]
return properties.count
default:
return 0
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch ((indexPath as NSIndexPath).section) {
case 0:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().enable
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableAction(_:)), for: UIControlEvents.valueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "StepperTableViewCell") as! StepperTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.stepper.value = Double(IQKeyboardManager.sharedManager().keyboardDistanceFromTextField)
cell.labelStepperValue.text = NSString(format: "%.0f", IQKeyboardManager.sharedManager().keyboardDistanceFromTextField) as String
cell.stepper.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.stepper.addTarget(self, action: #selector(self.keyboardDistanceFromTextFieldAction(_:)), for: UIControlEvents.valueChanged)
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.preventShowingBottomBlankSpaceAction(_:)), for: UIControlEvents.valueChanged)
return cell
default:
break
}
case 1:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().enableAutoToolbar
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableAutoToolbarAction(_:)), for: UIControlEvents.valueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldToolbarUsesTextFieldTintColorAction(_:)), for: UIControlEvents.valueChanged)
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldShowTextFieldPlaceholder(_:)), for: UIControlEvents.valueChanged)
return cell
case 4:
let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
case 5:
let cell = tableView.dequeueReusableCell(withIdentifier: "ColorTableViewCell") as! ColorTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.colorPickerTextField.selectedColor = IQKeyboardManager.sharedManager().toolbarTintColor
cell.colorPickerTextField.tag = 15
cell.colorPickerTextField.delegate = self
return cell
case 6:
let cell = tableView.dequeueReusableCell(withIdentifier: "ImageSwitchTableViewCell") as! ImageSwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.arrowImageView.image = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage != nil
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.toolbarDoneBarButtonItemImage(_:)), for: UIControlEvents.valueChanged)
return cell
case 7:
let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldTableViewCell") as! TextFieldTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.textField.text = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText
cell.textField.tag = 17
cell.textField.delegate = self
return cell
default:
break
}
case 2:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().overrideKeyboardAppearance
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.overrideKeyboardAppearanceAction(_:)), for: UIControlEvents.valueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
default:
break
}
case 3:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().shouldResignOnTouchOutside
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldResignOnTouchOutsideAction(_:)), for: UIControlEvents.valueChanged)
return cell
default:
break
}
case 4:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().shouldPlayInputClicks
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldPlayInputClicksAction(_:)), for: UIControlEvents.valueChanged)
return cell
default:
break
}
case 5:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().enableDebugging
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableDebugging(_:)), for: UIControlEvents.valueChanged)
return cell
default:
break
}
default:
break
}
return UITableViewCell()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
private func colorPickerTextField(_ textField: ColorPickerTextField, selectedColorAttributes colorAttributes: [String : AnyObject]) {
if textField.tag == 15 {
let color = colorAttributes["color"] as! UIColor
if color.isEqual(UIColor.clear) {
IQKeyboardManager.sharedManager().toolbarTintColor = nil
} else {
IQKeyboardManager.sharedManager().toolbarTintColor = color
}
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.tag == 17 {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText = textField.text?.characters.count != 0 ? textField.text : nil
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
if identifier == "OptionsViewController" {
let controller = segue.destination as! OptionsViewController
controller.delegate = self
let cell = sender as! UITableViewCell
selectedIndexPathForOptions = self.tableView.indexPath(for: cell)
if let selectedIndexPath = selectedIndexPathForOptions {
if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 1 {
controller.title = "Toolbar Manage Behaviour"
controller.options = ["IQAutoToolbar By Subviews","IQAutoToolbar By Tag","IQAutoToolbar By Position"]
controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue
} else if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 4 {
controller.title = "Fonts"
controller.options = ["Bold System Font","Italic system font","Regular"]
controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue
let fonts = [UIFont.boldSystemFont(ofSize: 12),UIFont.italicSystemFont(ofSize: 12),UIFont.systemFont(ofSize: 12)]
if let placeholderFont = IQKeyboardManager.sharedManager().placeholderFont {
if let index = fonts.index(of: placeholderFont) {
controller.selectedIndex = index
}
}
} else if (selectedIndexPath as NSIndexPath).section == 2 && (selectedIndexPath as NSIndexPath).row == 1 {
controller.title = "Keyboard Appearance"
controller.options = ["UIKeyboardAppearance Default","UIKeyboardAppearance Dark","UIKeyboardAppearance Light"]
controller.selectedIndex = IQKeyboardManager.sharedManager().keyboardAppearance.hashValue
}
}
}
}
}
func optionsViewController(_ controller: OptionsViewController, index: NSInteger) {
if let selectedIndexPath = selectedIndexPathForOptions {
if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 1 {
IQKeyboardManager.sharedManager().toolbarManageBehaviour = IQAutoToolbarManageBehaviour(rawValue: index)!
} else if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 4 {
let fonts = [UIFont.boldSystemFont(ofSize: 12),UIFont.italicSystemFont(ofSize: 12),UIFont.systemFont(ofSize: 12)]
IQKeyboardManager.sharedManager().placeholderFont = fonts[index]
} else if (selectedIndexPath as NSIndexPath).section == 2 && (selectedIndexPath as NSIndexPath).row == 1 {
IQKeyboardManager.sharedManager().keyboardAppearance = UIKeyboardAppearance(rawValue: index)!
}
}
}
}
|
apache-2.0
|
e7d4c5a7093242f1e913ebab46b9b94b
| 46.781421 | 377 | 0.610933 | 7.032708 | false | false | false | false |
Lclmyname/BookReader_Swift
|
BookStore/ViewController/StoreViewController.swift
|
1
|
5138
|
//
// StoreViewController.swift
// BookStore
//
// Created by apple on 16/9/30.
// Copyright © 2016年 刘朝龙. All rights reserved.
//
import UIKit
enum StoreType:Int {
case search = 1, category, charts, read
func simpleDescription() -> String {
switch self {
case .search:
return "搜索"
case .category:
return "分类"
case .charts:
return "排行榜"
case .read:
return "最近阅读"
}
}
}
class StoreViewController: BaseViewController {
func initUI() -> Swift.Void {
/// 搜索
let searchBtn = UIButton(type: .custom)
searchBtn.setBackgroundImage(UIImage.init(named: "book_cell_icon"), for: .normal)
searchBtn.setTitle(StoreType.search.simpleDescription(), for: .normal)
searchBtn.setTitleColor(textColor, for: .normal)
searchBtn.titleLabel?.font = subtitleFont
searchBtn.tag = StoreType.search.rawValue
searchBtn.addTarget(self, action: #selector(turnNextVC(_:)), for: .touchUpInside)
/// 分类
let cateBtn = UIButton(type: .custom)
cateBtn.setBackgroundImage(UIImage.init(named: "book_cell_icon"), for: .normal)
cateBtn.setTitle(StoreType.category.simpleDescription(), for: .normal)
cateBtn.setTitleColor(textColor, for: .normal)
cateBtn.titleLabel?.font = subtitleFont
cateBtn.tag = StoreType.category.rawValue
cateBtn.addTarget(self, action: #selector(turnNextVC(_:)), for: .touchUpInside)
/// 排行
let chartsBtn = UIButton(type: .custom)
chartsBtn.setBackgroundImage(UIImage.init(named: "book_cell_icon"), for: .normal)
chartsBtn.setTitle(StoreType.charts.simpleDescription(), for: .normal)
chartsBtn.setTitleColor(textColor, for: .normal)
chartsBtn.titleLabel?.font = subtitleFont
chartsBtn.tag = StoreType.charts.rawValue
chartsBtn.addTarget(self, action: #selector(turnNextVC(_:)), for: .touchUpInside)
/// 最近阅读
let readBtn = UIButton(type: .custom)
readBtn.setBackgroundImage(UIImage.init(named: "book_cell_icon"), for: .normal)
readBtn.setTitle(StoreType.read.simpleDescription(), for: .normal)
readBtn.setTitleColor(textColor, for: .normal)
readBtn.titleLabel?.font = subtitleFont
readBtn.tag = StoreType.read.rawValue
readBtn.addTarget(self, action: #selector(turnNextVC(_:)), for: .touchUpInside)
self.view.addSubview(searchBtn)
self.view.addSubview(cateBtn)
self.view.addSubview(chartsBtn)
self.view.addSubview(readBtn)
searchBtn.snp.makeConstraints { (make) in
make.top.equalTo(self.view).offset(51+64)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
}
cateBtn.snp.makeConstraints { (make) in
make.top.equalTo(searchBtn.snp.bottom).offset(30)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
// make.edges.equalToSuperview()
}
chartsBtn.snp.makeConstraints { (make) in
make.top.equalTo(cateBtn.snp.bottom).offset(30)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
}
readBtn.snp.makeConstraints { (make) in
make.top.equalTo(chartsBtn.snp.bottom).offset(30)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "书库"
initUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func turnNextVC(_ sender:AnyObject) -> Swift.Void {
let btn = sender as! UIButton
var vc:BaseViewController!
switch btn.tag {
case 1:
vc = storyboard?.instantiateViewController(withIdentifier: "SearchViewControllerID") as! SearchViewController
case 2:
vc = storyboard?.instantiateViewController(withIdentifier: "CategoryViewControllerID") as! CategoryViewController
case 3, 4:
let bookList = storyboard?.instantiateViewController(withIdentifier: "BookListViewControllerID") as! BookListViewController
bookList.type = BookCategory(rawValue: btn.tag)!
vc = bookList
default:
break
}
/// 跳转
self.navigationController?.pushViewController(vc, animated: 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.
}
*/
}
|
mit
|
4fe290c5e8d6c9c29a264d85f2ddf3db
| 35.021277 | 135 | 0.623942 | 4.482789 | false | false | false | false |
BlenderSleuth/Unlokit
|
Unlokit/Nodes/ReplayButtonNode.swift
|
1
|
1235
|
//
// ReplayButton.swift
// Unlokit
//
// Created by Ben Sutherland on 23/1/17.
// Copyright © 2017 blendersleuthdev. All rights reserved.
//
import SpriteKit
class ReplayButtonNode: SKSpriteNode {
var pressed = false
weak var levelController: LevelController!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Allow touch events
isUserInteractionEnabled = true
}
func press() {
pressed = !pressed
if pressed {
removeAllActions()
let color = SKAction.colorize(with: .red, colorBlendFactor: 1, duration: 0.2)
let wiggle = SKAction(named: "Wiggle")!
let action = SKAction.sequence([color, wiggle])
run(action)
} else {
removeAllActions()
let action = SKAction.group([SKAction(named: "StopWiggle")!,
SKAction.colorize(with: .red, colorBlendFactor: 0, duration: 0.2)])
run(action)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
press()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
press()
let location = touch.location(in: parent!)
if frame.contains(location) {
levelController.startNewGame()
}
}
}
}
|
gpl-3.0
|
e11b056667319db3f07e03f745daf2b2
| 22.283019 | 99 | 0.666937 | 3.545977 | false | false | false | false |
BlenderSleuth/Unlokit
|
Unlokit/Data/Level.swift
|
1
|
1365
|
//
// Level.swift
// Unlokit
//
// Created by Ben Sutherland on 4/2/17.
// Copyright © 2017 blendersleuthdev. All rights reserved.
//
import UIKit
class Level: NSObject, NSCoding {
let number: Int
var stageNumber: Int
var available: Bool
var isCompleted: Bool
var isSecret: Bool
var isTutorial: Bool
init(number: Int, stageNumber: Int, available: Bool, isCompleted: Bool = false, isTutorial: Bool = false) {
self.number = number
self.available = available
self.isCompleted = isCompleted
self.stageNumber = stageNumber
self.isTutorial = isTutorial
// Not to be encoded
self.isSecret = false
}
required convenience init?(coder aDecoder: NSCoder) {
// Decode properties
let number = aDecoder.decodeInteger(forKey: "number")
let stageNumber = aDecoder.decodeInteger(forKey: "stageNumber")
let available = aDecoder.decodeBool(forKey: "available")
let isCompleted = aDecoder.decodeBool(forKey: "isCompleted")
// Initialise with decoded properties
self.init(number: number, stageNumber: stageNumber, available: available, isCompleted: isCompleted)
}
func encode(with aCoder: NSCoder) {
// Encode properties
aCoder.encode(number, forKey: "number")
aCoder.encode(stageNumber, forKey: "stageNumber")
aCoder.encode(available, forKey: "available")
aCoder.encode(isCompleted, forKey: "isCompleted")
}
}
|
gpl-3.0
|
8978b423dd39f811a8850293a166a811
| 25.745098 | 108 | 0.730205 | 3.67655 | false | false | false | false |
developerY/Active-Learning-Swift-2.0_DEMO
|
ActiveLearningSwift2.playground/Pages/Collection Types.xcplaygroundpage/Contents.swift
|
3
|
14703
|
//: [Previous](@previous)
/*: Include a link to the Swift page in the text
Translated from [mengxiangyue](http://blog.csdn.net/mengxiangyue) by Google Tranranslate
*/
import UIKit
//: # Collections
//: **In Swift, the collection clearly know the type of value it can store, so if you insert a wrong type, an error.**
/*:
* ### Array: an ordered value stored
* ### Set: storage disorder unique value
* ### Dictionary: storage disorderly key-value key pairs
*/
var image = UIImage (named: "collectionTypes")
//: Mutability of Collections
// Use var, let distinguish whether a variable
//: ## Array
//:
//: ### Arrays are ordered lists of elements
//:
//: * The types of values that can be stored in an array must always be made clear either through
//: explicit type annotation or through type inference and does not have to be a base class type.
//: ----
//: * Arrays are type-safe and always clear about what they contain.
//: ----
//: * Arrays are value types, but Swift is smart about only copying when necessary to improve
//: performance.
//: ----
//: * Immutable arrays are immutable in terms of the array itself and the contents of the array.
//: This means you can't add/remove an element nor can you modify an element of an immutable
//: array.
//: ------------------------------------------------------------------------------------------------
//: Create an array of Strings
var someArray = Array<String>()
//: *Shorter, more common way to define an array of Strings*
var shorter: [String]
//: This is an array literal. Since all members are of type String, this will create a String array.
//:
//: If all members are ***not the same*** type (or cannot be inferred to a homogenized type) then you
//: would ***get a compiler error***.
["Eggs", "Milk"]
//: Let's create an array with some stuff in it. We'll use an explicit String type:
var commonPets: [String] = ["Cats", "Dogs"]
//: We can also let Swift infer the type of the Array based on the type of the initializer members.
//:
//: The folowing is an array of Strings
var shoppingList = ["Eggs", "Milk"]
//: ------------------------------------------------------------------------------------------------
//:
//: ### Accessing and modifying an Array
//:
//: We can get the number of elements
shoppingList.count
//: We can check to see if it's empty
if !shoppingList.isEmpty { "it's not empty" }
//: We can append to the end
shoppingList.append("Flour")
shoppingList.append("Baking Powder")
shoppingList.count
//: We can append another array of same type
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
shoppingList.count
//: We can get elements from the array by indexing them
shoppingList[0]
shoppingList[1]
//: We can modify an existing item
shoppingList[0] = "Six Eggs"
//: We can use a range operator to modify existing items. This operation modifies a range with
//: a target range. If the target range has more or fewer elements in it, the size of the array
//: will be adjusted.
//:
//: Here, we replace 3 items with only two, removing an item:
shoppingList[4...6] = ["Banannas", "Apples"]
shoppingList
//: Or we can replace two items with three, inserting a new item:
shoppingList[4..<6] = ["Limes", "Mint leaves", "Sugar"]
//: We can insert an item at a given index
shoppingList.insert("Maple Syrup", atIndex: 3)
//: We can remove the last element. During this, we can preserve the value of what was removed
//: into a stored value
let apples = shoppingList.removeLast()
//: or removeAtIndex
let eggs = shoppingList.removeAtIndex(0)
//: ***NOTE***
//: If you try to access or modify a value for an index that is outside of an array’s existing bounds, you will trigger a runtime error. However, you can check that an index is valid before using it, by comparing it to the array’s count property. Except when count is 0 (meaning the array is empty), the largest valid index in an array will always be count - 1, because arrays are indexed from zero.
//let bad = shoppingList.removeAtIndex(100)
//: ------------------------------------------------------------------------------------------------
//: ### Enumeration
//:
//: We can iterate over the the array using a for-in loop
for item in shoppingList
{
item
}
//: We can also use the the enumerate() method to return a tuple containing the index and value
//: for each element:
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
//: ------------------------------------------------------------------------------------------------
//: ### Creating and initializing an array
//:
//: Earlier, we saw how to declare an array of a given type. Here, we see how to declare an array
//: type and then assign it to a stored value, which gets its type by inference:
var someInts = [Int]()
//: Add the number '3' to the array
someInts.append(3)
someInts
//: We can assign it to an empty array, but we don't modify the type, since someInts is already
//: an Int[] type.
someInts = []
//: We can initialize an array and and fill it with default values
var threeDoubles = [Double](count: 3, repeatedValue: 3.3)
//: We can also use the Array initializer to fill it with default values. Note that we don't need to
//: specify type since it is inferred:
var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
//: If you store an array in a constant, it is considered "Immutable"
let immutableArray = ["a", "b"]
//: In terms of immutability, it's important to consider that the array and its contents are treated
//: separately. Therefore, you can change the contents of an immutable array, but you can't change
//: the array itself.
//:
//: We can't change the contents of an immutable array:
//:
//: immutableArray[0] = "b"
//:
//: Nor can we change the size or add an element, you will get a compiler error:
//:
//: immutableArray += "c"
//: ------------------------------------------------------------------------------------------------
//: Arrays are Value Types
//:
//: Arrays are value types that only copy when necessary, which is only when the array itself
//: changes (not the contents.)
//:
//: Here are three copies of an array:
var a = [1, 2, 3]
var b = a
var c = a
//: However, if we change the contents of one array (mutating it), then it is copied and becomes its
//: own unique entity:
a[0] = 42
b[0]
c[0]
//: The same is true if we mutate the array in other ways (mofify the array's size)...
b.append(4)
//: Now, we have three different arrays...
a
b
c
//: ## Set
//:
//: #### A set stores distinct values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once.
//: *Hash Values for Set Types A type must be hashable in order to be stored in a set—that is, the type must provide a way to compute a hash value for itself. A hash value is an Int value that is the same for all objects that compare equally, such that if a == b, it follows that a.hashValue == b.hashValue.*
//: Creating and Initializing an Empty Set
//: You can create an empty set of a certain type using initializer syntax:
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// adds a
letters.insert("a")
// empty
letters = []
//: The example below creates a set called favoriteGenres to store String values:
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
//: ### Accessing and Modifying a Set
print("I have \(favoriteGenres.count) favorite music genres.")
// check empty
if favoriteGenres.isEmpty {
print("As far as music goes, I'm not picky.")
} else {
print("I have particular music preferences.")
}
// insert
favoriteGenres.insert("Jazz")
// remove
let removedGenre = favoriteGenres.remove("Rock")
// contains
if favoriteGenres.contains("Jazz") {
print("I get up on the good foot.")
}
//: ### Iterating Over a Set
// even sort
for genre in favoriteGenres.sort() {
print("\(genre)")
}
//: ### Performing Set Operations
//:
//: You can efficiently perform fundamental set operations, such as combining two sets together, determining which values two sets have in common, or determining whether two sets contain all, some, or none of the same values.
//: *Fundamental Set Operations*
//: *The illustration below depicts two sets–a and b– with the results of various set operations represented by the shaded regions.*
image = UIImage(named: "SetOperations")
/*:
* Use the intersect(_:) method to create a new set with only the values common to both sets.
* Use the exclusiveOr(_:) method to create a new set with values in either set, but not both.
* Use the union(_:) method to create a new set with all of the values in both sets.
* Use the subtract(_:) method to create a new set with values not in the specified set.
*/
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
oddDigits.union(evenDigits).sort()
oddDigits.intersect(evenDigits).sort()
oddDigits.subtract(singleDigitPrimeNumbers).sort()
oddDigits.exclusiveOr(singleDigitPrimeNumbers).sort()
//: ### Set Membership and Equality
//: *The illustration below depicts three sets–a, b and c– with overlapping regions representing elements shared among sets. Set a is a superset of set b, because a contains all elements in b. Conversely, set b is a subset of set a, because all elements in b are also contained by a. Set b and set c are disjoint with one another, because they share no elements in common.*
image = UIImage(named: "setEulerDiagram")
/*:
* Use the “is equal” operator (==) to determine whether two sets contain all of the same values.
* Use the isSubsetOf(_:) method to determine whether all of the values of a set are contained in the specified set.
* Use the isSupersetOf(_:) method to determine whether a set contains all of the values in a specified set.
* Use the isStrictSubsetOf(_:) or isStrictSupersetOf(_:) methods to determine whether a set is a subset or superset, but not equal to, a specified set.
* Use the isDisjointWith(_:) method to determine whether two sets have any values in common.
*/
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]
houseAnimals.isSubsetOf(farmAnimals)
farmAnimals.isSupersetOf(houseAnimals)
farmAnimals.isDisjointWith(cityAnimals)
//: # Dictionaries
//: *A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary when you need to look up values based on their identifier, in much the same way that a real-world dictionary is used to look up the definition for a particular word.*
//: Notes:
//: * Dictionaries store multiple values of the same type, each associated with a key which acts as an identifier for that value within the dictionary.
//: * Dictionaries are type-safe and always clear about what they contain.
//: * The types of values that can be stored in a dictionary must always be made clear either through explicit type annotation or through type inference.
//: ------------------------------------------------------------------------------------------------
//: Creating a dictionary
//:
//: This is a Dictionary literal. They contain a comma-separated list of **key:value pairs**:
["TYO": "Tokyo", "DUB": "Dublin"]
// literal to define and initialize a Dictionary.
// This uses the syntactic sugar "[ KeyType: ValueType ]" to declare the dictionary.
var airports: [String : String] = ["TYO": "Tokyo", "DUB": "Dublin", "APL": "Apple Intl"]
// The declaration for airports above could also have been declared in this way:
var players: Dictionary<String, String> = ["Who" : "First", "What" : "Second"]
//inference works in our favor allowing us to avoid the type annotation:
let inferredDictionary = ["TYO": "Tokyo", "DUB": "Dublin"]
//: ------------------------------------------------------------------------------------------------
//: Accessing and modifying a Dictionary
//:
// get a value from the dictionary for the TYO airport:
airports["TYO"]
// chang the value
airports["TYO"] = "Tokyo Airport"
// update
airports.updateValue("Dublin Airport", forKey: "DUB")
airports
// removed
airports["APL"] = nil
let removedValue = airports.removeValueForKey("DUB")
//: ### Iterating over key/value pairs with a for-in loop, which uses a Tuple to hold the
//: key/value pair for each entry in the Dictionary:
for (airportCode, airportName) in airports
{
airportCode
airportName
}
// We can iterate over just the keys
for airportCode in airports.keys
{
airportCode
}
// We can iterate over jsut the values
for airportName in airports.values
{
airportName
}
// test empty
if airports.isEmpty {
print("The airports dictionary is empty.")
}
// get count
print("The airports dictionary contains \(airports.count) items.")
//: We can create an array from the keys or values
//:
//: Note that when doing this, the use of Array() is needed to convert the keys or values into
//: an array.
var airportCodes = [String](airports.keys)
var airportNames = [String](airports.values)
// do not use the old way
airportCodes = Array(airports.keys)
airportNames = Array(airports.values)
//: ------------------------------------------------------------------------------------------------
//: Creating an empty Dictionary
//:
//: Here, we create an empty Dictionary of Int keys and String values:
var namesOfIntegers = Dictionary<Int, String>()
// Let's set one of the values
namesOfIntegers[16] = "Sixteen"
// We can empty a dictionary using an empty dictionary literal:
namesOfIntegers = [:]
namesOfIntegers.count
// An immutable dictionary is a constant.
let immutableDict = ["a": "one", "b": "two"]
//: Similar to arrays, we cannot modify the contents of an immutable dictionary. The following lines
//: will not compile:
//:
// immutableDict["a"] = "b" // You cannot modify an element
// immutableDict["c"] = "three" // You cannot add a new entry or change the size
//: *Dictionaries are value types, which means they are copied on assignment.*
//
// Let's create a Dictionary and copy it:
var ages = ["Peter": 23, "Wei": 35, "Anish": 65, "Katya": 19]
var copiedAges = ages
// Next, we'll modify the copy:
copiedAges["Peter"] = 24
// And we can see that the original is not changed:
ages["Peter"]
//: [Next](@next)
|
apache-2.0
|
3dec37791983f095152b83b426351ef8
| 35.462687 | 514 | 0.6769 | 4.112795 | false | false | false | false |
BGDigital/mckuai2.0
|
mckuai/mckuai/mine/mineTableViewController.swift
|
1
|
19445
|
//
// mineTableViewController.swift
// mckuai
//
// Created by XingfuQiu on 15/4/22.
// Copyright (c) 2015年 XingfuQiu. All rights reserved.
//
import UIKit
class mineTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, MineProtocol, UITextViewDelegate {
var tableView: UITableView!
var isFirstLoad = true
var mineType = "message"
var mineMsgType = "reply"
var head: mineHeadViewController!
let NAVBAR_CHANGE_POINT:CGFloat = 50
var offsetY: CGFloat!
var manager = AFHTTPRequestOperationManager()
var page: PageInfo!
var hud: MBProgressHUD?
//快捷回复
var containerView:UIView!
var cancleButton:UIButton!
var sendButton:UIButton!
var viewButton:UIButton!
var textView:KMPlaceholderTextView!
var selectData: JSON!
var json: JSON! {
didSet {
if "ok" == self.json["state"].stringValue {
page = PageInfo(
currentPage: self.json["dataObject", "list", "page"].intValue,
pageCount: self.json["dataObject", "list", "pageCount"].intValue,
pageSize: self.json["dataObject", "list", "pageSize"].intValue,
allCount: self.json["dataObject", "list", "allCount"].intValue)
if let d = self.json["dataObject", "list", "data"].array {
if page.currentPage == 1 {
// println("刷新数据")
self.datasource = d
} else {
// println("加载更多")
self.datasource = self.datasource + d
}
}
self.User = self.json["dataObject", "user"] as JSON
}
head.RefreshHead(User, parent: self)
self.tableView.reloadData()
}
}
var User: JSON!
var datasource: Array<JSON> = Array() {
didSet {
if self.datasource.count < page.allCount {
self.tableView.footer.hidden = self.datasource.count < page.pageSize
// println("没有达到最大值 \(self.tableView.footer.hidden)")
} else {
// println("最大值了,noMoreData")
self.tableView.footer.hidden = true
}
self.tableView.reloadData()
}
}
class func initializationMine()->UIViewController{
var mine = UIStoryboard(name: "mine", bundle: nil).instantiateViewControllerWithIdentifier("mineTableViewController") as! mineTableViewController
return UINavigationController(rootViewController: mine)
}
func setupViews() {
self.tableView = UITableView(frame: CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height+64), style: UITableViewStyle.Plain)
tableView.autoresizingMask = .FlexibleWidth | .FlexibleBottomMargin | .FlexibleTopMargin
tableView.delegate = self
tableView.dataSource = self
tableView.opaque = false
tableView.backgroundColor = UIColor.whiteColor()
tableView.separatorStyle = .None
tableView.backgroundView = nil //这个可以改背影
tableView.scrollsToTop = false
//添加Header
self.head = UIStoryboard(name: "mine", bundle: nil).instantiateViewControllerWithIdentifier("mineHeadViewController") as! mineHeadViewController
tableView.tableHeaderView = self.head.view
self.head.Delegate = self
self.view.addSubview(tableView)
self.tableView.header = MJRefreshNormalHeader(refreshingBlock: { self.loadNewData() })
self.tableView.footer = MJRefreshAutoNormalFooter(refreshingBlock: {self.loadMoreData()})
// self.tableView.addLegendHeaderWithRefreshingBlock({self.loadNewData()})
// self.tableView.addLegendFooterWithRefreshingBlock({self.loadMoreData()})
self.tableView.footer.hidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
initReplyBar()
if isFirstLoad {
loadDataWithoutMJRefresh()
}
}
func loadDataWithoutMJRefresh() {
hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud?.labelText = MCUtils.TEXT_LOADING
loadNewData()
}
func scrollViewDidScroll(scrollView: UIScrollView) {
var color = UIColor(red: 0.247, green: 0.812, blue: 0.333, alpha: 1.00)
self.offsetY = scrollView.contentOffset.y
if self.offsetY > NAVBAR_CHANGE_POINT {
var alpha = 1 - (NAVBAR_CHANGE_POINT + 64 - offsetY) / 64
self.navigationItem.title = "个人中心"
self.navigationController?.navigationBar.lt_setBackgroundColor(color.colorWithAlphaComponent(alpha))
} else {
self.navigationItem.title = ""
self.navigationController?.navigationBar.lt_setBackgroundColor(color.colorWithAlphaComponent(0))
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if self.mineType != "work" {
return 100
} else {
return 80
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
if !self.datasource.isEmpty {
self.tableView.backgroundView = nil
return self.datasource.count
} else {
MCUtils.showEmptyView(self.tableView, aImg: Load_Empty!, aText: "你还没有发布作品,快去社区发贴吧")
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if self.mineType != "work" {
var cell = tableView.dequeueReusableCellWithIdentifier("messageCell") as? messageCell
if cell == nil {
let nib: NSArray = NSBundle.mainBundle().loadNibNamed("messageCell", owner: self, options: nil)
cell = nib.lastObject as? messageCell
}
let d = self.datasource[indexPath.row] as JSON
cell?.update(d, iType: self.mineType, sMsgType: self.mineMsgType)
// Configure the cell...
return cell!
} else {
var cell = tableView.dequeueReusableCellWithIdentifier("mainSubCell") as? mainSubCell
if cell == nil {
let nib: NSArray = NSBundle.mainBundle().loadNibNamed("mainSubCell", owner: self, options: nil)
cell = nib.lastObject as? mainSubCell
}
let d = self.datasource[indexPath.row] as JSON
cell?.update(d)
return cell!
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.selectData = self.datasource[indexPath.row]
if self.mineMsgType == "reply" {
self.textView.placeholder = "回复 " + self.selectData["userName"].stringValue
self.textView.becomeFirstResponder()
} else {
if self.mineMsgType != "system" {
let id = self.selectData["id"].stringValue
TalkDetail.showTalkDetailPage(self.navigationController, id: id)
}
}
}
override func becomeFirstResponder() -> Bool {
return super.becomeFirstResponder()
}
func loadNewData() {
//开始刷新
var param = [
"act": "center",
"id": appUserIdSave,
"page": 1,
"type":self.mineType,
"messageType": self.mineMsgType]
manager.GET(URL_MC,
parameters: param,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
self.isFirstLoad = false
self.json = JSON(responseObject)
self.tableView.header.endRefreshing()
self.hud?.hide(true)
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
self.tableView.header.endRefreshing()
self.hud?.hide(true)
MCUtils.showCustomHUD("数据加载失败", aType: .Error)
})
}
func loadMoreData() {
var param = [
"act": "center",
"id": appUserIdSave,
"page": page.currentPage+1,
"type":self.mineType,
"messageType": self.mineMsgType]
manager.GET(URL_MC,
parameters: param,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
self.json = JSON(responseObject)
self.tableView.footer.endRefreshing()
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
self.tableView.footer.endRefreshing()
MCUtils.showCustomHUD("数据加载失败", aType: .Error)
})
}
//刷新数据
//1:消息,2:动态,3:作品
//0:@Me,1:系统, 2:为空,不用传
func onRefreshDataSource(iType: Int, iMsgType: Int) {
//大类型
switch (iType) {
case 1:
self.mineType = "message"
case 2:
self.mineType = "dynamic"
break
default:
self.mineType = "work"
break
}
//小类型
switch (iMsgType) {
case 0:
self.mineMsgType = "reply"
break
case 1:
self.mineMsgType = "system"
break
default:
self.mineMsgType = ""
break
}
//开始加载数据
loadDataWithoutMJRefresh()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if self.offsetY > 64 {
return
}
//View 渐隐
var navAlpha = 1
var color = UIColor(hexString: MCUtils.COLOR_NavBG)
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.navigationController?.navigationBar.lt_setBackgroundColor(color?.colorWithAlphaComponent(0))
})
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
MobClick.beginLogPageView("mineTableView")
self.tabBarController?.tabBar.hidden = true
self.scrollViewDidScroll(self.tableView)
// //注册键盘通知事件
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
MobClick.endLogPageView("mineTableView")
self.tabBarController?.tabBar.hidden = false
self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor(hexString: MCUtils.COLOR_NavBG))
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//快捷回复
func initReplyBar() {
self.containerView = UIView(frame: CGRectMake(0, self.view.bounds.height, self.view.bounds.width, 100))
self.containerView.backgroundColor = UIColor(red: 0.949, green: 0.949, blue: 0.949, alpha: 1.00)
var line = UIView(frame: CGRectMake(0, 0, self.view.bounds.width, 1))
line.backgroundColor = UIColor(hexString: "#D8D8D8")
self.cancleButton = UIButton(frame: CGRectMake(5, 3, 50, 25))
self.cancleButton.setTitle("取消", forState: UIControlState.Normal)
self.cancleButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
self.cancleButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Highlighted)
self.cancleButton.titleLabel?.font = UIFont.systemFontOfSize(16)
self.cancleButton.addTarget(self, action: "cancleReply", forControlEvents: UIControlEvents.TouchUpInside)
self.sendButton = UIButton(frame: CGRectMake(self.containerView.frame.size.width-5-50, 3, 50, 25))
self.sendButton.setTitle("发送", forState: UIControlState.Normal)
self.sendButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
self.sendButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Highlighted)
self.sendButton.titleLabel?.font = UIFont.systemFontOfSize(16)
self.sendButton.addTarget(self, action: "sendReply", forControlEvents: UIControlEvents.TouchUpInside)
self.viewButton = UIButton(frame: CGRectMake((self.containerView.frame.size.width)/2-40, 3, 80, 25))
self.viewButton.setTitle("查看原帖", forState: UIControlState.Normal)
self.viewButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
self.viewButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Highlighted)
self.viewButton.titleLabel?.font = UIFont.systemFontOfSize(16)
self.viewButton.addTarget(self, action: "showReply", forControlEvents: UIControlEvents.TouchUpInside)
self.textView = KMPlaceholderTextView(frame: CGRectMake(5, 33, self.containerView.frame.size.width-10, 60))
self.textView.delegate = self
textView.layer.borderColor = UIColor(hexString: "#C7C7C7")!.CGColor
textView.layer.borderWidth = 1;
textView.layer.cornerRadius = 5;
textView.layer.masksToBounds = true;
textView.userInteractionEnabled = true;
textView.font = UIFont.systemFontOfSize(15)
textView.scrollEnabled = true;
textView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
var tapDismiss = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
tapDismiss.cancelsTouchesInView = false
self.tableView.addGestureRecognizer(tapDismiss)
self.containerView.addSubview(self.cancleButton)
self.containerView.addSubview(self.viewButton)
self.containerView.addSubview(self.sendButton)
self.containerView.addSubview(self.textView)
self.containerView.addSubview(line)
self.containerView.hidden = true
self.view.addSubview(containerView)
}
//查看原帖
func showReply() {
self.textView.resignFirstResponder()
let id = self.selectData["id"].stringValue
TalkDetail.showTalkDetailPage(self.navigationController, id: id)
}
//取消回复
func cancleReply() {
self.textView.resignFirstResponder()
}
//发送回复
func sendReply() {
self.sendButton.enabled = false
var replyContext = self.textView.text
if(replyContext == nil || replyContext.isEmpty){
self.textView.shake(.Horizontal, numberOfTimes: 10, totalDuration: 0.8, completion: {})
MCUtils.showCustomHUD("回复的内容不能为空", aType: .Error)
self.sendButton.enabled = true
return
}
var hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
hud.labelText = "正在发送"
//
var params = [
"act":"addReplyByCenter",
"loginId": appUserIdSave,
"replyContent": replyContext,
"cont2": selectData["cont2"].stringValue]
manager.POST(URL_MC,
parameters: params,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println(responseObject)
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
self.textView.resignFirstResponder()
hud.hide(true)
MCUtils.showCustomHUD("快速回复成功", aType: .Success)
self.sendButton.enabled = true
self.textView.text = ""
}else{
hud.hide(true)
self.sendButton.enabled = true
MCUtils.showCustomHUD("回复失败,请稍候再试", aType: .Error)
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
hud.hide(true)
self.sendButton.enabled = true
MCUtils.showCustomHUD("回复失败,请稍候再试", aType: .Error)
// MobClick.event("talkDetail", attributes: ["type":"sendReply","result":"error"])
})
}
func dismissKeyboard(){
// MobClick.event("talkDetail", attributes: ["type":"cancleReplyOther"])
println("dismissKeyboard")
self.textView.resignFirstResponder()
}
func textViewDidChange(textView: UITextView) {
self.textView.scrollRangeToVisible(self.textView.selectedRange)
}
func textViewDidBeginEditing(textView: UITextView) {
}
func textViewDidEndEditing(textView: UITextView) {
}
func keyboardDidShow(notification:NSNotification) {
self.containerView.hidden = false
var userInfo: NSDictionary = notification.userInfo! as NSDictionary
var v : NSValue = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
var keyHeight = v.CGRectValue().size.height
var duration = userInfo.objectForKey(UIKeyboardAnimationDurationUserInfoKey) as! NSNumber
var curve:NSNumber = userInfo.objectForKey(UIKeyboardAnimationCurveUserInfoKey) as! NSNumber
var temp:UIViewAnimationCurve = UIViewAnimationCurve(rawValue: curve.integerValue)!
UIView.animateWithDuration(duration.doubleValue, animations: {
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationCurve(temp)
self.containerView.frame = CGRectMake(0, self.view.frame.size.height-keyHeight-100, self.view.bounds.size.width, 100)
})
}
func keyboardDidHidden(notification:NSNotification) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.25)
self.containerView.frame = CGRectMake(0, self.view.frame.size.height, self.view.bounds.size.width, 100)
self.containerView.hidden = true
UIView.commitAnimations()
}
}
|
mit
|
04f1e53424f4cf998f0829ad24f01788
| 38.636929 | 154 | 0.613504 | 4.931595 | false | false | false | false |
abbeycode/Carthage
|
Source/carthage/Extensions.swift
|
1
|
8136
|
//
// Extensions.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2014-11-26.
// Copyright (c) 2014 Carthage. All rights reserved.
//
// This file contains extensions to anything that's not appropriate for
// CarthageKit.
import Box
import CarthageKit
import Commandant
import Foundation
import Result
import ReactiveCocoa
import ReactiveTask
private let outputQueue = { () -> dispatch_queue_t in
let queue = dispatch_queue_create("org.carthage.carthage.outputQueue", DISPATCH_QUEUE_SERIAL)
dispatch_set_target_queue(queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0))
atexit_b {
dispatch_barrier_sync(queue) {}
}
return queue
}()
/// A thread-safe version of Swift's standard println().
internal func println() {
dispatch_async(outputQueue) {
Swift.println()
}
}
/// A thread-safe version of Swift's standard println().
internal func println<T>(object: T) {
dispatch_async(outputQueue) {
Swift.println(object)
}
}
/// A thread-safe version of Swift's standard print().
internal func print<T>(object: T) {
dispatch_async(outputQueue) {
Swift.print(object)
}
}
/// Wraps CommandantError and adds ErrorType conformance.
public struct CommandError {
public let error: CommandantError<CarthageError>
public init(_ error: CommandantError<CarthageError>) {
self.error = error
}
}
extension CommandError: Printable {
public var description: String {
return error.description
}
}
extension CommandError: ErrorType {
public var nsError: NSError {
switch error {
case let .UsageError(description):
return NSError(domain: "org.carthage.Carthage", code: 0, userInfo: [
NSLocalizedDescriptionKey: description
])
case let .CommandError(commandError):
return commandError.value.nsError
}
}
}
/// Transforms the error type in a Result.
internal func mapError<T, E, F>(result: Result<T, E>, transform: E -> F) -> Result<T, F> {
switch result {
case let .Success(value):
return .Success(value)
case let .Failure(error):
return .Failure(Box(transform(error.value)))
}
}
/// Promotes CarthageErrors into CommandErrors.
internal func promoteErrors<T>(signal: Signal<T, CarthageError>) -> Signal<T, CommandError> {
return signal |> mapError { (error: CarthageError) -> CommandError in
let commandantError = CommandantError.CommandError(Box(error))
return CommandError(commandantError)
}
}
/// Lifts the Result of options parsing into a SignalProducer.
internal func producerWithOptions<T>(result: Result<T, CommandantError<CarthageError>>) -> SignalProducer<T, CommandError> {
let mappedResult = mapError(result) { CommandError($0) }
return SignalProducer(result: mappedResult)
}
/// Waits on a SignalProducer that implements the behavior of a CommandType.
internal func waitOnCommand<T>(producer: SignalProducer<T, CommandError>) -> Result<(), CommandantError<CarthageError>> {
let result = producer
|> then(SignalProducer<(), CommandError>.empty)
|> wait
TaskDescription.waitForAllTaskTermination()
return mapError(result) { $0.error }
}
extension GitURL: ArgumentType {
public static let name = "URL"
public static func fromString(string: String) -> GitURL? {
return self(string)
}
}
/// Logs project events put into the sink.
internal struct ProjectEventSink: SinkType {
private let colorOptions: ColorOptions
init(colorOptions: ColorOptions) {
self.colorOptions = colorOptions
}
mutating func put(event: ProjectEvent) {
let formatting = colorOptions.formatting
switch event {
case let .Cloning(project):
carthage.println(formatting.bullets + "Cloning " + formatting.projectName(string: project.name))
case let .Fetching(project):
carthage.println(formatting.bullets + "Fetching " + formatting.projectName(string: project.name))
case let .CheckingOut(project, revision):
carthage.println(formatting.bullets + "Checking out " + formatting.projectName(string: project.name) + " at " + formatting.quote(revision))
case let .DownloadingBinaries(project, release):
carthage.println(formatting.bullets + "Downloading " + formatting.projectName(string: project.name) + " at " + formatting.quote(release))
}
}
}
extension Project {
/// Determines whether the project needs to be migrated from an older
/// Carthage version, then performs the work if so.
///
/// If migration is necessary, sends one or more output lines describing the
/// process to the user.
internal func migrateIfNecessary(colorOptions: ColorOptions) -> SignalProducer<String, CarthageError> {
let directoryPath = directoryURL.path!
let fileManager = NSFileManager.defaultManager()
// These don't need to be declared more globally, since they're only for
// migration. We shouldn't need these names anywhere else.
let cartfileLock = "Cartfile.lock"
let carthageBuild = "Carthage.build"
let carthageCheckout = "Carthage.checkout"
let formatting = colorOptions.formatting
let migrationMessage = formatting.bulletinTitle("MIGRATION WARNING") + "\n\nThis project appears to be set up for an older (pre-0.4) version of Carthage. Unfortunately, the directory structure for Carthage projects has since changed, so this project will be migrated automatically.\n\nSpecifically, the following renames will occur:\n\n \(cartfileLock) -> \(CarthageProjectResolvedCartfilePath)\n \(carthageBuild) -> \(CarthageBinariesFolderPath)\n \(carthageCheckout) -> \(CarthageProjectCheckoutsPath)\n\nFor more information, see " + formatting.URL(string: "https://github.com/Carthage/Carthage/pull/224") + ".\n"
let producers = SignalProducer<SignalProducer<String, CarthageError>, CarthageError> { observer, disposable in
let checkFile: (String, String) -> () = { oldName, newName in
if fileManager.fileExistsAtPath(directoryPath.stringByAppendingPathComponent(oldName)) {
let producer = SignalProducer(value: migrationMessage)
|> concat(moveItemInPossibleRepository(self.directoryURL, fromPath: oldName, toPath: newName)
|> then(.empty))
sendNext(observer, producer)
}
}
checkFile(cartfileLock, CarthageProjectResolvedCartfilePath)
checkFile(carthageBuild, CarthageBinariesFolderPath)
// Carthage.checkout has to be handled specially, because if it
// includes submodules, we need to move them one-by-one to ensure
// that .gitmodules is properly updated.
if fileManager.fileExistsAtPath(directoryPath.stringByAppendingPathComponent(carthageCheckout)) {
let oldCheckoutsURL = self.directoryURL.URLByAppendingPathComponent(carthageCheckout)
var error: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(oldCheckoutsURL, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants | NSDirectoryEnumerationOptions.SkipsPackageDescendants | NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: &error) {
let trashProducer = SignalProducer<(), CarthageError>.try {
var error: NSError?
if fileManager.trashItemAtURL(oldCheckoutsURL, resultingItemURL: nil, error: &error) {
return .success(())
} else {
return .failure(CarthageError.WriteFailed(oldCheckoutsURL, error))
}
}
let moveProducer: SignalProducer<(), CarthageError> = SignalProducer(values: contents)
|> map { (object: AnyObject) in object as! NSURL }
|> flatMap(.Concat) { (URL: NSURL) -> SignalProducer<NSURL, CarthageError> in
let lastPathComponent: String! = URL.lastPathComponent
return moveItemInPossibleRepository(self.directoryURL, fromPath: carthageCheckout.stringByAppendingPathComponent(lastPathComponent), toPath: CarthageProjectCheckoutsPath.stringByAppendingPathComponent(lastPathComponent))
}
|> then(trashProducer)
|> then(.empty)
let producer = SignalProducer<String, CarthageError>(value: migrationMessage)
|> concat(moveProducer
|> then(.empty))
sendNext(observer, producer)
} else {
sendError(observer, CarthageError.ReadFailed(oldCheckoutsURL, error))
return
}
}
sendCompleted(observer)
}
return producers
|> flatten(.Concat)
|> takeLast(1)
}
}
|
mit
|
0abbb769ef3f97db39c634498ba4c2c1
| 34.684211 | 621 | 0.744592 | 4.096677 | false | false | false | false |
NghiaTranUIT/Unofficial-Uber-macOS
|
UberGoCore/UberGoCore/RxCLLocationManagerDelegateProxy.swift
|
9
|
1750
|
//
// RxCLLocationManagerDelegateProxy.swift
// RxExample
//
// Created by Carlos García on 8/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import CoreLocation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class RxCLLocationManagerDelegateProxy : DelegateProxy
, CLLocationManagerDelegate
, DelegateProxyType {
internal lazy var didUpdateLocationsSubject = PublishSubject<[CLLocation]>()
internal lazy var didFailWithErrorSubject = PublishSubject<Error>()
class func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
let locationManager: CLLocationManager = object as! CLLocationManager
return locationManager.delegate
}
class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
let locationManager: CLLocationManager = object as! CLLocationManager
if let delegate = delegate {
locationManager.delegate = (delegate as! CLLocationManagerDelegate)
} else {
locationManager.delegate = nil
}
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
_forwardToDelegate?.locationManager(manager, didUpdateLocations: locations)
didUpdateLocationsSubject.onNext(locations)
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
_forwardToDelegate?.locationManager(manager, didFailWithError: error)
didFailWithErrorSubject.onNext(error)
}
deinit {
self.didUpdateLocationsSubject.on(.completed)
self.didFailWithErrorSubject.on(.completed)
}
}
|
mit
|
682766b33841bdac5d5ac293f5702288
| 33.96 | 107 | 0.693364 | 5.96587 | false | false | false | false |
rambler-digital-solutions/rambler-it-ios
|
Carthage/Checkouts/rides-ios-sdk/source/UberRides/RideRequestView.swift
|
1
|
10364
|
//
// RideRequestView.swift
// UberRides
//
// Copyright © 2016 Uber Technologies, Inc. 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 WebKit
import CoreLocation
/**
* Delegates are informed of events that occur in the RideRequestView such as errors.
*/
@objc(UBSDKRideRequestViewDelegate) public protocol RideRequestViewDelegate {
/**
An error has occurred in the Ride Request Control.
- parameter rideRequestView: the RideRequestView
- parameter error: the NSError that occured, with a code of RideRequestViewErrorType
*/
func rideRequestView(_ rideRequestView: RideRequestView, didReceiveError error: NSError)
}
/// A view that shows the embedded Uber experience.
@objc(UBSDKRideRequestView) public class RideRequestView: UIView {
/// The RideRequestViewDelegate of this view.
@objc public var delegate: RideRequestViewDelegate?
/// The access token used to authorize the web view
@objc public var accessToken: AccessToken?
/// Ther RideParameters to use for prefilling the RideRequestView
@objc public var rideParameters: RideParameters
var webView: WKWebView
let redirectURL = "uberconnect://oauth"
static let sourceString = "ride_request_view"
/**
Initializes to show the embedded Uber ride request view.
- parameter rideParameters: The RideParameters to use for presetting values; defaults to using the current location for pickup
- parameter accessToken: specific access token to use with web view; defaults to using TokenManager's default token
- parameter frame: frame of the view. Defaults to CGRectZero
- returns: An initialized RideRequestView
*/
@objc public required init(rideParameters: RideParameters, accessToken: AccessToken?, frame: CGRect) {
self.rideParameters = rideParameters
self.accessToken = accessToken
let configuration = WKWebViewConfiguration()
configuration.processPool = Configuration.shared.processPool
webView = WKWebView(frame: CGRect.zero, configuration: configuration)
super.init(frame: frame)
initialSetup()
}
/**
Initializes to show the embedded Uber ride request view.
Uses the TokenManager's default accessToken
- parameter rideParameters: The RideParameters to use for presetting values
- parameter frame: frame of the view
- returns: An initialized RideRequestView
*/
@objc public convenience init(rideParameters: RideParameters, frame: CGRect) {
self.init(rideParameters: rideParameters, accessToken: TokenManager.fetchToken(), frame: frame)
}
/**
Initializes to show the embedded Uber ride request view.
Frame defaults to CGRectZero
Uses the TokenManager's default accessToken
- parameter rideParameters: The RideParameters to use for presetting values
- returns: An initialized RideRequestView
*/
@objc public convenience init(rideParameters: RideParameters) {
self.init(rideParameters: rideParameters, accessToken: TokenManager.fetchToken(), frame: CGRect.zero)
}
/**
Initializes to show the embedded Uber ride request view.
Uses the current location for pickup
Uses the TokenManager's default accessToken
- parameter frame: frame of the view
- returns: An initialized RideRequestView
*/
@objc public convenience override init(frame: CGRect) {
self.init(rideParameters: RideParametersBuilder().build(), accessToken: TokenManager.fetchToken(), frame: frame)
}
/**
Initializes to show the embedded Uber ride request view.
Uses the current location for pickup
Uses the TokenManager's default accessToken
Frame defaults to CGRectZero
- returns: An initialized RideRequestView
*/
@objc public convenience init() {
self.init(rideParameters: RideParametersBuilder().build(), accessToken: TokenManager.fetchToken(), frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
rideParameters = RideParametersBuilder().build()
let configuration = WKWebViewConfiguration()
configuration.processPool = Configuration.shared.processPool
webView = WKWebView(frame: CGRect.zero, configuration: configuration)
super.init(coder: aDecoder)
initialSetup()
}
deinit {
webView.scrollView.delegate = nil
NotificationCenter.default.removeObserver(self)
}
// MARK: Public
/**
Load the Uber Ride Request Widget view.
Requires that the access token has been retrieved.
*/
@objc public func load() {
guard let accessToken = accessToken else {
self.delegate?.rideRequestView(self, didReceiveError: RideRequestViewErrorFactory.errorForType(.accessTokenMissing))
return
}
let tokenString = accessToken.tokenString
rideParameters.source = rideParameters.source ?? RideRequestView.sourceString
let endpoint = Components.rideRequestWidget(rideParameters: rideParameters)
guard let request = Request(session: nil, endpoint: endpoint, bearerToken: tokenString) else {
delegate?.rideRequestView(self, didReceiveError: RideRequestViewErrorFactory.errorForType(.invalidRequest))
return
}
request.prepare()
var urlRequest = request.urlRequest
urlRequest.cachePolicy = .returnCacheDataElseLoad
webView.load(urlRequest)
}
/**
Stop loading the Ride Request Widget View and clears the view.
If the view has already loaded, calling this still clears the view.
*/
@objc public func cancelLoad() {
webView.stopLoading()
if let url = URL(string: "about:blank") {
webView.load(URLRequest(url: url))
}
}
// MARK: Private
private func initialSetup() {
webView.navigationDelegate = self
webView.scrollView.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidAppear(_:)), name: Notification.Name.UIKeyboardDidShow, object: nil)
setupWebView()
}
private func setupWebView() {
addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.scrollView.bounces = false
let views = ["webView": webView]
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[webView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[webView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
addConstraints(horizontalConstraints)
addConstraints(verticalConstraints)
}
// MARK: Keyboard Notifications
@objc func keyboardWillAppear(_ notification: Notification) {
webView.scrollView.isScrollEnabled = false
}
@objc func keyboardDidAppear(_ notification: Notification) {
webView.scrollView.isScrollEnabled = true
}
}
// MARK: WKNavigationDelegate
extension RideRequestView: WKNavigationDelegate {
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url {
if url.absoluteString.lowercased().hasPrefix(redirectURL.lowercased()) {
let error = OAuthUtil.parseRideWidgetErrorFromURL(url)
delegate?.rideRequestView(self, didReceiveError: error)
decisionHandler(.cancel)
return
} else if url.scheme == "tel" || url.scheme == "sms" {
if (!UIApplication.shared.openURL(url)) {
delegate?.rideRequestView(self, didReceiveError: RideRequestViewErrorFactory.errorForType(.notSupported))
}
decisionHandler(.cancel)
return
}
}
decisionHandler(.allow)
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
delegate?.rideRequestView(self, didReceiveError: RideRequestViewErrorFactory.errorForType(.networkError))
}
public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard (error as NSError).code != 102 else {
return
}
delegate?.rideRequestView(self, didReceiveError: RideRequestViewErrorFactory.errorForType(.networkError))
}
}
// MARK: UIScrollViewDelegate
extension RideRequestView : UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !scrollView.isScrollEnabled {
scrollView.bounds = self.webView.bounds
}
}
}
|
mit
|
08131abb706928117ca0fb98175d92f6
| 39.322957 | 174 | 0.689955 | 5.468602 | false | false | false | false |
diesmal/thisorthat
|
ThisOrThat/Code/Views/CircleRatioView.swift
|
1
|
8977
|
//
// CircleRatioView.swift
// ThisOrThat
//
// Created by Ilya Nikolaenko on 20/01/2017.
// Copyright © 2017 Ilya Nikolaenko. All rights reserved.
//
import UIKit
@IBDesignable
class CircleRatioView : UIView {
@IBInspectable var bottomColor: UIColor?
@IBInspectable var topColor: UIColor?
@IBInspectable var backColor: UIColor?
let background = CAShapeLayer()
let arcLayers = [CAShapeLayer(), CAShapeLayer(), CAShapeLayer(), CAShapeLayer()]
let progress = (top: UILabel(), bottom: UILabel())
let lineWidth = CGFloat(50)
let arcAnimationDuration = CFTimeInterval(0.5)
override var isHidden: Bool {
set {
super.isHidden = newValue
if newValue == true {
for layer in arcLayers {
layer.isHidden = true
}
progress.top.isHidden = true
progress.bottom.isHidden = true
}
}
get {
return super.isHidden
}
}
func radian(degrees: CGFloat) -> CGFloat {
return degrees * .pi / 180
}
func configureBackground() {
guard let backColor = self.backColor else {
return
}
let size = self.frame.size
let radius: CGFloat = min(size.width, size.height)/2
let roundedRect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
background.frame = roundedRect
background.path = UIBezierPath(roundedRect: roundedRect, cornerRadius: radius).cgPath
background.fillColor = backColor.cgColor
self.layer.addSublayer(background)
}
func configureArcs() {
guard let topColor = self.topColor,
let bottomColor = self.bottomColor else {
return
}
configureArc(layer: arcLayers[0],
color: topColor.cgColor,
startAngle: -90,
endAngle: 90,
clockwise: false)
configureArc(layer: arcLayers[1],
color: topColor.cgColor,
startAngle: -90,
endAngle: 90,
clockwise: true)
configureArc(layer: arcLayers[2],
color: bottomColor.cgColor,
startAngle: 90,
endAngle: 270,
clockwise: true)
configureArc(layer: arcLayers[3],
color: bottomColor.cgColor,
startAngle: 90,
endAngle: -90,
clockwise: false)
for layer in arcLayers {
layer.isHidden = true
self.layer.addSublayer(layer)
}
}
func configureArc(layer: CAShapeLayer, color: CGColor, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) {
let size = self.frame.size
let side = min(size.width, size.height) - lineWidth + 1
let center = CGPoint(x: size.width/2,
y: size.height/2)
let pathTop = UIBezierPath()
pathTop.addArc(withCenter: center,
radius: side/2,
startAngle: radian(degrees: startAngle),
endAngle: radian(degrees: endAngle),
clockwise: clockwise)
layer.path = pathTop.cgPath
layer.fillColor = UIColor.clear.cgColor
layer.strokeColor = color
layer.lineWidth = lineWidth
}
func configureLabels() {
let height = lineWidth/2
self.progress.top.frame = CGRect(x: 0, y: 0, width: height*2, height: height/2)
self.progress.bottom.frame = self.progress.top.frame
self.progress.top.textColor = UIColor.white
self.progress.bottom.textColor = self.progress.top.textColor
self.progress.top.font = UIFont.systemFont(ofSize: height * 0.4)
self.progress.bottom.font = self.progress.top.font
let size = self.frame.size
self.progress.top.center = CGPoint(x: size.width/2, y: height * 0.5 - 2)
self.progress.bottom.center = CGPoint(x: size.width/2, y: size.height - height * 0.5 + 2)
self.progress.top.text = "0%"
self.progress.bottom.text = "0%"
self.progress.top.textAlignment = .center
self.progress.bottom.textAlignment = .center
self.progress.top.isHidden = true
self.progress.bottom.isHidden = true
self.addSubview(self.progress.top)
self.addSubview(self.progress.bottom)
}
func animate(topValue: Float, bottomValue: Float) {
configureBackground()
configureArcs()
configureLabels()
CATransaction.begin()
let scale = backgroundAnimation()
CATransaction.setCompletionBlock {
let drawAnimation = self.arcsAnimation(topValue: topValue, bottomValue: bottomValue)
for layer in self.arcLayers {
layer.isHidden = false
}
self.arcLayers[0].add(drawAnimation.0, forKey: "draw")
self.arcLayers[1].add(drawAnimation.0, forKey: "draw")
self.arcLayers[2].add(drawAnimation.1, forKey: "draw")
self.arcLayers[3].add(drawAnimation.1, forKey: "draw")
self.animateTextProgress(topValue: topValue, bottomValue: bottomValue)
}
background.add(scale, forKey: "scale")
CATransaction.commit()
}
func backgroundAnimation() -> CABasicAnimation {
let scale = "transform.scale"
background.transform = CATransform3DMakeScale(1, 1, 1)
if #available(iOS 9, *) {
let scaleAnimation = CASpringAnimation(keyPath: scale)
scaleAnimation.duration = CFTimeInterval(0.7)
scaleAnimation.fromValue = 0.0
scaleAnimation.toValue = 1
scaleAnimation.autoreverses = false
scaleAnimation.repeatCount = 1
scaleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
scaleAnimation.isRemovedOnCompletion = false
return scaleAnimation
} else {
let scaleAnimation = CABasicAnimation(keyPath: scale)
scaleAnimation.duration = CFTimeInterval(0.7)
scaleAnimation.fromValue = 0.0
scaleAnimation.toValue = 1
scaleAnimation.autoreverses = false
scaleAnimation.repeatCount = 1
scaleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
scaleAnimation.isRemovedOnCompletion = false
return scaleAnimation
}
}
func arcsAnimation(topValue: Float, bottomValue: Float) -> (CABasicAnimation, CABasicAnimation) {
let strokeEnd = "strokeEnd"
let pathTopAnimation = CABasicAnimation(keyPath: strokeEnd)
let fullValue = (topValue + bottomValue)
let topValue = topValue / fullValue
let botValue = bottomValue / fullValue
pathTopAnimation.duration = arcAnimationDuration
pathTopAnimation.fromValue = 0.0
pathTopAnimation.toValue = topValue
pathTopAnimation.autoreverses = false
pathTopAnimation.repeatCount = 1
pathTopAnimation.fillMode = kCAFillModeForwards
pathTopAnimation.isRemovedOnCompletion = false
let pathBotAnimation = pathTopAnimation.copy() as! CABasicAnimation
pathBotAnimation.toValue = botValue
return (pathTopAnimation, pathBotAnimation)
}
func animateTextProgress(topValue: Float, bottomValue: Float) {
let topTarget = (topValue / (topValue + bottomValue)) * 100
let bottomTarget = 100 - topTarget
self.progress.top.text = (topTarget > 0) ? "\(Int(topTarget))%" : "0%"
self.progress.bottom.text = (bottomTarget > 0) ? "\(Int(bottomTarget))%" : "0%"
DispatchQueue.main.asyncAfter(deadline: .now() + arcAnimationDuration, execute: {
self.progress.top.isHidden = false
self.progress.bottom.isHidden = false
let animation = CAKeyframeAnimation()
animation.keyPath = "transform.scale"
animation.values = [0, 1.25, 1]
animation.keyTimes = [0, 0.25, 0.5]
animation.duration = 0.5
self.progress.top.layer.add(animation, forKey: "scale")
self.progress.bottom.layer.add(animation, forKey: "scale")
})
}
}
|
apache-2.0
|
d37923c6c7ae921c719962eeebb8841e
| 32.744361 | 117 | 0.563614 | 5.11453 | false | false | false | false |
qkrqjadn/SoonChat
|
source/Controller/DetailInfoViewController.swift
|
1
|
2856
|
//
// deTailViewController.swift
// soonchat
//
// Created by 박범우 on 2017. 2. 6..
// Copyright © 2017년 bumwoo. All rights reserved.
//
import UIKit
class DetailInfoViewController : UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
{
let cellid = "cellId"
var infomation : Info?
lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0.5
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .lightGray
cv.delegate = self
cv.dataSource = self
cv.register(DetailInfoCell.self, forCellWithReuseIdentifier: self.cellid)
return cv
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
collectionView.frame = view.bounds
view.addSubview(collectionView)
}
init(Infomation:Info) {
super.init(nibName: nil, bundle: nil)
self.infomation = Infomation
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellid, for: indexPath) as? DetailInfoCell
if indexPath.row == 0 {
cell?.commentTextView.text = infomation?.titleComment
cell?.commentTextView.font = UIFont.systemFont(ofSize: 20)
cell?.commentTextView.textAlignment = .center
}
else
{
cell?.commentTextView.text = infomation?.usercomment
print(cell?.commentTextView.text)
}
return cell!
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.row == 0 {
return CGSize(width: UIScreen.main.bounds.width, height: 50)
}else{
return CGSize(width: UIScreen.main.bounds.width, height: 400)
}
}
}
class DetailInfoCell : UICollectionViewCell
{
let commentTextView : UITextView = {
let tv = UITextView()
tv.isEditable = false
return tv
}()
override init(frame: CGRect) {
super.init(frame: frame)
commentTextView.frame = bounds
addSubview(commentTextView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
2c7acecc635669ef6c7eb7750eff049a
| 30.988764 | 160 | 0.654022 | 4.994737 | false | false | false | false |
tomoponzoo/Migrant
|
Migrant/Migrant.swift
|
1
|
1587
|
//
// Migrant.swift
// Migrant
//
// Created by tomoponzoo on 2016/06/17.
// Copyright © 2016年 tomoponzoo. All rights reserved.
//
import Foundation
public typealias MigrateBlock = (() -> Void)
public protocol Migratable {
var migratable: Bool { get }
}
public protocol Migrator {
var migrator: MigrateBlock { get }
}
public protocol MigrateTask: Migratable, Migrator {
}
open class MigrateBlockTask: MigrateTask {
private let _migratable: Migratable
private let _migrator: MigrateBlock
open var migratable: Bool {
return _migratable.migratable
}
open var migrator: MigrateBlock {
return _migrator
}
public init(migratable: Migratable, migrator: @escaping MigrateBlock) {
_migratable = migratable
_migrator = migrator
}
}
public class Migrant {
private var tasks = [MigrateTask]()
public init() {
}
public func set(_ task: MigrateTask) {
tasks.append(task)
}
public func set(_ migratable: Migratable, migrator: @escaping MigrateBlock) {
tasks.append(MigrateBlockTask(migratable: migratable, migrator: migrator))
}
public func migrate() {
migrate {
for task in self.tasks {
if !task.migratable {
continue
}
task.migrator()
}
}
}
private func migrate(_ block: () -> Void) {
block()
if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
Conf.sharedConfiguration.version = version
}
}
}
|
mit
|
8c3576de94e4afcc044af5e5b9875eb5
| 19.842105 | 108 | 0.630682 | 3.872861 | false | false | false | false |
curiousurick/BluetoothBackupSensor-iOS
|
CSS427Bluefruit_Connect/BLE Test/Constants.swift
|
5
|
6373
|
//
// Constants.swift
// Adafruit Bluefruit LE Connect
//
// Created by Collin Cunningham on 10/1/14.
// Copyright (c) 2014 Adafruit Industries. All rights reserved.
//
import Foundation
import UIKit
import CoreBluetooth
//System Variables
let CURRENT_DEVICE = UIDevice.currentDevice()
let INTERFACE_IS_PAD:Bool = (CURRENT_DEVICE.userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
let INTERFACE_IS_PHONE:Bool = (CURRENT_DEVICE.userInterfaceIdiom == UIUserInterfaceIdiom.Phone)
let IS_IPAD:Bool = INTERFACE_IS_PAD
let IS_IPHONE:Bool = INTERFACE_IS_PHONE
let MAIN_SCREEN = UIScreen.mainScreen()
let IS_IPHONE_5:Bool = MAIN_SCREEN.bounds.size.height == 568.0
let IS_IPHONE_4:Bool = MAIN_SCREEN.bounds.size.height == 480.0
let IS_RETINA:Bool = MAIN_SCREEN.respondsToSelector("scale") && (MAIN_SCREEN.scale == 2.0)
let IOS_VERSION_FLOAT:Float = (CURRENT_DEVICE.systemVersion as NSString).floatValue
#if DEBUG
let LOGGING = true
#else
let LOGGING = false
#endif
let PREF_UART_SHOULD_ECHO_LOCAL = "UartEchoLocal"
let cellSelectionColor = UIColor(red: 100.0/255.0, green: 182.0/255.0, blue: 255.0/255.0, alpha: 1.0)
let bleBlueColor = UIColor(red: 24.0/255.0, green: 126.0/255.0, blue: 248.0/255.0, alpha: 1.0)
func animateCellSelection(cell:UITableViewCell) {
//fade cell background blue to white
cell.backgroundColor = cellSelectionColor
UIView.animateWithDuration(0.25, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
cell.backgroundColor = UIColor.whiteColor()
}) { (done:Bool) -> Void in
}
}
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure
)
}
//MARK: User prefs
func uartShouldEchoLocal() ->Bool {
// Pref was not set
if NSUserDefaults.standardUserDefaults().valueForKey(PREF_UART_SHOULD_ECHO_LOCAL) == nil {
uartShouldEchoLocalSet(false)
return false
}
// Pref was set
else {
return NSUserDefaults.standardUserDefaults().boolForKey(PREF_UART_SHOULD_ECHO_LOCAL)
}
}
func uartShouldEchoLocalSet(shouldEcho:Bool) {
NSUserDefaults.standardUserDefaults().setBool(shouldEcho, forKey: PREF_UART_SHOULD_ECHO_LOCAL)
}
//MARK: UUID Retrieval
func uartServiceUUID()->CBUUID{
return CBUUID(string: "6e400001-b5a3-f393-e0a9-e50e24dcca9e")
}
func txCharacteristicUUID()->CBUUID{
return CBUUID(string: "6e400002-b5a3-f393-e0a9-e50e24dcca9e")
}
func rxCharacteristicUUID()->CBUUID{
return CBUUID(string: "6e400003-b5a3-f393-e0a9-e50e24dcca9e")
}
func deviceInformationServiceUUID()->CBUUID{
return CBUUID(string: "180A")
}
func hardwareRevisionStringUUID()->CBUUID{
return CBUUID(string: "2A27")
}
func manufacturerNameStringUUID()->CBUUID{
return CBUUID(string: "2A29")
}
func modelNumberStringUUID()->CBUUID{
return CBUUID(string: "2A24")
}
func firmwareRevisionStringUUID()->CBUUID{
return CBUUID(string: "2A26")
}
func softwareRevisionStringUUID()->CBUUID{
return CBUUID(string: "2A28")
}
func serialNumberStringUUID()->CBUUID{
return CBUUID(string: "2A25")
}
func systemIDStringUUID()->CBUUID{
return CBUUID(string: "2A23")
}
func dfuServiceUUID()->CBUUID{
return CBUUID(string: "00001530-1212-efde-1523-785feabcd123")
}
func modelNumberCharacteristicUUID()->CBUUID{
return CBUUID(string: "00002A24-0000-1000-8000-00805F9B34FB")
}
func manufacturerNameCharacteristicUUID() ->CBUUID {
return CBUUID(string: "00002A29-0000-1000-8000-00805F9B34FB")
}
func softwareRevisionCharacteristicUUID() ->CBUUID {
return CBUUID(string: "00002A28-0000-1000-8000-00805F9B34FB")
}
func firmwareRevisionCharacteristicUUID() ->CBUUID {
return CBUUID(string: "00002A26-0000-1000-8000-00805F9B34FB")
}
func dfuControlPointCharacteristicUUID() ->CBUUID {
return CBUUID(string: "00001531-1212-EFDE-1523-785FEABCD123")
}
func dfuPacketCharacteristicUUID() ->CBUUID {
return CBUUID(string: "00001532-1212-EFDE-1523-785FEABCD123")
}
func dfuVersionCharacteritsicUUID() ->CBUUID {
return CBUUID(string: "00001534-1212-EFDE-1523-785FEABCD123")
}
//let knownUUIDs:[CBUUID] = [
// uartServiceUUID(),
// txCharacteristicUUID(),
// rxCharacteristicUUID(),
// deviceInformationServiceUUID(),
// hardwareRevisionStringUUID(),
// manufacturerNameStringUUID(),
// modelNumberStringUUID(),
// firmwareRevisionStringUUID(),
// softwareRevisionStringUUID(),
// serialNumberStringUUID(),
// dfuServiceUUID(),
// modelNumberCharacteristicUUID(),
// manufacturerNameCharacteristicUUID(),
// softwareRevisionCharacteristicUUID(),
// firmwareRevisionCharacteristicUUID(),
// dfuControlPointCharacteristicUUID(),
// dfuPacketCharacteristicUUID(),
// dfuVersionCharacteritsicUUID(),
// CBUUID(string: CBUUIDCharacteristicAggregateFormatString),
// CBUUID(string: CBUUIDCharacteristicExtendedPropertiesString),
// CBUUID(string: CBUUIDCharacteristicFormatString),
// CBUUID(string: CBUUIDCharacteristicUserDescriptionString),
// CBUUID(string: CBUUIDClientCharacteristicConfigurationString),
// CBUUID(string: CBUUIDServerCharacteristicConfigurationString)
//]
//
//
//
//let knownUUIDNames:[String] = [
// "UART",
// "TXD",
// "RXD",
// "Device Information",
// "Hardware Revision",
// "Manufacturer Name",
// "Model Number",
// "Firmware Revision",
// "Software Revision",
// "Serial Number",
// "DFU Service",
// "Model Number",
// "Manufacturer Name",
// "Software Revision",
// "Firmware Revision",
// "DFU Control Point",
// "DFU Packet",
// "DFU Version",
// "Characteristic Aggregate Format",
// "Characteristic Extended Properties",
// "Characteristic Format",
// "Characteristic User Description",
// "Client Characteristic Configuration",
// "Server Characteristic Configuration",
//]
func UUIDsAreEqual(firstID:CBUUID, secondID:CBUUID)->Bool {
if firstID.representativeString() == secondID.representativeString() {
return true
}
else {
return false
}
}
|
mit
|
9df37b9094ec380ab6260d58d3d032d6
| 22.779851 | 122 | 0.692139 | 3.707388 | false | false | false | false |
SixFiveSoftware/Swift_Pair_Programming_Resources
|
2014-06-28/AsyncTests/AsyncTestsTests/AsyncTestsTests.swift
|
1
|
1965
|
//
// AsyncTestsTests.swift
// AsyncTestsTests
//
// Created by BJ Miller on 6/28/14.
// Copyright (c) 2014 Six Five Software, LLC. All rights reserved.
//
import XCTest
import CoreData
import UIKit
import Foundation
class OurDocument: UIDocument {
override func contentsForType(typeName: String!, error outError: NSErrorPointer) -> AnyObject! {
var hello = "Hello world"
var data = hello.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return data
}
override func loadFromContents(contents: AnyObject!, ofType typeName: String!, error outError: NSErrorPointer) -> Bool {
return true
}
}
class AsyncTestsTests: XCTestCase {
var document: OurDocument?
override func setUp() {
super.setUp()
let fileURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("someFile.sqlite")
document = OurDocument(fileURL: fileURL)
if let doc = document {
doc.saveToURL(doc.fileURL, forSaveOperation: .ForOverwriting, completionHandler: nil)
}
}
override func tearDown() {
document = nil
super.tearDown()
}
func testPerformanceExample() {
self.measureBlock() {
self.testDocumentOpening()
}
}
func testDocumentOpening() {
let expectation = self.expectationWithDescription("open doc")
if let doc = self.document {
doc.openWithCompletionHandler( { success in
XCTAssert(success, "should open the document")
expectation.fulfill()
})
}
self.waitForExpectationsWithTimeout(5.0, handler: nil)
}
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex-1] as NSURL
}
}
|
mit
|
9607a9a033ee2ed33b517cec25dd01ce
| 27.071429 | 124 | 0.638168 | 5.090674 | false | true | false | false |
werner-freytag/DockTime
|
ClockBundle-Classic-FlipClock/ClockView.swift
|
1
|
2928
|
// The MIT License
//
// Copyright 2012-2021 Werner Freytag
//
// 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 AppKit
import SwiftToolbox
class ClockView: NSView {
lazy var bundle = Bundle(for: type(of: self))
override func draw(_: NSRect) {
guard let context = currentContext else { return assertionFailure("Can not access graphics context.") }
let timeFormatter = DateFormatter()
timeFormatter.dateStyle = .none
timeFormatter.timeStyle = .short
let dateString: String! = timeFormatter.string(from: Date())
guard let components = try? dateString.match(regex: "([0-9])?([0-9])[^0-9]+([0-9]+)([0-9]+)") else { return assertionFailure("Can not parse date.") }
context.saveGState {
var imageName: String
var image: NSImage!
image = bundle.image(named: "Background")!
image.draw(at: .zero, from: .zero, operation: .copy, fraction: 1)
imageName = components[1].isEmpty ? "0" : components[1]
image = bundle.image(named: imageName)
image.draw(at: CGPoint(x: 17, y: 44), from: .zero, operation: .sourceOver, fraction: 1)
imageName = components[2]
image = bundle.image(named: imageName)
image.draw(at: CGPoint(x: 38, y: 44), from: .zero, operation: .sourceOver, fraction: 1)
imageName = components[3]
image = bundle.image(named: imageName)
image.draw(at: CGPoint(x: 72, y: 44), from: .zero, operation: .sourceOver, fraction: 1)
imageName = components[4]
image = bundle.image(named: imageName)
image.draw(at: CGPoint(x: 92, y: 44), from: .zero, operation: .sourceOver, fraction: 1)
image = bundle.image(named: "Foreground")
image.draw(at: .zero, from: .zero, operation: .sourceOver, fraction: 1)
}
}
}
|
mit
|
d4de84a8c8b59bc0873faa4da33aac26
| 42.701493 | 157 | 0.663251 | 4.255814 | false | false | false | false |
frootloops/swift
|
test/SILOptimizer/definite_init_protocol_init.swift
|
1
|
5533
|
// RUN: %target-swift-frontend -emit-sil -enable-sil-ownership %s -swift-version 5 -verify | %FileCheck %s
// Ensure that convenience initializers on concrete types can
// delegate to factory initializers defined in protocol
// extensions.
protocol TriviallyConstructible {
init(lower: Int)
}
extension TriviallyConstructible {
init(middle: Int) {
self.init(lower: middle)
}
init?(failingMiddle: Int) {
self.init(lower: failingMiddle)
}
init(throwingMiddle: Int) throws {
self.init(lower: throwingMiddle)
}
}
class TrivialClass : TriviallyConstructible {
required init(lower: Int) {}
// CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B012TrivialClassCACSi5upper_tcfc
// CHECK: bb0(%0 : $Int, [[OLD_SELF:%.*]] : $TrivialClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $TrivialClass
// CHECK-NEXT: debug_value
// CHECK-NEXT: store [[OLD_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick @dynamic_self TrivialClass.Type, %1
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $TrivialClass
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC
// CHECK-NEXT: apply [[FN]]<@dynamic_self TrivialClass>([[RESULT]], %0, [[METATYPE]])
// CHECK-NEXT: [[NEW_SELF:%.*]] = load [[RESULT]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick TrivialClass.Type, %1
// CHECK-NEXT: dealloc_partial_ref %1 : $TrivialClass, [[METATYPE]] : $@thick TrivialClass.Type
// CHECK-NEXT: dealloc_stack [[RESULT]]
// TODO: Once we restore arbitrary takes, the strong_retain/destroy_addr pair below will go away.
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
convenience init(upper: Int) {
self.init(middle: upper)
}
convenience init?(failingUpper: Int) {
self.init(failingMiddle: failingUpper)
}
convenience init(throwingUpper: Int) throws {
try self.init(throwingMiddle: throwingUpper)
}
}
struct TrivialStruct : TriviallyConstructible {
let x: Int
init(lower: Int) { self.x = lower }
// CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B013TrivialStructVACSi5upper_tcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin TrivialStruct.Type):
// CHECK-NEXT: [[SELF:%.*]] = alloc_stack $TrivialStruct
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $TrivialStruct
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick TrivialStruct.Type
// CHECK: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC
// CHECK-NEXT: apply [[FN]]<TrivialStruct>([[SELF_BOX]], %0, [[METATYPE]])
// CHECK-NEXT: [[NEW_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: return [[NEW_SELF]]
init(upper: Int) {
self.init(middle: upper)
}
init?(failingUpper: Int) {
self.init(failingMiddle: failingUpper)
}
init(throwingUpper: Int) throws {
try self.init(throwingMiddle: throwingUpper)
}
}
struct AddressOnlyStruct : TriviallyConstructible {
let x: Any
init(lower: Int) { self.x = lower }
// CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B017AddressOnlyStructVACSi5upper_tcfC
// CHECK: bb0(%0 : $*AddressOnlyStruct, %1 : $Int, %2 : $@thin AddressOnlyStruct.Type):
// CHECK-NEXT: [[SELF:%.*]] = alloc_stack $AddressOnlyStruct
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $AddressOnlyStruct
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick AddressOnlyStruct.Type
// CHECK: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC
// CHECK-NEXT: apply [[FN]]<AddressOnlyStruct>([[SELF_BOX]], %1, [[METATYPE]])
// CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [initialization] [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: copy_addr [take] [[SELF]] to [initialization] %0
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]]
init(upper: Int) {
self.init(middle: upper)
}
init?(failingUpper: Int) {
self.init(failingMiddle: failingUpper)
}
init(throwingUpper: Int) throws {
try self.init(throwingMiddle: throwingUpper)
}
}
enum TrivialEnum : TriviallyConstructible {
case NotSoTrivial
init(lower: Int) {
self = .NotSoTrivial
}
// CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B011TrivialEnumOACSi5upper_tcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin TrivialEnum.Type):
// CHECK-NEXT: [[SELF:%.*]] = alloc_stack $TrivialEnum
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $TrivialEnum
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick TrivialEnum.Type
// CHECK: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC
// CHECK-NEXT: apply [[FN]]<TrivialEnum>([[SELF_BOX]], %0, [[METATYPE]])
// CHECK-NEXT: [[NEW_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: return [[NEW_SELF]]
init(upper: Int) {
self.init(middle: upper)
}
init?(failingUpper: Int) {
self.init(failingMiddle: failingUpper)
}
init(throwingUpper: Int) throws {
try self.init(throwingMiddle: throwingUpper)
}
}
|
apache-2.0
|
78b4c076caffce6a155da37d7eebc7d9
| 35.401316 | 119 | 0.666546 | 3.484257 | false | false | false | false |
LIFX/Argo
|
ArgoTests/Tests/TypeTests.swift
|
2
|
928
|
import XCTest
import Argo
import Runes
class TypeTests: XCTestCase {
func testAllTheTypes() {
let model: TestModel? = JSONFileReader.JSON(fromFile: "types") >>- decode
XCTAssert(model != nil)
XCTAssert(model?.int == 5)
XCTAssert(model?.string == "Cooler User")
XCTAssert(model?.double == 3.4)
XCTAssert(model?.float == 1.1)
XCTAssert(model?.bool == false)
XCTAssert(model?.intOpt != nil)
XCTAssert(model?.intOpt! == 4)
XCTAssert(model?.stringArray.count == 2)
XCTAssert(model?.stringArrayOpt == nil)
XCTAssert(model?.eStringArray.count == 2)
XCTAssert(model?.eStringArrayOpt != nil)
XCTAssert(model?.eStringArrayOpt?.count == 0)
XCTAssert(model?.userOpt != nil)
XCTAssert(model?.userOpt?.id == 6)
}
func testFailingEmbedded() {
let model: TestModel? = JSONFileReader.JSON(fromFile: "types_fail_embedded") >>- decode
XCTAssert(model == nil)
}
}
|
mit
|
e26bcbf558af08733da8ac086cc0a252
| 28.935484 | 91 | 0.668103 | 3.772358 | false | true | false | false |
manuelCarlos/AutoLayout-park
|
collectionCellLayout/collectionCellLayout/CollectionViewController.swift
|
1
|
4419
|
//
// ViewController.swift
// CollectionCellLayout
//
// Created by manuel on 10/05/16.
//
//
import UIKit
class CollectionViewController: UICollectionViewController{
// MARK: Properties
private var fontChangeObserver: AnyObject?
private let mydataSource : CollectionViewDataSource = CollectionViewDataSource()
private var status: Bool = false
private var theLayout : Layout?
//MARK:- Initialzers
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
setupCollectionViewWithDataSource( mydataSource)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupCollectionViewWithDataSource( mydataSource)
}
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 10.0, *){}
else{ prepareFontChangeObserver() }
}
// MARK:- collection view Delegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
animateCellAt(index: indexPath)
}
//MARK:- ScrollView Delegate
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y > -10 { toogleStatus(true) }
else { toogleStatus(false) }
}
//MARK:- Status bar
override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }
override var prefersStatusBarHidden: Bool { return status }
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .slide }
//MARK:- Private convenience Methods
// Animate the IOS status bar on/off from the screen.
private func toogleStatus( _ on: Bool){
UIView.animate(withDuration: 0.5, animations: {
self.status = on
self.setNeedsStatusBarAppearanceUpdate()
})
}
private func setupCollectionViewWithDataSource(_ data: UICollectionViewDataSource){
theLayout = collectionViewLayout as? Layout
collectionView?.dataSource = data
collectionView?.delegate = self
collectionView?.register(Cell.self, forCellWithReuseIdentifier: Cell.cellreuseIdentifier)
let collectionInsets = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)
collectionView?.contentInset = collectionInsets
}
// setup dynamic type obsever
private func prepareFontChangeObserver(){
let application = UIApplication.shared
let notificationCenter = NotificationCenter.default
let queue = OperationQueue.main
fontChangeObserver = notificationCenter.addObserver(forName: NSNotification.Name.UIContentSizeCategoryDidChange, object: application, queue: queue) {
[unowned self] _ in
/*
In IOS 9.x
In the cell's prepareForReuse() override, the text is updated to the user prefered size,
but not all cells are subject to that call. Reloading the collectionView when the app is
notified that the user changed the prefered front size makes sure all cells get updated.
In IOS 10.x This method is unnecessary.
The system takes care of updatting the font size if the text's property
"adjustsFontForContentSizeCategory" is set to true.
*/
self.collectionView?.reloadData()
}
}
// animate collection view cell
private func animateCellAt(index indexPath: IndexPath){
theLayout?.tappedCellIndexPath = theLayout?.tappedCellIndexPath == indexPath ? nil : indexPath
UIView.animate(
withDuration: 0.5,
delay: 0.0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 4,
options: [],
animations: {
self.theLayout?.invalidateLayout() // recalculate the layout
self.collectionView?.layoutIfNeeded() // needed to inforce the spring animation
},
completion: nil
)
}
}//ENd
|
mit
|
2bc925929cddef8a22a0db263f56fef9
| 26.277778 | 157 | 0.61575 | 5.837517 | false | false | false | false |
tmandry/Swindler
|
Sources/Window.swift
|
1
|
15909
|
import AXSwift
import Cocoa
import PromiseKit
// MARK: - Window
/// A window.
public final class Window {
internal let delegate: WindowDelegate
// A Window holds a strong reference to the Application and therefore the ApplicationDelegate.
// It should not be held internally by delegates, or it would create a reference cycle.
fileprivate var application_: Application!
internal init(delegate: WindowDelegate, application: Application) {
self.delegate = delegate
application_ = application
}
/// This initializer fails only if the ApplicationDelegate is no longer reachable (because the
/// application terminated, which means this window no longer exists), or the StateDelegate has
/// been destroyed.
internal convenience init?(delegate: WindowDelegate) {
guard let appDelegate = delegate.appDelegate else {
// The application terminated.
log.debug("Window for delegate \(delegate) failed to initialize because of unreachable "
+ "ApplicationDelegate")
return nil
}
guard let app = Application(delegate: appDelegate) else {
log.debug("Window for delegate \(delegate) failed to initialize because Application "
+ "failed to initialize")
return nil
}
self.init(delegate: delegate, application: app)
}
/// The application the window belongs to.
public var application: Application { return application_ }
/// The screen that (most of) the window is on. `nil` if the window is completely off-screen.
public var screen: Screen? {
let screenIntersectSizes =
application.swindlerState.screens.lazy
.map { screen in (screen, screen.frame.intersection(self.frame.value)) }
.filter { _, intersect in !intersect.isNull }
.map { screen, intersect in (screen, intersect.size.width * intersect.size.height) }
let bestScreen = screenIntersectSizes.max { lhs, rhs in lhs.1 < rhs.1 }?.0
return bestScreen
}
/// Whether or not the window referred to by this type remains valid. Windows usually become
/// invalid because they are destroyed (in which case a WindowDestroyedEvent will be emitted).
/// They can also become invalid because they do not have all the required properties, or
/// because the application that owns them is otherwise not giving a well-behaved response.
public var isValid: Bool { return delegate.isValid }
/// The frame of the window.
///
/// The origin of the frame is the bottom-left corner of the window in screen coordinates.
public var frame: WriteableProperty<OfType<CGRect>> { return delegate.frame }
/// The size of the window in screen coordinates.
public var size: WriteableProperty<OfType<CGSize>> { return delegate.size }
/// The window title.
public var title: Property<OfDefaultedType<String>> { return delegate.title }
/// Whether the window is minimized.
public var isMinimized: WriteableProperty<OfType<Bool>> { return delegate.isMinimized }
/// Whether the window is fullscreen or not.
public var isFullscreen: WriteableProperty<OfType<Bool>> { return delegate.isFullscreen }
}
public func ==(lhs: Window, rhs: Window) -> Bool {
return lhs.delegate.equalTo(rhs.delegate)
}
extension Window: Equatable {}
extension Window: Hashable {
public func hash(into hasher: inout Hasher) {
// We take care never to have duplicate delegates for a window.
hasher.combine(Unmanaged.passUnretained(self.delegate as AnyObject).toOpaque())
}
}
extension Window: CustomDebugStringConvertible {
public var debugDescription: String {
return "Window(\"\(title.value.truncate(length: 30))\")"
//+ "app=\(application.bundleIdentifier ?? "<unknown>"))"
}
}
extension Window: CustomStringConvertible {
public var description: String {
"\"\(title.value.truncate(length: 30))\""
}
}
extension String {
func truncate(length: Int, trailing: String = "…") -> String {
if self.count > length {
return String(self.prefix(length)) + trailing
} else {
return self
}
}
}
extension String: Defaultable {
public static func defaultValue() -> String { "" }
}
protocol WindowDelegate: AnyObject {
var isValid: Bool { get }
// Optional because a WindowDelegate shouldn't hold a strong reference to its parent
// ApplicationDelegate.
var appDelegate: ApplicationDelegate? { get }
var frame: WriteableProperty<OfType<CGRect>>! { get }
var size: SizeProperty! { get }
var title: Property<OfDefaultedType<String>>! { get }
var isMinimized: WriteableProperty<OfType<Bool>>! { get }
var isFullscreen: WriteableProperty<OfType<Bool>>! { get }
func equalTo(_ other: WindowDelegate) -> Bool
}
// MARK: - OSXWindowDelegate
/// Implements WindowDelegate using the AXUIElement API.
final class OSXWindowDelegate<
UIElement, ApplicationElement: ApplicationElementType, Observer: ObserverType
>: WindowDelegate
where Observer.UIElement == UIElement, ApplicationElement.UIElement == UIElement {
typealias Object = Window
fileprivate weak var notifier: EventNotifier?
fileprivate var initialized: Promise<Void>!
let axElement: UIElement
fileprivate(set) var isValid: Bool = true
fileprivate var watchedAxProperties: [AXSwift.AXNotification: [PropertyType]]!
weak var appDelegate: ApplicationDelegate?
var frame: WriteableProperty<OfType<CGRect>>!
var size: SizeProperty!
var title: Property<OfDefaultedType<String>>!
var isMinimized: WriteableProperty<OfType<Bool>>!
var isFullscreen: WriteableProperty<OfType<Bool>>!
private init(_ appDelegate: ApplicationDelegate,
_ notifier: EventNotifier?,
_ axElement: UIElement,
_ observer: Observer,
_ systemScreens: SystemScreenDelegate) throws {
self.appDelegate = appDelegate
self.notifier = notifier
self.axElement = axElement
// Create a promise for the attribute dictionary we'll get from getMultipleAttributes.
let (initPromise, seal) = Promise<[AXSwift.Attribute: Any]>.pending()
// Initialize all properties.
let frameDelegate = FramePropertyDelegate(axElement, initPromise, systemScreens)
frame = WriteableProperty(
frameDelegate,
withEvent: WindowFrameChangedEvent.self,
receivingObject: Window.self,
notifier: self)
size = SizeProperty(
AXPropertyDelegate(axElement, .size, initPromise),
notifier: self,
frame: frame)
title = Property(
AXPropertyDelegate(axElement, .title, initPromise),
withEvent: WindowTitleChangedEvent.self,
receivingObject: Window.self,
notifier: self)
isMinimized = WriteableProperty(
AXPropertyDelegate(axElement, .minimized, initPromise),
withEvent: WindowMinimizedChangedEvent.self,
receivingObject: Window.self,
notifier: self)
isFullscreen = WriteableProperty(
AXPropertyDelegate(axElement, .fullScreen, initPromise),
notifier: self)
let axProperties: [PropertyType] = [
size,
title,
isMinimized,
isFullscreen
]
let allProperties: [PropertyType] = axProperties + [
frame
]
// Map notifications on this element to the corresponding property.
// Note that `size` implicitly updates every time `frame` updates, so it is not listed here.
watchedAxProperties = [
.moved: [frame],
.resized: [frame, isFullscreen],
.titleChanged: [title],
.windowMiniaturized: [isMinimized],
.windowDeminiaturized: [isMinimized]
]
// Start watching for notifications.
let notifications = watchedAxProperties.keys + [
.uiElementDestroyed
]
let watched = watchWindowElement(axElement,
observer: observer,
notifications: notifications)
// Fetch attribute values.
let attributes = axProperties.map {($0.delegate as! AXPropertyDelegateType).attribute} + [
.frame,
.subrole
]
fetchAttributes(
attributes, forElement: axElement, after: watched, seal: seal
)
// Ignore windows with the "AXUnknown" role. This (undocumented) role shows up in several
// places, including Chrome tooltips and OS X fullscreen transitions.
let subroleChecked = initPromise.done { attributeValues in
if attributeValues[.subrole] as! String? == "AXUnknown" {
log.trace("Window \(axElement) has subrole AXUnknown, unwatching")
self.unwatchWindowElement(
axElement, observer: observer, notifications: notifications
).catch { error in
log.warn("Error while unwatching ignored window \(axElement): \(error)")
}
throw OSXDriverError.windowIgnored(element: axElement)
}
}
initialized = when(fulfilled: initializeProperties(allProperties).asVoid(), subroleChecked)
}
private func watchWindowElement(_ element: UIElement,
observer: Observer,
notifications: [AXNotification]) -> Promise<Void> {
return Promise<Void>.value(()).done(on: .global()) {
for notification in notifications {
try traceRequest(self.axElement, "addNotification", notification) {
try observer.addNotification(notification, forElement: self.axElement)
}
}
}
}
private func unwatchWindowElement(_ element: UIElement,
observer: Observer,
notifications: [AXNotification]) -> Promise<Void> {
return Promise<Void>.value(()).done(on: .global()) {
for notification in notifications {
try traceRequest(self.axElement, "removeNotification", notification) {
try observer.removeNotification(notification, forElement: self.axElement)
}
}
}
}
func equalTo(_ rhs: WindowDelegate) -> Bool {
if let other = rhs as? OSXWindowDelegate {
return axElement == other.axElement
} else {
return false
}
}
}
/// Interface used by OSXApplicationDelegate.
extension OSXWindowDelegate {
/// Initializes the window, and returns it in a Promise once it's ready.
static func initialize(
appDelegate: ApplicationDelegate,
notifier: EventNotifier?,
axElement: UIElement,
observer: Observer,
systemScreens: SystemScreenDelegate
) -> Promise<OSXWindowDelegate> {
return firstly { () -> Promise<OSXWindowDelegate> in // capture thrown errors in promise
let window = try OSXWindowDelegate(
appDelegate, notifier, axElement, observer, systemScreens)
return window.initialized.map { window }
}
}
func handleEvent(_ event: AXSwift.AXNotification, observer: Observer) {
switch event {
case .uiElementDestroyed:
isValid = false
default:
if let properties = watchedAxProperties[event] {
properties.forEach { $0.issueRefresh() }
} else {
log.debug("Unknown event on \(self): \(event)")
}
}
}
}
extension OSXWindowDelegate: PropertyNotifier {
func notify<Event: PropertyEventType>(
_ event: Event.Type,
external: Bool,
oldValue: Event.PropertyType,
newValue: Event.PropertyType
) where Event.Object == Window {
guard let window = Window(delegate: self) else {
// Application terminated already; shouldn't send events.
return
}
notifier?.notify(
Event(external: external, object: window, oldValue: oldValue, newValue: newValue)
)
}
func notifyInvalid() {
isValid = false
}
}
// MARK: PropertyDelegates
/// PropertyAdapter that inverts the y-axis of the point value.
///
/// This is to convert between AXPosition coordinates, which have the origin at
/// the top-left, and Cocoa coordinates, which have it at the bottom-left.
private final class FramePropertyDelegate<UIElement: UIElementType>: PropertyDelegate {
typealias T = CGRect
let frame: AXPropertyDelegate<CGRect, UIElement>
let pos: AXPropertyDelegate<CGPoint, UIElement>
let size: AXPropertyDelegate<CGSize, UIElement>
let systemScreens: SystemScreenDelegate
typealias InitDict = [AXSwift.Attribute: Any]
init(_ element: UIElement, _ initPromise: Promise<InitDict>, _ screens: SystemScreenDelegate) {
frame = AXPropertyDelegate<CGRect, UIElement>(element, .frame, initPromise)
pos = AXPropertyDelegate<CGPoint, UIElement>(element, .position, initPromise)
size = AXPropertyDelegate<CGSize, UIElement>(element, .size, initPromise)
systemScreens = screens
}
func readValue() throws -> T? {
guard let rect = try frame.readValue() else { return nil }
return invert(rect)
}
func writeValue(_ newValue: T) throws {
let rect = invert(newValue)
try pos.writeValue(rect.origin)
try size.writeValue(rect.size)
}
func initialize() -> Promise<T?> {
return frame.initialize().map { rect in
rect.map{ self.invert($0) }
}
}
private func invert(_ rect: CGRect) -> CGRect {
let inverted = CGPoint(x: rect.minX, y: systemScreens.maxY - rect.maxY)
return CGRect(origin: inverted, size: rect.size)
}
}
// MARK: SizeProperty
/// Custom Property class for the `size` property.
///
/// Does not use the backing store at all; delegates to `frame` instead for all reads. This ensures
/// that `frame` and `size` are always consistent with each other.
///
/// The purpose of this property is to support atomic writes to the `size` attribute of a window.
final class SizeProperty: WriteableProperty<OfType<CGSize>> {
let frame: WriteableProperty<OfType<CGRect>>
init<Impl: PropertyDelegate, Notifier: PropertyNotifier>(
_ delegate: Impl, notifier: Notifier, frame: WriteableProperty<OfType<CGRect>>
) where Impl.T == NonOptionalType {
self.frame = frame
super.init(delegate, notifier: notifier)
}
override func initialize<Impl: PropertyDelegate>(_ delegate: Impl) -> Promise<Void> {
return frame.initialized
}
override func getValue() -> PropertyType {
return frame.value.size
}
@discardableResult
public override func refresh() -> Promise<PropertyType> {
return frame.refresh().map { rect in
return rect.size
}
}
public override func set(_ newValue: NonOptionalType) -> Promise<PropertyType> {
// Because we don't have a WindowSizeChangedEvent, we don't have to worry about our own
// events. However, the frame does need to know that we are mutating it from within
// Swindler, so events are correctly marked as internal.
return frame.mutateWith() {
let orig = self.frame.value
try self.delegate_.writeValue(newValue)
return CGRect(origin: orig.origin, size: newValue)
}.map { rect in
return rect.size
}
}
}
|
mit
|
2dbfb52a9419db41fa015a43cffea57a
| 36.605201 | 100 | 0.639844 | 5.078863 | false | false | false | false |
lipoyang/GPPropo-iOS
|
GPPropo/GPPropo/MyButton.swift
|
1
|
1338
|
//
// MyButton.swift
// GPPropo
//
// Created by Bizan Nishimura on 2016/05/29.
// Copyright (C)2016 Bizan Nishimura. All rights reserved.
//
import UIKit
@IBDesignable
class MyButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
common_init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
common_init()
}
func common_init()
{
self.layer.cornerRadius = 8.0
//self.layer.borderColor = UIColor.blackColor().CGColor
self.layer.borderColor = UIColor.lightGrayColor().CGColor
//self.layer.borderColor = UIColor(red:0.0, green:122/255.0, blue:1.0, alpha:1.0).CGColor
self.layer.borderWidth = 1.0
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override func drawRect(rect: CGRect)
{
/*
self.layer.cornerRadius = 10.0
//self.layer.borderColor = UIColor.blackColor().CGColor
self.layer.borderColor = UIColor(red:0.0, green:122/255.0, blue:1.0, alpha:1.0).CGColor
self.layer.borderWidth = 1.0
*/
super.drawRect(rect);
}
}
|
apache-2.0
|
232f93175e14492f6a7d770e94da519c
| 25.235294 | 97 | 0.615097 | 3.790368 | false | false | false | false |
jakubknejzlik/ChipmunkSwiftWrapper
|
Pod/Classes/ChipmunkShape.swift
|
1
|
4342
|
//
// ChipmunkShape.swift
// Pods
//
// Created by Jakub Knejzlik on 15/11/15.
//
//
import Foundation
public class ChipmunkShape: ChipmunkSpaceObject {
weak var body: ChipmunkBody?
let shape: UnsafeMutablePointer<cpShape>
override var space: ChipmunkSpace? {
willSet {
if let space = self.space {
cpSpaceRemoveShape(space.space, self.shape)
}
}
didSet {
if let space = self.space {
if let body = self.body where body.isStatic {
cpSpaceAddStaticShape(space.space, self.shape)
} else {
cpSpaceAddShape(space.space, self.shape)
}
}
}
}
/** A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.*/
public var sensor: Bool {
get {
return Bool(cpShapeGetSensor(shape))
}
set(value) {
cpShapeSetSensor(shape, value.cpBool())
}
}
/** Elasticity of the shape. A value of 0.0 gives no bounce, while a value of 1.0 will give a “perfect” bounce. However due to inaccuracies in the simulation using 1.0 or greater is not recommended however. The elasticity for a collision is found by multiplying the elasticity of the individual shapes together. */
public var elasticity: Double {
get {
return Double(cpShapeGetElasticity(shape))
}
set(value) {
cpShapeSetElasticity(shape, cpFloat(value))
}
}
/** Friction coefficient. Chipmunk uses the Coulomb friction model, a value of 0.0 is frictionless. The friction for a collision is found by multiplying the friction of the individual shapes together. */
public var friction: Double {
get {
return Double(cpShapeGetFriction(shape))
}
set(value) {
cpShapeSetFriction(shape, cpFloat(value))
}
}
/** The surface velocity of the object. Useful for creating conveyor belts or players that move around. This value is only used when calculating friction, not resolving the collision. */
public var surfaceVelocity: CGPoint {
get {
return cpShapeGetSurfaceVelocity(shape)
}
set(value) {
cpShapeSetSurfaceVelocity(shape, value)
}
}
/** You can assign types to Chipmunk collision shapes that trigger callbacks when objects of certain types touch.*/
public var collisionType: AnyObject {
get {
return UnsafeMutablePointer<AnyObject>(bitPattern: cpShapeGetCollisionType(shape)).memory
}
set(value) {
let pointer = unsafeAddressOf(value)
cpShapeSetCollisionType(shape, pointer.getUIntValue())
}
}
/** Shapes in the same non-zero group do not generate collisions. Useful when creating an object out of many shapes that you don’t want to self collide. Defaults to CP_NO_GROUP. */
public var group: AnyObject {
get {
return UnsafeMutablePointer<AnyObject>(bitPattern: cpShapeGetGroup(shape)).memory
}
set(value) {
let pointer = unsafeAddressOf(value)
cpShapeSetGroup(shape, pointer.getUIntValue())
}
}
/** Shapes only collide if they are in the same bit-planes. i.e. (a->layers & b->layers) != 0 By default, a shape occupies all bit-planes. */
public var layers: UInt {
get {
return UInt(cpShapeGetLayers(shape))
}
set(value) {
cpShapeSetLayers(shape, UInt32(value))
}
}
init(body: ChipmunkBody, shape: UnsafeMutablePointer<cpShape>) {
self.body = body
self.shape = shape
super.init()
cpShapeSetUserData(shape, UnsafeMutablePointer<ChipmunkShape>(unsafeAddressOf(self)))
body.addShape(self)
}
public convenience init(body: ChipmunkBody, radius: Double, offset: CGPoint) {
self.init(body: body, shape: cpCircleShapeNew(body.body, cpFloat(radius), offset))
}
public convenience init(body: ChipmunkBody, size: CGSize) {
self.init(body: body, shape: cpBoxShapeNew(body.body, cpFloat(size.width), cpFloat(size.height)))
}
}
|
mit
|
52e47ac3e6a55e3d09cffd1fb77c4d35
| 35.141667 | 318 | 0.620849 | 4.474716 | false | false | false | false |
angelodipaolo/Bobomb
|
Bobomb/Models/Platform.swift
|
1
|
620
|
//
// Platform.swift
// Bobomb
//
// Created by Angelo Di Paolo on 5/31/15.
// Copyright (c) 2015 Angelo Di Paolo. All rights reserved.
//
import Foundation
public struct Platform: Codable {
public var id: Int
public var name: String
public var abbreviation: String
public var siteDetailURLString: String
public var apiDetailURLString: String
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case abbreviation = "abbreviation"
case siteDetailURLString = "site_detail_url"
case apiDetailURLString = "api_detail_url"
}
}
|
mit
|
22e8f52186e51e0befbbec6a30ba0547
| 23.8 | 60 | 0.659677 | 4.052288 | false | false | false | false |
oleander/bitbar
|
Sources/Plugin/Classifier.swift
|
1
|
989
|
import PathKit
class Classifier {
weak var delegate: Manageable?
private let path: Path
private let args: [String]
private let env: Env
init(path: Path, args: [String], env: Env) {
self.env = env
self.args = args
self.path = path
}
func plugin() throws -> Pluginable {
switch try name() {
case "stream":
return stream()
case let type:
return interval(try Unit.parser(type))
}
}
private func name() throws -> String {
let parts = try path.fileName().split(".")
guard parts.count == 3 else {
throw ClassifierError.invalidParts(path)
}
return parts[1]
}
private func interval(_ frequency: Double) -> Pluginable {
return Interval(
path: path,
frequency: Int(frequency),
args: args,
env: env,
delegate: delegate
)
}
private func stream() -> Pluginable {
return Stream(
path: path,
args: args,
env: env,
delegate: delegate
)
}
}
|
mit
|
ddb102258caf0525a7a1e30c13946048
| 18.78 | 60 | 0.595551 | 3.909091 | false | false | false | false |
tourani/GHIssue
|
OAuth2PodApp/OAuth2RetryHandler.swift
|
1
|
2052
|
//
// OAuth2RetryHandler.swift
// OAuth2PodApp
//
//
//
import Foundation
import p2_OAuth2
import Alamofire
/**
An adapter for Alamofire. Set up your OAuth2 instance as usual, without forgetting to implement `handleRedirectURL()`, instantiate **one**
`SessionManager` and use this class as the manager's `adapter` and `retrier`, like so:
let oauth2 = OAuth2CodeGrant(settings: [...])
oauth2.authConfig.authorizeEmbedded = true // if you want embedded
oauth2.authConfig.authorizeContext = <# your UIViewController / NSWindow #>
let sessionManager = SessionManager()
let retrier = OAuth2RetryHandler(oauth2: oauth2)
sessionManager.adapter = retrier
sessionManager.retrier = retrier
self.alamofireManager = sessionManager
sessionManager.request("https://api.github.com/user").validate().responseJSON { response in
debugPrint(response)
}
*/
class OAuth2RetryHandler: RequestRetrier, RequestAdapter {
let loader: OAuth2DataLoader
init(oauth2: OAuth2) {
loader = OAuth2DataLoader(oauth2: oauth2)
}
/// Intercept 401 and do an OAuth2 authorization.
public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
if let response = request.task?.response as? HTTPURLResponse, 401 == response.statusCode, let req = request.request {
var dataRequest = OAuth2DataRequest(request: req, callback: { _ in })
dataRequest.context = completion
loader.enqueue(request: dataRequest)
loader.attemptToAuthorize() { authParams, error in
self.loader.dequeueAndApply() { req in
if let comp = req.context as? RequestRetryCompletion {
comp(nil != authParams, 0.0)
}
}
}
}
else {
completion(false, 0.0) // not a 401, not our problem
}
}
/// Sign the request with the access token.
public func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
guard nil != loader.oauth2.accessToken else {
return urlRequest
}
return urlRequest.signed(with: loader.oauth2)
}
}
|
mit
|
a825b8c78866472dd0da319a13488fa2
| 30.090909 | 138 | 0.717349 | 3.93858 | false | false | false | false |
Molbie/Outlaw-SpriteKit
|
Sources/OutlawSpriteKit/Enums/SKLabelVerticalAlignmentMode+String.swift
|
1
|
1417
|
//
// SKLabelVerticalAlignmentMode+String.swift
// OutlawSpriteKit
//
// Created by Brian Mullen on 12/16/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import SpriteKit
public extension SKLabelVerticalAlignmentMode {
struct StringValues {
public static let baseline = "baseline"
public static let center = "center"
public static let top = "top"
public static let bottom = "bottom"
}
private typealias strings = SKLabelVerticalAlignmentMode.StringValues
}
public extension SKLabelVerticalAlignmentMode {
init?(stringValue: String) {
switch stringValue.lowercased() {
case strings.baseline:
self = .baseline
case strings.center:
self = .center
case strings.top:
self = .top
case strings.bottom:
self = .bottom
default:
return nil
}
}
var stringValue: String {
let result: String
switch self {
case .baseline:
result = strings.baseline
case .center:
result = strings.center
case .top:
result = strings.top
case .bottom:
result = strings.bottom
@unknown default:
fatalError()
}
return result
}
}
|
mit
|
0f510564b8c8bb0df730b834596d3a72
| 24.745455 | 73 | 0.54661 | 5.244444 | false | false | false | false |
jondwillis/ReactiveReSwift-Router
|
ReactiveReSwiftRouter/NavigationActions.swift
|
1
|
1274
|
//
// NavigationAction.swift
// Meet
//
// Created by Benjamin Encz on 11/27/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import ReactiveReSwift
/// Exports the type map needed for using ReSwiftRouter with a Recording Store
public let typeMap: [String: StandardActionConvertible.Type] =
["RE_SWIFT_ROUTER_SET_ROUTE": SetRouteAction.self]
public struct SetRouteAction: StandardActionConvertible {
let route: Route
let animated: Bool
public static let type = "RE_SWIFT_ROUTER_SET_ROUTE"
public init (_ route: Route, animated: Bool = true) {
self.route = route
self.animated = animated
}
public init(_ action: StandardAction) {
self.route = action.payload!["route"] as! Route
self.animated = action.payload!["animated"] as! Bool
}
public func toStandardAction() -> StandardAction {
return StandardAction(
type: SetRouteAction.type,
payload: ["route": route as AnyObject, "animated": animated as AnyObject],
isTypedAction: true
)
}
}
public struct SetRouteSpecificData: Action {
let route: Route
let data: Any
public init(route: Route, data: Any) {
self.route = route
self.data = data
}
}
|
mit
|
306b5a2d6388e5f2390fcb2f70e9b0d9
| 24.979592 | 86 | 0.649647 | 4.215232 | false | false | false | false |
openhab/openhab.ios
|
OpenHABCore/Sources/OpenHABCore/Model/NumberState.swift
|
1
|
1800
|
// Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import Foundation
public struct NumberState: CustomStringConvertible, Equatable {
public var description: String {
toString(locale: Locale.current)
}
public var value: Double
private(set) var unit: String? = ""
private(set) var format: String? = ""
// Access to default memberwise initializer not permitted outside of package
public init(value: Double, unit: String? = "", format: String? = "") {
self.value = value
self.unit = unit
self.format = format
}
public func toString(locale: Locale?) -> String {
if let format = format, format.isEmpty == false {
let actualFormat = format.replacingOccurrences(of: "%unit%", with: unit ?? "")
if format.contains("%d") == true {
return String(format: actualFormat, locale: locale, Int(value))
} else {
return String(format: actualFormat, locale: locale, value)
}
}
if let unit = unit, unit.isEmpty == false {
return "\(formatValue()) \(unit)"
} else {
return formatValue()
}
}
public func formatValue() -> String {
String(value)
}
private func getActualValue() -> NSNumber {
if format?.contains("%d") == true {
return NSNumber(value: Int(value))
} else {
return NSNumber(value: value)
}
}
}
|
epl-1.0
|
1e19f35ae1785d3830ed60f3fa716dc9
| 30.578947 | 90 | 0.602778 | 4.433498 | false | false | false | false |
bugsnag/bugsnag-cocoa
|
features/fixtures/shared/scenarios/OnErrorOverwriteScenario.swift
|
1
|
943
|
//
// OnErrorOverwriteScenario.swift
// iOSTestApp
//
// Created by Jamie Lynch on 26/05/2020.
// Copyright © 2020 Bugsnag. All rights reserved.
//
import Foundation
/**
* Verifies that an OnErrorCallback can overwrite information for a handled error
*/
class OnErrorOverwriteScenario : Scenario {
override func startBugsnag() {
self.config.autoTrackSessions = false;
super.startBugsnag()
}
override func run() {
let error = NSError(domain: "HandledErrorScenario", code: 100, userInfo: nil)
Bugsnag.notifyError(error) { (event) -> Bool in
event.app.id = "customAppId"
event.context = "customContext"
event.device.id = "customDeviceId"
event.groupingHash = "customGroupingHash"
event.severity = .info
event.setUser("customId", withEmail: "customEmail", andName: "customName")
return true
}
}
}
|
mit
|
3570d8741adc2e8912db53446072e90d
| 28.4375 | 86 | 0.635881 | 4.168142 | false | false | false | false |
dani5447/node-ios-chat-prototype
|
ios-chat/SocketIOClientSwift/SocketParser.swift
|
2
|
6862
|
//
// SocketParser.swift
// Socket.IO-Client-Swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class SocketParser {
private static func isCorrectNamespace(nsp: String, _ socket: SocketIOClient) -> Bool {
return nsp == socket.nsp
}
private static func handleConnect(p: SocketPacket, socket: SocketIOClient) {
if p.nsp == "/" && socket.nsp != "/" {
socket.joinNamespace()
} else if p.nsp != "/" && socket.nsp == "/" {
socket.didConnect()
} else {
socket.didConnect()
}
}
private static func handlePacket(pack: SocketPacket, withSocket socket: SocketIOClient) {
switch pack.type {
case .Event where isCorrectNamespace(pack.nsp, socket):
socket.handleEvent(pack.event, data: pack.args ?? [],
isInternalMessage: false, wantsAck: pack.id)
case .Ack where isCorrectNamespace(pack.nsp, socket):
socket.handleAck(pack.id, data: pack.data)
case .BinaryEvent where isCorrectNamespace(pack.nsp, socket):
socket.waitingData.append(pack)
case .BinaryAck where isCorrectNamespace(pack.nsp, socket):
socket.waitingData.append(pack)
case .Connect:
handleConnect(pack, socket: socket)
case .Disconnect:
socket.didDisconnect("Got Disconnect")
case .Error:
socket.didError(pack.data)
default:
Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
}
}
static func parseString(message: String) -> Either<String, SocketPacket> {
var parser = SocketStringReader(message: message)
guard let type = SocketPacket.PacketType(str: parser.read(1)) else {
return .Left("Invalid packet type")
}
if !parser.hasNext {
return .Right(SocketPacket(type: type, nsp: "/"))
}
var namespace: String?
var placeholders = -1
if type == .BinaryEvent || type == .BinaryAck {
if let holders = Int(parser.readUntilStringOccurence("-")) {
placeholders = holders
} else {
return .Left("Invalid packet")
}
}
if parser.currentCharacter == "/" {
namespace = parser.readUntilStringOccurence(",") ?? parser.readUntilEnd()
}
if !parser.hasNext {
return .Right(SocketPacket(type: type, id: -1,
nsp: namespace ?? "/", placeholders: placeholders))
}
var idString = ""
if type == .Error {
parser.advanceIndexBy(-1)
}
while parser.hasNext && type != .Error {
if let int = Int(parser.read(1)) {
idString += String(int)
} else {
parser.advanceIndexBy(-2)
break
}
}
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
switch parseData(noPlaceholders) {
case .Left(let err):
// If first you don't succeed, try again
if case let .Right(data) = parseData("\([noPlaceholders as AnyObject])") {
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace ?? "/", placeholders: placeholders))
} else {
return .Left(err)
}
case .Right(let data):
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace ?? "/", placeholders: placeholders))
}
}
// Parses data for events
private static func parseData(data: String) -> Either<String, [AnyObject]> {
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do {
if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
return .Right(arr)
} else {
return .Left("Expected data array")
}
} catch {
return .Left("Error parsing data for packet")
}
}
// Parses messages recieved
static func parseSocketMessage(message: String, socket: SocketIOClient) {
guard !message.isEmpty else { return }
Logger.log("Parsing %@", type: "SocketParser", args: message)
switch parseString(message) {
case .Left(let err):
Logger.error("\(err): %@", type: "SocketParser", args: message)
case .Right(let pack):
Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
handlePacket(pack, withSocket: socket)
}
}
static func parseBinaryData(data: NSData, socket: SocketIOClient) {
guard !socket.waitingData.isEmpty else {
Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
// Should execute event?
guard socket.waitingData[socket.waitingData.count - 1].addData(data) else {
return
}
var packet = socket.waitingData.removeLast()
packet.fillInPlaceholders()
if packet.type != .BinaryAck {
socket.handleEvent(packet.event, data: packet.args ?? [],
isInternalMessage: false, wantsAck: packet.id)
} else {
socket.handleAck(packet.id, data: packet.args)
}
}
}
|
mit
|
8e0d44e2b41af99c83a6e72d8035929c
| 37.550562 | 98 | 0.583066 | 4.748789 | false | false | false | false |
hengZhuo/DouYuZhiBo
|
swift-DYZB/swift-DYZB/Classes/Main/Model/AnchorGroup.swift
|
1
|
1347
|
//
// AnchorGroup.swift
// swift-DYZB
//
// Created by chenrin on 2016/11/16.
// Copyright © 2016年 zhuoheng. All rights reserved.
//
import UIKit
class AnchorGroup: NSObject {
//该组中对应的房间信息
var room_list : [[String:NSObject]]?{
didSet{
guard let room_list = room_list else {
return
}
for dict in room_list{
anchors.append(AnchorModel(dict: dict))
}
}
}
//该组显示的标题
var tag_name : String = ""
//该组显示的图标
var icon_name : String = "home_header_normal"
//游戏对应的图标
var icon_url : String = ""
//定义主播的模型对象的数组
lazy var anchors:[AnchorModel] = [AnchorModel]()
//构造函数
override init() {
}
init(dict:[String : NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
/*
override func setValue(_ value: Any?, forKey key: String) {
if key == "room_list"{
if let dataArray = value as? [[String:NSObject]]{
for dict in dataArray{
anchors.append(AnchorModel(dict: dict))
}
}
}
*/
}
|
mit
|
27d12b1dfcbbfb00357374d202a27d6e
| 20.929825 | 72 | 0.5144 | 4.139073 | false | false | false | false |
stuffmc/RealmCloudKit
|
Example/Pods/Internet/Pod/Classes/Internet.swift
|
1
|
2106
|
import ReachabilitySwift
public class Internet
{
public class Change
{
private let block: (Reachability.NetworkStatus) -> Void
public init(block: (Reachability.NetworkStatus) -> Void)
{
self.block = block
}
public func run(status: Reachability.NetworkStatus)
{
self.block(status)
}
}
internal static var reachability: Reachability!
private static var blocks: [Change] = []
public static func start(hostName: String) throws
{
try Internet.start(Reachability(hostname: hostName))
}
public static func start(reachability: Reachability) throws
{
Internet.reachability = reachability
let statusBlock = { (reachability: Reachability) -> Void in
let status = reachability.currentReachabilityStatus
for block in Internet.blocks {
block.run(status)
}
}
Internet.reachability.whenReachable = statusBlock
Internet.reachability.whenUnreachable = statusBlock
try Internet.reachability.startNotifier()
}
public static func start() throws
{
try Internet.start(Reachability.reachabilityForInternetConnection())
}
public static func pause()
{
Internet.reachability.stopNotifier()
}
public static func addChangeBlock(block: (Reachability.NetworkStatus) -> Void) -> Internet.Change
{
let result = Internet.Change(block: block)
Internet.blocks.append(result)
return result
}
public static func removeChangeBlock(block: Internet.Change)
{
Internet.blocks -= block
}
public static func areYouThere() -> Bool
{
return Internet.reachability.currentReachabilityStatus != .NotReachable
}
}
private func -=(inout lhs: [Internet.Change], rhs: Internet.Change)
{
var result: [Internet.Change] = []
for element in lhs {
if element !== rhs {
result.append(element)
}
}
lhs = result
}
|
mit
|
797864530c6c5b62bbaa079f6f535878
| 25.325 | 101 | 0.614435 | 5.161765 | false | false | false | false |
matthewelse/experiments
|
monte.swift
|
1
|
454
|
import Foundation
var inside = 0
var total = 0
let radius = 300.0
let radius_sq = radius * radius
while true {
let x = ((Double(arc4random())/Double(UInt32.max)) * 2.0 * radius) - radius
let y = ((Double(arc4random())/Double(UInt32.max)) * 2.0 * radius) - radius
if (x*x + y*y < radius_sq) {
inside++
}
total++
if (total % 100000000 == 0) {
let pi: Double = 4*Double(inside)/Double(total)
println("\(total) (\(inside)): \(pi)")
}
}
|
mit
|
5aaf52c153b49482d4cf38120c3e355a
| 18.73913 | 76 | 0.605727 | 2.751515 | false | false | false | false |
firebase/snippets-ios
|
firestore/swift/firestore-smoketest/ViewController.swift
|
1
|
44360
|
//
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebaseCore
import FirebaseFirestore
import FirebaseFirestoreSwift
class ViewController: UIViewController {
var db: Firestore!
override func viewDidLoad() {
super.viewDidLoad()
// [START setup]
let settings = FirestoreSettings()
Firestore.firestore().settings = settings
// [END setup]
db = Firestore.firestore()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func didTouchSmokeTestButton(_ sender: AnyObject) {
// Quickstart
addAdaLovelace()
addAlanTuring()
getCollection()
listenForUsers()
// Structure Data
demonstrateReferences()
// Save Data
setDocument()
dataTypes()
setData()
addDocument()
newDocument()
updateDocument()
createIfMissing()
updateDocumentNested()
deleteDocument()
deleteCollection()
deleteField()
serverTimestamp()
serverTimestampOptions()
simpleTransaction()
transaction()
writeBatch()
// Retrieve Data
exampleData()
exampleDataCollectionGroup()
getDocument()
customClassGetDocument()
listenDocument()
listenDocumentLocal()
listenWithMetadata()
getMultiple()
getMultipleAll()
listenMultiple()
listenDiffs()
listenState()
detachListener()
handleListenErrors()
// Query Data
simpleQueries()
exampleFilters()
onlyCapitals()
chainFilters()
validRangeFilters()
// IN Queries
arrayContainsAnyQueries()
inQueries()
// Can't run this since it throws a fatal error
// invalidRangeFilters()
orderAndLimit()
orderAndLimitDesc()
orderMultiple()
filterAndOrder()
validFilterAndOrder()
// Can't run this since it throws a fatal error
// invalidFilterAndOrder()
// Enable Offline
// Can't run this since it throws a fatal error
// enableOffline()
listenToOffline()
toggleOffline()
setupCacheSize()
// Cursors
simpleCursor()
snapshotCursor()
paginate()
multiCursor()
}
@IBAction func didTouchDeleteButton(_ sender: AnyObject) {
deleteCollection(collection: "users")
deleteCollection(collection: "cities")
}
private func deleteCollection(collection: String) {
db.collection(collection).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
return
}
for document in querySnapshot!.documents {
print("Deleting \(document.documentID) => \(document.data())")
document.reference.delete()
}
}
}
private func setupCacheSize() {
// [START fs_setup_cache]
let settings = Firestore.firestore().settings
settings.cacheSizeBytes = FirestoreCacheSizeUnlimited
Firestore.firestore().settings = settings
// [END fs_setup_cache]
}
// =======================================================================================
// ======== https://firebase.google.com/preview/firestore/client/quickstart ==============
// =======================================================================================
private func addAdaLovelace() {
// [START add_ada_lovelace]
// Add a new document with a generated ID
var ref: DocumentReference? = nil
ref = db.collection("users").addDocument(data: [
"first": "Ada",
"last": "Lovelace",
"born": 1815
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
// [END add_ada_lovelace]
}
private func addAlanTuring() {
var ref: DocumentReference? = nil
// [START add_alan_turing]
// Add a second document with a generated ID.
ref = db.collection("users").addDocument(data: [
"first": "Alan",
"middle": "Mathison",
"last": "Turing",
"born": 1912
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
// [END add_alan_turing]
}
private func getCollection() {
// [START get_collection]
db.collection("users").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}
// [END get_collection]
}
private func listenForUsers() {
// [START listen_for_users]
// Listen to a query on a collection.
//
// We will get a first snapshot with the initial results and a new
// snapshot each time there is a change in the results.
db.collection("users")
.whereField("born", isLessThan: 1900)
.addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error retreiving snapshots \(error!)")
return
}
print("Current users born before 1900: \(snapshot.documents.map { $0.data() })")
}
// [END listen_for_users]
}
// =======================================================================================
// ======= https://firebase.google.com/preview/firestore/client/structure-data ===========
// =======================================================================================
private func demonstrateReferences() {
// [START doc_reference]
let alovelaceDocumentRef = db.collection("users").document("alovelace")
// [END doc_reference]
print(alovelaceDocumentRef)
// [START collection_reference]
let usersCollectionRef = db.collection("users")
// [END collection_reference]
print(usersCollectionRef)
// [START subcollection_reference]
let messageRef = db
.collection("rooms").document("roomA")
.collection("messages").document("message1")
// [END subcollection_reference]
print(messageRef)
// [START path_reference]
let aLovelaceDocumentReference = db.document("users/alovelace")
// [END path_reference]
print(aLovelaceDocumentReference)
}
// =======================================================================================
// ========= https://firebase.google.com/preview/firestore/client/save-data ==============
// =======================================================================================
private func setDocument() {
// [START set_document]
// Add a new document in collection "cities"
db.collection("cities").document("LA").setData([
"name": "Los Angeles",
"state": "CA",
"country": "USA"
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
// [END set_document]
}
private func setDocumentWithCodable() {
// [START set_document_codable]
let city = City(name: "Los Angeles",
state: "CA",
country: "USA",
isCapital: false,
population: 5000000)
do {
try db.collection("cities").document("LA").setData(from: city)
} catch let error {
print("Error writing city to Firestore: \(error)")
}
// [END set_document_codable]
}
private func dataTypes() {
// [START data_types]
let docData: [String: Any] = [
"stringExample": "Hello world!",
"booleanExample": true,
"numberExample": 3.14159265,
"dateExample": Timestamp(date: Date()),
"arrayExample": [5, true, "hello"],
"nullExample": NSNull(),
"objectExample": [
"a": 5,
"b": [
"nested": "foo"
]
]
]
db.collection("data").document("one").setData(docData) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
// [END data_types]
}
private func setData() {
let data: [String: Any] = [:]
// [START set_data]
db.collection("cities").document("new-city-id").setData(data)
// [END set_data]
}
private func addDocument() {
// [START add_document]
// Add a new document with a generated id.
var ref: DocumentReference? = nil
ref = db.collection("cities").addDocument(data: [
"name": "Tokyo",
"country": "Japan"
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
// [END add_document]
}
private func newDocument() {
// [START new_document]
let newCityRef = db.collection("cities").document()
// later...
newCityRef.setData([
// [START_EXCLUDE]
"name": "Some City Name"
// [END_EXCLUDE]
])
// [END new_document]
}
private func updateDocument() {
// [START update_document]
let washingtonRef = db.collection("cities").document("DC")
// Set the "capital" field of the city 'DC'
washingtonRef.updateData([
"capital": true
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}
// [END update_document]
}
private func updateDocumentArray() {
// [START update_document_array]
let washingtonRef = db.collection("cities").document("DC")
// Atomically add a new region to the "regions" array field.
washingtonRef.updateData([
"regions": FieldValue.arrayUnion(["greater_virginia"])
])
// Atomically remove a region from the "regions" array field.
washingtonRef.updateData([
"regions": FieldValue.arrayRemove(["east_coast"])
])
// [END update_document_array]
}
private func updateDocumentIncrement() {
// [START update_document-increment]
let washingtonRef = db.collection("cities").document("DC")
// Atomically increment the population of the city by 50.
// Note that increment() with no arguments increments by 1.
washingtonRef.updateData([
"population": FieldValue.increment(Int64(50))
])
// [END update_document-increment]
}
private func createIfMissing() {
// [START create_if_missing]
// Update one field, creating the document if it does not exist.
db.collection("cities").document("BJ").setData([ "capital": true ], merge: true)
// [END create_if_missing]
}
private func updateDocumentNested() {
// [START update_document_nested]
// Create an initial document to update.
let frankDocRef = db.collection("users").document("frank")
frankDocRef.setData([
"name": "Frank",
"favorites": [ "food": "Pizza", "color": "Blue", "subject": "recess" ],
"age": 12
])
// To update age and favorite color:
db.collection("users").document("frank").updateData([
"age": 13,
"favorites.color": "Red"
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}
// [END update_document_nested]
}
private func deleteDocument() {
// [START delete_document]
db.collection("cities").document("DC").delete() { err in
if let err = err {
print("Error removing document: \(err)")
} else {
print("Document successfully removed!")
}
}
// [END delete_document]
}
private func deleteCollection() {
// [START delete_collection]
func delete(collection: CollectionReference, batchSize: Int = 100, completion: @escaping (Error?) -> ()) {
// Limit query to avoid out-of-memory errors on large collections.
// When deleting a collection guaranteed to fit in memory, batching can be avoided entirely.
collection.limit(to: batchSize).getDocuments { (docset, error) in
// An error occurred.
guard let docset = docset else {
completion(error)
return
}
// There's nothing to delete.
guard docset.count > 0 else {
completion(nil)
return
}
let batch = collection.firestore.batch()
docset.documents.forEach { batch.deleteDocument($0.reference) }
batch.commit { (batchError) in
if let batchError = batchError {
// Stop the deletion process and handle the error. Some elements
// may have been deleted.
completion(batchError)
} else {
delete(collection: collection, batchSize: batchSize, completion: completion)
}
}
}
}
// [END delete_collection]
}
private func deleteField() {
// [START delete_field]
db.collection("cities").document("BJ").updateData([
"capital": FieldValue.delete(),
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}
// [END delete_field]
}
private func serverTimestamp() {
// [START server_timestamp]
db.collection("objects").document("some-id").updateData([
"lastUpdated": FieldValue.serverTimestamp(),
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}
// [END server_timestamp]
}
private func serverTimestampOptions() {
// [START server_timestamp_options]
// Perform an update followed by an immediate read without waiting for the update to
// complete. Due to the snapshot options we will get two results: one with an estimated
// timestamp and one with a resolved server timestamp.
let docRef = db.collection("objects").document("some-id")
docRef.updateData(["timestamp": FieldValue.serverTimestamp()])
docRef.addSnapshotListener { (snapshot, error) in
guard let timestamp = snapshot?.data(with: .estimate)?["timestamp"] else { return }
guard let pendingWrites = snapshot?.metadata.hasPendingWrites else { return }
print("Timestamp: \(timestamp), pending: \(pendingWrites)")
}
// [END server_timestamp_options]
}
private func simpleTransaction() {
// [START simple_transaction]
let sfReference = db.collection("cities").document("SF")
db.runTransaction({ (transaction, errorPointer) -> Any? in
let sfDocument: DocumentSnapshot
do {
try sfDocument = transaction.getDocument(sfReference)
} catch let fetchError as NSError {
errorPointer?.pointee = fetchError
return nil
}
guard let oldPopulation = sfDocument.data()?["population"] as? Int else {
let error = NSError(
domain: "AppErrorDomain",
code: -1,
userInfo: [
NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)"
]
)
errorPointer?.pointee = error
return nil
}
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
transaction.updateData(["population": oldPopulation + 1], forDocument: sfReference)
return nil
}) { (object, error) in
if let error = error {
print("Transaction failed: \(error)")
} else {
print("Transaction successfully committed!")
}
}
// [END simple_transaction]
}
private func transaction() {
// [START transaction]
let sfReference = db.collection("cities").document("SF")
db.runTransaction({ (transaction, errorPointer) -> Any? in
let sfDocument: DocumentSnapshot
do {
try sfDocument = transaction.getDocument(sfReference)
} catch let fetchError as NSError {
errorPointer?.pointee = fetchError
return nil
}
guard let oldPopulation = sfDocument.data()?["population"] as? Int else {
let error = NSError(
domain: "AppErrorDomain",
code: -1,
userInfo: [
NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)"
]
)
errorPointer?.pointee = error
return nil
}
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
let newPopulation = oldPopulation + 1
guard newPopulation <= 1000000 else {
let error = NSError(
domain: "AppErrorDomain",
code: -2,
userInfo: [NSLocalizedDescriptionKey: "Population \(newPopulation) too big"]
)
errorPointer?.pointee = error
return nil
}
transaction.updateData(["population": newPopulation], forDocument: sfReference)
return newPopulation
}) { (object, error) in
if let error = error {
print("Error updating population: \(error)")
} else {
print("Population increased to \(object!)")
}
}
// [END transaction]
}
private func writeBatch() {
// [START write_batch]
// Get new write batch
let batch = db.batch()
// Set the value of 'NYC'
let nycRef = db.collection("cities").document("NYC")
batch.setData([:], forDocument: nycRef)
// Update the population of 'SF'
let sfRef = db.collection("cities").document("SF")
batch.updateData(["population": 1000000 ], forDocument: sfRef)
// Delete the city 'LA'
let laRef = db.collection("cities").document("LA")
batch.deleteDocument(laRef)
// Commit the batch
batch.commit() { err in
if let err = err {
print("Error writing batch \(err)")
} else {
print("Batch write succeeded.")
}
}
// [END write_batch]
}
// =======================================================================================
// ======= https://firebase.google.com/preview/firestore/client/retrieve-data ============
// =======================================================================================
private func exampleData() {
// [START example_data]
let citiesRef = db.collection("cities")
citiesRef.document("SF").setData([
"name": "San Francisco",
"state": "CA",
"country": "USA",
"capital": false,
"population": 860000,
"regions": ["west_coast", "norcal"]
])
citiesRef.document("LA").setData([
"name": "Los Angeles",
"state": "CA",
"country": "USA",
"capital": false,
"population": 3900000,
"regions": ["west_coast", "socal"]
])
citiesRef.document("DC").setData([
"name": "Washington D.C.",
"country": "USA",
"capital": true,
"population": 680000,
"regions": ["east_coast"]
])
citiesRef.document("TOK").setData([
"name": "Tokyo",
"country": "Japan",
"capital": true,
"population": 9000000,
"regions": ["kanto", "honshu"]
])
citiesRef.document("BJ").setData([
"name": "Beijing",
"country": "China",
"capital": true,
"population": 21500000,
"regions": ["jingjinji", "hebei"]
])
// [END example_data]
}
private func exampleDataCollectionGroup() {
// [START fs_collection_group_query_data_setup]
let citiesRef = db.collection("cities")
var data = ["name": "Golden Gate Bridge", "type": "bridge"]
citiesRef.document("SF").collection("landmarks").addDocument(data: data)
data = ["name": "Legion of Honor", "type": "museum"]
citiesRef.document("SF").collection("landmarks").addDocument(data: data)
data = ["name": "Griffith Park", "type": "park"]
citiesRef.document("LA").collection("landmarks").addDocument(data: data)
data = ["name": "The Getty", "type": "museum"]
citiesRef.document("LA").collection("landmarks").addDocument(data: data)
data = ["name": "Lincoln Memorial", "type": "memorial"]
citiesRef.document("DC").collection("landmarks").addDocument(data: data)
data = ["name": "National Air and Space Museum", "type": "museum"]
citiesRef.document("DC").collection("landmarks").addDocument(data: data)
data = ["name": "Ueno Park", "type": "park"]
citiesRef.document("TOK").collection("landmarks").addDocument(data: data)
data = ["name": "National Museum of Nature and Science", "type": "museum"]
citiesRef.document("TOK").collection("landmarks").addDocument(data: data)
data = ["name": "Jingshan Park", "type": "park"]
citiesRef.document("BJ").collection("landmarks").addDocument(data: data)
data = ["name": "Beijing Ancient Observatory", "type": "museum"]
citiesRef.document("BJ").collection("landmarks").addDocument(data: data)
// [END fs_collection_group_query_data_setup]
}
private func getDocument() {
// [START get_document]
let docRef = db.collection("cities").document("SF")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
// [END get_document]
}
private func getDocumentWithOptions() {
// [START get_document_options]
let docRef = db.collection("cities").document("SF")
// Force the SDK to fetch the document from the cache. Could also specify
// FirestoreSource.server or FirestoreSource.default.
docRef.getDocument(source: .cache) { (document, error) in
if let document = document {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Cached document data: \(dataDescription)")
} else {
print("Document does not exist in cache")
}
}
// [END get_document_options]
}
private func customClassGetDocument() {
// [START custom_type]
let docRef = db.collection("cities").document("BJ")
docRef.getDocument(as: City.self) { result in
// The Result type encapsulates deserialization errors or
// successful deserialization, and can be handled as follows:
//
// Result
// /\
// Error City
switch result {
case .success(let city):
// A `City` value was successfully initialized from the DocumentSnapshot.
print("City: \(city)")
case .failure(let error):
// A `City` value could not be initialized from the DocumentSnapshot.
print("Error decoding city: \(error)")
}
}
// [END custom_type]
}
private func listenDocument() {
// [START listen_document]
db.collection("cities").document("SF")
.addSnapshotListener { documentSnapshot, error in
guard let document = documentSnapshot else {
print("Error fetching document: \(error!)")
return
}
guard let data = document.data() else {
print("Document data was empty.")
return
}
print("Current data: \(data)")
}
// [END listen_document]
}
private func listenDocumentLocal() {
// [START listen_document_local]
db.collection("cities").document("SF")
.addSnapshotListener { documentSnapshot, error in
guard let document = documentSnapshot else {
print("Error fetching document: \(error!)")
return
}
let source = document.metadata.hasPendingWrites ? "Local" : "Server"
print("\(source) data: \(document.data() ?? [:])")
}
// [END listen_document_local]
}
private func listenWithMetadata() {
// [START listen_with_metadata]
// Listen to document metadata.
db.collection("cities").document("SF")
.addSnapshotListener(includeMetadataChanges: true) { documentSnapshot, error in
// ...
}
// [END listen_with_metadata]
}
private func getMultiple() {
// [START get_multiple]
db.collection("cities").whereField("capital", isEqualTo: true)
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}
// [END get_multiple]
}
private func getMultipleAll() {
// [START get_multiple_all]
db.collection("cities").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}
// [END get_multiple_all]
}
private func listenMultiple() {
// [START listen_multiple]
db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
let cities = documents.map { $0["name"]! }
print("Current cities in CA: \(cities)")
}
// [END listen_multiple]
}
private func listenDiffs() {
// [START listen_diffs]
db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added) {
print("New city: \(diff.document.data())")
}
if (diff.type == .modified) {
print("Modified city: \(diff.document.data())")
}
if (diff.type == .removed) {
print("Removed city: \(diff.document.data())")
}
}
}
// [END listen_diffs]
}
private func listenState() {
// [START listen_state]
db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching documents: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added) {
print("New city: \(diff.document.data())")
}
}
if !snapshot.metadata.isFromCache {
print("Synced with server state.")
}
}
// [END listen_state]
}
private func detachListener() {
// [START detach_listener]
let listener = db.collection("cities").addSnapshotListener { querySnapshot, error in
// [START_EXCLUDE]
// [END_EXCLUDE]
}
// ...
// Stop listening to changes
listener.remove()
// [END detach_listener]
}
private func handleListenErrors() {
// [START handle_listen_errors]
db.collection("cities")
.addSnapshotListener { querySnapshot, error in
if let error = error {
print("Error retreiving collection: \(error)")
}
}
// [END handle_listen_errors]
}
// =======================================================================================
// ======== https://firebase.google.com/preview/firestore/client/query-data ==============
// =======================================================================================
private func simpleQueries() {
// [START simple_queries]
// Create a reference to the cities collection
let citiesRef = db.collection("cities")
// Create a query against the collection.
let query = citiesRef.whereField("state", isEqualTo: "CA")
// [END simple_queries]
// [START simple_query_not_equal]
let notEqualQuery = citiesRef.whereField("capital", isNotEqualTo: false)
// [END simple_query_not_equal]
print(query)
}
private func exampleFilters() {
let citiesRef = db.collection("cities")
// [START example_filters]
let stateQuery = citiesRef.whereField("state", isEqualTo: "CA")
let populationQuery = citiesRef.whereField("population", isLessThan: 100000)
let nameQuery = citiesRef.whereField("name", isGreaterThanOrEqualTo: "San Francisco")
// [END example_filters]
}
private func onlyCapitals() {
// [START only_capitals]
let capitalCities = db.collection("cities").whereField("capital", isEqualTo: true)
// [END only_capitals]
print(capitalCities)
}
private func arrayContainsFilter() {
let citiesRef = db.collection("cities")
// [START array_contains_filter]
citiesRef
.whereField("regions", arrayContains: "west_coast")
// [END array_contains_filter]
}
private func chainFilters() {
let citiesRef = db.collection("cities")
// [START chain_filters]
citiesRef
.whereField("state", isEqualTo: "CO")
.whereField("name", isEqualTo: "Denver")
citiesRef
.whereField("state", isEqualTo: "CA")
.whereField("population", isLessThan: 1000000)
// [END chain_filters]
}
private func validRangeFilters() {
let citiesRef = db.collection("cities")
// [START valid_range_filters]
citiesRef
.whereField("state", isGreaterThanOrEqualTo: "CA")
.whereField("state", isLessThanOrEqualTo: "IN")
citiesRef
.whereField("state", isEqualTo: "CA")
.whereField("population", isGreaterThan: 1000000)
// [END valid_range_filters]
}
private func invalidRangeFilters() throws {
let citiesRef = db.collection("cities")
// [START invalid_range_filters]
citiesRef
.whereField("state", isGreaterThanOrEqualTo: "CA")
.whereField("population", isGreaterThan: 1000000)
// [END invalid_range_filters]
}
private func orderAndLimit() {
let citiesRef = db.collection("cities")
// [START order_and_limit]
citiesRef.order(by: "name").limit(to: 3)
// [END order_and_limit]
}
private func orderAndLimitDesc() {
let citiesRef = db.collection("cities")
// [START order_and_limit_desc]
citiesRef.order(by: "name", descending: true).limit(to: 3)
// [END order_and_limit_desc]
}
private func orderMultiple() {
let citiesRef = db.collection("cities")
// [START order_multiple]
citiesRef
.order(by: "state")
.order(by: "population", descending: true)
// [END order_multiple]
}
private func filterAndOrder() {
let citiesRef = db.collection("cities")
// [START filter_and_order]
citiesRef
.whereField("population", isGreaterThan: 100000)
.order(by: "population")
.limit(to: 2)
// [END filter_and_order]
}
private func validFilterAndOrder() {
let citiesRef = db.collection("cities")
// [START valid_filter_and_order]
citiesRef
.whereField("population", isGreaterThan: 100000)
.order(by: "population")
// [END valid_filter_and_order]
}
private func invalidFilterAndOrder() throws {
let citiesRef = db.collection("cities")
// [START invalid_filter_and_order]
citiesRef
.whereField("population", isGreaterThan: 100000)
.order(by: "country")
// [END invalid_filter_and_order]
}
private func arrayContainsAnyQueries() {
// [START array_contains_any_filter]
let citiesRef = db.collection("cities")
citiesRef.whereField("regions", arrayContainsAny: ["west_coast", "east_coast"])
// [END array_contains_any_filter]
}
private func inQueries() {
// [START in_filter]
let citiesRef = db.collection("cities")
citiesRef.whereField("country", in: ["USA", "Japan"])
// [END in_filter]
// [START in_filter_with_array]
citiesRef.whereField("regions", in: [["west_coast"], ["east_coast"]]);
// [END in_filter_with_array]
// [START not_in_filter]
citiesRef.whereField("country", notIn: ["USA", "Japan"])
// [END not_in_filter]
}
// =======================================================================================
// ====== https://firebase.google.com/preview/firestore/client/enable-offline ============
// =======================================================================================
private func enableOffline() {
// [START enable_offline]
let settings = FirestoreSettings()
settings.isPersistenceEnabled = true
// Any additional options
// ...
// Enable offline data persistence
let db = Firestore.firestore()
db.settings = settings
// [END enable_offline]
}
private func listenToOffline() {
let db = Firestore.firestore()
// [START listen_to_offline]
// Listen to metadata updates to receive a server snapshot even if
// the data is the same as the cached data.
db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener(includeMetadataChanges: true) { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error retreiving snapshot: \(error!)")
return
}
for diff in snapshot.documentChanges {
if diff.type == .added {
print("New city: \(diff.document.data())")
}
}
let source = snapshot.metadata.isFromCache ? "local cache" : "server"
print("Metadata: Data fetched from \(source)")
}
// [END listen_to_offline]
}
private func toggleOffline() {
// [START disable_network]
Firestore.firestore().disableNetwork { (error) in
// Do offline things
// ...
}
// [END disable_network]
// [START enable_network]
Firestore.firestore().enableNetwork { (error) in
// Do online things
// ...
}
// [END enable_network]
}
// =======================================================================================
// ====== https://firebase.google.com/preview/firestore/client/cursors ===================
// =======================================================================================
private func simpleCursor() {
let db = Firestore.firestore()
// [START cursor_greater_than]
// Get all cities with population over one million, ordered by population.
db.collection("cities")
.order(by: "population")
.start(at: [1000000])
// [END cursor_greater_than]
// [START cursor_less_than]
// Get all cities with population less than one million, ordered by population.
db.collection("cities")
.order(by: "population")
.end(at: [1000000])
// [END cursor_less_than]
}
private func snapshotCursor() {
let db = Firestore.firestore()
// [START snapshot_cursor]
db.collection("cities")
.document("SF")
.addSnapshotListener { (document, error) in
guard let document = document else {
print("Error retreving cities: \(error.debugDescription)")
return
}
// Get all cities with a population greater than or equal to San Francisco.
let sfSizeOrBigger = db.collection("cities")
.order(by: "population")
.start(atDocument: document)
}
// [END snapshot_cursor]
}
private func paginate() {
let db = Firestore.firestore()
// [START paginate]
// Construct query for first 25 cities, ordered by population
let first = db.collection("cities")
.order(by: "population")
.limit(to: 25)
first.addSnapshotListener { (snapshot, error) in
guard let snapshot = snapshot else {
print("Error retreving cities: \(error.debugDescription)")
return
}
guard let lastSnapshot = snapshot.documents.last else {
// The collection is empty.
return
}
// Construct a new query starting after this document,
// retrieving the next 25 cities.
let next = db.collection("cities")
.order(by: "population")
.start(afterDocument: lastSnapshot)
// Use the query for pagination.
// ...
}
// [END paginate]
}
private func multiCursor() {
let db = Firestore.firestore()
// [START multi_cursor]
// Will return all Springfields
db.collection("cities")
.order(by: "name")
.order(by: "state")
.start(at: ["Springfield"])
// Will return "Springfield, Missouri" and "Springfield, Wisconsin"
db.collection("cities")
.order(by: "name")
.order(by: "state")
.start(at: ["Springfield", "Missouri"])
// [END multi_cursor]
}
private func collectionGroupQuery() {
// [START fs_collection_group_query]
db.collectionGroup("landmarks").whereField("type", isEqualTo: "museum").getDocuments { (snapshot, error) in
// [START_EXCLUDE]
print(snapshot?.documents.count ?? 0)
// [END_EXCLUDE]
}
// [END fs_collection_group_query]
}
private func emulatorSettings() {
// [START fs_emulator_connect]
let settings = Firestore.firestore().settings
settings.host = "localhost:8080"
settings.isPersistenceEnabled = false
settings.isSSLEnabled = false
Firestore.firestore().settings = settings
// [END fs_emulator_connect]
}
// MARK: Aggregation queries
private func countAggregateCollection() async {
// [START count_aggregate_collection]
let query = db.collection("cities")
let countQuery = query.count
do {
let snapshot = try await countQuery.getAggregation(source: .server)
print(snapshot.count)
} catch {
print(error);
}
// [END count_aggregate_collection]
}
private func countAggregateQuery() async {
// [START count_aggregate_query]
let query = db.collection("cities").whereField("state", isEqualTo: "CA")
let countQuery = query.count
do {
let snapshot = try await countQuery.getAggregation(source: .server)
print(snapshot.count)
} catch {
print(error);
}
// [END count_aggregate_query]
}
}
// [START codable_struct]
public struct City: Codable {
let name: String
let state: String?
let country: String?
let isCapital: Bool?
let population: Int64?
enum CodingKeys: String, CodingKey {
case name
case state
case country
case isCapital = "capital"
case population
}
}
// [END codable_struct]
|
apache-2.0
|
2916a08e057892b3309a98a9d1e47c7d
| 32.914373 | 115 | 0.520243 | 4.894627 | false | false | false | false |
bmichotte/HSTracker
|
HSTracker/Logging/Parsers/TagChangeHandler.swift
|
1
|
6220
|
/*
* This file is part of the HSTracker package.
* (c) Benjamin Michotte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Created on 13/02/16.
*/
import Foundation
import CleanroomLogger
import RegexUtil
class TagChangeHandler {
let ParseEntityIDRegex: RegexPattern = "id=(\\d+)"
let ParseEntityZonePosRegex: RegexPattern = "zonePos=(\\d+)"
let ParseEntityPlayerRegex: RegexPattern = "player=(\\d+)"
let ParseEntityNameRegex: RegexPattern = "name=(\\w+)"
let ParseEntityZoneRegex: RegexPattern = "zone=(\\w+)"
let ParseEntityCardIDRegex: RegexPattern = "cardId=(\\w+)"
let ParseEntityTypeRegex: RegexPattern = "type=(\\w+)"
private var creationTagActionQueue = [
(tag: GameTag, eventHandler: PowerEventHandler, id: Int, value: Int, prevValue: Int)
]()
private var tagChangeAction = TagChangeActions()
func tagChange(eventHandler: PowerEventHandler, rawTag: String, id: Int,
rawValue: String, isCreationTag: Bool = false) {
if let tag = GameTag(rawString: rawTag) {
let value = self.parseTag(tag: tag, rawValue: rawValue)
tagChange(eventHandler: eventHandler, tag: tag, id: id, value: value,
isCreationTag: isCreationTag)
} else {
//Log.warning?.message("Can't parse \(rawTag) -> \(rawValue)")
}
}
func tagChange(eventHandler: PowerEventHandler, tag: GameTag, id: Int,
value: Int, isCreationTag: Bool = false) {
if eventHandler.entities[id] == .none {
eventHandler.entities[id] = Entity(id: id)
}
eventHandler.lastId = id
if let entity = eventHandler.entities[id] {
let prevValue = entity[tag]
entity[tag ] = value
//print("Set tag \(tag) with value \(value) to entity \(id)")
if isCreationTag {
creationTagActionQueue.append((tag, eventHandler, id, value, prevValue))
} else {
tagChangeAction.callAction(eventHandler: eventHandler, tag: tag,
id: id, value: value,
prevValue: prevValue)
}
}
}
func invokeQueuedActions(eventHandler: PowerEventHandler) {
while creationTagActionQueue.count > 0 {
let act = creationTagActionQueue.removeFirst()
tagChangeAction.callAction(eventHandler: eventHandler, tag: act.tag, id: act.id,
value: act.value, prevValue: act.prevValue)
if creationTagActionQueue.all({ $0.id != act.id }) && eventHandler.entities[act.id] != nil {
eventHandler.entities[act.id]!.info.hasOutstandingTagChanges = false
}
}
}
func clearQueuedActions() {
if creationTagActionQueue.count > 0 {
// swiftlint:disable line_length
Log.warning?.message("Clearing tagActionQueue with \(creationTagActionQueue.count) elements in it")
// swiftlint:enable line_length
}
creationTagActionQueue.removeAll()
}
struct LogEntity {
var id: Int?
var zonePos: Int?
var player: Int?
var name: String?
var zone: String?
var cardId: String?
var type: String?
func isValid() -> Bool {
let a: [Any?] = [id, zonePos, player, name, zone, cardId, type]
return a.any { $0 != nil }
}
}
// parse an entity
func parseEntity(entity: String) -> LogEntity {
var id: Int?, zonePos: Int?, player: Int?
var name: String?, zone: String?, cardId: String?, type: String?
if entity.match(ParseEntityIDRegex) {
if let match = entity.matches(ParseEntityIDRegex).first {
id = Int(match.value)
}
}
if entity.match(ParseEntityZonePosRegex) {
if let match = entity.matches(ParseEntityZonePosRegex).first {
zonePos = Int(match.value)
}
}
if entity.match(ParseEntityPlayerRegex) {
if let match = entity.matches(ParseEntityPlayerRegex).first {
player = Int(match.value)
}
}
if entity.match(ParseEntityNameRegex) {
if let match = entity.matches(ParseEntityNameRegex).first {
name = match.value
}
}
if entity.match(ParseEntityZoneRegex) {
if let match = entity.matches(ParseEntityZoneRegex).first {
zone = match.value
}
}
if entity.match(ParseEntityCardIDRegex) {
if let match = entity.matches(ParseEntityCardIDRegex).first {
cardId = match.value
}
}
if entity.match(ParseEntityTypeRegex) {
if let match = entity.matches(ParseEntityTypeRegex).first {
type = match.value
}
}
return LogEntity(id: id, zonePos: zonePos, player: player,
name: name, zone: zone, cardId: cardId, type: type)
}
// check if the entity is a raw entity
func isEntity(rawEntity: String) -> Bool {
return parseEntity(entity: rawEntity).isValid()
}
func parseTag(tag: GameTag, rawValue: String) -> Int {
switch tag {
case .zone:
return Zone(rawString: rawValue)!.rawValue
case .mulligan_state:
return Mulligan(rawString: rawValue)!.rawValue
case .playstate:
return PlayState(rawString: rawValue)!.rawValue
case .cardtype:
return CardType(rawString: rawValue)!.rawValue
case .class:
return TagClass(rawString: rawValue)!.rawValue
case .state:
return State(rawString: rawValue)!.rawValue
case .step:
return Step(rawString: rawValue)!.rawValue
default:
if let value = Int(rawValue) {
return value
}
return 0
}
}
}
|
mit
|
6446a15646563c08391905d668d01d8b
| 33.555556 | 111 | 0.573151 | 4.517066 | false | false | false | false |
sudeepunnikrishnan/ios-sdk
|
Instamojo/PaymentOptionsView.swift
|
1
|
6979
|
//
// PaymentOptionsView.swift
// Instamojo
//
// Created by Sukanya Raj on 06/02/17.
// Copyright © 2017 Sukanya Raj. All rights reserved.
//
import UIKit
class PaymentOptionsView: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var paymentOptionsTableView: UITableView!
var order: Order!
var paymentOptions: NSMutableArray = [Constants.DebitCardOption, Constants.NetBankingOption, Constants.CreditCardOption, Constants.WalletsOption, Constants.EmiOption, Constants.UpiOption]
var paymentCompleted : Bool = false;
var mainStoryboard: UIStoryboard = UIStoryboard()
var isBackButtonNeeded: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
paymentOptionsTableView.tableFooterView = UIView()
mainStoryboard = Constants.getStoryboardInstance()
self.reloadDataBasedOnOrder()
NotificationCenter.default.addObserver(self, selector: #selector(self.backToViewController), name: NSNotification.Name("INSTAMOJO"), object: nil)
if(isBackButtonNeeded == false){
let menu_button_ = UIBarButtonItem.init(title: "Exit", style: .plain, target: self, action:#selector(self.exitViewController))
self.navigationItem.rightBarButtonItem = menu_button_
}
}
@objc func exitViewController(){
self.dismiss(animated: true, completion: nil)
}
@objc func backToViewController(){
Logger.logDebug(tag: "Payment Done", message: "In Observer")
paymentCompleted = true
}
//Set payment options based on the order
func reloadDataBasedOnOrder() {
if order.netBankingOptions == nil {
paymentOptions.remove(Constants.NetBankingOption)
}
if order.cardOptions == nil {
paymentOptions.remove(Constants.CreditCardOption)
paymentOptions.remove(Constants.DebitCardOption)
}
if order.emiOptions == nil {
paymentOptions.remove(Constants.EmiOption)
}
if order.walletOptions == nil {
paymentOptions.remove(Constants.WalletsOption)
}
if order.upiOptions == nil {
paymentOptions.remove(Constants.UpiOption)
}
paymentOptionsTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return paymentOptions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.PaymentOptionsCell, for: indexPath)
cell.textLabel?.text = paymentOptions.object(at: indexPath.row) as? String
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let rowSelected = indexPath.row
let options = paymentOptions.object(at: rowSelected) as? String
switch options {
case Constants.NetBankingOption? :
DispatchQueue.main.async {
self.onNetBankingSelected(options: options!)
}
break
case Constants.CreditCardOption? :
onCreditCardSelected()
break
case Constants.DebitCardOption? :
onDebitCardSelected()
break
case Constants.EmiOption? :
onEmiSelected(options : options!)
break
case Constants.WalletsOption? :
DispatchQueue.main.async {
self.onWalletSelected(options: options!)
}
break
case Constants.UpiOption? :
onUPISelected()
break
default:
onCreditCardSelected()
break
}
}
func onNetBankingSelected(options: String) {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsListviewController) as? ListOptionsView {
viewController.paymentOption = options
viewController.order = order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if UserDefaults.standard.value(forKey: "USER-CANCELLED-ON-VERIFY") != nil {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
_ = self.navigationController?.popViewController(animated: true)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "INSTAMOJO"), object: nil)
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if paymentCompleted {
Logger.logDebug(tag: "Payment Done", message: "GO BACK")
paymentCompleted = false
_ = self.navigationController?.popViewController(animated: true)
}
}
func onCreditCardSelected() {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsCardViewController) as? CardFormView {
viewController.cardType = Constants.CreditCard
viewController.order = self.order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
func onDebitCardSelected() {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsCardViewController) as? CardFormView {
viewController.cardType = Constants.DebitCard
viewController.order = self.order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
func onEmiSelected(options: String) {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsListviewController) as? ListOptionsView {
viewController.paymentOption = options
viewController.order = order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
func onWalletSelected(options: String) {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsListviewController) as? ListOptionsView {
viewController.paymentOption = options
viewController.order = order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
func onUPISelected() {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsUpiViewController) as? UPIPaymentView {
viewController.order = order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
}
|
lgpl-3.0
|
4b5f37411eb94d9d6657beb4a6f4544a
| 38.647727 | 191 | 0.671539 | 5.434579 | false | false | false | false |
younata/RSSClient
|
TethysKitSpecs/Helpers/Fakes/FakeLocalFeedService.swift
|
1
|
1600
|
import Result
import CBGPromise
@testable import TethysKit
final class FakeLocalFeedService: FakeFeedService, LocalFeedService {
private(set) var updateFeedsCalls: [AnyCollection<Feed>] = []
private(set) var updateFeedsPromises: [Promise<Result<AnyCollection<Feed>, TethysError>>] = []
func updateFeeds(with feeds: AnyCollection<Feed>) -> Future<Result<AnyCollection<Feed>, TethysError>> {
self.updateFeedsCalls.append(feeds)
let promise = Promise<Result<AnyCollection<Feed>, TethysError>>()
self.updateFeedsPromises.append(promise)
return promise.future
}
private(set) var updateFeedFromCalls: [Feed] = []
private(set) var updateFeedFromPromises: [Promise<Result<Feed, TethysError>>] = []
func updateFeed(from feed: Feed) -> Future<Result<Feed, TethysError>> {
self.updateFeedFromCalls.append(feed)
let promise = Promise<Result<Feed, TethysError>>()
self.updateFeedFromPromises.append(promise)
return promise.future
}
private(set) var updateArticlesCalls: [(articles: AnyCollection<Article>, feed: Feed)] = []
private(set) var updateArticlesPromises: [Promise<Result<AnyCollection<Article>, TethysError>>] = []
func updateArticles(
with articles: AnyCollection<Article>,
feed: Feed
) -> Future<Result<AnyCollection<Article>, TethysError>> {
self.updateArticlesCalls.append((articles, feed))
let promise = Promise<Result<AnyCollection<Article>, TethysError>>()
self.updateArticlesPromises.append(promise)
return promise.future
}
}
|
mit
|
ac4241760cb7ff5557b863cda0bcb8c4
| 42.243243 | 107 | 0.706875 | 4.456825 | false | false | false | false |
GuoZhiQiang/SwiftBasicTableView
|
SwiftBasicTableView/MealTableViewController.swift
|
1
|
5368
|
//
// MealTableViewController.swift
// SwiftBasicTableView
//
// Created by guo on 16/4/18.
// Copyright © 2016年 guo. All rights reserved.
//
import UIKit
class MealTableViewController: UITableViewController {
// MARK: Properties
var arr_meal = [Meal]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = editButtonItem()
if let savedMeals = loadMeals() {
arr_meal += savedMeals
}
else {
loadMealData()
}
}
// MARK: Actions
func loadMealData() {
let photo1 = UIImage(named: "meal1")!
let photo2 = UIImage(named: "meal2")!
let photo3 = UIImage(named: "meal3")!
// 加入的数组的对象不能为空,所有,meal 对象后都需要加上!
let meal1 = Meal(name: "Food one", photo: photo1, rating: 4)!
let meal2 = Meal(name: "Food two", photo: photo2, rating: 5)!
let meal3 = Meal(name: "Food Four", photo: photo3, rating: 3)!
arr_meal += [meal1,meal2,meal3]
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr_meal.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MEAL_CELL", forIndexPath: indexPath) as!MealCell
let meal = arr_meal[indexPath.row]
cell.lb_name.text = meal.name
cell.img_meal.image = meal.photo
cell.v_rating.rating = meal.rating
return cell
}
// Exit
@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
if let sourceVC = sender.sourceViewController as? ViewController, meal = sourceVC.meal {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
arr_meal[selectedIndexPath.row] = meal
tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
}
else {
let newIndexPath = NSIndexPath(forRow: arr_meal.count, inSection: 0)
arr_meal.append(meal)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
saveMeals()
}
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
arr_meal.removeAtIndex(indexPath.row)
saveMeals()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail" {
let detailVC = segue.destinationViewController as! ViewController
if let selectedCell = sender as? MealCell {
let indexPath = tableView.indexPathForCell(selectedCell)!
let selectedMeal = arr_meal[indexPath.row]
detailVC.meal = selectedMeal
}
}
else if segue.identifier == "AddItem" {
print("Add new meal")
}
}
// MARK: NSCoding
func saveMeals() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(arr_meal, toFile: Meal.ArchiveURL.path!)
if !isSuccessfulSave {
print("Failed to save meals...")
}
}
func loadMeals() -> [Meal]? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(Meal.ArchiveURL.path!) as? [Meal]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
a9ce8aec645428a9758e38a83ab4e975
| 31.212121 | 157 | 0.611101 | 5.185366 | false | false | false | false |
ganczar/SonicScales-iOS
|
gauge/SettingsTableViewController.swift
|
1
|
11751
|
//
// SettingsTableViewController.swift
// gauge
//
// Created by Wojciech Ganczarski on 16/12/15.
// Copyright © 2015 Sonic Scales. All rights reserved.
//
import UIKit
import CoreData
class SettingsTableViewController: UITableViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {
@IBOutlet weak var densityTextField: UITextFieldWithoutCaret!;
@IBOutlet weak var diameterTextField: UITextFieldWithoutCaret!;
@IBOutlet weak var lengthTextField: UITextFieldWithoutCaret!;
@IBOutlet weak var forceArmTextField: UITextFieldWithoutCaret!;
@IBOutlet weak var resistanceArmTextField: UITextFieldWithoutCaret!;
var densityPicker: UIPickerView!;
var diameterPicker: UIPickerView!;
var lengthPicker: UIPickerView!;
var forceArmPicker: UIPickerView!;
var resistanceArmPicker: UIPickerView!;
var settings: Settings!;
let densityArray = [Int](5000...10000);
let diameterArray = [Int](8...84);
let lengthArray = [Int](100...3000);
let forceArmArray = [Int](1...300);
let resistanceArmArray = [Int](1...200);
override func viewDidLoad() {
super.viewDidLoad();
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SettingsTableViewController.handleTap));
tapGestureRecognizer.cancelsTouchesInView = false;
self.view.addGestureRecognizer(tapGestureRecognizer);
let context: NSManagedObjectContext! = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext;
let fetchRequest = NSFetchRequest<NSFetchRequestResult>();
let entityDescription = NSEntityDescription.entity(forEntityName: "Settings", in: context);
fetchRequest.entity = entityDescription;
do {
settings = try context.fetch(fetchRequest)[0] as? Settings;
} catch {
let fetchError = error as NSError;
print(fetchError);
}
densityPicker = createPicker();
densityPicker.selectRow(densityArray.firstIndex(of: Int(settings.density))!, inComponent: 0, animated: false);
densityTextField.inputView = densityPicker;
densityTextField.inputAccessoryView = createPickerToolbar("String's density [kg/m³]");
densityTextField.delegate = self;
densityTextField.selectedTextRange = nil;
densityTextField.text = String(Int(settings.density));
diameterPicker = createPicker();
diameterPicker.selectRow(diameterArray.firstIndex(of: Int(settings.stringDiameter))!, inComponent: 0, animated: false);
diameterTextField.inputView = diameterPicker;
diameterTextField.inputAccessoryView = createPickerToolbar("String's diameter [1/1000 inch]");
diameterTextField.delegate = self;
diameterTextField.selectedTextRange = nil;
diameterTextField.text = String(Int(settings.stringDiameter));
lengthPicker = createPicker();
lengthPicker.selectRow(lengthArray.firstIndex(of: Int(settings.stringLength))!, inComponent: 0, animated: false);
lengthTextField.inputView = lengthPicker;
lengthTextField.inputAccessoryView = createPickerToolbar("String's length [mm]");
lengthTextField.delegate = self;
lengthTextField.selectedTextRange = nil;
lengthTextField.text = String(Int(settings.stringLength));
forceArmPicker = createPicker();
forceArmPicker.selectRow(forceArmArray.firstIndex(of: Int(settings.forceArmLength))!, inComponent: 0, animated: false);
forceArmTextField.inputView = forceArmPicker;
forceArmTextField.inputAccessoryView = createPickerToolbar("Force arm's length [length unit]");
forceArmTextField.delegate = self;
forceArmTextField.selectedTextRange = nil;
forceArmTextField.text = String(Int(settings.forceArmLength));
resistanceArmPicker = createPicker();
resistanceArmPicker.selectRow(resistanceArmArray.firstIndex(of: Int(settings.resistanceArmLength))!, inComponent: 0, animated: false);
resistanceArmTextField.inputView = resistanceArmPicker;
resistanceArmTextField.inputAccessoryView = createPickerToolbar("Resistance arm's length [length unit]");
resistanceArmTextField.delegate = self;
resistanceArmTextField.selectedTextRange = nil;
resistanceArmTextField.text = String(Int(settings.resistanceArmLength));
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
}
@objc func handleTap() {
self.view.endEditing(true);
}
fileprivate func createPicker() -> UIPickerView {
let picker = UIPickerView();
picker.backgroundColor = .white;
picker.dataSource = self;
picker.delegate = self;
return picker;
}
fileprivate func createPickerToolbar(_ title: String) -> UIToolbar {
let toolBar = UIToolbar();
toolBar.barStyle = UIBarStyle.default;
toolBar.isTranslucent = true;
toolBar.tintColor = .darkGray;
toolBar.sizeToFit();
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(SettingsTableViewController.handleTap));
let titleButton = UIBarButtonItem(title: title, style: UIBarButtonItem.Style.plain, target: self, action: nil);
titleButton.isEnabled = false;
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil);
toolBar.setItems([titleButton, spaceButton, doneButton], animated: false);
toolBar.isUserInteractionEnabled = true;
return toolBar;
}
// MARK: - Picker view data source
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 1;
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
if (pickerView == densityPicker) {
return densityArray.count;
} else if (pickerView == diameterPicker) {
return diameterArray.count;
} else if (pickerView == lengthPicker) {
return lengthArray.count;
} else if (pickerView == forceArmPicker) {
return forceArmArray.count;
} else if (pickerView == resistanceArmPicker) {
return resistanceArmArray.count;
} else {
return 0;
}
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var label: UILabel? = view as? UILabel;
if (label == nil) {
label = UILabel();//UILabel(frame: CGRectMake(20, 0, 60, 30));
label?.font = UIFont.systemFont(ofSize: 25);
label?.textAlignment = NSTextAlignment.center;
}
if (pickerView == densityPicker) {
label?.text = String(densityArray[row]);
} else if (pickerView == diameterPicker) {
label?.text = String(diameterArray[row]);
} else if (pickerView == lengthPicker) {
label?.text = String(lengthArray[row]);
} else if (pickerView == forceArmPicker) {
label?.text = String(forceArmArray[row]);
} else if (pickerView == resistanceArmPicker) {
label?.text = String(resistanceArmArray[row]);
}
return label!;
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
if (pickerView == densityPicker) {
densityTextField.text = String(pickerView.selectedRow(inComponent: 0) + densityArray[0]);
} else if (pickerView == diameterPicker) {
diameterTextField.text = String(pickerView.selectedRow(inComponent: 0) + diameterArray[0]);
} else if (pickerView == lengthPicker) {
lengthTextField.text = String(pickerView.selectedRow(inComponent: 0) + lengthArray[0]);
} else if (pickerView == forceArmPicker) {
forceArmTextField.text = String(pickerView.selectedRow(inComponent: 0) + forceArmArray[0]);
} else if (pickerView == resistanceArmPicker) {
resistanceArmTextField.text = String(pickerView.selectedRow(inComponent: 0) + resistanceArmArray[0]);
}
}
// MARK: - Text field delegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return false;
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder();
return true;
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false;
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 3;
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 3
case 1:
return 2
case 2:
return 2
default:
return 0
}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerLabel: UILabel = UILabel()
headerLabel.frame = CGRect(x: 10, y: 1, width: 320, height: 20);
headerLabel.font = UIFont.systemFont(ofSize: 12)
headerLabel.text = self.tableView(tableView, titleForHeaderInSection: section)
headerLabel.textColor = UIColor.darkGray
let headerView: UIView = UIView()
headerView.backgroundColor = UIColor.groupTableViewBackground
headerView.alpha = 0.5
headerView.addSubview(headerLabel)
return headerView;
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func cancel(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil);
}
@IBAction func done(_ sender: UIBarButtonItem) {
settings.density = Double(densityPicker.selectedRow(inComponent: 0) + densityArray[0]) as Double;
settings.stringDiameter = Double(diameterPicker.selectedRow(inComponent: 0) + diameterArray[0]) as Double;
settings.stringLength = Double(lengthPicker.selectedRow(inComponent: 0) + lengthArray[0]) as Double;
settings.forceArmLength = Double(forceArmPicker.selectedRow(inComponent: 0) + forceArmArray[0]) as Double;
settings.resistanceArmLength = Double(resistanceArmPicker.selectedRow(inComponent: 0) + resistanceArmArray[0]) as Double;
(UIApplication.shared.delegate as! AppDelegate).saveContext();
self.dismiss(animated: true, completion: nil);
}
}
|
mit
|
f1f931da93049462dfd0fee369d65610
| 36.536741 | 157 | 0.739552 | 4.298939 | false | false | false | false |
ocrickard/Theodolite
|
Theodolite/UI/Text/TextKitContext.swift
|
1
|
1323
|
//
// TextKitContext.swift
// Theodolite
//
// Created by Oliver Rickard on 10/29/17.
// Copyright © 2017 Oliver Rickard. All rights reserved.
//
import Foundation
var gGlobalLock: NSLock = NSLock()
public final class TextKitContext {
private let layoutManager: NSLayoutManager
private let textStorage: NSTextStorage
private let textContainer: NSTextContainer
private let internalLock: NSLock
init(attributedString: NSAttributedString,
lineBreakMode: NSLineBreakMode,
maximumNumberOfLines: Int,
constrainedSize: CGSize) {
internalLock = NSLock()
gGlobalLock.lock(); defer { gGlobalLock.unlock() }
textStorage = NSTextStorage(attributedString: attributedString)
layoutManager = NSLayoutManager()
layoutManager.usesFontLeading = false
textStorage.addLayoutManager(layoutManager)
textContainer = NSTextContainer(size: constrainedSize)
textContainer.lineFragmentPadding = 0
textContainer.lineBreakMode = lineBreakMode
textContainer.maximumNumberOfLines = maximumNumberOfLines
layoutManager.addTextContainer(textContainer)
}
public func withLock(closure: (NSLayoutManager, NSTextStorage, NSTextContainer) -> ()) {
internalLock.lock(); defer { internalLock.unlock() }
closure(layoutManager, textStorage, textContainer)
}
}
|
mit
|
f68aba575916ffc44f7b5e35aaad05f1
| 31.243902 | 90 | 0.755673 | 5.373984 | false | false | false | false |
evnaz/Design-Patterns-In-Swift
|
Design-Patterns-CN.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift
|
2
|
18072
|
/*:
行为型模式
========
>在软件工程中, 行为型模式为设计模式的一种类型,用来识别对象之间的常用交流模式并加以实现。如此,可在进行这些交流活动时增强弹性。
>
>**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E8%A1%8C%E7%82%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)
## 目录
* [行为型模式](Behavioral)
* [创建型模式](Creational)
* [结构型模式](Structural)
*/
import Foundation
/*:
🐝 责任链(Chain Of Responsibility)
------------------------------
责任链模式在面向对象程式设计里是一种软件设计模式,它包含了一些命令对象和一系列的处理对象。每一个处理对象决定它能处理哪些命令对象,它也知道如何将它不能处理的命令对象传递给该链中的下一个处理对象。
### 示例:
*/
protocol Withdrawing {
func withdraw(amount: Int) -> Bool
}
final class MoneyPile: Withdrawing {
let value: Int
var quantity: Int
var next: Withdrawing?
init(value: Int, quantity: Int, next: Withdrawing?) {
self.value = value
self.quantity = quantity
self.next = next
}
func withdraw(amount: Int) -> Bool {
var amount = amount
func canTakeSomeBill(want: Int) -> Bool {
return (want / self.value) > 0
}
var quantity = self.quantity
while canTakeSomeBill(want: amount) {
if quantity == 0 {
break
}
amount -= self.value
quantity -= 1
}
guard amount > 0 else {
return true
}
if let next = self.next {
return next.withdraw(amount: amount)
}
return false
}
}
final class ATM: Withdrawing {
private var hundred: Withdrawing
private var fifty: Withdrawing
private var twenty: Withdrawing
private var ten: Withdrawing
private var startPile: Withdrawing {
return self.hundred
}
init(hundred: Withdrawing,
fifty: Withdrawing,
twenty: Withdrawing,
ten: Withdrawing) {
self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}
func withdraw(amount: Int) -> Bool {
return startPile.withdraw(amount: amount)
}
}
/*:
### 用法
*/
// 创建一系列的钱堆,并将其链接起来:10<20<50<100
let ten = MoneyPile(value: 10, quantity: 6, next: nil)
let twenty = MoneyPile(value: 20, quantity: 2, next: ten)
let fifty = MoneyPile(value: 50, quantity: 2, next: twenty)
let hundred = MoneyPile(value: 100, quantity: 1, next: fifty)
// 创建 ATM 实例
var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount: 310) // Cannot because ATM has only 300
atm.withdraw(amount: 100) // Can withdraw - 1x100
/*:
👫 命令(Command)
------------
命令模式是一种设计模式,它尝试以对象来代表实际行动。命令对象可以把行动(action) 及其参数封装起来,于是这些行动可以被:
* 重复多次
* 取消(如果该对象有实现的话)
* 取消后又再重做
### 示例:
*/
protocol DoorCommand {
func execute() -> String
}
final class OpenCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Opened \(doors)"
}
}
final class CloseCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Closed \(doors)"
}
}
final class HAL9000DoorsOperations {
let openCommand: DoorCommand
let closeCommand: DoorCommand
init(doors: String) {
self.openCommand = OpenCommand(doors:doors)
self.closeCommand = CloseCommand(doors:doors)
}
func close() -> String {
return closeCommand.execute()
}
func open() -> String {
return openCommand.execute()
}
}
/*:
### 用法
*/
let podBayDoors = "Pod Bay Doors"
let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()
/*:
🎶 解释器(Interpreter)
------------------
给定一种语言,定义他的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中句子。
### 示例:
*/
protocol IntegerExpression {
func evaluate(_ context: IntegerContext) -> Int
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
func copied() -> IntegerExpression
}
final class IntegerContext {
private var data: [Character:Int] = [:]
func lookup(name: Character) -> Int {
return self.data[name]!
}
func assign(expression: IntegerVariableExpression, value: Int) {
self.data[expression.name] = value
}
}
final class IntegerVariableExpression: IntegerExpression {
let name: Character
init(name: Character) {
self.name = name
}
func evaluate(_ context: IntegerContext) -> Int {
return context.lookup(name: self.name)
}
func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
if name == self.name {
return integerExpression.copied()
} else {
return IntegerVariableExpression(name: self.name)
}
}
func copied() -> IntegerExpression {
return IntegerVariableExpression(name: self.name)
}
}
final class AddExpression: IntegerExpression {
private var operand1: IntegerExpression
private var operand2: IntegerExpression
init(op1: IntegerExpression, op2: IntegerExpression) {
self.operand1 = op1
self.operand2 = op2
}
func evaluate(_ context: IntegerContext) -> Int {
return self.operand1.evaluate(context) + self.operand2.evaluate(context)
}
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))
}
func copied() -> IntegerExpression {
return AddExpression(op1: self.operand1, op2: self.operand2)
}
}
/*:
### 用法
*/
var context = IntegerContext()
var a = IntegerVariableExpression(name: "A")
var b = IntegerVariableExpression(name: "B")
var c = IntegerVariableExpression(name: "C")
var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value: 2)
context.assign(expression: b, value: 1)
context.assign(expression: c, value: 3)
var result = expression.evaluate(context)
/*:
🍫 迭代器(Iterator)
---------------
迭代器模式可以让用户通过特定的接口巡访容器中的每一个元素而不用了解底层的实现。
### 示例:
*/
struct Novella {
let name: String
}
struct Novellas {
let novellas: [Novella]
}
struct NovellasIterator: IteratorProtocol {
private var current = 0
private let novellas: [Novella]
init(novellas: [Novella]) {
self.novellas = novellas
}
mutating func next() -> Novella? {
defer { current += 1 }
return novellas.count > current ? novellas[current] : nil
}
}
extension Novellas: Sequence {
func makeIterator() -> NovellasIterator {
return NovellasIterator(novellas: novellas)
}
}
/*:
### 用法
*/
let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
for novella in greatNovellas {
print("I've read: \(novella)")
}
/*:
💐 中介者(Mediator)
---------------
用一个中介者对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使耦合松散,而且可以独立地改变它们之间的交互。
### 示例:
*/
protocol Receiver {
associatedtype MessageType
func receive(message: MessageType)
}
protocol Sender {
associatedtype MessageType
associatedtype ReceiverType: Receiver
var recipients: [ReceiverType] { get }
func send(message: MessageType)
}
struct Programmer: Receiver {
let name: String
init(name: String) {
self.name = name
}
func receive(message: String) {
print("\(name) received: \(message)")
}
}
final class MessageMediator: Sender {
internal var recipients: [Programmer] = []
func add(recipient: Programmer) {
recipients.append(recipient)
}
func send(message: String) {
for recipient in recipients {
recipient.receive(message: message)
}
}
}
/*:
### 用法
*/
func spamMonster(message: String, worker: MessageMediator) {
worker.send(message: message)
}
let messagesMediator = MessageMediator()
let user0 = Programmer(name: "Linus Torvalds")
let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)
spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
/*:
💾 备忘录(Memento)
--------------
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态
### 示例:
*/
typealias Memento = [String: String]
/*:
发起人(Originator)
*/
protocol MementoConvertible {
var memento: Memento { get }
init?(memento: Memento)
}
struct GameState: MementoConvertible {
private enum Keys {
static let chapter = "com.valve.halflife.chapter"
static let weapon = "com.valve.halflife.weapon"
}
var chapter: String
var weapon: String
init(chapter: String, weapon: String) {
self.chapter = chapter
self.weapon = weapon
}
init?(memento: Memento) {
guard let mementoChapter = memento[Keys.chapter],
let mementoWeapon = memento[Keys.weapon] else {
return nil
}
chapter = mementoChapter
weapon = mementoWeapon
}
var memento: Memento {
return [ Keys.chapter: chapter, Keys.weapon: weapon ]
}
}
/*:
管理者(Caretaker)
*/
enum CheckPoint {
private static let defaults = UserDefaults.standard
static func save(_ state: MementoConvertible, saveName: String) {
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()
}
static func restore(saveName: String) -> Any? {
return defaults.object(forKey: saveName)
}
}
/*:
### 用法
*/
var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
gameState.chapter = "Anomalous Materials"
gameState.weapon = "Glock 17"
CheckPoint.save(gameState, saveName: "gameState1")
gameState.chapter = "Unforeseen Consequences"
gameState.weapon = "MP5"
CheckPoint.save(gameState, saveName: "gameState2")
gameState.chapter = "Office Complex"
gameState.weapon = "Crossbow"
CheckPoint.save(gameState, saveName: "gameState3")
if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
let finalState = GameState(memento: memento)
dump(finalState)
}
/*:
👓 观察者(Observer)
---------------
一个目标对象管理所有相依于它的观察者对象,并且在它本身的状态改变时主动发出通知
### 示例:
*/
protocol PropertyObserver : class {
func willChange(propertyName: String, newPropertyValue: Any?)
func didChange(propertyName: String, oldPropertyValue: Any?)
}
final class TestChambers {
weak var observer:PropertyObserver?
private let testChamberNumberName = "testChamberNumber"
var testChamberNumber: Int = 0 {
willSet(newValue) {
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
}
}
}
final class Observer : PropertyObserver {
func willChange(propertyName: String, newPropertyValue: Any?) {
if newPropertyValue as? Int == 1 {
print("Okay. Look. We both said a lot of things that you're going to regret.")
}
}
func didChange(propertyName: String, oldPropertyValue: Any?) {
if oldPropertyValue as? Int == 0 {
print("Sorry about the mess. I've really let the place go since you killed me.")
}
}
}
/*:
### 用法
*/
var observerInstance = Observer()
var testChambers = TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber += 1
/*:
🐉 状态(State)
---------
在状态模式中,对象的行为是基于它的内部状态而改变的。
这个模式允许某个类对象在运行时发生改变。
### 示例:
*/
final class Context {
private var state: State = UnauthorizedState()
var isAuthorized: Bool {
get { return state.isAuthorized(context: self) }
}
var userId: String? {
get { return state.userId(context: self) }
}
func changeStateToAuthorized(userId: String) {
state = AuthorizedState(userId: userId)
}
func changeStateToUnauthorized() {
state = UnauthorizedState()
}
}
protocol State {
func isAuthorized(context: Context) -> Bool
func userId(context: Context) -> String?
}
class UnauthorizedState: State {
func isAuthorized(context: Context) -> Bool { return false }
func userId(context: Context) -> String? { return nil }
}
class AuthorizedState: State {
let userId: String
init(userId: String) { self.userId = userId }
func isAuthorized(context: Context) -> Bool { return true }
func userId(context: Context) -> String? { return userId }
}
/*:
### 用法
*/
let userContext = Context()
(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId: "admin")
(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()
(userContext.isAuthorized, userContext.userId)
/*:
💡 策略(Strategy)
--------------
对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。策略模式:
* 定义了一族算法(业务规则);
* 封装了每个算法;
* 这族的算法可互换代替(interchangeable)。
### 示例:
*/
struct TestSubject {
let pupilDiameter: Double
let blushResponse: Double
let isOrganic: Bool
}
protocol RealnessTesting: AnyObject {
func testRealness(_ testSubject: TestSubject) -> Bool
}
final class VoightKampffTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
}
}
final class GeneticTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.isOrganic
}
}
final class BladeRunner {
private let strategy: RealnessTesting
init(test: RealnessTesting) {
self.strategy = test
}
func testIfAndroid(_ testSubject: TestSubject) -> Bool {
return !strategy.testRealness(testSubject)
}
}
/*:
### 用法
*/
let rachel = TestSubject(pupilDiameter: 30.2,
blushResponse: 0.3,
isOrganic: false)
// Deckard is using a traditional test
let deckard = BladeRunner(test: VoightKampffTest())
let isRachelAndroid = deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
let gaff = BladeRunner(test: GeneticTest())
let isDeckardAndroid = gaff.testIfAndroid(rachel)
/*:
📝 模板方法模式
-----------
模板方法模式是一种行为设计模式, 它通过父类/协议中定义了一个算法的框架, 允许子类/具体实现对象在不修改结构的情况下重写算法的特定步骤。
### 示例:
*/
protocol Garden {
func prepareSoil()
func plantSeeds()
func waterPlants()
func prepareGarden()
}
extension Garden {
func prepareGarden() {
prepareSoil()
plantSeeds()
waterPlants()
}
}
final class RoseGarden: Garden {
func prepare() {
prepareGarden()
}
func prepareSoil() {
print ("prepare soil for rose garden")
}
func plantSeeds() {
print ("plant seeds for rose garden")
}
func waterPlants() {
print ("water the rose garden")
}
}
/*:
### 用法
*/
let roseGarden = RoseGarden()
roseGarden.prepare()
/*:
🏃 访问者(Visitor)
--------------
封装某些作用于某种数据结构中各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。
### 示例:
*/
protocol PlanetVisitor {
func visit(planet: PlanetAlderaan)
func visit(planet: PlanetCoruscant)
func visit(planet: PlanetTatooine)
func visit(planet: MoonJedha)
}
protocol Planet {
func accept(visitor: PlanetVisitor)
}
final class MoonJedha: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetAlderaan: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetCoruscant: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetTatooine: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class NameVisitor: PlanetVisitor {
var name = ""
func visit(planet: PlanetAlderaan) { name = "Alderaan" }
func visit(planet: PlanetCoruscant) { name = "Coruscant" }
func visit(planet: PlanetTatooine) { name = "Tatooine" }
func visit(planet: MoonJedha) { name = "Jedha" }
}
/*:
### 用法
*/
let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]
let names = planets.map { (planet: Planet) -> String in
let visitor = NameVisitor()
planet.accept(visitor: visitor)
return visitor.name
}
names
|
gpl-3.0
|
a6a82761f0e2b39f370e5f806f0b8dfc
| 21.355769 | 111 | 0.65745 | 3.47237 | false | true | false | false |
erikmartens/NearbyWeather
|
NearbyWeather/Routing/Settings Flow/SettingsFlow.swift
|
1
|
9099
|
//
// SettingsFlow.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 19.04.20.
// Copyright © 2020 Erik Maximilian Martens. All rights reserved.
//
import RxSwift
import RxFlow
import Swinject
// MARK: - Dependencies
extension SettingsFlow {
struct Dependencies {
let dependencyContainer: Container
}
}
// MARK: - Definitions {
private extension SettingsFlow {
struct Definitions {
static let preferredTableViewStyle = UITableView.Style.insetGrouped
}
}
// MARK: - Class Definition
final class SettingsFlow: Flow {
// MARK: - Assets
var root: Presentable {
rootViewController
}
private lazy var rootViewController = Factory.NavigationController.make(fromType: .standardTabbed(
tabTitle: R.string.localizable.tab_settings(),
systemImageName: "gear"
))
// MARK: - Properties
let dependencies: Dependencies
// MARK: - Initialization
init(dependencies: Dependencies) {
self.dependencies = dependencies
}
deinit {
printDebugMessage(
domain: String(describing: self),
message: "was deinitialized",
type: .info
)
}
// MARK: - Functions
func navigate(to step: Step) -> FlowContributors { // swiftlint:disable:this cyclomatic_complexity
guard let step = step as? SettingsStep else {
return .none
}
switch step {
case .settings:
return summonSettingsController()
case .about:
return summonAboutAppFlow()
case .apiKeyEdit:
return summonApiKeyEditFlow()
case .manageBookmarks:
return summonManageBookmarksFlow()
case .addBookmark:
return summonAddBookmarkFlow()
case .changePreferredBookmarkAlert:
return .none // will be handled via `func adapt(step:)`
case let .changePreferredBookmarkAlertAdapted(selectionDelegate, selectedOptionValue, boomarkedLocations):
return summonChangePreferredBookmarkAlert(selectionDelegate: selectionDelegate, preferredBookmarkOption: selectedOptionValue, bookmarkedLocations: boomarkedLocations)
case .changeTemperatureUnitAlert:
return .none // will be handled via `func adapt(step:)`
case let .changeTemperatureUnitAlertAdapted(selectionDelegate, currentSelectedOptionValue):
return summonChangeTemperatureUnitAlert(selectionDelegate: selectionDelegate, currentSelectedOptionValue: currentSelectedOptionValue)
case .changeDimensionalUnitAlert:
return .none // will be handled via `func adapt(step:)`
case let .changeDimensionalUnitAlertAdapted(selectionDelegate, selectedOptionValue):
return summonChangeDimensionalUnitAlert(selectionDelegate: selectionDelegate, currentSelectedOptionValue: selectedOptionValue)
case let .webBrowser(url):
return summonWebBrowser(url: url)
case .pop:
return popPushedViewController()
}
}
func adapt(step: Step) -> Single<Step> {
guard let step = step as? SettingsStep else {
return .just(step)
}
switch step {
case let .changePreferredBookmarkAlert(selectionDelegate):
return Observable
.combineLatest(
Observable.just(selectionDelegate),
dependencies.dependencyContainer.resolve(WeatherStationService.self)!.createGetPreferredBookmarkObservable(),
dependencies.dependencyContainer.resolve(WeatherStationService.self)!.createGetBookmarkedStationsObservable().take(1),
resultSelector: SettingsStep.changePreferredBookmarkAlertAdapted
)
.take(1)
.asSingle()
case let .changeTemperatureUnitAlert(selectionDelegate):
return Observable
.combineLatest(
Observable.just(selectionDelegate),
dependencies.dependencyContainer.resolve(PreferencesService.self)!.createGetTemperatureUnitOptionObservable().map { $0.value }.take(1),
resultSelector: SettingsStep.changeTemperatureUnitAlertAdapted
)
.take(1)
.asSingle()
case let .changeDimensionalUnitAlert(selectionDelegate):
return Observable
.combineLatest(
Observable.just(selectionDelegate),
dependencies.dependencyContainer.resolve(PreferencesService.self)!.createGetDimensionalUnitsOptionObservable().map { $0.value }.take(1),
resultSelector: SettingsStep.changeDimensionalUnitAlertAdapted
)
.take(1)
.asSingle()
default:
return .just(step)
}
}
}
// MARK: - Summoning Functions
private extension SettingsFlow {
func summonSettingsController() -> FlowContributors {
let settingsViewController = SettingsViewController(dependencies: SettingsViewModel.Dependencies(
weatherStationService: dependencies.dependencyContainer.resolve(WeatherStationService.self)!,
preferencesService: dependencies.dependencyContainer.resolve(PreferencesService.self)!,
notificationService: dependencies.dependencyContainer.resolve(NotificationService.self)!
))
rootViewController.setViewControllers([settingsViewController], animated: false)
return .one(flowContributor: .contribute(
withNextPresentable: settingsViewController,
withNextStepper: settingsViewController.viewModel,
allowStepWhenNotPresented: true
))
}
func summonAboutAppFlow() -> FlowContributors {
let aboutAppFlow = AboutAppFlow(dependencies: AboutAppFlow.Dependencies(
flowPresentationStyle: .pushed(navigationController: rootViewController),
endingStep: SettingsStep.pop,
dependencyContainer: dependencies.dependencyContainer
))
let aboutAppStepper = AboutAppStepper()
return .one(flowContributor: .contribute(withNextPresentable: aboutAppFlow, withNextStepper: aboutAppStepper))
}
func summonApiKeyEditFlow() -> FlowContributors {
let apiKeyInputFlow = ApiKeyInputFlow(dependencies: ApiKeyInputFlow.Dependencies(
flowPresentationStyle: .pushed(navigationController: rootViewController),
endingStep: SettingsStep.pop,
dependencyContainer: dependencies.dependencyContainer
))
let apiKeyInputStepper = ApiKeyInputStepper()
return .one(flowContributor: .contribute(withNextPresentable: apiKeyInputFlow, withNextStepper: apiKeyInputStepper))
}
func summonManageBookmarksFlow() -> FlowContributors {
let manageBookmarksFlow = ManageBookmarksFlow(dependencies: ManageBookmarksFlow.Dependencies(
flowPresentationStyle: .pushed(navigationController: rootViewController),
endingStep: SettingsStep.pop,
dependencyContainer: dependencies.dependencyContainer
))
let manageBookmarksStepper = ManageBookmarksStepper()
return .one(flowContributor: .contribute(withNextPresentable: manageBookmarksFlow, withNextStepper: manageBookmarksStepper))
}
func summonAddBookmarkFlow() -> FlowContributors {
let addBookmarkFlow = AddBookmarkFlow(dependencies: AddBookmarkFlow.Dependencies(
flowPresentationStyle: .pushed(navigationController: rootViewController),
endingStep: SettingsStep.pop,
dependencyContainer: dependencies.dependencyContainer
))
let addBookmarkStepper = AddBookmarkStepper()
return .one(flowContributor: .contribute(withNextPresentable: addBookmarkFlow, withNextStepper: addBookmarkStepper))
}
func summonChangePreferredBookmarkAlert(selectionDelegate: PreferredBookmarkSelectionAlertDelegate, preferredBookmarkOption: PreferredBookmarkOption?, bookmarkedLocations: [WeatherStationDTO]) -> FlowContributors {
let alert = PreferredBookmarkSelectionAlert(dependencies: PreferredBookmarkSelectionAlert.Dependencies(
preferredBookmarkOption: preferredBookmarkOption,
bookmarkedLocations: bookmarkedLocations,
selectionDelegate: selectionDelegate
))
rootViewController.present(alert.alertController, animated: true, completion: nil)
return .none
}
func summonChangeTemperatureUnitAlert(selectionDelegate: TemperatureUnitSelectionAlertDelegate, currentSelectedOptionValue: TemperatureUnitOptionValue) -> FlowContributors {
let alert = TemperatureUnitSelectionAlert(dependencies: TemperatureUnitSelectionAlert.Dependencies(
selectionDelegate: selectionDelegate,
selectedOptionValue: currentSelectedOptionValue
))
rootViewController.present(alert.alertController, animated: true, completion: nil)
return .none
}
func summonChangeDimensionalUnitAlert(selectionDelegate: DimensionalUnitSelectionAlertDelegate, currentSelectedOptionValue: DimensionalUnitOptionValue) -> FlowContributors {
let alert = DimensionalUnitSelectionAlert(dependencies: DimensionalUnitSelectionAlert.Dependencies(
selectionDelegate: selectionDelegate,
selectedOptionValue: currentSelectedOptionValue
))
rootViewController.present(alert.alertController, animated: true, completion: nil)
return .none
}
func summonWebBrowser(url: URL) -> FlowContributors {
rootViewController.presentSafariViewController(for: url)
return .none
}
func popPushedViewController() -> FlowContributors {
rootViewController.popViewController(animated: true)
return .none
}
}
|
mit
|
a5e01d26be31c172077ffe849ec8a877
| 37.550847 | 216 | 0.758299 | 5.157596 | false | false | false | false |
wangyun-hero/sinaweibo-with-swift
|
sinaweibo/Classes/Tools/IBExtension/UIImage+Extension.swift
|
1
|
1935
|
//
// UIImage+Extension.swift
// sinaweibo
//
// Created by 王云 on 16/9/7.
// Copyright © 2016年 王云. All rights reserved.
//
import UIKit
extension UIImage {
/// 截屏的功能
///
/// - returns: <#return value description#>
class func getScreenSnap() -> UIImage? {
// 先获取到window
let window = UIApplication.shared.keyWindow!
// 开启上下文
// 如果最后一参数传入0的话,会按照屏幕的真实大小来截取,就是不会截取缩放之后的内容
UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, 0)
// 将window的内容渲染到上下文中
window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
// 取到上下文中的图片
let image = UIGraphicsGetImageFromCurrentImageContext()
// 关闭上下文
UIGraphicsEndImageContext()
// 保存到桌面
// let data = UIImagePNGRepresentation(image!)! as NSData
// data.write(toFile: "/Users/gaolingfeng/Desktop/Untitled.png", atomically: true)
// 返回结果
return image
}
func scaleTo(width:CGFloat) -> UIImage {
if self.size.width < width {
return self
}
//根据宽度求出等比例缩放之后的高度
let height = self.size.height * (width / self.size.width)
//定义一个范围
let rect = CGRect(x: 0, y: 0, width: width, height: height)
//开启上下文
UIGraphicsBeginImageContext(rect.size)
// 会将当前图片的所有内容完整的画到上下文中
self.draw(in: rect)
//取值
let result = UIGraphicsGetImageFromCurrentImageContext()!
//关闭上下文
UIGraphicsEndImageContext()
//返回
return result
}
}
|
mit
|
601acfeb15d0fae49018c47e74e0f643
| 25.852459 | 97 | 0.573871 | 4.276762 | false | false | false | false |
PANDA-Guide/PandaGuideApp
|
Carthage/Checkouts/SwiftTweaks/SwiftTweaks/TweakStore+Sharing.swift
|
1
|
1464
|
//
// TweakStore+Sharing.swift
// SwiftTweaks
//
// Created by Bryan Clark on 11/19/15.
// Copyright © 2015 Khan Academy. All rights reserved.
//
import UIKit
internal extension TweakStore {
internal var textRepresentation: String {
// Let's sort our tweaks by collection/group/name, and then return the list!
let returnValue: String = sortedTweakCollections
.reduce([]) { $0 + $1.allTweaks }
.map {
let (stringValue, differs) = currentViewDataForTweak($0).stringRepresentation
let linePrefix = differs ? "* " : ""
return "\(linePrefix)\($0.tweakIdentifier) = \(stringValue)"
}.reduce("Here are your tweaks!\nA * indicates a tweaked value.") { $0 + "\n\n" + $1 }
return returnValue
}
}
@objc internal class TweakStoreActivityItemSource: NSObject {
fileprivate let textRepresentation: String
init(text: String) {
self.textRepresentation = text
}
}
extension TweakStoreActivityItemSource: UIActivityItemSource {
@objc func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return textRepresentation
}
@objc func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivityType?) -> String {
return "SwiftTweaks Backup"
}
@objc func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType) -> Any? {
return textRepresentation
}
}
|
gpl-3.0
|
8ff5367acb9192241de961c644733e31
| 31.511111 | 152 | 0.749829 | 4.328402 | false | false | false | false |
lotpb/iosSQLswift
|
mySQLswift/JobController.swift
|
1
|
15377
|
//
// JobController.swift
// mySQLswift
//
// Created by Peter Balsamo on 1/8/16.
// Copyright © 2016 Peter Balsamo. All rights reserved.
//
import UIKit
import Parse
class JobController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
let searchScope = ["job","jobNo","active"]
@IBOutlet weak var tableView: UITableView?
var isFormStat = false
var _feedItems : NSMutableArray = NSMutableArray()
var _feedheadItems : NSMutableArray = NSMutableArray()
var filteredString : NSMutableArray = NSMutableArray()
var pasteBoard = UIPasteboard.generalPasteboard()
var refreshControl: UIRefreshControl!
var searchController: UISearchController!
var resultsController: UITableViewController!
var foundUsers = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let titleButton: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 32))
titleButton.setTitle("myJobs", forState: UIControlState.Normal)
titleButton.titleLabel?.font = Font.navlabel
titleButton.titleLabel?.textAlignment = NSTextAlignment.Center
titleButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
titleButton.addTarget(self, action: Selector(), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.titleView = titleButton
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.estimatedRowHeight = 65
self.tableView!.rowHeight = UITableViewAutomaticDimension
self.tableView!.backgroundColor = UIColor(white:0.90, alpha:1.0)
self.automaticallyAdjustsScrollViewInsets = false
//users = []
foundUsers = []
resultsController = UITableViewController(style: .Plain)
resultsController.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UserFoundCell")
resultsController.tableView.dataSource = self
resultsController.tableView.delegate = self
//self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(JobController.newData))
let searchButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: #selector(JobController.searchButton))
let buttons:NSArray = [addButton,searchButton]
self.navigationItem.rightBarButtonItems = buttons as? [UIBarButtonItem]
parseData()
self.refreshControl = UIRefreshControl()
refreshControl.backgroundColor = Color.Table.navColor
refreshControl.tintColor = UIColor.whiteColor()
let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh", attributes: attributes)
self.refreshControl.addTarget(self, action: #selector(JobController.refreshData), forControlEvents: UIControlEvents.ValueChanged)
self.tableView!.addSubview(refreshControl)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//navigationController?.hidesBarsOnSwipe = true
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barTintColor = Color.Table.navColor
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
//navigationController?.hidesBarsOnSwipe = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Refresh
func refreshData(sender:AnyObject) {
parseData()
self.refreshControl?.endRefreshing()
}
// MARK: - Button
func newData() {
isFormStat = true
self.performSegueWithIdentifier("jobDetailSegue", sender: self)
}
// MARK: - Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
return _feedItems.count ?? 0
}
return foundUsers.count
//return filteredString.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier: String!
if tableView == self.tableView {
cellIdentifier = "Cell"
} else {
cellIdentifier = "UserFoundCell"
}
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! CustomTableCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad {
cell.jobtitleLabel!.font = Font.celltitle
} else {
cell.jobtitleLabel!.font = Font.celltitle
}
if (tableView == self.tableView) {
cell.jobtitleLabel!.text = _feedItems[indexPath.row] .valueForKey("Description") as? String
} else {
cell.jobtitleLabel!.text = filteredString[indexPath.row] .valueForKey("Description") as? String
}
let myLabel:UILabel = UILabel(frame: CGRectMake(10, 10, 50, 50))
myLabel.backgroundColor = Color.Table.labelColor
myLabel.textColor = UIColor.whiteColor()
myLabel.textAlignment = NSTextAlignment.Center
myLabel.layer.masksToBounds = true
myLabel.text = "Job's"
myLabel.font = Font.headtitle
myLabel.layer.cornerRadius = 25.0
myLabel.userInteractionEnabled = true
myLabel.tag = indexPath.row
cell.addSubview(myLabel)
return cell
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone {
return 90.0
} else {
return 0.0
}
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let vw = UIView()
vw.backgroundColor = Color.Table.navColor
//tableView.tableHeaderView = vw
let myLabel1:UILabel = UILabel(frame: CGRectMake(10, 15, 50, 50))
myLabel1.numberOfLines = 0
myLabel1.backgroundColor = UIColor.whiteColor()
myLabel1.textColor = UIColor.blackColor()
myLabel1.textAlignment = NSTextAlignment.Center
myLabel1.layer.masksToBounds = true
myLabel1.text = String(format: "%@%d", "Job's\n", _feedItems.count)
myLabel1.font = Font.headtitle
myLabel1.layer.cornerRadius = 25.0
myLabel1.userInteractionEnabled = true
vw.addSubview(myLabel1)
let separatorLineView1 = UIView(frame: CGRectMake(10, 75, 50, 2.5))
separatorLineView1.backgroundColor = Color.Table.labelColor
vw.addSubview(separatorLineView1)
let myLabel2:UILabel = UILabel(frame: CGRectMake(80, 15, 50, 50))
myLabel2.numberOfLines = 0
myLabel2.backgroundColor = UIColor.whiteColor()
myLabel2.textColor = UIColor.blackColor()
myLabel2.textAlignment = NSTextAlignment.Center
myLabel2.layer.masksToBounds = true
myLabel2.text = String(format: "%@%d", "Active\n", _feedheadItems.count)
myLabel2.font = Font.headtitle
myLabel2.layer.cornerRadius = 25.0
myLabel2.userInteractionEnabled = true
vw.addSubview(myLabel2)
let separatorLineView2 = UIView(frame: CGRectMake(80, 75, 50, 2.5))
separatorLineView2.backgroundColor = Color.Table.labelColor
vw.addSubview(separatorLineView2)
let myLabel3:UILabel = UILabel(frame: CGRectMake(150, 15, 50, 50))
myLabel3.numberOfLines = 0
myLabel3.backgroundColor = UIColor.whiteColor()
myLabel3.textColor = UIColor.blackColor()
myLabel3.textAlignment = NSTextAlignment.Center
myLabel3.layer.masksToBounds = true
myLabel3.text = "Active"
myLabel3.font = Font.headtitle
myLabel3.layer.cornerRadius = 25.0
myLabel3.userInteractionEnabled = true
vw.addSubview(myLabel3)
let separatorLineView3 = UIView(frame: CGRectMake(150, 75, 50, 2.5))
separatorLineView3.backgroundColor = Color.Table.labelColor
vw.addSubview(separatorLineView3)
return vw
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let query = PFQuery(className:"Job")
query.whereKey("objectId", equalTo:(self._feedItems.objectAtIndex(indexPath.row) .valueForKey("objectId") as? String)!)
let alertController = UIAlertController(title: "Delete", message: "Confirm Delete", preferredStyle: .Alert)
let destroyAction = UIAlertAction(title: "Delete!", style: .Destructive) { (action) in
query.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects! {
object.deleteInBackground()
self.refreshData(self)
}
}
})
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
self.refreshData(self)
}
alertController.addAction(cancelAction)
alertController.addAction(destroyAction)
self.presentViewController(alertController, animated: true) {
}
_feedItems.removeObjectAtIndex(indexPath.row)
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.
}
}
// MARK: - Content Menu
func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if (action == #selector(NSObject.copy(_:))) {
return true
}
return false
}
func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
pasteBoard.string = cell!.textLabel?.text
}
// MARK: - Search
func searchButton(sender: AnyObject) {
searchController = UISearchController(searchResultsController: resultsController)
searchController.searchBar.searchBarStyle = .Prominent
searchController.searchResultsUpdater = self
searchController.searchBar.showsBookmarkButton = false
searchController.searchBar.showsCancelButton = true
searchController.searchBar.placeholder = "Search here..."
searchController.searchBar.sizeToFit()
definesPresentationContext = true
searchController.dimsBackgroundDuringPresentation = true
searchController.hidesNavigationBarDuringPresentation = true
searchController.searchBar.scopeButtonTitles = searchScope
//tableView!.tableHeaderView = searchController.searchBar
tableView!.tableFooterView = UIView(frame: .zero)
UISearchBar.appearance().barTintColor = Color.Table.navColor
self.presentViewController(searchController, animated: true, completion: nil)
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
}
// MARK: - Parse
func parseData() {
let query = PFQuery(className:"Job")
//query.limit = 1000
query.orderByAscending("Description")
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self._feedItems = temp.mutableCopy() as! NSMutableArray
self.tableView!.reloadData()
} else {
print("Error")
}
}
let query1 = PFQuery(className:"Job")
query1.whereKey("Active", equalTo:"Active")
query1.cachePolicy = PFCachePolicy.CacheThenNetwork
query1.orderByDescending("createdAt")
query1.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self._feedheadItems = temp.mutableCopy() as! NSMutableArray
self.tableView!.reloadData()
} else {
print("Error")
}
}
}
// MARK: - Segues
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView == resultsController.tableView {
//userDetails = foundUsers[indexPath.row]
//self.performSegueWithIdentifier("PushDetailsVC", sender: self)
} else {
isFormStat = false
self.performSegueWithIdentifier("jobDetailSegue", sender: self)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "jobDetailSegue" {
let VC = segue.destinationViewController as? NewEditData
VC!.formController = "Jobs"
if (isFormStat == true) {
VC!.formStatus = "New"
} else {
VC!.formStatus = "Edit"
let myIndexPath = self.tableView!.indexPathForSelectedRow!.row
VC!.objectId = _feedItems[myIndexPath] .valueForKey("objectId") as? String
VC!.frm11 = _feedItems[myIndexPath] .valueForKey("Active") as? String
VC!.frm12 = _feedItems[myIndexPath] .valueForKey("JobNo") as? String
VC!.frm13 = _feedItems[myIndexPath] .valueForKey("Description") as? String
}
}
}
}
//-----------------------end------------------------------
|
gpl-2.0
|
16af9e850009312ef7f8ad20d04cf34e
| 38.628866 | 160 | 0.632999 | 5.544897 | false | false | false | false |
DarrenKong/firefox-ios
|
Client/Frontend/Browser/QRCodeViewController.swift
|
2
|
11884
|
/* 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 AVFoundation
import SnapKit
import Shared
private struct QRCodeViewControllerUX {
static let navigationBarBackgroundColor = UIColor.black
static let navigationBarTitleColor = UIColor.white
static let maskViewBackgroungColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
static let isLightingNavigationItemColor = UIColor(red: 0.45, green: 0.67, blue: 0.84, alpha: 1)
}
protocol QRCodeViewControllerDelegate {
func didScanQRCodeWithURL(_ url: URL)
func didScanQRCodeWithText(_ text: String)
}
class QRCodeViewController: UIViewController {
var qrCodeDelegate: QRCodeViewControllerDelegate?
fileprivate lazy var captureSession: AVCaptureSession = {
let session = AVCaptureSession()
session.sessionPreset = AVCaptureSessionPresetHigh
return session
}()
private lazy var captureDevice: AVCaptureDevice? = {
return AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
}()
private var videoPreviewLayer: AVCaptureVideoPreviewLayer?
private let scanLine: UIImageView = UIImageView(image: UIImage(named: "qrcode-scanLine"))
private let scanBorder: UIImageView = UIImageView(image: UIImage(named: "qrcode-scanBorder"))
private lazy var instructionsLabel: UILabel = {
let label = UILabel()
label.text = Strings.ScanQRCodeInstructionsLabel
label.textColor = UIColor.white
label.textAlignment = .center
label.numberOfLines = 0
return label
}()
private var maskView: UIView = UIView()
private var isAnimationing: Bool = false
private var isLightOn: Bool = false
private var shapeLayer: CAShapeLayer = CAShapeLayer()
private var scanRange: CGRect {
let size = UIDevice.current.userInterfaceIdiom == .pad ?
CGSize(width: view.frame.width / 2, height: view.frame.width / 2) :
CGSize(width: view.frame.width / 3 * 2, height: view.frame.width / 3 * 2)
var rect = CGRect(size: size)
rect.center = UIScreen.main.bounds.center
return rect
}
private var scanBorderHeight: CGFloat {
return UIDevice.current.userInterfaceIdiom == .pad ?
view.frame.width / 2 : view.frame.width / 3 * 2
}
override func viewDidLoad() {
super.viewDidLoad()
guard let captureDevice = self.captureDevice else {
dismiss(animated: false)
return
}
self.navigationItem.title = Strings.ScanQRCodeViewTitle
// Setup the NavigationBar
self.navigationController?.navigationBar.barTintColor = QRCodeViewControllerUX.navigationBarBackgroundColor
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: QRCodeViewControllerUX.navigationBarTitleColor]
// Setup the NavigationItem
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "qrcode-goBack"), style: .plain, target: self, action: #selector(goBack))
self.navigationItem.leftBarButtonItem?.tintColor = UIColor.white
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "qrcode-light"), style: .plain, target: self, action: #selector(openLight))
if captureDevice.hasTorch {
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.white
} else {
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.gray
self.navigationItem.rightBarButtonItem?.isEnabled = false
}
let getAuthorizationStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if getAuthorizationStatus != .denied {
setupCamera()
} else {
let alert = UIAlertController(title: "", message: Strings.ScanQRCodePermissionErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.ScanQRCodeErrorOKButton, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
maskView.backgroundColor = QRCodeViewControllerUX.maskViewBackgroungColor
self.view.addSubview(maskView)
self.view.addSubview(scanBorder)
self.view.addSubview(scanLine)
self.view.addSubview(instructionsLabel)
setupConstraints()
let rectPath = UIBezierPath(rect: UIScreen.main.bounds)
rectPath.append(UIBezierPath(rect: scanRange).reversing())
shapeLayer.path = rectPath.cgPath
maskView.layer.mask = shapeLayer
isAnimationing = true
startScanLineAnimation()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.captureSession.stopRunning()
stopScanLineAnimation()
}
private func setupConstraints() {
maskView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
if UIDevice.current.userInterfaceIdiom == .pad {
scanBorder.snp.makeConstraints { (make) in
make.center.equalTo(self.view)
make.width.height.equalTo(view.frame.width / 2)
}
} else {
scanBorder.snp.makeConstraints { (make) in
make.center.equalTo(self.view)
make.width.height.equalTo(view.frame.width / 3 * 2)
}
}
scanLine.snp.makeConstraints { (make) in
make.left.equalTo(scanBorder.snp.left)
make.top.equalTo(scanBorder.snp.top).offset(6)
make.width.equalTo(scanBorder.snp.width)
make.height.equalTo(6)
}
instructionsLabel.snp.makeConstraints { (make) in
make.left.right.equalTo(self.view.layoutMarginsGuide)
make.top.equalTo(scanBorder.snp.bottom).offset(30)
}
}
func startScanLineAnimation() {
if !isAnimationing {
return
}
self.view.layoutIfNeeded()
self.view.setNeedsLayout()
UIView.animate(withDuration: 2.4, animations: {
self.scanLine.snp.updateConstraints({ (make) in
make.top.equalTo(self.scanBorder.snp.top).offset(self.scanBorderHeight - 6)
})
self.view.layoutIfNeeded()
}) { (value: Bool) in
self.scanLine.snp.updateConstraints({ (make) in
make.top.equalTo(self.scanBorder.snp.top).offset(6)
})
self.perform(#selector(self.startScanLineAnimation), with: nil, afterDelay: 0)
}
}
func stopScanLineAnimation() {
isAnimationing = false
}
func goBack() {
self.dismiss(animated: true, completion: nil)
}
func openLight() {
guard let captureDevice = self.captureDevice else {
return
}
if isLightOn {
do {
try captureDevice.lockForConfiguration()
captureDevice.torchMode = AVCaptureTorchMode.off
captureDevice.unlockForConfiguration()
navigationItem.rightBarButtonItem?.image = UIImage(named: "qrcode-light")
navigationItem.rightBarButtonItem?.tintColor = UIColor.white
} catch {
print(error)
}
} else {
do {
try captureDevice.lockForConfiguration()
captureDevice.torchMode = AVCaptureTorchMode.on
captureDevice.unlockForConfiguration()
navigationItem.rightBarButtonItem?.image = UIImage(named: "qrcode-isLighting")
navigationItem.rightBarButtonItem?.tintColor = QRCodeViewControllerUX.isLightingNavigationItemColor
} catch {
print(error)
}
}
isLightOn = !isLightOn
}
func setupCamera() {
guard let captureDevice = self.captureDevice else {
dismiss(animated: false)
return
}
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(input)
} catch {
print(error)
}
let output = AVCaptureMetadataOutput()
if captureSession.canAddOutput(output) {
captureSession.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
}
if let videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer.frame = UIScreen.main.bounds
view.layer.addSublayer(videoPreviewLayer)
self.videoPreviewLayer = videoPreviewLayer
captureSession.startRunning()
}
}
override func willAnimateRotation(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
shapeLayer.removeFromSuperlayer()
let rectPath = UIBezierPath(rect: UIScreen.main.bounds)
rectPath.append(UIBezierPath(rect: scanRange).reversing())
shapeLayer.path = rectPath.cgPath
maskView.layer.mask = shapeLayer
guard let videoPreviewLayer = self.videoPreviewLayer else {
return
}
videoPreviewLayer.frame = UIScreen.main.bounds
switch toInterfaceOrientation {
case .portrait:
videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientation.portrait
case .landscapeLeft:
videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientation.landscapeLeft
case .landscapeRight:
videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientation.landscapeRight
case .portraitUpsideDown:
videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientation.portraitUpsideDown
default:
videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientation.portrait
}
}
}
extension QRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
if metadataObjects == nil || metadataObjects.count == 0 {
self.captureSession.stopRunning()
let alert = UIAlertController(title: "", message: Strings.ScanQRCodeInvalidDataErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.ScanQRCodeErrorOKButton, style: .default, handler: { (UIAlertAction) in
self.captureSession.startRunning()
}))
self.present(alert, animated: true, completion: nil)
} else {
self.captureSession.stopRunning()
stopScanLineAnimation()
self.dismiss(animated: true, completion: {
guard let metaData = metadataObjects.first as? AVMetadataMachineReadableCodeObject, let qrCodeDelegate = self.qrCodeDelegate, let text = metaData.stringValue else {
Sentry.shared.sendWithStacktrace(message: "Unable to scan QR code", tag: .general)
return
}
if let url = URIFixup.getURL(text) {
qrCodeDelegate.didScanQRCodeWithURL(url)
} else {
qrCodeDelegate.didScanQRCodeWithText(text)
}
})
}
}
}
class QRCodeNavigationController: UINavigationController {
override open var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
|
mpl-2.0
|
781f29f0d05550eecbf5682f6f0468df
| 39.838488 | 180 | 0.65685 | 5.466421 | false | false | false | false |
ashfurrow/RxSwift
|
RxSwift/Observables/Observable+Creation.swift
|
3
|
7873
|
//
// Observable+Creation.swift
// Rx
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// MARK: create
/**
Creates an observable sequence from a specified subscribe method implementation.
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func create<E>(subscribe: (AnyObserver<E>) -> Disposable) -> Observable<E> {
return AnonymousObservable(subscribe)
}
// MARK: empty
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- parameter type: Optional type hint.
- returns: An observable sequence with no elements.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func empty<E>(type: E.Type = E.self) -> Observable<E> {
return Empty<E>()
}
// MARK: never
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- parameter type: Optional type hint.
- returns: An observable sequence whose observers will never get called.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func never<E>(type: E.Type = E.self) -> Observable<E> {
return Never()
}
// MARK: just
/**
Returns an observable sequence that contains a single element.
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func just<E>(element: E) -> Observable<E> {
return Just(element: element)
}
/**
Returns an observable sequence that contains a single element.
- parameter element: Single element in the resulting observable sequence.
- parameter: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func just<E>(element: E, scheduler: ImmediateSchedulerType) -> Observable<E> {
return JustScheduled(element: element, scheduler: scheduler)
}
// MARK: of
/**
This method creates a new Observable instance with a variable number of elements.
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription.
- returns: The observable sequence whose elements are pulled from the given arguments.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func sequenceOf<E>(elements: E ..., scheduler: ImmediateSchedulerType? = nil) -> Observable<E> {
return Sequence(elements: elements, scheduler: scheduler)
}
extension SequenceType {
/**
Converts a sequence to an observable sequence.
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
@available(*, deprecated=2.0.0, message="Please use toObservable extension.")
public func asObservable() -> Observable<Generator.Element> {
return Sequence(elements: Array(self), scheduler: nil)
}
/**
Converts a sequence to an observable sequence.
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func toObservable(scheduler: ImmediateSchedulerType? = nil) -> Observable<Generator.Element> {
return Sequence(elements: Array(self), scheduler: scheduler)
}
}
extension Array {
/**
Converts a sequence to an observable sequence.
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func toObservable(scheduler: ImmediateSchedulerType? = nil) -> Observable<Generator.Element> {
return Sequence(elements: self, scheduler: scheduler)
}
}
// MARK: fail
/**
Returns an observable sequence that terminates with an `error`.
- parameter type: Optional type hint.
- returns: The observable sequence that terminates with specified error.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func failWith<E>(error: ErrorType, _ type: E.Type = E.self) -> Observable<E> {
return FailWith(error: error)
}
// MARK: defer
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func deferred<E>(observableFactory: () throws -> Observable<E>)
-> Observable<E> {
return Deferred(observableFactory: observableFactory)
}
/**
Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler
to run the loop send out observer messages.
- parameter initialState: Initial state.
- parameter condition: Condition to terminate generation (upon returning `false`).
- parameter iterate: Iteration step function.
- parameter scheduler: Scheduler on which to run the generator loop.
- returns: The generated sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func generate<E>(initialState: E, condition: E throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: E throws -> E) -> Observable<E> {
return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler)
}
/**
Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages.
- parameter start: The value of the first integer in the sequence.
- parameter count: The number of sequential integers to generate.
- parameter scheduler: Scheduler to run the generator loop on.
- returns: An observable sequence that contains a range of sequential integral numbers.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func range(start: Int, _ count: Int, _ scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<Int> {
return RangeProducer<Int>(start: start, count: count, scheduler: scheduler)
}
/**
Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages.
- parameter element: Element to repeat.
- parameter scheduler: Scheduler to run the producer loop on.
- returns: An observable sequence that repeats the given element infinitely.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func repeatElement<E>(element: E, _ scheduler: ImmediateSchedulerType) -> Observable<E> {
return RepeatElement(element: element, scheduler: scheduler)
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func using<S, R: Disposable>(resourceFactory: () throws -> R, observableFactory: R throws -> Observable<S>) -> Observable<S> {
return Using(resourceFactory: resourceFactory, observableFactory: observableFactory)
}
|
mit
|
f889fcd50ae2595698730c3562e46823
| 37.975248 | 181 | 0.752191 | 4.297489 | false | false | false | false |
bubnov/SBTableViewAdapter
|
TableViewAdapter/ValueContainer.swift
|
2
|
868
|
//
// ValueContainer.swift
// Collections
//
// Created by Bubnov Slavik on 02/03/2017.
// Copyright © 2017 Bubnov Slavik. All rights reserved.
//
import Foundation
public protocol ValueContainerType: class {
var value: Any? { get }
var isDynamic: Bool { get }
}
public class ValueContainer: ValueContainerType {
public typealias DynamicValueClosure = () -> Any
private var _value: Any?
private var _dynamicValue: DynamicValueClosure?
public var value: Any? {
if _value != nil { return _value }
if _dynamicValue != nil { return _dynamicValue!() }
return nil
}
public var isDynamic: Bool {
return _dynamicValue != nil
}
init(value: Any?) {
_value = value
}
init(closure: @escaping DynamicValueClosure) {
_dynamicValue = closure
}
}
|
mit
|
cdc2fbfdce11897ffd37fca0ee616528
| 19.642857 | 59 | 0.61361 | 4.148325 | false | false | false | false |
hgani/ganilib-ios
|
glib/Classes/JsonUi/Views/Panels/Split.swift
|
1
|
1248
|
class JsonView_Panels_SplitV1: JsonView {
private let panel = GSplitPanel().width(.matchParent)
override func initView() -> UIView {
let content = spec["content"]
if let center = content["center"].presence {
return panel.withViews(
createSubview(content["left"], center: false),
createSubview(center, center: true),
createSubview(content["right"], center: false)
)
} else {
return panel.withViews(
left: createSubview(content["left"], center: false),
right: createSubview(content["right"], center: false)
)
}
}
private func createSubview(_ subviewSpec: Json, center: Bool) -> UIView {
if subviewSpec.isNull {
return GView().width(0)
}
let view = JsonView.create(spec: subviewSpec, screen: screen)?.createView() ?? UIView()
if center, let iview = view as? IView {
// Make sure the center view doesn't stretch up until the right of the container.
// Let the split view stretch it only up until the left of the right component.
iview.width(.wrapContent)
}
return view
}
}
|
mit
|
4fce24fb059a217be8915f1d4f7a2076
| 36.818182 | 95 | 0.573718 | 4.622222 | false | false | false | false |
sivaganeshsg/Virtual-Tourist-iOS-App
|
VirtualTorist/ViewController.swift
|
1
|
4284
|
//
// ViewController.swift
// VirtualTorist
//
// Created by Siva Ganesh on 27/11/15.
// Copyright © 2015 Siva Ganesh. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import CoreData
class ViewController: UIViewController, MKMapViewDelegate {
// MARK: - Core Data Convenience. This will be useful for fetching. And for adding and saving objects as well.
var sharedContext: NSManagedObjectContext {
return CoreDataStackManager.sharedInstance().managedObjectContext!
}
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
getLocations()
// 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.
}
@IBOutlet weak var mapView: MKMapView!
@IBOutlet var longPressRecogniser: UILongPressGestureRecognizer!
// Add New PIN
@IBAction func handleLongPressAction(sender: UILongPressGestureRecognizer) {
print("Adding new pin")
let getstureRecognizer = sender as UILongPressGestureRecognizer
if getstureRecognizer.state != .Began { return }
let touchPoint = getstureRecognizer.locationInView(self.mapView)
let touchMapCoordinate = mapView.convertPoint(touchPoint, toCoordinateFromView: mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = touchMapCoordinate
let newLocation = saveNewLocation(touchMapCoordinate.latitude, longitude: touchMapCoordinate.longitude)
addLocationToMap(newLocation)
// mapView.addAnnotation(newLocation)
}
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
let place = view.annotation as! Place
let singlePlaceVC = self.storyboard?.instantiateViewControllerWithIdentifier("SinglePlaceViewController") as! SinglePlaceViewController
singlePlaceVC.place = place
self.navigationController?.pushViewController(singlePlaceVC, animated: true)
}
// Helper Functions
func getLocations(){
let locations = getLocationsFromCoreData()
for location in locations {
addLocationToMap(location)
}
}
func getLocationsFromCoreData() -> [Place] {
var error: NSError?
let fetchRequest = NSFetchRequest(entityName: "Place")
let locations: [AnyObject]?
do {
locations = try sharedContext.executeFetchRequest(fetchRequest)
} catch let CDError as NSError {
error = CDError
locations = nil
}
if let errorMsg = error {
let alertController = UIAlertController(title: "Error", message:
errorMsg.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
return locations as! [Place]
}
func addLocationToMap(location: Place) {
dispatch_async(dispatch_get_main_queue(), {
self.mapView.addAnnotation(location)
})
}
func saveNewLocation(latitude : Double, longitude : Double) -> Place{
let locDict = ["latitude" : latitude, "longitude" : longitude]
let newLocation = Place(dictionary: locDict, context: sharedContext)
print(newLocation)
do{
try sharedContext.save()
}catch{
print(error)
}
return newLocation
}
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2000.0, regionRadius * 2000.0)
mapView.setRegion(coordinateRegion, animated: true)
}
}
|
apache-2.0
|
68bd2475386143f363e5c58846d2f2f1
| 28.951049 | 143 | 0.640906 | 5.725936 | false | false | false | false |
wyp767363905/GiftSay
|
GiftSay/GiftSay/classes/category/categoryDetail/model/CDModel.swift
|
1
|
5391
|
//
// CDModel.swift
// GiftSay
//
// Created by qianfeng on 16/9/5.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
import SwiftyJSON
class CDModel: NSObject {
var code: NSNumber?
var data: CDDataModel?
var message: String?
class func parseModel(data: NSData) -> CDModel {
let jsonData = JSON(data: data)
let model = CDModel()
model.code = jsonData["code"].number
model.message = jsonData["message"].string
model.data = CDDataModel.parseModel(jsonData["data"])
return model
}
}
class CDDataModel: NSObject {
var banner_image_url: String?
var banner_webp_url: String?
var category: String?
var cover_image_url: String?
var cover_webp_url: String?
var created_at: NSNumber?
var desc: String? //description
var id: NSNumber?
var likes_count: NSNumber?
var order: NSNumber?
var paging: CDPagingModel?
var post_published_at: NSNumber?
var posts: Array<CDPostModel>?
var share_url: String?
var status: NSNumber?
var subtitle: String?
var title: String?
var updated_at: NSNumber?
class func parseModel(jsonData: JSON) -> CDDataModel {
let model = CDDataModel()
model.banner_image_url = jsonData["banner_image_url"].string
model.banner_webp_url = jsonData["banner_webp_url"].string
model.category = jsonData["category"].string
model.cover_image_url = jsonData["cover_image_url"].string
model.cover_webp_url = jsonData["cover_webp_url"].string
model.created_at = jsonData["created_at"].number
model.desc = jsonData["description"].string
model.id = jsonData["id"].number
model.likes_count = jsonData["likes_count"].number
model.order = jsonData["order"].number
model.post_published_at = jsonData["post_published_at"].number
model.share_url = jsonData["share_url"].string
model.status = jsonData["status"].number
model.subtitle = jsonData["subtitle"].string
model.title = jsonData["title"].string
model.updated_at = jsonData["updated_at"].number
model.paging = CDPagingModel.parseModel(jsonData["paging"])
var array = Array<CDPostModel>()
for (_,subjson) in jsonData["posts"] {
let postsModel = CDPostModel.parseModel(subjson)
array.append(postsModel)
}
model.posts = array
return model
}
}
class CDPagingModel: NSObject {
var next_url: String?
class func parseModel(jsonData: JSON) -> CDPagingModel {
let model = CDPagingModel()
model.next_url = jsonData["next_url"].string
return model
}
}
class CDPostModel: NSObject {
var ad_monitors: NSArray?//
var author: CDAuthorModel?
var content_type: NSNumber?
var content_url: String?
var cover_image_url: String?
var cover_webp_url: String?
var created_at: NSNumber?
var editor_id: NSNumber?
var feature_list: NSArray?//
var id: NSNumber?
var label_ids: NSArray?//
var liked: Bool?
var likes_count: NSNumber?
var published_at: NSNumber?
var share_msg: String?
var short_title: String?
var status: NSNumber?
var template: String?
var title: String?
var updated_at: NSNumber?
var url: String?
class func parseModel(jsonData: JSON) -> CDPostModel {
let model = CDPostModel ()
model.content_type = jsonData["content_type"].number
model.content_url = jsonData["content_url"].string
model.cover_image_url = jsonData["cover_image_url"].string
model.cover_webp_url = jsonData["cover_webp_url"].string
model.created_at = jsonData["created_at"].number
model.editor_id = jsonData["editor_id"].number
model.id = jsonData["id"].number
model.liked = jsonData["liked"].bool
model.likes_count = jsonData["likes_count"].number
model.published_at = jsonData["published_at"].number
model.share_msg = jsonData["share_msg"].string
model.short_title = jsonData["short_title"].string
model.status = jsonData["status"].number
model.template = jsonData["template"].string
model.title = jsonData["title"].string
model.updated_at = jsonData["updated_at"].number
model.url = jsonData["url"].string
model.author = CDAuthorModel.parseModel(jsonData["author"])
return model
}
}
class CDAuthorModel: NSObject {
var avatar_url: String?
var created_at: NSNumber?
var id: NSNumber?
var nickname: String?
class func parseModel(jsonData: JSON) -> CDAuthorModel {
let model = CDAuthorModel()
model.avatar_url = jsonData["avatar_url"].string
model.created_at = jsonData["created_at"].number
model.id = jsonData["id"].number
model.nickname = jsonData["nickname"].string
return model
}
}
|
mit
|
569b1609999ef56c64bf39a445f56751
| 25.028986 | 70 | 0.588159 | 4.359223 | false | false | false | false |
abring/sample_ios
|
Abring/ABRNetworkManager.swift
|
1
|
2506
|
//
// ABManager.swift
// abringTest
//
// Created by Hosein Abbaspour on 5/3/1396 AP.
// Copyright © 1396 AP Sanjaqak. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
@objc public enum ABRErrorType : Int {
case invalidToken
case serverError
case noConnection
case unknownError
}
struct ABRNetworkManager {
static func request(_ url : String , tokenNeeded : Bool , parameters : [String : Any]? ,completion : @escaping (_ responseJSON : JSON? , _ errorType : ABRErrorType?) -> Void) {
assert(ABRAppConfig.name != nil, "You must set the app name: ABAppConfig.name = YOURAPPNAME")
var finalParameters : Parameters = [
"app": ABRAppConfig.name!
]
if tokenNeeded {
let token = ABRPlayer.current()?.token
assert(token != nil, "Token is nil")
finalParameters["token"] = ABRPlayer.current()?.token!
}
if parameters != nil {
for (key , value) in parameters! {
finalParameters[key] = value
}
}
if !NetworkReachabilityManager()!.isReachable {
completion(nil, ABRErrorType.noConnection)
return
}
Alamofire.request(url ,
method: .post ,
parameters: finalParameters ,
encoding: URLEncoding.default).validate().responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
print(json)
switch json["code"].string ?? "" {
case "200" :
completion(json["result"], nil)
case "401" :
//WARNING: incomplete
completion(nil, ABRErrorType.invalidToken)
default :
completion(nil, ABRErrorType.unknownError)
}
case .failure(let error):
if response.response?.statusCode == 500 {
completion(nil, ABRErrorType.serverError)
}
print(error)
}
}
}
}
|
mit
|
d0f1b86b9e5bd2a2ccd9019b26bc0cb5
| 36.954545 | 180 | 0.467864 | 5.517621 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
Client/Frontend/Browser/TopSitesManager.swift
|
1
|
3943
|
/* 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 Shared
import UIKit
import Storage
import SyncTelemetry
import WidgetKit
struct TopSitesHandler {
static func getTopSites(profile: Profile) -> Deferred<[Site]> {
let maxItems = UIDevice.current.userInterfaceIdiom == .pad ? 32 : 16
return profile.history.getTopSitesWithLimit(maxItems).both(profile.history.getPinnedTopSites()).bindQueue(.main) { (topsites, pinnedSites) in
let deferred = Deferred<[Site]>()
guard let mySites = topsites.successValue?.asArray(), let pinned = pinnedSites.successValue?.asArray() else {
return deferred
}
// How sites are merged together. We compare against the url's base domain. example m.youtube.com is compared against `youtube.com`
let unionOnURL = { (site: Site) -> String in
return URL(string: site.url)?.normalizedHost ?? ""
}
// Fetch the default sites
let defaultSites = defaultTopSites(profile)
// create PinnedSite objects. used by the view layer to tell topsites apart
let pinnedSites: [Site] = pinned.map({ PinnedSite(site: $0) })
// Merge default topsites with a user's topsites.
let mergedSites = mySites.union(defaultSites, f: unionOnURL)
// Merge pinnedSites with sites from the previous step
let allSites = pinnedSites.union(mergedSites, f: unionOnURL)
// Favour topsites from defaultSites as they have better favicons. But keep PinnedSites
let newSites = allSites.map { site -> Site in
if let _ = site as? PinnedSite {
return site
}
let domain = URL(string: site.url)?.shortDisplayString
return defaultSites.find { $0.title.lowercased() == domain } ?? site
}
deferred.fill(newSites)
return deferred
}
}
@available(iOS 14.0, *)
static func writeWidgetKitTopSites(profile: Profile) {
TopSitesHandler.getTopSites(profile: profile).uponQueue(.main) { result in
var widgetkitTopSites = [WidgetKitTopSiteModel]()
result.forEach { site in
// Favicon icon url
let iconUrl = site.icon?.url ?? ""
let imageKey = site.tileURL.baseDomain ?? ""
if let webUrl = URL(string: site.url) {
widgetkitTopSites.append(WidgetKitTopSiteModel(title: site.title, faviconUrl: iconUrl, url: webUrl, imageKey: imageKey))
// fetch favicons and cache them on disk
FaviconFetcher.downloadFaviconAndCache(imageURL: !iconUrl.isEmpty ? URL(string: iconUrl) : nil, imageKey: imageKey )
}
}
// save top sites for widgetkit use
WidgetKitTopSiteModel.save(widgetKitTopSites: widgetkitTopSites)
// Update widget timeline
WidgetCenter.shared.reloadAllTimelines()
}
}
static func defaultTopSites(_ profile: Profile) -> [Site] {
let suggested = SuggestedSites.asArray()
let deleted = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? []
return suggested.filter({deleted.firstIndex(of: $0.url) == .none})
}
static let DefaultSuggestedSitesKey = "topSites.deletedSuggestedSites"
}
open class PinnedSite: Site {
let isPinnedSite = true
init(site: Site) {
super.init(url: site.url, title: site.title, bookmarked: site.bookmarked)
self.icon = site.icon
self.metadata = site.metadata
}
}
|
mpl-2.0
|
b40a3952c1aeb5aaa6f7d1aef5759c1f
| 42.32967 | 149 | 0.608927 | 4.762077 | false | false | false | false |
practicalswift/swift
|
test/attr/attr_escaping.swift
|
2
|
9924
|
// RUN: %target-typecheck-verify-swift -swift-version 4
@escaping var fn : () -> Int = { 4 } // expected-error {{attribute can only be applied to types, not declarations}}
func paramDeclEscaping(@escaping fn: (Int) -> Void) {} // expected-error {{attribute can only be applied to types, not declarations}}
func wrongParamType(a: @escaping Int) {} // expected-error {{@escaping attribute only applies to function types}}
func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{@escaping conflicts with @noescape}}
// expected-error@-1{{@noescape is the default and has been removed}} {{29-39=}}
func takesEscaping(_ fn: @escaping () -> Int) {} // ok
func callEscapingWithNoEscape(_ fn: () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
// expected-note@-2{{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
takesEscaping(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
let _ = fn // expected-error{{non-escaping parameter 'fn' may only be called}}
}
typealias IntSugar = Int
func callSugared(_ fn: () -> IntSugar) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{24-24=@escaping }}
takesEscaping(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
struct StoresClosure {
var closure : () -> Int
init(_ fn: () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{14-14=@escaping }}
closure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
func arrayPack(_ fn: () -> Int) -> [() -> Int] {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{24-24=@escaping }}
return [fn] // expected-error{{using non-escaping parameter 'fn' in a context expecting an @escaping closure}}
}
func arrayPack(_ fn: @escaping () -> Int, _ fn2 : () -> Int) -> [() -> Int] {
// expected-note@-1{{parameter 'fn2' is implicitly non-escaping}} {{53-53=@escaping }}
return [fn, fn2] // expected-error{{using non-escaping parameter 'fn2' in a context expecting an @escaping closure}}
}
}
func takesEscapingBlock(_ fn: @escaping @convention(block) () -> Void) {
fn()
}
func callEscapingWithNoEscapeBlock(_ fn: () -> Void) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{42-42=@escaping }}
takesEscapingBlock(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func takesEscapingAutoclosure(_ fn: @autoclosure @escaping () -> Int) {}
func callEscapingAutoclosureWithNoEscape(_ fn: () -> Int) {
takesEscapingAutoclosure(1+1)
}
func callEscapingAutoclosureWithNoEscape_2(_ fn: () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}}
takesEscapingAutoclosure(fn()) // expected-error{{closure use of non-escaping parameter 'fn' may allow it to escape}}
}
func callEscapingAutoclosureWithNoEscape_3(_ fn: @autoclosure () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}}
takesEscapingAutoclosure(fn()) // expected-error{{closure use of non-escaping parameter 'fn' may allow it to escape}}
}
let foo: @escaping (Int) -> Int // expected-error{{@escaping attribute may only be used in function parameter position}} {{10-20=}}
struct GenericStruct<T> {}
func misuseEscaping(_ a: @escaping Int) {} // expected-error{{@escaping attribute only applies to function types}} {{26-38=}}
func misuseEscaping(_ a: (@escaping Int)?) {} // expected-error{{@escaping attribute only applies to function types}} {{27-39=}}
func misuseEscaping(opt a: @escaping ((Int) -> Int)?) {} // expected-error{{@escaping attribute only applies to function types}} {{28-38=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(_ a: (@escaping (Int) -> Int)?) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(nest a: (((@escaping (Int) -> Int))?)) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-42=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(iuo a: (@escaping (Int) -> Int)!) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{29-39=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(_ a: Optional<@escaping (Int) -> Int>, _ b: Int) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{35-45=}}
func misuseEscaping(_ a: (@escaping (Int) -> Int, Int)) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}}
func misuseEscaping(_ a: [@escaping (Int) -> Int]) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}}
func misuseEscaping(_ a: [@escaping (Int) -> Int]?) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}}
func misuseEscaping(_ a: [Int : @escaping (Int) -> Int]) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{33-43=}}
func misuseEscaping(_ a: GenericStruct<@escaping (Int) -> Int>) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{40-50=}}
func takesEscapingGeneric<T>(_ fn: @escaping () -> T) {}
func callEscapingGeneric<T>(_ fn: () -> T) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{35-35=@escaping }}
takesEscapingGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
class Super {}
class Sub: Super {}
func takesEscapingSuper(_ fn: @escaping () -> Super) {}
func callEscapingSuper(_ fn: () -> Sub) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{30-30=@escaping }}
takesEscapingSuper(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func takesEscapingSuperGeneric<T: Super>(_ fn: @escaping () -> T) {}
func callEscapingSuperGeneric(_ fn: () -> Sub) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
takesEscapingSuperGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func callEscapingSuperGeneric<T: Sub>(_ fn: () -> T) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{45-45=@escaping }}
takesEscapingSuperGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func testModuloOptionalness() {
var iuoClosure: (() -> Void)! = nil
func setIUOClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{28-28=@escaping }}
iuoClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
var iuoClosureExplicit: (() -> Void)!
func setExplicitIUOClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{36-36=@escaping }}
iuoClosureExplicit = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
var deepOptionalClosure: (() -> Void)???
func setDeepOptionalClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
deepOptionalClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
}
// Check that functions in vararg position are @escaping
func takesEscapingFunction(fn: @escaping () -> ()) {}
func takesArrayOfFunctions(array: [() -> ()]) {}
func takesVarargsOfFunctions(fns: () -> ()...) {
takesArrayOfFunctions(array: fns)
for fn in fns {
takesEscapingFunction(fn: fn)
}
}
func takesVarargsOfFunctionsExplicitEscaping(fns: @escaping () -> ()...) {} // expected-error{{@escaping attribute may only be used in function parameter position}}
func takesNoEscapeFunction(fn: () -> ()) { // expected-note {{parameter 'fn' is implicitly non-escaping}}
takesVarargsOfFunctions(fns: fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
class FooClass {
var stored : Optional<(()->Int)->Void> = nil
var computed : (()->Int)->Void {
get { return stored! }
set(newValue) { stored = newValue } // ok
}
var computedEscaping : (@escaping ()->Int)->Void {
get { return stored! }
set(newValue) { stored = newValue } // expected-error{{cannot assign value of type '(@escaping () -> Int) -> Void' to type 'Optional<(() -> Int) -> Void>'}}
}
}
// A call of a closure literal should be non-escaping
func takesInOut(y: inout Int) {
_ = {
y += 1 // no-error
}()
_ = ({
y += 1 // no-error
})()
_ = { () in
y += 1 // no-error
}()
_ = ({ () in
y += 1 // no-error
})()
_ = { () -> () in
y += 1 // no-error
}()
_ = ({ () -> () in
y += 1 // no-error
})()
}
class HasIVarCaptures {
var x: Int = 0
func method() {
_ = {
x += 1 // no-error
}()
_ = ({
x += 1 // no-error
})()
_ = { () in
x += 1 // no-error
}()
_ = ({ () in
x += 1 // no-error
})()
_ = { () -> () in
x += 1 // no-error
}()
_ = ({ () -> () in
x += 1 // no-error
})()
}
}
// https://bugs.swift.org/browse/SR-9760
protocol SR_9760 {
typealias F = () -> Void
typealias G<T> = (T) -> Void
func foo<T>(_: T, _: @escaping F) // Ok
func bar<T>(_: @escaping G<T>) // Ok
}
extension SR_9760 {
func fiz<T>(_: T, _: @escaping F) {} // Ok
func baz<T>(_: @escaping G<T>) {} // Ok
}
|
apache-2.0
|
0a18fc393e302929008358d9149981f0
| 41.775862 | 171 | 0.656187 | 3.763367 | false | false | false | false |
legendecas/Rocket.Chat.iOS
|
Rocket.Chat.Shared/Controllers/Chat/ChatControllerSocketConnectionHandler.swift
|
1
|
947
|
//
// ChatControllerSocketConnectionHandler.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 17/12/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
extension ChatViewController: SocketConnectionHandler {
public func socketDidConnect(socket: SocketManager) {
hideHeaderStatusView()
DispatchQueue.main.async { [weak self] in
if let subscription = self?.subscription {
self?.subscription = subscription
}
}
rightButton.isEnabled = true
}
public func socketDidDisconnect(socket: SocketManager) {
showHeaderStatusView()
chatHeaderViewStatus?.labelTitle.text = localized("connection.offline.banner.message")
chatHeaderViewStatus?.buttonRefresh.isHidden = false
chatHeaderViewStatus?.backgroundColor = .RCLightGray()
chatHeaderViewStatus?.setTextColor(.RCDarkBlue())
}
}
|
mit
|
3ae05398f1259c82745e067dafdc9223
| 26.823529 | 94 | 0.686047 | 4.927083 | false | false | false | false |
practicalswift/swift
|
test/DebugInfo/variables.swift
|
6
|
4722
|
// RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s
// Ensure that the debug info we're emitting passes the back end verifier.
// RUN: %target-swift-frontend %s -g -S -o - | %FileCheck %s --check-prefix ASM-%target-object-format
// ASM-macho: .section __DWARF,__debug_info
// ASM-elf: .section .debug_info,"",{{[@%]}}progbits
// ASM-coff: .section .debug_info,"dr"
// Test variables-interpreter.swift runs this code with `swift -g -i`.
// Test variables-repl.swift runs this code with `swift -g < variables.swift`.
// CHECK-DAG: ![[TLC:.*]] = !DIModule({{.*}}, name: "variables"
// Global variables.
var glob_i8: Int8 = 8
// CHECK-DAG: !DIGlobalVariable(name: "glob_i8",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I8:[^,]+]]
var glob_i16: Int16 = 16
// CHECK-DAG: !DIGlobalVariable(name: "glob_i16",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I16:[^,]+]]
var glob_i32: Int32 = 32
// CHECK-DAG: !DIGlobalVariable(name: "glob_i32",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I32:[^,]+]]
var glob_i64: Int64 = 64
// CHECK-DAG: !DIGlobalVariable(name: "glob_i64",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I64:[^,]+]]
var glob_f: Float = 2.89
// CHECK-DAG: !DIGlobalVariable(name: "glob_f",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[F:[^,]+]]
var glob_d: Double = 3.14
// CHECK-DAG: !DIGlobalVariable(name: "glob_d",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[D:[^,]+]]
var glob_b: Bool = true
// CHECK-DAG: !DIGlobalVariable(name: "glob_b",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[B:[^,]+]]
var glob_s: String = "😄"
// CHECK-DAG: !DIGlobalVariable(name: "glob_s",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[S:[^,]+]]
// FIXME: Dreadful type-checker performance prevents this from being this single
// print expression:
// print("\(glob_v), \(glob_i8), \(glob_i16), \(glob_i32), \(glob_i64), \(glob_f), \(glob_d), \(glob_b), \(glob_s)", terminator: "")
print(", \(glob_i8)", terminator: "")
print(", \(glob_i16)", terminator: "")
print(", \(glob_i32)", terminator: "")
print(", \(glob_i64)", terminator: "")
print(", \(glob_f)", terminator: "")
print(", \(glob_d)", terminator: "")
print(", \(glob_b)", terminator: "")
print(", \(glob_s)", terminator: "")
var unused: Int32 = -1
// CHECK-DAG: ![[RT:[0-9]+]] ={{.*}}"{{.*}}Swift.swiftmodule{{(/.+[.]swiftmodule)?}}"
// Stack variables.
func foo(_ dt: Float) -> Float {
// CHECK-DAG: call void @llvm.dbg.declare
// CHECK-DAG: !DILocalVariable(name: "f"
let f: Float = 9.78
// CHECK-DAG: !DILocalVariable(name: "r"
let r: Float = f*dt
return r
}
var g = foo(1.0);
// Tuple types.
var tuple: (Int, Bool) = (1, true)
// CHECK-DAG: !DIGlobalVariable(name: "tuple", linkageName: "$s{{9variables|4main}}5tupleSi_Sbtvp",{{.*}} type: ![[TUPTY:[^,)]+]]
// CHECK-DAG: ![[TUPTY]] = !DICompositeType({{.*}}identifier: "$sSi_SbtD"
func myprint(_ p: (i: Int, b: Bool)) {
print("\(p.i) -> \(p.b)")
}
myprint(tuple)
// Arrays are represented as an instantiation of Array.
// CHECK-DAG: ![[ARRAYTY:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Array",
// CHECK-DAG: !DIGlobalVariable(name: "array_of_tuples",{{.*}} type: ![[ARRAYTY]]
var array_of_tuples : [(a : Int, b : Int)] = [(1,2)]
var twod : [[Int]] = [[1]]
func bar(_ x: [(a : Int, b : Int)], y: [[Int]]) {
}
// CHECK-DAG: !DIGlobalVariable(name: "P",{{.*}} type: ![[PTY:[0-9]+]]
// CHECK-DAG: ![[PTUP:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSd1x_Sd1ySd1ztD",
// CHECK-DAG: ![[PTY]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s{{9variables|4main}}5PointaD",{{.*}} baseType: ![[PTUP]]
typealias Point = (x: Double, y: Double, z: Double)
var P:Point = (1, 2, 3)
func myprint(_ p: (x: Double, y: Double, z: Double)) {
print("(\(p.x), \(p.y), \(p.z))")
}
myprint(P)
// CHECK-DAG: !DIGlobalVariable(name: "P2",{{.*}} type: ![[APTY:[0-9]+]]
// CHECK-DAG: ![[APTY]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s{{9variables|4main}}13AliasForPointaD",{{.*}} baseType: ![[PTY:[0-9]+]]
typealias AliasForPoint = Point
var P2:AliasForPoint = (4, 5, 6)
myprint(P2)
// Unions.
enum TriValue {
case false_
case true_
case top
}
// CHECK-DAG: !DIGlobalVariable(name: "unknown",{{.*}} type: ![[TRIVAL:[0-9]+]]
// CHECK-DAG: ![[TRIVAL]] = !DICompositeType({{.*}}name: "TriValue",
var unknown = TriValue.top
func myprint(_ value: TriValue) {
switch value {
case TriValue.false_: print("false")
case TriValue.true_: print("true")
case TriValue.top: print("⊤")
}
}
myprint(unknown)
// CHECK-DAG: !DIFile(filename: "{{.*}}variables.swift"
|
apache-2.0
|
a55da14a035d11d5241664953fcb51cf
| 39.316239 | 142 | 0.574094 | 3.019846 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/CryptoAssets/Sources/ERC20Kit/Domain/ERC20CryptoAssetService.swift
|
1
|
4717
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainNamespace
import Combine
import EthereumKit
import MoneyKit
import PlatformKit
public enum ERC20CryptoAssetServiceError: LocalizedError, Equatable {
case failedToLoadDefaultAccount
case failedToLoadReceiveAddress
case failedToFetchTokens
public var errorDescription: String? {
switch self {
case .failedToLoadDefaultAccount:
return "Failed to load default account."
case .failedToLoadReceiveAddress:
return "Failed to load receive address."
case .failedToFetchTokens:
return "Failed to load ERC20 Assets."
}
}
}
/// Service to initialise required ERC20 CryptoAsset.
public protocol ERC20CryptoAssetServiceAPI {
func initialize() -> AnyPublisher<Void, ERC20CryptoAssetServiceError>
}
final class ERC20CryptoAssetService: ERC20CryptoAssetServiceAPI {
private let accountsRepository: ERC20BalancesRepositoryAPI
private let app: AppProtocol
private let coincore: CoincoreAPI
private let enabledCurrenciesService: EnabledCurrenciesServiceAPI
init(
accountsRepository: ERC20BalancesRepositoryAPI,
app: AppProtocol,
coincore: CoincoreAPI,
enabledCurrenciesService: EnabledCurrenciesServiceAPI
) {
self.accountsRepository = accountsRepository
self.app = app
self.coincore = coincore
self.enabledCurrenciesService = enabledCurrenciesService
}
func initialize() -> AnyPublisher<Void, ERC20CryptoAssetServiceError> {
initializeEthereum
.zip(initializePolygon)
.replaceOutput(with: ())
}
private var initializeEthereum: AnyPublisher<Void, ERC20CryptoAssetServiceError> {
Deferred { [coincore] in
Just(coincore[.ethereum])
}
.flatMap(\.defaultAccount)
.replaceError(with: ERC20CryptoAssetServiceError.failedToLoadDefaultAccount)
.flatMap { account in
self.initialize(account: account, network: .ethereum)
}
.eraseToAnyPublisher()
}
private var initializePolygon: AnyPublisher<Void, ERC20CryptoAssetServiceError> {
guard enabledCurrenciesService.allEnabledCryptoCurrencies.contains(.polygon) else {
return .just(())
}
return Deferred { [coincore] in
Just(coincore[.polygon])
}
.flatMap(\.defaultAccount)
.replaceError(with: ERC20CryptoAssetServiceError.failedToLoadDefaultAccount)
.flatMap { [app] account -> AnyPublisher<Void, ERC20CryptoAssetServiceError> in
app
.publisher(
for: blockchain.app.configuration.polygon.tokens.always.fetch.is.enabled,
as: Bool.self
)
.flatMap { result -> AnyPublisher<Bool, Error> in
result.value == true ? .just(true) : account.isFunded
}
.replaceError(with: ERC20CryptoAssetServiceError.failedToLoadDefaultAccount)
.flatMap { isFunded -> AnyPublisher<Void, ERC20CryptoAssetServiceError> in
guard isFunded else {
return .just(())
}
return self.initialize(account: account, network: .polygon)
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
private func initialize(
account: SingleAccount,
network: EVMNetwork
) -> AnyPublisher<Void, ERC20CryptoAssetServiceError> {
account.receiveAddress
.map { receiveAddress -> EthereumAddress? in
EthereumAddress(address: receiveAddress.address)
}
.replaceError(with: ERC20CryptoAssetServiceError.failedToLoadReceiveAddress)
.onNil(ERC20CryptoAssetServiceError.failedToLoadReceiveAddress)
.flatMap { [accountsRepository] ethereumAddress in
accountsRepository.tokens(for: ethereumAddress, network: network)
.replaceError(with: ERC20CryptoAssetServiceError.failedToFetchTokens)
}
.handleEvents(
receiveOutput: { [coincore] response -> Void in
// For each ERC20 token present in the response.
response.keys.forEach { currency in
// Gets its CryptoAsset from CoinCore to allow it to be preloaded.
_ = coincore[currency]
}
}
)
.mapToVoid()
.eraseToAnyPublisher()
}
}
|
lgpl-3.0
|
a134dba388e50f2fe8bab900d3b6c380
| 36.728 | 93 | 0.632103 | 5.414466 | false | false | false | false |
PekanMmd/Pokemon-XD-Code
|
enums/CMTMs.swift
|
1
|
4725
|
//
// CMTMs.swift
// Colosseum Tool
//
// Created by The Steez on 06/06/2018.
//
import Foundation
var kFirstTMListOffset: Int {
switch region {
case .US: return 0x365018
case .JP: return 0x351758
case .EU: return 0x3B20D0
case .OtherGame: return 0
}
}
let kSizeOfTMEntry = 0x08
let kFirstTMItemIndex = 0x121
let kNumberOfTMsAndHMs = 0x3A
let kNumberOfTMs = 0x32
let kNumberOfTutorMoves = 0
enum XGTMs {
case tm(Int)
case tutor(Int)
var index : Int {
switch self {
case .tm(let i): return i
default:
assertionFailure("This is only for XD compatibility")
return -1
}
}
var startOffset : Int {
return kFirstTMListOffset + 6 + ((index - 1) * kSizeOfTMEntry)
}
var item : XGItems {
let i = kFirstTMItemIndex + (index - 1)
return .index(i)
}
var move : XGMoves {
return .index( XGFiles.dol.data!.get2BytesAtOffset(startOffset) )
}
var location : String {
return TMLocations[self.index - 1]
}
func replaceWithMove(_ move: XGMoves) {
if move == XGMoves.index(0) { return }
if let dol = XGFiles.dol.data {
dol.replace2BytesAtOffset(startOffset, withBytes: move.index)
dol.save()
updateItemDescription()
}
}
static func createItemDescriptionForMove(_ move: XGMoves) -> String {
let desc = move.mdescription.string
let maxLineLength = 20
let newLine = "[New Line]"
let words = desc.replacingOccurrences(of: newLine, with: " ").components(separatedBy: " ")
var splitDesc = ""
var lineLength = 0
for w in 0 ..< words.count {
let word = words[w]
let len = word.count
if lineLength + len > maxLineLength {
let end = splitDesc.endIndex
splitDesc = splitDesc.replacingCharacters(in: splitDesc.index(before: end)..<end , with: newLine)
lineLength = 0
}
splitDesc += word
if w != words.count - 1 {
splitDesc += " "
}
lineLength += len + 1
}
return splitDesc
}
func updateItemDescription() {
item.descriptionString.duplicateWithString(XGTMs.createItemDescriptionForMove(self.move)).replace()
}
static func allTMs() -> [XGTMs] {
var tms = [XGTMs]()
for i in 1 ... kNumberOfTMs {
tms.append(.tm(i))
}
return tms
}
}
func allTMsArray() -> [XGTMs] {
var tms: [XGTMs] = []
for i in 1 ... kNumberOfTMs {
tms.append(XGTMs.tm(i))
}
return tms
}
let TMLocations = [
"Pyrite Colosseum",
"Deep Colosseum",
"-",
"-",
"Pyrite Colosseum",
"Pyrite Colosseum",
"Pyrite Colosseum",
"-",
"-",
"Under PokeMart",
"Phenac Stadium",
"Deep Colosseum",
"Mt.Battle Prize",
"Under PokeMart",
"Under PokeMart",
"Under PokeMart",
"Under PokeMart",
"Phenac Stadium",
"Phenac Stadium",
"Under PokeMart",
"-",
"Phenac Stadium",
"Under Colosseum",
"Mt.Battle Prize",
"Under PokeMart",
"Shadow Lab",
"Phenac City",
"-",
"Mt.Battle Prize",
"Under Colosseum",
"Pyrite Colosseum",
"Mt.Battle Prize",
"Under PokeMart",
"-",
"Mt.Battle Prize",
"Under Colosseum",
"Under Colosseum",
"Under PokeMart",
"-",
"-",
"Phenac City",
"-",
"-",
"Deep Colosseum",
"The Under",
"Pyrite Town",
"Mt. Battle",
"Deep Colosseum",
"Pyrite Cave",
"-",
]
extension XGTMs: Codable {
enum CodingKeys: String, CodingKey {
case index, move
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let index = try container.decode(Int.self, forKey: .index)
self = .tm(index)
}
static func update(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let index = try container.decode(Int.self, forKey: .index)
let move = try container.decode(XGMoves.self, forKey: .move)
let tm = XGTMs.tm(index)
tm.replaceWithMove(move)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(index, forKey: .index)
try container.encode(move, forKey: .move)
}
}
extension XGTMs: XGEnumerable {
var enumerableName: String {
return "TM" + String(format: "%02d", index)
}
var enumerableValue: String? {
return move.name.string
}
static var className: String {
return "TMs"
}
static var allValues: [XGTMs] {
return allTMs()
}
}
extension XGTMs: XGDocumentable {
var documentableName: String {
return enumerableName
}
static var DocumentableKeys: [String] {
return ["index", "hex index", "name", "description"]
}
func documentableValue(for key: String) -> String {
switch key {
case "index":
return index.string
case "hex index":
return index.hexString()
case "name":
return move.name.string
case "description":
return item.descriptionString.string
default:
return ""
}
}
}
|
gpl-2.0
|
9341e2bb801dca791069afc2e6a858f3
| 17.824701 | 101 | 0.657778 | 2.858439 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.