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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
miguelgutierrez/Curso-iOS-Swift-Programming-Netmind
|
newsApp 1.7/newsApp/DetalleArticuloViewController.swift
|
1
|
1298
|
//
// DetalleArticuloViewController.swift
// newsApp
//
// Created by Miguel Gutiérrez Moreno on 23/1/15.
// Copyright (c) 2015 MGM. All rights reserved.
//
import UIKit
class DetalleArticuloViewController: UIViewController {
// MARK: properties
@IBOutlet weak var articuloTextView: UITextView!
var articulo : Articulo?
weak var delegate : ArticulosTableViewController?
// MARK: life cicle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let articulo = self.articulo {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = FormatoFecha.formatoGeneral
let fechaStr = dateFormatter.stringFromDate(articulo.fecha )
articuloTextView.text = "Nombre: \(articulo.nombre)\n Fecha: \(fechaStr)\n Texto: \(articulo.texto)"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: eventos
@IBAction func ok(sender: UIButton) {
delegate?.cerrar(self)
//self.dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
bf2a7f85fa2533fc5dc9bab10a084f05
| 24.94 | 112 | 0.651503 | 4.716364 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard
|
Pods/GCBCore/GCBCore/GrandCentralBoardController.swift
|
4
|
2920
|
//
// Created by Oktawian Chojnacki on 24.02.2016.
// Copyright © 2016 Oktawian Chojnacki. All rights reserved.
//
import UIKit
/// The errors that `GrandCentralBoardController` can throw.
public enum GrandCentralBoardError: ErrorType, HavingMessage {
case WrongWidgetsCount
public var message: String {
switch self {
case .WrongWidgetsCount:
return NSLocalizedString("Expected six configured widgets!", comment: "")
}
}
}
/// The class is configurable with `Configuration`.
public protocol Configurable: class {
/**
Configure class with `Configuration`.
- parameter configuration: Widgets Settings and Widget Builders.
- throws: GrandCentralBoardError if widget count is different than **6** but can throw other `ErrorTypes`.
*/
func configure(configuration: Configuration) throws
}
/// This is a controller class that stacks views on `ViewStacking` view and schedules updates for Widgets using object conforming to `SchedulingJobs`.
public class GrandCentralBoardController {
private let stack: ViewStacking
private let scheduler: SchedulingJobs
private let expectedWidgetsCount = 6
private var configuration: Configuration?
private var widgets: [WidgetControlling] = []
/**
Initialize the `GrandCentralBoardController`.
- parameter scheduler: scheduling updates for widgets.
- parameter stack: a view having the ability to stack views.
*/
public init(scheduler: SchedulingJobs, stack: ViewStacking) {
self.scheduler = scheduler
self.stack = stack
}
}
extension GrandCentralBoardController: Configurable {
public func configure(configuration: Configuration) throws {
if let previousConfiguration = self.configuration where previousConfiguration == configuration {
return
}
scheduler.invalidateAll()
stack.removeAllStackedViews()
self.configuration = configuration
widgets = try configuration.settings.flatMap({ widgetConfiguration in
if let builder = configuration.builders.filter({ $0.name == widgetConfiguration.name }).first {
return try builder.build(widgetConfiguration.settings)
}
return nil
})
guard widgets.count == expectedWidgetsCount else {
throw GrandCentralBoardError.WrongWidgetsCount
}
widgets.forEach { widget in
stack.stackView(widget.view)
widget.sources.forEach { source in
scheduler.schedule(Job(target: widget, source: source))
}
}
}
}
@available(*, deprecated, message="`GrandCentralBoard` class name is deprecated, use the replacement class `GrandCentralBoardController` as in v1.5 this class will cease to exist.")
public final class GrandCentralBoard : GrandCentralBoardController {
}
|
gpl-3.0
|
37a81a342d5bd09f154e4f9d37442606
| 30.053191 | 181 | 0.688592 | 5.2125 | false | true | false | false |
0Mooshroom/Learning-Swift
|
11_方法/11_方法/main.swift
|
1
|
2820
|
//
// main.swift
// 11_方法
//
// Created by Mooshroom on 2017/8/25.
// Copyright © 2017年 Mooshroom. All rights reserved.
//
import Foundation
//: 方法是关联了特定类型的函数。类,结构体,枚举都可以定义实例方法
class Counter {
var count = 0;
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
counter.increment()
counter.increment(by: 2)
print(counter.count)
counter.reset()
print(counter.count)
//: self属性 普通的函数调用中是不需要写的系统可以判断,但是在你的函数的形式参数和你的类的属性相同的时候self就派上用场了。
struct Point {
var x = 0.0, y = 0.0
func isToTheRightOf(x: Double) -> Bool {
return self.x > x
}
}
//: 在实例方法中修改值类型
// 通常我们都知道结构体和枚举都是值类型,类是引用类型,所以在结构体和枚举的实例方法中修改属性需要用到mutating
struct Mooshroom {
var name = "moo", age = 25
// func replaceName(name: String, age: Int) {
// self.name = name // 报错 Cannot assign to property: 'self' is immutable
// }
// 这样就不会报错啦
mutating func replaceName(name: String, age: Int) {
self.name = name // 这样就不会报错啦
self.age = age
}
}
//: 异变方法里指定自身
struct Mooshroom1 {
var name = "moo", age = 25
mutating func replaceName(name: String, age: Int) {
self = Mooshroom1(name: name, age: age)
}
}
enum TriStateSwitch {
case off, low, high
mutating func next() {
switch self {
case .off:
self = .low
case .low:
self = .high
case .high:
self = .off
}
}
}
var ovenLight = TriStateSwitch.low
ovenLight.next()
ovenLight.next()
ovenLight.next()
//: 类方法 结构体方法
// 如果你想访问类的属性 或者结构体的属性 就需要使用 static 或者 class 前缀来限制它:
// static var highestUnlockedLevel = 1
struct LevelTracker {
static var highestUnlockedLevel = 1
var currentLevel = 1
static func unlock(_ level: Int) {
if level > highestUnlockedLevel { highestUnlockedLevel = level }
}
static func isUnlock(_ level: Int) -> Bool {
return level <= highestUnlockedLevel
}
@discardableResult // 忽略返回值
mutating func advance(to level: Int) -> Bool {
if LevelTracker.isUnlock(level) {
currentLevel = level
return true
} else {
return false
}
}
}
var levelTracker = LevelTracker(currentLevel: 1)
levelTracker.advance(to: 2)
|
mit
|
761a48c7336c27771987696c42483ba4
| 19.161017 | 82 | 0.601934 | 3.413199 | false | false | false | false |
rajprins/rekentv
|
RekenTV/shuffle.swift
|
1
|
698
|
import Foundation
extension CollectionType where Index == Int {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
extension MutableCollectionType where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in 0..<count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
|
mit
|
d43943c7935e6e048e76aa23a86bc9f1
| 28.083333 | 66 | 0.577364 | 4.282209 | false | false | false | false |
practicalswift/swift
|
stdlib/public/core/ShadowProtocols.swift
|
7
|
6069
|
//===--- ShadowProtocols.swift - Protocols for decoupled ObjC bridging ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// To implement bridging, the core standard library needs to interact
// a little bit with Cocoa. Because we want to keep the core
// decoupled from the Foundation module, we can't use foundation
// classes such as NSArray directly. We _can_, however, use an @objc
// protocols whose API is "layout-compatible" with that of NSArray,
// and use unsafe casts to treat NSArray instances as instances of
// that protocol.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
@objc
internal protocol _ShadowProtocol {}
/// A shadow for the `NSFastEnumeration` protocol.
@objc
internal protocol _NSFastEnumeration: _ShadowProtocol {
@objc(countByEnumeratingWithState:objects:count:)
func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int
}
/// A shadow for the `NSEnumerator` class.
@objc
internal protocol _NSEnumerator: _ShadowProtocol {
init()
func nextObject() -> AnyObject?
}
/// A token that can be used for `NSZone*`.
internal typealias _SwiftNSZone = OpaquePointer
/// A shadow for the `NSCopying` protocol.
@objc
internal protocol _NSCopying: _ShadowProtocol {
@objc(copyWithZone:)
func copy(with zone: _SwiftNSZone?) -> AnyObject
}
/// A shadow for the "core operations" of NSArray.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSArray` subclass.
@unsafe_no_objc_tagged_pointer @objc
internal protocol _NSArrayCore: _NSCopying, _NSFastEnumeration {
@objc(objectAtIndex:)
func objectAt(_ index: Int) -> AnyObject
func getObjects(_: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange)
@objc(countByEnumeratingWithState:objects:count:)
override func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int
var count: Int { get }
}
/// A shadow for the "core operations" of NSDictionary.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSDictionary` subclass.
@objc
internal protocol _NSDictionaryCore: _NSCopying, _NSFastEnumeration {
// The following methods should be overridden when implementing an
// NSDictionary subclass.
// The designated initializer of `NSDictionary`.
init(
objects: UnsafePointer<AnyObject?>,
forKeys: UnsafeRawPointer, count: Int)
var count: Int { get }
@objc(objectForKey:)
func object(forKey aKey: AnyObject) -> AnyObject?
func keyEnumerator() -> _NSEnumerator
// We also override the following methods for efficiency.
@objc(copyWithZone:)
override func copy(with zone: _SwiftNSZone?) -> AnyObject
@objc(getObjects:andKeys:count:)
func getObjects(
_ objects: UnsafeMutablePointer<AnyObject>?,
andKeys keys: UnsafeMutablePointer<AnyObject>?,
count: Int
)
@objc(countByEnumeratingWithState:objects:count:)
override func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int
}
/// A shadow for the API of `NSDictionary` we will use in the core
/// stdlib.
///
/// `NSDictionary` operations, in addition to those on
/// `_NSDictionaryCore`, that we need to use from the core stdlib.
/// Distinct from `_NSDictionaryCore` because we don't want to be
/// forced to implement operations that `NSDictionary` already
/// supplies.
@unsafe_no_objc_tagged_pointer @objc
internal protocol _NSDictionary: _NSDictionaryCore {
// Note! This API's type is different from what is imported by the clang
// importer.
override func getObjects(
_ objects: UnsafeMutablePointer<AnyObject>?,
andKeys keys: UnsafeMutablePointer<AnyObject>?,
count: Int)
}
/// A shadow for the "core operations" of NSSet.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSSet` subclass.
@objc
internal protocol _NSSetCore: _NSCopying, _NSFastEnumeration {
// The following methods should be overridden when implementing an
// NSSet subclass.
// The designated initializer of `NSSet`.
init(objects: UnsafePointer<AnyObject?>, count: Int)
var count: Int { get }
func member(_ object: AnyObject) -> AnyObject?
func objectEnumerator() -> _NSEnumerator
// We also override the following methods for efficiency.
@objc(copyWithZone:)
override func copy(with zone: _SwiftNSZone?) -> AnyObject
@objc(countByEnumeratingWithState:objects:count:)
override func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int
}
/// A shadow for the API of NSSet we will use in the core
/// stdlib.
///
/// `NSSet` operations, in addition to those on
/// `_NSSetCore`, that we need to use from the core stdlib.
/// Distinct from `_NSSetCore` because we don't want to be
/// forced to implement operations that `NSSet` already
/// supplies.
@unsafe_no_objc_tagged_pointer @objc
internal protocol _NSSet: _NSSetCore {
}
/// A shadow for the API of NSNumber we will use in the core
/// stdlib.
@objc
internal protocol _NSNumber {
var doubleValue: Double { get }
var floatValue: Float { get }
var unsignedLongLongValue: UInt64 { get }
var longLongValue: Int64 { get }
var objCType: UnsafePointer<Int8> { get }
}
#else
internal protocol _NSSetCore {}
internal protocol _NSDictionaryCore {}
#endif
|
apache-2.0
|
078d78de56a2328c041428ad8fde939f
| 30.609375 | 80 | 0.712473 | 4.515625 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Blockchain/App/App+Namespace.State.swift
|
1
|
2541
|
import BlockchainNamespace
import Combine
import Foundation
import ToolKit
import UIKit
final class ApplicationStateObserver: Session.Observer {
unowned let app: AppProtocol
let notificationCenter: NotificationCenter
init(app: AppProtocol, notificationCenter: NotificationCenter = .default) {
self.app = app
self.notificationCenter = notificationCenter
}
var didEnterBackgroundNotification, willEnterForegroundNotification: AnyCancellable?
func start() {
app.state.transaction { state in
state.set(blockchain.app.deep_link.dsl.is.enabled, to: BuildFlag.isInternal)
state.set(blockchain.app.environment, to: BuildFlag.isInternal ? blockchain.app.environment.debug[] : blockchain.app.environment.production[])
state.set(blockchain.app.launched.at.time, to: Date())
state.set(blockchain.app.is.first.install, to: (try? state.get(blockchain.app.number.of.launches)).or(0) == 0)
state.set(blockchain.app.number.of.launches, to: (try? state.get(blockchain.app.number.of.launches)).or(0) + 1)
state.set(blockchain.ui.device.id, to: UIDevice.current.identifierForVendor?.uuidString)
state.set(blockchain.ui.device.os.name, to: UIDevice.current.systemName)
state.set(blockchain.ui.device.os.version, to: UIDevice.current.systemVersion)
state.set(blockchain.ui.device.locale.language.code, to: { try Locale.current.languageCode.or(throw: "No languageCode") })
state.set(blockchain.ui.device.current.local.time, to: { Date() })
if let versionIsGreater = try? (Bundle.main.plist.version.string > state.get(blockchain.app.version)) {
state.set(blockchain.app.did.update, to: versionIsGreater)
}
state.set(blockchain.app.version, to: Bundle.main.plist.version.string)
}
didEnterBackgroundNotification = notificationCenter.publisher(for: UIApplication.didEnterBackgroundNotification)
.sink { [app] _ in app.state.set(blockchain.app.is.in.background, to: true) }
willEnterForegroundNotification = notificationCenter.publisher(for: UIApplication.willEnterForegroundNotification)
.sink { [app] _ in app.state.set(blockchain.app.is.in.background, to: false) }
}
func stop() {
let tasks = [
didEnterBackgroundNotification,
willEnterForegroundNotification
]
for task in tasks {
task?.cancel()
}
}
}
|
lgpl-3.0
|
f82e1c9fcb231a15bae2127730eb56f7
| 41.35 | 154 | 0.68477 | 4.32879 | false | false | false | false |
jopamer/swift
|
stdlib/public/core/Policy.swift
|
1
|
17717
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Swift Standard Prolog Library.
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Standardized uninhabited type
//===----------------------------------------------------------------------===//
/// The return type of functions that do not return normally, that is, a type
/// with no values.
///
/// Use `Never` as the return type when declaring a closure, function, or
/// method that unconditionally throws an error, traps, or otherwise does
/// not terminate.
///
/// func crashAndBurn() -> Never {
/// fatalError("Something very, very bad happened")
/// }
@_frozen
public enum Never {}
extension Never: Error {}
extension Never: Equatable {}
extension Never: Comparable {
public static func < (lhs: Never, rhs: Never) -> Bool {
switch (lhs, rhs) {
}
}
}
extension Never: Hashable {}
//===----------------------------------------------------------------------===//
// Standardized aliases
//===----------------------------------------------------------------------===//
/// The return type of functions that don't explicitly specify a return type,
/// that is, an empty tuple `()`.
///
/// When declaring a function or method, you don't need to specify a return
/// type if no value will be returned. However, the type of a function,
/// method, or closure always includes a return type, which is `Void` if
/// otherwise unspecified.
///
/// Use `Void` or an empty tuple as the return type when declaring a closure,
/// function, or method that doesn't return a value.
///
/// // No return type declared:
/// func logMessage(_ s: String) {
/// print("Message: \(s)")
/// }
///
/// let logger: (String) -> Void = logMessage
/// logger("This is a void function")
/// // Prints "Message: This is a void function"
public typealias Void = ()
//===----------------------------------------------------------------------===//
// Aliases for floating point types
//===----------------------------------------------------------------------===//
// FIXME: it should be the other way round, Float = Float32, Double = Float64,
// but the type checker loses sugar currently, and ends up displaying 'FloatXX'
// in diagnostics.
/// A 32-bit floating point type.
public typealias Float32 = Float
/// A 64-bit floating point type.
public typealias Float64 = Double
//===----------------------------------------------------------------------===//
// Default types for unconstrained literals
//===----------------------------------------------------------------------===//
/// The default type for an otherwise-unconstrained integer literal.
public typealias IntegerLiteralType = Int
/// The default type for an otherwise-unconstrained floating point literal.
public typealias FloatLiteralType = Double
/// The default type for an otherwise-unconstrained Boolean literal.
///
/// When you create a constant or variable using one of the Boolean literals
/// `true` or `false`, the resulting type is determined by the
/// `BooleanLiteralType` alias. For example:
///
/// let isBool = true
/// print("isBool is a '\(type(of: isBool))'")
/// // Prints "isBool is a 'Bool'"
///
/// The type aliased by `BooleanLiteralType` must conform to the
/// `ExpressibleByBooleanLiteral` protocol.
public typealias BooleanLiteralType = Bool
/// The default type for an otherwise-unconstrained unicode scalar literal.
public typealias UnicodeScalarType = String
/// The default type for an otherwise-unconstrained Unicode extended
/// grapheme cluster literal.
public typealias ExtendedGraphemeClusterType = String
/// The default type for an otherwise-unconstrained string literal.
public typealias StringLiteralType = String
//===----------------------------------------------------------------------===//
// Default types for unconstrained number literals
//===----------------------------------------------------------------------===//
// Integer literals are limited to 2048 bits.
// The intent is to have arbitrary-precision literals, but implementing that
// requires more work.
//
// Rationale: 1024 bits are enough to represent the absolute value of min/max
// IEEE Binary64, and we need 1 bit to represent the sign. Instead of using
// 1025, we use the next round number -- 2048.
public typealias _MaxBuiltinIntegerType = Builtin.Int2048
#if !os(Windows) && (arch(i386) || arch(x86_64))
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80
#else
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64
#endif
//===----------------------------------------------------------------------===//
// Standard protocols
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
/// The protocol to which all classes implicitly conform.
///
/// You use `AnyObject` when you need the flexibility of an untyped object or
/// when you use bridged Objective-C methods and properties that return an
/// untyped result. `AnyObject` can be used as the concrete type for an
/// instance of any class, class type, or class-only protocol. For example:
///
/// class FloatRef {
/// let value: Float
/// init(_ value: Float) {
/// self.value = value
/// }
/// }
///
/// let x = FloatRef(2.3)
/// let y: AnyObject = x
/// let z: AnyObject = FloatRef.self
///
/// `AnyObject` can also be used as the concrete type for an instance of a type
/// that bridges to an Objective-C class. Many value types in Swift bridge to
/// Objective-C counterparts, like `String` and `Int`.
///
/// let s: AnyObject = "This is a bridged string." as NSString
/// print(s is NSString)
/// // Prints "true"
///
/// let v: AnyObject = 100 as NSNumber
/// print(type(of: v))
/// // Prints "__NSCFNumber"
///
/// The flexible behavior of the `AnyObject` protocol is similar to
/// Objective-C's `id` type. For this reason, imported Objective-C types
/// frequently use `AnyObject` as the type for properties, method parameters,
/// and return values.
///
/// Casting AnyObject Instances to a Known Type
/// ===========================================
///
/// Objects with a concrete type of `AnyObject` maintain a specific dynamic
/// type and can be cast to that type using one of the type-cast operators
/// (`as`, `as?`, or `as!`).
///
/// This example uses the conditional downcast operator (`as?`) to
/// conditionally cast the `s` constant declared above to an instance of
/// Swift's `String` type.
///
/// if let message = s as? String {
/// print("Successful cast to String: \(message)")
/// }
/// // Prints "Successful cast to String: This is a bridged string."
///
/// If you have prior knowledge that an `AnyObject` instance has a particular
/// type, you can use the unconditional downcast operator (`as!`). Performing
/// an invalid cast triggers a runtime error.
///
/// let message = s as! String
/// print("Successful cast to String: \(message)")
/// // Prints "Successful cast to String: This is a bridged string."
///
/// let badCase = v as! String
/// // Runtime error
///
/// Casting is always safe in the context of a `switch` statement.
///
/// let mixedArray: [AnyObject] = [s, v]
/// for object in mixedArray {
/// switch object {
/// case let x as String:
/// print("'\(x)' is a String")
/// default:
/// print("'\(object)' is not a String")
/// }
/// }
/// // Prints "'This is a bridged string.' is a String"
/// // Prints "'100' is not a String"
///
/// Accessing Objective-C Methods and Properties
/// ============================================
///
/// When you use `AnyObject` as a concrete type, you have at your disposal
/// every `@objc` method and property---that is, methods and properties
/// imported from Objective-C or marked with the `@objc` attribute. Because
/// Swift can't guarantee at compile time that these methods and properties
/// are actually available on an `AnyObject` instance's underlying type, these
/// `@objc` symbols are available as implicitly unwrapped optional methods and
/// properties, respectively.
///
/// This example defines an `IntegerRef` type with an `@objc` method named
/// `getIntegerValue()`.
///
/// class IntegerRef {
/// let value: Int
/// init(_ value: Int) {
/// self.value = value
/// }
///
/// @objc func getIntegerValue() -> Int {
/// return value
/// }
/// }
///
/// func getObject() -> AnyObject {
/// return IntegerRef(100)
/// }
///
/// let obj: AnyObject = getObject()
///
/// In the example, `obj` has a static type of `AnyObject` and a dynamic type
/// of `IntegerRef`. You can use optional chaining to call the `@objc` method
/// `getIntegerValue()` on `obj` safely. If you're sure of the dynamic type of
/// `obj`, you can call `getIntegerValue()` directly.
///
/// let possibleValue = obj.getIntegerValue?()
/// print(possibleValue)
/// // Prints "Optional(100)"
///
/// let certainValue = obj.getIntegerValue()
/// print(certainValue)
/// // Prints "100"
///
/// If the dynamic type of `obj` doesn't implement a `getIntegerValue()`
/// method, the system returns a runtime error when you initialize
/// `certainValue`.
///
/// Alternatively, if you need to test whether `obj.getIntegerValue()` exists,
/// use optional binding before calling the method.
///
/// if let f = obj.getIntegerValue {
/// print("The value of 'obj' is \(f())")
/// } else {
/// print("'obj' does not have a 'getIntegerValue()' method")
/// }
/// // Prints "The value of 'obj' is 100"
public typealias AnyObject = Builtin.AnyObject
#else
/// The protocol to which all classes implicitly conform.
public typealias AnyObject = Builtin.AnyObject
#endif
/// The protocol to which all class types implicitly conform.
///
/// You can use the `AnyClass` protocol as the concrete type for an instance of
/// any class. When you do, all known `@objc` class methods and properties are
/// available as implicitly unwrapped optional methods and properties,
/// respectively. For example:
///
/// class IntegerRef {
/// @objc class func getDefaultValue() -> Int {
/// return 42
/// }
/// }
///
/// func getDefaultValue(_ c: AnyClass) -> Int? {
/// return c.getDefaultValue?()
/// }
///
/// The `getDefaultValue(_:)` function uses optional chaining to safely call
/// the implicitly unwrapped class method on `c`. Calling the function with
/// different class types shows how the `getDefaultValue()` class method is
/// only conditionally available.
///
/// print(getDefaultValue(IntegerRef.self))
/// // Prints "Optional(42)"
///
/// print(getDefaultValue(NSString.self))
/// // Prints "nil"
public typealias AnyClass = AnyObject.Type
//===----------------------------------------------------------------------===//
// Standard pattern matching forms
//===----------------------------------------------------------------------===//
/// Returns a Boolean value indicating whether two arguments match by value
/// equality.
///
/// The pattern-matching operator (`~=`) is used internally in `case`
/// statements for pattern matching. When you match against an `Equatable`
/// value in a `case` statement, this operator is called behind the scenes.
///
/// let weekday = 3
/// let lunch: String
/// switch weekday {
/// case 3:
/// lunch = "Taco Tuesday!"
/// default:
/// lunch = "Pizza again."
/// }
/// // lunch == "Taco Tuesday!"
///
/// In this example, the `case 3` expression uses this pattern-matching
/// operator to test whether `weekday` is equal to the value `3`.
///
/// - Note: In most cases, you should use the equal-to operator (`==`) to test
/// whether two instances are equal. The pattern-matching operator is
/// primarily intended to enable `case` statement pattern matching.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
@_transparent
public func ~= <T : Equatable>(a: T, b: T) -> Bool {
return a == b
}
//===----------------------------------------------------------------------===//
// Standard precedence groups
//===----------------------------------------------------------------------===//
precedencegroup AssignmentPrecedence {
assignment: true
associativity: right
}
precedencegroup FunctionArrowPrecedence {
associativity: right
higherThan: AssignmentPrecedence
}
precedencegroup TernaryPrecedence {
associativity: right
higherThan: FunctionArrowPrecedence
}
precedencegroup DefaultPrecedence {
higherThan: TernaryPrecedence
}
precedencegroup LogicalDisjunctionPrecedence {
associativity: left
higherThan: TernaryPrecedence
}
precedencegroup LogicalConjunctionPrecedence {
associativity: left
higherThan: LogicalDisjunctionPrecedence
}
precedencegroup ComparisonPrecedence {
higherThan: LogicalConjunctionPrecedence
}
precedencegroup NilCoalescingPrecedence {
associativity: right
higherThan: ComparisonPrecedence
}
precedencegroup CastingPrecedence {
higherThan: NilCoalescingPrecedence
}
precedencegroup RangeFormationPrecedence {
higherThan: CastingPrecedence
}
precedencegroup AdditionPrecedence {
associativity: left
higherThan: RangeFormationPrecedence
}
precedencegroup MultiplicationPrecedence {
associativity: left
higherThan: AdditionPrecedence
}
precedencegroup BitwiseShiftPrecedence {
higherThan: MultiplicationPrecedence
}
//===----------------------------------------------------------------------===//
// Standard operators
//===----------------------------------------------------------------------===//
// Standard postfix operators.
postfix operator ...
// Optional<T> unwrapping operator is built into the compiler as a part of
// postfix expression grammar.
//
// postfix operator !
// Standard prefix operators.
prefix operator !
prefix operator ~
prefix operator +
prefix operator -
prefix operator ...
prefix operator ..<
// Standard infix operators.
// "Exponentiative"
infix operator << : BitwiseShiftPrecedence
infix operator &<< : BitwiseShiftPrecedence
infix operator >> : BitwiseShiftPrecedence
infix operator &>> : BitwiseShiftPrecedence
// "Multiplicative"
infix operator * : MultiplicationPrecedence
infix operator &* : MultiplicationPrecedence
infix operator / : MultiplicationPrecedence
infix operator % : MultiplicationPrecedence
infix operator & : MultiplicationPrecedence
// "Additive"
infix operator + : AdditionPrecedence
infix operator &+ : AdditionPrecedence
infix operator - : AdditionPrecedence
infix operator &- : AdditionPrecedence
infix operator | : AdditionPrecedence
infix operator ^ : AdditionPrecedence
// FIXME: is this the right precedence level for "..." ?
infix operator ... : RangeFormationPrecedence
infix operator ..< : RangeFormationPrecedence
// The cast operators 'as' and 'is' are hardcoded as if they had the
// following attributes:
// infix operator as : CastingPrecedence
// "Coalescing"
infix operator ?? : NilCoalescingPrecedence
// "Comparative"
infix operator < : ComparisonPrecedence
infix operator <= : ComparisonPrecedence
infix operator > : ComparisonPrecedence
infix operator >= : ComparisonPrecedence
infix operator == : ComparisonPrecedence
infix operator != : ComparisonPrecedence
infix operator === : ComparisonPrecedence
infix operator !== : ComparisonPrecedence
// FIXME: ~= will be built into the compiler.
infix operator ~= : ComparisonPrecedence
// "Conjunctive"
infix operator && : LogicalConjunctionPrecedence
// "Disjunctive"
infix operator || : LogicalDisjunctionPrecedence
// User-defined ternary operators are not supported. The ? : operator is
// hardcoded as if it had the following attributes:
// operator ternary ? : : TernaryPrecedence
// User-defined assignment operators are not supported. The = operator is
// hardcoded as if it had the following attributes:
// infix operator = : AssignmentPrecedence
// Compound
infix operator *= : AssignmentPrecedence
infix operator &*= : AssignmentPrecedence
infix operator /= : AssignmentPrecedence
infix operator %= : AssignmentPrecedence
infix operator += : AssignmentPrecedence
infix operator &+= : AssignmentPrecedence
infix operator -= : AssignmentPrecedence
infix operator &-= : AssignmentPrecedence
infix operator <<= : AssignmentPrecedence
infix operator &<<= : AssignmentPrecedence
infix operator >>= : AssignmentPrecedence
infix operator &>>= : AssignmentPrecedence
infix operator &= : AssignmentPrecedence
infix operator ^= : AssignmentPrecedence
infix operator |= : AssignmentPrecedence
// Workaround for <rdar://problem/14011860> SubTLF: Default
// implementations in protocols. Library authors should ensure
// that this operator never needs to be seen by end-users. See
// test/Prototypes/GenericDispatch.swift for a fully documented
// example of how this operator is used, and how its use can be hidden
// from users.
infix operator ~>
|
apache-2.0
|
94a362b439bcf303fdd74af4fd55e73b
| 34.50501 | 80 | 0.626291 | 4.950265 | false | false | false | false |
faimin/ZDOpenSourceDemo
|
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/PolygonNode.swift
|
1
|
4814
|
//
// PolygonNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/21/19.
//
import Foundation
import QuartzCore
final class PolygonNodeProperties: NodePropertyMap, KeypathSearchable {
var keypathName: String
var childKeypaths: [KeypathSearchable] = []
init(star: Star) {
self.keypathName = star.name
self.direction = star.direction
self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: star.position.keyframes))
self.outerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRadius.keyframes))
self.outerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRoundness.keyframes))
self.rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: star.rotation.keyframes))
self.points = NodeProperty(provider: KeyframeInterpolator(keyframes: star.points.keyframes))
self.keypathProperties = [
"Position" : position,
"Outer Radius" : outerRadius,
"Outer Roundedness" : outerRoundedness,
"Rotation" : rotation,
"Points" : points
]
self.properties = Array(keypathProperties.values)
}
let keypathProperties: [String : AnyNodeProperty]
let properties: [AnyNodeProperty]
let direction: PathDirection
let position: NodeProperty<Vector3D>
let outerRadius: NodeProperty<Vector1D>
let outerRoundedness: NodeProperty<Vector1D>
let rotation: NodeProperty<Vector1D>
let points: NodeProperty<Vector1D>
}
final class PolygonNode: AnimatorNode, PathNode {
let properties: PolygonNodeProperties
let pathOutput: PathOutputNode
init(parentNode: AnimatorNode?, star: Star) {
self.pathOutput = PathOutputNode(parent: parentNode?.outputNode)
self.properties = PolygonNodeProperties(star: star)
self.parentNode = parentNode
}
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
return properties
}
let parentNode: AnimatorNode?
var hasLocalUpdates: Bool = false
var hasUpstreamUpdates: Bool = false
var lastUpdateFrame: CGFloat? = nil
var isEnabled: Bool = true {
didSet{
self.pathOutput.isEnabled = self.isEnabled
}
}
/// Magic number needed for constructing path.
static let PolygonConstant: CGFloat = 0.25
func rebuildOutputs(frame: CGFloat) {
let outerRadius = properties.outerRadius.value.cgFloatValue
let outerRoundedness = properties.outerRoundedness.value.cgFloatValue * 0.01
let numberOfPoints = properties.points.value.cgFloatValue
let rotation = properties.rotation.value.cgFloatValue
let position = properties.position.value.pointValue
var currentAngle = (rotation - 90).toRadians()
let anglePerPoint = ((2 * CGFloat.pi) / numberOfPoints)
var point = CGPoint(x: (outerRadius * cos(currentAngle)),
y: (outerRadius * sin(currentAngle)))
var vertices = [CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero)]
var previousPoint = point
currentAngle += anglePerPoint;
for _ in 0..<Int(ceil(numberOfPoints)) {
previousPoint = point
point = CGPoint(x: (outerRadius * cos(currentAngle)),
y: (outerRadius * sin(currentAngle)))
if outerRoundedness != 0 {
let cp1Theta = (atan2(previousPoint.y, previousPoint.x) - CGFloat.pi / 2)
let cp1Dx = cos(cp1Theta);
let cp1Dy = sin(cp1Theta);
let cp2Theta = (atan2(point.y, point.x) - CGFloat.pi / 2)
let cp2Dx = cos(cp2Theta)
let cp2Dy = sin(cp2Theta)
let cp1 = CGPoint(x: outerRadius * outerRoundedness * PolygonNode.PolygonConstant * cp1Dx,
y: outerRadius * outerRoundedness * PolygonNode.PolygonConstant * cp1Dy)
let cp2 = CGPoint(x: outerRadius * outerRoundedness * PolygonNode.PolygonConstant * cp2Dx,
y: outerRadius * outerRoundedness * PolygonNode.PolygonConstant * cp2Dy)
let previousVertex = vertices[vertices.endIndex-1]
vertices[vertices.endIndex-1] = CurveVertex(previousVertex.inTangent, previousVertex.point, previousVertex.point - cp1 + position)
vertices.append(CurveVertex(point: point + position, inTangentRelative: cp2, outTangentRelative: .zero))
} else {
vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero))
}
currentAngle += anglePerPoint;
}
let reverse = properties.direction == .counterClockwise
if reverse {
vertices = vertices.reversed()
}
var path = BezierPath()
for vertex in vertices {
path.addVertex(reverse ? vertex.reversed() : vertex)
}
path.close()
pathOutput.setPath(path, updateFrame: frame)
}
}
|
mit
|
2099e12746e1a2dacd4453f7727a6908
| 35.469697 | 138 | 0.697341 | 4.340848 | false | false | false | false |
vapor-tools/vapor-jsonapi
|
Sources/VaporJsonApi/Request/URI+JsonApiQueryParser.swift
|
1
|
3754
|
//
// URI+JsonApiQueryParser.swift
// VaporJsonApi
//
// Created by Koray Koska on 01/05/2017.
//
//
import HTTP
import Vapor
import URI
/*
extension URI {
// TODO: Vapor 2.0 will include query dictionary parsing so this should be removed ASAP once it is released.
// See the discussion on Github: https://github.com/vapor/vapor/issues/955
func jsonApiQuery() -> JSON {
guard let query = query, var json = try? JSON(node: [:]) else {
return JSON(Node(nilLiteral: ()))
}
let keyValueArray = query.components(separatedBy: "&")
let keyValues = keyValueArray
.map({ s in
return s.characters.split(separator: "=", maxSplits: 1).map(String.init)
})
.filter({ $0.count == 2 })
.map({ (key: $0[0], value: $0[1]) })
for keyValue in keyValues {
if keyValue.key.hasSuffix("[]") {
// This value is part of an array
let keyKey = keyValue.key.jsonApiKeySubKey()
let topLevelKey = keyKey.topLevelKey
// The dictionaryKey is empty because we have elements like "array[]" where there are no
// characters between the square brackets...
// let dictionaryKey = keyKey.dictionaryKey
if let a = try? json[topLevelKey]?.makeJSON().array, var arr = a {
arr.append(keyValue.value)
let jsonArr = arr.map({ JSON(Node($0.string ?? "")) })
json[topLevelKey] = JSON(jsonArr)
} else {
json[topLevelKey] = JSON([JSON(Node(keyValue.value))])
}
} else if keyValue.key.hasSuffix("]")
&& keyValue.key.contains("[")
&& !(Array(keyValue.key.characters).filter({ $0 == "[" }).count == 1 && keyValue.key.hasPrefix("[")) {
// This value is part of a dictionary
// Possible values: page[number], pa[g]e[number]. pag[e[number]
// Impossible values: [pagenumber], page[numbe]r, page]number], page]number[
let keyKey = keyValue.key.jsonApiKeySubKey()
let topLevelKey = keyKey.topLevelKey
let dictionaryKey = keyKey.dictionaryKey
if let o = try? json[topLevelKey]?.makeJSON(), var old = o {
old[dictionaryKey] = JSON(Node(keyValue.value))
json[topLevelKey] = old
} else {
json[topLevelKey] = try? JSON(node: [
dictionaryKey: keyValue.value
])
}
} else {
// This value is a simple key=value property where value will be treated as a string
json[keyValue.key] = JSON(Node(keyValue.value))
}
}
return json
}
}
fileprivate extension String {
func jsonApiKeySubKey() -> (topLevelKey: String, dictionaryKey: String) {
// Generate top level key and dictionary key
let keyArray = Array(self.characters)
var lastOpenBracket = 0
for i in 0 ..< keyArray.count {
if keyArray[i] == "[" {
lastOpenBracket = i
}
}
let topLevelKey = String(keyArray[0..<lastOpenBracket])
// We don't need the open bracket
let startDictionaryKeyIndex = lastOpenBracket + 1
// We don't need the last character (closed bracket)
let endDictionaryKeyIndex = keyArray.count - 1
let dictionaryKey = String(keyArray[startDictionaryKeyIndex..<endDictionaryKeyIndex])
return (topLevelKey: topLevelKey, dictionaryKey: dictionaryKey)
}
}
*/
|
mit
|
63073f781e090b907f7610ee197bbe62
| 35.096154 | 118 | 0.547949 | 4.539299 | false | false | false | false |
nanoxd/Rex
|
Source/Foundation/NSUserDefaults.swift
|
1
|
1289
|
//
// NSUserDefaults.swift
// Rex
//
// Created by Neil Pankey on 5/28/15.
// Copyright (c) 2015 Neil Pankey. All rights reserved.
//
import Foundation
import ReactiveCocoa
extension NSUserDefaults {
/// Sends value of `key` whenever it changes. Attempts to filter out repeats
/// by casting to NSObject and checking for equality. If the values aren't
/// convertible this will generate events whenever _any_ value in NSUserDefaults
/// changes.
func rex_valueForKey(key: String) -> SignalProducer<AnyObject?, NoError> {
let center = NSNotificationCenter.defaultCenter()
let changes = center.rac_notifications(name: NSUserDefaultsDidChangeNotification)
|> map { notification in
// The notification doesn't provide what changed so we have to look
// it up every time
return self.objectForKey(key)
}
return SignalProducer<AnyObject?, NoError>(value: objectForKey(key))
|> concat(changes)
|> skipRepeats { previous, next in
if let previous = previous as? NSObject,
let next = next as? NSObject {
return previous == next
}
return false
}
}
}
|
mit
|
2db3b8617a8cd3c228c06faab4a6a004
| 34.805556 | 89 | 0.610551 | 5.197581 | false | false | false | false |
dannofx/AudioPal
|
AudioPal/AudioPal/UUID+Utils.swift
|
1
|
932
|
//
// UUID+Utils.swift
// AudioPal
//
// Created by Danno on 6/1/17.
// Copyright © 2017 Daniel Heredia. All rights reserved.
//
import UIKit
extension UUID {
var data: Data {
get {
var uuid_bytes = self.uuid
let uuid_data = withUnsafePointer(to: &uuid_bytes) { (unsafe_uuid) -> Data in
Data(bytes: unsafe_uuid, count: MemoryLayout<uuid_t>.size)
}
return uuid_data
}
}
init?(data: Data) {
if data.count < MemoryLayout<uuid_t>.size {
return nil
}
var uuid_bytes: uuid_t = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
let uuid_p1: UnsafePointer<Data> = data.withUnsafeBytes { $0 }
let uuid_p2: UnsafeMutablePointer<uuid_t> = withUnsafeMutablePointer(to: &uuid_bytes) { $0 }
memcpy(uuid_p2, uuid_p1, MemoryLayout<uuid_t>.size)
self.init(uuid: uuid_bytes)
}
}
|
mit
|
cc48ff4885accd0e426626dadf6269a3
| 26.382353 | 100 | 0.557465 | 3.301418 | false | false | false | false |
freshOS/Stevia
|
Sources/Stevia/Stevia+Hierarchy.swift
|
1
|
7530
|
//
// Stevia+Hierarchy.swift
// LoginStevia
//
// Created by Sacha Durand Saint Omer on 01/10/15.
// Copyright © 2015 Sacha Durand Saint Omer. All rights reserved.
//
#if canImport(UIKit)
import UIKit
@resultBuilder public struct SubviewsBuilder {
public static func buildBlock(_ content: UIView...) -> [UIView] {
return content
}
}
public extension UIView {
@available(*, deprecated, renamed: "subviews")
@discardableResult
func sv(_ subViews: UIView...) -> UIView {
subviews(subViews)
}
/**
Defines the view hierachy for the view.
Esentially, this is just a shortcut to `addSubview`
and 'translatesAutoresizingMaskIntoConstraints = false'
```
class MyView: UIView {
let email = UITextField()
let password = UITextField()
let login = UIButton()
convenience init() {
self.init(frame: CGRect.zero)
subviews(
email,
password,
login
)
...
}
}
```
- Returns: Itself to enable nested layouts.
*/
@discardableResult
func subviews(_ subViews: UIView...) -> UIView {
subviews(subViews)
}
/**
Defines the view hierachy for the view.
Esentially, this is just a shortcut to `addSubview`
and 'translatesAutoresizingMaskIntoConstraints = false'
```
class MyView: UIView {
let email = UITextField()
let password = UITextField()
let login = UIButton()
convenience init() {
self.init(frame: CGRect.zero)
subviews {
email
password
login
}
...
}
}
```
- Returns: Itself to enable nested layouts.
*/
@discardableResult
func subviews(@SubviewsBuilder content: () -> [UIView]) -> UIView {
subviews(content())
}
/**
Defines the view hierachy for the view.
Esentially, this is just a shortcut to `addSubview`
and 'translatesAutoresizingMaskIntoConstraints = false'
```
class MyView: UIView {
let email = UITextField()
let password = UITextField()
let login = UIButton()
convenience init() {
self.init(frame: CGRect.zero)
subviews {
email
password
login
}
...
}
}
```
- Returns: Itself to enable nested layouts.
*/
@discardableResult
func subviews(@SubviewsBuilder content: () -> UIView) -> UIView {
let subview = content()
subviews(subview)
return self
}
/**
Defines the view hierachy for the view.
Esentially, this is just a shortcut to `addSubview`
and 'translatesAutoresizingMaskIntoConstraints = false'
```
class MyView: UIView {
let email = UITextField()
let password = UITextField()
let login = UIButton()
convenience init() {
self.init(frame: CGRect.zero)
sv(
email,
password,
login
)
...
}
}
```
- Returns: Itself to enable nested layouts.
*/
@objc
@available(*, deprecated, renamed: "subviews")
@discardableResult
func sv(_ subViews: [UIView]) -> UIView {
subviews(subViews)
}
@discardableResult
@objc
func subviews(_ subViews: [UIView]) -> UIView {
for sv in subViews {
addSubview(sv)
sv.translatesAutoresizingMaskIntoConstraints = false
}
return self
}
}
public extension UITableViewCell {
/**
Defines the view hierachy for the view.
Esentially, this is just a shortcut to `contentView.addSubview`
and 'translatesAutoresizingMaskIntoConstraints = false'
```
class NotificationCell: UITableViewCell {
var avatar = UIImageView()
var name = UILabel()
var followButton = UIButton()
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier) {
sv(
avatar,
name,
followButton
)
...
}
}
```
- Returns: Itself to enable nested layouts.
*/
@available(*, deprecated, renamed: "subviews")
@discardableResult
override func sv(_ subViews: [UIView]) -> UIView {
contentView.subviews(subViews)
}
/**
Defines the view hierachy for the view.
Esentially, this is just a shortcut to `contentView.addSubview`
and 'translatesAutoresizingMaskIntoConstraints = false'
```
class NotificationCell: UITableViewCell {
var avatar = UIImageView()
var name = UILabel()
var followButton = UIButton()
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier) {
subviews(
avatar,
name,
followButton
)
...
}
}
```
- Returns: Itself to enable nested layouts.
*/
@discardableResult
override func subviews(_ subViews: [UIView]) -> UIView {
contentView.subviews(subViews)
}
}
public extension UICollectionViewCell {
/**
Defines the view hierachy for the view.
Esentially, this is just a shortcut to `contentView.addSubview`
and 'translatesAutoresizingMaskIntoConstraints = false'
```
class PhotoCollectionViewCell: UICollectionViewCell {
var avatar = UIImageView()
var name = UILabel()
var followButton = UIButton()
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override init(frame: CGRect) {
super.init(frame: frame)
subviews(
avatar,
name,
followButton
)
...
}
}
```
- Returns: Itself to enable nested layouts.
*/
@available(*, deprecated, renamed: "subviews")
@discardableResult
override func sv(_ subViews: [UIView]) -> UIView {
contentView.subviews(subViews)
}
@discardableResult
override func subviews(_ subViews: [UIView]) -> UIView {
contentView.subviews(subViews)
}
}
public extension UIStackView {
@discardableResult
func arrangedSubviews(@SubviewsBuilder content: () -> [UIView]) -> UIView {
arrangedSubviews(content())
}
@discardableResult
func arrangedSubviews(@SubviewsBuilder content: () -> UIView) -> UIView {
arrangedSubviews([content()])
}
@discardableResult
private func arrangedSubviews(_ subViews: UIView...) -> UIView {
arrangedSubviews(subViews)
}
@discardableResult
func arrangedSubviews(_ subViews: [UIView]) -> UIView {
subViews.forEach { addArrangedSubview($0) }
return self
}
}
#endif
|
mit
|
d265c9246614e26c6260b34099fa96d5
| 21.677711 | 100 | 0.556116 | 5.328379 | false | false | false | false |
ph1ps/Food101-CoreML
|
Food101Prediction/UIImage+PixelBuffer.swift
|
1
|
1964
|
//
// UIImage+PixelBuffer.swift
// Food101Prediction
//
// Created by Philipp Gabriel on 15.02.18.
// Copyright © 2018 Philipp Gabriel. All rights reserved.
//
import UIKit
extension UIImage {
func resize(to newSize: CGSize) -> UIImage? {
guard self.size != newSize else { return self }
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
defer { UIGraphicsEndImageContext() }
return UIGraphicsGetImageFromCurrentImageContext()
}
func pixelBuffer() -> CVPixelBuffer? {
let width = Int(self.size.width)
let height = Int(self.size.height)
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary
var pixelBuffer: CVPixelBuffer?
let status = CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32ARGB, attrs, &pixelBuffer)
guard status == kCVReturnSuccess else {
return nil
}
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(data: pixelData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) else {
return nil
}
context.translateBy(x: 0, y: CGFloat(height))
context.scaleBy(x: 1.0, y: -1.0)
UIGraphicsPushContext(context)
self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
UIGraphicsPopContext()
CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
return pixelBuffer
}
}
|
mit
|
c90ffcfa67910895bb3f93c51e4004dc
| 35.351852 | 243 | 0.696383 | 4.96962 | false | false | false | false |
nikHowlett/WatchHealthMedicalDoctor
|
mobile/SurveyNotificationSystemViewController.swift
|
1
|
21109
|
//
// SurveyNotificationSystemViewController.swift
// mobile
//
// Created by MAC-ATL019922 on 6/26/15.
// Copyright (c) 2015 UCB+nikhowlett. All rights reserved.
//
import UIKit
import Foundation
import CoreData
class SurveyNotificationSystemViewController: UIViewController {
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var howOftenPicker: UIDatePicker!
@IBOutlet weak var csslol: UIButton!
//@IBOutlet weak var cssolo: UIButton!
@IBOutlet weak var cssolo: UIButton!
//@IBOutlet weak var csslol: UIButton!
@IBOutlet weak var watchimagelol: UIImageView!
@IBOutlet weak var ntso: UILabel!
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var pointless1: UILabel!
@IBOutlet weak var pointfull1: UILabel!
@IBOutlet weak var pointesl22: UILabel!
@IBOutlet weak var send1: UIButton!
@IBOutlet weak var pointless6: UILabel!
@IBOutlet weak var pointless47: UILabel!
// var data2sendlabel: String = ""
var surveyList: NSMutableArray = []
var data2sendlabel: String = ""
lazy var managedObjectContext : NSManagedObjectContext? = {
let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
if let managedContext : NSManagedObjectContext? = appDelegate.managedObjectContext {
return managedContext
} else {
return nil
}
}()
var surveys : [Survey] = [Survey]()
var surveyLines = [NSManagedObject]()
func handleWatchKitNotification(notification: NSNotification) {
if let userInfo = notification.object as? [String : String] {
print("watchnot received/text updated")
//if (userInfo["message"]!) {
// println("successfully caught sleepnotification")
//} else {
data2sendlabel = userInfo["message"]!
//}
//pointfull1.text = userInfo["message"]
/*println("1")
let tstamp = pointfull1.text!.substringToIndex(advance(pointfull1.text!.startIndex, 19))
let surveydata = pointfull1.text!.substringFromIndex(advance(pointfull1.text!.startIndex,26))
let newsurveydataitem: surveydatables = surveydatables(dataname: tstamp, result: surveydata)
println("2")
var stu = surveyList.count
func handleWatchKitNotification(notification: NSNotification) {
if let userInfo = notification.object as? [String : String] {
println("watchnot received/text updated")
data2sendlabel = userInfo["message"]!
}
var surveytimestampdata = data2sendlabel.substringToIndex(advance(data2sendlabel.startIndex, 19))
var surveydatainfo = data2sendlabel.substringFromIndex(advance(data2sendlabel.startIndex,26))
self.saveSurvey(surveytimestampdata, results: surveydatainfo)
println("savingsurvey")
}
var jan = surveyd.count
println("3")
surveyd.insert((newsurveydataitem), atIndex: jan)
surveyList.addObject(newsurveydataitem)
println("4")
saveSurveyList()
println("5")*/
//self.saveSurvey(pointfull1.text!)
}
/*scheduleLocalNotification()
var nextNotification = UILocalNotification()
//nextNotification.fireDate = fixNotificationDate(howOftenPicker.date)
var seconds = howOftenPicker.countDownDuration
print(seconds)
nextNotification.fireDate = NSDate(timeIntervalSinceNow: seconds)
nextNotification.category = "someCategory"
nextNotification.alertTitle = "CheckUp Survey!"
nextNotification.soundName = "beep-01a.wav"
nextNotification.alertBody = "Doctor Jenkins says 'Take a UCB watch-app survey!'"
nextNotification.alertAction = "JustWokeUp"
UIApplication.sharedApplication().scheduleLocalNotification(nextNotification)
*/
let localNotification = UILocalNotification()
localNotification.soundName = "beep-01a.wav"
localNotification.alertTitle = "Take your next survey!"
localNotification.alertBody = "Doctor Jenkins says 'Take a UCB watch-app survey!'"
localNotification.alertAction = "Take Survey"
localNotification.category = "someCategory"
let seconds = howOftenPicker.countDownDuration
print(seconds, appendNewline: false)
localNotification.fireDate = NSDate(timeIntervalSinceNow: seconds)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
let math: Int = data2sendlabel.characters.count
if (math > 18) {
let surveytimestampdata = data2sendlabel.substringToIndex(advance(data2sendlabel.startIndex, 19))
let surveydatainfo = data2sendlabel.substringFromIndex(advance(data2sendlabel.startIndex,26))
self.saveSurvey(surveytimestampdata, results: surveydatainfo)
print("savingsurvey")
}
}
/*func saveSurvey(name: String) {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
//2
let entity = NSEntityDescription.entityForName("SurveyData",
inManagedObjectContext:
managedContext)
let simp = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext:managedContext)
//3
let tstamp = name.substringToIndex(advance(name.startIndex, 19))
let surveydata = name.substringFromIndex(advance(name.startIndex,26))
simp.setValue(tstamp, forKey: "timeStamp")
simp.setValue(surveydata, forKey: "results")
//4
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
//
surveyLines.append(simp)
}
*/
private func saveSurvey(timeStamp: String, results: String) {
if managedObjectContext != nil {
let entity = NSEntityDescription.entityForName("Survey", inManagedObjectContext: managedObjectContext!)
let survey = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext!) as! mobile.Survey
survey.timeStamp = timeStamp
survey.results = results
var error: NSError? = nil
do {
try managedObjectContext!.save()
surveys.append(survey)
} catch var error1 as NSError {
error = error1
print("Could not save \(error), \(error?.userInfo)")
}
} else {
print("Could not get managed object context")
}
}
@IBAction func ohmyshare(sender: AnyObject) {
if (pointfull1.text == "Label") {
let nextNotification = UILocalNotification()
//nextNotification.fireDate = fixNotificationDate(howOftenPicker.date)
//var seconds = howOftenPicker.countDownDuration
//print(seconds)
nextNotification.fireDate = NSDate(timeIntervalSinceNow: 1)
nextNotification.soundName = "beep-01a.wav"
nextNotification.alertBody = "No survey data collected!"
UIApplication.sharedApplication().scheduleLocalNotification(nextNotification)
} else {
let textToShare = "Hey Doctor Scott, my UCB 'Next-Gen-Med' app is sending you my latest survey data."
let tstamp = pointfull1.text!.substringToIndex(advance(pointfull1.text!.startIndex, 19))
let surveydata = pointfull1.text!.substringFromIndex(advance(pointfull1.text!.startIndex,26))
if let myWebsite = pointfull1.text {
let objectsToShare = [tstamp, textToShare, surveydata]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList]
self.presentViewController(activityVC, animated: true, completion: nil)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
//self.view.backgroundColor = UIColor.blueColor()
datePicker.hidden = true
howOftenPicker.hidden = true
//datePicker.setValue(UIColor.whiteColor(), forKeyPath: "textColor")
//howOftenPicker.setValue(UIColor.whiteColor(), forKeyPath: "textColor")
cssolo.hidden = true
label1.hidden = true
label2.hidden = true
howOftenPicker.countDownDuration = 120.0;
setupNotificationSettings()
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes:[UIUserNotificationType.Sound, UIUserNotificationType.Alert], categories: nil))
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleWatchKitNotification:"), name: "WatchKitReq", object: nil)
// Do any additional setup after loading the view, typically from a nib.
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleTakeSurveyNotification"), name: "takeSurveyNotification", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleRemindMeNotification"), name: "remindMeNotification", object: nil)
pointfull1.text = "Label"
print("thishas")
}
func handleTakeSurveyNotification() {
//txtAddItem.becomeFirstResponder()
//add immediate notiication to trigger on watch
}
func handleRemindMeNotification() {
let nextNotification = UILocalNotification()
//nextNotification.fireDate = fixNotificationDate(howOftenPicker.date)
let seconds = howOftenPicker.countDownDuration
//print(seconds)
nextNotification.fireDate = NSDate(timeIntervalSinceNow: 60 * seconds)
nextNotification.soundName = "beep-01a.wav"
nextNotification.alertBody = "Doctor Jenkins says 'Take a UCB watch-app survey!'"
UIApplication.sharedApplication().scheduleLocalNotification(nextNotification)
}
@IBAction func configuresurveysettings(sender: AnyObject) {
if datePicker.hidden {
animateMyViews(ntso, viewToShow: datePicker)
animateMyViews(pointless6, viewToShow: howOftenPicker)
animateMyViews(pointless1, viewToShow: label1)
animateMyViews(pointfull1, viewToShow: label2)
animateMyViews(csslol, viewToShow: cssolo)
animateMyViews(pointless47, viewToShow: pointesl22)
//csslol.text = "Back"
//UIApplication.sharedApplication().cancelAllLocalNotifications()
}
else{
animateMyViews(datePicker, viewToShow: ntso)
animateMyViews(howOftenPicker, viewToShow: pointless6)
animateMyViews(label1, viewToShow: pointless1)
animateMyViews(label2, viewToShow: pointfull1)
animateMyViews(cssolo, viewToShow: csslol)
animateMyViews(pointesl22, viewToShow: pointless47)
//scheduleLocalNotification()
}
//txtAddItem.enabled = !txtAddItem.enabled
}
@IBAction func savesurveysettings(sender: AnyObject) {
animateMyViews(datePicker, viewToShow: ntso)
animateMyViews(howOftenPicker, viewToShow: pointless6)
animateMyViews(label1, viewToShow: pointless1)
animateMyViews(label2, viewToShow: pointfull1)
animateMyViews(cssolo, viewToShow: csslol)
animateMyViews(pointless47, viewToShow: pointesl22)
scheduleLocalNotification()
//showNotificationFire()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func animateMyViews(viewToHide: UIView, viewToShow: UIView) {
let animationDuration = 0.35
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
viewToHide.transform = CGAffineTransformScale(viewToHide.transform, 0.001, 0.001)
}) { (completion) -> Void in
viewToHide.hidden = true
viewToShow.hidden = false
viewToShow.transform = CGAffineTransformScale(viewToShow.transform, 0.001, 0.001)
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
viewToShow.transform = CGAffineTransformIdentity
})
}
}
func scheduleLocalNotification() {
//finish repeat fires
//ohmygod I figured it out holy crap it just came to me
//and it was so stressfull at first when I couldn't come up with it
//and it seems obvious, but its always hard to come up
//with a solution yourself
//so exciting
//that was worth 5000 dollars
/* let localNotification = UILocalNotification()
localNotification.soundName = "beep-01a.wav"
localNotification.alertTitle = "Take your next survey!"
localNotification.alertBody = "Doctor Jenkins says 'Take a UCB watch-app survey!'"
localNotification.alertAction = "Take Survey"
localNotification.category = "someCategory"
let seconds = howOftenPicker.countDownDuration
print(seconds, appendNewline: false)
localNotification.fireDate = NSDate(timeIntervalSinceNow: seconds)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
*/
let localNotification = UILocalNotification()
localNotification.soundName = "beep-01a.wav"
localNotification.alertTitle = "Take your first survey of the day!"
localNotification.alertBody = "Just respond on your Apple Watch to get started."
localNotification.alertAction = "Take Survey"
localNotification.category = "someCategory"
print(datePicker.date)
//localNotification.fireDate = fixNotificationDate(datePicker.date)
localNotification.fireDate = datePicker.date
localNotification.repeatInterval = .Day
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
/*var nextNotification = UILocalNotification()
//nextNotification.fireDate = fixNotificationDate(howOftenPicker.date)
var seconds = howOftenPicker.countDownDuration
print(seconds)
nextNotification.fireDate = NSDate(timeIntervalSinceNow: seconds)
nextNotification.soundName = "beep-01a.wav"
nextNotification.alertBody = "Doctor Jenkins says 'Take a UCB watch-app survey!'"
*/
//UIApplication.sharedApplication().scheduleLocalNotification(nextNotification)
}
func setupNotificationSettings() {
let notificationSettings: UIUserNotificationSettings! = UIApplication.sharedApplication().currentUserNotificationSettings()
if (notificationSettings.types == UIUserNotificationType.None){
// Specify the notification types.
var notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Sound]
// Specify the notification actions.
var remindMe = UIMutableUserNotificationAction()
remindMe.identifier = "remindMe"
remindMe.title = "Remind me in 5!"
remindMe.activationMode = UIUserNotificationActivationMode.Background
remindMe.destructive = false
remindMe.authenticationRequired = true
var takeSurvey = UIMutableUserNotificationAction()
takeSurvey.identifier = "takeSurvey"
takeSurvey.title = "Take Survey"
takeSurvey.activationMode = UIUserNotificationActivationMode.Foreground
takeSurvey.destructive = false
takeSurvey.authenticationRequired = true
var trashAction = UIMutableUserNotificationAction()
trashAction.identifier = "trashAction"
trashAction.title = "Ignore"
trashAction.activationMode = UIUserNotificationActivationMode.Background
trashAction.destructive = true
trashAction.authenticationRequired = false
let actionsArray = NSArray(objects: takeSurvey, remindMe, trashAction)
let actionsArrayMinimal = NSArray(objects: remindMe, takeSurvey)
// Specify the category related to the above actions.
var surveyReminderCategory = UIMutableUserNotificationCategory()
surveyReminderCategory.identifier = "surveyReminderCategory"
/*surveyReminderCategory.setActions(actionsArray as [AnyObject], forContext: UIUserNotificationActionContext.Default)
surveyReminderCategory.setActions(actionsArrayMinimal as [AnyObject], forContext: UIUserNotificationActionContext.Minimal)*/
surveyReminderCategory.setActions(actionsArray as! [UIUserNotificationAction], forContext: UIUserNotificationActionContext.Default)
surveyReminderCategory.setActions(actionsArrayMinimal as! [UIUserNotificationAction], forContext: UIUserNotificationActionContext.Minimal)
let categoriesForSettings = NSSet(objects: surveyReminderCategory)
// Register the notification settings.
//let newNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: categoriesForSettings as Set<NSObject> as Set<NSObject>)
let newNotificationSettings = UIUserNotificationSettings(
forTypes: [.Alert, .Badge, .Sound],
categories: NSSet(objects: categoriesForSettings) as! Set<UIUserNotificationCategory>)
//let settings = UIUserNotificationSettings(forTypes: notificationTypes, categories: NSSet(object: categoriesForSettings
//) as Set<NSObject>)
UIApplication.sharedApplication().registerUserNotificationSettings(newNotificationSettings)
}
}
func fixNotificationDate(dateToFix: NSDate) -> NSDate {
let dateComponets: NSDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.NSDayCalendarUnit, NSCalendarUnit.NSMonthCalendarUnit, NSCalendarUnit.NSYearCalendarUnit, NSCalendarUnit.NSHourCalendarUnit, NSCalendarUnit.NSMinuteCalendarUnit], fromDate: dateToFix)
dateComponets.second = 0
let fixedDate: NSDate! = NSCalendar.currentCalendar().dateFromComponents(dateComponets)
print(fixedDate)
return fixedDate
}
func saveSurveyList() {
let pathsArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory = pathsArray[0] as String
let savePath = documentsDirectory.stringByAppendingPathComponent("survey_list")
surveyList.writeToFile(savePath, atomically: true)
}
}
|
mit
|
59bc4adc3878814835fe811206e967bb
| 49.021327 | 289 | 0.61803 | 5.775376 | false | false | false | false |
xiangwangfeng/M80AttributedLabel
|
SwiftDemo/Classes/TextAlignmentViewController.swift
|
1
|
1163
|
//
// TextAlignmentViewController.swift
// SwiftDemo
//
// Created by amao on 2016/10/13.
// Copyright © 2016年 amao. All rights reserved.
//
import UIKit
class TextAlignmentViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Text Alignment"
let text = "Hello M80AttributedLabel"
let alignments : [CTTextAlignment] = [.left,.right,.center,.justified,.natural]
for alignment in alignments {
let label = M80AttributedLabel()
label.text = text
label.textAlignment = alignment
label.frame = CGRect.init(x: 20, y: 20 + Int(alignment.rawValue) * 60 , width: Int(self.view.bounds.width - 40), height: 25)
label.layer.borderWidth = 1
label.layer.borderColor = UIColor.orange.cgColor
self.view.addSubview(label)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
aec0a4b183d0dd6cf2231c2ca0feeb93
| 24.777778 | 136 | 0.580172 | 4.813278 | false | false | false | false |
kylef/RxHyperdrive
|
Pods/RxSwift/RxSwift/Observables/Observable+Time.swift
|
1
|
9191
|
//
// Observable+Time.swift
// Rx
//
// Created by Krunoslav Zaher on 3/22/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// MARK: throttle
extension ObservableType {
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
`throttle` and `debounce` are synonyms.
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers and send events on.
- returns: The throttled sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func throttle<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S)
-> Observable<E> {
return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
`throttle` and `debounce` are synonyms.
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers and send events on.
- returns: The throttled sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func debounce<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S)
-> Observable<E> {
return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
// MARK: sample
extension ObservableType {
/**
Samples the source observable sequence using a samper observable sequence producing sampling ticks.
Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence.
**In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.**
- parameter sampler: Sampling tick sequence.
- returns: Sampled observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func sample<O: ObservableType>(sampler: O)
-> Observable<E> {
return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: true)
}
/**
Samples the source observable sequence using a samper observable sequence producing sampling ticks.
Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence.
**In case there were no new elements between sampler ticks, last produced element is always sent to the resulting sequence.**
- parameter sampler: Sampling tick sequence.
- returns: Sampled observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func sampleLatest<O: ObservableType>(sampler: O)
-> Observable<E> {
return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: false)
}
}
// MARK: interval
/**
Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages.
- parameter period: Period for producing the values in the resulting sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence that produces a value after each period.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func interval<S: SchedulerType>(period: S.TimeInterval, _ scheduler: S)
-> Observable<Int64> {
return Timer(dueTime: period,
period: period,
scheduler: scheduler
)
}
// MARK: timer
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- parameter dueTime: Relative time at which to produce the first value.
- parameter period: Period to produce subsequent values.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func timer<S: SchedulerType>(dueTime: S.TimeInterval, _ period: S.TimeInterval, _ scheduler: S)
-> Observable<Int64> {
return Timer(
dueTime: dueTime,
period: period,
scheduler: scheduler
)
}
/**
Returns an observable sequence that produces a single value at the specified absolute due time, using the specified scheduler to run the timer.
- parameter dueTime: Time interval after which to produce the value.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence that produces a value at due time.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func timer<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S)
-> Observable<Int64> {
return Timer(
dueTime: dueTime,
period: nil,
scheduler: scheduler
)
}
// MARK: take
extension ObservableType {
/**
Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func take<S: SchedulerType>(duration: S.TimeInterval, _ scheduler: S)
-> Observable<E> {
return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// MARK: skip
extension ObservableType {
/**
Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- parameter duration: Duration for skipping elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func skip<S: SchedulerType>(duration: S.TimeInterval, _ scheduler: S)
-> Observable<E> {
return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// MARK: delaySubscription
extension ObservableType {
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func delaySubscription<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S)
-> Observable<E> {
return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
// MARK: buffer
extension ObservableType {
/**
Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers.
A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first.
- parameter timeSpan: Maximum time length of a buffer.
- parameter count: Maximum element count of a buffer.
- parameter scheduler: Scheduler to run buffering timers on.
- returns: An observable sequence of buffers.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func buffer<S: SchedulerType>(timeSpan timeSpan: S.TimeInterval, count: Int, scheduler: S)
-> Observable<[E]> {
return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
// MARK: window
extension ObservableType {
/**
Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed.
- parameter timeSpan: Maximum time length of a window.
- parameter count: Maximum element count of a window.
- parameter scheduler: Scheduler to run windowing timers on.
- returns: An observable sequence of windows (instances of `Observable`).
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func window<S: SchedulerType>(timeSpan timeSpan: S.TimeInterval, count: Int, scheduler: S)
-> Observable<Observable<E>> {
return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
|
mit
|
4640264e0ac4226486d4b147a5fbe513
| 38.952174 | 187 | 0.712482 | 4.603707 | false | false | false | false |
aknuds1/foodtracker
|
FoodTracker/MealTableViewController.swift
|
1
|
4639
|
import UIKit
enum NSCodingError: ErrorType {
case CodingFailure
}
class MealTableViewController: UITableViewController {
// MARK: Properties
var meals = [Meal]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = editButtonItem()
if let savedMeals = loadMeals() {
meals += savedMeals
print("Loaded stored meals")
} else {
print("Loading sample meals")
loadSampleMeals()
}
}
func loadSampleMeals() {
let photo1 = UIImage(named: "Squirrel")!
let meal1 = Meal(name: "Caprese Salad", photo: photo1, rating: 4)!
let photo2 = UIImage(named: "Squirrel 2")!
let meal2 = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5)!
let photo3 = UIImage(named: "Squirrel 3")!
let meal3 = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3)!
meals += [meal1, meal2, meal3,]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
meals.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 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
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return meals.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MealTableViewCell", forIndexPath: indexPath) as! MealTableViewCell
let meal = meals[indexPath.row]
cell.nameLabel.text = meal.name
cell.photoImageView.image = meal.photo
cell.ratingControl.rating = meal.rating
return cell
}
@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.sourceViewController as? MealViewController, meal = sourceViewController.meal {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing meal.
meals[selectedIndexPath.row] = meal
tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
}
else {
// Add a new meal.
let newIndexPath = NSIndexPath(forRow: meals.count, inSection: 0)
meals.append(meal)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
saveMeals()
}
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print("Prepare for segue \(segue.identifier)")
if segue.identifier == "showDetail" {
let mealDetailViewController = segue.destinationViewController as! MealViewController
if let selectedMealCell = sender as? MealTableViewCell {
let indexPath = tableView.indexPathForCell(selectedMealCell)!
let selectedMeal = meals[indexPath.row]
mealDetailViewController.meal = selectedMeal
}
}
else if segue.identifier == "addItem" {
print("Adding new meal.")
}
}
// MARK: NSCoding
func saveMeals() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveUrl.path!)
if !isSuccessfulSave {
print("Failed to save meals :(")
}
}
func loadMeals() -> [Meal]? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(Meal.ArchiveUrl.path!) as? [Meal]
}
}
|
mit
|
4f3d358d205a7da96424f66e4fc4c005
| 37.02459 | 157 | 0.633757 | 5.326062 | false | false | false | false |
SuPair/firefox-ios
|
Client/Frontend/AuthenticationManager/ChangePasscodeViewController.swift
|
12
|
3454
|
/* 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 SwiftKeychainWrapper
import Shared
/// Displayed to the user when changing an existing passcode.
class ChangePasscodeViewController: PagingPasscodeViewController, PasscodeInputViewDelegate {
fileprivate var newPasscode: String?
fileprivate var oldPasscode: String?
override init() {
super.init()
self.title = AuthenticationStrings.changePasscode
self.panes = [
PasscodePane(title: AuthenticationStrings.enterPasscode, passcodeSize: authenticationInfo?.passcode?.count ?? 6),
PasscodePane(title: AuthenticationStrings.enterNewPasscode, passcodeSize: 6),
PasscodePane(title: AuthenticationStrings.reenterPasscode, passcodeSize: 6),
]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
panes.forEach { $0.codeInputView.delegate = self }
// Don't show the keyboard or allow typing if we're locked out. Also display the error.
if authenticationInfo?.isLocked() ?? false {
displayLockoutError()
panes.first?.codeInputView.isUserInteractionEnabled = false
} else {
panes.first?.codeInputView.becomeFirstResponder()
}
}
func passcodeInputView(_ inputView: PasscodeInputView, didFinishEnteringCode code: String) {
switch currentPaneIndex {
case 0:
// Constraint: We need to make sure that the first passcode they've entered matches the one stored in the keychain
if code != authenticationInfo?.passcode {
panes[currentPaneIndex].shakePasscode()
failIncorrectPasscode(inputView)
return
}
oldPasscode = code
authenticationInfo?.recordValidation()
// Clear out any previous errors if we are allowed to proceed
errorToast?.removeFromSuperview()
scrollToNextAndSelect()
case 1:
// Constraint: The new passcode cannot match their old passcode.
if oldPasscode == code {
failMustBeDifferent()
// Scroll back and reset the input fields
resetAllInputFields()
return
}
newPasscode = code
errorToast?.removeFromSuperview()
scrollToNextAndSelect()
case 2:
if newPasscode != code {
failMismatchPasscode()
// Scroll back and reset input fields
resetAllInputFields()
scrollToPreviousAndSelect()
newPasscode = nil
return
}
changePasscodeToCode(code)
dismissAnimated()
default:
break
}
}
fileprivate func changePasscodeToCode(_ code: String) {
authenticationInfo?.updatePasscode(code)
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo)
let notificationCenter = NotificationCenter.default
notificationCenter.post(name: .PasscodeDidChange, object: nil)
}
}
|
mpl-2.0
|
c2cc2fef3444c4e8133061561cba8477
| 36.956044 | 126 | 0.634916 | 5.718543 | false | false | false | false |
cpimhoff/AntlerKit
|
Framework/AntlerKit/Physics/PhysicsBodyCategory.swift
|
1
|
3303
|
//
// PhysicsBodyCategory.swift
// AntlerKit
//
// Created by Charlie Imhoff on 1/3/17.
// Copyright © 2017 Charlie Imhoff. All rights reserved.
//
import Foundation
import SpriteKit
public struct PhysicsBodyCategory : OptionSet, Hashable {
internal static var collisions = [PhysicsBodyCategory : Set<PhysicsBodyCategory>]()
internal static var contacts = [PhysicsBodyCategory : Set<PhysicsBodyCategory>]()
public let rawValue : UInt32
public var hashValue : Int {
return rawValue.hashValue
}
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
public init(uniqueInt1Through32 index: UInt32) {
if index == 0 || index > 32 { fatalError("PhysicsBodyCategory index must be within 1...32") }
self.init(rawValue: 1 << (index - 1))
}
}
// MARK: - Built In Categories
public extension PhysicsBodyCategory {
static let none = PhysicsBodyCategory(rawValue: 0)
static let all = PhysicsBodyCategory(rawValue: ~0)
}
// MARK: - Setting Collisions and Contacts
public extension PhysicsBodyCategory {
static func enableCollision(between a: PhysicsBodyCategory, and b: PhysicsBodyCategory) {
combineSeperatedFlags(compositeA: a, compositeB: b) { (x, y) in
let previous = PhysicsBodyCategory.collisions[x] ?? Set<PhysicsBodyCategory>()
let updated = previous.union([y])
PhysicsBodyCategory.collisions[x] = updated
}
}
static func enableContacts(between a: PhysicsBodyCategory, and b: PhysicsBodyCategory) {
combineSeperatedFlags(compositeA: a, compositeB: b) { (x, y) in
let previous = PhysicsBodyCategory.contacts[x] ?? Set<PhysicsBodyCategory>()
let updated = previous.union([y])
PhysicsBodyCategory.contacts[x] = updated
}
}
private static func combineSeperatedFlags(compositeA: PhysicsBodyCategory, compositeB: PhysicsBodyCategory, action: (PhysicsBodyCategory, PhysicsBodyCategory) -> Void) {
let aFlags = compositeA.seperatedFlags
let bFlags = compositeB.seperatedFlags
for aFlag in aFlags {
for bFlag in bFlags {
action(aFlag, bFlag)
action(bFlag, aFlag)
}
}
}
}
// MARK: - SpriteKit Integration
public extension PhysicsBody {
var category : PhysicsBodyCategory {
get {
return PhysicsBodyCategory(rawValue: self.categoryBitMask)
}
set {
self.categoryBitMask = newValue.categoryBitMask
self.collisionBitMask = newValue.collisionBitMask
self.contactTestBitMask = newValue.contactTestBitMask
}
}
}
internal extension PhysicsBodyCategory {
var categoryBitMask : UInt32 {
return rawValue
}
var collisionBitMask : UInt32 {
var mask = PhysicsBodyCategory.none
for flag in self.seperatedFlags {
PhysicsBodyCategory.collisions[flag]?.forEach {
mask.insert($0)
}
}
return mask.rawValue
}
var contactTestBitMask : UInt32 {
var mask = PhysicsBodyCategory.none
for flag in self.seperatedFlags {
PhysicsBodyCategory.contacts[flag]?.forEach {
mask.insert($0)
}
}
return mask.rawValue
}
}
// MARK: - Decomposing Flags
private extension PhysicsBodyCategory {
var seperatedFlags : Set<PhysicsBodyCategory> {
var flags = Set<PhysicsBodyCategory>()
for i : UInt32 in 0..<32 {
let mask = PhysicsBodyCategory(rawValue: 1 << i)
if self.contains(mask) {
flags.insert(mask)
}
}
return flags
}
}
|
mit
|
272f2d518501f26d864b41fb8ed994c1
| 22.755396 | 170 | 0.72229 | 3.685268 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
Pods/QRCodeReader.swift/Sources/QRCodeReader.swift
|
1
|
13611
|
/*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import AVFoundation
protocol QRCodeReaderLifeCycleDelegate: class {
func readerDidStartScanning()
func readerDidStopScanning()
}
/// Reader object base on the `AVCaptureDevice` to read / scan 1D and 2D codes.
public final class QRCodeReader: NSObject, AVCaptureMetadataOutputObjectsDelegate {
private let sessionQueue = DispatchQueue(label: "session queue")
private let metadataObjectsQueue = DispatchQueue(label: "com.yannickloriot.qr", attributes: [], target: nil)
var defaultDevice: AVCaptureDevice? = AVCaptureDevice.default(for: .video)
var frontDevice: AVCaptureDevice? = {
if #available(iOS 10, *) {
return AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .front)
}
else {
for device in AVCaptureDevice.devices(for: AVMediaType.video) {
if device.position == .front {
return device
}
}
}
return nil
}()
lazy var defaultDeviceInput: AVCaptureDeviceInput? = {
guard let defaultDevice = defaultDevice else { return nil }
return try? AVCaptureDeviceInput(device: defaultDevice)
}()
lazy var frontDeviceInput: AVCaptureDeviceInput? = {
if let _frontDevice = self.frontDevice {
return try? AVCaptureDeviceInput(device: _frontDevice)
}
return nil
}()
public var metadataOutput = AVCaptureMetadataOutput()
var session = AVCaptureSession()
weak var lifeCycleDelegate: QRCodeReaderLifeCycleDelegate?
// MARK: - Managing the Properties
/// CALayer that you use to display video as it is being captured by an input device.
public let previewLayer: AVCaptureVideoPreviewLayer
/// An array of object identifying the types of metadata objects to process.
public let metadataObjectTypes: [AVMetadataObject.ObjectType]
// MARK: - Managing the Code Discovery
/// Flag to know whether the scanner should stop scanning when a code is found.
public var stopScanningWhenCodeIsFound: Bool = true
/// Block is executed when a metadata object is found.
public var didFindCode: ((QRCodeReaderResult) -> Void)?
/// Block is executed when a found metadata object string could not be decoded.
public var didFailDecoding: (() -> Void)?
// MARK: - Creating the Code Reade
/**
Initializes the code reader with the QRCode metadata type object.
*/
public convenience override init() {
self.init(metadataObjectTypes: [AVMetadataObject.ObjectType.qr], captureDevicePosition: .back)
}
/**
Initializes the code reader with an array of metadata object types, and the default initial capture position
- parameter metadataObjectTypes: An array of objects identifying the types of metadata objects to process.
*/
public convenience init(metadataObjectTypes types: [AVMetadataObject.ObjectType]) {
self.init(metadataObjectTypes: types, captureDevicePosition: .back)
}
/**
Initializes the code reader with the starting capture device position, and the default array of metadata object types
- parameter captureDevicePosition: The capture position to use on start of scanning
*/
public convenience init(captureDevicePosition position: AVCaptureDevice.Position) {
self.init(metadataObjectTypes: [AVMetadataObject.ObjectType.qr], captureDevicePosition: position)
}
/**
Initializes the code reader with an array of metadata object types.
- parameter metadataObjectTypes: An array of objects identifying the types of metadata objects to process.
- parameter captureDevicePosition: The Camera to use on start of scanning.
*/
public init(metadataObjectTypes types: [AVMetadataObject.ObjectType], captureDevicePosition: AVCaptureDevice.Position) {
metadataObjectTypes = types
previewLayer = AVCaptureVideoPreviewLayer(session: session)
super.init()
sessionQueue.async {
self.configureDefaultComponents(withCaptureDevicePosition: captureDevicePosition)
}
}
// MARK: - Initializing the AV Components
private func configureDefaultComponents(withCaptureDevicePosition: AVCaptureDevice.Position) {
for output in session.outputs {
session.removeOutput(output)
}
for input in session.inputs {
session.removeInput(input)
}
// Add video input
switch withCaptureDevicePosition {
case .front:
if let _frontDeviceInput = frontDeviceInput {
session.addInput(_frontDeviceInput)
}
case .back, .unspecified:
if let _defaultDeviceInput = defaultDeviceInput {
session.addInput(_defaultDeviceInput)
}
}
// Add metadata output
session.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: metadataObjectsQueue)
let allTypes = Set(metadataOutput.availableMetadataObjectTypes)
let filtered = metadataObjectTypes.filter { (mediaType) -> Bool in
allTypes.contains(mediaType)
}
metadataOutput.metadataObjectTypes = filtered
previewLayer.videoGravity = .resizeAspectFill
session.commitConfiguration()
}
/// Switch between the back and the front camera.
@discardableResult
public func switchDeviceInput() -> AVCaptureDeviceInput? {
if let _frontDeviceInput = frontDeviceInput {
session.beginConfiguration()
if let _currentInput = session.inputs.first as? AVCaptureDeviceInput {
session.removeInput(_currentInput)
let newDeviceInput = (_currentInput.device.position == .front) ? defaultDeviceInput : _frontDeviceInput
session.addInput(newDeviceInput!)
}
session.commitConfiguration()
}
return session.inputs.first as? AVCaptureDeviceInput
}
// MARK: - Controlling Reader
/**
Starts scanning the codes.
*Notes: if `stopScanningWhenCodeIsFound` is sets to true (default behaviour), each time the scanner found a code it calls the `stopScanning` method.*
*/
public func startScanning() {
sessionQueue.async {
guard !self.session.isRunning else { return }
self.session.startRunning()
DispatchQueue.main.async {
self.lifeCycleDelegate?.readerDidStartScanning()
}
}
}
/// Stops scanning the codes.
public func stopScanning() {
sessionQueue.async {
guard self.session.isRunning else { return }
self.session.stopRunning()
DispatchQueue.main.async {
self.lifeCycleDelegate?.readerDidStopScanning()
}
}
}
/**
Indicates whether the session is currently running.
The value of this property is a Bool indicating whether the receiver is running.
Clients can key value observe the value of this property to be notified when
the session automatically starts or stops running.
*/
public var isRunning: Bool {
return session.isRunning
}
/**
Indicates whether a front device is available.
- returns: true whether the device has a front device.
*/
public var hasFrontDevice: Bool {
return frontDevice != nil
}
/**
Indicates whether the torch is available.
- returns: true if a torch is available.
*/
public var isTorchAvailable: Bool {
return defaultDevice?.isTorchAvailable ?? false
}
/**
Toggles torch on the default device.
*/
public func toggleTorch() {
do {
try defaultDevice?.lockForConfiguration()
defaultDevice?.torchMode = defaultDevice?.torchMode == .on ? .off : .on
defaultDevice?.unlockForConfiguration()
}
catch _ { }
}
// MARK: - Managing the Orientation
/**
Returns the video orientation corresponding to the given device orientation.
- parameter orientation: The orientation of the app's user interface.
- parameter supportedOrientations: The supported orientations of the application.
- parameter fallbackOrientation: The video orientation if the device orientation is FaceUp or FaceDown.
*/
public class func videoOrientation(deviceOrientation orientation: UIDeviceOrientation, withSupportedOrientations supportedOrientations: UIInterfaceOrientationMask, fallbackOrientation: AVCaptureVideoOrientation? = nil) -> AVCaptureVideoOrientation {
let result: AVCaptureVideoOrientation
switch (orientation, fallbackOrientation) {
case (.landscapeLeft, _):
result = .landscapeRight
case (.landscapeRight, _):
result = .landscapeLeft
case (.portrait, _):
result = .portrait
case (.portraitUpsideDown, _):
result = .portraitUpsideDown
case (_, .some(let orientation)):
result = orientation
default:
result = .portrait
}
if supportedOrientations.contains(orientationMask(videoOrientation: result)) {
return result
}
else if let orientation = fallbackOrientation , supportedOrientations.contains(orientationMask(videoOrientation: orientation)) {
return orientation
}
else if supportedOrientations.contains(.portrait) {
return .portrait
}
else if supportedOrientations.contains(.landscapeLeft) {
return .landscapeLeft
}
else if supportedOrientations.contains(.landscapeRight) {
return .landscapeRight
}
else {
return .portraitUpsideDown
}
}
class func orientationMask(videoOrientation orientation: AVCaptureVideoOrientation) -> UIInterfaceOrientationMask {
switch orientation {
case .landscapeLeft:
return .landscapeLeft
case .landscapeRight:
return .landscapeRight
case .portrait:
return .portrait
case .portraitUpsideDown:
return .portraitUpsideDown
}
}
// MARK: - Checking the Reader Availabilities
/**
Checks whether the reader is available.
- returns: A boolean value that indicates whether the reader is available.
*/
public class func isAvailable() -> Bool {
guard let captureDevice = AVCaptureDevice.default(for: .video) else { return false }
return (try? AVCaptureDeviceInput(device: captureDevice)) != nil
}
/**
Checks and return whether the given metadata object types are supported by the current device.
- parameter metadataTypes: An array of objects identifying the types of metadata objects to check.
- returns: A boolean value that indicates whether the device supports the given metadata object types.
*/
public class func supportsMetadataObjectTypes(_ metadataTypes: [AVMetadataObject.ObjectType]? = nil) throws -> Bool {
guard let captureDevice = AVCaptureDevice.default(for: .video) else {
throw NSError(domain: "com.yannickloriot.error", code: -1001, userInfo: nil)
}
let deviceInput = try AVCaptureDeviceInput(device: captureDevice)
let output = AVCaptureMetadataOutput()
let session = AVCaptureSession()
session.addInput(deviceInput)
session.addOutput(output)
var metadataObjectTypes = metadataTypes
if metadataObjectTypes == nil || metadataObjectTypes?.count == 0 {
// Check the QRCode metadata object type by default
metadataObjectTypes = [.qr]
}
for metadataObjectType in metadataObjectTypes! {
if !output.availableMetadataObjectTypes.contains { $0 == metadataObjectType } {
return false
}
}
return true
}
// MARK: - AVCaptureMetadataOutputObjects Delegate Methods
public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
sessionQueue.async { [weak self] in
guard let weakSelf = self else { return }
for current in metadataObjects {
if let _readableCodeObject = current as? AVMetadataMachineReadableCodeObject {
if _readableCodeObject.stringValue != nil {
if weakSelf.metadataObjectTypes.contains(_readableCodeObject.type) {
guard weakSelf.session.isRunning, let sVal = _readableCodeObject.stringValue else { return }
if weakSelf.stopScanningWhenCodeIsFound {
weakSelf.session.stopRunning()
DispatchQueue.main.async {
weakSelf.lifeCycleDelegate?.readerDidStopScanning()
}
}
let scannedResult = QRCodeReaderResult(value: sVal, metadataType:_readableCodeObject.type.rawValue)
DispatchQueue.main.async {
weakSelf.didFindCode?(scannedResult)
}
}
}
}
else {
weakSelf.didFailDecoding?()
}
}
}
}
}
|
mit
|
47f8dcb23a5f9a339f58ee57a725a00e
| 32.116788 | 251 | 0.712806 | 5.241047 | false | false | false | false |
SlimGinz/HomeworkHelper
|
Homework Helper/GradesViewController.swift
|
1
|
2652
|
//
// GradesViewController.swift
// Homework Helper
//
// Created by Cory Ginsberg on 2/7/15.
// Copyright (c) 2015 Boiling Point Development. All rights reserved.
//
import UIKit
import CoreData
class GradesViewController: UIViewController, UITableViewDelegate, PathMenuDelegate, MenuDelegate {
let menu = Menu()
override func viewDidLoad() {
super.viewDidLoad()
menu.delegate = self
menu.createPathMenu()
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
navigationController?.navigationBar.shadowImage = UIImage(named: "yellow-shadow")
}
func getCurrentViewController() -> UIViewController {
return self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
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.
return 1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
return cell
}
// Override to support editing the table view.
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
}
}
/*
// 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.
}
*/
}
|
gpl-2.0
|
f97d848f6cc6e2cb06fa3b85e38b992f
| 32.56962 | 148 | 0.671569 | 5.666667 | false | false | false | false |
PureSwift/BlueZ
|
Sources/BluetoothLinux/L2CAP.swift
|
2
|
14358
|
//
// L2CAP.swift
// BluetoothLinux
//
// Created by Alsey Coleman Miller on 2/28/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if os(Linux)
import Glibc
#elseif os(OSX) || os(iOS)
import Darwin.C
#endif
import Foundation
import Bluetooth
import CSwiftBluetoothLinux
/// L2CAP Bluetooth socket
public final class L2CAPSocket: L2CAPSocketProtocol {
// MARK: - Properties
/// The socket's security level.
public private(set) var securityLevel: SecurityLevel
// MARK: - Internal Properties
/// Internal socket file descriptor
internal let internalSocket: CInt
/// Internal L2CAP Socket address
internal let internalAddress: sockaddr_l2
// MARK: - Initialization
deinit {
close(internalSocket)
}
/// Create a new L2CAP socket on the HostController with the specified identifier.
public init(controllerAddress: BluetoothAddress,
protocolServiceMultiplexer: ProtocolServiceMultiplexer? = nil,
channelIdentifier: ChannelIdentifier = .att,
addressType: AddressType? = .lowEnergyPublic,
securityLevel: SecurityLevel = .low) throws {
let (internalSocket, internalAddress) = try L2CAPSocket.createSocket(
controllerAddress: controllerAddress,
protocolServiceMultiplexer: UInt16(protocolServiceMultiplexer?.rawValue ?? 0),
channelIdentifier: channelIdentifier.rawValue,
addressType: addressType)
// store values
self.internalSocket = internalSocket
self.internalAddress = internalAddress
self.securityLevel = .sdp
// configure socket
try self.setSecurityLevel(securityLevel)
}
/// For new incoming connections for server.
internal init(clientSocket: CInt,
remoteAddress: sockaddr_l2,
securityLevel: SecurityLevel) {
self.internalSocket = clientSocket
self.internalAddress = remoteAddress
self.securityLevel = securityLevel
}
/// Creates a server socket for an L2CAP connection.
public static func lowEnergyServer(controllerAddress: BluetoothAddress = .zero,
isRandom: Bool = false,
securityLevel: SecurityLevel = .low) throws -> L2CAPSocket {
let socket = try L2CAPSocket(controllerAddress: controllerAddress,
protocolServiceMultiplexer: nil,
channelIdentifier: .att,
addressType: isRandom ? .lowEnergyRandom : .lowEnergyPublic,
securityLevel: securityLevel)
try socket.startListening()
return socket
}
/// Creates a client socket for an L2CAP connection.
public static func lowEnergyClient(controllerAddress: BluetoothAddress = .zero,
destination: (address: BluetoothAddress, type: AddressType),
securityLevel: SecurityLevel = .low) throws -> L2CAPSocket {
let socket = try L2CAPSocket(controllerAddress: controllerAddress,
protocolServiceMultiplexer: nil,
channelIdentifier: .att,
addressType: nil,
securityLevel: securityLevel)
try socket.openConnection(to: destination.address, type: destination.type)
return socket
}
// MARK: - Static Methods
/// Check whether the file descriptor is a L2CAP socket.
public static func validate(fileDescriptor: CInt) throws -> Bool {
func value(for socketOption: CInt) throws -> CInt {
var optionValue: CInt = 0
var optionLength = socklen_t(MemoryLayout<CInt>.size)
guard getsockopt(fileDescriptor, SOL_SOCKET, socketOption, &optionValue, &optionLength) == 0
else { throw POSIXError.errorno }
return optionValue
}
//. socket domain and protocol
guard try value(for: SO_DOMAIN) == AF_BLUETOOTH,
try value(for: SO_PROTOCOL) == BluetoothProtocol.l2cap.rawValue
else { return false }
return true
}
/// Create the underlying socket for the L2CAP.
@inline(__always)
private static func createSocket(controllerAddress: BluetoothAddress,
protocolServiceMultiplexer: UInt16,
channelIdentifier: UInt16,
addressType: AddressType?) throws -> (CInt, sockaddr_l2) {
// open socket
let internalSocket = socket(AF_BLUETOOTH,
SOCK_SEQPACKET,
BluetoothProtocol.l2cap.rawValue)
// error creating socket
guard internalSocket >= 0
else { throw POSIXError.errorno }
// set source address
var localAddress = sockaddr_l2()
memset(&localAddress, 0, MemoryLayout<sockaddr_l2>.size)
localAddress.l2_family = sa_family_t(AF_BLUETOOTH)
localAddress.l2_bdaddr = controllerAddress.littleEndian
localAddress.l2_psm = protocolServiceMultiplexer.littleEndian
localAddress.l2_cid = channelIdentifier.littleEndian
localAddress.l2_bdaddr_type = addressType?.rawValue ?? 0
// bind socket to port and address
guard withUnsafeMutablePointer(to: &localAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1, {
bind(internalSocket, $0, socklen_t(MemoryLayout<sockaddr_l2>.size)) == 0
})
}) else { close(internalSocket); throw POSIXError.errorno }
return (internalSocket, localAddress)
}
// MARK: - Accessors
/// Bluetooth address
public var address: BluetoothAddress {
return BluetoothAddress(littleEndian: internalAddress.l2_bdaddr)
}
public var addressType: AddressType {
return AddressType(rawValue: internalAddress.l2_bdaddr_type)!
}
/// Protocol/Service Multiplexer (PSM)
public var protocolServiceMultiplexer: UInt16 {
return UInt16(littleEndian: internalAddress.l2_psm)
}
/// Channel Identifier (CID)
///
/// L2CAP channel endpoints are identified to their clients by a Channel Identifier (CID).
/// This is assigned by L2CAP, and each L2CAP channel endpoint on any device has a different CID.
public var channelIdentifier: ChannelIdentifier {
return ChannelIdentifier(rawValue: UInt16(littleEndian: internalAddress.l2_cid))
}
// MARK: - Methods
/// Attempts to change the socket's security level.
public func setSecurityLevel(_ securityLevel: SecurityLevel) throws {
// set security level
var security = bt_security()
security.level = securityLevel.rawValue
guard setsockopt(internalSocket, SOL_BLUETOOTH, BT_SECURITY, &security, socklen_t(MemoryLayout<bt_security>.size)) == 0
else { throw POSIXError.errorno }
self.securityLevel = securityLevel
}
/// Put socket into listening mode.
public func startListening(queueLimit: Int = 10) throws {
// put socket into listening mode
guard listen(internalSocket, Int32(queueLimit)) == 0
else { throw POSIXError.errorno }
}
/// Blocks the caller until a new connection is recieved.
public func waitForConnection() throws -> L2CAPSocket {
var remoteAddress = sockaddr_l2()
var socketLength = socklen_t(MemoryLayout<sockaddr_l2>.size)
// accept new client
let client = withUnsafeMutablePointer(to: &remoteAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1, {
accept(internalSocket, $0, &socketLength)
})
})
// error accepting new connection
guard client >= 0 else { throw POSIXError.errorno }
let newSocket = L2CAPSocket(clientSocket: client,
remoteAddress: remoteAddress,
securityLevel: securityLevel)
// make socket non-blocking
try newSocket.setNonblocking()
return newSocket
}
/// Connect to another L2CAP server.
public func openConnection(to address: BluetoothAddress,
type addressType: AddressType = .lowEnergyPublic) throws {
// Set up destination address
var destinationAddress = sockaddr_l2()
memset(&destinationAddress, 0, MemoryLayout<sockaddr_l2>.size)
destinationAddress.l2_family = sa_family_t(AF_BLUETOOTH)
destinationAddress.l2_bdaddr = address.littleEndian
destinationAddress.l2_psm = internalAddress.l2_psm
destinationAddress.l2_cid = internalAddress.l2_cid
destinationAddress.l2_bdaddr_type = addressType.rawValue
guard withUnsafeMutablePointer(to: &destinationAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1, {
connect(internalSocket, $0, socklen_t(MemoryLayout<sockaddr_l2>.size)) == 0
})
}) else { throw POSIXError.errorno }
// make socket non-blocking
try setNonblocking()
}
/// Reads from the socket.
public func recieve(_ bufferSize: Int = 1024) throws -> Data? {
// check if reading buffer has data.
guard try canRead()
else { return nil }
// read socket
var buffer = [UInt8](repeating: 0, count: bufferSize)
let actualByteCount = read(internalSocket, &buffer, bufferSize)
guard actualByteCount >= 0 else { throw POSIXError.errorno }
let actualBytes = Array(buffer.prefix(actualByteCount))
return Data(bytes: actualBytes)
}
private func canRead() throws -> Bool {
var readSockets = FileDescriptorSet()
readSockets.zero()
readSockets.add(internalSocket)
var time = timeval()
let fdCount = select(internalSocket + 1, &readSockets, nil, nil, &time)
guard fdCount != -1
else { throw POSIXError.errorno }
return fdCount > 0
}
private func setNonblocking() throws {
var flags = fcntl(internalSocket, F_GETFL, 0)
guard flags != -1
else { throw POSIXError.errorno }
flags = fcntl(internalSocket, F_SETFL, flags | O_NONBLOCK);
guard flags != -1
else { throw POSIXError.errorno }
}
/// Write to the socket.
public func send(_ data: Data) throws {
var buffer = Array(data)
let actualByteCount = write(internalSocket, &buffer, buffer.count)
guard actualByteCount >= 0
else { throw POSIXError.errorno }
guard actualByteCount == buffer.count
else { throw L2CAPSocketError.sentLessBytes(actualByteCount) }
}
/// Attempt to get L2CAP socket options.
public func requestSocketOptions() throws -> Options {
var optionValue = Options()
var optionLength = socklen_t(MemoryLayout<Options>.size)
guard getsockopt(internalSocket, SOL_L2CAP, L2CAP_OPTIONS, &optionValue, &optionLength) == 0
else { throw POSIXError.errorno }
return optionValue
}
}
// MARK: - Supporting Types
public extension L2CAPSocket {
public typealias Error = L2CAPSocketError
}
public enum L2CAPSocketError: Error {
/// Sent less bytes than expected.
case sentLessBytes(Int)
/// The provided file descriptor was invalid
case invalidFileDescriptor(CInt)
}
public extension L2CAPSocket {
/// L2CAP Socket Options
public struct Options {
public var outputMaximumTransmissionUnit: UInt16 // omtu
public var inputMaximumTransmissionUnit: UInt16 // imtu
public var flushTo: UInt16 // flush_to
public var mode: UInt8
public var fcs: UInt8
public var maxTX: UInt8 // max_tx
public var txwinSize: UInt8 // txwin_size
fileprivate init() {
self.outputMaximumTransmissionUnit = 0
self.inputMaximumTransmissionUnit = 0
self.flushTo = 0
self.mode = 0
self.fcs = 0
self.maxTX = 0
self.txwinSize = 0
}
}
public enum ConnectionResult: UInt16 {
case success = 0x0000
case pending = 0x0001
case badPSM = 0x0002
case secBlock = 0x0003
case noMemory = 0x0004
}
public enum ConnectionStatus: UInt16 {
case noInfo = 0x0000
case authenticationPending = 0x0001
case authorizationPending = 0x0002
}
}
// MARK: - Internal Supporting Types
let AF_BLUETOOTH: CInt = 31
//let BTPROTO_L2CAP: CInt = 0 // BluetoothProtocol.L2CAP
let SOL_BLUETOOTH: CInt = 274
let BT_SECURITY: CInt = 4
let BT_FLUSHABLE: CInt = 8
let SOL_L2CAP: CInt = 6
let L2CAP_OPTIONS: CInt = 0x01
/// L2CAP socket address (not packed)
struct sockaddr_l2 {
var l2_family: sa_family_t = 0
var l2_psm: CUnsignedShort = 0
var l2_bdaddr: BluetoothAddress = .zero
var l2_cid: CUnsignedShort = 0
var l2_bdaddr_type: UInt8 = 0
init() { }
}
/// Bluetooth security level (not packed)
struct bt_security {
var level: UInt8 = 0
var key_size: UInt8 = 0
init() { }
}
// MARK: - Linux Support
#if os(Linux)
let SOCK_SEQPACKET: CInt = CInt(Glibc.SOCK_SEQPACKET.rawValue)
#endif
// MARK: - OS X support
#if os(macOS)
let SO_PROTOCOL: CInt = 38
let SO_DOMAIN: CInt = 39
#endif
|
mit
|
ab8444c1ef66a81348ddb4d2131957f2
| 31.046875 | 127 | 0.594414 | 4.800067 | false | false | false | false |
aroyer/neo4j-ios-patch
|
Source/Theo/Theo/Node.swift
|
1
|
7664
|
//
// Node.swift
// Theo
//
// Created by Cory D. Wiles on 9/19/14.
// Copyright (c) 2014 Theo. All rights reserved.
//
import Foundation
let TheoNodeExtensions: String = "extensions"
let TheoNodePagedTraverse: String = "paged_traverse"
let TheoNodeLabels: String = "labels"
let TheoNodeOutGoingRelationships: String = "outgoing_relationships"
let TheoNodeTraverse: String = "traverse"
let TheoNodeAllTypedRelationships: String = "all_typed_relationships"
let TheoNodeProperty: String = "property"
let TheoNodeAllRelationships: String = "all_relationships"
let TheoNodeSelf: String = "self"
let TheoNodeOutGoingTypedRelationships: String = "outgoing_typed_relationships"
let TheoNodeProperties: String = "properties"
let TheoNodeIncomingRelationships: String = "incoming_relationships"
let TheoNodeIncomingTypedRelationships: String = "incoming_typed_relationships"
let TheoNodeCreateRelationship: String = "create_relationship"
let TheoNodeData: String = "data"
let TheoNodeMetaData: String = "metadata"
public struct NodeMeta: Printable {
var extensions: [String: AnyObject] = [String: AnyObject]()
var page_traverse: String = ""
var labels: String = ""
var outgoing_relationships: String = ""
var traverse: String = ""
var all_typed_relationships: String = ""
var property: String = ""
var all_relationships: String = ""
var node_self: String = ""
var outgoing_typed_relationships: String = ""
var properties: String = ""
var incoming_relationships: String = ""
var incoming_typed_relationships: String = ""
var create_relationship: String = ""
var data: [String: AnyObject] = [String: AnyObject]()
var metadata: [String: AnyObject] = [String: AnyObject]()
public func nodeID() -> String {
let pathComponents: Array<String> = self.node_self.componentsSeparatedByString("/")
return pathComponents.last!
}
public init(dictionary: Dictionary<String, AnyObject>!) {
for (key: String, value: AnyObject) in dictionary {
switch key {
case TheoNodeExtensions:
self.extensions = value as! Dictionary
case TheoNodePagedTraverse:
self.page_traverse = value as! String
case TheoNodeLabels:
self.labels = value as! String
case TheoNodeOutGoingRelationships:
self.outgoing_relationships = value as! String
case TheoNodeTraverse:
self.traverse = value as! String
case TheoNodeAllRelationships:
self.all_relationships = value as! String
case TheoNodeProperty:
self.property = value as! String
case TheoNodeAllRelationships:
self.all_relationships = value as! String
case TheoNodeSelf:
self.node_self = value as! String
case TheoNodeOutGoingTypedRelationships:
self.outgoing_typed_relationships = value as! String
case TheoNodeProperties:
self.properties = value as! String
case TheoNodeIncomingRelationships:
self.incoming_relationships = value as! String
case TheoNodeIncomingTypedRelationships:
self.incoming_typed_relationships = value as! String
case TheoNodeCreateRelationship:
self.create_relationship = value as! String
case TheoNodeData:
self.data = value as! Dictionary
case TheoNodeMetaData:
self.metadata = value as! Dictionary
default:
""
}
}
}
public var description: String {
return "Extensions: \(self.extensions), page_traverse \(self.page_traverse), labels \(self.labels), outgoing_relationships \(self.outgoing_relationships), traverse \(self.traverse), all_typed_relationships \(self.all_typed_relationships), all_typed_relationships \(self.all_typed_relationships), property \(self.property), all_relationships \(self.all_relationships), self \(self.node_self), outgoing_typed_relationships \(self.outgoing_typed_relationships), properties \(self.properties), incoming_relationships \(self.incoming_relationships), incoming_typed_relationships \(self.incoming_typed_relationships), create_relationship \(self.create_relationship), data \(self.data), metadata \(self.metadata), nodeID \(self.nodeID())"
}
}
public class Node {
// MARK: Private Setters and Public Getters
private (set) var nodeData: [String:AnyObject] = [String:AnyObject]()
private (set) var labels: [String] = [String]()
// MARK: Public Properties
public var meta: NodeMeta? = nil {
didSet {
if let metaForNode = self.meta {
self.nodeData = metaForNode.data
}
}
}
// MARK: Constructors
/// Designated Initializer
///
/// :param: Dictionary<String,AnyObject>? data
/// :returns: Node
public required init(data: Dictionary<String,AnyObject>?) {
if let dictionaryData: [String:AnyObject] = data {
self.meta = NodeMeta(dictionary: dictionaryData)
if let metaForNode = self.meta {
self.nodeData = metaForNode.data
}
}
}
/// Convenience initializer
///
/// calls init(data:) with the param value as nil
///
/// :returns: Node
public convenience init() {
self.init(data: nil)
}
/// Gets a specified property for the Node
///
/// :param: String propertyName
/// :returns: AnyObject?
public func getProp(propertyName: String) -> AnyObject? {
if let object: AnyObject = self.nodeData[propertyName] {
return object
}
return nil
}
/// Sets the property for the relationship
///
/// :param: String propertyName
/// :param: String propertyValue
/// :returns: Void
public func setProp(propertyName: String, propertyValue: AnyObject) -> Void {
var objectValue: AnyObject = propertyValue
self.nodeData[propertyName] = objectValue
}
/// Adds label to array of labels for the node
///
/// :param: String label
/// :returns: Void
public func addLabel(label:String) -> Void {
self.labels.append(label)
}
/// Returns whether or not the nodeData is empty
///
/// This is done by checking for empty keys array
///
/// :returns: Bool
public func isEmpty() -> Bool {
return self.nodeData.keys.isEmpty
}
/// Returns whether the current node has labels
///
/// :returns: Bool
public func hasLabels() -> Bool {
return self.labels.isEmpty
}
}
// MARK: - Printable
extension Node: Printable {
public var description: String {
var returnString: String = ""
for (key, value) in self.nodeData {
returnString += "\(key): \(value) "
}
if let meta: NodeMeta = self.meta {
returnString += meta.description
}
return returnString
}
}
|
mit
|
7e3cfc301d7f478fd4f1ec47b2198e7c
| 34.155963 | 739 | 0.590945 | 4.772105 | false | false | false | false |
mattadatta/sulfur
|
xcode-version-script.swift
|
1
|
3554
|
#!/usr/bin/env xcrun --sdk macosx swift
/*
Copyright (c) 2016 Matthew Brown
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Foundation
import Darwin
// Utils
@discardableResult
func shell(_ args: String ...) -> (statusCode: Int, output: String) {
let process = Process()
process.launchPath = "/usr/bin/env"
process.arguments = args
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
return (Int(process.terminationStatus), String(data: data, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines))
}
func setPlistProperty(_ property: String, toValue value: Any) {
let environment = ProcessInfo.processInfo.environment
guard let projectDir = environment["PROJECT_DIR"] else {
print("\'PROJECT_DIR\' environment variable not set!")
exit(1)
}
guard let infoPlistFile = environment["INFOPLIST_FILE"] else {
print("\'INFOPLIST_FILE\' environment variable not set!")
exit(1)
}
if shell("/usr/libexec/PlistBuddy", "-c", "Set :\(property) \(value)", "\(projectDir)/\(infoPlistFile)").statusCode == 0 {
print("Set \(property) to \(value)")
} else {
print("Failed to set \(property) to \(value)")
exit(1)
}
}
// Script
shell("sh", "/etc/profile")
let gitExec = shell("which", "git").output
let branchName = shell(gitExec, "rev-parse", "--abbrev-ref", "HEAD").output
guard branchName.hasPrefix("release") else {
print("Not in release branch, not updating version numbers.")
exit(0)
}
guard let versionStartIndex = branchName.range(of: "/")?.upperBound else {
print("Release branch should have form \"release/x.y.z\".")
exit(1)
}
let versionNumberString = branchName.substring(from: versionStartIndex)
let versionNumberPattern = "^\\d+(\\.\\d+)*$"
guard (try! NSRegularExpression(pattern: versionNumberPattern, options: [])).numberOfMatches(in: versionNumberString, options: [], range: NSRange(location: 0, length: versionNumberString.characters.count)) > 0 else {
print("Version number should match regex pattern \"\(versionNumberPattern)\".")
exit(1)
}
let rcNumber = Int(shell("git", "rev-list", "dev..", "--count").output)! + 1
let shortVersionString = "\(versionNumberString)-rc\(rcNumber)"
let buildNumber = shell(gitExec, "rev-list", "--all", "--count").output
setPlistProperty("CFBundleShortVersionString", toValue: shortVersionString)
setPlistProperty("CFBundleVersion", toValue: buildNumber)
|
mit
|
32d44ceb5a929b286016feef2ac450a1
| 42.341463 | 461 | 0.718627 | 4.382244 | false | false | false | false |
frtlupsvn/Vietnam-To-Go
|
Pods/Former/Former/Cells/FormSelectorDatePickerCell.swift
|
1
|
2730
|
//
// FormSelectorDatePickerCell.swift
// Former-Demo
//
// Created by Ryo Aoyama on 8/25/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
public class FormSelectorDatePickerCell: FormCell, SelectorDatePickerFormableRow {
// MARK: Public
public var selectorDatePicker: UIDatePicker?
public var selectorAccessoryView: UIView?
public private(set) weak var titleLabel: UILabel!
public private(set) weak var displayLabel: UILabel!
public func formTitleLabel() -> UILabel? {
return titleLabel
}
public func formDisplayLabel() -> UILabel? {
return displayLabel
}
public override func updateWithRowFormer(rowFormer: RowFormer) {
super.updateWithRowFormer(rowFormer)
rightConst.constant = (accessoryType == .None) ? -15 : 0
}
public override func setup() {
super.setup()
let titleLabel = UILabel()
titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.insertSubview(titleLabel, atIndex: 0)
self.titleLabel = titleLabel
let displayLabel = UILabel()
displayLabel.textColor = .lightGrayColor()
displayLabel.textAlignment = .Right
displayLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.insertSubview(displayLabel, atIndex: 0)
self.displayLabel = displayLabel
let constraints = [
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-0-[title]-0-|",
options: [],
metrics: nil,
views: ["title": titleLabel]
),
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-0-[display]-0-|",
options: [],
metrics: nil,
views: ["display": displayLabel]
),
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-15-[title]-10-[display(>=0)]",
options: [],
metrics: nil,
views: ["title": titleLabel, "display": displayLabel]
)
].flatMap { $0 }
let rightConst = NSLayoutConstraint(
item: displayLabel,
attribute: .Trailing,
relatedBy: .Equal,
toItem: contentView,
attribute: .Trailing,
multiplier: 1,
constant: 0
)
contentView.addConstraints(constraints + [rightConst])
self.rightConst = rightConst
}
// MARK: Private
private weak var rightConst: NSLayoutConstraint!
}
|
mit
|
82242fdb1cbbcdc920e674e49a96aefa
| 30.744186 | 82 | 0.58996 | 5.685417 | false | false | false | false |
nanthi1990/Typhoon-Swift-Example
|
PocketForecast/Dao/CityDaoUserDefaultsImpl.swift
|
3
|
3232
|
////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Typhoon Framework Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
public class CityDaoUserDefaultsImpl : NSObject, CityDao {
var defaults : NSUserDefaults
let citiesListKey = "pfWeather.cities"
let currentCityKey = "pfWeather.currentCityKey"
let defaultCities = [
"Manila",
"Madrid",
"San Francisco",
"Phnom Penh",
"Omsk"
]
init(defaults : NSUserDefaults) {
self.defaults = defaults
}
public func listAllCities() -> [AnyObject]! {
var cities : NSArray? = self.defaults.arrayForKey(self.citiesListKey)
if (cities == nil) {
cities = defaultCities;
self.defaults.setObject(cities, forKey:self.citiesListKey)
}
return sorted(cities as! [String]) {
return $0 < $1
}
}
public func saveCity(name: String!) {
let trimmedName = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
var savedCities : Array? = self.defaults.arrayForKey(self.citiesListKey)
if (savedCities == nil) {
savedCities = defaultCities
}
var cities = NSMutableArray(array: savedCities!)
var canAddCity = true
for city in cities {
if (city.lowercaseString == trimmedName.lowercaseString) {
canAddCity = false
}
}
if (canAddCity) {
cities.addObject(trimmedName)
self.defaults.setObject(cities, forKey: self.citiesListKey)
}
}
public func deleteCity(name: String!) {
let trimmedName = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
var cities = NSMutableArray(array: self.defaults.arrayForKey(self.citiesListKey)!)
var cityToRemove : String?
for city in cities {
if (city.lowercaseString == trimmedName.lowercaseString) {
cityToRemove = city as? String
}
}
if (cityToRemove != nil)
{
cities.removeObject(cityToRemove!)
}
self.defaults.setObject(cities, forKey: self.citiesListKey)
}
public func saveCurrentlySelectedCity(cityName: String!) {
let trimmed = cityName.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if (!trimmed.isEmpty) {
self.defaults.setObject(trimmed, forKey: self.currentCityKey)
}
}
public func clearCurrentlySelectedCity() {
self.defaults.setObject(nil, forKey: self.currentCityKey)
}
public func loadSelectedCity() -> String? {
return self.defaults.objectForKey(self.currentCityKey) as? String
}
}
|
apache-2.0
|
c5e8e3d7ce2ea1539ce3dcfaa1bc1ba9
| 29.490566 | 113 | 0.580446 | 5.229773 | false | false | false | false |
anto0522/AdMate
|
Pods/p2.OAuth2/Sources/OSX/OAuth2WebViewController.swift
|
1
|
9297
|
//
// OAuth2WebViewController.swift
// OAuth2
//
// Created by Guilherme Rambo on 18/01/16.
// Copyright 2014 Pascal Pfiffner
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
import WebKit
/**
A view controller that allows you to display the login/authorization screen.
*/
@available(OSX 10.10, *)
public class OAuth2WebViewController: NSViewController, WKNavigationDelegate, NSWindowDelegate {
init() {
super.init(nibName: nil, bundle: nil)!
}
/// Handle to the OAuth2 instance in play, only used for debug logging at this time.
var oauth: OAuth2?
/// Configure the view to be shown as sheet, false by default; must be present before the view gets loaded.
var willBecomeSheet = false
/// The URL to load on first show.
public var startURL: NSURL? {
didSet(oldURL) {
if nil != startURL && nil == oldURL && viewLoaded {
loadURL(startURL!)
}
}
}
/// The URL string to intercept and respond to.
var interceptURLString: String? {
didSet(oldURL) {
if nil != interceptURLString {
if let url = NSURL(string: interceptURLString!) {
interceptComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: true)
}
else {
oauth?.logIfVerbose("Failed to parse URL \(interceptURLString), discarding")
interceptURLString = nil
}
}
else {
interceptComponents = nil
}
}
}
var interceptComponents: NSURLComponents?
/// Closure called when the web view gets asked to load the redirect URL, specified in `interceptURLString`. Return a Bool indicating
/// that you've intercepted the URL.
var onIntercept: ((url: NSURL) -> Bool)?
/// Called when the web view is about to be dismissed manually.
var onWillCancel: (Void -> Void)?
/// Our web view; implicitly unwrapped so do not attempt to use it unless isViewLoaded() returns true.
var webView: WKWebView!
private var progressIndicator: NSProgressIndicator!
private var loadingView: NSView {
let view = NSView(frame: self.view.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
progressIndicator = NSProgressIndicator(frame: NSZeroRect)
progressIndicator.style = .SpinningStyle
progressIndicator.displayedWhenStopped = false
progressIndicator.sizeToFit()
progressIndicator.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(progressIndicator)
view.addConstraint(NSLayoutConstraint(item: progressIndicator, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: progressIndicator, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
return view
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - View Handling
internal static let WebViewWindowWidth = CGFloat(600.0)
internal static let WebViewWindowHeight = CGFloat(500.0)
override public func loadView() {
view = NSView(frame: NSMakeRect(0, 0, OAuth2WebViewController.WebViewWindowWidth, OAuth2WebViewController.WebViewWindowHeight))
view.translatesAutoresizingMaskIntoConstraints = false
webView = WKWebView(frame: view.bounds, configuration: WKWebViewConfiguration())
webView.translatesAutoresizingMaskIntoConstraints = false
webView.navigationDelegate = self
webView.alphaValue = 0.0
view.addSubview(webView)
view.addConstraint(NSLayoutConstraint(item: webView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: webView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: webView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: webView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1.0, constant: 0.0))
// add a dismiss button
if willBecomeSheet {
let button = NSButton(frame: NSRect(x: 0, y: 0, width: 120, height: 20))
button.translatesAutoresizingMaskIntoConstraints = false
button.title = "Cancel"
button.target = self
button.action = "cancel:"
view.addSubview(button)
view.addConstraint(NSLayoutConstraint(item: button, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1.0, constant: -10.0))
view.addConstraint(NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1.0, constant: -10.0))
}
showLoadingIndicator()
}
override public func viewWillAppear() {
super.viewWillAppear()
if !webView.canGoBack {
if nil != startURL {
loadURL(startURL!)
}
else {
webView.loadHTMLString("There is no `startURL`", baseURL: nil)
}
}
}
public override func viewDidAppear() {
super.viewDidAppear()
view.window?.delegate = self
}
func showLoadingIndicator() {
let loadingContainerView = loadingView
view.addSubview(loadingContainerView)
view.addConstraint(NSLayoutConstraint(item: loadingContainerView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: loadingContainerView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: loadingContainerView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: loadingContainerView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1.0, constant: 0.0))
progressIndicator.startAnimation(nil)
}
func hideLoadingIndicator() {
guard progressIndicator != nil else { return }
progressIndicator.stopAnimation(nil)
progressIndicator.superview?.removeFromSuperview()
}
func showErrorMessage(message: String, animated: Bool) {
hideLoadingIndicator()
webView.animator().alphaValue = 1.0
webView.loadHTMLString("<p style=\"text-align:center;font:'helvetica neue', sans-serif;color:red\">\(message)</p>", baseURL: nil)
}
// MARK: - Actions
public func loadURL(url: NSURL) {
webView.loadRequest(NSURLRequest(URL: url))
}
func goBack(sender: AnyObject?) {
webView.goBack()
}
func cancel(sender: AnyObject?) {
webView.stopLoading()
onWillCancel?()
}
// MARK: - Web View Delegate
public func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
let request = navigationAction.request
if nil == onIntercept {
decisionHandler(.Allow)
return
}
// we compare the scheme and host first, then check the path (if there is any). Not sure if a simple string comparison
// would work as there may be URL parameters attached
if let url = request.URL where url.scheme == interceptComponents?.scheme && url.host == interceptComponents?.host {
let haveComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: true)
if let hp = haveComponents?.path, ip = interceptComponents?.path where hp == ip || ("/" == hp + ip) {
if onIntercept!(url: url) {
decisionHandler(.Cancel)
}
else {
decisionHandler(.Allow)
}
}
}
decisionHandler(.Allow)
}
public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
if let scheme = interceptComponents?.scheme where "urn" == scheme {
if let path = interceptComponents?.path where path.hasPrefix("ietf:wg:oauth:2.0:oob") {
if let title = webView.title where title.hasPrefix("Success ") {
oauth?.logIfVerbose("Creating redirect URL from document.title")
let qry = title.stringByReplacingOccurrencesOfString("Success ", withString: "")
if let url = NSURL(string: "http://localhost/?\(qry)") {
onIntercept?(url: url)
return
}
else {
oauth?.logIfVerbose("Failed to create a URL with query parts \"\(qry)\"")
}
}
}
}
webView.animator().alphaValue = 1.0
hideLoadingIndicator()
}
public func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
if NSURLErrorDomain == error.domain && NSURLErrorCancelled == error.code {
return
}
// do we still need to intercept "WebKitErrorDomain" error 102?
showErrorMessage(error.localizedDescription, animated: true)
}
// MARK: - Window Delegate
public func windowShouldClose(sender: AnyObject) -> Bool {
onWillCancel?()
return false
}
}
|
mit
|
8b392a6dad48bd813d0021c9caf26143
| 34.34981 | 173 | 0.726578 | 4.068709 | false | false | false | false |
icetime17/CSSwiftExtension
|
Sources/UIKit+CSExtension/UIImage+CSExtension.swift
|
1
|
16285
|
//
// UIImage+CSExtension.swift
// CSSwiftExtension
//
// Created by Chris Hu on 16/12/25.
// Copyright © 2016年 com.icetime17. All rights reserved.
//
import UIKit
import ImageIO
// MARK: - init
public extension UIImage {
/**
UIImage init from an URL string. Synchronsize and NOT recommended.
- parameter urlString: URL string
- returns: UIImage
*/
convenience init(urlString: String) {
let imageData = try! Data(contentsOf: URL(string: urlString)!)
self.init(data: imageData)!
}
/**
UIImage init from pure color
- parameter pureColor: pure color
- parameter targetSize:targetSize
- returns: UIImage
*/
convenience init(pureColor: UIColor, targetSize: CGSize) {
UIGraphicsBeginImageContextWithOptions(targetSize, false, 1)
defer {
UIGraphicsEndImageContext()
}
pureColor.setFill()
UIRectFill(CGRect(origin: CGPoint.zero, size: targetSize))
let image = UIGraphicsGetImageFromCurrentImageContext()!
self.init(cgImage: image.cgImage!)
}
}
public extension CSSwift where Base: UIImage {
// center
var center: CGPoint {
return CGPoint(x: base.size.width / 2, y: base.size.height / 2)
}
}
// MARK: - save
public extension CSSwift where Base: UIImage {
/**
Save UIImage to file
- parameter filePath: file path
- parameter compressionFactor: compression factor, only useful for JPEG format image.
Default to be 1.0.
- returns: true or false
*/
func saveImageToFile(filePath: String, compressionFactor: CGFloat = 1.0) -> Bool {
if FileManager.default.fileExists(atPath: filePath) {
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {
CS_Print("This file (\(filePath)) exists already, and NSFileManager failed to remove it.")
return false
}
}
var imageData: Data?
if filePath.hasSuffix(".jpeg") {
imageData = base.jpegData(compressionQuality: compressionFactor)
} else {
imageData = base.pngData()
}
if FileManager.default.createFile(atPath: filePath, contents: imageData, attributes: nil) {
let url = URL(fileURLWithPath: filePath)
do {
try imageData?.write(to: url)
return true
} catch {
CS_Print("FileManager failed to write imageData to filepath: \(filePath).")
}
} else {
CS_Print("FileManager failed to create file at path: \(filePath).")
}
return false
}
}
// MARK: - utility
public extension CSSwift where Base: UIImage {
/**
Crop UIImage
- returns: UIImage cropped
*/
func imageCropped(bounds: CGRect) -> UIImage {
let imageRef = base.cgImage!.cropping(to: bounds)
let imageCropped = UIImage(cgImage: imageRef!)
return imageCropped
}
/**
Crop UIImage to fit target size
- returns: UIImage cropped
*/
func imageCroppedToFit(targetSize: CGSize) -> UIImage {
var widthImage: CGFloat = 0.0
var heightImage: CGFloat = 0.0
var rectRatioed: CGRect!
if base.size.height / base.size.width < targetSize.height / targetSize.width {
// 图片的height过小, 剪裁其width, 而height不变
heightImage = base.size.height
widthImage = heightImage * targetSize.width / targetSize.height
rectRatioed = CGRect(x: (base.size.width - widthImage) / 2, y: 0, width: widthImage, height: heightImage)
} else {
// 图片的width过小, 剪裁其height, 而width不变
widthImage = base.size.width
heightImage = widthImage * targetSize.height / targetSize.width
rectRatioed = CGRect(x: 0, y: (base.size.height - heightImage) / 2, width: widthImage, height: heightImage)
}
return imageCropped(bounds: rectRatioed)
}
/**
Mirror UIImage
- returns: UIImage mirrored
*/
var imageMirrored: UIImage {
let width = base.size.width
let height = base.size.height
UIGraphicsBeginImageContext(base.size)
defer {
UIGraphicsEndImageContext()
}
let context = UIGraphicsGetCurrentContext()
context?.interpolationQuality = .high
context?.translateBy(x: width, y: height)
context?.concatenate(CGAffineTransform(scaleX: -1.0, y: -1.0))
context?.draw(base.cgImage!, in: CGRect(x: 0, y: 0, width: width, height: height))
let imageRef = context!.makeImage()
let resultImage = UIImage(cgImage: imageRef!)
return resultImage
}
/**
Rotate UIImage to specified degress
- parameter degress: degress to rotate
- returns: UIImage rotated
*/
func imageRotatedByDegrees(degrees: CGFloat) -> UIImage {
let radians = CGFloat(Double.pi) * degrees / 180.0
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(x: 0, y: 0, width: base.size.width, height: base.size.height))
rotatedViewBox.transform = CGAffineTransform(rotationAngle: radians)
let rotatedSize = rotatedViewBox.frame.size
// Create bitmap context.
UIGraphicsBeginImageContext(rotatedSize)
defer {
UIGraphicsEndImageContext()
}
let context = UIGraphicsGetCurrentContext()
// Move the origin to the middle of the image so we will rotate and.
context?.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0)
// Rotate the image context
context?.rotate(by: radians)
// Now, draw the rotated/scaled image into the context
context?.scaleBy(x: 1.0, y: -1.0)
context?.draw(base.cgImage!, in: CGRect(x: -base.size.width / 2.0, y: -base.size.height / 2.0, width: base.size.width, height: base.size.height))
let imageRotated = UIGraphicsGetImageFromCurrentImageContext()
return imageRotated!
}
/**
Scale UIImage to specified size.
- parameter targetSize: targetSize
- parameter withOriginalRatio: whether the result UIImage should keep the original ratio
Default to be true
- returns: UIImage scaled
*/
func imageScaledToSize(targetSize: CGSize, withOriginalRatio: Bool = true) -> UIImage {
var sizeFinal = targetSize
if withOriginalRatio {
let ratioOriginal = base.size.width / base.size.height
let ratioTemp = targetSize.width / targetSize.height
if ratioOriginal < ratioTemp {
sizeFinal.width = targetSize.height * ratioOriginal
} else if ratioOriginal > ratioTemp {
sizeFinal.height = targetSize.width / ratioOriginal
}
}
UIGraphicsBeginImageContext(sizeFinal)
defer {
UIGraphicsEndImageContext()
}
base.draw(in: CGRect(x: 0, y: 0, width: sizeFinal.width, height: sizeFinal.height))
let imageScaled: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
return imageScaled
}
/**
UIImage with corner radius without Off-Screen Rendering.
Much better than setting layer.cornerRadius and layer.masksToBounds.
- parameter cornerRadius: corner radius
- parameter backgroundColor: backgroundColor, default clear color.
- returns: UIImage
*/
func imageWithCornerRadius(cornerRadius: CGFloat, backgroundColor: UIColor = UIColor.clear) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: base.size.width, height: base.size.height)
UIGraphicsBeginImageContext(base.size)
defer {
UIGraphicsEndImageContext()
}
// Add a clip before drawing anything, in the shape of an rounded rect
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
backgroundColor.setFill()
UIRectFill(rect)
// Draw the image
base.draw(in: rect)
let imageWithCornerRadius = UIGraphicsGetImageFromCurrentImageContext()
return imageWithCornerRadius!
}
var imageWithNormalOrientation: UIImage {
if base.imageOrientation == UIImage.Orientation.up {
return base
}
UIGraphicsBeginImageContextWithOptions(base.size, false, base.scale)
defer {
UIGraphicsEndImageContext()
}
base.draw(in: CGRect(origin: CGPoint.zero, size: base.size))
let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
return normalizedImage!
}
var grayScale: UIImage {
// Create image rectangle with current image width/height
let rect = CGRect(x: 0, y: 0, width: base.size.width, height: base.size.height);
// Grayscale color space
let colorSpace = CGColorSpaceCreateDeviceGray()
// Create bitmap content with current image size and grayscale colorspace
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
// Draw image into current context, with specified rectangle
// using previously defined context (with grayscale colorspace)
guard let context = CGContext(data: nil, width: Int(base.size.width), height: Int(base.size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { return base }
context.setFillColor(UIColor.clear.cgColor)
context.fill(rect)
context.draw(base.cgImage!, in: rect)
// Create bitmap image info from pixel data in current context
guard let imageRef = context.makeImage() else { return base }
// Create a new UIImage object
let newImage = UIImage(cgImage: imageRef)
// Release colorspace, context and bitmap information
// Return the new grayscale image
return newImage;
}
}
// MARK: - Watermark
public extension CSSwift where Base: UIImage {
// Add image watermark via rect
func imageWithWatermark(img: UIImage, rect: CGRect) -> UIImage {
p_setUpImageContext()
img.draw(in: rect)
let r = p_imageFromContext()
p_tearDownImageContext()
return r
}
// Add image watermark via center and size
func imageWithWatermark(img: UIImage,
center: CGPoint,
size: CGSize) -> UIImage {
let rect = CGRect(x: center.x - size.width / 2,
y: center.y - size.height / 2,
width: size.width,
height: size.height)
return imageWithWatermark(img: img, rect: rect)
}
// Text
func imageWithWatermark(text: String,
point: CGPoint,
font: UIFont,
color: UIColor = .white) -> UIImage {
let paraStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paraStyle.alignment = .center
let attributes = [
.font: font,
.paragraphStyle: paraStyle,
.foregroundColor: color
] as [NSAttributedString.Key: Any]
return imageWithWatermark(text: text, point: point, attributes: attributes)
}
// Text with custom style
/**
let style = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
style.alignment = .center
let attributes = [
NSFontAttributeName: font,
NSParagraphStyleAttributeName: style,
NSForegroundColorAttributeName: color,
]
imageWithWatermark(text: text, point: point, attributes: attributes)
*/
func imageWithWatermark(text: String,
point: CGPoint,
attributes: [NSAttributedString.Key: Any]?) -> UIImage {
p_setUpImageContext()
(text as NSString).draw(at: point, withAttributes: attributes)
let r = p_imageFromContext()
p_tearDownImageContext()
return r
}
private func p_setUpImageContext() {
let rectCanvas = CGRect(origin: CGPoint.zero, size: base.size)
UIGraphicsBeginImageContextWithOptions(rectCanvas.size, false, 0)
base.draw(in: rectCanvas)
}
private func p_tearDownImageContext() {
UIGraphicsEndImageContext()
}
private func p_imageFromContext() -> UIImage {
guard let retImage = UIGraphicsGetImageFromCurrentImageContext() else {
return base
}
return retImage
}
}
// MARK: - 微信分享缩略图
public extension CSSwift where Base: UIImage {
var wechatShareThumbnail: UIImage {
var scale: CGFloat = 0
var isNeedCut = false
var imageSize = CGSize.zero
let ratio = base.size.width / base.size.height
if ratio > 3 {
isNeedCut = true
if base.size.height > 100 {
scale = 100 / base.size.height
} else {
scale = 1
}
imageSize = CGSize(width: CGFloat(base.size.height * scale * 3), height: CGFloat(base.size.height * scale))
} else if ratio < 0.333 {
isNeedCut = true
if base.size.width > 100 {
scale = 100 / base.size.width
} else {
scale = 1
}
imageSize = CGSize(width: base.size.width * scale, height: base.size.width * scale * 3)
} else {
isNeedCut = false
if ratio > 1 {
scale = 280 / base.size.width
} else {
scale = 280 / base.size.height
}
if scale > 1 {
scale = 1
}
imageSize = CGSize(width: base.size.width * scale, height: base.size.height * scale)
}
let image = p_thumbnailWithSize(targetSize: imageSize, isNeedCut: isNeedCut)
let imageData = image.jpegData(compressionQuality: 0.4)
return UIImage(data: imageData!)!
}
private func p_thumbnailWithSize(targetSize: CGSize, isNeedCut: Bool) -> UIImage {
var imageSize = base.size
let scaleWidth = targetSize.width / imageSize.width
let scaleHeight = targetSize.height / imageSize.height
let scale = max(scaleWidth, scaleHeight)
imageSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
UIGraphicsBeginImageContext(imageSize)
defer {
UIGraphicsEndImageContext()
}
let context = UIGraphicsGetCurrentContext()
context?.interpolationQuality = .medium
UIGraphicsPushContext(context!)
base.draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
UIGraphicsPopContext()
let tmpImage = UIGraphicsGetImageFromCurrentImageContext()
if targetSize.width == 0 || targetSize.height == 0 || !isNeedCut {
return tmpImage!
}
let thumbRect = CGRect(x: (imageSize.width - targetSize.width) / 2, y: (imageSize.height - targetSize.height) / 2, width: targetSize.width, height: targetSize.height)
let temp_img = tmpImage?.cgImage?.cropping(to: thumbRect)
return UIImage(cgImage: temp_img!)
}
}
|
mit
|
7e551684a7dc5cf8c740aa4b766a7738
| 32.72973 | 218 | 0.5866 | 5.087488 | false | false | false | false |
TruckMuncher/TruckMuncher-iOS
|
TruckMuncher/api/RMenuItem.swift
|
1
|
1576
|
//
// RMenuItem.swift
// TruckMuncher
//
// Created by Josh Ault on 10/27/14.
// Copyright (c) 2014 TruckMuncher. All rights reserved.
//
import UIKit
import Realm
class RMenuItem: RLMObject {
dynamic var id = ""
dynamic var name = ""
dynamic var price = 0.0
dynamic var notes = ""
dynamic var tags = RLMArray(objectClassName: RString.className())
dynamic var orderInCategory = 0
dynamic var isAvailable = true
override init() {
super.init()
}
class func initFromSmallProto(menuItem: [String: AnyObject]) -> RMenuItem {
let rmenuitem = RMenuItem()
rmenuitem.id = menuItem["menuItemId"] as! String
rmenuitem.isAvailable = menuItem["isAvailable"] as? Bool ?? false
return rmenuitem
}
class func initFromFullProto(menuItem: [String: AnyObject]) -> RMenuItem {
let rmenuitem = RMenuItem()
rmenuitem.id = menuItem["id"] as! String
rmenuitem.name = menuItem["name"] as? String ?? ""
rmenuitem.price = menuItem["price"] as? Double ?? 0.0
rmenuitem.notes = menuItem["notes"] as? String ?? ""
if let tags = menuItem["tags"] as? [String] {
for tag in tags {
rmenuitem.tags.addObject(RString.initFromString(tag))
}
}
rmenuitem.orderInCategory = menuItem["orderInCategory"] as? Int ?? 0
rmenuitem.isAvailable = menuItem["isAvailable"] as? Bool ?? false
return rmenuitem
}
override class func primaryKey() -> String! {
return "id"
}
}
|
gpl-2.0
|
179b3eb4fbdacd5d351c0ba83782ba4d
| 29.901961 | 79 | 0.611041 | 4.061856 | false | false | false | false |
Raizlabs/SketchyCode
|
SketchyCode/CLI/Utils/Command.swift
|
1
|
597
|
//
// SwiftGenKit
// Copyright (c) 2017 SwiftGen
// MIT License
//
import Foundation
struct Command {
private static let Environment = "/usr/bin/env"
private var arguments: [String]
init(_ executable: String, arguments: String...) {
self.arguments = [executable]
self.arguments += arguments
}
func execute() -> Data {
let task = Process()
task.launchPath = Command.Environment
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
return data
}
}
|
mit
|
aff80ce2c9f6d1b7253117fe9f3d087c
| 18.258065 | 62 | 0.668342 | 4.326087 | false | false | false | false |
fawadsuhail/TwilioTest
|
TwilioTest/ViewController.swift
|
1
|
1557
|
//
// ViewController.swift
// TwilioTest
//
// Created by fawad on 22/01/2017.
// Copyright © 2017 fawad. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = "https://api.twilio.com/2010-04-01/Accounts/\(K.Twilio.SID)/Messages.json"
// credentials
let credentialData = "\(K.Twilio.SID):\(K.Twilio.authToken)".utf8
let base64Credentials = Data(credentialData).base64EncodedString()
let headers = ["Authorization": "Basic \(base64Credentials)"]
// params
let params: [String: String] = ["From": "FROM_NUMBER",
"To": "TO_NUMBER",
"Body": "Hello from Twilio"]
Alamofire.request(url, method: .post, parameters: params,
encoding: URLEncoding.default, headers: headers)
.authenticate(user: K.Twilio.SID,
password: K.Twilio.authToken).responseJSON { response in
switch response.result {
case .success:
print("success \(response)")
case .failure(let error):
print(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
9ea3246f8bf13957fa67ffb2ed053361
| 28.923077 | 88 | 0.561697 | 4.686747 | false | false | false | false |
fjbelchi/CodeTest-BoardingPass-Swift
|
BoardingCards/Models/AnyBoardingPass.swift
|
1
|
1198
|
//
// AnyBoardingPass.swift
//
// Copyright © 2015 Francisco J. Belchi. All rights reserved.
import Foundation
public struct AnyBoardingPass : BoardingPassType {
public let boardingPass: BoardingPassType
public var boardingId: String {
return self.boardingPass.boardingId
}
public var cityFrom: City {
return self.boardingPass.cityFrom
}
public var cityTo: City {
return self.boardingPass.cityTo
}
public init(_ boardingPass: BoardingPassType) {
self.boardingPass = boardingPass
}
}
// MARK: Hashable
extension AnyBoardingPass: Hashable {
public var hashValue: Int {
return self.boardingPass.boardingId.hash;
}
}
// MARK: Equatable
extension AnyBoardingPass: Equatable {}
public func == (lhs: AnyBoardingPass, rhs: AnyBoardingPass) -> Bool {
return lhs.boardingPass.isEqualTo(rhs.boardingPass)
}
// MARK: CustomStringConvertible
extension AnyBoardingPass: CustomStringConvertible {
public var description: String {
return "AnyBoardingPass id=\(self.boardingPass.boardingId), from=\(self.boardingPass.cityFrom.name), to=\(self.boardingPass.cityTo.name)"
}
}
|
mit
|
a81c5df69309be8c3c0d670f05f67a93
| 22.470588 | 145 | 0.696742 | 4.368613 | false | false | false | false |
TintPoint/Overlay
|
Sources/CustomizableProtocols/CellCustomizable.swift
|
1
|
6979
|
//
// CellCustomizable.swift
// Overlay
//
// Created by Justin Jia on 6/24/17.
// Copyright © 2017 TintPoint. MIT license.
//
import UIKit
/// A protocol that describes a view that its cells can be customized.
public protocol CellCustomizable {
/// The type that represents cells of the view.
associatedtype Cell
/// The metatype that represents the class of cells of the view.
associatedtype CellClass
/// Registers a `CellClass` for use in creating new cells.
/// - Parameter cellClass: A `CellClass` that represents the class of a cell.
func register(_ cellClass: CellClass)
}
/// A protocol that describes a view that its header footer views can be customized.
public protocol HeaderFooterViewCustomizable {
/// The type that represents header footer views of the view.
associatedtype HeaderFooterView
/// The metatype that represents the class of header footer views of the view.
associatedtype HeaderFooterViewClass
/// Registers a `HeaderFooterViewClass` for use in creating new header footer views.
/// - Parameter headerFooterViewClass: A `HeaderFooterViewClass` that represents the class of a header footer view.
func register(_ headerFooterViewClass: HeaderFooterViewClass)
}
/// A protocol that describes a view that its reusable views can be customized.
public protocol ReusableViewCustomizable {
/// The type that represents reusable views of the view.
associatedtype ReusableView
/// The metatype that represents the class of reusable views of the view.
associatedtype ReusableViewClass
/// Registers a `ReusableViewClass` for use in creating new reusable views.
/// - Parameter ReusableViewClass: A `ReusableViewClass` that represents the class of a reusable view.
func register(_ reusableViewClass: ReusableViewClass)
}
extension UICollectionView: CellCustomizable {
public typealias Cell = UICollectionViewCell & CustomCell
public typealias CellClass = Cell.Type
public func register(_ cellClass: CellClass) {
if let contentNib = cellClass.contentNib {
register(contentNib, forCellWithReuseIdentifier: cellClass.suggestedIdentifier)
} else {
register(cellClass, forCellWithReuseIdentifier: cellClass.suggestedIdentifier)
}
}
}
extension UICollectionView: ReusableViewCustomizable {
public typealias ReusableView = UICollectionReusableView & CustomReusableView
public typealias ReusableViewClass = ReusableView.Type
public func register(_ reusableViewClass: ReusableViewClass) {
if let contentNib = reusableViewClass.contentNib {
register(contentNib, forSupplementaryViewOfKind: reusableViewClass.suggestedKind, withReuseIdentifier: reusableViewClass.suggestedIdentifier)
} else {
register(reusableViewClass, forSupplementaryViewOfKind: reusableViewClass.suggestedKind, withReuseIdentifier: reusableViewClass.suggestedIdentifier)
}
}
}
public extension UICollectionView {
/// Returns a reusable `Cell` located by its class.
/// Calls `dequeueReusableCell(withReuseIdentifier:for:)` method.
/// - Parameter cellClass: A `Cell.Type` that represents the class of a cell.
/// - Parameter indexPath: An `IndexPath` that represents the location of a cell.
/// - Returns: A reusable `Cell` located by its class.
func dequeueReusableCell<T: Cell>(_ cellClass: T.Type, for indexPath: IndexPath) -> T {
return dequeueReusableCell(withReuseIdentifier: cellClass.suggestedIdentifier, for: indexPath) as! T
}
/// Returns a supplementary `ReusableView` located by its class.
/// Calls `dequeueReusableSupplementaryView(ofKind:withReuseIdentifier:for:)` method.
/// - Parameter reusableViewClass: A `ReusableView.Type` that represents the class of a reusable view.
/// - Parameter indexPath: An `IndexPath` that represents the location of a reusable view.
/// - Returns: A supplementary `ReusableView` located by its class.
func dequeueReusableSupplementaryView<T: ReusableView>(_ reusableViewClass: T.Type, for indexPath: IndexPath) -> T {
return dequeueReusableSupplementaryView(ofKind: reusableViewClass.suggestedKind, withReuseIdentifier: reusableViewClass.suggestedIdentifier, for: indexPath) as! T
}
}
extension UITableView: CellCustomizable {
public typealias Cell = UITableViewCell & CustomCell
public typealias CellClass = Cell.Type
public func register(_ cellClass: CellClass) {
if let contentNib = cellClass.contentNib {
register(contentNib, forCellReuseIdentifier: cellClass.suggestedIdentifier)
} else {
register(cellClass, forCellReuseIdentifier: cellClass.suggestedIdentifier)
}
}
}
extension UITableView: HeaderFooterViewCustomizable {
public typealias HeaderFooterView = UITableViewHeaderFooterView & CustomHeaderFooterView
public typealias HeaderFooterViewClass = HeaderFooterView.Type
public func register(_ headerFooterViewClass: HeaderFooterViewClass) {
if let contentNib = headerFooterViewClass.contentNib {
register(contentNib, forHeaderFooterViewReuseIdentifier: headerFooterViewClass.suggestedIdentifier)
} else {
register(headerFooterViewClass, forHeaderFooterViewReuseIdentifier: headerFooterViewClass.suggestedIdentifier)
}
}
}
public extension UITableView {
/// Returns a reusable `Cell` located by its class and adds it to the table.
/// Calls `dequeueReusableCell(withIdentifier:for:)` method.
/// - Parameter cellClass: A `Cell.Type` that represents the class of a cell.
/// - Parameter indexPath: An `IndexPath` that represents the location of a cell.
/// - Returns: A reusable `Cell` located by its class.
func dequeueReusableCell<T: Cell>(_ cellClass: T.Type, for indexPath: IndexPath) -> T {
return dequeueReusableCell(withIdentifier: cellClass.suggestedIdentifier, for: indexPath) as! T
}
/// Returns a reusable `Cell` located by its class.
/// Calls `dequeueReusableCell(withIdentifier:)` method.
/// - Parameter cellClass: A `Cell.Type` that represents the class of a cell.
/// - Returns: A reusable `Cell` located by its class.
func dequeueReusableCell<T: Cell>(_ cellClass: T.Type) -> T {
return dequeueReusableCell(withIdentifier: cellClass.suggestedIdentifier) as! T
}
/// Returns a reusable `HeaderFooterView` located by its class.
/// Calls `dequeueReusableHeaderFooterView(withIdentifier:)` method.
/// - Parameter headerFooterViewClass: A `HeaderFooterView.Type` that represents the class of a header footer view.
/// Returns: A reusable `HeaderFooterView` located by its class.
func dequeueReusableHeaderFooterView<T: HeaderFooterView>(_ headerFooterViewClass: T.Type) -> T {
return dequeueReusableHeaderFooterView(withIdentifier: headerFooterViewClass.suggestedIdentifier) as! T
}
}
|
mit
|
553a1bf6444b1504d4991ed8d333f646
| 45.211921 | 170 | 0.740613 | 5.322654 | false | false | false | false |
MR-Zong/ZGResource
|
Project/FamilyEducationApp-master/家教/UUChat/ChatViewController.swift
|
1
|
3520
|
//
// ViewController.swift
// UUChatTableViewSwift
//
// Created by XcodeYang on 8/13/15.
// Copyright © 2015 XcodeYang. All rights reserved.
//
import UIKit
class ChatViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var chatTableView: UITableView!
@IBOutlet weak var inputBackView: UIView!
@IBOutlet weak var inputViewBottomContraint: NSLayoutConstraint!
var dataArray: NSMutableArray!
override func viewDidLoad() {
super.viewDidLoad()
let navBar = self.navigationController?.navigationBar
navBar?.barTintColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1)
navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.dataArray = NSMutableArray(array: [])
for var i=0; i<20; i++ {
self.dataArray.addObject(random()%60+5)
}
chatTableView?.estimatedRowHeight = 50;
}
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
self.chatTableView.reloadData()
}
// private method
@objc func batteryLevelChanged(notification: NSNotification) {
let dict = NSDictionary(dictionary: notification.userInfo!)
let keyboardValue = dict.objectForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let bootomDistance = UIScreen.mainScreen().bounds.size.height - keyboardValue.CGRectValue().origin.y
let duration = Double(dict.objectForKey(UIKeyboardAnimationDurationUserInfoKey) as! NSNumber);
UIView.animateWithDuration(duration, animations: {
self.inputViewBottomContraint.constant = bootomDistance
self.view.layoutIfNeeded()
}, completion: {
(value: Bool) in
let indexPath = NSIndexPath(forRow: self.dataArray.count-1, inSection: 0)
self.chatTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true);
})
}
// tableview delegate & dataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArray.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let num: NSInteger! = self.dataArray.objectAtIndex(indexPath.row) as! NSInteger
if num > 50{
let cell:UUChatRightMessageCell = tableView.dequeueReusableCellWithIdentifier("UUChatRightMessageCell") as! UUChatRightMessageCell
cell.configUIWithModel(num);
return cell;
}
else {
let cell:UUChatLeftMessageCell = tableView.dequeueReusableCellWithIdentifier("UUChatLeftMessageCell") as! UUChatLeftMessageCell
cell.configUIWithModel(num);
return cell;
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.view.endEditing(true)
}
}
|
gpl-2.0
|
b98f9055f8255627f07eaf04a257dfcf
| 36.43617 | 154 | 0.681159 | 5.498438 | false | false | false | false |
frootloops/swift
|
test/SILGen/extensions_objc.swift
|
3
|
1265
|
// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
//
// REQUIRES: objc_interop
import Foundation
class Foo {}
extension Foo {
dynamic func kay() {}
dynamic var cox: Int { return 0 }
}
// CHECK-LABEL: sil hidden @_T015extensions_objc19extensionReferencesyAA3FooCF
// CHECK: bb0([[ARG:%.*]] : @owned $Foo):
func extensionReferences(_ x: Foo) {
// dynamic extension methods are still dynamically dispatched.
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: objc_method [[BORROWED_ARG]] : $Foo, #Foo.kay!1.foreign
x.kay()
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: objc_method [[BORROWED_ARG]] : $Foo, #Foo.cox!getter.1.foreign
_ = x.cox
}
func extensionMethodCurrying(_ x: Foo) {
_ = x.kay
}
// CHECK-LABEL: sil shared [thunk] @_T015extensions_objc3FooC3kayyyFTc
// CHECK: function_ref @_T015extensions_objc3FooC3kayyyFTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T015extensions_objc3FooC3kayyyFTD
// CHECK: bb0([[SELF:%.*]] : @guaranteed $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: objc_method [[SELF_COPY]] : $Foo, #Foo.kay!1.foreign
|
apache-2.0
|
467f5fe7aecd1acb157446f247471a0f
| 33.189189 | 134 | 0.650593 | 3.170426 | false | false | false | false |
IGRSoft/IGRPhotoTweaks
|
IGRPhotoTweaks/PhotoTweakView/ScrollViews/IGRPhotoContentView.swift
|
1
|
765
|
//
// IGRPhotoContentView.swift
// IGRPhotoTweaks
//
// Created by Vitalii Parovishnyk on 2/6/17.
// Copyright © 2017 IGR Software. All rights reserved.
//
import UIKit
public class IGRPhotoContentView: UIView {
lazy fileprivate var imageView: UIImageView! = {
let imageView = UIImageView(frame: self.bounds)
self.addSubview(imageView)
return imageView
}()
public var image: UIImage! {
didSet {
self.imageView.frame = self.bounds
self.imageView.image = self.image
self.imageView.isUserInteractionEnabled = true
}
}
override public func layoutSubviews() {
super.layoutSubviews()
self.imageView?.frame = self.bounds
}
}
|
mit
|
3b3135df121600a93efe43152610128c
| 22.875 | 58 | 0.621728 | 4.547619 | false | false | false | false |
kingsic/SGSegmentedControl
|
SGPagingView/Example/FixedOneVC.swift
|
2
|
2441
|
//
// FixedOneVC.swift
// SGPagingView
//
// Created by kingsic on 2020/12/29.
// Copyright © 2020 kingsic. All rights reserved.
//
import UIKit
class FixedOneVC: UIViewController, SGPagingTitleViewDelegate, SGPagingContentViewDelegate {
deinit {
print("FixedOneVC - deinit")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .black
addPagingView()
}
var pagingTitleView: SGPagingTitleView!
var pagingContentView: SGPagingContentScrollView!
func addPagingView() {
let configure = SGPagingTitleViewConfigure()
configure.equivalence = false
configure.additionalWidth = 37
configure.selectedFont = .systemFont(ofSize: 17)
let frame = CGRect.init(x: 0, y: UIScreen.navBarHeight, width: UIScreen
.width, height: 44)
let titles = ["滚动", "内容视图", "最左或最右", "回弹"]
let pagingTitle = SGPagingTitleView(frame: frame, titles: titles, configure: configure)
pagingTitle.delegate = self
view.addSubview(pagingTitle)
pagingTitleView = pagingTitle
let vc1 = UIViewController()
vc1.view.backgroundColor = .orange
let vc2 = UIViewController()
vc2.view.backgroundColor = .purple
let vc3 = UIViewController()
vc3.view.backgroundColor = .green
let vc4 = UIViewController()
vc4.view.backgroundColor = .brown
let vcs = [vc1, vc2, vc3, vc4]
let y: CGFloat = pagingTitle.frame.maxY
let tempRect: CGRect = CGRect.init(x: 0, y: y, width: UIScreen.width, height: UIScreen.height - y)
let pagingContent = SGPagingContentScrollView(frame: tempRect, parentVC: self, childVCs: vcs)
pagingContent.delegate = self
pagingContent.isBounces = true
view.addSubview(pagingContent)
pagingContentView = pagingContent
}
func pagingTitleView(titleView: SGPagingTitleView, index: Int) {
pagingContentView.setPagingContentView(index: index)
}
func pagingContentView(contentView: SGPagingContentView, progress: CGFloat, currentIndex: Int, targetIndex: Int) {
pagingTitleView.setPagingTitleView(progress: progress, currentIndex: currentIndex, targetIndex: targetIndex)
}
}
|
mit
|
4847b2fc4d640652b160145364fc3c37
| 33 | 118 | 0.653273 | 4.633397 | false | true | false | false |
karivalkama/Agricola-Scripture-Editor
|
Pods/SwitchLanguage/CIFramework/Language.swift
|
1
|
9918
|
//
// Language.swift
// Multilingue-Test
//
// Created by Bérangère La Touche on 21/01/2018.
// Copyright © 2018 Bérangère La Touche. All rights reserved.
//
import Foundation
import UIKit
let LCLCurrentLanguageKey = "LCLCurrentLanguageKey"
let LCLDefaultLanguage = "en-US"
let LCLBaseBundle = "Base"
let LCLCurrentTableNameKey = "LCLCurrentTableNameKey"
let LCLDefaultTableName = "Localizable"
public let LCLLanguageChangeNotification = "LCLLanguageChangeNotification"
public protocol LanguageDelegate: class {
func language(_ language: Language.Type, getLanguageFlag flag: UIImage)
}
public extension String {
/**
It search the localized string
@return The localized string.
*/
func localized() -> String {
return localized(using: Language.getTableName())
}
/**
It search the localized string
@param tableName: The receiver’s string table to search.
@param bundle: The receiver’s bundle to search.
@return The localized string.
*/
func localized(using tableName: String, in bundle: Bundle = .main) -> String {
if let path = bundle.path(forResource: Language.getCurrentLanguage(), ofType: "lproj"),
let bundle = Bundle(path: path) {
return bundle.localizedString(forKey: self, value: nil, table: tableName)
}
else if let path = bundle.path(forResource: LCLBaseBundle, ofType: "lproj"),
let bundle = Bundle(path: path) {
return bundle.localizedString(forKey: self, value: nil, table: tableName)
}
return self
}
}
public class Language : NSObject {
public static var delegate : LanguageDelegate?
/**
Get the table name
@return The current table name
**/
public class func getTableName() -> String {
if let currentTableName = UserDefaults.standard.object(forKey: LCLCurrentTableNameKey) as? String {
return currentTableName
}
return LCLDefaultTableName
}
/**
Set the table name
@param The table nameto set
**/
public class func setTableName(_ name: String) {
UserDefaults.standard.set(name, forKey: LCLCurrentTableNameKey)
UserDefaults.standard.synchronize()
}
/**
It get the list of all available languages in the app.
@return Array of available languages.
*/
public class func getAllLanguages(_ bundle: Bundle = .main) -> [String] {
var listLanguages = bundle.localizations
if let indexOfBase = listLanguages.index(of: LCLBaseBundle) {
listLanguages.remove(at: indexOfBase)
}
return listLanguages
}
/**
It get the current language of the app.
@return String of current language.
*/
public class func getCurrentLanguage() -> String {
if let currentLanguage = UserDefaults.standard.object(forKey: LCLCurrentLanguageKey) as? String {
return currentLanguage
}
return getDefaultLanguage()
}
/**
It change the current language of the app.
@param language String correspondant to desired language.
*/
public class func setCurrentLanguage(_ language: String, bundle: Bundle = .main) {
let selectedLanguage = getAllLanguages(bundle).contains(language) ? language : getDefaultLanguage()
if (selectedLanguage != getCurrentLanguage()){
UserDefaults.standard.set(selectedLanguage, forKey: LCLCurrentLanguageKey)
UserDefaults.standard.synchronize()
NotificationCenter.default.post(name: Notification.Name(rawValue: LCLLanguageChangeNotification), object: nil)
}
}
/**
It get the default language of the app.
@return String of app default language.
*/
public class func getDefaultLanguage(bundle: Bundle = .main) -> String {
var defaultLanguage: String = String()
guard let preferredLanguage = bundle.preferredLocalizations.first else {
return LCLDefaultLanguage
}
let availableLanguages: [String] = getAllLanguages(bundle)
if (availableLanguages.contains(preferredLanguage)) {
defaultLanguage = preferredLanguage
}
else {
defaultLanguage = LCLDefaultLanguage
}
return defaultLanguage
}
/**
It reset the language with the default language of the app.
@return Void
*/
public class func resetCurrentLanguageToDefault() {
setCurrentLanguage(self.getDefaultLanguage())
}
/**
It get the current language and display his name.
@param language String correspondant to desired language.
@return String name of the current languages.
*/
public class func displayNameForLanguage(_ language: String) -> String {
let locale : NSLocale = NSLocale(localeIdentifier: getCurrentLanguage())
if let displayName = locale.displayName(forKey: NSLocale.Key.identifier, value: language) {
return displayName
}
return String()
}
/**
It get the flag of the current language and display it in the settings button.
@return Void
*/
public class func setFlagToButton() {
let cLanguage = getCurrentLanguage()
let countryCode = cLanguage.split(separator: "-")
var newLang : String
if (countryCode.count == 2) {
newLang = String(countryCode[1])
} else {
newLang = String(countryCode[0])
}
let flag = URL(string: "http://www.countryflags.io/\(newLang)/flat/64.png")
var cFlag = UIImage()
downloadImage(url: flag!) { img in
if (img?.cgImage != nil) {
cFlag = img!
self.delegate?.language(self, getLanguageFlag: cFlag)
}
}
}
/**
It display a basic alert with each names of available languages of the app.
@param [String] array of all available languages.
@return UIAlertController alert action to change the language.
*/
public class func basicAlert(_ languages: [String]) -> UIAlertController {
let actionSheet = UIAlertController(title: nil, message: "Switch Language".localized(), preferredStyle: UIAlertControllerStyle.actionSheet)
for lang in languages {
let displayName = displayNameForLanguage(lang)
let languageAction = UIAlertAction(title: displayName, style: .default, handler: {
(alert: UIAlertAction!) -> Void in
setCurrentLanguage(lang)
})
actionSheet.addAction(languageAction)
}
let cancelAction = UIAlertAction(title: "Cancel".localized(), style: UIAlertActionStyle.cancel, handler: {
(alert: UIAlertAction) -> Void in
})
actionSheet.addAction(cancelAction)
return actionSheet
}
/**
It display an alert with the flags of each available languages of the app.
@param [String] array of all available languages.
@return UIAlertController alert action to change the language.
*/
public class func flagAlert(_ languages: [String]) -> UIAlertController {
let actionSheet = UIAlertController(title: nil, message: "Switch Language".localized(), preferredStyle: UIAlertControllerStyle.actionSheet)
let imageView = UIImageView()
actionSheet.view.addSubview(imageView)
for lang in languages {
let countryCode = lang.split(separator: "-")
var newLang : String
if (countryCode.count == 2) {
newLang = String(countryCode[1])
} else {
newLang = String(countryCode[0])
}
let flag = URL(string: "http://www.countryflags.io/\(newLang)/flat/64.png")
var cFlag = UIImage()
downloadImage(url: flag!) { img in
if (img?.cgImage != nil) {
cFlag = img!
let displayName = displayNameForLanguage(lang)
let languageAction = UIAlertAction(title: displayName, style: .default, handler: { (alert: UIAlertAction!) -> Void in
setCurrentLanguage(lang)
})
languageAction.setValue(cFlag.withRenderingMode(UIImageRenderingMode.alwaysOriginal), forKey: "image")
actionSheet.addAction(languageAction)
}
}
}
let cancelAction = UIAlertAction(title: "Cancel".localized(), style: UIAlertActionStyle.cancel, handler: {
(alert: UIAlertAction) -> Void in
})
actionSheet.addAction(cancelAction)
return actionSheet
}
}
extension Language {
/**
Request to get the flag image of the languages.
@param URL of the awaited image
*/
class func getDataFromUrl(url : URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url) {
data, response, error in completion(data, response, error)
}.resume()
}
/**
Call the request to download the awaited image for languages.
@param URL of the awaited image
*/
class func downloadImage(url: URL, completionHandler: @escaping (UIImage?) -> Void) {
getDataFromUrl(url: url) { data, response, error in
guard let data = data, error == nil else { return }
DispatchQueue.main.async() {
let image = UIImage(data: data)
completionHandler(image)
}
}
}
}
|
mit
|
80d8f8a19b70dd8a45486ae6d5a34847
| 31.811258 | 147 | 0.609749 | 5.040183 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/PeerMediaWebpageRowContent.swift
|
1
|
16140
|
//
// MediaWebpageRowItem.swift
// Telegram-Mac
//
// Created by keepcoder on 27/10/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import Postbox
import SwiftSignalKit
class PeerMediaWebpageRowItem: PeerMediaRowItem {
private(set) var textLayout:TextViewLayout?
private(set) var linkLayouts:[TextViewLayout] = []
private(set) var iconText:NSAttributedString?
private(set) var firstCharacter:String?
private(set) var icon:TelegramMediaImage?
private(set) var iconArguments:TransformImageArguments?
private(set) var thumb:CGImage? = nil
//, gallery: GalleryAppearType = .history
override init(_ initialSize:NSSize, _ interface:ChatInteraction, _ object: PeerMediaSharedEntry, galleryType: GalleryAppearType = .history, gallery: @escaping(Message, GalleryAppearType)->Void, viewType: GeneralViewType = .legacy) {
super.init(initialSize, interface, object, galleryType: galleryType, gallery: gallery, viewType: viewType)
var linkLayouts:[TextViewLayout] = []
var links:[NSAttributedString] = []
for attr in message.attributes {
if let attr = attr as? TextEntitiesMessageAttribute {
for entity in attr.entities {
inner: switch entity.type {
case .Email:
let attributed = NSMutableAttributedString()
let link = message.text.nsstring.substring(with: NSMakeRange(min(entity.range.lowerBound, message.text.length), max(min(entity.range.upperBound - entity.range.lowerBound, message.text.length - entity.range.lowerBound), 0)))
let range = attributed.append(string: link, color: theme.colors.link, font: .normal(.text))
attributed.addAttribute(.link, value: inApp(for: link as NSString, context: interface.context, peerId: interface.peerId, openInfo: interface.openInfo, applyProxy: interface.applyProxy, confirm: false), range: range)
links.append(attributed)
case .Url:
let attributed = NSMutableAttributedString()
let link = message.text.nsstring.substring(with: NSMakeRange(min(entity.range.lowerBound, message.text.length), max(min(entity.range.upperBound - entity.range.lowerBound, message.text.length - entity.range.lowerBound), 0)))
let range = attributed.append(string: link, color: theme.colors.link, font: .normal(.text))
attributed.addAttribute(.link, value: inApp(for: link as NSString, context: interface.context, peerId: interface.peerId, openInfo: interface.openInfo, applyProxy: interface.applyProxy, confirm: false), range: range)
links.append(attributed)
case let .TextUrl(url):
let attributed = NSMutableAttributedString()
let range = attributed.append(string: url, color: theme.colors.link, font: .normal(.text))
attributed.addAttribute(.link, value: inApp(for: url as NSString, context: interface.context, peerId:
interface.peerId, openInfo: interface.openInfo, applyProxy: interface.applyProxy, confirm: false), range: range)
links.append(attributed)
default:
break inner
}
}
break
}
}
for attributed in links {
let linkLayout = TextViewLayout(attributed, maximumNumberOfLines: 1, truncationType: .middle)
linkLayout.interactions = globalLinkExecutor
linkLayouts.append(linkLayout)
}
if let webpage = message.effectiveMedia as? TelegramMediaWebpage {
if case let .Loaded(content) = webpage.content {
var hostName: String = ""
if let url = URL(string: content.url), let host = url.host, !host.isEmpty {
hostName = host
firstCharacter = host.prefix(1)
} else {
firstCharacter = content.url.prefix(1)
}
var iconImageRepresentation:TelegramMediaImageRepresentation? = nil
if let image = content.image {
iconImageRepresentation = largestImageRepresentation(image.representations)
} else if let file = content.file {
iconImageRepresentation = largestImageRepresentation(file.previewRepresentations)
}
if let iconImageRepresentation = iconImageRepresentation {
icon = TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: [iconImageRepresentation], immediateThumbnailData: nil, reference: nil, partialReference: nil, flags: [])
let imageCorners = ImageCorners(radius: .cornerRadius)
iconArguments = TransformImageArguments(corners: imageCorners, imageSize: iconImageRepresentation.dimensions.size.aspectFilled(PeerMediaIconSize), boundingSize: PeerMediaIconSize, intrinsicInsets: NSEdgeInsets())
}
let attributedText = NSMutableAttributedString()
let _ = attributedText.append(string: content.title ?? content.websiteName ?? hostName, color: theme.colors.text, font: .medium(.text))
if let text = content.text {
let _ = attributedText.append(string: "\n")
let _ = attributedText.append(string: text, color: theme.colors.text, font: .normal(.short))
attributedText.detectLinks(type: [.Links], context: interface.context, openInfo: interface.openInfo)
}
textLayout = TextViewLayout(attributedText, maximumNumberOfLines: 3, truncationType: .end)
}
} else if let linkLayout = linkLayouts.first {
let attributed = linkLayout.attributedString
var hostName: String = attributed.string
if let url = URL(string: attributed.string), let host = url.host, !host.isEmpty {
hostName = host
firstCharacter = host.prefix(1)
} else {
firstCharacter = "L"
}
let attributedText = NSMutableAttributedString()
let _ = attributedText.append(string: hostName, color: theme.colors.text, font: .medium(.text))
if !hostName.isEmpty {
let _ = attributedText.append(string: "\n")
}
if message.text != linkLayout.attributedString.string {
let _ = attributedText.append(string: message.text, color: theme.colors.text, font: .normal(.short))
}
textLayout = TextViewLayout(attributedText, maximumNumberOfLines: 3, truncationType: .end)
}
if icon == nil {
thumb = generateMediaEmptyLinkThumb(color: theme.colors.listBackground, textColor: theme.colors.listGrayText, host: firstCharacter?.uppercased() ?? "H")
}
textLayout?.interactions = globalLinkExecutor
if message.stableId != UINT32_MAX {
textLayout?.interactions.menuItems = { [weak self] inside in
guard let `self` = self else {return .complete()}
return self.menuItems(in: NSZeroPoint) |> map { items in
var items = items
if let layout = self.textLayout, layout.selectedRange.hasSelectText {
let text = layout.attributedString.attributedSubstring(from: layout.selectedRange.range)
items.insert(ContextMenuItem(strings().textCopy, handler: {
copyToClipboard(text.string)
}, itemImage: MenuAnimation.menu_copy.value), at: 0)
items.insert(ContextSeparatorItem(), at: 1)
}
return items
}
}
}
for linkLayout in linkLayouts {
linkLayout.interactions = TextViewInteractions(processURL: { [weak self] url in
if let webpage = self?.message.effectiveMedia as? TelegramMediaWebpage, let `self` = self {
if self.hasInstantPage {
showInstantPage(InstantPageViewController(self.interface.context, webPage: webpage, message: nil, saveToRecent: false))
return
}
}
globalLinkExecutor.processURL(url)
}, copy: { [weak linkLayout] in
guard let linkLayout = linkLayout else {return false}
copyToClipboard(linkLayout.attributedString.string)
return false
}, localizeLinkCopy: { link in
return strings().textContextCopyLink
})
}
self.linkLayouts = linkLayouts
_ = makeSize(initialSize.width, oldWidth: 0)
}
var hasInstantPage: Bool {
if let webpage = message.effectiveMedia as? TelegramMediaWebpage {
if case let .Loaded(content) = webpage.content {
if let instantPage = content.instantPage {
let hasInstantPage:()->Bool = {
if instantPage.blocks.count == 3 {
switch instantPage.blocks[2] {
case let .collage(_, caption), let .slideshow(_, caption):
return !attributedStringForRichText(caption.text, styleStack: InstantPageTextStyleStack()).string.isEmpty
default:
break
}
}
return true
}
if content.websiteName?.lowercased() == "instagram" || content.websiteName?.lowercased() == "twitter" || content.websiteName?.lowercased() == "telegram" || content.type == "telegram_album" {
return false
}
return hasInstantPage()
}
}
}
return false
}
var isArticle: Bool {
return message.stableId == UINT32_MAX
}
override func makeSize(_ width: CGFloat, oldWidth:CGFloat) -> Bool {
let result = super.makeSize(width, oldWidth: oldWidth)
textLayout?.measure(width: self.blockWidth - contentInset.left - contentInset.right - self.viewType.innerInset.left - self.viewType.innerInset.right)
for linkLayout in linkLayouts {
linkLayout.measure(width: self.blockWidth - contentInset.left - contentInset.right - self.viewType.innerInset.left - self.viewType.innerInset.right - (hasInstantPage ? 10 : 0))
}
var textSizes:CGFloat = 0
if let tLayout = textLayout {
textSizes += tLayout.layoutSize.height
}
for linkLayout in linkLayouts {
textSizes += linkLayout.layoutSize.height
}
contentSize = NSMakeSize(width, max(textSizes + contentInset.top + contentInset.bottom + 2.0, 40))
return result
}
override func viewClass() -> AnyClass {
return PeerMediaWebpageRowView.self
}
}
class PeerMediaWebpageRowView : PeerMediaRowView {
private var imageView:TransformImageView
private var textView:TextView
private var linkViews:[TextView] = []
private var ivImage: ImageView? = nil
required init(frame frameRect: NSRect) {
imageView = TransformImageView(frame:NSMakeRect(0, 0, PeerMediaIconSize.width, PeerMediaIconSize.height))
textView = TextView()
super.init(frame: frameRect)
addSubview(imageView)
addSubview(textView)
}
override func layout() {
super.layout()
if let item = item as? PeerMediaWebpageRowItem {
ivImage?.setFrameOrigin(item.contentInset.left, textView.frame.maxY + 6.0)
textView.setFrameOrigin(NSMakePoint(item.contentInset.left,item.contentInset.top))
var linkY: CGFloat = textView.frame.maxY + 2.0
for linkView in self.linkViews {
linkView.setFrameOrigin(NSMakePoint(item.contentInset.left + (item.hasInstantPage ? 10 : 0), linkY))
linkY += linkView.frame.height
}
}
}
override func mouseUp(with event: NSEvent) {
guard let item = item as? PeerMediaWebpageRowItem, item.isArticle else {
super.mouseUp(with: event)
return
}
// item.linkLayout?.interactions.processURL(event)
}
override func set(item: TableRowItem, animated: Bool) {
super.set(item: item,animated:animated)
textView.backgroundColor = backdorColor
if let item = item as? PeerMediaWebpageRowItem {
textView.userInteractionEnabled = !item.isArticle
textView.update(item.textLayout, origin: NSMakePoint(item.contentInset.left,item.contentInset.top))
while self.linkViews.count > item.linkLayouts.count {
let last = self.linkViews.removeLast()
last.removeFromSuperview()
}
while self.linkViews.count < item.linkLayouts.count {
let new = TextView()
addSubview(new)
self.linkViews.append(new)
}
var linkY: CGFloat = textView.frame.maxY + 2.0
for (i, linkView) in self.linkViews.enumerated() {
let linkLayout = item.linkLayouts[i]
linkView.backgroundColor = backdorColor
linkView.update(linkLayout, origin: NSMakePoint(item.contentInset.left + (item.hasInstantPage ? 10 : 0), linkY))
linkY += linkLayout.layoutSize.height
}
if item.hasInstantPage {
if ivImage == nil {
ivImage = ImageView()
}
ivImage!.image = theme.icons.chatInstantView
ivImage!.sizeToFit()
addSubview(ivImage!)
} else {
ivImage?.removeFromSuperview()
ivImage = nil
}
let updateIconImageSignal:Signal<ImageDataTransformation,NoError>
if let icon = item.icon {
updateIconImageSignal = chatWebpageSnippetPhoto(account: item.interface.context.account, imageReference: ImageMediaReference.message(message: MessageReference(item.message), media: icon), scale: backingScaleFactor, small:true)
} else {
updateIconImageSignal = .single(ImageDataTransformation())
}
if let arguments = item.iconArguments {
imageView.set(arguments: arguments)
imageView.setSignal( updateIconImageSignal)
}
if item.icon == nil {
imageView.layer?.contents = item.thumb
}
needsLayout = true
}
}
override func updateSelectingMode(with selectingMode:Bool, animated:Bool = false) {
super.updateSelectingMode(with: selectingMode, animated: animated)
self.textView.isSelectable = !selectingMode
for linkView in self.linkViews {
linkView.userInteractionEnabled = !selectingMode
}
self.textView.userInteractionEnabled = !selectingMode
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-2.0
|
dba90bd39e0010f9fe7cec5f1ef68663
| 44.849432 | 247 | 0.57928 | 5.31938 | false | false | false | false |
minikin/Algorithmics
|
Pods/Charts/Charts/Classes/Components/ChartLegend.swift
|
6
|
17206
|
//
// ChartLegend.swift
// Charts
//
// Created by Daniel Cohen Gindi on 24/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class ChartLegend: ChartComponentBase
{
@objc
public enum ChartLegendPosition: Int
{
case RightOfChart
case RightOfChartCenter
case RightOfChartInside
case LeftOfChart
case LeftOfChartCenter
case LeftOfChartInside
case BelowChartLeft
case BelowChartRight
case BelowChartCenter
case AboveChartLeft
case AboveChartRight
case AboveChartCenter
case PiechartCenter
}
@objc
public enum ChartLegendForm: Int
{
case Square
case Circle
case Line
}
@objc
public enum ChartLegendDirection: Int
{
case LeftToRight
case RightToLeft
}
/// the legend colors array, each color is for the form drawn at the same index
public var colors = [NSUIColor?]()
// the legend text array. a nil label will start a group.
public var labels = [String?]()
internal var _extraColors = [NSUIColor?]()
internal var _extraLabels = [String?]()
/// colors that will be appended to the end of the colors array after calculating the legend.
public var extraColors: [NSUIColor?] { return _extraColors; }
/// labels that will be appended to the end of the labels array after calculating the legend. a nil label will start a group.
public var extraLabels: [String?] { return _extraLabels; }
/// Are the legend labels/colors a custom value or auto calculated? If false, then it's auto, if true, then custom.
///
/// **default**: false (automatic legend)
private var _isLegendCustom = false
public var position = ChartLegendPosition.BelowChartLeft
public var direction = ChartLegendDirection.LeftToRight
public var font: NSUIFont = NSUIFont.systemFontOfSize(10.0)
public var textColor = NSUIColor.blackColor()
public var form = ChartLegendForm.Square
public var formSize = CGFloat(8.0)
public var formLineWidth = CGFloat(1.5)
public var xEntrySpace = CGFloat(6.0)
public var yEntrySpace = CGFloat(0.0)
public var formToTextSpace = CGFloat(5.0)
public var stackSpace = CGFloat(3.0)
public var calculatedLabelSizes = [CGSize]()
public var calculatedLabelBreakPoints = [Bool]()
public var calculatedLineSizes = [CGSize]()
public override init()
{
super.init()
self.xOffset = 5.0
self.yOffset = 4.0
}
public init(colors: [NSUIColor?], labels: [String?])
{
super.init()
self.colors = colors
self.labels = labels
}
public init(colors: [NSObject], labels: [NSObject])
{
super.init()
self.colorsObjc = colors
self.labelsObjc = labels
}
public func getMaximumEntrySize(font: NSUIFont) -> CGSize
{
var maxW = CGFloat(0.0)
var maxH = CGFloat(0.0)
var labels = self.labels
for (var i = 0; i < labels.count; i++)
{
if (labels[i] == nil)
{
continue
}
let size = (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: font])
if (size.width > maxW)
{
maxW = size.width
}
if (size.height > maxH)
{
maxH = size.height
}
}
return CGSize(
width: maxW + formSize + formToTextSpace,
height: maxH
)
}
public func getLabel(index: Int) -> String?
{
return labels[index]
}
public func getFullSize(labelFont: NSUIFont) -> CGSize
{
var width = CGFloat(0.0)
var height = CGFloat(0.0)
var labels = self.labels
for (var i = 0, count = labels.count; i < count; i++)
{
if (labels[i] != nil)
{
// make a step to the left
if (colors[i] != nil)
{
width += formSize + formToTextSpace
}
let size = (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont])
width += size.width
height += size.height
if (i < count - 1)
{
width += xEntrySpace
height += yEntrySpace
}
}
else
{
width += formSize + stackSpace
if (i < count - 1)
{
width += stackSpace
}
}
}
return CGSize(width: width, height: height)
}
public var neededWidth = CGFloat(0.0)
public var neededHeight = CGFloat(0.0)
public var textWidthMax = CGFloat(0.0)
public var textHeightMax = CGFloat(0.0)
/// flag that indicates if word wrapping is enabled
/// this is currently supported only for: `BelowChartLeft`, `BelowChartRight`, `BelowChartCenter`.
/// note that word wrapping a legend takes a toll on performance.
/// you may want to set maxSizePercent when word wrapping, to set the point where the text wraps.
///
/// **default**: false
public var wordWrapEnabled = false
/// if this is set, then word wrapping the legend is enabled.
public var isWordWrapEnabled: Bool { return wordWrapEnabled }
/// The maximum relative size out of the whole chart view in percent.
/// If the legend is to the right/left of the chart, then this affects the width of the legend.
/// If the legend is to the top/bottom of the chart, then this affects the height of the legend.
/// If the legend is the center of the piechart, then this defines the size of the rectangular bounds out of the size of the "hole".
///
/// **default**: 0.95 (95%)
public var maxSizePercent: CGFloat = 0.95
public func calculateDimensions(labelFont labelFont: NSUIFont, viewPortHandler: ChartViewPortHandler)
{
if (position == .RightOfChart
|| position == .RightOfChartCenter
|| position == .LeftOfChart
|| position == .LeftOfChartCenter
|| position == .PiechartCenter)
{
let maxEntrySize = getMaximumEntrySize(labelFont)
let fullSize = getFullSize(labelFont)
neededWidth = maxEntrySize.width
neededHeight = fullSize.height
textWidthMax = maxEntrySize.width
textHeightMax = maxEntrySize.height
}
else if (position == .BelowChartLeft
|| position == .BelowChartRight
|| position == .BelowChartCenter
|| position == .AboveChartLeft
|| position == .AboveChartRight
|| position == .AboveChartCenter)
{
var labels = self.labels
var colors = self.colors
let labelCount = labels.count
let labelLineHeight = labelFont.lineHeight
let formSize = self.formSize
let formToTextSpace = self.formToTextSpace
let xEntrySpace = self.xEntrySpace
let stackSpace = self.stackSpace
let wordWrapEnabled = self.wordWrapEnabled
let contentWidth: CGFloat = viewPortHandler.contentWidth
// Prepare arrays for calculated layout
if (calculatedLabelSizes.count != labelCount)
{
calculatedLabelSizes = [CGSize](count: labelCount, repeatedValue: CGSize())
}
if (calculatedLabelBreakPoints.count != labelCount)
{
calculatedLabelBreakPoints = [Bool](count: labelCount, repeatedValue: false)
}
calculatedLineSizes.removeAll(keepCapacity: true)
// Start calculating layout
let labelAttrs = [NSFontAttributeName: labelFont]
var maxLineWidth: CGFloat = 0.0
var currentLineWidth: CGFloat = 0.0
var requiredWidth: CGFloat = 0.0
var stackedStartIndex: Int = -1
for (var i = 0; i < labelCount; i++)
{
let drawingForm = colors[i] != nil
calculatedLabelBreakPoints[i] = false
if (stackedStartIndex == -1)
{
// we are not stacking, so required width is for this label only
requiredWidth = 0.0
}
else
{
// add the spacing appropriate for stacked labels/forms
requiredWidth += stackSpace
}
// grouped forms have null labels
if (labels[i] != nil)
{
calculatedLabelSizes[i] = (labels[i] as NSString!).sizeWithAttributes(labelAttrs)
requiredWidth += drawingForm ? formToTextSpace + formSize : 0.0
requiredWidth += calculatedLabelSizes[i].width
}
else
{
calculatedLabelSizes[i] = CGSize()
requiredWidth += drawingForm ? formSize : 0.0
if (stackedStartIndex == -1)
{
// mark this index as we might want to break here later
stackedStartIndex = i
}
}
if (labels[i] != nil || i == labelCount - 1)
{
let requiredSpacing = currentLineWidth == 0.0 ? 0.0 : xEntrySpace
if (!wordWrapEnabled || // No word wrapping, it must fit.
currentLineWidth == 0.0 || // The line is empty, it must fit.
(contentWidth - currentLineWidth >= requiredSpacing + requiredWidth)) // It simply fits
{
// Expand current line
currentLineWidth += requiredSpacing + requiredWidth
}
else
{ // It doesn't fit, we need to wrap a line
// Add current line size to array
calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight))
maxLineWidth = max(maxLineWidth, currentLineWidth)
// Start a new line
calculatedLabelBreakPoints[stackedStartIndex > -1 ? stackedStartIndex : i] = true
currentLineWidth = requiredWidth
}
if (i == labelCount - 1)
{ // Add last line size to array
calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight))
maxLineWidth = max(maxLineWidth, currentLineWidth)
}
}
stackedStartIndex = labels[i] != nil ? -1 : stackedStartIndex
}
let maxEntrySize = getMaximumEntrySize(labelFont)
textWidthMax = maxEntrySize.width
textHeightMax = maxEntrySize.height
neededWidth = maxLineWidth
neededHeight = labelLineHeight * CGFloat(calculatedLineSizes.count) +
yEntrySpace * CGFloat(calculatedLineSizes.count == 0 ? 0 : (calculatedLineSizes.count - 1))
}
else
{
let maxEntrySize = getMaximumEntrySize(labelFont)
let fullSize = getFullSize(labelFont)
/* RightOfChartInside, LeftOfChartInside */
neededWidth = fullSize.width
neededHeight = maxEntrySize.height
textWidthMax = maxEntrySize.width
textHeightMax = maxEntrySize.height
}
}
/// MARK: - Custom legend
/// colors and labels that will be appended to the end of the auto calculated colors and labels after calculating the legend.
/// (if the legend has already been calculated, you will need to call notifyDataSetChanged() to let the changes take effect)
public func setExtra(colors colors: [NSUIColor?], labels: [String?])
{
self._extraLabels = labels
self._extraColors = colors
}
/// Sets a custom legend's labels and colors arrays.
/// The colors count should match the labels count.
/// * Each color is for the form drawn at the same index.
/// * A nil label will start a group.
/// * A nil color will avoid drawing a form, and a clearColor will leave a space for the form.
/// This will disable the feature that automatically calculates the legend labels and colors from the datasets.
/// Call `resetCustom(...)` to re-enable automatic calculation (and then `notifyDataSetChanged()` is needed).
public func setCustom(colors colors: [NSUIColor?], labels: [String?])
{
self.labels = labels
self.colors = colors
_isLegendCustom = true
}
/// Calling this will disable the custom legend labels (set by `setLegend(...)`). Instead, the labels will again be calculated automatically (after `notifyDataSetChanged()` is called).
public func resetCustom()
{
_isLegendCustom = false
}
/// **default**: false (automatic legend)
/// - returns: true if a custom legend labels and colors has been set
public var isLegendCustom: Bool
{
return _isLegendCustom
}
/// MARK: - ObjC compatibility
/// colors that will be appended to the end of the colors array after calculating the legend.
public var extraColorsObjc: [NSObject] { return ChartUtils.bridgedObjCGetNSUIColorArray(swift: _extraColors); }
/// labels that will be appended to the end of the labels array after calculating the legend. a nil label will start a group.
public var extraLabelsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _extraLabels); }
/// the legend colors array, each color is for the form drawn at the same index
/// (ObjC bridging functions, as Swift 1.2 does not bridge optionals in array to `NSNull`s)
public var colorsObjc: [NSObject]
{
get { return ChartUtils.bridgedObjCGetNSUIColorArray(swift: colors); }
set { self.colors = ChartUtils.bridgedObjCGetNSUIColorArray(objc: newValue); }
}
// the legend text array. a nil label will start a group.
/// (ObjC bridging functions, as Swift 1.2 does not bridge optionals in array to `NSNull`s)
public var labelsObjc: [NSObject]
{
get { return ChartUtils.bridgedObjCGetStringArray(swift: labels); }
set { self.labels = ChartUtils.bridgedObjCGetStringArray(objc: newValue); }
}
/// colors and labels that will be appended to the end of the auto calculated colors and labels after calculating the legend.
/// (if the legend has already been calculated, you will need to call `notifyDataSetChanged()` to let the changes take effect)
public func setExtra(colors colors: [NSObject], labels: [NSObject])
{
if (colors.count != labels.count)
{
fatalError("ChartLegend:setExtra() - colors array and labels array need to be of same size")
}
self._extraLabels = ChartUtils.bridgedObjCGetStringArray(objc: labels)
self._extraColors = ChartUtils.bridgedObjCGetNSUIColorArray(objc: colors)
}
/// Sets a custom legend's labels and colors arrays.
/// The colors count should match the labels count.
/// * Each color is for the form drawn at the same index.
/// * A nil label will start a group.
/// * A nil color will avoid drawing a form, and a clearColor will leave a space for the form.
/// This will disable the feature that automatically calculates the legend labels and colors from the datasets.
/// Call `resetLegendToAuto(...)` to re-enable automatic calculation, and then if needed - call `notifyDataSetChanged()` on the chart to make it refresh the data.
public func setCustom(colors colors: [NSObject], labels: [NSObject])
{
if (colors.count != labels.count)
{
fatalError("ChartLegend:setCustom() - colors array and labels array need to be of same size")
}
self.labelsObjc = labels
self.colorsObjc = colors
_isLegendCustom = true
}
}
|
mit
|
19bfc2b6416aca5219fbc400773975e7
| 36.32321 | 188 | 0.571661 | 5.431187 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples
|
MapsAndPlacesDemo/MapsAndPlacesDemo/UITextViewExtension.swift
|
1
|
1286
|
/* Copyright (c) 2020 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 SwiftUI
extension UITextView {
// MARK: Text view property functions
/// Centers the text to be in the middle, down the y-axis
func centerVertically() {
let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
let size = sizeThatFits(fittingSize)
let horizontalOffset = (bounds.size.width - size.width * zoomScale) / 2
let positiveHorizontalOffset = max(1, horizontalOffset)
contentOffset.x = -positiveHorizontalOffset
let topOffset = (bounds.size.height - size.height * zoomScale) / 2
let positiveTopOffset = max(1, topOffset)
contentOffset.y = -positiveTopOffset
}
}
|
apache-2.0
|
8213ee785b8d57fc386b6b51daa2660f
| 36.823529 | 94 | 0.709953 | 4.480836 | false | false | false | false |
mightydeveloper/swift
|
stdlib/public/SDK/AppKit/NSError.swift
|
7
|
1357
|
public extension NSCocoaError {
public static var TextReadInapplicableDocumentTypeError: NSCocoaError {
return NSCocoaError(rawValue: 65806)
}
public static var TextWriteInapplicableDocumentTypeError: NSCocoaError {
return NSCocoaError(rawValue: 66062)
}
public static var ServiceApplicationNotFoundError: NSCocoaError {
return NSCocoaError(rawValue: 66560)
}
public static var ServiceApplicationLaunchFailedError: NSCocoaError {
return NSCocoaError(rawValue: 66561)
}
public static var ServiceRequestTimedOutError: NSCocoaError {
return NSCocoaError(rawValue: 66562)
}
public static var ServiceInvalidPasteboardDataError: NSCocoaError {
return NSCocoaError(rawValue: 66563)
}
public static var ServiceMalformedServiceDictionaryError: NSCocoaError {
return NSCocoaError(rawValue: 66564)
}
public static var ServiceMiscellaneousError: NSCocoaError {
return NSCocoaError(rawValue: 66800)
}
public static var SharingServiceNotConfiguredError: NSCocoaError {
return NSCocoaError(rawValue: 67072)
}
public var isServiceError: Bool {
return rawValue >= 66560 && rawValue <= 66817;
}
public var isSharingServiceError: Bool {
return rawValue >= 67072 && rawValue <= 67327;
}
public var isTextReadWriteError: Bool {
return rawValue >= 65792 && rawValue <= 66303;
}
}
|
apache-2.0
|
edc11f160d357e5f2f95ad96a42b0e3a
| 32.097561 | 74 | 0.762712 | 5.471774 | false | false | false | false |
soeurngsar/DWImagePicker-Swift3
|
WDImagePicker/ViewController.swift
|
2
|
6298
|
//
// ViewController.swift
// WDImagePicker
//
// Created by Wu Di on 27/8/15.
// Copyright (c) 2015 Wu Di. All rights reserved.
//
import UIKit
class ViewController: UIViewController, WDImagePickerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
private var imagePicker: WDImagePicker!
private var popoverController: UIPopoverController!
private var imagePickerController: UIImagePickerController!
private var customCropButton: UIButton!
private var normalCropButton: UIButton!
private var imageView: UIImageView!
private var resizableButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.customCropButton = UIButton()
self.customCropButton.frame = UIDevice.currentDevice().userInterfaceIdiom == .Pad ?
CGRectMake(20, 20, 220, 44) :
CGRectMake(20, CGRectGetMaxY(self.customCropButton.frame) + 20 , CGRectGetWidth(self.view.bounds) - 40, 44)
self.customCropButton.setTitleColor(self.view.tintColor, forState: .Normal)
self.customCropButton.setTitle("Custom Crop", forState: .Normal)
self.customCropButton.addTarget(self, action: #selector(ViewController.showPicker(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(self.customCropButton)
self.normalCropButton = UIButton()
self.normalCropButton.setTitleColor(self.view.tintColor, forState: .Normal)
self.normalCropButton.setTitle("Apple's Build In Crop", forState: .Normal)
self.normalCropButton.addTarget(self, action: #selector(ViewController.showNormalPicker(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(self.normalCropButton)
self.resizableButton = UIButton()
self.resizableButton.setTitleColor(self.view.tintColor, forState: .Normal)
self.resizableButton.setTitle("Resizable Custom Crop", forState: .Normal)
self.resizableButton.addTarget(self, action: #selector(ViewController.showResizablePicker(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(self.resizableButton)
self.imageView = UIImageView(frame: CGRectZero)
self.imageView.contentMode = .ScaleAspectFit
self.imageView.backgroundColor = UIColor.grayColor()
self.view.addSubview(self.imageView)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.normalCropButton.frame = UIDevice.currentDevice().userInterfaceIdiom == .Pad ?
CGRectMake(260, 20, 220, 44) :
CGRectMake(20, CGRectGetMaxY(self.customCropButton.frame) + 20 , CGRectGetWidth(self.view.bounds) - 40, 44)
self.resizableButton.frame = UIDevice.currentDevice().userInterfaceIdiom == .Pad ?
CGRectMake(500, 20, 220, 44) :
CGRectMake(20, CGRectGetMaxY(self.normalCropButton.frame) + 20 , CGRectGetWidth(self.view.bounds) - 40, 44)
self.imageView.frame = UIDevice.currentDevice().userInterfaceIdiom == .Pad ?
CGRectMake(20, 84, CGRectGetWidth(self.view.bounds) - 40, CGRectGetHeight(self.view.bounds) - 104) :
CGRectMake(20, CGRectGetMaxY(self.resizableButton.frame) + 20, CGRectGetWidth(self.view.bounds) - 40, CGRectGetHeight(self.view.bounds) - 20 - (CGRectGetMaxY(self.resizableButton.frame) + 20))
}
func showPicker(button: UIButton) {
self.imagePicker = WDImagePicker()
self.imagePicker.cropSize = CGSizeMake(280, 280)
self.imagePicker.delegate = self
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.popoverController = UIPopoverController(contentViewController: self.imagePicker.imagePickerController)
self.popoverController.presentPopoverFromRect(button.frame, inView: self.view, permittedArrowDirections: .Any, animated: true)
} else {
self.presentViewController(self.imagePicker.imagePickerController, animated: true, completion: nil)
}
}
func showNormalPicker(button: UIButton) {
self.imagePickerController = UIImagePickerController()
self.imagePickerController.sourceType = .PhotoLibrary
self.imagePickerController.delegate = self
self.imagePickerController.allowsEditing = true
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.popoverController = UIPopoverController(contentViewController: self.imagePickerController)
self.popoverController.presentPopoverFromRect(button.frame, inView: self.view, permittedArrowDirections: .Any, animated: true)
} else {
self.presentViewController(self.imagePickerController, animated: true, completion: nil)
}
}
func showResizablePicker(button: UIButton) {
self.imagePicker = WDImagePicker()
self.imagePicker.cropSize = CGSizeMake(280, 280)
self.imagePicker.delegate = self
self.imagePicker.resizableCropArea = true
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.popoverController = UIPopoverController(contentViewController: self.imagePicker.imagePickerController)
self.popoverController.presentPopoverFromRect(button.frame, inView: self.view, permittedArrowDirections: .Any, animated: true)
} else {
self.presentViewController(self.imagePicker.imagePickerController, animated: true, completion: nil)
}
}
func imagePicker(imagePicker: WDImagePicker, pickedImage: UIImage) {
self.imageView.image = pickedImage
self.hideImagePicker()
}
func hideImagePicker() {
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.popoverController.dismissPopoverAnimated(true)
} else {
self.imagePicker.imagePickerController.dismissViewControllerAnimated(true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.imageView.image = image
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.popoverController.dismissPopoverAnimated(true)
} else {
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
}
|
mit
|
8e396b97a2c7649adfe729e54cceefa3
| 46.712121 | 204 | 0.710861 | 5.042434 | false | false | false | false |
HariniMurali/TestDemoPodSDK
|
TestDemoPodSDK/Classes/TicketHomeController.swift
|
1
|
22673
|
//
// TicketHomeController.swift
// HelpSumoSDK
//
// Created by APP DEVELOPEMENT on 16/11/16.
// Copyright © 2016 APP DEVELOPEMENT. All rights reserved.
//
import UIKit
import CoreData
import FMDB
public class TicketHomeController: UITableViewController {
var ticketsData: [[String:String]] = []
var databasePath = String()
let defaults = UserDefaults.standard
let constants = Constants()
var selectedTicketID: String! = ""
@IBOutlet var ticketsTable: UITableView!
@IBAction func onAddPressed(sender: UIBarButtonItem) {
let frameworkBundle = Bundle(for: TicketHomeController.self)
let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent( "TestDemoPodSDK.bundle")
let resourceBundle = Bundle(url: bundleURL!)
let storyboard = UIStoryboard(name: "Ticket", bundle: resourceBundle)
let controller = storyboard.instantiateViewController(withIdentifier: "InitialController") as! UINavigationController
var viewController = controller.topViewController as! NewTicketController
viewController.pageTitle = "Create Ticket"
self.navigationController?.pushViewController(viewController, animated: true)
}
override public func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
self.ticketsData = []
self.initializeDatabase()
self.ticketsTable.reloadData()
self.navigationController?.isToolbarHidden = true
self.ConfigureTableView()
if(self.defaults.value(forKey: "userName") == nil || self.defaults.value(forKey: "userMail") == nil)
{
var alertController = UIAlertController(title: "Login", message: "Input name and email address", preferredStyle: .alert)
alertController.addTextField(configurationHandler: {(_ textField: UITextField) -> Void in
textField.placeholder = "Name"
textField.textColor = UIColor.black
textField.clearButtonMode = .whileEditing
textField.borderStyle = .roundedRect
})
alertController.addTextField(configurationHandler: {(_ textField: UITextField) -> Void in
textField.placeholder = "Email Address"
textField.textColor = UIColor.black
textField.clearButtonMode = .whileEditing
textField.borderStyle = .roundedRect
})
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {(_ action: UIAlertAction) -> Void in
var textfields = alertController.textFields
var namefield = textfields?[0]
var emailfield = textfields?[1]
if(namefield?.text! == "" || emailfield?.text! == "" || !self.isValidEmail(testStr: (emailfield?.text!)!))
{
self.present(alertController, animated: true, completion: { _ in })
}
else
{
var name : String! = namefield!.text!
var email : String! = emailfield!.text!
self.defaults.set(name!, forKey: "userName")
self.defaults.set(email!, forKey: "userMail")
self.downloadTickets(){
results in
let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String)
if (dbObj?.open())! {
let querySQL = "SELECT ticket_subject, ticket_description, department_id, priority_id, type_id, ticket_attachment, staff_name, ticket_no, ticket_id, ticket_status, ticket_offline_flag, ticket_date FROM TABLE_TICKET"
let results:FMResultSet? = dbObj?.executeQuery(querySQL,
withArgumentsIn: nil)
while results?.next() == true {
let jsonObject: [String: String] = [
"Requester": "Carey sam",
"TicketID" : (results?.string(forColumn: "ticket_id"))!,
"Status" : self.constants.TicketStatus[Int((results?.string(forColumn: "ticket_status"))!)!],
"Title" : (results?.string(forColumn: "ticket_subject"))!,
"Date": (results?.string(forColumn: "ticket_date"))!
]
self.ticketsData.append(jsonObject)
}
dbObj?.close()
} else {
print("Error: \(dbObj?.lastErrorMessage())")
}
DispatchQueue.main.async {
self.ticketsTable.reloadData()
}
}
}
}))
self.present(alertController, animated: true, completion: { _ in })
}
if (HSConfig.isInternetAvailable())
{
self.downloadTickets(){
results in
let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String)
if (dbObj?.open())! {
let querySQL = "SELECT ticket_subject, ticket_description, department_id, priority_id, type_id, ticket_attachment, staff_name, ticket_no, ticket_id, ticket_status, ticket_offline_flag, ticket_date FROM TABLE_TICKET"
let results:FMResultSet? = dbObj?.executeQuery(querySQL,
withArgumentsIn: nil)
while results?.next() == true {
let jsonObject: [String: String] = [
"Requester": "Carey sam",
"TicketID" : (results?.string(forColumn: "ticket_id"))!,
"Status" : self.constants.TicketStatus[Int((results?.string(forColumn: "ticket_status"))!)!],
"Title" : (results?.string(forColumn: "ticket_subject"))!,
"Date": (results?.string(forColumn: "ticket_date"))!
]
self.ticketsData.append(jsonObject)
}
dbObj?.close()
} else {
print("Error: \(dbObj?.lastErrorMessage())")
}
DispatchQueue.main.async {
self.ticketsTable.reloadData()
}
}
}else
{
let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String)
if (dbObj?.open())! {
let querySQL = "SELECT ticket_subject, ticket_description, department_id, priority_id, type_id, ticket_attachment, staff_name, ticket_no, ticket_id, ticket_status, ticket_offline_flag, ticket_date FROM TABLE_TICKET"
let results:FMResultSet? = dbObj?.executeQuery(querySQL,
withArgumentsIn: nil)
while results?.next() == true {
let jsonObject: [String: String] = [
"Requester": "Carey sam",
"TicketID" : (results?.string(forColumn: "ticket_id"))!,
"Status" : self.constants.TicketStatus[Int((results?.string(forColumn: "ticket_status"))!)!],
"Title" : (results?.string(forColumn: "ticket_subject"))!,
"Date": (results?.string(forColumn: "ticket_date"))!
]
self.ticketsData.append(jsonObject)
}
dbObj?.close()
} else {
print("Error: \(dbObj?.lastErrorMessage())")
}
DispatchQueue.main.async {
self.ticketsTable.reloadData()
}
}
}
override public func viewDidLoad() {
super.viewDidLoad()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ticketsData.count
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "singleCell", for: indexPath) as! TicketsCell
cell.labelStatus.text = ticketsData[indexPath.row]["Status"]
cell.labelTitle.text = ticketsData[indexPath.row]["Title"]
cell.labelDate.text = ticketsData[indexPath.row]["Date"]
cell.statusIndicator.backgroundColor = UIColor.red
cell.ticketID = ticketsData[indexPath.row]["TicketID"]
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
return cell
}
override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
let cell = tableView.cellForRow(at: indexPath) as! TicketsCell
self.selectedTicketID = cell.ticketID
self.performSegue(withIdentifier: "ticketDetailSegue", sender: tableView)
}
func ConfigureTableView() {
self.ticketsTable.delegate = self
self.ticketsTable.dataSource = self
let frameworkBundle = Bundle(for: TicketHomeController.self)
let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent( "TestDemoPodSDK.bundle")
let resourceBundle = Bundle(url: bundleURL!)
self.ticketsTable.register(UINib(nibName: "TicketCell", bundle: resourceBundle), forCellReuseIdentifier: "singleCell")
self.ticketsTable.rowHeight = 100.0
}
func initializeDatabase()
{
let filemgr = FileManager.default
let dirPaths = filemgr.urls(for: .documentDirectory,
in: .userDomainMask)
let databasePath = dirPaths[0].appendingPathComponent("database.db").path
defaults.set(String(databasePath), forKey: "databasePath")
let dbObj = FMDatabase(path: defaults.value(forKey: "databasePath") as! String)
if dbObj == nil {
print("Error: \(dbObj?.lastErrorMessage())")
}
if (dbObj?.open())!
{
let sql_stmt = "CREATE TABLE IF NOT EXISTS TABLE_TICKET (ID INTEGER PRIMARY KEY AUTOINCREMENT, TICKET_SUBJECT TEXT, TICKET_DESCRIPTION TEXT, DEPARTMENT_ID TEXT, PRIORITY_ID TEXT NOT NULL, TYPE_ID TEXT NOT NULL, TICKET_ATTACHMENT TEXT, STAFF_NAME TEXT NOT NULL, TICKET_NO TEXT NOT NULL, TICKET_ID TEXT NOT NULL, TICKET_STATUS TEXT NOT NULL,TICKET_OFFLINE_FLAG TEXT NOT NULL,TICKET_DATE TEXT NOT NULL, TICKET_UPDATE_TIME TEXT )"
if !(dbObj?.executeStatements(sql_stmt))! {
print("Error: \(dbObj?.lastErrorMessage())")
}
dbObj?.close()
}
else
{
print("Error: \(dbObj?.lastErrorMessage())")
}
}
func downloadTickets(completionHandler: @escaping (_ results: String) -> ())
{
let defaultSession = URLSession(configuration: URLSessionConfiguration.ephemeral)
let constants = Constants()
let url = URL(string: constants.AppUrl+"ticket")!
var request = URLRequest(url: url)
request.addValue("text/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let jsonObject: [String: String] = [
"apikey": HSConfig.getAPIKey(),
"email": String(describing: defaults.value(forKey: "userMail")) == "nil" ? "" : String(describing: defaults.value(forKey: "userMail")!),
"action":"list",
"modified_date" : String(describing: defaults.value(forKey: "ticketSyncDateTime")) == "nil" ? "" : String(describing: defaults.value(forKey: "ticketSyncDateTime")!)
]
var data : AnyObject
let dict = jsonObject as NSDictionary
do
{
data = try JSONSerialization.data(withJSONObject: dict, options:.prettyPrinted) as AnyObject
let strData = NSString(data: (data as! NSData) as Data, encoding: String.Encoding.utf8.rawValue)! as String
data = strData.data(using: String.Encoding.utf8)! as AnyObject
let task = defaultSession.uploadTask(with: request, from: (data as! NSData) as Data, completionHandler:
{(data,response,error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
let alertController:UIAlertController? = UIAlertController(title: "",
message: "Error loading tickets",
preferredStyle: .alert)
let alertAction = UIAlertAction(title: "Okay",style: .default,
handler:nil)
alertController!.addAction(alertAction)
self.present(alertController!,animated: true, completion: nil)
return
}
let json = JSON(data: data!)
if String(describing: json["response"]["CurrentDateTime"]) != "null"
{
self.defaults.set(String(describing: json["response"]["CurrentDateTime"]), forKey: "ticketSyncDateTime")
}
let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String)
var ticket_IDs = [String]()
if json["response"]["Ticket"].count > 0
{
if (dbObj?.open())! {
let querySQL = "SELECT ticket_id FROM TABLE_TICKET"
let results:FMResultSet? = dbObj?.executeQuery(querySQL,
withArgumentsIn: nil)
while results?.next() == true {
ticket_IDs.append((results?.string(forColumn: "ticket_id"))!)
}
dbObj?.close()
} else {
print("Error: \(dbObj?.lastErrorMessage())")
}
}
for i in 0..<json["response"]["Ticket"].count
{
var newTicketID: String! = String(describing: json["response"]["Ticket"][i]["ticket_id"])
if (dbObj?.open())!
{
if let existingTicket = ticket_IDs.index(of:newTicketID)
{
var assignedTo = String(describing: json["response"]["Ticket"][i]["first_name"])+" "+String(describing: json["response"]["Ticket"][i]["last_name"])
var attachementString:String = ""
for j in 0..<json["response"]["Ticket"][i]["ticket_files"].count
{
attachementString = "\(attachementString)" + "\(String(describing: json["response"]["Ticket"][i]["ticket_files"][j]))" + ","
}
let updateSQL = "UPDATE TABLE_TICKET SET ticket_subject = '\(String(describing: json["response"]["Ticket"][i]["subject"]))', ticket_description = '\(String(describing: json["response"]["Ticket"][i]["message"]))', department_id = '\(String(describing: json["response"]["Ticket"][i]["assign_department_id"]))', priority_id = '\(String(describing: json["response"]["Ticket"][i]["ticket_priority_id"]))', type_id = '\(String(describing: json["response"]["Ticket"][i]["ticket_type_id"]))', ticket_attachment = '\(attachementString)', staff_name = '\(assignedTo)', ticket_no = '\(String(describing: json["response"]["Ticket"][i]["ticket_no"]))', ticket_status = '\(String(describing: json["response"]["Ticket"][i]["ticket_status"]))', ticket_offline_flag = '1', ticket_date = '\(String(describing: json["response"]["Ticket"][i]["tickets_posted_date"]))' WHERE ticket_id = '\(newTicketID!)'"
let result = dbObj?.executeUpdate(updateSQL,
withArgumentsIn: nil)
if !result! {
print("Error: \(dbObj?.lastErrorMessage())")
}
}
else
{
var assignedTo = String(describing: json["response"]["Ticket"][i]["first_name"])+" "+String(describing: json["response"]["Ticket"][i]["last_name"])
var attachementString:String = ""
for j in 0..<json["response"]["Ticket"][i]["ticket_files"].count
{
attachementString = "\(attachementString)" + "\(String(describing: json["response"]["Ticket"][i]["ticket_files"][j]))" + ","
}
var attachments = String(describing: json["response"]["Ticket"][i]["ticket_files"][0])
let insertSQL = "INSERT INTO TABLE_TICKET (ticket_subject, ticket_description, department_id, priority_id, type_id, ticket_attachment, staff_name, ticket_no, ticket_id, ticket_status, ticket_offline_flag, ticket_date, ticket_update_time) VALUES ('\(String(describing: json["response"]["Ticket"][i]["subject"]))', '\(String(describing: json["response"]["Ticket"][i]["message"]))', '\(String(describing: json["response"]["Ticket"][i]["assign_department_id"]))', '\(String(describing: json["response"]["Ticket"][i]["ticket_priority_id"]))', '\(String(describing: json["response"]["Ticket"][i]["ticket_type_id"]))', '\(attachementString)', '\(assignedTo)', '\(String(describing: json["response"]["Ticket"][i]["ticket_no"]))', '\(String(describing: json["response"]["Ticket"][i]["ticket_id"]))', '\(String(describing: json["response"]["Ticket"][i]["ticket_status"]))', '1', '\(String(describing: json["response"]["Ticket"][i]["tickets_posted_date"]))','')"
let result = dbObj?.executeUpdate(insertSQL,
withArgumentsIn: nil)
if !result! {
print("Error: \(dbObj?.lastErrorMessage())")
}
}
} else {
print("Error: \(dbObj?.lastErrorMessage())")
}
}
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
completionHandler(dataString as! String)
}
);
task.resume()
}catch{
}
}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: testStr)
}
override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let backItem = UIBarButtonItem()
backItem.title = "Back"
navigationItem.backBarButtonItem = backItem
if (segue.identifier == "ticketDetailSegue") {
var viewController = segue.destination as! TicketDetailController
viewController.currentTicketID = self.selectedTicketID
}
}
}
|
mit
|
9afb4773673781682f6163c613466e51
| 44.253493 | 983 | 0.477549 | 5.79106 | false | false | false | false |
liulichao123/fangkuaishou
|
快手/快手/classes/右侧/首页/view/home/NavSliderView.swift
|
1
|
1674
|
//
// NavSliderView.swift
// 快手
//
// Created by liulichao on 16/5/4.
// Copyright © 2016年 刘立超. All rights reserved.
//
import UIKit
class NavSliderView: UIView {
private var slider: UIView
private var count: Int
private var perW: CGFloat
/**
导航栏滑动视图
- parameter frame: 滑动视图frame
- parameter count: 滑动块个数
*/
init(frame: CGRect, count: Int) {
perW = frame.width / CGFloat(count)
slider = UIView(frame: CGRectMake(0, 0, perW, frame.height))
slider.backgroundColor = UIColor.redColor()
self.count = count
super.init(frame: frame)
backgroundColor = UIColor.clearColor()
slider.layer.cornerRadius = 3
addSubview(slider)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**移动到下标位置(不带动画 1-count)*/
internal func moveToIndex(index: Int) {
/**下标从1开始**/
let x = perW * CGFloat(index-1)
self.slider.frame.origin.x = x
}
/**移动到下标位置(带动画 1- count)*/
internal func moveToIndexWithAnimate(index: Int) {
/**下标从1开始**/
let x = perW * CGFloat(index-1)
UIView.animateWithDuration(0.2) {
self.slider.frame.origin.x = x
}
}
/**
根据传入比例移动slider
- parameter scale: slider滑块位置 占sliderView宽度的比例
*/
internal func moveToScale(scale: CGFloat){
slider.frame.origin.x = scale * slider.frame.width * 2
}
}
|
apache-2.0
|
d0cc08f5c85be270833870488b360e23
| 23.174603 | 68 | 0.58503 | 3.732843 | false | false | false | false |
demetrio812/EurekaCreditCard
|
Pod/Classes/EurekaCreditCard.swift
|
1
|
32645
|
//
// EurekaCreditCard.swift
// Examples
//
// Created by Demetrio Filocamo on 02/04/2016.
// Copyright © 2016 Novaware Ltd. All rights reserved.
//
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Eureka
import BKMoneyKit
public protocol CreditCardRowConformance {
var dataSectionWidthPercentage: CGFloat? { get set }
var placeholderColor: UIColor? { get set }
var cardNumberPlaceholder: String? { get set }
var expirationMonthPlaceholder: String? { get set }
var expirationYearPlaceholder: String? { get set }
var cvcPlaceholder: String? { get set }
}
/**
* Protocol for cells that contain a postal address
*/
public protocol CreditCardCellConformance {
var cardNumberTextField: BKCardNumberField { get }
var expirationMonthTextField: UITextField { get }
var expirationYearTextField: UITextField { get }
var cvcTextField: UITextField { get }
}
/**
* Protocol to be implemented by CreditCard types.
*/
public protocol CreditCardType: Equatable {
var cardNumber: String? { get set }
var expirationMonth: String? { get set }
var expirationYear: String? { get set }
var cvc: String? { get set }
}
public func ==<T:CreditCardType>(lhs: T, rhs: T) -> Bool {
return lhs.cardNumber == rhs.cardNumber && lhs.expirationMonth == rhs.expirationMonth && lhs.expirationYear == rhs.expirationYear && lhs.cvc == rhs.cvc
}
public struct CreditCard: CreditCardType {
public var cardNumber: String?
public var expirationMonth: String?
public var expirationYear: String?
public var cvc: String?
public init() {
}
public init(cardNumber: String?, expirationMonth: String?, expirationYear: String?, cvc: String?) {
self.cardNumber = cardNumber
self.expirationMonth = expirationMonth
self.expirationYear = expirationYear
self.cvc = cvc
}
}
public class CreditCardCell<T:CreditCardType>: Cell<T>, CellType, CreditCardCellConformance, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
public var months = [String]()
public var monthsName = [String]()
public var years = [String]()
public lazy var pickerMonth: UIPickerView = {
[unowned self] in
let picker = UIPickerView()
picker.translatesAutoresizingMaskIntoConstraints = false
return picker
}()
public lazy var pickerYear: UIPickerView = {
[unowned self] in
let picker = UIPickerView()
picker.translatesAutoresizingMaskIntoConstraints = false
return picker
}()
lazy public var cardNumberTextField: BKCardNumberField = {
let textField = BKCardNumberField()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
lazy public var cardNumberSeparatorView: UIView = {
let separatorView = UIView()
separatorView.translatesAutoresizingMaskIntoConstraints = false
separatorView.backgroundColor = .lightGrayColor()
return separatorView
}()
lazy public var expirationMonthTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
lazy public var expirationMonthYearSeparatorLabel: UILabel = {
let label = UILabel()
label.text = "/"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy public var expirationYearTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
lazy public var cvcTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
public var titleLabel: UILabel? {
textLabel?.translatesAutoresizingMaskIntoConstraints = false
textLabel?.setContentHuggingPriority(500, forAxis: .Horizontal)
textLabel?.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)
return textLabel
}
private var dynamicConstraints = [NSLayoutConstraint]()
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
deinit {
cardNumberTextField.delegate = nil
cardNumberTextField.removeTarget(self, action: nil, forControlEvents: .AllEvents)
expirationMonthTextField.delegate = nil
expirationMonthTextField.removeTarget(self, action: nil, forControlEvents: .AllEvents)
expirationYearTextField.delegate = nil
expirationYearTextField.removeTarget(self, action: nil, forControlEvents: .AllEvents)
cvcTextField.delegate = nil
cvcTextField.removeTarget(self, action: nil, forControlEvents: .AllEvents)
titleLabel?.removeObserver(self, forKeyPath: "text")
imageView?.removeObserver(self, forKeyPath: "image")
pickerMonth.delegate = nil
pickerMonth.dataSource = nil
pickerYear.delegate = nil
pickerYear.dataSource = nil
}
public override func setup() {
super.setup()
height = {
60
}
selectionStyle = .None
let dateFormatter: NSDateFormatter = NSDateFormatter()
monthsName = dateFormatter.shortMonthSymbols
for myMonthInt in 1 ... 12 {
months.append(String(format: "%02d", myMonthInt))
}
let currentYear = NSCalendar.currentCalendar().component(.Year, fromDate: NSDate())
for myYearInt in currentYear ... (currentYear + 20) {
years.append(String(myYearInt))
}
contentView.addSubview(titleLabel!)
contentView.addSubview(cardNumberTextField)
contentView.addSubview(cardNumberSeparatorView)
contentView.addSubview(expirationMonthTextField)
contentView.addSubview(expirationMonthYearSeparatorLabel)
contentView.addSubview(expirationYearTextField)
contentView.addSubview(cvcTextField)
titleLabel?.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.Old.union(.New), context: nil)
imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.Old.union(.New), context: nil)
cardNumberTextField.addTarget(self, action: #selector(CreditCardCell.textFieldDidChange(_:)), forControlEvents: .EditingChanged)
expirationMonthTextField.addTarget(self, action: #selector(CreditCardCell.textFieldDidChange(_:)), forControlEvents: .EditingChanged)
expirationYearTextField.addTarget(self, action: #selector(CreditCardCell.textFieldDidChange(_:)), forControlEvents: .EditingChanged)
cvcTextField.addTarget(self, action: #selector(CreditCardCell.textFieldDidChange(_:)), forControlEvents: .EditingChanged)
expirationMonthTextField.inputView = pickerMonth
expirationYearTextField.inputView = pickerYear
pickerMonth.delegate = self
pickerMonth.dataSource = self
pickerYear.delegate = self
pickerYear.dataSource = self
}
public override func update() {
super.update()
detailTextLabel?.text = nil
if let title = row.title {
cardNumberTextField.textAlignment = .Left
cardNumberTextField.clearButtonMode = title.isEmpty ? .WhileEditing : .Never
expirationMonthTextField.textAlignment = .Left
expirationMonthTextField.clearButtonMode = .Never
expirationYearTextField.textAlignment = .Left
expirationYearTextField.clearButtonMode = .Never
cvcTextField.textAlignment = .Right
cvcTextField.clearButtonMode = title.isEmpty ? .WhileEditing : .Never
} else {
cardNumberTextField.textAlignment = .Left
cardNumberTextField.clearButtonMode = .WhileEditing
expirationMonthTextField.textAlignment = .Left
expirationMonthTextField.clearButtonMode = .Never
expirationYearTextField.textAlignment = .Left
expirationYearTextField.clearButtonMode = .Never
cvcTextField.textAlignment = .Right
cvcTextField.clearButtonMode = .WhileEditing
}
cardNumberTextField.delegate = self
cardNumberTextField.cardNumber = row.value?.cardNumber
cardNumberTextField.enabled = !row.isDisabled
cardNumberTextField.textColor = row.isDisabled ? .grayColor() : .blackColor()
cardNumberTextField.font = .preferredFontForTextStyle(UIFontTextStyleBody)
cardNumberTextField.autocorrectionType = .No
cardNumberTextField.autocapitalizationType = .None
cardNumberTextField.keyboardType = .NumberPad
cardNumberTextField.showsCardLogo = true
expirationMonthTextField.delegate = self
expirationMonthTextField.text = row.value?.expirationMonth
expirationMonthTextField.enabled = !row.isDisabled
expirationMonthTextField.textColor = row.isDisabled ? .grayColor() : .blackColor()
expirationMonthTextField.font = .preferredFontForTextStyle(UIFontTextStyleBody)
expirationMonthTextField.autocorrectionType = .No
expirationMonthTextField.autocapitalizationType = .None
expirationMonthTextField.keyboardType = .NumberPad
expirationMonthTextField.tintColor = UIColor.clearColor(); // This will hide the blinking cursor in the textfield
expirationMonthTextField.ccMaxLength = 2
expirationYearTextField.delegate = self
expirationYearTextField.text = row.value?.expirationYear
expirationYearTextField.enabled = !row.isDisabled
expirationYearTextField.textColor = row.isDisabled ? .grayColor() : .blackColor()
expirationYearTextField.font = .preferredFontForTextStyle(UIFontTextStyleBody)
expirationYearTextField.autocorrectionType = .No
expirationYearTextField.autocapitalizationType = .None
expirationYearTextField.keyboardType = .NumberPad
expirationYearTextField.tintColor = UIColor.clearColor(); // This will hide the blinking cursor in the textfield
expirationYearTextField.ccMaxLength = 4
cvcTextField.delegate = self
cvcTextField.text = row.value?.cvc
cvcTextField.enabled = !row.isDisabled
cvcTextField.textColor = row.isDisabled ? .grayColor() : .blackColor()
cvcTextField.font = .preferredFontForTextStyle(UIFontTextStyleBody)
cvcTextField.autocorrectionType = .No
cvcTextField.autocapitalizationType = .None
cvcTextField.keyboardType = .NumberPad
cvcTextField.ccMaxLength = 3
cvcTextField.secureTextEntry = true
if let rowConformance = row as? CreditCardRowConformance {
if let placeholder = rowConformance.cardNumberPlaceholder {
cardNumberTextField.placeholder = placeholder
if let color = rowConformance.placeholderColor {
cardNumberTextField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color])
}
}
if let placeholder = rowConformance.expirationMonthPlaceholder {
expirationMonthTextField.placeholder = placeholder
if let color = rowConformance.placeholderColor {
expirationMonthTextField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color])
}
}
if let placeholder = rowConformance.expirationYearPlaceholder {
expirationYearTextField.placeholder = placeholder
if let color = rowConformance.placeholderColor {
expirationYearTextField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color])
}
}
if let placeholder = rowConformance.cvcPlaceholder {
cvcTextField.placeholder = placeholder
if let color = rowConformance.placeholderColor {
cvcTextField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color])
}
}
}
pickerMonth.reloadAllComponents()
if let selectedValue = row.value?.expirationMonth, let index = months.indexOf(selectedValue) {
pickerMonth.selectRow(index + 1, inComponent: 0, animated: true)
}
pickerYear.reloadAllComponents()
if let selectedValue = row.value?.expirationYear, let index = years.indexOf(selectedValue) {
pickerYear.selectRow(index + 1, inComponent: 0, animated: true)
}
}
public override func cellCanBecomeFirstResponder() -> Bool {
return !row.isDisabled && (
cardNumberTextField.canBecomeFirstResponder() ||
expirationMonthTextField.canBecomeFirstResponder() ||
expirationYearTextField.canBecomeFirstResponder() ||
cvcTextField.canBecomeFirstResponder()
)
}
public override func cellBecomeFirstResponder(direction: Direction) -> Bool {
return direction == .Down ? cardNumberTextField.becomeFirstResponder() : cvcTextField.becomeFirstResponder()
}
public override func cellResignFirstResponder() -> Bool {
return cardNumberTextField.resignFirstResponder()
&& expirationMonthTextField.resignFirstResponder()
&& expirationYearTextField.resignFirstResponder()
&& cvcTextField.resignFirstResponder()
}
override public var inputAccessoryView: UIView? {
if let v = formViewController()?.inputAccessoryViewForRow(row) as? NavigationAccessoryView {
if cardNumberTextField.isFirstResponder() {
v.nextButton.enabled = true
v.nextButton.target = self
v.nextButton.action = #selector(CreditCardCell.internalNavigationAction(_:))
} else if expirationMonthTextField.isFirstResponder() {
v.previousButton.target = self
v.previousButton.action = #selector(CreditCardCell.internalNavigationAction(_:))
v.nextButton.target = self
v.nextButton.action = #selector(CreditCardCell.internalNavigationAction(_:))
v.previousButton.enabled = true
v.nextButton.enabled = true
} else if expirationYearTextField.isFirstResponder() {
v.previousButton.target = self
v.previousButton.action = #selector(CreditCardCell.internalNavigationAction(_:))
v.nextButton.target = self
v.nextButton.action = #selector(CreditCardCell.internalNavigationAction(_:))
v.previousButton.enabled = true
v.nextButton.enabled = true
} else if cvcTextField.isFirstResponder() {
v.previousButton.target = self
v.previousButton.action = #selector(CreditCardCell.internalNavigationAction(_:))
v.previousButton.enabled = true
}
return v
}
return super.inputAccessoryView
}
func internalNavigationAction(sender: UIBarButtonItem) {
guard let inputAccesoryView = inputAccessoryView as? NavigationAccessoryView else {
return
}
if cardNumberTextField.isFirstResponder() {
sender == inputAccesoryView.previousButton ? cardNumberTextField.becomeFirstResponder() : expirationMonthTextField.becomeFirstResponder()
} else if expirationMonthTextField.isFirstResponder() {
sender == inputAccesoryView.previousButton ? cardNumberTextField.becomeFirstResponder() : expirationYearTextField.becomeFirstResponder()
} else if expirationYearTextField.isFirstResponder() {
sender == inputAccesoryView.previousButton ? expirationMonthTextField.becomeFirstResponder() : cvcTextField.becomeFirstResponder()
} else if cvcTextField.isFirstResponder() {
expirationYearTextField.becomeFirstResponder()
}
}
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String:AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let obj = object, let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKindKey] where ((obj === titleLabel && keyPathValue == "text") || (obj === imageView && keyPathValue == "image")) && changeType.unsignedLongValue == NSKeyValueChange.Setting.rawValue {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
// Mark: Helpers
public override func updateConstraints() {
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
let cellHeight: CGFloat = self.height!()
let cellPadding: CGFloat = 4.0
let textFieldMargin: CGFloat = 4.0
let textFieldHeight: CGFloat = (cellHeight - 2.0 * cellPadding - 2.0 * textFieldMargin) / 2.0
let expirationMonthTextFieldWidth: CGFloat = 30.0
let expirationYearTextFieldWidth: CGFloat = 50.0
let expirationMonthYearLabelWidth: CGFloat = 15.0
let separatorViewHeight = 0.45
var views: [String:AnyObject] = [
"cardNumberTextField": cardNumberTextField,
"cardNumberSeparatorView": cardNumberSeparatorView,
"expirationMonthTextField": expirationMonthTextField,
"expirationMonthYearSeparatorLabel": expirationMonthYearSeparatorLabel,
"expirationYearTextField": expirationYearTextField,
"cvcTextField": cvcTextField
]
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(cellPadding)-[cardNumberTextField(\(textFieldHeight))]-\(textFieldMargin)-[cardNumberSeparatorView(\(separatorViewHeight))]-\(textFieldMargin)-[expirationMonthTextField(\(textFieldHeight))]", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(cellPadding)-[cardNumberTextField(\(textFieldHeight))]-\(textFieldMargin)-[cardNumberSeparatorView(\(separatorViewHeight))]-\(textFieldMargin)-[expirationMonthYearSeparatorLabel(\(textFieldHeight))]", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(cellPadding)-[cardNumberTextField(\(textFieldHeight))]-\(textFieldMargin)-[cardNumberSeparatorView(\(separatorViewHeight))]-\(textFieldMargin)-[expirationYearTextField(\(textFieldHeight))]", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(cellPadding)-[cardNumberTextField(\(textFieldHeight))]-\(textFieldMargin)-[cardNumberSeparatorView(\(separatorViewHeight))]-\(textFieldMargin)-[cvcTextField(\(textFieldHeight))]", options: [], metrics: nil, views: views)
if let label = titleLabel, let text = label.text where !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(cellPadding)-[titleLabel]-\(cellPadding)-|", options: [], metrics: nil, views: ["titleLabel": label])
dynamicConstraints.append(NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: self.contentView, attribute: .CenterY, multiplier: 1, constant: 0))
}
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
if let titleLabel = titleLabel, let text = titleLabel.text where !text.isEmpty {
views["label"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView]-[label]-[cardNumberTextField]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView]-[label]-[expirationMonthTextField(\(expirationMonthTextFieldWidth))]-\(textFieldMargin * 2.0)-[expirationMonthYearSeparatorLabel(\(expirationMonthYearLabelWidth))]-[expirationYearTextField(\(expirationYearTextFieldWidth))]-\(textFieldMargin * 2.0)-[cvcTextField]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView]-[label]-[cardNumberSeparatorView]-|", options: [], metrics: nil, views: views)
} else {
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView]-[cardNumberTextField]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView]-[expirationMonthTextField(\(expirationMonthTextFieldWidth))]-\(textFieldMargin * 2.0)-[expirationMonthYearSeparatorLabel(\(expirationMonthYearLabelWidth))]-[expirationYearTextField(\(expirationYearTextFieldWidth))]-\(textFieldMargin * 2.0)-[cvcTextField]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView]-[cardNumberSeparatorView]-|", options: [], metrics: nil, views: views)
}
} else {
if let titleLabel = titleLabel, let text = titleLabel.text where !text.isEmpty {
views["label"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-[cardNumberTextField]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-[expirationMonthTextField(\(expirationMonthTextFieldWidth))]-\(textFieldMargin * 2.0)-[expirationMonthYearSeparatorLabel(\(expirationMonthYearLabelWidth))]-[expirationYearTextField(\(expirationYearTextFieldWidth))]-\(textFieldMargin * 2.0)-[cvcTextField]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-[cardNumberSeparatorView]-|", options: [], metrics: nil, views: views)
let multiplier = (row as? CreditCardRowConformance)?.dataSectionWidthPercentage ?? 0.3
dynamicConstraints.append(NSLayoutConstraint(item: cardNumberTextField, attribute: .Width, relatedBy: (row as? CreditCardRowConformance)?.dataSectionWidthPercentage != nil ? .Equal : .GreaterThanOrEqual, toItem: contentView, attribute: .Width, multiplier: multiplier, constant: 0.0))
} else {
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[cardNumberTextField]-|", options: .AlignAllLeft, metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[expirationMonthTextField(\(expirationMonthTextFieldWidth))]-\(textFieldMargin * 2.0)-[expirationMonthYearSeparatorLabel(\(expirationMonthYearLabelWidth))]-[expirationYearTextField(\(expirationYearTextFieldWidth))]-\(textFieldMargin * 2.0)-[cvcTextField]-|", options: [], metrics: nil, views: views)
dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[cardNumberSeparatorView]-|", options: .AlignAllLeft, metrics: nil, views: views)
}
}
contentView.addConstraints(dynamicConstraints)
super.updateConstraints()
}
public func textFieldDidChange(textField: UITextField) {
guard let textValue = textField.text else {
switch (textField) {
case cardNumberTextField:
row.value?.cardNumber = nil
case expirationMonthTextField:
row.value?.expirationMonth = nil
case expirationYearTextField:
row.value?.expirationYear = nil
case cvcTextField:
row.value?.cvc = nil
default:
break
}
return
}
guard !textValue.isEmpty else {
switch (textField) {
case cardNumberTextField:
row.value?.cardNumber = nil
case expirationMonthTextField:
row.value?.expirationMonth = nil
case expirationYearTextField:
row.value?.expirationYear = nil
case cvcTextField:
row.value?.cvc = nil
default:
break
}
return
}
switch (textField) {
case cardNumberTextField:
row.value?.cardNumber = textValue
case expirationMonthTextField:
row.value?.expirationMonth = textValue
case expirationYearTextField:
row.value?.expirationYear = textValue
case cvcTextField:
row.value?.cvc = textValue
default:
break
}
}
//MARK: TextFieldDelegate
public func textFieldDidBeginEditing(textField: UITextField) {
formViewController()?.beginEditing(self)
formViewController()?.textInputDidBeginEditing(textField, cell: self)
}
public func textFieldDidEndEditing(textField: UITextField) {
formViewController()?.endEditing(self)
formViewController()?.textInputDidEndEditing(textField, cell: self)
textFieldDidChange(textField)
}
public func textFieldShouldReturn(textField: UITextField) -> Bool {
return formViewController()?.textInputShouldReturn(textField, cell: self) ?? true
}
public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == expirationMonthTextField
|| textField == expirationYearTextField {
return false;
}
return formViewController()?.textInputShouldEndEditing(textField, cell: self) ?? true
}
public func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}
public func textFieldShouldClear(textField: UITextField) -> Bool {
return formViewController()?.textInputShouldClear(textField, cell: self) ?? true
}
public func textFieldShouldEndEditing(textField: UITextField) -> Bool {
return formViewController()?.textInputShouldEndEditing(textField, cell: self) ?? true
}
// MARK: Pickers
public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == pickerMonth {
return self.months.count + 1 ?? 0
} else {
return self.years.count + 1 ?? 0
}
}
public func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if row == 0 {
return "Select..."
} else {
if pickerView == pickerMonth {
return "\(self.months[row - 1]) - \(self.monthsName[row - 1])"
} else {
return self.years[row - 1]
}
}
}
public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == pickerMonth {
// self.row.value?.expirationMonth = self.months[row]
if row > 0 {
expirationMonthTextField.text = self.months[row - 1]
} else {
expirationMonthTextField.text = nil
}
} else {
// self.row.value?.expirationYear = self.years[row]
if row > 0 {
expirationYearTextField.text = self.years[row - 1]
} else {
expirationYearTextField.text = nil
}
}
}
}
public class _CreditCardRow<T:Equatable, Cell:CellType where Cell: BaseCell, Cell: TypedCellType, Cell: CreditCardCellConformance, Cell.Value == T>: Row<T, Cell>, CreditCardRowConformance, KeyboardReturnHandler {
/// Configuration for the keyboardReturnType of this row
public var keyboardReturnType: KeyboardReturnTypeConfiguration?
/// The percentage of the cell that should be occupied by the postal address
public var dataSectionWidthPercentage: CGFloat?
/// The textColor for the textField's placeholder
public var placeholderColor: UIColor?
/// The placeholder for the cardNumber textField
public var cardNumberPlaceholder: String?
/// The placeholder for the zip textField
public var expirationMonthPlaceholder: String?
/// The placeholder for the expirationYear textField
public var expirationYearPlaceholder: String?
/// The placeholder for the cvc textField
public var cvcPlaceholder: String?
/// A formatter to be used to format the user's input for cardNumber
public var cardNumberFormatter: NSFormatter?
/// If the formatter should be used while the user is editing the cardNumber.
public var cardNumberUseFormatterDuringInput: Bool
public required init(tag: String?) {
cardNumberUseFormatterDuringInput = false
super.init(tag: tag)
}
}
/// A CreditCard valued row where the user can enter a postal address.
public final class CreditCardRow: _CreditCardRow<CreditCard, CreditCardCell<CreditCard>>, RowType {
public required init(tag: String? = nil) {
super.init(tag: tag)
/*onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}*/
}
}
// Extension that adds the maxLenght to a UITextField
private var maxLengthDictionary = [UITextField:Int]()
extension UITextField {
@IBInspectable var ccMaxLength: Int {
get {
if let length = maxLengthDictionary[self] {
return length
} else {
return Int.max
}
}
set {
maxLengthDictionary[self] = newValue
addTarget(self, action: #selector(UITextField.checkMaxLength(_:)), forControlEvents: UIControlEvents.EditingChanged)
}
}
func checkMaxLength(sender: UITextField) {
let newText = sender.text
if newText?.characters.count > ccMaxLength {
let cursorPosition = selectedTextRange
text = (newText! as NSString).substringWithRange(NSRange(location: 0, length: ccMaxLength))
selectedTextRange = cursorPosition
}
}
}
|
mit
|
7948fb1da8e0b61272ccecebfb48be8a
| 46.105339 | 409 | 0.668086 | 5.972192 | false | false | false | false |
epv44/TwitchAPIWrapper
|
Sources/TwitchAPIWrapper/Models/CodeStatus.swift
|
1
|
1133
|
//
// CodeStatus.swift
// TwitchAPIWrapper
//
// Created by Eric Vennaro on 5/8/21.
//
import Foundation
/// Code status response: https://dev.twitch.tv/docs/api/reference/#get-code-status
public struct CodeStatusResponse: Codable {
public let codeStatuses: [CodeStatus]
private enum CodingKeys: String, CodingKey {
case codeStatuses = "data"
}
}
/// Code status options mirroring: https://dev.twitch.tv/docs/api/reference/#get-code-status
public enum CodeSuccessStatus: String, Codable {
case successfullyRedeemed = "SUCCESSFULLY_REDEEMED"
case alreadyClaimed = "ALREADY_CLAIMED"
case expired = "EXPIRED"
case userNotEligible = "USER_NOT_ELIGIBLE"
case notFound = "NOT_FOUND"
case inactive = "INACTIVE"
case unused = "UNUSED"
case incorrectFormat = "INCORRECT_FORMAT"
case internalError = "INTERNAL_ERROR"
}
/// Code status object returned from the server as part of the `CodeStatusResponse` https://dev.twitch.tv/docs/api/reference/#get-code-status
public struct CodeStatus: Codable, Equatable {
public let code: String
public let status: CodeSuccessStatus
}
|
mit
|
ea9b4e86595a54ce1602052e88c9ea5e
| 30.472222 | 141 | 0.72286 | 3.76412 | false | false | false | false |
Poligun/NihonngoSwift
|
Nihonngo/EditExampleViewController.swift
|
1
|
2779
|
//
// EditExampleViewController.swift
// Nihonngo
//
// Created by ZhaoYuhan on 15/1/9.
// Copyright (c) 2015年 ZhaoYuhan. All rights reserved.
//
import UIKit
class EditExampleViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
private let textViewCellIdentifier = "TextViewCell"
private var tableView: UITableView!
private var example: String!
private var translation: String!
private var onSaveFunc: ((newExample: String, newTranslation: String) -> Void)?
convenience init(example: String, translation: String, onSave: ((newExample: String, newTranslation: String) -> Void)?) {
self.init()
self.example = example
self.translation = translation
self.onSaveFunc = onSave
}
override func viewDidLoad() {
tableView = UITableView(frame: self.view.bounds, style: .Grouped)
tableView.setTranslatesAutoresizingMaskIntoConstraints(false)
tableView.rowHeight = 120.0
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
tableView.registerClass(TextViewCell.self, forCellReuseIdentifier: textViewCellIdentifier)
navigationItem.title = "编辑例子"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .Plain, target: self, action: "onSaveButtonClick:")
}
override func viewWillAppear(animated: Bool) {
tableView.reloadData()
}
func onSaveButtonClick(sender: AnyObject) {
view.endEditing(false)
onSaveFunc?(newExample: example, newTranslation: translation)
navigationController?.popViewControllerAnimated(true)
}
// TableView DataSource & Delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? "例子" : "翻译"
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textViewCellIdentifier, forIndexPath: indexPath) as TextViewCell
if indexPath.section == 0 {
cell.setText(example, onEndEditing: {(textView: UITextView) -> Void in
self.example = textView.text
})
} else {
cell.setText(translation, onEndEditing: {(textView: UITextView) -> Void in
self.translation = textView.text
})
}
return cell
}
}
|
mit
|
9c2439349a5c53a5b68d8110cd33f6d3
| 33.4625 | 131 | 0.663402 | 5.19209 | false | false | false | false |
dshamany/CIToolbox
|
CIToolbox/SalesQuestionaire.swift
|
1
|
11676
|
//
// SalesQuestionaire.swift
// CIToolbox
//
// Created by Daniel Shamany on 7/1/17.
// Copyright © 2017 Daniel Shamany. All rights reserved.
//
import UIKit
class SalesQuestionaire: UIViewController {
@IBOutlet weak var question: UILabel!
@IBOutlet weak var answer: UITextField!
@IBOutlet weak var hasLEDOutlet: UISwitch!
@IBOutlet weak var removedAsbestosOutlet: UISwitch!
@IBOutlet weak var properInsulationOutlet: UISwitch!
@IBOutlet weak var qualifyingQuestion: UILabel!
@IBOutlet weak var qualifyingAnswer: UITextField!
var currentPreliminary = 0
var currentQualifying = 0
@IBOutlet weak var nextBarButton: UIBarButtonItem!
@IBOutlet weak var previousSection: UIButton!
@IBOutlet weak var nextSection: UIButton!
@IBOutlet weak var questionaireView: UIVisualEffectView!
@IBOutlet weak var questionaireViewConstraintY: NSLayoutConstraint!
@IBOutlet weak var energyAuditView: UIVisualEffectView!
@IBOutlet weak var qualifyingQuestionsView: UIVisualEffectView!
//MARK: Energy Audit Components
let hasLEDString = "Has LED"
let asbestosRemovedString = "Asbestos Removed"
let properInsulationString = "Proper Insulation"
var energyAuditAnswers = [String : String]()
@IBAction func hasLED(_ sender: UISwitch) {
if (sender.isOn){
energyAuditAnswers["\(hasLEDString)"] = "YES"
} else {
energyAuditAnswers["\(hasLEDString)"] = "NO"
}
}
@IBAction func removedAspestos(_ sender: UISwitch) {
if (sender.isOn){
energyAuditAnswers["\(asbestosRemovedString)"] = "YES"
} else {
energyAuditAnswers["\(asbestosRemovedString)"] = "NO"
}
}
@IBAction func properInsulation(_ sender: UISwitch) {
if (sender.isOn){
energyAuditAnswers["\(properInsulationString)"] = "YES"
} else {
energyAuditAnswers["\(properInsulationString)"] = "NO"
}
}
var selectedView = 1
let preliminary = [
"1 - How long have you owned your home?",
"2 - How long do you intend to live in this home?",
"3 - Who is on the title of the home and who is on the utility bill?",
"4 - What is your highest and lowest monthly electric bill?",
"5 - What is your highest and lowest monthly gas bill?",
"6 - When was the last time you had a safety inspection done in the home for Asbestos or Carbon Monoxide?",
"7 - Does anyone in the home have asthma, allergies, or any health problems?"
]
let qualifying = [
"1 - Are you currently employed?",
"2 - Would you rate your FICO score high, medium or low?",
"3 - Have you had a bankruptcy in the past five years?",
"4 - Do you receive any form of taxable income?",
"5 - Are you currently up-to-date with your property taxes and mortgage?",
"6 - Are you currently on any discount program on your utilities?",
"7 - Have you discussed energy discount programs with any other company?",
"8 - How do you currently pay your utility bill?"
]
var preliminaryAnswers = ["", "", "", "", "", "", ""]
var qualifyingAnswers = ["", "", "", "", "", "", "", ""]
func setInterface(){
nextBarButton.title = ""
answer.becomeFirstResponder()
questionaireView.layer.cornerRadius = 10
energyAuditView.layer.cornerRadius = 10
qualifyingQuestionsView.layer.cornerRadius = 10
questionaireView.layer.masksToBounds = true
energyAuditView.layer.masksToBounds = true
qualifyingQuestionsView.layer.masksToBounds = true
question.text = preliminary[0]
qualifyingQuestion.text = qualifying[0]
qualifyingQuestionsView.isHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
setInterface()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addQuestionaireData(){
let cc = Current.Customer
if (!cc.Preliminary_Questions.isEmpty) { cc.Preliminary_Questions.removeAll() }
if (!cc.Qualifying_Questions.isEmpty) { cc.Qualifying_Questions.removeAll() }
if (!cc.Energy_Audit.isEmpty) { cc.Energy_Audit.removeAll() }
for index in 0..<preliminary.count {
if (Current.Customer.Preliminary_Questions.isEmpty) { Current.Customer.Preliminary_Questions.removeAll() }
Current.Customer.Preliminary_Questions[preliminary[index]] = { () -> String in
if (preliminaryAnswers[index] == ""){
return "n/a"
} else {
return preliminaryAnswers[index]
}
}()
}
for index in 0..<qualifying.count {
Current.Customer.Qualifying_Questions[qualifying[index]] = { () -> String in
if (qualifyingAnswers[index] == ""){
return "n/a"
} else {
return qualifyingAnswers[index]
}
}()
}
Current.Customer.Energy_Audit = energyAuditAnswers as Dictionary
}
@IBAction func nextPage(_ sender: Any){
self.view.endEditing(true)
addQuestionaireData()
performSegue(withIdentifier: "toBill", sender: nil)
}
@IBAction func tapAnywhere(_ sender: Any){
self.view.endEditing(true)
}
func enableQuestionaireView(_ sender: Any) {
answer.becomeFirstResponder()
UIView.animate(withDuration: 0.4, animations: {
self.nextBarButton.title = ""
self.questionaireView.alpha = 1.0
self.energyAuditView.alpha = 0.5
self.qualifyingQuestionsView.isHidden = true
})
}
func enableEnergyAuditView(_ sender: Any) {
UIView.animate(withDuration: 0.4, animations: {
self.nextBarButton.title = " "
self.energyAuditView.alpha = 1.0
self.qualifyingQuestionsView.alpha = 0.5
self.qualifyingQuestionsView.isHidden = false
self.questionaireView.isHidden = false
self.questionaireView.alpha = 0.5
})
}
func enableQualifyingQuestionsView(_ sender: Any) {
qualifyingAnswer.becomeFirstResponder()
UIView.animate(withDuration: 0.4, animations: {
self.nextBarButton.title = "Next"
self.qualifyingQuestionsView.alpha = 1.0
self.energyAuditView.alpha = 0.5
self.questionaireView.isHidden = true
})
}
@IBAction func nextQuestion(_ sender: Any) {
preliminaryAnswers[currentPreliminary] = answer.text!
currentPreliminary += 1
if (currentPreliminary < preliminary.count){
question.text = preliminary[currentPreliminary]
answer.text = preliminaryAnswers[currentPreliminary]
} else if (currentPreliminary >= preliminary.count){
currentPreliminary = preliminary.count - 1
self.view.endEditing(true)
nextSection(self)
}
}
@IBAction func previousQuestion(_ sender: Any) {
preliminaryAnswers[currentPreliminary] = answer.text!
currentPreliminary -= 1
if (currentPreliminary > 0){
question.text = preliminary[currentPreliminary]
answer.text = preliminaryAnswers[currentPreliminary]
} else if (currentPreliminary <= 0) {
currentPreliminary = 0
question.text = preliminary[currentPreliminary]
answer.text = preliminaryAnswers[currentPreliminary]
}
}
@IBAction func qualifyingPreviousQuestion(_ sender: Any) {
qualifyingAnswers[currentQualifying] = qualifyingAnswer.text!
currentQualifying -= 1
if (currentQualifying > 0){
qualifyingQuestion.text = qualifying[currentQualifying]
qualifyingAnswer.text = qualifyingAnswers[currentQualifying]
} else if (currentQualifying <= 0) {
currentQualifying = 0
qualifyingQuestion.text = qualifying[currentQualifying]
qualifyingAnswer.text! = qualifyingAnswers[currentQualifying]
}
}
@IBAction func qualifyingNextQuestion(_ sender: Any) {
qualifyingAnswers[currentQualifying] = qualifyingAnswer.text!
currentQualifying += 1
if (currentQualifying < qualifying.count){
qualifyingQuestion.text = qualifying[currentQualifying]
qualifyingAnswer.text = qualifyingAnswers[currentQualifying]
} else if (currentQualifying >= qualifying.count){
currentQualifying = qualifying.count - 1
self.view.endEditing(true)
nextPage(self)
}
}
func selectView(){
switch(selectedView){
case 1:
enableQuestionaireView(self)
break
case 2:
enableEnergyAuditView(self)
break
case 3:
enableQualifyingQuestionsView(self)
break
default:
break
}
}
@IBAction func nextSection(_ sender: Any){
self.view.endEditing(true)
if (selectedView < 3){
selectedView += 1
self.questionaireViewConstraintY.constant -= 260
selectView()
} else {
return
}
}
@IBAction func previousSection(_ sender: Any){
self.view.endEditing(true)
if (selectedView > 1){
selectedView -= 1
self.questionaireViewConstraintY.constant += 260
selectView()
} else {
self.questionaireViewConstraintY.constant = 0
selectView()
}
}
//MARK: Keyboard Functions
func textFieldShouldReturn(_ textField: UITextField) -> Bool{
if(selectedView == 1){
nextQuestion(self)
} else if (selectedView == 3){
qualifyingNextQuestion(self)
}
return true
}
func keyboardWillShow(notification: NSNotification){
if (Global.isLandscape){
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue{
questionaireViewConstraintY.constant -= (keyboardSize.height/2)
}
} else {
return
}
}
func keyboardWillHide(notification: NSNotification){
if (Global.isLandscape){
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue{
questionaireViewConstraintY.constant += (keyboardSize.height/2)
}
} else if (Global.isLandscape && selectedView == 1) {
questionaireViewConstraintY.constant = 0
} else if (Global.isLandscape && selectedView == 3) {
questionaireViewConstraintY.constant = -500
}
}
}
|
gpl-3.0
|
0c51e45791fa51773fc11ef72cf0a1f1
| 35.484375 | 151 | 0.613448 | 4.673739 | false | false | false | false |
FelixZhu/FZWebViewProgress
|
FZWebViewProgress/FZWebViewProgressView.swift
|
1
|
2723
|
//
// SwiftWebViewProgressView.swift
// SwiftWebViewProgress
//
// Created by Felix Zhu on 15/11/23.
// Copyright © 2015年 Felix Zhu. All rights reserved.
//
import UIKit
public class FZWebViewProgressView: UIView {
var progress: Float = 0.0
var progressBarView: UIView!
var barAnimationDuration: NSTimeInterval!
var fadeAnimationDuration: NSTimeInterval!
var fadeOutDelay: NSTimeInterval!
// MARK: Initializer
override init(frame: CGRect) {
super.init(frame: frame)
configureViews()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func awakeFromNib() {
super.awakeFromNib()
configureViews()
}
// MARK: Private Method
private func configureViews() {
self.userInteractionEnabled = false
self.autoresizingMask = .FlexibleWidth
progressBarView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: self.bounds.height))
progressBarView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
var tintColor = UIColor(red: 22/255, green: 126/255, blue: 251/255, alpha: 1.0)
if let color = UIApplication.sharedApplication().delegate?.window??.tintColor {
tintColor = color
}
progressBarView.backgroundColor = tintColor
self.addSubview(progressBarView)
barAnimationDuration = 0.1
fadeAnimationDuration = 0.27
fadeOutDelay = 0.1
}
// MARK: Public Method
func setProgress(progress: Float, animated: Bool = false) {
let isGrowing = progress > 0.0
UIView.animateWithDuration((isGrowing && animated) ? barAnimationDuration : 0.0, delay: 0.0, options: .CurveEaseInOut, animations: {
var frame = self.progressBarView.frame
frame.size.width = CGFloat(progress) * self.bounds.size.width
self.progressBarView.frame = frame
}, completion: nil)
if progress >= 1.0 {
UIView.animateWithDuration(animated ? fadeAnimationDuration : 0.0, delay: fadeOutDelay, options: .CurveEaseInOut, animations: {
self.progressBarView.alpha = 0.0
}, completion: {
completed in
var frame = self.progressBarView.frame
frame.size.width = 0
self.progressBarView.frame = frame
})
} else {
UIView.animateWithDuration(animated ? fadeAnimationDuration : 0.0, delay: 0.0, options: .CurveEaseInOut, animations: {
self.progressBarView.alpha = 1.0
}, completion: nil)
}
}
}
|
mit
|
8b6fe8bface6a6a0304c56848114065d
| 34.789474 | 140 | 0.620956 | 4.797178 | false | false | false | false |
allenngn/firefox-ios
|
Client/Frontend/Browser/BackForwardListViewController.swift
|
22
|
2169
|
/* 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 UIKit
import WebKit
class BackForwardListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var listData: [WKBackForwardListItem]?
var tabManager: TabManager!
override func viewDidLoad() {
let toolbar = UIToolbar()
view.addSubview(toolbar)
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "SELdidClickDone")
let spacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
toolbar.items = [doneItem, spacer]
let listTableView = UITableView()
listTableView.dataSource = self
listTableView.delegate = self
view.addSubview(listTableView)
toolbar.snp_makeConstraints { make in
let topLayoutGuide = self.topLayoutGuide as! UIView
make.top.equalTo(topLayoutGuide.snp_bottom)
make.left.right.equalTo(self.view)
return
}
listTableView.snp_makeConstraints { make in
make.top.equalTo(toolbar.snp_bottom)
make.left.right.bottom.equalTo(self.view)
}
}
func SELdidClickDone() {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Table view
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listData?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let item = listData![indexPath.item]
cell.textLabel?.text = item.title ?? item.URL.absoluteString
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tabManager.selectedTab?.goToBackForwardListItem(listData![indexPath.item])
dismissViewControllerAnimated(true, completion: nil)
}
}
|
mpl-2.0
|
8f0c4432383f3e181c9a7b2c224a9102
| 35.762712 | 128 | 0.690641 | 5.13981 | false | false | false | false |
pixelmaid/DynamicBrushes
|
swift/Palette-Knife/util/RequestHandler.swift
|
1
|
8705
|
//
// RequestHandler.swift
// PaletteKnife
//
// Created by JENNIFER MARY JACOBS on 4/13/17.
// Copyright © 2017 pixelmaid. All rights reserved.
//
import Foundation
import SwiftyJSON
class RequestHandler{
static let saveManager = SaveManager();
static let socketManager = SocketManager();
static var requestQueue = [Request]()
static var dataQueue = [(String,JSON?)]()
static var dataEvent = Event<(String,JSON?)>();
static let socketKey = NSUUID().uuidString
static let storageKey = NSUUID().uuidString
static let sharedInstance = RequestHandler()
static var activeItem:Request?
static func addRequest(requestData:Request){
requestQueue.append(requestData);
if(activeItem == nil){
checkRequest();
}
}
init(){
_ = RequestHandler.socketManager.dataEvent.addHandler(target:self,handler: RequestHandler.socketDataHandler, key:RequestHandler.socketKey)
_ = RequestHandler.saveManager.dataEvent.addHandler(target:self,handler: RequestHandler.saveDataHandler, key:RequestHandler.storageKey)
}
static func checkRequest(){
#if DEBUG
print("checking request, activeitem: \(RequestHandler.activeItem == nil), requestQueue: \(requestQueue.count), dataQueue: \(dataQueue.count)")
for val in requestQueue {
print("request: \(val.action,val.requester, val.data)")
}
#endif
if(RequestHandler.activeItem == nil){
if requestQueue.count>0 {
sharedInstance.handleRequest();
}
else if dataQueue.count>0{
sharedInstance.handleData();
}
}
}
static func emptyQueue(){
RequestHandler.activeItem = nil
requestQueue.removeAll();
RequestHandler.socketManager.requestEvent.removeAllHandlers();
RequestHandler.saveManager.requestEvent.removeAllHandlers();
}
private func handleRequest(){
if(RequestHandler.requestQueue.count>0){
let request = RequestHandler.requestQueue.removeFirst()
RequestHandler.activeItem = request as Request
switch(RequestHandler.activeItem!.target){
case "socket":
_ = RequestHandler.socketManager.requestEvent.addHandler(target:self, handler:RequestHandler.socketRequestHandler,key:RequestHandler.socketKey)
switch RequestHandler.activeItem!.action{
case "connect":
RequestHandler.socketManager.connect();
break;
case "disconnect":
RequestHandler.socketManager.disconnect();
break;
case "send_storage_data":
let data = RequestHandler.activeItem!.data!
var send_data:JSON = [:]
send_data["data"] = data;
send_data["type"] = JSON("storage_data")
RequestHandler.socketManager.sendData(data: send_data);
break;
case "authoring_response":
let data = RequestHandler.activeItem!.data!
RequestHandler.socketManager.sendData(data: data);
break;
case "synchronize":
let data = RequestHandler.activeItem!.data!
let requester = RequestHandler.activeItem!.requester as! ViewController;
let currentBehaviorName = requester.currentBehaviorName;
let currentBehaviorFile = requester.currentBehaviorFile;
var send_data:JSON = [:]
send_data["data"] = data;
send_data["currentBehaviorName"] = JSON(currentBehaviorName)
send_data["currentFile"] = JSON(currentBehaviorFile)
send_data["type"] = JSON("synchronize")
RequestHandler.socketManager.sendData(data: send_data);
break
default:
break;
}
break;
case "storage":
_ = RequestHandler.saveManager.requestEvent.addHandler(target:self, handler:RequestHandler.saveRequestHandler,key:RequestHandler.storageKey)
switch RequestHandler.activeItem!.action{
case "configure":
RequestHandler.saveManager.configure();
break;
case "upload":
RequestHandler.saveManager.uploadFile(uploadData:RequestHandler.activeItem!.data!)
break;
case "upload_image":
RequestHandler.saveManager.uploadImage(uploadData:RequestHandler.activeItem!.data!)
break;
case "download":
RequestHandler.saveManager.downloadFile(downloadData:RequestHandler.activeItem!.data!)
break;
case "download_project_file":
RequestHandler.saveManager.downloadProjectFile(downloadData:RequestHandler.activeItem!.data!)
break;
case "filelist":
let targetFolder = RequestHandler.activeItem!.data!["targetFolder"].stringValue
let list_type = RequestHandler.activeItem!.data!["list_type"].stringValue
RequestHandler.saveManager.accessFileList(targetFolder: targetFolder,list_type:list_type, uploadData: nil)
break;
default:
break;
}
break;
default:
break;
}
}
else{
RequestHandler.checkRequest();
}
}
private func handleData(){
if(RequestHandler.dataQueue.count>0){
let data = RequestHandler.dataQueue.removeFirst();
RequestHandler.dataEvent.raise(data: data);
}
RequestHandler.checkRequest();
}
private func socketRequestHandler(data:(String,JSON?), key:String) {
#if DEBUG
print("socket request handler called \(String(describing: RequestHandler.activeItem))")
#endif
if(RequestHandler.activeItem != nil){
RequestHandler.socketManager.requestEvent.removeHandler(key: RequestHandler.socketKey)
RequestHandler.activeItem?.requester.processRequest(data:data)
RequestHandler.activeItem = nil;
RequestHandler.checkRequest();
}
else {
#if DEBUG
print("error, socket request does not exist");
#endif
}
}
private func saveRequestHandler(data:(String,JSON?), key:String) {
#if DEBUG
print("save request handler called \(String(describing: RequestHandler.activeItem),data.0)")
#endif
if(RequestHandler.activeItem != nil){
let activeItem = RequestHandler.activeItem;
RequestHandler.saveManager.requestEvent.removeHandler(key: RequestHandler.storageKey)
activeItem?.requester.processRequest(data:data)
RequestHandler.activeItem = nil;
RequestHandler.checkRequest();
}
else {
#if DEBUG
print("error, save request does not exist");
#endif
}
}
private func saveDataHandler(data:(String,JSON?), key:String){
#if DEBUG
print("save data handler called \(data.0,data.1?["type"].stringValue,RequestHandler.activeItem == nil )")
#endif
//RequestHandler.dataQueue.append(data);
RequestHandler.checkRequest();
}
private func socketDataHandler(data:(String,JSON?), key:String){
if(data.1 != nil){
#if DEBUG
print("socket data handler called \(data.0,data.1?["type"].stringValue,RequestHandler.activeItem == nil )")
#endif
}
RequestHandler.dataQueue.append(data);
RequestHandler.checkRequest();
}
}
struct Request{
let target:String
let action:String
let data:JSON?
let requester:Requester
}
protocol Requester{
func processRequest(data:(String,JSON?))
func processRequestHandler(data: (String, JSON?), key: String)
}
|
mit
|
5825637c5f97940ccb2624acaaeca5a3
| 33.539683 | 159 | 0.563189 | 5.565217 | false | false | false | false |
tjw/swift
|
test/SILOptimizer/definite_init_objc_factory_init.swift
|
5
|
4151
|
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/../IDE/Inputs/custom-modules %s -emit-sil -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import ImportAsMember.Class
// CHECK-LABEL: sil shared [serializable] [thunk] @$SSo4HiveC5queenABSgSo3BeeCSg_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive>
func testInstanceTypeFactoryMethod(queen: Bee) {
// CHECK: bb0([[QUEEN:%[0-9]+]] : $Optional<Bee>, [[HIVE_META:%[0-9]+]] : $@thick Hive.Type):
// CHECK-NEXT: [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK-NEXT: [[FACTORY:%[0-9]+]] = objc_method [[HIVE_META_OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: [[HIVE:%[0-9]+]] = apply [[FACTORY]]([[QUEEN]], [[HIVE_META_OBJC]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: release_value [[QUEEN]]
// CHECK-NEXT: return [[HIVE]] : $Optional<Hive>
var hive1 = Hive(queen: queen)
}
extension Hive {
// FIXME: This whole approach is wrong. This should be a factory
// initializer, not a convenience initializer, which means it does
// not have an initializing entry point at all.
// CHECK-LABEL: sil hidden @$SSo4HiveC027definite_init_objc_factory_C0E10otherQueenABSo3BeeC_tcfc : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive
convenience init(otherQueen other: Bee) {
// CHECK: [[SELF_ADDR:%[0-9]+]] = alloc_stack $Hive
// CHECK: store [[OLD_SELF:%[0-9]+]] to [[SELF_ADDR]]
// CHECK: [[META:%[0-9]+]] = value_metatype $@thick Hive.Type, [[OLD_SELF]] : $Hive
// CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: [[FACTORY:%[0-9]+]] = objc_method [[OBJC_META]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: apply [[FACTORY]]([[QUEEN:%[0-9]+]], [[OBJC_META]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: store [[NEW_SELF:%[0-9]+]] to [[SELF_ADDR]]
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick Hive.Type, [[OLD_SELF]] : $Hive
// CHECK: dealloc_partial_ref [[OLD_SELF]] : $Hive, [[METATYPE]] : $@thick Hive.Type
// CHECK: dealloc_stack [[SELF_ADDR]]
// CHECK: return [[NEW_SELF]]
self.init(queen: other)
}
convenience init(otherFlakyQueen other: Bee) throws {
try self.init(flakyQueen: other)
}
}
extension SomeClass {
// SIL-LABEL: sil hidden @_TFE16import_as_memberCSo9SomeClasscfT6doubleSd_S0_
// SIL: bb0([[DOUBLE:%[0-9]+]] : $Double
// SIL-NOT: value_metatype
// SIL: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
// SIL: apply [[FNREF]]([[DOUBLE]])
convenience init(double: Double) {
self.init(value: double)
}
}
class SubHive : Hive {
// CHECK-LABEL: sil hidden @$S027definite_init_objc_factory_B07SubHiveC20delegatesToInheritedACyt_tcfc : $@convention(method) (@owned SubHive) -> @owned SubHive
convenience init(delegatesToInherited: ()) {
// CHECK: [[UPCAST:%.*]] = upcast %0 : $SubHive to $Hive
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick Hive.Type, [[UPCAST]] : $Hive
// CHECK: [[OBJC:%.*]] = thick_to_objc_metatype [[METATYPE]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: [[METHOD:%.*]] = objc_method [[OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?
// CHECK: apply [[METHOD]]({{.*}}, [[OBJC]])
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick SubHive.Type, %0 : $SubHive
// CHECK-NEXT: dealloc_partial_ref %0 : $SubHive, [[METATYPE]] : $@thick SubHive.Type
// CHECK: return {{%.*}} : $SubHive
self.init(queen: Bee())
}
}
|
apache-2.0
|
e388922ade6c28f3b6bb66086e614ce2
| 57.464789 | 265 | 0.642737 | 3.363857 | false | false | false | false |
shuoli84/RxSwift
|
RxSwift/RxSwift/ObserverOf.swift
|
17
|
1934
|
//
// ObserverOf.swift
// Rx
//
// Created by Krunoslav Zaher on 2/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
public struct ObserverOf<ElementType> {
typealias Element = ElementType
private typealias ObserverSinkType = (Event<Element>) -> Void
private let observer: ObserverSinkType
private let instance: AnyObject?
/// Construct an instance whose `on(event)` calls `observer.on(event)`
public init<O : ObserverType where O.Element == Element>(_ observer: O) {
var observerReference = observer // this is because swift compiler crashing
self.instance = observerReference
self.observer = { e in
return observerReference.on(e)
}
}
/// Send `event` to this observer.
public func on(event: Event<Element>) {
return observer(event)
}
}
public func dispatch<Element, S: SequenceType where S.Generator.Element == ObserverOf<Element>>(event: Event<Element>, observers: S?) {
if let observers = observers {
for o in observers {
o.on(event)
}
}
}
public func dispatchNext<Element, S: SequenceType where S.Generator.Element == ObserverOf<Element>>(element: Element, observers: S?) {
if let observers = observers {
let event = Event.Next(RxBox(element))
for o in observers {
o.on(event)
}
}
}
public func dispatch<S: SequenceType, O: ObserverType where S.Generator.Element == O>(event: Event<O.Element>, observers: S?) {
if let observers = observers {
for o in observers {
o.on(event)
}
}
}
public func dispatchNext<S: SequenceType, O: ObserverType where S.Generator.Element == O>(element: O.Element, observers: S?) {
if let observers = observers {
let event = Event.Next(RxBox(element))
for o in observers {
o.on(event)
}
}
}
|
mit
|
961ddcaa04f9c41c99cb1b71633b6b18
| 27.880597 | 135 | 0.633402 | 4.150215 | false | false | false | false |
alanwangke213/ALRefresher
|
ALRefresher/ALRefresher/ViewController.swift
|
1
|
1011
|
//
// OnePageViewController.swift
// BoomTest
//
// Created by 王可成 on 15/12/17.
// Copyright © 2015年 AL. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var refresher: ALRefresher?
//MARK: - ------------------
override func viewDidLoad() {
super.viewDidLoad()
//增加一组
//只需要设置refresher的frame就行,根据宽度和高度来计算小方块的宽高
let refresher = ALRefresher(frame: CGRect(x: 100, y: 200, width: 150, height: 150))
refresher.squareColor = UIColor.lightGrayColor()
//修改动画时间
refresher.duration = 0.4
refresher.timeRatio = 0.3
self.refresher = refresher
view.addSubview(refresher)
}
@IBAction func didClickStartBtn() {
refresher!.start()
}
@IBAction func didClickStopBtn() {
refresher!.stop()
}
@IBAction func didClickResetBtn() {
refresher!.reset()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
refresher!.reset()
}
}
|
mit
|
2307d51c0860a281d6905689a0909a6f
| 18.020408 | 85 | 0.686695 | 3.328571 | false | false | false | false |
caronae/caronae-ios
|
Caronae/Ride/MyRidesViewController.swift
|
1
|
6993
|
import UIKit
import RealmSwift
class MyRidesViewController: RideListController {
var notificationTokens: [NotificationToken?] = []
var unreadNotifications: Results<Notification>!
var sectionRides = [Results<Ride>]()
let sectionTitles = ["Pendentes", "Ativas", "Ofertadas"]
override func viewDidLoad() {
hidesDirectionControl = true
super.viewDidLoad()
self.navigationController?.view.backgroundColor = UIColor.white
navigationItem.titleView = UIImageView(image: UIImage(named: "NavigationBarLogo"))
RideService.instance.getMyRides(success: { pending, active, offered in
self.sectionRides = [pending, active, offered]
self.subscribeToChanges()
}, error: { err in
NSLog("Error getting My Rides. %@", err.localizedDescription)
})
NotificationCenter.default.addObserver(self, selector: #selector(updateNotificationBadges), name: .CaronaeDidUpdateNotifications, object: nil)
updateNotificationBadges()
}
deinit {
notificationTokens.forEach { $0?.invalidate() }
NotificationCenter.default.removeObserver(self)
}
override func refreshTable() {
RideService.instance.updateMyRides(success: {
self.refreshControl?.endRefreshing()
NSLog("My rides updated")
}, error: { error in
self.refreshControl?.endRefreshing()
self.loadingFailed(withError: error as NSError)
})
}
func subscribeToChanges() {
// Open issue: Support grouping in RLMResults
// https://github.com/realm/realm-cocoa/issues/3384
let pending = sectionRides[0]
let active = sectionRides[1]
let offered = sectionRides[2]
let pendingNotificationToken = pending.observe { [weak self] (_: RealmCollectionChange) in
guard let tableView = self?.tableView else { return }
tableView.reloadData()
self?.changeBackgroundIfNeeded()
}
let activeNotificationToken = active.observe { [weak self] (_: RealmCollectionChange) in
guard let tableView = self?.tableView else { return }
tableView.tableFooterView = active.isEmpty ? nil : self?.tableFooter
tableView.reloadData()
self?.changeBackgroundIfNeeded()
}
let offeredNotificationToken = offered.observe { [weak self] (_: RealmCollectionChange) in
guard let tableView = self?.tableView else { return }
tableView.reloadData()
self?.changeBackgroundIfNeeded()
}
notificationTokens.append(contentsOf: [pendingNotificationToken, activeNotificationToken, offeredNotificationToken])
}
@objc func updateNotificationBadges() {
unreadNotifications = try! NotificationService.instance.getNotifications(of: [.chat, .rideJoinRequest, .rideJoinRequestAccepted])
if unreadNotifications.isEmpty {
navigationController?.tabBarItem.badgeValue = nil
} else {
navigationController?.tabBarItem.badgeValue = String(format: "%ld", unreadNotifications.count)
}
tableView.reloadData()
}
func changeBackgroundIfNeeded() {
tableView.backgroundView = (sectionRides.contains(where: { !$0.isEmpty })) ? nil : emptyTableLabel
}
override func loadingFailed(withError error: NSError, checkFilteredRides: Bool = false) {
tableView.backgroundView = (sectionRides.contains(where: { !$0.isEmpty })) ? nil : errorLabel
super.loadingFailed(withError: error, checkFilteredRides: false)
}
func openRide(withID rideID: Int, openChat: Bool) {
guard let ride = RideService.instance.getRideFromRealm(withID: rideID) else {
NSLog("Could not open ride %ld, did not find ride on realm.", rideID)
return
}
let rideViewController = RideViewController.instance(for: ride)
rideViewController.shouldOpenChatWindow = openChat
_ = navigationController?.popToRootViewController(animated: false)
navigationController?.pushViewController(rideViewController, animated: true)
}
func loadAcceptedRide(withID id: Int) {
RideService.instance.getRide(withID: id, success: { ride, _ in
guard let user = UserService.instance.user,
ride.riders.contains(where: { $0.id == user.id }) else {
NSLog("Could not open ride %ld, user is not listed as a rider", id)
return
}
let rideViewController = RideViewController.instance(for: ride)
rideViewController.shouldLoadFromRealm = false
_ = self.navigationController?.popToRootViewController(animated: false)
self.navigationController?.pushViewController(rideViewController, animated: true)
}, error: { err in
NSLog("Error loading accepted ride %ld: %@", id, err.localizedDescription)
})
}
// MARK: Table methods
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView!, titleForHeaderInSection section: Int) -> String! {
guard !sectionRides[section].isEmpty else {
return nil
}
return sectionTitles[section]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionRides[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let ride = sectionRides[indexPath.section][indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Ride Cell", for: indexPath) as! RideCell
cell.configureCell(with: ride)
cell.badgeCount = unreadNotifications.filter("rideID == %@", ride.id).count
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let ride = sectionRides[indexPath.section][indexPath.row]
let rideVC = RideViewController.instance(for: ride)
self.navigationController?.show(rideVC, sender: self)
}
lazy var tableFooter: UIView = {
let tableFooter = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 40))
tableFooter.text = "Se você é motorista de alguma carona, não\n esqueça de concluí-la após seu término. :)"
tableFooter.numberOfLines = 0
tableFooter.backgroundColor = .white
tableFooter.font = .systemFont(ofSize: 10)
tableFooter.textColor = .lightGray
tableFooter.textAlignment = .center
return tableFooter
}()
}
|
gpl-3.0
|
269072d8007936a9c2bc64a6f7a0ee7b
| 39.616279 | 150 | 0.641712 | 5.14433 | false | false | false | false |
SunLiner/Floral
|
Floral/Floral/Classes/Home/Top/View/TopArticleOtherCell.swift
|
1
|
2438
|
//
// TopArticleOtherCell.swift
// Floral
//
// Created by 孙林 on 16/5/2.
// Copyright © 2016年 ALin. All rights reserved.
// 专题, 4-10名的Cell
import UIKit
class TopArticleOtherCell: TopArticleCell {
override func setupUI()
{
super.setupUI()
contentView.addSubview(smallIconView)
smallIconView.addSubview(coverView)
contentView.addSubview(logoView)
logoView.addSubview(sortLabel)
contentView.addSubview(topLine)
contentView.addSubview(underLine)
contentView.addSubview(titleLabel)
sortLabel.textColor = UIColor.blackColor()
underLine.backgroundColor = UIColor.blackColor()
topLine.backgroundColor = UIColor.blackColor()
titleLabel.textColor = UIColor.blackColor()
titleLabel.font = UIFont.systemFontOfSize(12)
smallIconView.snp_makeConstraints { (make) in
make.top.equalTo(contentView)
make.left.equalTo(contentView).offset(10)
make.height.equalTo(contentView)
make.width.equalTo(contentView.snp_height)
}
coverView.snp_makeConstraints { (make) in
make.edges.equalTo(0)
}
// logo的x应该是除去缩略图之后, 剩下的一半的位置
logoView.snp_makeConstraints { (make) in
make.size.equalTo(CGSize(width: 97, height: 58))
make.top.equalTo(10)
make.left.equalTo(smallIconView.snp_right).offset((ScreenWidth-120 - 97) * 0.5)
}
sortLabel.snp_makeConstraints { (make) in
make.center.equalTo(logoView)
}
topLine.snp_makeConstraints { (make) in
make.top.equalTo(logoView.snp_bottom).offset(10)
make.left.equalTo(logoView)
make.height.equalTo(1)
make.width.equalTo(logoView.snp_width)
}
titleLabel.snp_makeConstraints { (make) in
make.top.equalTo(topLine.snp_bottom).offset(5)
make.left.width.equalTo(topLine)
}
underLine.snp_makeConstraints { (make) in
make.left.equalTo(topLine)
make.size.equalTo(topLine)
make.top.equalTo(titleLabel.snp_bottom).offset(5)
}
}
/// Logo
private lazy var logoView : UIImageView = UIImageView(image: UIImage(named: "f_top"))
}
|
mit
|
391ee91473f53b7c87ca9237b8397d73
| 30.8 | 91 | 0.602096 | 4.297297 | false | false | false | false |
MrZoidberg/metapp
|
metapp/metapp/MainViewController.swift
|
1
|
7158
|
//
// ViewController.swift
// metapp
//
// Created by Mikhail Merkulov on 9/22/16.
// Copyright © 2016 ZoidSoft. All rights reserved.
//
import UIKit
import RxDataSources
import RxSwift
import RxCocoa
import Photos
import XCGLogger
import RealmSwift
import RxRealm
struct PhotoSection {
var header: String
var photos: [MAPhoto]
var updated: Date
init(header: String, photos: [MAPhoto], updated: Date) {
self.header = header
self.photos = photos
self.updated = updated
}
}
extension PhotoSection : AnimatableSectionModelType {
typealias Item = MAPhoto
typealias Identity = String
var identity: String {
return header
}
var items: [MAPhoto] {
return photos
}
init(original: PhotoSection, items: [Item]) {
self = original
self.photos = items
}
}
class PhotoCell: UICollectionViewCell {
@IBOutlet weak var image: UIImageView!
var viewModel: MAPhoto?
}
final class MainViewController: UIViewController, Loggable {
//private let collectionDataSource = RxCollectionViewSectionedAnimatedDataSource<PhotoSection>()
// MARK: Properties
var viewModel: MainViewModel?
//let photoItems: PublishSubject<MAPhoto> = PublishSubject<MAPhoto>()
var log: XCGLogger?
let disposeBag = DisposeBag()
var photosUpdateToken: NotificationToken? = nil
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var collectionView: UICollectionView!
deinit {
photosUpdateToken?.stop()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
guard (viewModel != nil) else {
return
}
//bind imageSize from model to collectionView
viewModel?.imageSize
.asObservable()
.subscribeOn(MainScheduler.instance)
.subscribe(onNext: {[unowned self] (size) in
if size != CGSize.zero {
(self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize = size
self.collectionView?.reloadData()
}
})
.addDisposableTo(disposeBag)
viewModel?.analyzerProgress?.map({ p in
return Float(p) / 100
})
.observeOn(MainScheduler.instance)
.bindTo(progressView.rx.progress)
.addDisposableTo(disposeBag)
photosUpdateToken = viewModel?.photoSource.addNotificationBlock({[weak self] (changes) in
self?.applyCollectionChange(changes)
})
registerForPreviewing(with: self, sourceView: self.collectionView!)
}
override func viewDidAppear(_ animated: Bool) {
viewModel?.setImageSize(calcOptimalImageSize())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func calcOptimalImageSize() -> CGSize {
self.collectionView!.collectionViewLayout.invalidateLayout()
let contentSize = self.collectionView!.collectionViewLayout.collectionViewContentSize
let dimension: Double = Double(contentSize.width) / 2.0 - 5.0*2
self.log?.debug("collection view size is \(self.collectionView!.bounds.debugDescription). Image size is \(dimension)")
return CGSize(width: dimension, height: dimension)
}
}
extension MainViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return self.viewModel?.photoSource.count ?? 0
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
guard let viewModel = self.viewModel else {
return cell
}
let photoModel: MAPhoto = viewModel.photoSource[(indexPath as NSIndexPath).item]
cell.viewModel = photoModel
self.viewModel!.requestImage(photoModel.id!, {(image) in
//self?.log?.debug("loading photo \(photoModel.identity) + for \(ip.description)")
cell.image.image = image
})
return cell
}
}
extension MainViewController: UIViewControllerPreviewingDelegate {
// MARK: UIViewControllerPreviewingDelegate
func previewingContext(_ previewingContext: UIViewControllerPreviewing,
viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = self.collectionView!.indexPathForItem(at: location), let cell = self.collectionView!.cellForItem(at: indexPath) as? PhotoCell,
let photoModel = cell.viewModel else {
return nil
}
guard let peekPhotoViewController = storyboard?.instantiateViewController(withIdentifier: "PeekPhotoViewController") as? PeekPhotoViewController else { return nil }
peekPhotoViewController.viewModel = photoModel
return peekPhotoViewController
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing,
commit viewControllerToCommit: UIViewController) {
}
}
extension MainViewController {
func applyCollectionChange(_ changes: RealmCollectionChange<Results<MAPhoto>>) {
switch changes {
case .initial:
self.collectionView?.reloadData()
break
case .update(_, deletions: let deletions, insertions: let insertions, modifications: let modifications):
//Changeset<PhotoSection>
self.collectionView?.performBatchUpdates({
self.collectionView?.deleteItemsAtIndexPaths(self.indexesToIndexPathes(deletions), animationStyle: .automatic)
self.collectionView?.insertItemsAtIndexPaths(self.indexesToIndexPathes(insertions), animationStyle: .automatic)
self.collectionView?.reloadItemsAtIndexPaths(self.indexesToIndexPathes(modifications), animationStyle: .automatic)
}, completion: { (b) in
})
break
case .error(let err):
self.log?.error("Cannot load photos. Error: \(err.localizedDescription)")
// An error occurred while opening the Realm file on the background worker thread
//fatalError("\(err)")
break
//insertItems(at: changes.inserted.map { IndexPath(row: $0, section: 0) })
//reloadItems(at: changes.updated.map { IndexPath(row: $0, section: 0) })
//deleteItems (at: changes.deleted.map { IndexPath(row: $0, section: 0) })
}
}
func indexesToIndexPathes(_ indexes: [Int], atSection section: Int? = 0) -> [IndexPath] {
return indexes.map({ (index) -> IndexPath in
IndexPath(item: index, section: section!)
})
}
}
|
mpl-2.0
|
c5a202bb9a4fb7677e03783f4c47f6e0
| 32.759434 | 172 | 0.658097 | 5.289727 | false | false | false | false |
ps2/rileylink_ios
|
MinimedKit/PumpManager/MinimedDoseProgressEstimator.swift
|
1
|
1383
|
//
// MinimedDoseProgressEstimator.swift
// MinimedKit
//
// Created by Pete Schwamb on 3/14/19.
// Copyright © 2019 Pete Schwamb. All rights reserved.
//
import Foundation
import LoopKit
class MinimedDoseProgressEstimator: DoseProgressTimerEstimator {
let dose: DoseEntry
public let pumpModel: PumpModel
override var progress: DoseProgress {
let elapsed = -dose.startDate.timeIntervalSinceNow
let (deliveredUnits, progress) = pumpModel.estimateBolusProgress(elapsed: elapsed, programmedUnits: dose.programmedUnits)
return DoseProgress(deliveredUnits: deliveredUnits, percentComplete: progress)
}
init(dose: DoseEntry, pumpModel: PumpModel, reportingQueue: DispatchQueue) {
self.dose = dose
self.pumpModel = pumpModel
super.init(reportingQueue: reportingQueue)
}
override func timerParameters() -> (delay: TimeInterval, repeating: TimeInterval) {
let timeSinceStart = -dose.startDate.timeIntervalSinceNow
let duration = dose.endDate.timeIntervalSince(dose.startDate)
let timeBetweenPulses = duration / (Double(pumpModel.pulsesPerUnit) * dose.programmedUnits)
let delayUntilNextPulse = timeBetweenPulses - timeSinceStart.remainder(dividingBy: timeBetweenPulses)
return (delay: delayUntilNextPulse, repeating: timeBetweenPulses)
}
}
|
mit
|
98b23d2146cba7e019e9a734e13594d5
| 32.707317 | 129 | 0.729378 | 4.749141 | false | false | false | false |
google/android-auto-companion-ios
|
Tests/AndroidAutoConnectedDeviceManagerTests/SystemFeatureManagerTest.swift
|
1
|
8994
|
// Copyright 2021 Google LLC
//
// 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 AndroidAutoConnectedDeviceManagerMocks
import CoreBluetooth
import XCTest
@_implementationOnly import AndroidAutoCompanionProtos
@testable import AndroidAutoConnectedDeviceManager
private typealias SystemQuery = Com_Google_Companionprotos_SystemQuery
private typealias SystemQueryType = Com_Google_Companionprotos_SystemQueryType
private typealias SystemUserRoleResponse = Com_Google_Companionprotos_SystemUserRoleResponse
typealias SystemUserRole = Com_Google_Companionprotos_SystemUserRole
/// Unit tests for `SystemFeatureManager`.
class SystemFeatureManagerTest: XCTestCase {
private let deviceName = "DeviceName"
private let appName = "appName"
private var car: Car!
private var connectedCarManagerMock: ConnectedCarManagerMock!
private var channel: SecuredCarChannelMock!
private var manager: SystemFeatureManager!
override func setUp() {
super.setUp()
continueAfterFailure = false
connectedCarManagerMock = ConnectedCarManagerMock()
car = Car(id: "id", name: "name")
channel = SecuredCarChannelMock(car: car)
manager = SystemFeatureManager(
connectedCarManager: connectedCarManagerMock,
nameProvider: FakeDevice(name: deviceName),
appNameProvider: FakeAppNameProvider(appName: appName)
)
}
// MARK: - Device name tests
func testOnValidQuery_sendsDeviceName() {
connectedCarManagerMock.triggerSecureChannelSetUp(with: channel)
let request = createSystemQuery(type: SystemQueryType.deviceName)
let query = Query(request: request, parameters: nil)
let queryID: Int32 = 13
channel.triggerQuery(query, queryID: queryID, from: SystemFeatureManager.recipientUUID)
let expectedQueryResponse = QueryResponse(
id: queryID,
isSuccessful: true,
response: Data(deviceName.utf8)
)
XCTAssertEqual(channel.writtenQueryResponses.count, 1)
XCTAssertEqual(channel.writtenQueryResponses[0].queryResponse, expectedQueryResponse)
}
// MARK: - App name tests
func testOnValidQuery_sendsAppName() {
connectedCarManagerMock.triggerSecureChannelSetUp(with: channel)
let request = createSystemQuery(type: SystemQueryType.appName)
let query = Query(request: request, parameters: nil)
let queryID: Int32 = 13
channel.triggerQuery(query, queryID: queryID, from: SystemFeatureManager.recipientUUID)
let expectedQueryResponse = QueryResponse(
id: queryID,
isSuccessful: true,
response: Data(appName.utf8)
)
XCTAssertEqual(channel.writtenQueryResponses.count, 1)
XCTAssertEqual(channel.writtenQueryResponses[0].queryResponse, expectedQueryResponse)
}
func testOnAppNameRetrievalFaiL_sendsUnsuccessfulQueryResponse() {
manager = SystemFeatureManager(
connectedCarManager: connectedCarManagerMock,
nameProvider: FakeDevice(name: deviceName),
appNameProvider: FakeAppNameProvider(appName: nil)
)
connectedCarManagerMock.triggerSecureChannelSetUp(with: channel)
let request = createSystemQuery(type: SystemQueryType.appName)
let query = Query(request: request, parameters: nil)
let queryID: Int32 = 13
channel.triggerQuery(query, queryID: queryID, from: SystemFeatureManager.recipientUUID)
let expectedQueryResponse = QueryResponse(
id: queryID,
isSuccessful: false,
response: Data()
)
XCTAssertEqual(channel.writtenQueryResponses.count, 1)
XCTAssertEqual(channel.writtenQueryResponses[0].queryResponse, expectedQueryResponse)
}
func testBundleExtension_looksUpAppName() {
// If the `test_host` ever changes, this value will need to change.
XCTAssertEqual(Bundle.main.appName, "TrustAgentSample")
}
// MARK: - User Role Request
func testRequestUserRole_callsCompletionWithDriverRole() throws {
connectedCarManagerMock.triggerSecureChannelSetUp(with: channel)
var completionCalled = false
let queryID = channel.queryID
var userRole: UserRole? = nil
manager.requestUserRole(with: channel) {
userRole = $0
completionCalled = true
}
var roleResponse = SystemUserRoleResponse()
roleResponse.role = .driver
let queryResponse = QueryResponse(
id: queryID,
isSuccessful: true,
response: try roleResponse.serializedData()
)
channel.triggerQueryResponse(queryResponse)
XCTAssertEqual(channel.writtenQueries.count, 1)
XCTAssertTrue(completionCalled)
XCTAssertNotNil(userRole)
XCTAssertTrue(userRole?.isDriver ?? false)
XCTAssertFalse(userRole?.isPassenger ?? false)
}
func testRequestUserRole_callsCompletionWithPassengerRole() throws {
connectedCarManagerMock.triggerSecureChannelSetUp(with: channel)
var completionCalled = false
let queryID = channel.queryID
var userRole: UserRole? = nil
manager.requestUserRole(with: channel) {
userRole = $0
completionCalled = true
}
var roleResponse = SystemUserRoleResponse()
roleResponse.role = .passenger
let queryResponse = QueryResponse(
id: queryID,
isSuccessful: true,
response: try roleResponse.serializedData()
)
channel.triggerQueryResponse(queryResponse)
XCTAssertEqual(channel.writtenQueries.count, 1)
XCTAssertTrue(completionCalled)
XCTAssertNotNil(userRole)
XCTAssertFalse(userRole?.isDriver ?? false)
XCTAssertTrue(userRole?.isPassenger ?? false)
}
func testRequestUserRole_unsuccessfulResponse() throws {
connectedCarManagerMock.triggerSecureChannelSetUp(with: channel)
var completionCalled = false
let queryID = channel.queryID
var userRole: UserRole? = nil
manager.requestUserRole(with: channel) {
userRole = $0
completionCalled = true
}
var roleResponse = SystemUserRoleResponse()
roleResponse.role = .passenger
let queryResponse = QueryResponse(
id: queryID,
isSuccessful: false,
response: try roleResponse.serializedData()
)
channel.triggerQueryResponse(queryResponse)
XCTAssertEqual(channel.writtenQueries.count, 1)
XCTAssertTrue(completionCalled)
XCTAssertNil(userRole)
}
// MARK: - Error path tests
func testQueryWithInvalidType_sendsUnsuccessfulQueryResponse() {
connectedCarManagerMock.triggerSecureChannelSetUp(with: channel)
// Create a query with the wrong type.
let request = createSystemQuery(type: SystemQueryType.unknown)
let query = Query(request: request, parameters: nil)
let queryID: Int32 = 13
channel.triggerQuery(query, queryID: queryID, from: SystemFeatureManager.recipientUUID)
let expectedQueryResponse = QueryResponse(
id: queryID,
isSuccessful: false,
response: Data()
)
XCTAssertEqual(channel.writtenQueryResponses.count, 1)
XCTAssertEqual(channel.writtenQueryResponses[0].queryResponse, expectedQueryResponse)
}
func testInvalidQueryProto_doesNotSendQueryResponse() {
connectedCarManagerMock.triggerSecureChannelSetUp(with: channel)
// Query with an invalid `request` field.
let query = Query(request: Data("fake proto".utf8), parameters: nil)
channel.triggerQuery(query, queryID: 13, from: SystemFeatureManager.recipientUUID)
XCTAssertTrue(channel.writtenQueryResponses.isEmpty)
XCTAssertTrue(channel.writtenMessages.isEmpty)
}
func testOnMessageReceived_doesNotSendQueryResponse() {
connectedCarManagerMock.triggerSecureChannelSetUp(with: channel)
channel.triggerMessageReceived(Data("message".utf8), from: SystemFeatureManager.recipientUUID)
XCTAssertTrue(channel.writtenQueryResponses.isEmpty)
XCTAssertTrue(channel.writtenMessages.isEmpty)
}
// MARK: - Helper methods
/// Returns a serialized `SystemQuery` proto that has its type set to the given value.
private func createSystemQuery(type: SystemQueryType) -> Data {
var systemQuery = SystemQuery()
systemQuery.type = type
return try! systemQuery.serializedData()
}
}
/// A fake device that will return the name it is initialized with.
struct FakeDevice: AnyDevice {
let name: String
let model = "model"
let localizedModel = "localizedModel"
let systemName = "systemName"
let systemVersion = "systemVersion"
let batteryLevel: Float = 100
init(name: String) {
self.name = name
}
}
/// A fake `AppNameProvider` that returns the app name it was initialized with.
struct FakeAppNameProvider: AppNameProvider {
let appName: String?
}
|
apache-2.0
|
a5707f933175426a38558febe4c44779
| 32.939623 | 98 | 0.751501 | 4.54472 | false | true | false | false |
zvonler/PasswordElephant
|
external/github.com/apple/swift-protobuf/Sources/SwiftProtobuf/HashVisitor.swift
|
5
|
3912
|
// Sources/SwiftProtobuf/HashVisitor.swift - Hashing support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Hashing is basically a serialization problem, so we can leverage the
/// generated traversal methods for that.
///
// -----------------------------------------------------------------------------
import Foundation
private let i_2166136261 = Int(bitPattern: 2166136261)
private let i_16777619 = Int(16777619)
/// Computes the hash value of a message by visiting its fields recursively.
///
/// Note that because this visits every field, it has the potential to be slow
/// for large or deeply nested messages. Users who need to use such messages as
/// dictionary keys or set members should override `hashValue` in an extension
/// and provide a more efficient implementation by examining only a subset of
/// key fields.
internal struct HashVisitor: Visitor {
// Roughly based on FNV hash: http://tools.ietf.org/html/draft-eastlake-fnv-03
private(set) var hashValue = i_2166136261
private mutating func mix(_ hash: Int) {
hashValue = (hashValue ^ hash) &* i_16777619
}
private mutating func mixMap<K, V: Hashable>(map: Dictionary<K,V>) {
var mapHash = 0
for (k, v) in map {
// Note: This calculation cannot depend on the order of the items.
mapHash = mapHash &+ (k.hashValue ^ v.hashValue)
}
mix(mapHash)
}
init() {}
mutating func visitUnknown(bytes: Data) throws {
mix(bytes.hashValue)
}
mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws {
mix(fieldNumber)
mix(value.hashValue)
}
mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws {
mix(fieldNumber)
mix(value.hashValue)
}
mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws {
mix(fieldNumber)
mix(value.hashValue)
}
mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws {
mix(fieldNumber)
mix(value.hashValue)
}
mutating func visitSingularStringField(value: String, fieldNumber: Int) throws {
mix(fieldNumber)
mix(value.hashValue)
}
mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws {
mix(fieldNumber)
#if swift(>=3.1)
mix(value.hashValue)
#else
// Workaround for https://bugs.swift.org/browse/SR-936
// (Fortunately, seems to have been fixed in Swift 3.1)
value.enumerateBytes { (block, index, stop) in
for b in block {
mix(Int(b))
}
}
#endif
}
mutating func visitSingularEnumField<E: Enum>(value: E,
fieldNumber: Int) {
mix(fieldNumber)
mix(value.hashValue)
}
mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) {
mix(fieldNumber)
mix(value.hashValue)
}
mutating func visitMapField<KeyType, ValueType: MapValueType>(
fieldType: _ProtobufMap<KeyType, ValueType>.Type,
value: _ProtobufMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws {
mix(fieldNumber)
mixMap(map: value)
}
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type,
value: _ProtobufEnumMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws where ValueType.RawValue == Int {
mix(fieldNumber)
mixMap(map: value)
}
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type,
value: _ProtobufMessageMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws {
mix(fieldNumber)
mixMap(map: value)
}
}
|
gpl-3.0
|
aeb27891156b4c882348d5c8975c50e2
| 28.636364 | 83 | 0.670757 | 4.224622 | false | false | false | false |
jeroendesloovere/swifter
|
SwifterCommon/SwifterLists.swift
|
3
|
54601
|
//
// SwifterLists.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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
extension Swifter {
/*
GET lists/list
Returns all lists the authenticating or specified user subscribes to, including their own. The user is specified using the user_id or screen_name parameters. If no user is given, the authenticating user is used.
This method used to be GET lists in version 1.0 of the API and has been renamed for consistency with other call.
A maximum of 100 results will be returned by this call. Subscribed lists are returned first, followed by owned lists. This means that if a user subscribes to 90 lists and owns 20 lists, this method returns 90 subscriptions and 10 owned lists. The reverse method returns owned lists first, so with reverse=true, 20 owned lists and 80 subscriptions would be returned. If your goal is to obtain every list a user owns or subscribes to, use GET lists/ownerships and/or GET lists/subscriptions instead.
*/
func getListsSubscribedByUserWithReverse(reverse: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/list.json"
var parameters = Dictionary<String, AnyObject>()
if reverse {
parameters["reverse"] = reverse!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscribedByUserWithID(userID: Int, reverse: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/list.json"
var parameters = Dictionary<String, AnyObject>()
parameters["userID"] = userID
if reverse {
parameters["reverse"] = reverse!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscribedByUserWithScreenName(screenName: String, reverse: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/list.json"
var parameters = Dictionary<String, AnyObject>()
parameters["screen_name"] = screenName
if reverse {
parameters["reverse"] = reverse!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
GET lists/statuses
Returns a timeline of tweets authored by members of the specified list. Retweets are included by default. Use the include_rts=false parameter to omit retweets. Embedded Timelines is a great way to embed list timelines on your website.
*/
func getListsStatusesWithListID(listID: Int, ownerScreenName: String, sinceID: Int?, maxID: Int?, count: Int?, includeEntities: Bool?, includeRTs: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/statuses.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["owner_screen_name"] = ownerScreenName
if sinceID {
parameters["since_id"] = sinceID!
}
if maxID {
parameters["max_id"] = maxID!
}
if count {
parameters["count"] = count!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if includeRTs {
parameters["include_rts"] = includeRTs!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsStatuesWithListID(listID: Int, ownerID: Int, sinceID: Int?, maxID: Int?, count: Int?, includeEntities: Bool?, includeRTs: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/statuses.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["owner_id"] = ownerID
if sinceID {
parameters["since_id"] = sinceID!
}
if maxID {
parameters["max_id"] = maxID!
}
if count {
parameters["count"] = count!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if includeRTs {
parameters["include_rts"] = includeRTs!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsStatuesWithSlug(slug: String, ownerScreenName: String, sinceID: Int?, maxID: Int?, count: Int?, includeEntities: Bool?, includeRTs: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/statuses.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
if sinceID {
parameters["since_id"] = sinceID!
}
if maxID {
parameters["max_id"] = maxID!
}
if count {
parameters["count"] = count!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if includeRTs {
parameters["include_rts"] = includeRTs!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsStatuesWithSlug(slug: String, ownerID: Int, sinceID: Int?, maxID: Int?, count: Int?, includeEntities: Bool?, includeRTs: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/statuses.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
if sinceID {
parameters["since_id"] = sinceID!
}
if maxID {
parameters["max_id"] = maxID!
}
if count {
parameters["count"] = count!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if includeRTs {
parameters["include_rts"] = includeRTs!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
POST lists/members/destroy
Removes the specified member from the list. The authenticated user must be the list's owner to remove members from the list.
*/
func postListsMembersDestroyWithListID(listID: Int, userID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["user_id"] = userID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersDestroyWithListID(listID: Int, screenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["screen_name"] = screenName
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersDestroyWithSlug(slug: String, userID: Int, ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["userID"] = userID
parameters["owner_screen_name"] = ownerScreenName
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersDestroyWithSlug(slug: String, screenName: String, ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["screen_name"] = screenName
parameters["owner_screen_name"] = ownerScreenName
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersDestroyWithSlug(slug: String, userID: Int, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["userID"] = userID
parameters["owner_id"] = ownerID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersDestroyWithSlug(slug: String, screenName: String, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["screen_name"] = screenName
parameters["owner_id"] = ownerID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
GET lists/memberships
Returns the lists the specified user has been added to. If user_id or screen_name are not provided the memberships for the authenticating user are returned.
*/
func getListsMembershipsWithUserID(userID: Int, cursor: Int?, filterToOwnedLists: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/memberships.json"
var parameters = Dictionary<String, AnyObject>()
parameters["user_id"] = userID
if cursor {
parameters["cursor"] = cursor!
}
if filterToOwnedLists {
parameters["filter_to_owned_lists"] = filterToOwnedLists!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsMembershipsWithScreenName(screenName: String, cursor: Int?, filterToOwnedLists: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/memberships.json"
var parameters = Dictionary<String, AnyObject>()
parameters["screen_name"] = screenName
if cursor {
parameters["cursor"] = cursor!
}
if filterToOwnedLists {
parameters["filter_to_owned_lists"] = filterToOwnedLists!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
GET lists/subscribers
Returns the subscribers of the specified list. Private list subscribers will only be shown if the authenticated user owns the specified list.
*/
func getListsSubscribersWithListID(listID: Int, ownerScreenName: String?, cursor: Int?, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
if ownerScreenName {
parameters["owner_screen_name"] = ownerScreenName!
}
if cursor {
parameters["cursor"] = cursor!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscribersWithListID(listID: Int, ownerID: Int?, cursor: Int?, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
if ownerID {
parameters["owner_id"] = ownerID!
}
if cursor {
parameters["cursor"] = cursor!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscribersWithSlug(slug: String, ownerScreenName: String?, cursor: Int?, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
if ownerScreenName {
parameters["owner_screen_name"] = ownerScreenName!
}
if cursor {
parameters["cursor"] = cursor!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscribersWithSlug(slug: String, ownerID: Int?, cursor: Int?, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
if ownerID {
parameters["owner_id"] = ownerID!
}
if cursor {
parameters["cursor"] = cursor!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
POST lists/subscribers/create
Subscribes the authenticated user to the specified list.
*/
func postListsSubscribersCreateWithListID(listID: Int, ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/create.json"
var parameters = Dictionary<String, AnyObject>()
parameters["owner_screen_name"] = ownerScreenName
parameters["list_id"] = listID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsSubscribersCreateWithListID(listID: Int, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/create.json"
var parameters = Dictionary<String, AnyObject>()
parameters["owner_id"] = ownerID
parameters["list_id"] = listID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsSubscribersCreateWithSlug(slug: String, ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/create.json"
var parameters = Dictionary<String, AnyObject>()
parameters["owner_screen_name"] = ownerScreenName
parameters["slug"] = slug
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsSubscribersCreateWithSlug(slug: String, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/create.json"
var parameters = Dictionary<String, AnyObject>()
parameters["owner_id"] = ownerID
parameters["slug"] = slug
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
GET lists/subscribers/show
Check if the specified user is a subscriber of the specified list. Returns the user if they are subscriber.
*/
func getListsSubscribersShowWithListID(listID: Int, userID: Int, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["user_id"] = userID
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscribersShowWithListID(listID: Int, screenName: String, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["screen_name"] = screenName
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscribersShowWithSlug(slug: String, ownerID: Int, userID: Int, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
parameters["user_id"] = userID
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscribersShowWithSlug(slug: String, ownerID: Int, screenName: Int, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
parameters["screen_name"] = screenName
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscribersShowWithSlug(slug: String, ownerScreenName: Int, userID: Int, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
parameters["user_id"] = userID
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscribersShowWithSlug(slug: String, ownerScreenName: Int, screenName: Int, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
parameters["screen_name"] = screenName
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
POST lists/subscribers/destroy
Unsubscribes the authenticated user from the specified list.
*/
func postListsSubscribersDestroyWithListID(listID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["listID"] = listID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsSubscribersDestroyWithSlug(slug: String, ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsSubscribersDestroyWithSlug(slug: String, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
POST lists/members/create_all
Adds multiple members to a list, by specifying a comma-separated list of member ids or screen names. The authenticated user must own the list to be able to add members to it. Note that lists can't have more than 5,000 members, and you are limited to adding up to 100 members to a list at a time with this method.
Please note that there can be issues with lists that rapidly remove and add memberships. Take care when using these methods such that you are not too rapidly switching between removals and adds on the same list.
*/
func postListsMembersCreateWithListID(listID: Int, userIDs: Int[], includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/create_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["user_id"] = userIDs.bridgeToObjectiveC().componentsJoinedByString(",")
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersCreateWithListID(listID: Int, screenNames: String[], includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/create_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["screen_name"] = screenNames.bridgeToObjectiveC().componentsJoinedByString(",")
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersCreateWithSlug(slug: String, ownerID: Int, userIDs: Int[], includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/create_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
parameters["user_id"] = userIDs.bridgeToObjectiveC().componentsJoinedByString(",")
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersCreateWithSlug(slug: String, ownerID: Int, screenNames: String[], includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/create_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
parameters["screen_name"] = screenNames.bridgeToObjectiveC().componentsJoinedByString(",")
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersCreateWithSlug(slug: String, ownerScreenName: String, userIDs: Int[], includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/create_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
parameters["user_id"] = userIDs.bridgeToObjectiveC().componentsJoinedByString(",")
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersCreateWithSlug(slug: String, ownerScreenName: String, screenNames: String[], includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/create_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
parameters["screen_name"] = screenNames.bridgeToObjectiveC().componentsJoinedByString(",")
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
GET lists/members/show
Check if the specified user is a member of the specified list.
*/
func getListsMembersShowWithListID(listID: Int, userID: Int, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["user_id"] = userID
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsMembersShowWithListID(listID: Int, screenName: String, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["screen_name"] = screenName
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsMembersShowWithSlug(slug: String, ownerID: Int, userID: Int, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
parameters["user_id"] = userID
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsMembersShowWithSlug(slug: String, ownerID: Int, screenName: Int, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
parameters["screen_name"] = screenName
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsMembersShowWithSlug(slug: String, ownerScreenName: Int, userID: Int, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
parameters["user_id"] = userID
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
GET lists/members
Returns the members of the specified list. Private list members will only be shown if the authenticated user owns the specified list.
*/
func getListsMembersShowWithSlug(slug: String, ownerScreenName: Int, screenName: Int, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
parameters["screen_name"] = screenName
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsMembersWithListID(listID: Int, ownerScreenName: String?, cursor: Int?, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
if ownerScreenName {
parameters["owner_screen_name"] = ownerScreenName!
}
if cursor {
parameters["cursor"] = cursor!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsMembersWithListID(listID: Int, ownerID: Int?, cursor: Int?, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
if ownerID {
parameters["owner_id"] = ownerID!
}
if cursor {
parameters["cursor"] = cursor!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsMembersWithSlug(slug: String, ownerScreenName: String?, cursor: Int?, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
if ownerScreenName {
parameters["owner_screen_name"] = ownerScreenName!
}
if cursor {
parameters["cursor"] = cursor!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsMembersWithSlug(slug: String, ownerID: Int?, cursor: Int?, includeEntities: Bool?, skipStatus: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
if ownerID {
parameters["owner_id"] = ownerID!
}
if cursor {
parameters["cursor"] = cursor!
}
if includeEntities {
parameters["include_entities"] = includeEntities!
}
if skipStatus {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
POST lists/members/create
Creates a new list for the authenticated user. Note that you can't create more than 20 lists per account.
*/
func postListsMembersCreateWithListID(listID: Int, ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/create.json"
var parameters = Dictionary<String, AnyObject>()
parameters["owner_screen_name"] = ownerScreenName
parameters["list_id"] = listID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersCreateWithListID(listID: Int, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/create.json"
var parameters = Dictionary<String, AnyObject>()
parameters["owner_id"] = ownerID
parameters["list_id"] = listID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersCreateWithSlug(slug: String, ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/create.json"
var parameters = Dictionary<String, AnyObject>()
parameters["owner_screen_name"] = ownerScreenName
parameters["slug"] = slug
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersCreateWithSlug(slug: String, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscribers/create.json"
var parameters = Dictionary<String, AnyObject>()
parameters["owner_id"] = ownerID
parameters["slug"] = slug
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
POST lists/destroy
Deletes the specified list. The authenticated user must own the list to be able to destroy it.
*/
func postListsDestroyWithListID(listID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsDestroyWithSlug(slug: String, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsDestroyWithSlug(slug: String, ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/destroy.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
POST lists/update
Updates the specified list. The authenticated user must own the list to be able to update it.
*/
func postListsUpdateWithListID(listID: Int, name: String?, public: Bool?, description: String?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/update.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
if name {
parameters["name"] = name!
}
if public {
if public! {
parameters["mode"] = "public"
}
else {
parameters["mode"] = "private"
}
}
if description {
parameters["description"] = description!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsUpdateWithSlug(slug: String, ownerID: Int, name: String?, public: Bool?, description: String?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/update.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
if name {
parameters["name"] = name!
}
if public {
if public! {
parameters["mode"] = "public"
}
else {
parameters["mode"] = "private"
}
}
if description {
parameters["description"] = description!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsUpdateWithSlug(slug: String, ownerScreenName: String, name: String?, public: Bool?, description: String?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/update.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
if name {
parameters["name"] = name!
}
if public {
if public! {
parameters["mode"] = "public"
}
else {
parameters["mode"] = "private"
}
}
if description {
parameters["description"] = description!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
POST lists/create
Creates a new list for the authenticated user. Note that you can't create more than 20 lists per account.
*/
func postListsCreateWithName(name: String, public: Bool?, description: String?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/create.json"
var parameters = Dictionary<String, AnyObject>()
parameters["name"] = name
if public {
if public! {
parameters["mode"] = "public"
}
else {
parameters["mode"] = "private"
}
}
if description {
parameters["description"] = description!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
GET lists/show
Returns the specified list. Private lists will only be shown if the authenticated user owns the specified list.
*/
func getListsShowWithID(listID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsShowWithSlug(slug: String, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_id"] = ownerID
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsShowWithSlug(slug: String, ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/show.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["owner_screen_name"] = ownerScreenName
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
GET lists/subscriptions
Obtain a collection of the lists the specified user is subscribed to, 20 lists per page by default. Does not include the user's own lists.
*/
func getListsSubscriptionsWithUserID(userID: Int, count: Int?, cursor: Int?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscriptions.json"
var parameters = Dictionary<String, AnyObject>()
parameters["user_id"] = userID
if count {
parameters["count"] = count!
}
if cursor {
parameters["cursor"] = cursor!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func getListsSubscriptionsWithScreenName(screenName: String, count: Int?, cursor: Int?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/subscriptions.json"
var parameters = Dictionary<String, AnyObject>()
parameters["screen_name"] = screenName
if count {
parameters["count"] = count!
}
if cursor {
parameters["cursor"] = cursor!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
POST lists/members/destroy_all
Removes multiple members from a list, by specifying a comma-separated list of member ids or screen names. The authenticated user must own the list to be able to remove members from it. Note that lists can't have more than 500 members, and you are limited to removing up to 100 members to a list at a time with this method.
Please note that there can be issues with lists that rapidly remove and add memberships. Take care when using these methods such that you are not too rapidly switching between removals and adds on the same list.
*/
func postListsMembersDestroyAllWithListID(listID: Int, userIDs: Int[], success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["user_id"] = userIDs.bridgeToObjectiveC().componentsJoinedByString(",")
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersDestroyAllWithListID(listID: Int, screenNames: String[], success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["list_id"] = listID
parameters["screen_name"] = screenNames.bridgeToObjectiveC().componentsJoinedByString(",")
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersDestroyAllWithSlug(slug: String, userIDs: Int[], ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["userID"] = userIDs.bridgeToObjectiveC().componentsJoinedByString(",")
parameters["owner_screen_name"] = ownerScreenName
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersDestroyAllWithSlug(slug: String, screenName: String, ownerScreenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["screen_name"] = screenName
parameters["owner_screen_name"] = ownerScreenName
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersDestroyAllWithSlug(slug: String, userID: Int, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["userID"] = userID
parameters["owner_id"] = ownerID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
func postListsMembersDestroyAllWithSlug(slug: String, screenName: String, ownerID: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/members/destroy_all.json"
var parameters = Dictionary<String, AnyObject>()
parameters["slug"] = slug
parameters["screen_name"] = screenName
parameters["owner_id"] = ownerID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
/*
GET lists/ownerships
Returns the lists owned by the specified Twitter user. Private lists will only be shown if the authenticated user is also the owner of the lists.
*/
func getListsOwnershipsWithUserID(userID: Int, count: Int?, cursor: Int?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "lists/ownerships.json"
var parameters = Dictionary<String, AnyObject>()
parameters["user_id"] = userID
if count {
parameters["count"] = count!
}
if cursor {
parameters["cursor"] = cursor!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure)
}
}
|
mit
|
93801748f42f3594fd21fa350c713fc2
| 43.354996 | 505 | 0.67301 | 4.923889 | false | false | false | false |
f2m2/f2m2-swift-forms
|
ObjCExample/ObjCExample/ObjCExample/Generator/FormCell.swift
|
3
|
5131
|
//
// FormCell.swift
// FormSerializer
//
// Created by Michael L Mork on 12/2/14.
// Copyright (c) 2014 f2m2. All rights reserved.
//
import Foundation
import UIKit
let addedViewTag = 150
let addedLabelTag = 160
/**
FormCell needed to be subclassed in order to callback when text changes, allowing a change of the model and update to the cell's interface.
*/
class FormCell: UITableViewCell, UITextFieldDelegate {
//Typealias is similar to typedef from objective-C.
var valueDidChange: FieldDidChange?
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
valueChange(textField.text)
return true
}
func valueChange(anyObject: AnyObject) {
if let valueChange = valueDidChange as FieldDidChange? {
valueChange(value: anyObject)
}
}
func setState(value: UISwitch) {
println("the switch: \(value) \n\n\n")
valueChange(value.on)
}
func btnTouch(btn: UIButton) {
valueChange(btn)
}
func removeTagView() {
if let view = contentView.viewWithTag(addedViewTag) as UIView! {
view.removeFromSuperview()
}
if let view = contentView.viewWithTag(addedLabelTag) as UILabel! {
view.removeFromSuperview()
}
}
}
/**
This extension exists because of the possibility (but not currently it seems) support for setting a function as an associated object on the cell.
When this possibility is apparent, there will be no need to subclass UITableViewCell. The function in question is Form Cell's "valueDidChange" variable.
*/
extension FormCell {
func addTextField (textField: UITextField?) {
removeTagView()
var theTextField = textField
if let textField = textField as UITextField! {} else {
theTextField = UITextField(frame: CGRectMake(0, 30, 100, 40))
theTextField!.borderStyle = UITextBorderStyle.RoundedRect
}
contentView.addSubview(theTextField!)
layout(theTextField!, contentView) { (TextField, backgroundOutlet) -> () in
TextField.width == backgroundOutlet.width - 30
TextField.center == backgroundOutlet.center
return()
}
theTextField!.delegate = self
self.layoutIfNeeded()
theTextField!.tag = addedViewTag
}
func addSwitch(label: UILabel?, aSwitch: UISwitch?) {
removeTagView()
var aSwitch = aSwitch
if let aSwitch = aSwitch as UISwitch! {} else {
let newSwitch = UISwitch()
aSwitch = newSwitch
}
contentView.addSubview(aSwitch!)
///If the label was passed then add it to the cell; otherwise center the solitary switch
if let label = label as UILabel! {
contentView.addSubview(label)
layout(aSwitch!, label, contentView) {(TheSwitch, TheLabel, ContentView) -> () in
TheLabel.width == ContentView.width - 80
TheLabel.centerX == ContentView.centerX - 30
TheLabel.centerY == ContentView.centerY
TheSwitch.leading == TheLabel.trailing + 10
TheSwitch.centerY == TheLabel.centerY
return()
}
} else {
layout(aSwitch!, contentView) {(TheSwitch, ContentView) -> () in
TheSwitch.center == ContentView.center
return()
}
}
aSwitch!.addTarget(self, action: "setState:", forControlEvents: UIControlEvents.ValueChanged)
aSwitch!.tag = addedViewTag
}
func addButton(button: UIButton?) {
removeTagView()
var button = button
if let button = button as UIButton? {} else {
let newButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
newButton.setTitle("Submit", forState: UIControlState.Normal)
button = newButton
}
contentView.addSubview(button!)
layout(button!, contentView) {(button, ContentView) -> () in
button.edges == inset(ContentView.edges, 20, 20, 20, 20); return
}
button!.addTarget(self, action: "btnTouch:", forControlEvents: UIControlEvents.TouchUpInside)
button!.tag = addedViewTag
}
func addCustomView(view: UIView?) {
removeTagView()
if let view = view as UIView? {
contentView.addSubview(view)
layout(view, contentView) {(View, ContentView) -> () in
View.edges == inset(ContentView.edges, 0, 0, 0, 0); return
}
}
}
}
|
mit
|
d322fc2fecaea3fc5195dea7ac62f34e
| 27.825843 | 156 | 0.565972 | 5.317098 | false | false | false | false |
codestergit/SweetAlert-iOS
|
SweetAlert/SweetAlert.swift
|
1
|
24674
|
//
// SweetAlert.swift
// SweetAlert
//
// Created by Codester on 11/3/14.
// Copyright (c) 2014 Codester. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
public enum AlertStyle {
case success,error,warning,none
case customImage(imageFile:String)
}
open class SweetAlert: UIViewController {
let kBakcgroundTansperancy: CGFloat = 0.7
let kHeightMargin: CGFloat = 10.0
let KTopMargin: CGFloat = 20.0
let kWidthMargin: CGFloat = 10.0
let kAnimatedViewHeight: CGFloat = 70.0
let kMaxHeight: CGFloat = 300.0
var kContentWidth: CGFloat = 300.0
let kButtonHeight: CGFloat = 35.0
var textViewHeight: CGFloat = 90.0
let kTitleHeight:CGFloat = 30.0
var strongSelf:SweetAlert?
var contentView = UIView()
var titleLabel: UILabel = UILabel()
var buttons: [UIButton] = []
var animatedView: AnimatableView?
var imageView:UIImageView?
var subTitleTextView = UITextView()
var userAction:((_ isOtherButton: Bool) -> Void)? = nil
let kFont = "Helvetica"
init() {
super.init(nibName: nil, bundle: nil)
self.view.frame = UIScreen.main.bounds
self.view.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth]
self.view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:kBakcgroundTansperancy)
self.view.addSubview(contentView)
//Retaining itself strongly so can exist without strong refrence
strongSelf = self
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupContentView() {
contentView.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
contentView.layer.cornerRadius = 5.0
contentView.layer.masksToBounds = true
contentView.layer.borderWidth = 0.5
contentView.addSubview(titleLabel)
contentView.addSubview(subTitleTextView)
contentView.backgroundColor = UIColor.colorFromRGB(0xFFFFFF)
contentView.layer.borderColor = UIColor.colorFromRGB(0xCCCCCC).cgColor
view.addSubview(contentView)
}
fileprivate func setupTitleLabel() {
titleLabel.text = ""
titleLabel.numberOfLines = 1
titleLabel.textAlignment = .center
titleLabel.font = UIFont(name: kFont, size:25)
titleLabel.textColor = UIColor.colorFromRGB(0x575757)
}
fileprivate func setupSubtitleTextView() {
subTitleTextView.text = ""
subTitleTextView.textAlignment = .center
subTitleTextView.font = UIFont(name: kFont, size:16)
subTitleTextView.textColor = UIColor.colorFromRGB(0x797979)
subTitleTextView.isEditable = false
}
fileprivate func resizeAndRelayout() {
let mainScreenBounds = UIScreen.main.bounds
self.view.frame.size = mainScreenBounds.size
let x: CGFloat = kWidthMargin
var y: CGFloat = KTopMargin
let width: CGFloat = kContentWidth - (kWidthMargin*2)
if animatedView != nil {
animatedView!.frame = CGRect(x: (kContentWidth - kAnimatedViewHeight) / 2.0, y: y, width: kAnimatedViewHeight, height: kAnimatedViewHeight)
contentView.addSubview(animatedView!)
y += kAnimatedViewHeight + kHeightMargin
}
if imageView != nil {
imageView!.frame = CGRect(x: (kContentWidth - kAnimatedViewHeight) / 2.0, y: y, width: kAnimatedViewHeight, height: kAnimatedViewHeight)
contentView.addSubview(imageView!)
y += imageView!.frame.size.height + kHeightMargin
}
// Title
if self.titleLabel.text != nil {
titleLabel.frame = CGRect(x: x, y: y, width: width, height: kTitleHeight)
contentView.addSubview(titleLabel)
y += kTitleHeight + kHeightMargin
}
// Subtitle
if self.subTitleTextView.text.isEmpty == false {
let subtitleString = subTitleTextView.text! as NSString
let rect = subtitleString.boundingRect(with: CGSize(width: width, height: 0.0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:subTitleTextView.font!], context: nil)
textViewHeight = ceil(rect.size.height) + 10.0
subTitleTextView.frame = CGRect(x: x, y: y, width: width, height: textViewHeight)
contentView.addSubview(subTitleTextView)
y += textViewHeight + kHeightMargin
}
var buttonRect:[CGRect] = []
for button in buttons {
let string = button.title(for: UIControlState())! as NSString
buttonRect.append(string.boundingRect(with: CGSize(width: width, height:0.0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:[NSFontAttributeName:button.titleLabel!.font], context:nil))
}
var totalWidth: CGFloat = 0.0
if buttons.count == 2 {
totalWidth = buttonRect[0].size.width + buttonRect[1].size.width + kWidthMargin + 40.0
}
else{
totalWidth = buttonRect[0].size.width + 20.0
}
y += kHeightMargin
var buttonX = (kContentWidth - totalWidth ) / 2.0
for i in 0 ..< buttons.count {
buttons[i].frame = CGRect(x: buttonX, y: y, width: buttonRect[i].size.width + 20.0, height: buttonRect[i].size.height + 10.0)
buttonX = buttons[i].frame.origin.x + kWidthMargin + buttonRect[i].size.width + 20.0
buttons[i].layer.cornerRadius = 5.0
self.contentView.addSubview(buttons[i])
buttons[i].addTarget(self, action: #selector(SweetAlert.pressed(_:)), for: UIControlEvents.touchUpInside)
}
y += kHeightMargin + buttonRect[0].size.height + 10.0
if y > kMaxHeight {
let diff = y - kMaxHeight
let sFrame = subTitleTextView.frame
subTitleTextView.frame = CGRect(x: sFrame.origin.x, y: sFrame.origin.y, width: sFrame.width, height: sFrame.height - diff)
for button in buttons {
let bFrame = button.frame
button.frame = CGRect(x: bFrame.origin.x, y: bFrame.origin.y - diff, width: bFrame.width, height: bFrame.height)
}
y = kMaxHeight
}
contentView.frame = CGRect(x: (mainScreenBounds.size.width - kContentWidth) / 2.0, y: (mainScreenBounds.size.height - y) / 2.0, width: kContentWidth, height: y)
contentView.clipsToBounds = true
}
open func pressed(_ sender: UIButton!) {
self.closeAlert(sender.tag)
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
var sz = UIScreen.main.bounds.size
let sver = UIDevice.current.systemVersion as NSString
let ver = sver.floatValue
if ver < 8.0 {
// iOS versions before 7.0 did not switch the width and height on device roration
if UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) {
let ssz = sz
sz = CGSize(width:ssz.height, height:ssz.width)
}
}
self.resizeAndRelayout()
}
func closeAlert(_ buttonIndex:Int){
if userAction != nil {
let isOtherButton = buttonIndex == 0 ? true: false
SweetAlertContext.shouldNotAnimate = true
userAction!(isOtherButton)
SweetAlertContext.shouldNotAnimate = false
}
UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.view.alpha = 0.0
}) { (Bool) -> Void in
self.view.removeFromSuperview()
self.cleanUpAlert()
//Releasing strong refrence of itself.
self.strongSelf = nil
}
}
func cleanUpAlert() {
if self.animatedView != nil {
self.animatedView!.removeFromSuperview()
self.animatedView = nil
}
self.contentView.removeFromSuperview()
self.contentView = UIView()
}
open func showAlert(_ title: String) -> SweetAlert {
_ = showAlert(title, subTitle: nil, style: .none)
return self
}
open func showAlert(_ title: String, subTitle: String?, style: AlertStyle) -> SweetAlert {
_ = showAlert(title, subTitle: subTitle, style: style, buttonTitle: "OK")
return self
}
open func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String, action: ((_ isOtherButton: Bool) -> Void)? = nil) -> SweetAlert {
_ = showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: UIColor.colorFromRGB(0xAEDEF4))
userAction = action
return self
}
open func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,action: ((_ isOtherButton: Bool) -> Void)? = nil) -> SweetAlert {
_ = showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: buttonColor,otherButtonTitle:
nil)
userAction = action
return self
}
open func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,otherButtonTitle:
String?, action: ((_ isOtherButton: Bool) -> Void)? = nil) -> SweetAlert {
self.showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: buttonColor,otherButtonTitle:
otherButtonTitle,otherButtonColor: UIColor.red)
userAction = action
return self
}
open func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,otherButtonTitle:
String?, otherButtonColor: UIColor?,action: ((_ isOtherButton: Bool) -> Void)? = nil) {
userAction = action
let window: UIWindow = UIApplication.shared.keyWindow!
window.addSubview(view)
window.bringSubview(toFront: view)
view.frame = window.bounds
self.setupContentView()
self.setupTitleLabel()
self.setupSubtitleTextView()
switch style {
case .success:
self.animatedView = SuccessAnimatedView()
case .error:
self.animatedView = CancelAnimatedView()
case .warning:
self.animatedView = InfoAnimatedView()
case let .customImage(imageFile):
if let image = UIImage(named: imageFile) {
self.imageView = UIImageView(image: image)
}
case .none:
self.animatedView = nil
}
self.titleLabel.text = title
if subTitle != nil {
self.subTitleTextView.text = subTitle
}
buttons = []
if buttonTitle.isEmpty == false {
let button: UIButton = UIButton(type: UIButtonType.custom)
button.setTitle(buttonTitle, for: UIControlState())
button.backgroundColor = buttonColor
button.isUserInteractionEnabled = true
button.tag = 0
buttons.append(button)
}
if otherButtonTitle != nil && otherButtonTitle!.isEmpty == false {
let button: UIButton = UIButton(type: UIButtonType.custom)
button.setTitle(otherButtonTitle, for: UIControlState())
button.backgroundColor = otherButtonColor
button.addTarget(self, action: #selector(SweetAlert.pressed(_:)), for: UIControlEvents.touchUpInside)
button.tag = 1
buttons.append(button)
}
resizeAndRelayout()
if SweetAlertContext.shouldNotAnimate == true {
//Do not animate Alert
if self.animatedView != nil {
self.animatedView!.animate()
}
}
else {
animateAlert()
}
}
func animateAlert() {
view.alpha = 0;
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.view.alpha = 1.0;
})
let previousTransform = self.contentView.transform
self.contentView.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0);
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.contentView.layer.transform = CATransform3DMakeScale(1.1, 1.1, 0.0);
}, completion: { (Bool) -> Void in
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.contentView.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0);
}, completion: { (Bool) -> Void in
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.contentView.layer.transform = CATransform3DMakeScale(1.0, 1.0, 0.0);
if self.animatedView != nil {
self.animatedView!.animate()
}
}, completion: { (Bool) -> Void in
self.contentView.transform = previousTransform
})
})
})
}
fileprivate struct SweetAlertContext {
static var shouldNotAnimate = false
}
}
// MARK: -
// MARK: Animatable Views
class AnimatableView: UIView {
func animate(){
print("Should overide by subclasss", terminator: "")
}
}
class CancelAnimatedView: AnimatableView {
var circleLayer = CAShapeLayer()
var crossPathLayer = CAShapeLayer()
override required init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
var t = CATransform3DIdentity;
t.m34 = 1.0 / -500.0;
t = CATransform3DRotate(t, CGFloat(90.0 * M_PI / 180.0), 1, 0, 0);
circleLayer.transform = t
crossPathLayer.opacity = 0.0
}
override func layoutSubviews() {
setupLayers()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate var outlineCircle: CGPath {
let path = UIBezierPath()
let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0
let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360
path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.width/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
return path.cgPath
}
fileprivate var crossPath: CGPath {
let path = UIBezierPath()
let factor:CGFloat = self.frame.size.width / 5.0
path.move(to: CGPoint(x: self.frame.size.height/2.0-factor,y: self.frame.size.height/2.0-factor))
path.addLine(to: CGPoint(x: self.frame.size.height/2.0+factor,y: self.frame.size.height/2.0+factor))
path.move(to: CGPoint(x: self.frame.size.height/2.0+factor,y: self.frame.size.height/2.0-factor))
path.addLine(to: CGPoint(x: self.frame.size.height/2.0-factor,y: self.frame.size.height/2.0+factor))
return path.cgPath
}
fileprivate func setupLayers() {
circleLayer.path = outlineCircle
circleLayer.fillColor = UIColor.clear.cgColor;
circleLayer.strokeColor = UIColor.colorFromRGB(0xF27474).cgColor;
circleLayer.lineCap = kCALineCapRound
circleLayer.lineWidth = 4;
circleLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
circleLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0)
self.layer.addSublayer(circleLayer)
crossPathLayer.path = crossPath
crossPathLayer.fillColor = UIColor.clear.cgColor;
crossPathLayer.strokeColor = UIColor.colorFromRGB(0xF27474).cgColor;
crossPathLayer.lineCap = kCALineCapRound
crossPathLayer.lineWidth = 4;
crossPathLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
crossPathLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0)
self.layer.addSublayer(crossPathLayer)
}
override func animate() {
var t = CATransform3DIdentity;
t.m34 = 1.0 / -500.0;
t = CATransform3DRotate(t, CGFloat(90.0 * M_PI / 180.0), 1, 0, 0);
var t2 = CATransform3DIdentity;
t2.m34 = 1.0 / -500.0;
t2 = CATransform3DRotate(t2, CGFloat(-M_PI), 1, 0, 0);
let animation = CABasicAnimation(keyPath: "transform")
let time = 0.3
animation.duration = time;
animation.fromValue = NSValue(caTransform3D: t)
animation.toValue = NSValue(caTransform3D:t2)
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
self.circleLayer.add(animation, forKey: "transform")
var scale = CATransform3DIdentity;
scale = CATransform3DScale(scale, 0.3, 0.3, 0)
let crossAnimation = CABasicAnimation(keyPath: "transform")
crossAnimation.duration = 0.3;
crossAnimation.beginTime = CACurrentMediaTime() + time
crossAnimation.fromValue = NSValue(caTransform3D: scale)
crossAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.25, 0.8, 0.7, 2.0)
crossAnimation.toValue = NSValue(caTransform3D:CATransform3DIdentity)
self.crossPathLayer.add(crossAnimation, forKey: "scale")
let fadeInAnimation = CABasicAnimation(keyPath: "opacity")
fadeInAnimation.duration = 0.3;
fadeInAnimation.beginTime = CACurrentMediaTime() + time
fadeInAnimation.fromValue = 0.3
fadeInAnimation.toValue = 1.0
fadeInAnimation.isRemovedOnCompletion = false
fadeInAnimation.fillMode = kCAFillModeForwards
self.crossPathLayer.add(fadeInAnimation, forKey: "opacity")
}
}
class InfoAnimatedView: AnimatableView {
var circleLayer = CAShapeLayer()
var crossPathLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
}
override func layoutSubviews() {
setupLayers()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var outlineCircle: CGPath {
let path = UIBezierPath()
let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0
let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360
path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.width/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
let factor:CGFloat = self.frame.size.width / 1.5
path.move(to: CGPoint(x: self.frame.size.width/2.0 , y: 15.0))
path.addLine(to: CGPoint(x: self.frame.size.width/2.0,y: factor))
path.move(to: CGPoint(x: self.frame.size.width/2.0,y: factor + 10.0))
path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0,y: factor + 10.0), radius: 1.0, startAngle: startAngle, endAngle: endAngle, clockwise: true)
return path.cgPath
}
func setupLayers() {
circleLayer.path = outlineCircle
circleLayer.fillColor = UIColor.clear.cgColor;
circleLayer.strokeColor = UIColor.colorFromRGB(0xF8D486).cgColor;
circleLayer.lineCap = kCALineCapRound
circleLayer.lineWidth = 4;
circleLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
circleLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0)
self.layer.addSublayer(circleLayer)
}
override func animate() {
let colorAnimation = CABasicAnimation(keyPath:"strokeColor")
colorAnimation.duration = 1.0;
colorAnimation.repeatCount = HUGE
colorAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
colorAnimation.autoreverses = true
colorAnimation.fromValue = UIColor.colorFromRGB(0xF7D58B).cgColor
colorAnimation.toValue = UIColor.colorFromRGB(0xF2A665).cgColor
circleLayer.add(colorAnimation, forKey: "strokeColor")
}
}
class SuccessAnimatedView: AnimatableView {
var circleLayer = CAShapeLayer()
var outlineLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
circleLayer.strokeStart = 0.0
circleLayer.strokeEnd = 0.0
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
setupLayers()
}
var outlineCircle: CGPath {
let path = UIBezierPath()
let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0
let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360
path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
return path.cgPath
}
var path: CGPath {
let path = UIBezierPath()
let startAngle:CGFloat = CGFloat((60) / 180.0 * M_PI) //60
let endAngle:CGFloat = CGFloat((200) / 180.0 * M_PI) //190
path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
path.addLine(to: CGPoint(x: 36.0 - 10.0 ,y: 60.0 - 10.0))
path.addLine(to: CGPoint(x: 85.0 - 20.0, y: 30.0 - 20.0))
return path.cgPath
}
func setupLayers() {
outlineLayer.position = CGPoint(x: 0,
y: 0);
outlineLayer.path = outlineCircle
outlineLayer.fillColor = UIColor.clear.cgColor;
outlineLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).cgColor;
outlineLayer.lineCap = kCALineCapRound
outlineLayer.lineWidth = 4;
outlineLayer.opacity = 0.1
self.layer.addSublayer(outlineLayer)
circleLayer.position = CGPoint(x: 0,
y: 0);
circleLayer.path = path
circleLayer.fillColor = UIColor.clear.cgColor;
circleLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).cgColor;
circleLayer.lineCap = kCALineCapRound
circleLayer.lineWidth = 4;
circleLayer.actions = [
"strokeStart": NSNull(),
"strokeEnd": NSNull(),
"transform": NSNull()
]
self.layer.addSublayer(circleLayer)
}
override func animate() {
let strokeStart = CABasicAnimation(keyPath: "strokeStart")
let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
let factor = 0.045
strokeEnd.fromValue = 0.00
strokeEnd.toValue = 0.93
strokeEnd.duration = 10.0*factor
let timing = CAMediaTimingFunction(controlPoints: 0.3, 0.6, 0.8, 1.2)
strokeEnd.timingFunction = timing
strokeStart.fromValue = 0.0
strokeStart.toValue = 0.68
strokeStart.duration = 7.0*factor
strokeStart.beginTime = CACurrentMediaTime() + 3.0*factor
strokeStart.fillMode = kCAFillModeBackwards
strokeStart.timingFunction = timing
circleLayer.strokeStart = 0.68
circleLayer.strokeEnd = 0.93
self.circleLayer.add(strokeEnd, forKey: "strokeEnd")
self.circleLayer.add(strokeStart, forKey: "strokeStart")
}
}
extension UIColor {
class func colorFromRGB(_ rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
|
mit
|
82326768d1068add13e2e3ff663f7705
| 39.185668 | 219 | 0.616641 | 4.503377 | false | false | false | false |
m-alani/contests
|
hackerrank/AlternatingCharacters.swift
|
1
|
1595
|
//
// AlternatingCharacters.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/alternating-characters
// Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code
//
if let cases: Int = Int(readLine() ?? "0") {
var output: [String] = [String]()
// Process Input
for _ in 1...cases {
if let input: String = readLine() {
// Initializations
var line: String.CharacterView = input.characters
var deleteOperations: Int = 0
var charIndex: String.CharacterView.Index = line.startIndex
var previousChar: Character = line[charIndex]
charIndex = line.index(after: charIndex)
// Loop through the input line, starting at the second character
while (charIndex != line.endIndex) {
// Same character as before? Delete
if (line[charIndex] == previousChar) {
line.remove(at: charIndex)
deleteOperations += 1
} else {
// Not the same? update the previous character variable, and move on
previousChar = line[charIndex]
charIndex = line.index(after: charIndex)
}
}
// Save the number of deletions for this case
output.append("\(deleteOperations)")
}
}
// Print Output
for line in output {
print(line)
}
}
|
mit
|
22b68f185a8c464260ff21f8f3d0de49
| 36.093023 | 118 | 0.571787 | 4.623188 | false | false | false | false |
acmacalister/Github-Swift
|
Github/Login/Login.swift
|
1
|
3198
|
//
// Login.swift
// Github
//
// Created by Austin Cherry on 6/3/14.
// Copyright (c) 2014 Vluxe. All rights reserved.
//
import SwiftHTTP
import JSONJoy
struct App: JSONJoy {
var url: String?
var name: String?
var clientId: String?
init(_ decoder: JSONDecoder) {
url = decoder["url"].string
name = decoder["name"].string
clientId = decoder["client_id"].string
}
}
struct Authorization: JSONJoy {
var id: Int?
var url: String?
//var scopes: Array<String>?
var app: App?
var token: String?
var note: String?
var noteUrl: String?
//var updatedAt: String?
//var createdAt: String?
init(_ decoder: JSONDecoder) {
id = decoder["id"].integer
url = decoder["url"].string
//decoder["scopes"].array(&scopes)
app = App(decoder["app"])
token = decoder["token"].string
note = decoder["note"].string
noteUrl = decoder["note_url"].string
//updatedAt = decoder["updated_at"].string
//createdAt = decoder["created_at"].string
}
}
struct Login {
let clientId = "80b1798b0b410dd723ee"
let clientSecret = "58b7abd90008cb39626802d4bb9444c53d9d79ad"
var basicAuth = ""
init(username: String, password: String) {
let optData = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding)
if let data = optData {
basicAuth = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
}
}
func auth(completionHandler: (Bool -> Void)) -> Void {
let params = ["scopes":"repo", "note": "dev", "client_id": clientId, "client_secret": clientSecret]
do {
let opt = try HTTP.POST("https://api.github.com/authorizations", parameters: params, headers: ["Authorization": "Basic \(basicAuth)"] ,requestSerializer: JSONParameterSerializer())
opt.start { response in
if let error = response.error {
print("got an error: \(error)")
dispatch_async(dispatch_get_main_queue(),{
completionHandler(false)
})
return //also notify app of failure as needed
}
let auth = Authorization(JSONDecoder(response.data))
if let token = auth.token {
print("token: \(token)")
let defaults = NSUserDefaults()
defaults.setObject(token, forKey: "token")
defaults.synchronize()
dispatch_async(dispatch_get_main_queue(),{
completionHandler(true)
})
} else {
dispatch_async(dispatch_get_main_queue(),{
completionHandler(false)
})
}
}
} catch let error {
dispatch_async(dispatch_get_main_queue(),{
completionHandler(false)
})
print("got an error creating the request: \(error)")
}
}
}
|
mit
|
ac3b6d8b6f0e4fcd9be206afb5f106d2
| 31.642857 | 192 | 0.54065 | 4.702941 | false | false | false | false |
klundberg/swift-corelibs-foundation
|
Foundation/NSURLResponse.swift
|
1
|
17291
|
// 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
//
/// An `NSURLResponse` object represents a URL load response in a
/// manner independent of protocol and URL scheme.
///
/// `NSURLResponse` encapsulates the metadata associated
/// with a URL load. Note that NSURLResponse objects do not contain
/// the actual bytes representing the content of a URL. See
/// `NSURLSession` for more information about receiving the content
/// data for a URL load.
public class URLResponse : NSObject, NSSecureCoding, NSCopying {
static public func supportsSecureCoding() -> Bool {
return true
}
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
public func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
public func copy(with zone: NSZone? = nil) -> AnyObject {
return self
}
/// Initialize an NSURLResponse with the provided values.
///
/// This is the designated initializer for NSURLResponse.
/// - Parameter URL: the URL
/// - Parameter mimeType: the MIME content type of the response
/// - Parameter expectedContentLength: the expected content length of the associated data
/// - Parameter textEncodingName the name of the text encoding for the associated data, if applicable, else nil
/// - Returns: The initialized NSURLResponse.
public init(url: URL, mimeType: String?, expectedContentLength length: Int, textEncodingName name: String?) {
self.url = url
self.mimeType = mimeType
self.expectedContentLength = Int64(length)
self.textEncodingName = name
let c = url.lastPathComponent
self.suggestedFilename = (c?.isEmpty ?? true) ? "Unknown" : c
}
/// The URL of the receiver.
/*@NSCopying*/ public private(set) var url: URL?
/// The MIME type of the receiver.
///
/// The MIME type is based on the information provided
/// from an origin source. However, that value may be changed or
/// corrected by a protocol implementation if it can be determined
/// that the origin server or source reported the information
/// incorrectly or imprecisely. An attempt to guess the MIME type may
/// be made if the origin source did not report any such information.
public private(set) var mimeType: String?
/// The expected content length of the receiver.
///
/// Some protocol implementations report a content length
/// as part of delivering load metadata, but not all protocols
/// guarantee the amount of data that will be delivered in actuality.
/// Hence, this method returns an expected amount. Clients should use
/// this value as an advisory, and should be prepared to deal with
/// either more or less data.
///
/// The expected content length of the receiver, or `-1` if
/// there is no expectation that can be arrived at regarding expected
/// content length.
public private(set) var expectedContentLength: Int64
/// The name of the text encoding of the receiver.
///
/// This name will be the actual string reported by the
/// origin source during the course of performing a protocol-specific
/// URL load. Clients can inspect this string and convert it to an
/// NSStringEncoding or CFStringEncoding using the methods and
/// functions made available in the appropriate framework.
public private(set) var textEncodingName: String?
/// A suggested filename if the resource were saved to disk.
///
/// The method first checks if the server has specified a filename
/// using the content disposition header. If no valid filename is
/// specified using that mechanism, this method checks the last path
/// component of the URL. If no valid filename can be obtained using
/// the last path component, this method uses the URL's host as the
/// filename. If the URL's host can't be converted to a valid
/// filename, the filename "unknown" is used. In mose cases, this
/// method appends the proper file extension based on the MIME type.
///
/// This method always returns a valid filename.
public private(set) var suggestedFilename: String?
}
/// A Response to an HTTP URL load.
///
/// An NSHTTPURLResponse object represents a response to an
/// HTTP URL load. It is a specialization of NSURLResponse which
/// provides conveniences for accessing information specific to HTTP
/// protocol responses.
public class NSHTTPURLResponse : URLResponse {
/// Initializer for NSHTTPURLResponse objects.
///
/// - Parameter url: the URL from which the response was generated.
/// - Parameter statusCode: an HTTP status code.
/// - Parameter httpVersion: The version of the HTTP response as represented by the server. This is typically represented as "HTTP/1.1".
/// - Parameter headerFields: A dictionary representing the header keys and values of the server response.
/// - Returns: the instance of the object, or `nil` if an error occurred during initialization.
public init?(url: URL, statusCode: Int, httpVersion: String?, headerFields: [String : String]?) {
self.statusCode = statusCode
self.allHeaderFields = headerFields ?? [:]
super.init(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil)
expectedContentLength = getExpectedContentLength(fromHeaderFields: headerFields) ?? -1
suggestedFilename = getSuggestedFilename(fromHeaderFields: headerFields) ?? "Unknown"
if let type = ContentTypeComponents(headerFields: headerFields) {
mimeType = type.mimeType.lowercased()
textEncodingName = type.textEncoding?.lowercased()
}
}
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
/// The HTTP status code of the receiver.
public let statusCode: Int
/// Returns a dictionary containing all the HTTP header fields
/// of the receiver.
///
/// By examining this header dictionary, clients can see
/// the "raw" header information which was reported to the protocol
/// implementation by the HTTP server. This may be of use to
/// sophisticated or special-purpose HTTP clients.
///
/// - Returns: A dictionary containing all the HTTP header fields of the
/// receiver.
///
/// - Important: This is an *experimental* change from the
/// `[NSObject: AnyObject]` type that Darwin Foundation uses.
public let allHeaderFields: [String: String]
/// Convenience method which returns a localized string
/// corresponding to the status code for this response.
/// - Parameter forStatusCode: the status code to use to produce a localized string.
public class func localizedString(forStatusCode statusCode: Int) -> String {
switch statusCode {
case 100: return "Continue"
case 101: return "Switching Protocols"
case 102: return "Processing"
case 100...199: return "Informational"
case 200: return "OK"
case 201: return "Created"
case 202: return "Accepted"
case 203: return "Non-Authoritative Information"
case 204: return "No Content"
case 205: return "Reset Content"
case 206: return "Partial Content"
case 207: return "Multi-Status"
case 208: return "Already Reported"
case 226: return "IM Used"
case 200...299: return "Success"
case 300: return "Multiple Choices"
case 301: return "Moved Permanently"
case 302: return "Found"
case 303: return "See Other"
case 304: return "Not Modified"
case 305: return "Use Proxy"
case 307: return "Temporary Redirect"
case 308: return "Permanent Redirect"
case 300...399: return "Redirection"
case 400: return "Bad Request"
case 401: return "Unauthorized"
case 402: return "Payment Required"
case 403: return "Forbidden"
case 404: return "Not Found"
case 405: return "Method Not Allowed"
case 406: return "Not Acceptable"
case 407: return "Proxy Authentication Required"
case 408: return "Request Timeout"
case 409: return "Conflict"
case 410: return "Gone"
case 411: return "Length Required"
case 412: return "Precondition Failed"
case 413: return "Payload Too Large"
case 414: return "URI Too Long"
case 415: return "Unsupported Media Type"
case 416: return "Range Not Satisfiable"
case 417: return "Expectation Failed"
case 421: return "Misdirected Request"
case 422: return "Unprocessable Entity"
case 423: return "Locked"
case 424: return "Failed Dependency"
case 426: return "Upgrade Required"
case 428: return "Precondition Required"
case 429: return "Too Many Requests"
case 431: return "Request Header Fields Too Large"
case 451: return "Unavailable For Legal Reasons"
case 400...499: return "Client Error"
case 500: return "Internal Server Error"
case 501: return "Not Implemented"
case 502: return "Bad Gateway"
case 503: return "Service Unavailable"
case 504: return "Gateway Timeout"
case 505: return "HTTP Version Not Supported"
case 506: return "Variant Also Negotiates"
case 507: return "Insufficient Storage"
case 508: return "Loop Detected"
case 510: return "Not Extended"
case 511: return "Network Authentication Required"
case 500...599: return "Server Error"
default: return "Server Error"
}
}
/// A string that represents the contents of the NSHTTPURLResponse Object.
/// This property is intended to produce readable output.
override public var description: String {
var result = "<\(self.dynamicType) \(unsafeAddress(of: self))> { URL: \(url!.absoluteString) }{ status: \(statusCode), headers {\n"
for(key, value) in allHeaderFields {
if((key.lowercased() == "content-disposition" && suggestedFilename != "Unknown") || key.lowercased() == "content-type") {
result += " \"\(key)\" = \"\(value)\";\n"
} else {
result += " \"\(key)\" = \(value);\n"
}
}
result += "} }"
return result
}
}
/// Parses the expected content length from the headers.
///
/// Note that the message content length is different from the message
/// transfer length.
/// The transfer length can only be derived when the Transfer-Encoding is identity (default).
/// For compressed content (Content-Encoding other than identity), there is not way to derive the
/// content length from the transfer length.
private func getExpectedContentLength(fromHeaderFields headerFields: [String : String]?) -> Int64? {
guard
let f = headerFields,
let contentLengthS = valueForCaseInsensitiveKey("content-length", fields: f),
let contentLength = Int64(contentLengthS)
else { return nil }
return contentLength
}
/// Parses the suggested filename from the `Content-Disposition` header.
///
/// - SeeAlso: [RFC 2183](https://tools.ietf.org/html/rfc2183)
private func getSuggestedFilename(fromHeaderFields headerFields: [String : String]?) -> String? {
// Typical use looks like this:
// Content-Disposition: attachment; filename="fname.ext"
guard
let f = headerFields,
let contentDisposition = valueForCaseInsensitiveKey("content-disposition", fields: f),
let field = contentDisposition.httpHeaderParts
else { return nil }
for part in field.parameters where part.attribute == "filename" {
if let path = part.value {
return _pathComponents(path)?.map{ $0 == "/" ? "" : $0}.joined(separator: "_")
} else {
return nil
}
}
return nil
}
/// Parts corresponding to the `Content-Type` header field in a HTTP message.
private struct ContentTypeComponents {
/// For `text/html; charset=ISO-8859-4` this would be `text/html`
let mimeType: String
/// For `text/html; charset=ISO-8859-4` this would be `ISO-8859-4`. Will be
/// `nil` when no `charset` is specified.
let textEncoding: String?
}
extension ContentTypeComponents {
/// Parses the `Content-Type` header field
///
/// `Content-Type: text/html; charset=ISO-8859-4` would result in `("text/html", "ISO-8859-4")`, while
/// `Content-Type: text/html` would result in `("text/html", nil)`.
init?(headerFields: [String : String]?) {
guard
let f = headerFields,
let contentType = valueForCaseInsensitiveKey("content-type", fields: f),
let field = contentType.httpHeaderParts
else { return nil }
for parameter in field.parameters where parameter.attribute == "charset" {
self.mimeType = field.value
self.textEncoding = parameter.value
return
}
self.mimeType = field.value
self.textEncoding = nil
}
}
/// A type with paramteres
///
/// RFC 2616 specifies a few types that can have parameters, e.g. `Content-Type`.
/// These are specified like so
/// ```
/// field = value *( ";" parameter )
/// value = token
/// ```
/// where parameters are attribute/value as specified by
/// ```
/// parameter = attribute "=" value
/// attribute = token
/// value = token | quoted-string
/// ```
private struct ValueWithParameters {
let value: String
let parameters: [Parameter]
struct Parameter {
let attribute: String
let value: String?
}
}
private extension String {
/// Split the string at each ";", remove any quoting.
///
/// The trouble is if there's a
/// ";" inside something that's quoted. And we can escape the separator and
/// the quotes with a "\".
var httpHeaderParts: ValueWithParameters? {
var type: String?
var parameters: [ValueWithParameters.Parameter] = []
let ws = CharacterSet.whitespaces
func append(_ string: String) {
if type == nil {
type = string
} else {
if let r = string.range(of: "=") {
let name = string[string.startIndex..<r.lowerBound].trimmingCharacters(in: ws)
let value = string[r.upperBound..<string.endIndex].trimmingCharacters(in: ws)
parameters.append(ValueWithParameters.Parameter(attribute: name, value: value))
} else {
let name = string.trimmingCharacters(in: ws)
parameters.append(ValueWithParameters.Parameter(attribute: name, value: nil))
}
}
}
let escape = UnicodeScalar(0x5c) // \
let quote = UnicodeScalar(0x22) // "
let separator = UnicodeScalar(0x3b) // ;
enum State {
case nonQuoted(String)
case nonQuotedEscaped(String)
case quoted(String)
case quotedEscaped(String)
}
var state = State.nonQuoted("")
for next in unicodeScalars {
switch (state, next) {
case (.nonQuoted(let s), separator):
append(s)
state = .nonQuoted("")
case (.nonQuoted(let s), escape):
state = .nonQuotedEscaped(s + String(next))
case (.nonQuoted(let s), quote):
state = .quoted(s)
case (.nonQuoted(let s), _):
state = .nonQuoted(s + String(next))
case (.nonQuotedEscaped(let s), _):
state = .nonQuoted(s + String(next))
case (.quoted(let s), quote):
state = .nonQuoted(s)
case (.quoted(let s), escape):
state = .quotedEscaped(s + String(next))
case (.quoted(let s), _):
state = .quoted(s + String(next))
case (.quotedEscaped(let s), _):
state = .quoted(s + String(next))
}
}
switch state {
case .nonQuoted(let s): append(s)
case .nonQuotedEscaped(let s): append(s)
case .quoted(let s): append(s)
case .quotedEscaped(let s): append(s)
}
guard let t = type else { return nil }
return ValueWithParameters(value: t, parameters: parameters)
}
}
private func valueForCaseInsensitiveKey(_ key: String, fields: [String: String]) -> String? {
let kk = key.lowercased()
for (k, v) in fields {
if k.lowercased() == kk {
return v
}
}
return nil
}
|
apache-2.0
|
93891ff8436451ac1af369065cb65052
| 40.7657 | 141 | 0.630559 | 4.742457 | false | false | false | false |
chain/chain
|
desktop/mac/ChainCore/TaskCleaner.swift
|
1
|
1064
|
import Foundation
// Note: this is not the most efficient way to watch the parent's death.
// This will be more efficient, but requires more complicated Xcode setup with extra binaries:
// https://developer.apple.com/reference/corefoundation/1667011-cffiledescriptor
class TaskCleaner {
public let childPid: Int32
public let parentPid: Int32
public let interval: Int
private var task:Process? = nil
init(childPid: Int32, parentPid: Int32 = ProcessInfo.processInfo.processIdentifier, interval: Int = 1) {
self.parentPid = parentPid
self.childPid = childPid
self.interval = interval
}
func watch() {
if task != nil {
task?.terminate()
task = nil
}
let script = "while kill -0 \(parentPid); do sleep \(interval); done; kill -9 \(childPid); exit 1"
task = Process()
task?.launchPath = "/bin/sh"
task?.arguments = ["-c", script]
task?.launch()
}
func terminate() {
task?.terminate()
task = nil
}
}
|
agpl-3.0
|
3f04559a9f8d101c7bb79f933b1572a3
| 27 | 108 | 0.619361 | 4.140078 | false | false | false | false |
kallahir/MarvelFinder
|
MarvelFinder/CollectionItemDetailViewController.swift
|
1
|
1501
|
//
// CollectionItemDetailViewController.swift
// MarvelFinder
//
// Created by Itallo Rossi Lucas on 20/01/17.
// Copyright © 2017 Kallahir Labs. All rights reserved.
//
import UIKit
class CollectionItemDetailViewController: UIViewController {
@IBOutlet weak var collectionImage: UIImageView!
@IBOutlet weak var collectionTitle: UILabel!
@IBOutlet weak var collectionLinkButton: UIButton!
var collectionItem: CollectionItem!
var collectionType: String!
override func viewDidLoad() {
let urlString = "\(self.collectionItem.thumbnail ?? "nothing")/portrait_incredible.\(self.collectionItem.thumbFormat ?? "nothing")"
self.collectionImage.af_setImage(withURL: URL(string: urlString)!, placeholderImage: UIImage(named: "placeholder_collection_item"), imageTransition: UIImageView.ImageTransition.crossDissolve(0.3))
self.collectionTitle.text = self.collectionItem.name
self.navigationItem.title = NSLocalizedString(self.collectionType, comment: "")
let label = self.collectionLinkButton.titleLabel
label?.minimumScaleFactor = 0.5
label?.adjustsFontSizeToFitWidth = true
self.collectionLinkButton.setTitle(NSLocalizedString("Cell.marvelAck", comment: ""), for: .normal)
}
@IBAction func linkBackToMarvel(_ sender: Any) {
UIApplication.shared.open(NSURL(string:"http://www.marvel.com/") as! URL, options: [:], completionHandler: nil)
}
}
|
mit
|
64f10748e9402e8b34b0583672a35c1f
| 37.461538 | 204 | 0.707333 | 4.672897 | false | false | false | false |
icylydia/PlayWithLeetCode
|
78. Subsets/Solution.swift
|
1
|
537
|
class Solution {
func subsets(nums: [Int]) -> [[Int]] {
let nums = nums.sort(<)
let count = Int(pow(Double(2), Double(nums.count)))
var ans = [[Int]]()
for i in 0..<count {
var block = [Int]()
var p = i
var idx = 0
while p != 0 {
if (p & 1) != 0 {
block.append(nums[idx])
}
p >>= 1
idx++
}
ans.append(block)
}
return ans
}
}
|
mit
|
5b14e27dd32d7076f6eaeda804956f1c
| 24.571429 | 59 | 0.348231 | 4.162791 | false | false | false | false |
ripventura/VCUIKit
|
VCUIKit/Classes/VCTheme/VCTableView.swift
|
1
|
3158
|
//
// TableView.swift
// VCUIKit
//
// Created by Vitor Cesco on 13/04/17.
// Copyright © 2017 Vitor Cesco. All rights reserved.
//
import UIKit
open class VCTableView: UITableView {
/** Whether the appearance is being set manually on Storyboard */
@IBInspectable var storyboardAppearance: Bool = false
/** Whether this TableView should react to keyboard notifications. Use only under a UIViewController.
UITableViewController already does this by default. */
@IBInspectable var reactToKeyboard: Bool = true
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.applyAppearance()
self.setupNotifications()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
self.applyAppearance()
self.setupNotifications()
}
deinit {
self.removeNotifications()
}
override open func applyAppearance() -> Void {
super.applyAppearance()
if !storyboardAppearance {
self.backgroundColor = sharedAppearanceManager.appearance.tableViewBackgroundColor
self.separatorColor = sharedAppearanceManager.appearance.tableViewSeparatorColor
}
}
// MARK: - Keyboard Notifications
// Listens for Keyboard notifications
func setupNotifications() -> Void {
if self.reactToKeyboard {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}
}
// Removes Keyboard notifications
func removeNotifications() -> Void {
if self.reactToKeyboard {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}
}
@objc private func keyboardDidShow(notification : NSNotification) {
let keyboardHeight : CGFloat = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size.height
self.contentInset = UIEdgeInsetsMake(self.contentInset.top, self.contentInset.left, self.contentInset.bottom >= keyboardHeight ? self.contentInset.bottom : self.contentInset.bottom + keyboardHeight, self.contentInset.right)
}
@objc private func keyboardDidHide(notification : NSNotification) {
let keyboardHeight : CGFloat = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size.height
self.contentInset = UIEdgeInsetsMake(self.contentInset.top, self.contentInset.left, self.contentInset.bottom >= keyboardHeight ? self.contentInset.bottom - keyboardHeight : self.contentInset.bottom, self.contentInset.right)
}
}
|
mit
|
6f245bc95f59f27a76aa1ec192ff9a95
| 38.962025 | 231 | 0.697181 | 5.378194 | false | false | false | false |
Noobish1/KeyedMapper
|
KeyedMapperTests/Extensions/Foundation/DictionarySpec.swift
|
1
|
1049
|
import Quick
import Nimble
@testable import KeyedMapper
class DictionarySpec: QuickSpec {
override func spec() {
describe("Dictionary") {
describe("mapKeys") {
it("should transform the dictionary's keys into the correct values") {
let dict = ["one": 1, "two": 2]
let expectedKeys = ["onemapped", "twomapped"]
let actualKeys = Array(dict.mapKeys { $0.appending("mapped") }.keys)
expect(actualKeys).to(contain(expectedKeys))
expect(actualKeys.count) == 2
}
}
describe("mapFilterValues") {
it("should map the values then filter out nil values") {
let dict: [String: Int?] = ["one": 1, "two": nil]
let expectedValues = [1]
let actualValues = Array(dict.mapFilterValues { $0 }.values)
expect(actualValues) == expectedValues
}
}
}
}
}
|
mit
|
e92bd57cf12f9ade68ed9d0f24d90f99
| 33.966667 | 88 | 0.49857 | 4.834101 | false | false | false | false |
jieyuanz/Swift-Learning
|
swiftLeaning/swiftLeaning/CollectionViewController.swift
|
1
|
2391
|
//
// CollectionViewController.swift
// swiftLeaning
//
// Created by jieyuan on 2017/10/10.
// Copyright © 2017年 jieyuan.zhuang. All rights reserved.
//
import UIKit
class CollectionViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.collection()
}
func collection (){
//MARK:- 1.集合的可变性
/*
如果创建一个Arrays、Sets或Dictionaries并且把它分配成一个变量,这个集合将会是可变的。
如果把Arrays、Sets或Dictionaries分配成常量,那么它就是不可变的
*/
//MARK:- 2.数组
//MARK:2.1创建一个由特定数据类型构成的空数组
var someInt = [Int]()
someInt.append(3)
someInt = []//如果上下文中已经可以推断 Int 类型,则可以省略 Int 和 ()
//MARK:2.2创建一个带默认值的数值
let threeDoubles = Array(repeating:0.0, count:3)//等价于 [0.0,0.0,0.0]
//MARK:2.3两个数组相加
let anotherThreeDoubles = Array(repeating:2.6, count:3)
let sixDoubles = threeDoubles + anotherThreeDoubles//等价于 [0.0,0.0,0.0,2.6,2.6,2.6]
print("\(threeDoubles),\(anotherThreeDoubles),\(sixDoubles)")
//MARK:2.4从字面量构造数组
var shoppingList:[String] = ["Eggs", "Milk", "Break"]
//类型推断机制,不需要定义类型
var anotherShoppingList = ["Eggs", "Milk", "Break"]
//MARK:2.5访问和修改数组
if !shoppingList.isEmpty {
print("The shopping list contains \(shoppingList.count) items")
}else{
shoppingList.append("Apple")
anotherShoppingList += ["Banana"]
}
let firstItem = shoppingList[0]
shoppingList[0] = "Six eggs"
print("first item is \(firstItem), lists is \(shoppingList)")
//利用下标一次改变一系列数据(注意下标同样不能超出)
shoppingList[0...2] = ["Bananas", "Butter"]//相当于 shoppingList[0,1,2] = ["Bananas", "Butter", nil]
print("lists is \(shoppingList)")
//MARK:- 3.集合
//MARK:- 4.集合操作
//MARK:- 5.字典
}
}
|
mit
|
34a6185f4abb3be8db0acbfe53b8ad5e
| 28.676471 | 105 | 0.562934 | 3.702752 | false | false | false | false |
HackerEdu/ChenWeijia
|
教学/WhatsLEFT/DetailViewControllerTableViewController.swift
|
1
|
3353
|
//
// DetailViewControllerTableViewController.swift
// WhatsLEFT
//
// Created by 陈伟嘉 on 15-2-3.
// Copyright (c) 2015年 陈伟嘉. All rights reserved.
//
import UIKit
class DetailViewControllerTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
d5a4b304a5ea2aa6da489c7c5193e3ef
| 33.42268 | 157 | 0.686733 | 5.57429 | false | false | false | false |
Molbie/Outlaw
|
Sources/Outlaw/Types/Value/Int+Value.swift
|
1
|
6413
|
//
// Int+Value.swift
// Outlaw
//
// Created by Brian Mullen on 11/5/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
extension Int: Value {
public static func value(from object: Any) throws -> Int {
let value: Int
switch object {
case let rawValue as Int:
value = ValueType(rawValue)
case let rawValue as UInt:
value = ValueType(rawValue)
case let rawValue as NSNumber:
value = ValueType(rawValue.intValue)
case let rawValue as Int64:
value = ValueType(rawValue)
case let rawValue as UInt64:
value = ValueType(rawValue)
case let rawValue as Int32:
value = ValueType(rawValue)
case let rawValue as UInt32:
value = ValueType(rawValue)
case let rawValue as Int16:
value = ValueType(rawValue)
case let rawValue as UInt16:
value = ValueType(rawValue)
case let rawValue as Int8:
value = ValueType(rawValue)
case let rawValue as UInt8:
value = ValueType(rawValue)
default:
throw OutlawError.typeMismatch(expected: ValueType.self, actual: type(of: object))
}
return value
}
}
extension Int8: Value {
public static func value(from object: Any) throws -> Int8 {
let value: Int8
switch object {
case let rawValue as Int:
value = ValueType(rawValue)
case let rawValue as UInt:
value = ValueType(rawValue)
case let rawValue as NSNumber:
value = ValueType(rawValue.int8Value)
case let rawValue as Int64:
value = ValueType(rawValue)
case let rawValue as UInt64:
value = ValueType(rawValue)
case let rawValue as Int32:
value = ValueType(rawValue)
case let rawValue as UInt32:
value = ValueType(rawValue)
case let rawValue as Int16:
value = ValueType(rawValue)
case let rawValue as UInt16:
value = ValueType(rawValue)
case let rawValue as Int8:
value = ValueType(rawValue)
case let rawValue as UInt8:
value = ValueType(rawValue)
default:
throw OutlawError.typeMismatch(expected: ValueType.self, actual: type(of: object))
}
return value
}
}
extension Int16: Value {
public static func value(from object: Any) throws -> Int16 {
let value: Int16
switch object {
case let rawValue as Int:
value = ValueType(rawValue)
case let rawValue as UInt:
value = ValueType(rawValue)
case let rawValue as NSNumber:
value = ValueType(rawValue.int16Value)
case let rawValue as Int64:
value = ValueType(rawValue)
case let rawValue as UInt64:
value = ValueType(rawValue)
case let rawValue as Int32:
value = ValueType(rawValue)
case let rawValue as UInt32:
value = ValueType(rawValue)
case let rawValue as Int16:
value = ValueType(rawValue)
case let rawValue as UInt16:
value = ValueType(rawValue)
case let rawValue as Int8:
value = ValueType(rawValue)
case let rawValue as UInt8:
value = ValueType(rawValue)
default:
throw OutlawError.typeMismatch(expected: ValueType.self, actual: type(of: object))
}
return value
}
}
extension Int32: Value {
public static func value(from object: Any) throws -> Int32 {
let value: Int32
switch object {
case let rawValue as Int:
value = ValueType(rawValue)
case let rawValue as UInt:
value = ValueType(rawValue)
case let rawValue as NSNumber:
value = ValueType(rawValue.int32Value)
case let rawValue as Int64:
value = ValueType(rawValue)
case let rawValue as UInt64:
value = ValueType(rawValue)
case let rawValue as Int32:
value = ValueType(rawValue)
case let rawValue as UInt32:
value = ValueType(rawValue)
case let rawValue as Int16:
value = ValueType(rawValue)
case let rawValue as UInt16:
value = ValueType(rawValue)
case let rawValue as Int8:
value = ValueType(rawValue)
case let rawValue as UInt8:
value = ValueType(rawValue)
default:
throw OutlawError.typeMismatch(expected: ValueType.self, actual: type(of: object))
}
return value
}
}
extension Int64: Value {
public static func value(from object: Any) throws -> Int64 {
let value: Int64
switch object {
case let rawValue as Int:
value = ValueType(rawValue)
case let rawValue as UInt:
value = ValueType(rawValue)
case let rawValue as NSNumber:
value = ValueType(rawValue.int64Value)
case let rawValue as Int64:
value = ValueType(rawValue)
case let rawValue as UInt64:
value = ValueType(rawValue)
case let rawValue as Int32:
value = ValueType(rawValue)
case let rawValue as UInt32:
value = ValueType(rawValue)
case let rawValue as Int16:
value = ValueType(rawValue)
case let rawValue as UInt16:
value = ValueType(rawValue)
case let rawValue as Int8:
value = ValueType(rawValue)
case let rawValue as UInt8:
value = ValueType(rawValue)
default:
throw OutlawError.typeMismatch(expected: ValueType.self, actual: type(of: object))
}
return value
}
}
|
mit
|
aaee764c9bd40a447b4d0bcd3e5a393c
| 33.659459 | 98 | 0.536338 | 5.31675 | false | false | false | false |
aatalyk/swift-algorithm-club
|
Huffman Coding/NSData+Bits.swift
|
2
|
1263
|
import Foundation
/* Helper class for writing bits to an NSData object. */
public class BitWriter {
public var data = NSMutableData()
var outByte: UInt8 = 0
var outCount = 0
public func writeBit(bit: Bool) {
if outCount == 8 {
data.append(&outByte, length: 1)
outCount = 0
}
outByte = (outByte << 1) | (bit ? 1 : 0)
outCount += 1
}
public func flush() {
if outCount > 0 {
if outCount < 8 {
let diff = UInt8(8 - outCount)
outByte <<= diff
}
data.append(&outByte, length: 1)
}
}
}
/* Helper class for reading bits from an NSData object. */
public class BitReader {
var ptr: UnsafePointer<UInt8>
var inByte: UInt8 = 0
var inCount = 8
public init(data: NSData) {
ptr = data.bytes.assumingMemoryBound(to: UInt8.self)
}
public func readBit() -> Bool {
if inCount == 8 {
inByte = ptr.pointee // load the next byte
inCount = 0
ptr = ptr.successor()
}
let bit = inByte & 0x80 // read the next bit
inByte <<= 1
inCount += 1
return bit == 0 ? false : true
}
}
|
mit
|
dd44361bd4524cb6c6d6d615c73281b8
| 24.26 | 60 | 0.511481 | 3.984227 | false | false | false | false |
mercadopago/px-ios
|
MercadoPagoSDK/MercadoPagoSDK/Flows/OneTap/UI/PXOneTapInstallments/PXOneTapInstallmentsSelectorCell.swift
|
1
|
3697
|
import UIKit
final class PXOneTapInstallmentsSelectorCell: UITableViewCell {
var data: PXOneTapInstallmentsSelectorData?
func updateData(_ data: PXOneTapInstallmentsSelectorData) {
self.data = data
self.selectionStyle = .default
let selectedView = UIView()
selectedView.backgroundColor = UIColor.Andes.graySolid070
self.selectedBackgroundView = selectedView
let selectedIndicatorView = PXCheckbox(selected: data.isSelected)
selectedIndicatorView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(selectedIndicatorView)
PXLayout.setWidth(owner: selectedIndicatorView, width: 20).isActive = true
PXLayout.setHeight(owner: selectedIndicatorView, height: 20).isActive = true
PXLayout.pinLeft(view: selectedIndicatorView, withMargin: PXLayout.SM_MARGIN).isActive = true
PXLayout.centerVertically(view: selectedIndicatorView)
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.attributedText = data.title
titleLabel.textAlignment = .left
contentView.addSubview(titleLabel)
PXLayout.put(view: titleLabel, rightOf: selectedIndicatorView, withMargin: PXLayout.SM_MARGIN).isActive = true
PXLayout.centerVertically(view: titleLabel).isActive = true
let valueLabelsContainer = UIStackView()
valueLabelsContainer.translatesAutoresizingMaskIntoConstraints = false
valueLabelsContainer.axis = .vertical
let topValueLabel = UILabel()
topValueLabel.translatesAutoresizingMaskIntoConstraints = false
topValueLabel.numberOfLines = 1
topValueLabel.attributedText = data.topValue
topValueLabel.textAlignment = .right
valueLabelsContainer.addArrangedSubview(topValueLabel)
let bottomValueLabel = UILabel()
bottomValueLabel.translatesAutoresizingMaskIntoConstraints = false
bottomValueLabel.numberOfLines = 1
bottomValueLabel.attributedText = data.bottomValue
bottomValueLabel.textAlignment = .right
valueLabelsContainer.addArrangedSubview(bottomValueLabel)
// Value labels content view layout
contentView.addSubview(valueLabelsContainer)
PXLayout.pinRight(view: valueLabelsContainer, withMargin: PXLayout.M_MARGIN).isActive = true
PXLayout.centerVertically(view: valueLabelsContainer).isActive = true
PXLayout.setHeight(owner: valueLabelsContainer, height: 39).isActive = true
PXLayout.put(view: valueLabelsContainer, rightOf: titleLabel, withMargin: PXLayout.XXS_MARGIN).isActive = true
setAccessibilityMessage(data.title.string, data.topValue?.string, data.bottomValue?.string)
}
}
// MARK: Accessibility
private extension PXOneTapInstallmentsSelectorCell {
func setAccessibilityMessage(_ titleLabel: String, _ topLabel: String?, _ bottomLabel: String?) {
let title = titleLabel.replacingOccurrences(of: "x", with: "de".localized).replacingOccurrences(of: "$", with: "") + " " + "pesos".localized
var topText = ""
var bottomText = ""
if let text = topLabel, text.isNotEmpty {
topText = text.replacingOccurrences(of: "$", with: "").replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: "") + "pesos".localized
}
if let text = bottomLabel, text.isNotEmpty {
bottomText = text.replacingOccurrences(of: "$", with: "").replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: "") + "pesos".localized
}
accessibilityLabel = title + ":" + topText + bottomText
}
}
|
mit
|
e5d79d49cc4f80ebdcc52b76c302df2f
| 48.959459 | 169 | 0.716527 | 5.342486 | false | false | false | false |
qRoC/Loobee
|
Tests/LoobeeTests/Library/AssertionConcern/Assertion/IsBlankStringTypesTests.swift
|
1
|
3201
|
// This file is part of the Loobee package.
//
// (c) Andrey Savitsky <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
import XCTest
#if canImport(Loobee)
@testable import Loobee
#else
@testable import LoobeeAssertionConcern
#endif
internal final class IsBlankStringTypesTests: BaseAssertionsTests {
///
internal let newLineString = "\u{000A}\u{000B}\u{000C}\u{000D}\u{0085}\u{2028}\u{2029}"
///
internal let whitespaceString = "\u{0009}\u{0020}\u{2029}\u{3000}"
///
func testIsBlankForEmptyString() {
self.assertMustBeValid(assert(isBlank: ""))
}
///
func testIsBlankForNewlineString() {
self.assertMustBeValid(assert(isBlank: newLineString))
}
///
func testIsBlankForWhitespaceString() {
self.assertMustBeValid(assert(isBlank: whitespaceString))
}
///
func testIsBlankForNotEmptyString() {
self.assertMustBeNotValid(assert(isBlank: "a"))
}
///
func testIsBlankForNotNewlineString() {
let testString = newLineString + "a" + newLineString
self.assertMustBeNotValid(assert(isBlank: testString))
}
///
func testIsBlankForNotWhitespaceString() {
let testString = whitespaceString + "a" + whitespaceString
self.assertMustBeNotValid(assert(isBlank: testString))
}
///
func testIsNotBlankForEmptyString() {
self.assertMustBeNotValid(assert(isNotBlank: ""))
}
///
func testIsNotBlankForNewlineString() {
self.assertMustBeNotValid(assert(isNotBlank: newLineString))
}
///
func testIsNotBlankForWhitespaceString() {
self.assertMustBeNotValid(assert(isNotBlank: whitespaceString))
}
///
func testIsNotBlankForNotEmptyString() {
self.assertMustBeValid(assert(isNotBlank: "a"))
}
///
func testIsNotBlankForNotNewlineString() {
let testString = newLineString + "a" + newLineString
self.assertMustBeValid(assert(isNotBlank: testString))
}
///
func testIsNotBlankForNotWhitespaceString() {
let testString = whitespaceString + "a" + whitespaceString
self.assertMustBeValid(assert(isNotBlank: testString))
}
///
func testIsBlankDefaultMessage() {
let message = kIsBlankDefaultMessage.description
self.assertMustBeNotValid(
assert(isBlank: "a"),
withMessage: message
)
}
///
func testIsBlankCustomMessage() {
let message = "Test"
self.assertMustBeNotValid(
assert(isBlank: "a", orNotification: message),
withMessage: message
)
}
///
func testIsNotBlankDefaultMessage() {
let message = kIsNotBlankDefaultMessage.description
self.assertMustBeNotValid(
assert(isNotBlank: ""),
withMessage: message
)
}
///
func testIsNotBlankCustomMessage() {
let message = "Test"
self.assertMustBeNotValid(
assert(isNotBlank: "", orNotification: message),
withMessage: message
)
}
}
|
mit
|
a87082bb93951b0eda9acfda7f3cd65e
| 23.813953 | 91 | 0.642299 | 4.384932 | false | true | false | false |
zdrzdr/SwiftFundation
|
SwiftFoundation/main.swift
|
1
|
1514
|
//
// main.swift
// SwiftFoundation
//
// Created by 张德荣 on 15/8/13.
// Copyright (c) 2015年 张德荣. All rights reserved.
//
import Foundation
func sayHello(personName: String) ->String{
let greeting = "Hello," + personName + "!"
return greeting
}
print(sayHello("Anna"))
print(sayHello("Brina"))
func sayHelloWorld() ->String {
return "hello, world"
}
print(sayHelloWorld())
func sayGoodbye(personName :String) {
println("Goodbye, \(personName)")
}
sayGoodbye("Dave")
func printAndCount(stringToPrint : String) ->Int {
println(stringToPrint)
return count(stringToPrint)
}
func printWithoutCounting(stringToPrint: String) {
printAndCount(stringToPrint)
}
printAndCount("hello, world")
var a = printAndCount("hello, world")
println(a)
func count(string : String) ->(vowels: Int,consonants: Int, others:Int){
var vowels = 0,consonants = 0,others = 0
for character in string {
switch String(character).lowercaseString {
case "a","e","i","o","u":
++vowels
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
++consonants
default:
++others
}
}
return(vowels,consonants,others)
}
let total = count("some arbitrary string!")
println("\(total.0) \(total.consonants) \(total.2)")
func someFunction(parameterName:Int) {
}
func join(s1: String, s2: String,joiner:String) ->String{
return s1 + joiner + s2
}
|
mit
|
e689f215facfff5c35ae957b5a97029e
| 18.480519 | 72 | 0.614 | 3.225806 | false | false | false | false |
gribozavr/swift
|
test/Driver/SourceRanges/range-lifecycle.swift
|
1
|
11256
|
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/range-lifecycle/* %t && cp %t/fileB{0-baseline,}.swift
// =============================================================================
// Without range dependencies, but logging comparison
// =============================================================================
// RUN: cd %t && %swiftc_driver -enable-batch-mode -j2 -incremental -driver-show-incremental ./main.swift ./fileA.swift ./fileB.swift -module-name main -output-file-map %t/output.json >& output1
// =============================================================================
// Compile with range dependencies enabled
// and logging the comparison to comparo.
// =============================================================================
// RUN: cd %t && %swiftc_driver -disable-fine-grained-dependencies -enable-batch-mode -j2 -incremental -enable-source-range-dependencies -driver-compare-incremental-schemes-path=./comparo -driver-show-incremental -driver-show-job-lifecycle ./main.swift ./fileA.swift ./fileB.swift -module-name main -output-file-map %t/output.json >& %t/output2
// RUN: tail -1 %t/comparo | %FileCheck -match-full-lines -check-prefix=CHECK-COMPARO-1 %s
// CHECK-COMPARO-1: *** Incremental build disabled because different arguments passed to compiler, cannot compare ***
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-TURN-ON %s < %t/output2
// CHECK-TURN-ON-DAG: Incremental compilation has been disabled, because different arguments were passed to the compiler.
// CHECK-TURN-ON-DAG: Batchable: {compile: main.o <= main.swift}
// CHECK-TURN-ON-DAG: Batchable: {compile: fileA.o <= fileA.swift}
// CHECK-TURN-ON-DAG: Batchable: {compile: fileB.o <= fileB.swift}
// RUN: cmp main.swift main.compiledsource
// RUN: cmp fileA.swift fileA.compiledsource
// RUN: cmp fileB.swift fileB.compiledsource
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-MAIN-1 %s <%t/main.swiftranges
// CHECK-MAIN-1: ### Swift source ranges file v0 ###
// CHECK-MAIN-1-NEXT: ---
// CHECK-MAIN-1-NEXT: noninlinableFunctionBodies:
// CHECK-MAIN-1-NEXT: - { start: { line: 5, column: 32 }, end: { line: 5, column: 39 } }
// CHECK-MAIN-1-NEXT: ...
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-FILEA-1 %s <%t/fileA.swiftranges
// CHECK-FILEA-1: ### Swift source ranges file v0 ###
// CHECK-FILEA-1: ---
// CHECK-FILEA-1: noninlinableFunctionBodies:
// CHECK-FILEA-1: - { start: { line: 1, column: 17 }, end: { line: 4, column: 2 } }
// CHECK-FILEA-1: - { start: { line: 5, column: 32 }, end: { line: 7, column: 2 } }
// CHECK-FILEA-1: ...
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-FILEB-1 %s <%t/fileB.swiftranges
// CHECK-FILEB-1: ### Swift source ranges file v0 ###
// CHECK-FILEB-1: ---
// CHECK-FILEB-1: noninlinableFunctionBodies:
// CHECK-FILEB-1: - { start: { line: 2, column: 13 }, end: { line: 2, column: 16 } }
// CHECK-FILEB-1: - { start: { line: 5, column: 13 }, end: { line: 5, column: 15 } }
// CHECK-FILEB-1: ...
// =============================================================================
// Steady-state: Now, do it again with no changes
// =============================================================================
// RUN: cd %t && %swiftc_driver -disable-fine-grained-dependencies -enable-batch-mode -j2 -incremental -enable-source-range-dependencies -driver-compare-incremental-schemes-path=./comparo -driver-show-incremental -driver-show-job-lifecycle ./main.swift ./fileA.swift ./fileB.swift -module-name main -output-file-map %t/output.json >& %t/output3
// RUN: tail -1 %t/comparo | %FileCheck -match-full-lines -check-prefix=CHECK-COMPARO-2 %s
// CHECK-COMPARO-2: *** Range benefit: 0 compilations, 0 stages, without ranges: 0, with ranges: 0, used ranges, total: 3 ***
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-NO-CHANGES %s < %t/output3
// CHECK-NO-CHANGES: (tentatively) Skipping <With ranges> file is up-to-date and output exists: {compile: main.o <= main.swift}
// CHECK-NO-CHANGES: (tentatively) Skipping <With ranges> file is up-to-date and output exists: {compile: fileA.o <= fileA.swift}
// CHECK-NO-CHANGES: (tentatively) Skipping <With ranges> file is up-to-date and output exists: {compile: fileB.o <= fileB.swift}
// CHECK-NO-CHANGES: Hypothetically: (tentatively) Skipping <Without ranges> file is up-to-date and output exists: {compile: main.o <= main.swift}
// CHECK-NO-CHANGES: Hypothetically: (tentatively) Skipping <Without ranges> file is up-to-date and output exists: {compile: fileA.o <= fileA.swift}
// CHECK-NO-CHANGES: Hypothetically: (tentatively) Skipping <Without ranges> file is up-to-date and output exists: {compile: fileB.o <= fileB.swift}
// CHECK-NO-CHANGES: Skipping <With ranges> : {compile: main.o <= main.swift}
// CHECK-NO-CHANGES: Skipping <With ranges> : {compile: fileA.o <= fileA.swift}
// CHECK-NO-CHANGES: Skipping <With ranges> : {compile: fileB.o <= fileB.swift}
// RUN: %FileCheck -check-prefix=CHECK-NO-MAIN %s < %t/output3
// RUN: %FileCheck -check-prefix=CHECK-NO-FILEA %s < %t/output3
// RUN: %FileCheck -check-prefix=CHECK-NO-FILEB %s < %t/output3
// CHECK-NO-MAIN-NOT: Added to TaskQueue: {{.*}} main.cpp
// CHECK-NO-FILEA-NOT: Added to TaskQueue: {{.*}} fileA.cpp
// CHECK-NO-FILEB-NOT: Added to TaskQueue: {{.*}} fileB.cpp
// Recheck supplementaries:
// RUN: cmp main.swift main.compiledsource
// RUN: cmp fileA.swift fileA.compiledsource
// RUN: cmp fileB.swift fileB.compiledsource
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-MAIN-1 %s <%t/main.swiftranges
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-FILEA-1 %s <%t/fileA.swiftranges
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-FILEB-1 %s <%t/fileB.swiftranges
// =============================================================================
// Steady-state: Now, do it again with no changes, but touching files
// =============================================================================
// RUN: touch %t/*.swift
// RUN: cd %t && %swiftc_driver -disable-fine-grained-dependencies -enable-batch-mode -j2 -incremental -enable-source-range-dependencies -driver-compare-incremental-schemes-path=./comparo -driver-show-incremental -driver-show-job-lifecycle ./main.swift ./fileA.swift ./fileB.swift -module-name main -output-file-map %t/output.json >& %t/output4
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-COMPARO-3 %s < %t/comparo
// CHECK-COMPARO-3: *** Range benefit: 3 compilations, 1 stages, without ranges: 3, with ranges: 0, used ranges, total: 3 ***
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-TOUCHING-FILES %s < %t/output4
// CHECK-TOUCHING-FILES: (tentatively) Queuing <With ranges> (initial): {compile: main.o <= main.swift}
// CHECK-TOUCHING-FILES: Skipping <With ranges> Did not change at all: {compile: main.o <= main.swift}
// CHECK-TOUCHING-FILES: (tentatively) Queuing <With ranges> (initial): {compile: fileA.o <= fileA.swift}
// CHECK-TOUCHING-FILES: Skipping <With ranges> Did not change at all: {compile: fileA.o <= fileA.swift}
// CHECK-TOUCHING-FILES: (tentatively) Queuing <With ranges> (initial): {compile: fileB.o <= fileB.swift}
// CHECK-TOUCHING-FILES: Skipping <With ranges> Did not change at all: {compile: fileB.o <= fileB.swift}
// CHECK-TOUCHING-FILES: Hypothetically: (tentatively) Queuing <Without ranges> (initial): {compile: main.o <= main.swift}
// CHECK-TOUCHING-FILES: Hypothetically: (tentatively) Queuing <Without ranges> (initial): {compile: fileA.o <= fileA.swift}
// CHECK-TOUCHING-FILES: Hypothetically: (tentatively) Queuing <Without ranges> (initial): {compile: fileB.o <= fileB.swift}
// CHECK-TOUCHING-FILES: Skipping <With ranges> : {compile: main.o <= main.swift}
// CHECK-TOUCHING-FILES: Skipping <With ranges> : {compile: fileA.o <= fileA.swift}
// CHECK-TOUCHING-FILES: Skipping <With ranges> : {compile: fileB.o <= fileB.swift}
// RUN: %FileCheck -check-prefix=CHECK-NO-MAIN %s < %t/output4
// RUN: %FileCheck -check-prefix=CHECK-NO-FILEA %s < %t/output4
// RUN: %FileCheck -check-prefix=CHECK-NO-FILEB %s < %t/output4
// Recheck supplementaries:
// RUN: cmp main.swift main.compiledsource
// RUN: cmp fileA.swift fileA.compiledsource
// RUN: cmp fileB.swift fileB.compiledsource
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-MAIN-1 %s <%t/main.swiftranges
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-FILEA-1 %s <%t/fileA.swiftranges
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-FILEB-1 %s <%t/fileB.swiftranges
// =============================================================================
// Make an internal change, should not recompile dependents at all
// =============================================================================
// RUN: cp %t/fileB{1-internal-change,}.swift
// RUN: cd %t && %swiftc_driver -disable-fine-grained-dependencies -driver-compare-incremental-schemes -enable-source-range-dependencies -output-file-map %t/output.json -incremental -enable-batch-mode ./main.swift ./fileA.swift ./fileB.swift -module-name main -j2 -driver-show-job-lifecycle -driver-show-incremental >& %t/output5
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-INTERNAL-CHANGE %s < %t/output5
// CHECK-INTERNAL-CHANGE: Skipping <With ranges> : {compile: main.o <= main.swift}
// CHECK-INTERNAL-CHANGE: Skipping <With ranges> : {compile: fileA.o <= fileA.swift}
// CHECK-INTERNAL-CHANGE: *** Range benefit: 0 compilations, 0 stages, without ranges: 1, with ranges: 1, used ranges, total: 3 ***
// RUN: %FileCheck -check-prefix=CHECK-NO-MAIN %s < %t/output5
// RUN: %FileCheck -check-prefix=CHECK-NO-FILEA %s < %t/output5
// =============================================================================
// Make an external change, should recompile dependents right away with ranges
// =============================================================================
// RUN: cp %t/fileB{2-external-change,}.swift
// RUN: cd %t && %swiftc_driver -disable-fine-grained-dependencies -driver-compare-incremental-schemes -enable-source-range-dependencies -output-file-map %t/output.json -incremental -enable-batch-mode ./main.swift ./fileA.swift ./fileB.swift -module-name main -j2 -driver-show-job-lifecycle -driver-show-incremental >& %t/output6
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-EXTERNAL-CHANGE-1 %s < %t/output6
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-EXTERNAL-CHANGE-2 %s < %t/output6
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-EXTERNAL-CHANGE-3 %s < %t/output6
// CHECK-EXTERNAL-CHANGE-1: Queuing <With ranges> changed at [4:18--4:18): {compile: fileB.o <= fileB.swift}
// CHECK-EXTERNAL-CHANGE-NEXT-1: - Will immediately schedule dependents of {compile: fileB.o <= fileB.swift} because changed outside a function body at: [4:18--4:18)
// CHECK-EXTERNAL-CHANGE-2: Queuing <With ranges> because of the initial set: {compile: fileA.o <= fileA.swift}
// CHECK-EXTERNAL-CHANGE-NEXT-2: fileB.swift provides type 'main.Struct1InB'
// CHECK-EXTERNAL-CHANGE-3: Skipping <With ranges> : {compile: main.o <= main.swift}
// CHECK-EXTERNAL-CHANGE-3: *** Range benefit: 0 compilations, 1 stages, without ranges: 2, with ranges: 2, used ranges, total: 3 ***
|
apache-2.0
|
7468071d81f3709e3b9054e66b7fd540
| 65.60355 | 347 | 0.651919 | 3.293154 | false | false | false | false |
ahoppen/swift
|
test/SILGen/tuple_conversion_refutable_pattern.swift
|
25
|
2217
|
// RUN: %target-swift-emit-silgen %s | %FileCheck %s
// CHECK-LABEL: sil hidden [ossa] @$s34tuple_conversion_refutable_pattern2f13argySi1a_SiSg1bt_tF : $@convention(thin) (Int, Optional<Int>) -> () {
func f1(arg: (a: Int, b: Int?)) {
guard case let (x, y?) = arg else { return }
}
// CHECK-LABEL: sil hidden [ossa] @$s34tuple_conversion_refutable_pattern2f13argyyXl1a_yXlSg1bt_tF : $@convention(thin) (@guaranteed AnyObject, @guaranteed Optional<AnyObject>) -> () {
func f1(arg: (a: AnyObject, b: AnyObject?)) {
guard case let (x, y?) = arg else { return }
}
// CHECK-LABEL: sil hidden [ossa] @$s34tuple_conversion_refutable_pattern2f13argyyp1a_ypSg1bt_tF : $@convention(thin) (@in_guaranteed Any, @in_guaranteed Optional<Any>) -> () {
func f1(arg: (a: Any, b: Any?)) {
guard case let (x, y?) = arg else { return }
}
// CHECK-LABEL: sil hidden [ossa] @$s34tuple_conversion_refutable_pattern2f23argySi1a_Si1bt_tF : $@convention(thin) (Int, Int) -> () {
func f2(arg: (a: Int, b: Int)) {
guard case let (x, 4) = arg else { return }
}
// CHECK-LABEL: sil hidden [ossa] @$s34tuple_conversion_refutable_pattern2f23argySi1a_SS1bt_tF : $@convention(thin) (Int, @guaranteed String) -> () {
func f2(arg: (a: Int, b: String)) {
guard case let (x, "") = arg else { return }
}
// CHECK-LABEL: sil hidden [ossa] @$s34tuple_conversion_refutable_pattern2f33argySi1a_Si1bt_tF : $@convention(thin) (Int, Int) -> () {
func f3(arg: (a: Int, b: Int)) {
guard case let (x, is String) = arg else { return }
}
// CHECK-LABEL: sil hidden [ossa] @$s34tuple_conversion_refutable_pattern2f33argySi1a_yXl1bt_tF : $@convention(thin) (Int, @guaranteed AnyObject) -> () {
func f3(arg: (a: Int, b: AnyObject)) {
guard case let (x, is String) = arg else { return }
}
// CHECK-LABEL: sil hidden [ossa] @$s34tuple_conversion_refutable_pattern2f33argySi1a_yp1bt_tF : $@convention(thin) (Int, @in_guaranteed Any) -> () {
func f3(arg: (a: Int, b: Any)) {
guard case let (x, is String) = arg else { return }
}
// CHECK-LABEL: sil hidden [ossa] @$s34tuple_conversion_refutable_pattern2f43argySi1a_Sb1bt_tF : $@convention(thin) (Int, Bool) -> () {
func f4(arg: (a: Int, b: Bool)) {
guard case let (x, false) = arg else { return }
}
|
apache-2.0
|
a3820a1ca251eaf6a723be3cb7ecd060
| 47.195652 | 184 | 0.66396 | 2.764339 | false | false | false | false |
sitdh/Forest
|
Forest/AppDelegate.swift
|
1
|
6333
|
//
// AppDelegate.swift
// Forest
//
// Created by Sitdhibong Laokok on 22/8/57.
// Copyright (c) พ.ศ. 2557 App Tree. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
// Override point for customization after application launch.
var ubiquityContainer = NSFileManager.defaultManager().URLForUbiquityContainerIdentifier(nil);
NSLog("B \(ubiquityContainer)");
return true
}
func applicationWillResignActive(application: UIApplication!) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication!) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication!) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication!) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication!) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.sitdh.mobile.Forest" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Forest", withExtension: "momd")
return NSManagedObjectModel(contentsOfURL: modelURL!)
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Forest.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
|
mit
|
479c52f89cde5fc6b9ccf41cbc510989
| 53.560345 | 290 | 0.710065 | 5.785192 | false | false | false | false |
capstone411/SHAF
|
Capstone/IOS_app/SHAF/SHAF/WeightAmountViewController.swift
|
1
|
2510
|
//
// WeightAmountViewController.swift
// SHAF
//
// Created by Ahmed Abdulkareem on 6/1/16.
// Copyright © 2016 Ahmed Abdulkareem. All rights reserved.
//
import UIKit
class WeightAmountViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var howMuchWeightLabel: UILabel!
@IBOutlet weak var weightNumField: UITextField!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var lbsLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// set up font
//self.howMuchWeightLabel.textAlignment = NSTextAlignment.Center
//self.howMuchWeightLabel.font = UIFont(name: self.howMuchWeightLabel.font.fontName, size: 50)
// disable next button
self.nextButton.enabled = false
// set delegate of text field
self.weightNumField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (weightNumField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
// make sure weight amount < 120 and not a negative number
let weightAmount = Int(text)
if (weightAmount != nil && weightAmount > 0 && weightAmount <= 120) {
// Text field converted to an Int
BLEDiscovery.weightAmount = weightAmount!
self.nextButton.enabled = true
} else {
// Text field is not an Int
self.nextButton.enabled = false
}
// Return true so the text field will be changed
return true
}
@IBAction func nextButtonClicked(sender: AnyObject) {
performSegueWithIdentifier("CalibrationIdentifier", sender: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
bbfe3ade2a54da91dfd4a0fac2ada3cc
| 32.453333 | 132 | 0.659227 | 5.038153 | false | false | false | false |
LedgerHQ/ledger-wallet-ios
|
ledger-wallet-ios/Controllers/Pairing/Add/PairingAddNameStepViewController.swift
|
1
|
2692
|
//
// PairingAddNameStepViewController.swift
// ledger-wallet-ios
//
// Created by Nicolas Bigot on 16/01/2015.
// Copyright (c) 2015 Ledger. All rights reserved.
//
import UIKit
final class PairingAddNameStepViewController: PairingAddBaseStepViewController {
@IBOutlet private weak var nameTextField: TextField!
@IBOutlet private weak var walletImageView: UIImageView!
@IBOutlet private weak var indicationLabel: Label!
override var stepIndication: String {
return localizedString("your_device_is_now_paired")
}
override var stepNumber: Int {
return 5
}
override var finalizable: Bool {
return true
}
override var cancellable: Bool {
return false
}
// MARK: - Actions
override func complete() {
super.complete()
// verify entered name
if checkThatNameIsUnique(nameTextField.text) {
notifyResult(nameTextField.text)
}
}
// MARK: - Interface
private func checkThatNameIsUnique(name: String) -> Bool {
var message:String? = nil
// create message
if name.isEmpty {
message = localizedString("you_need_to_provide_a_dongle_name")
}
else if (!PairingProtocolContext.canCreatePairingKeychainItemNamed(name)) {
message = localizedString("a_dongle_with_this_name_already_exists")
}
else {
message = nil
}
// show message if necessary
if message != nil {
let alertController = AlertController(title: message, message: nil)
alertController.addAction(AlertController.Action(title: localizedString("OK"), style: .Default, handler: nil))
alertController.presentFromViewController(self, animated: true)
return false
}
return true
}
override func configureView() {
super.configureView()
nameTextField?.delegate = self
// remove invisible views
if (DeviceManager.sharedInstance.screenHeightClass == DeviceManager.HeightClass.Medium) {
indicationLabel?.removeFromSuperview()
}
if (DeviceManager.sharedInstance.screenHeightClass == DeviceManager.HeightClass.Small) {
indicationLabel?.removeFromSuperview()
walletImageView?.removeFromSuperview()
}
nameTextField?.becomeFirstResponder()
}
}
extension PairingAddNameStepViewController: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
complete()
return false
}
}
|
mit
|
196740f6e5f0fa37ad52b625d093647e
| 27.946237 | 122 | 0.627415 | 5.237354 | false | false | false | false |
rnystrom/GitHawk
|
Classes/Issues/Comments/Reactions/ReactionViewModel.swift
|
1
|
1226
|
//
// ReactionViewModel.swift
// Freetime
//
// Created by Ryan Nystrom on 6/1/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
struct ReactionViewModel {
let content: ReactionContent
let count: Int
let viewerDidReact: Bool
let users: [String]
}
func createReactionDetailText(model: ReactionViewModel) -> String {
let users = model.users
switch users.count {
case 0:
return ""
case 1:
let format = NSLocalizedString("%@", comment: "")
return String(format: format, users[0])
case 2:
let format = NSLocalizedString("%@ and %@", comment: "")
return String(format: format, arguments: [users[0], users[1]])
default:
assert(users.count >= 3)
if model.count > 3 {
let difference = model.count - users.count
let format = NSLocalizedString("%@, %@, %@ and %d other(s)", comment: "")
return String(format: format, arguments: [users[0], users[1], users[2], difference])
} else {
let format = NSLocalizedString("%@, %@ and %@", comment: "")
return String(format: format, arguments: [users[0], users[1], users[2]])
}
}
}
|
mit
|
d13ac5962d381782deddd0ae4cb816ec
| 28.166667 | 96 | 0.593469 | 4.124579 | false | false | false | false |
iOS-mamu/SS
|
P/Library/Eureka/Source/Rows/ButtonRow.swift
|
1
|
3583
|
//
// ButtonRow.swift
// Eureka
//
// Created by Martin Barreto on 2/23/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
// MARK: ButtonCell
open class ButtonCellOf<T: Equatable>: Cell<T>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
accessoryType = .none
editingAccessoryType = accessoryType
textLabel?.textAlignment = .center
textLabel?.textColor = tintColor
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
textLabel?.textColor = UIColor(red: red, green: green, blue: blue, alpha: row.isDisabled ? 0.3 : 1.0)
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
}
public typealias ButtonCell = ButtonCellOf<String>
//MARK: ButtonRow
open class _ButtonRowOf<T: Equatable> : Row<T, ButtonCellOf<T>> {
open var presentationMode: PresentationMode<UIViewController>?
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
cellStyle = .default
}
open override func customDidSelect() {
super.customDidSelect()
if !isDisabled {
if let presentationMode = presentationMode {
if let controller = presentationMode.createController(){
presentationMode.presentViewController(controller, row: self, presentingViewController: self.cell.formViewController()!)
}
else{
presentationMode.presentViewController(nil, row: self, presentingViewController: self.cell.formViewController()!)
}
}
}
}
open override func customUpdateCell() {
super.customUpdateCell()
let leftAligmnment = presentationMode != nil
cell.textLabel?.textAlignment = leftAligmnment ? .left : .center
cell.accessoryType = !leftAligmnment || isDisabled ? .none : .disclosureIndicator
cell.editingAccessoryType = cell.accessoryType
if (!leftAligmnment){
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
cell.tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
cell.textLabel?.textColor = UIColor(red: red, green: green, blue: blue, alpha:isDisabled ? 0.3 : 1.0)
}
else{
cell.textLabel?.textColor = nil
}
}
open override func prepareForSegue(_ segue: UIStoryboardSegue) {
super.prepareForSegue(segue)
let rowVC = segue.destination as? RowControllerType
rowVC?.completionCallback = self.presentationMode?.completionHandler
}
}
/// A generic row with a button. The action of this button can be anything but normally will push a new view controller
public final class ButtonRowOf<T: Equatable> : _ButtonRowOf<T>, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
/// A row with a button and String value. The action of this button can be anything but normally will push a new view controller
public typealias ButtonRow = ButtonRowOf<String>
|
mit
|
0abf728b886366f1e164986fec72b886
| 34.82 | 140 | 0.644891 | 4.782377 | false | false | false | false |
EsriJapan/arcgis-samples-ios
|
swift/ArcGISSample/TopMenuController.swift
|
1
|
2495
|
//
// TopMenuController.swift
// ArcGISSample
//
// Created by esrij on 2015/07/27.
// Copyright (c) 2015年 esrij. All rights reserved.
//
import UIKit
class TopMenuController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let items = [
"GpsViewController",
"SpatialQueryViewController",
"SwipeViewController",
"AppLoginViewController",
"ElevationViewController",
"SceneLayerViewController",
"SceneGraphicsViewController",
"FeatureLayerViewController",
"ExtrusionRendererViewController"
]
let itemNames = [
"ナビゲーション",
"空間検索",
"スワイプ",
"アプリ認証",
"地形表示(3D)",
"景観表示(3D)",
"グラフィック表示(3D)",
"レイヤーの表示(3D)",
"レイヤーの立ち上げ(3D)"
]
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = "メニュー"
tableView = UITableView(frame: view.bounds)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.cellLayoutMarginsFollowReadableWidth = false
tableView.dataSource = self
tableView.delegate = self
view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel!.text = "\(itemNames[indexPath.row])"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let strTarget:String = "ArcGISSample."
let strVC:String = items[indexPath.row] as String
let className = strTarget + strVC
if let theClass = NSClassFromString(className) as? UIViewController.Type {
let controller = theClass.init(nibName: nil, bundle: nil)
navigationController!.pushViewController(controller, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
9f548c6d010df66883bbb3894fdcb90b
| 25.52809 | 100 | 0.621347 | 4.693837 | false | false | false | false |
Genhain/OAuth-Moya-Promise
|
Example/Tests/Tests.swift
|
1
|
1278
|
//// https://github.com/Quick/Quick
//
//import Quick
//import Nimble
//@testable import OAuth_Moya_Promise
//
//class TableOfContentsSpec: QuickSpec {
// override func spec() {
// describe("these will fail") {
//
// it("can do maths") {
// expect(1) == 2
// }
//
// it("can read") {
// expect("number") == "string"
// }
//
// it("will eventually fail") {
// expect("time").toEventually( equal("done") )
// }
//
// context("these will pass") {
//
// it("can do maths") {
// expect(23) == 23
// }
//
// it("can read") {
// expect("🐮") == "🐮"
// }
//
// it("will eventually pass") {
// var time = "passing"
//
// DispatchQueue.main.async {
// time = "done"
// }
//
// waitUntil { done in
// Thread.sleep(forTimeInterval: 0.5)
// expect(time) == "done"
//
// done()
// }
// }
// }
// }
// }
//}
|
mit
|
4f32dfe152862e447f0b01038117f11f
| 24.44 | 62 | 0.335692 | 4.184211 | false | false | false | false |
nurseymybush/fitbitSwiftTest
|
OAuthSwiftOSXDemo/ViewController.swift
|
4
|
27887
|
//
// ViewController.swift
// OAuthSwiftOSXDemo
//
// Created by phimage on 07/05/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Cocoa
import OAuthSwift
class ViewController: NSViewController , NSTableViewDelegate, NSTableViewDataSource {
var services = ["Twitter", "Flickr", "Github", "Instagram", "Foursquare", "Fitbit", "Withings", "Linkedin", "Linkedin2", "Dropbox", "Dribbble", "Salesforce", "BitBucket", "GoogleDrive", "Smugmug", "Intuit", "Zaim", "Tumblr", "Slack", "Uber"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func createWebViewController() -> WebViewController {
let controller = WebViewController()
controller.view = NSView(frame: NSRect(x:0, y:0, width: 450, height: 500)) // needed if no nib or not loaded from storyboard
controller.viewDidLoad()
return controller
}
func get_url_handler() -> OAuthSwiftURLHandlerType {
// Create a WebViewController with default behaviour from OAuthWebViewController
let url_handler = createWebViewController()
self.addChildViewController(url_handler) // allow WebViewController to use this ViewController as parent to be presented
return url_handler
// a better way is
// - to make this ViewController implement OAuthSwiftURLHandlerType and assigned in oauthswift object
/* return self */
// - have an instance of WebViewController here (I) or a segue name to launch (S)
// - in handle(url)
// (I) : affect url to WebViewController, and self.presentViewControllerAsModalWindow(self.webViewController)
// (S) : affect url to a temp variable (ex: urlForWebView), then perform segue
/* performSegueWithIdentifier("oauthwebview", sender:nil) */
// then override prepareForSegue() to affect url to destination controller WebViewController
}
//(I)
//let webViewController: WebViewController = createWebViewController()
//(S)
//var urlForWebView:?NSURL = nil
func doOAuthTwitter(){
let oauthswift = OAuth1Swift(
consumerKey: Twitter["consumerKey"]!,
consumerSecret: Twitter["consumerSecret"]!,
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
authorizeUrl: "https://api.twitter.com/oauth/authorize",
accessTokenUrl: "https://api.twitter.com/oauth/access_token"
)
//oauthswift.authorize_url_handler = createWebViewController()
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/twitter")!, success: {
credential, response in
self.showAlertView("Twitter", message: "auth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
let parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.twitter.com/1.1/statuses/mentions_timeline.json", parameters: parameters,
success: {
data, response in
do {
let jsonDict: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers)
print("SUCCESS: \(jsonDict)")
} catch let error as NSError {
print(error)
}
}, failure: {(error:NSError!) -> Void in
})
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
}
)
}
func doOAuthFlickr(){
let oauthswift = OAuth1Swift(
consumerKey: Flickr["consumerKey"]!,
consumerSecret: Flickr["consumerSecret"]!,
requestTokenUrl: "https://www.flickr.com/services/oauth/request_token",
authorizeUrl: "https://www.flickr.com/services/oauth/authorize",
accessTokenUrl: "https://www.flickr.com/services/oauth/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/flickr")!, success: {
credential, response in
self.showAlertView("Flickr", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
let url :String = "https://api.flickr.com/services/rest/"
let parameters :Dictionary = [
"method" : "flickr.photos.search",
"api_key" : Flickr["consumerKey"]!,
"user_id" : "128483205@N08",
"format" : "json",
"nojsoncallback" : "1",
"extras" : "url_q,url_z"
]
oauthswift.client.get(url, parameters: parameters,
success: {
data, response in
do {
let jsonDict: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers)
print("SUCCESS: \(jsonDict)")
} catch let error as NSError {
print(error)
}
}, failure: {(error:NSError!) -> Void in
print(error)
})
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthGithub(){
let oauthswift = OAuth2Swift(
consumerKey: Github["consumerKey"]!,
consumerSecret: Github["consumerSecret"]!,
authorizeUrl: "https://github.com/login/oauth/authorize",
accessTokenUrl: "https://github.com/login/oauth/access_token",
responseType: "code"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/github")!, scope: "user,repo", state: state, success: {
credential, response, parameters in
self.showAlertView("Github", message: "oauth_token:\(credential.oauth_token)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthSalesforce(){
let oauthswift = OAuth2Swift(
consumerKey: Salesforce["consumerKey"]!,
consumerSecret: Salesforce["consumerSecret"]!,
authorizeUrl: "https://login.salesforce.com/services/oauth2/authorize",
accessTokenUrl: "https://login.salesforce.com/services/oauth2/token",
responseType: "code"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/salesforce")!, scope: "full", state: state, success: {
credential, response, parameters in
self.showAlertView("Salesforce", message: "oauth_token:\(credential.oauth_token)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthInstagram(){
let oauthswift = OAuth2Swift(
consumerKey: Instagram["consumerKey"]!,
consumerSecret: Instagram["consumerSecret"]!,
authorizeUrl: "https://api.instagram.com/oauth/authorize",
responseType: "token"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorize_url_handler = get_url_handler()
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/instagram")!, scope: "likes+comments", state:state, success: {
credential, response, parameters in
self.showAlertView("Instagram", message: "oauth_token:\(credential.oauth_token)")
let url :String = "https://api.instagram.com/v1/users/1574083/?access_token=\(credential.oauth_token)"
let parameters :Dictionary = Dictionary<String, AnyObject>()
oauthswift.client.get(url, parameters: parameters,
success: {
data, response in
do {
let jsonDict: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers)
print("SUCCESS: \(jsonDict)")
} catch let error as NSError {
print(error)
}
}, failure: {(error:NSError!) -> Void in
print(error)
})
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthFoursquare(){
let oauthswift = OAuth2Swift(
consumerKey: Foursquare["consumerKey"]!,
consumerSecret: Foursquare["consumerSecret"]!,
authorizeUrl: "https://foursquare.com/oauth2/authorize",
responseType: "token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/foursquare")!, scope: "", state: "", success: {
credential, response, parameters in
self.showAlertView("Foursquare", message: "oauth_token:\(credential.oauth_token)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthFitbit(){
let oauthswift = OAuth1Swift(
consumerKey: Fitbit["consumerKey"]!,
consumerSecret: Fitbit["consumerSecret"]!,
requestTokenUrl: "https://api.fitbit.com/oauth/request_token",
authorizeUrl: "https://www.fitbit.com/oauth/authorize?display=touch",
accessTokenUrl: "https://api.fitbit.com/oauth/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/fitbit")!, success: {
credential, response in
self.showAlertView("Fitbit", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthWithings(){
let oauthswift = OAuth1Swift(
consumerKey: Withings["consumerKey"]!,
consumerSecret: Withings["consumerSecret"]!,
requestTokenUrl: "https://oauth.withings.com/account/request_token",
authorizeUrl: "https://oauth.withings.com/account/authorize",
accessTokenUrl: "https://oauth.withings.com/account/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/withings")!, success: {
credential, response in
self.showAlertView("Withings", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthLinkedin(){
let oauthswift = OAuth1Swift(
consumerKey: Linkedin["consumerKey"]!,
consumerSecret: Linkedin["consumerSecret"]!,
requestTokenUrl: "https://api.linkedin.com/uas/oauth/requestToken",
authorizeUrl: "https://api.linkedin.com/uas/oauth/authenticate",
accessTokenUrl: "https://api.linkedin.com/uas/oauth/accessToken"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/linkedin")!, success: {
credential, response in
self.showAlertView("Linkedin", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
let parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.linkedin.com/v1/people/~", parameters: parameters,
success: {
data, response in
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
print(dataString)
}, failure: {(error:NSError!) -> Void in
print(error)
})
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthLinkedin2(){
let oauthswift = OAuth2Swift(
consumerKey: Linkedin2["consumerKey"]!,
consumerSecret: Linkedin2["consumerSecret"]!,
authorizeUrl: "https://www.linkedin.com/uas/oauth2/authorization",
accessTokenUrl: "https://www.linkedin.com/uas/oauth2/accessToken",
responseType: "code"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorizeWithCallbackURL( NSURL(string: "http://oauthswift.herokuapp.com/callback/linkedin2")!, scope: "r_fullprofile", state: state, success: {
credential, response, parameters in
self.showAlertView("Linkedin2", message: "oauth_token:\(credential.oauth_token)")
let parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.linkedin.com/v1/people/~?format=json", parameters: parameters,
success: {
data, response in
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
print(dataString)
}, failure: {(error:NSError!) -> Void in
print(error)
})
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthSmugmug(){
let oauthswift = OAuth1Swift(
consumerKey: Smugmug["consumerKey"]!,
consumerSecret: Smugmug["consumerSecret"]!,
requestTokenUrl: "http://api.smugmug.com/services/oauth/getRequestToken.mg",
authorizeUrl: "http://api.smugmug.com/services/oauth/authorize.mg",
accessTokenUrl: "http://api.smugmug.com/services/oauth/getAccessToken.mg"
)
oauthswift.allowMissingOauthVerifier = true
// NOTE: Smugmug's callback URL is configured on their site and the one passed in is ignored.
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/smugmug")!, success: {
credential, response in
self.showAlertView("Smugmug", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthDropbox(){
let oauthswift = OAuth2Swift(
consumerKey: Dropbox["consumerKey"]!,
consumerSecret: Dropbox["consumerSecret"]!,
authorizeUrl: "https://www.dropbox.com/1/oauth2/authorize",
accessTokenUrl: "https://api.dropbox.com/1/oauth2/token",
responseType: "token"
)
oauthswift.authorize_url_handler = get_url_handler()
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/dropbox")!, scope: "", state: "", success: {
credential, response, parameters in
self.showAlertView("Dropbox", message: "oauth_token:\(credential.oauth_token)")
// Get Dropbox Account Info
let parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.dropbox.com/1/account/info?access_token=\(credential.oauth_token)", parameters: parameters,
success: {
data, response in
do {
let jsonDict: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers)
print("SUCCESS: \(jsonDict)")
} catch let error as NSError {
print(error)
}
}, failure: {(error:NSError!) -> Void in
print(error)
})
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthDribbble(){
let oauthswift = OAuth2Swift(
consumerKey: Dribbble["consumerKey"]!,
consumerSecret: Dribbble["consumerSecret"]!,
authorizeUrl: "https://dribbble.com/oauth/authorize",
accessTokenUrl: "https://dribbble.com/oauth/token",
responseType: "code"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/dribbble")!, scope: "", state: "", success: {
credential, response, parameters in
self.showAlertView("Dribbble", message: "oauth_token:\(credential.oauth_token)")
// Get User
let parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.dribbble.com/v1/user?access_token=\(credential.oauth_token)", parameters: parameters,
success: {
data, response in
do {
let jsonDict: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers)
print("SUCCESS: \(jsonDict)")
} catch let error as NSError {
print(error)
}
}, failure: {(error:NSError!) -> Void in
print(error)
})
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthBitBucket(){
let oauthswift = OAuth1Swift(
consumerKey: BitBucket["consumerKey"]!,
consumerSecret: BitBucket["consumerSecret"]!,
requestTokenUrl: "https://bitbucket.org/api/1.0/oauth/request_token",
authorizeUrl: "https://bitbucket.org/api/1.0/oauth/authenticate",
accessTokenUrl: "https://bitbucket.org/api/1.0/oauth/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/bitbucket")!, success: {
credential, response in
self.showAlertView("BitBucket", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
let parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://bitbucket.org/api/1.0/user", parameters: parameters,
success: {
data, response in
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
print(dataString)
}, failure: {(error:NSError!) -> Void in
print(error)
})
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthGoogle(){
let oauthswift = OAuth2Swift(
consumerKey: GoogleDrive["consumerKey"]!,
consumerSecret: GoogleDrive["consumerSecret"]!,
authorizeUrl: "https://accounts.google.com/o/oauth2/auth",
accessTokenUrl: "https://accounts.google.com/o/oauth2/token",
responseType: "code"
)
// For googgle the redirect_uri should match your this syntax: your.bundle.id:/oauth2Callback
// in plist define a url schem with: your.bundle.id:
oauthswift.authorizeWithCallbackURL( NSURL(string: "https://oauthswift.herokuapp.com/callback/google")!, scope: "https://www.googleapis.com/auth/drive", state: "", success: {
credential, response, parameters in
self.showAlertView("Github", message: "oauth_token:\(credential.oauth_token)")
let parameters = Dictionary<String, AnyObject>()
// Multi-part upload
oauthswift.client.postImage("https://www.googleapis.com/upload/drive/v2/files", parameters: parameters, image: self.snapshot(),
success: {
data, response in
do {
let jsonDict: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers)
print("SUCCESS: \(jsonDict)")
} catch let error as NSError {
print(error)
}
}, failure: {(error:NSError!) -> Void in
print(error)
})
}, failure: {(error:NSError!) -> Void in
print("ERROR: \(error.localizedDescription)")
})
}
func doOAuthIntuit(){
let oauthswift = OAuth1Swift(
consumerKey: Intuit["consumerKey"]!,
consumerSecret: Intuit["consumerSecret"]!,
requestTokenUrl: "https://oauth.intuit.com/oauth/v1/get_request_token",
authorizeUrl: "https://appcenter.intuit.com/Connect/Begin",
accessTokenUrl: "https://oauth.intuit.com/oauth/v1/get_access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/intuit")!, success: {
credential, response in
self.showAlertView("Intuit", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthZaim(){
let oauthswift = OAuth1Swift(
consumerKey: Zaim["consumerKey"]!,
consumerSecret: Zaim["consumerSecret"]!,
requestTokenUrl: "https://api.zaim.net/v2/auth/request",
authorizeUrl: "https://auth.zaim.net/users/auth",
accessTokenUrl: "https://api.zaim.net/v2/auth/access"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/zaim")!, success: {
credential, response in
self.showAlertView("Zaim", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthTumblr(){
let oauthswift = OAuth1Swift(
consumerKey: Tumblr["consumerKey"]!,
consumerSecret: Tumblr["consumerSecret"]!,
requestTokenUrl: "http://www.tumblr.com/oauth/request_token",
authorizeUrl: "http://www.tumblr.com/oauth/authorize",
accessTokenUrl: "http://www.tumblr.com/oauth/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/tumblr")!, success: {
credential, response in
self.showAlertView("Tumblr", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthSlack(){
let oauthswift = OAuth2Swift(
consumerKey: Slack["consumerKey"]!,
consumerSecret: Slack["consumerSecret"]!,
authorizeUrl: "https://slack.com/oauth/authorize",
accessTokenUrl: "https://slack.com/api/oauth.access",
responseType: "code"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/slack")!, scope: "", state: state, success: {
credential, response, parameters in
self.showAlertView("Slack", message: "oauth_token:\(credential.oauth_token)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func doOAuthUber(){
let oauthswift = OAuth2Swift(
consumerKey: Uber["consumerKey"]!,
consumerSecret: Uber["consumerSecret"]!,
authorizeUrl: "https://login.uber.com/oauth/authorize",
accessTokenUrl: "https://login.uber.com/oauth/token",
responseType: "code",
contentType: "multipart/form-data"
)
let state: String = generateStateWithLength(20) as String
let redirectURL = "https://oauthswift.herokuapp.com/callback/uber".stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
oauthswift.authorizeWithCallbackURL( NSURL(string: redirectURL!)!, scope: "profile", state: state, success: {
credential, response, parameters in
self.showAlertView("Uber", message: "oauth_token:\(credential.oauth_token)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func snapshot() -> NSData {
let rep: NSBitmapImageRep = self.view.bitmapImageRepForCachingDisplayInRect(self.view.bounds)!
self.view.cacheDisplayInRect(self.view.bounds, toBitmapImageRep:rep)
return rep.TIFFRepresentation!
}
func showAlertView(title: String, message: String) {
let alert = NSAlert()
alert.messageText = title
alert.informativeText = message
alert.addButtonWithTitle("Close")
alert.runModal()
}
// MARK: NSTableViewDataSource
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return self.services.count
}
// MARK: NSTableViewDelegate
func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
return self.services[row]
}
func tableViewSelectionDidChange(notification: NSNotification) {
if let tableView = notification.object as? NSTableView {
let row = tableView.selectedRow
if row != -1 {
let service: String = self.services[row]
switch service {
case "Twitter":
doOAuthTwitter()
case "Flickr":
doOAuthFlickr()
case "Github":
doOAuthGithub()
case "Instagram":
doOAuthInstagram()
case "Foursquare":
doOAuthFoursquare()
case "Fitbit":
doOAuthFitbit()
case "Withings":
doOAuthWithings()
case "Linkedin":
doOAuthLinkedin()
case "Linkedin2":
doOAuthLinkedin2()
case "Dropbox":
doOAuthDropbox()
case "Dribbble":
doOAuthDribbble()
case "Salesforce":
doOAuthSalesforce()
case "BitBucket":
doOAuthBitBucket()
case "GoogleDrive":
doOAuthGoogle()
case "Smugmug":
doOAuthSmugmug()
case "Intuit":
doOAuthIntuit()
case "Zaim":
doOAuthZaim()
case "Tumblr":
doOAuthTumblr()
case "Slack":
doOAuthSlack()
case "Uber":
doOAuthUber()
default:
print("default (check ViewController tableView)")
}
tableView.deselectRow(row)
}
}
}
}
|
mit
|
c0adce055ae5a1a01f276c9c88bdfea6
| 45.790268 | 245 | 0.583534 | 4.989622 | false | false | false | false |
Michael-Lfx/SwiftArmyKnife
|
Controls/SAKCopyableLabel.swift
|
1
|
3208
|
// 改写自 https://github.com/hoteltonight/HTCopyableLabel
// 已简单测试
import UIKit
@IBDesignable public class SAKCopyableLabel: UILabel {
// MARK: - 属性
@IBInspectable var copyingEnabled: Bool = true {
didSet {
userInteractionEnabled = copyingEnabled
longPressGestureRecognizer.enabled = copyingEnabled
}
}
var copyMenuArrowDirection = UIMenuControllerArrowDirection.Default
private(set) lazy var longPressGestureRecognizer: UILongPressGestureRecognizer! = {
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressGestureRecognized:")
self.addGestureRecognizer(longPressGestureRecognizer)
return longPressGestureRecognizer
}()
var stringToCopyForCopyableLabel: ((SAKCopyableLabel) -> String)?
var copyMenuTargetRectInCopyableLabelCoordinates: ((SAKCopyableLabel) -> CGRect)?
var copyPressed: ((SAKCopyableLabel) -> Void)?
// MARK: - 覆盖方法
override init(frame: CGRect) {
super.init(frame: frame)
userInteractionEnabled = true
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
userInteractionEnabled = true
}
// MARK: - 回调
func longPressGestureRecognized(gestureRecognizer: UILongPressGestureRecognizer) {
if gestureRecognizer != self.longPressGestureRecognizer {
return
}
if gestureRecognizer.state != .Began {
return
}
becomeFirstResponder()
let copyMenu = UIMenuController.sharedMenuController()
if copyMenuTargetRectInCopyableLabelCoordinates != nil {
let rect = copyMenuTargetRectInCopyableLabelCoordinates!(self)
copyMenu.setTargetRect(rect, inView: self)
} else {
copyMenu.setTargetRect(bounds, inView: self)
}
copyMenu.arrowDirection = copyMenuArrowDirection
copyMenu.setMenuVisible(true, animated: true)
}
// MARK: - UIResponder
public override func canBecomeFirstResponder() -> Bool {
return copyingEnabled
}
public override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
var retValue = false
if action == "copy:" && copyingEnabled {
retValue = true
} else {
// Pass the canPerformAction:withSender: message to the superclass
// and possibly up the responder chain.
retValue = super.canPerformAction(action, withSender: sender)
}
return retValue
}
public override func copy(sender: AnyObject?) {
if !copyingEnabled {
return
}
var pasteboard = UIPasteboard.generalPasteboard()
var stringToCopy: String?
if stringToCopyForCopyableLabel != nil {
stringToCopy = stringToCopyForCopyableLabel!(self)
} else {
stringToCopy = text
}
pasteboard.string = stringToCopy
if stringToCopyForCopyableLabel != nil {
copyPressed!(self)
}
}
}
|
mit
|
570eb2756a861cde7192564ecbcb6478
| 31.080808 | 122 | 0.639484 | 5.651246 | false | false | false | false |
SereivoanYong/Charts
|
Source/Charts/Charts/PieChartView.swift
|
1
|
10394
|
//
// PieChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import UIKit
/// View that represents a pie chart. Draws cake like slices.
open class PieChartView: BasePieRadarChartView {
/// maximum angle for this pie
fileprivate var _maxAngle: CGFloat = 360.0
internal override func initialize() {
super.initialize()
renderer = PieRenderer(chart: self, animator: animator, viewPortHandler: viewPortHandler)
_xAxis = nil
self.highlighter = PieHighlighter(chart: self)
}
open override func draw(_ rect: CGRect) {
super.draw(rect)
if data == nil {
return
}
let context = UIGraphicsGetCurrentContext()!
renderer!.drawData(context: context)
if valuesToHighlight() {
renderer!.drawHighlighted(context: context, indices: _indicesToHighlight)
}
renderer!.drawExtras(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
internal override func calculateOffsets() {
super.calculateOffsets()
// prevent nullpointer when no data set
if data == nil {
return
}
let radius = diameter / 2.0
let c = centerOffsets
let shift = (data as? PieData)?.dataSet?.selectionShift ?? 0.0
// create the circle box that will contain the pie-chart (the bounds of the pie-chart)
circleBox = CGRect(x: (c.x - radius) + shift, y: (c.y - radius) + shift, width: diameter - shift * 2.0, height: diameter - shift * 2.0)
}
internal override func calcMinMax() {
calcAngles()
}
open override func getMarkerPosition(highlight: Highlight) -> CGPoint {
let center = centerCircleBox
var r = radius
var off = r / 10.0 * 3.6
if isDrawHoleEnabled {
off = (r - (r * holeRadiusPercent)) / 2.0
}
r -= off // offset to keep things inside the chart
let rotationAngle = self.rotationAngle
let entryIndex = Int(highlight.x)
// offset needed to center the drawn text in the slice
let offset = drawAngles[entryIndex] / 2.0
// calculate the text position
let x = r * cos(((rotationAngle + absoluteAngles[entryIndex] - offset) * animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.x
let y = r * sin(((rotationAngle + absoluteAngles[entryIndex] - offset) * animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.y
return CGPoint(x: x, y: y)
}
/// calculates the needed angles for the chart slices
fileprivate func calcAngles() {
drawAngles.removeAll(keepingCapacity: false)
absoluteAngles.removeAll(keepingCapacity: false)
guard let data = data else { return }
let entryCount = data.entryCount
drawAngles.reserveCapacity(entryCount)
absoluteAngles.reserveCapacity(entryCount)
let yValueSum = (data as! PieData).yValueSum
var cnt = 0
for set in data.dataSets {
for entry in set.entries {
drawAngles.append(calcAngle(value: abs(entry.y), yValueSum: yValueSum))
if cnt == 0 {
absoluteAngles.append(drawAngles[cnt])
} else {
absoluteAngles.append(absoluteAngles[cnt - 1] + drawAngles[cnt])
}
cnt += 1
}
}
}
/// Checks if the given index is set to be highlighted.
open func needsHighlight(index: Int) -> Bool {
// no highlight
if !valuesToHighlight() {
return false
}
for i in 0 ..< _indicesToHighlight.count {
// check if the xvalue for the given dataset needs highlight
if Int(_indicesToHighlight[i].x) == index {
return true
}
}
return false
}
/// calculates the needed angle for a given value
fileprivate func calcAngle(_ value: CGFloat) -> CGFloat {
return calcAngle(value: value, yValueSum: (data as! PieData).yValueSum)
}
/// calculates the needed angle for a given value
fileprivate func calcAngle(value: CGFloat, yValueSum: CGFloat) -> CGFloat {
return value / yValueSum * _maxAngle
}
/// This will throw an exception, PieChart has no XAxis object.
open override var xAxis: XAxis {
fatalError("PieChart has no XAxis")
}
open override func indexForAngle(_ angle: CGFloat) -> Int {
// take the current angle of the chart into consideration
let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle)
for i in 0 ..< absoluteAngles.count {
if absoluteAngles[i] > a {
return i
}
}
return -1 // return -1 if no index found
}
/// - returns: The index of the DataSet this x-index belongs to.
open func dataSetIndexForIndex(_ xValue: CGFloat) -> Int {
var dataSets = data?.dataSets ?? []
for i in 0 ..< dataSets.count {
if (dataSets[i].entryForXValue(xValue, closestToY: .nan) != nil) {
return i
}
}
return -1
}
/// - returns: An integer array of all the different angles the chart slices
/// have the angles in the returned array determine how much space (of 360°)
/// each slice takes
open fileprivate(set) var drawAngles: [CGFloat] = []
/// - returns: The absolute angles of the different chart slices (where the
/// slices end)
open fileprivate(set) var absoluteAngles: [CGFloat] = []
/// The color for the hole that is drawn in the center of the PieChart (if enabled).
///
/// - note: Use holeTransparent with holeColor = nil to make the hole transparent.*
open var holeColor: UIColor? = .white {
didSet {
setNeedsDisplay()
}
}
/// if true, the hole will see-through to the inner tips of the slices
///
/// **default**: `false`
open var isDrawSlicesUnderHoleEnabled: Bool = false {
didSet {
setNeedsDisplay()
}
}
/// `true` if the hole in the center of the pie-chart is set to be visible, `false` ifnot
///
/// **default**: `false`
open var isDrawHoleEnabled: Bool = true {
didSet {
setNeedsDisplay()
}
}
/// the text that is displayed in the center of the pie-chart
open var centerText: String? {
get {
return centerAttributedText?.string
}
set {
var attrString: NSMutableAttributedString?
if newValue == nil {
attrString = nil
} else {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .center
attrString = NSMutableAttributedString(string: newValue!)
attrString?.setAttributes([NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFont(ofSize: 12.0), NSParagraphStyleAttributeName: paragraphStyle],
range: NSMakeRange(0, attrString!.length))
}
centerAttributedText = attrString
}
}
/// the text that is displayed in the center of the pie-chart
open var centerAttributedText: NSAttributedString? {
didSet {
setNeedsDisplay()
}
}
/// Sets the offset the center text should have from it's original position in dp. Default x = 0, y = 0
open var centerTextOffset: CGPoint = .zero {
didSet {
setNeedsDisplay()
}
}
/// `true` if drawing the center text is enabled
open var isDrawCenterTextEnabled: Bool = true {
didSet {
setNeedsDisplay()
}
}
internal override var requiredLegendOffset: CGFloat {
return legend.font.pointSize * 2.0
}
internal override var requiredBaseOffset: CGFloat {
return 0.0
}
open override var radius: CGFloat {
return circleBox.width / 2.0
}
/// - returns: The circlebox, the boundingbox of the pie-chart slices
open fileprivate(set) var circleBox: CGRect = .zero
/// - returns: The center of the circlebox
open var centerCircleBox: CGPoint {
return CGPoint(x: circleBox.midX, y: circleBox.midY)
}
/// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.5 (50%) (half the pie)
open var holeRadiusPercent: CGFloat = 0.5 {
didSet {
setNeedsDisplay()
}
}
/// The color that the transparent-circle should have.
///
/// **default**: `nil`
open var transparentCircleColor: UIColor? = UIColor(white: 1.0, alpha: 105.0/255.0) {
didSet {
setNeedsDisplay()
}
}
/// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.55 (55%) -> means 5% larger than the center-hole by default
open var transparentCircleRadiusPercent: CGFloat = 0.55 {
didSet {
setNeedsDisplay()
}
}
/// The color the entry labels are drawn with.
open var entryLabelColor: UIColor? = .white {
didSet {
setNeedsDisplay()
}
}
/// The font the entry labels are drawn with.
open var entryLabelFont: UIFont? = .systemFont(ofSize: 13.0) {
didSet {
setNeedsDisplay()
}
}
/// Set this to true to draw the enrty labels into the pie slices
open var isDrawEntryLabelsEnabled: Bool = true {
didSet {
setNeedsDisplay()
}
}
/// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent.
open var isUsePercentValuesEnabled: Bool = true {
didSet {
setNeedsDisplay()
}
}
/// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole
open var centerTextRadiusPercent: CGFloat = 1.0 {
didSet {
setNeedsDisplay()
}
}
/// The max angle that is used for calculating the pie-circle.
/// 360 means it's a full pie-chart, 180 results in a half-pie-chart.
/// **default**: 360.0
open var maxAngle: CGFloat {
get {
return _maxAngle
}
set {
_maxAngle = newValue
if _maxAngle > 360.0 {
_maxAngle = 360.0
}
if _maxAngle < 90.0 {
_maxAngle = 90.0
}
}
}
}
|
apache-2.0
|
191ff28e0750b15213f2726d0669d242
| 27.165312 | 187 | 0.64072 | 4.503033 | false | false | false | false |
tensorflow/swift-models
|
Gym/PPO/Agent.swift
|
1
|
6616
|
// Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import PythonKit
import TensorFlow
/// Agent that uses the Proximal Policy Optimization (PPO).
///
/// Proximal Policy Optimization is an algorithm that trains an actor (policy) and a critic (value
/// function) using a clipped objective function. The clipped objective function simplifies the
/// update equation from its predecessor Trust Region Policy Optimization (TRPO). For more
/// information, check Proximal Policy Optimization Algorithms (Schulman et al., 2017).
class PPOAgent {
// Cache for trajectory segments for minibatch updates.
var memory: PPOMemory
/// The learning rate for both the actor and the critic.
let learningRate: Float
/// The discount factor that measures how much to weight to give to future
/// rewards when calculating the action value.
let discount: Float
/// Number of epochs to run minibatch updates once enough trajectory segments are collected.
let epochs: Int
/// Parameter to clip the probability ratio.
let clipEpsilon: Float
/// Coefficient for the entropy bonus added to the objective.
let entropyCoefficient: Float
var actorCritic: ActorCritic
var oldActorCritic: ActorCritic
var actorOptimizer: Adam<ActorNetwork>
var criticOptimizer: Adam<CriticNetwork>
init(
observationSize: Int,
hiddenSize: Int,
actionCount: Int,
learningRate: Float,
discount: Float,
epochs: Int,
clipEpsilon: Float,
entropyCoefficient: Float
) {
self.learningRate = learningRate
self.discount = discount
self.epochs = epochs
self.clipEpsilon = clipEpsilon
self.entropyCoefficient = entropyCoefficient
self.memory = PPOMemory()
self.actorCritic = ActorCritic(
observationSize: observationSize,
hiddenSize: hiddenSize,
actionCount: actionCount
)
self.oldActorCritic = self.actorCritic
self.actorOptimizer = Adam(for: actorCritic.actorNetwork, learningRate: learningRate)
self.criticOptimizer = Adam(for: actorCritic.criticNetwork, learningRate: learningRate)
}
func step(env: PythonObject, state: PythonObject) -> (PythonObject, Bool, Float) {
let tfState: Tensor<Float> = Tensor<Float>(numpy: np.array([state], dtype: np.float32))!
let dist: Categorical<Int32> = oldActorCritic(tfState)
let action: Int32 = dist.sample().scalarized()
let (newState, reward, isDone, _) = env.step(action).tuple4
memory.append(
state: Array(state)!,
action: action,
reward: Float(reward)!,
logProb: dist.logProbabilities[Int(action)].scalarized(),
isDone: Bool(isDone)!
)
return (newState, Bool(isDone)!, Float(reward)!)
}
func update() {
// Discount rewards for advantage estimation
var rewards: [Float] = []
var discountedReward: Float = 0
for i in (0..<memory.rewards.count).reversed() {
if memory.isDones[i] {
discountedReward = 0
}
discountedReward = memory.rewards[i] + (discount * discountedReward)
rewards.insert(discountedReward, at: 0)
}
var tfRewards = Tensor<Float>(rewards)
tfRewards = (tfRewards - tfRewards.mean()) / (tfRewards.standardDeviation() + 1e-5)
// Retrieve stored states, actions, and log probabilities
let oldStates: Tensor<Float> = Tensor<Float>(numpy: np.array(memory.states, dtype: np.float32))!
let oldActions: Tensor<Int32> = Tensor<Int32>(numpy: np.array(memory.actions, dtype: np.int32))!
let oldLogProbs: Tensor<Float> = Tensor<Float>(numpy: np.array(memory.logProbs, dtype: np.float32))!
// Optimize actor and critic
var actorLosses: [Float] = []
var criticLosses: [Float] = []
for _ in 0..<epochs {
// Optimize policy network (actor)
let (actorLoss, actorGradients) = valueWithGradient(at: self.actorCritic.actorNetwork) { actorNetwork -> Tensor<Float> in
let npIndices = np.stack([np.arange(oldActions.shape[0], dtype: np.int32), oldActions.makeNumpyArray()], axis: 1)
let tfIndices = Tensor<Int32>(numpy: npIndices)!
let actionProbs = actorNetwork(oldStates).dimensionGathering(atIndices: tfIndices)
let dist = Categorical<Int32>(probabilities: actionProbs)
let stateValues = self.actorCritic.criticNetwork(oldStates).flattened()
let ratios: Tensor<Float> = exp(dist.logProbabilities - oldLogProbs)
let advantages: Tensor<Float> = tfRewards - stateValues
let surrogateObjective = Tensor(stacking: [
ratios * advantages,
ratios.clipped(min:1 - self.clipEpsilon, max: 1 + self.clipEpsilon) * advantages
]).min(alongAxes: 0).flattened()
let entropyBonus: Tensor<Float> = Tensor<Float>(self.entropyCoefficient * dist.entropy())
let loss: Tensor<Float> = -1 * (surrogateObjective + entropyBonus)
return loss.mean()
}
self.actorOptimizer.update(&self.actorCritic.actorNetwork, along: actorGradients)
actorLosses.append(actorLoss.scalarized())
// Optimize value network (critic)
let (criticLoss, criticGradients) = valueWithGradient(at: self.actorCritic.criticNetwork) { criticNetwork -> Tensor<Float> in
let stateValues = criticNetwork(oldStates).flattened()
let loss: Tensor<Float> = 0.5 * pow(stateValues - tfRewards, 2)
return loss.mean()
}
self.criticOptimizer.update(&self.actorCritic.criticNetwork, along: criticGradients)
criticLosses.append(criticLoss.scalarized())
}
self.oldActorCritic = self.actorCritic
memory.removeAll()
}
}
|
apache-2.0
|
7cdb0c8d11fc33c24e1ad373142979b0
| 43.702703 | 137 | 0.652963 | 4.187342 | false | false | false | false |
tkremenek/swift
|
test/SILGen/lifetime.swift
|
5
|
31217
|
// RUN: %target-swift-emit-silgen -module-name lifetime -Xllvm -sil-full-demangle -parse-as-library -primary-file %s | %FileCheck %s
struct Buh<T> {
var x: Int {
get {}
set {}
}
}
class Ref {
init() { }
}
struct Val {
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime13local_valtypeyyF
func local_valtype() {
var b: Val
// CHECK: [[B:%[0-9]+]] = alloc_box ${ var Val }
// CHECK: [[MARKED_B:%.*]] = mark_uninitialized [var] [[B]]
// CHECK: destroy_value [[MARKED_B]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime20local_valtype_branch{{[_0-9a-zA-Z]*}}F
func local_valtype_branch(_ a: Bool) {
var a = a
// CHECK: [[A:%[0-9]+]] = alloc_box ${ var Bool }
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: br [[EPILOG:bb[0-9]+]]
var x:Int
// CHECK: [[X:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[MARKED_X:%.*]] = mark_uninitialized [var] [[X]]
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_X]]
// CHECK: br [[EPILOG]]
while a {
// CHECK: cond_br
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK-NOT: destroy_value [[X]]
// CHECK: br
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_X]]
// CHECK: br [[EPILOG]]
var y:Int
// CHECK: [[Y:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[MARKED_Y:%.*]] = mark_uninitialized [var] [[Y]]
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Y]]
// CHECK-NOT: destroy_value [[MARKED_X]]
// CHECK-NOT: destroy_value [[A]]
// CHECK: br
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Y]]
// CHECK: destroy_value [[MARKED_X]]
// CHECK: br [[EPILOG]]
if true {
var z:Int
// CHECK: [[Z:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[MARKED_Z:%.*]] = mark_uninitialized [var] [[Z]]
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Z]]
// CHECK: destroy_value [[MARKED_Y]]
// CHECK-NOT: destroy_value [[MARKED_X]]
// CHECK-NOT: destroy_value [[A]]
// CHECK: br
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Z]]
// CHECK: destroy_value [[MARKED_Y]]
// CHECK: destroy_value [[MARKED_X]]
// CHECK: br [[EPILOG]]
// CHECK: destroy_value [[MARKED_Z]]
}
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Y]]
// CHECK-NOT: destroy_value [[MARKED_X]]
// CHECK-NOT: destroy_value [[A]]
// CHECK: br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Y]]
// CHECK: br
}
// CHECK: destroy_value [[MARKED_X]]
// CHECK: [[EPILOG]]:
// CHECK: return
}
func reftype_func() -> Ref {}
func reftype_func_with_arg(_ x: Ref) -> Ref {}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime14reftype_returnAA3RefCyF
func reftype_return() -> Ref {
return reftype_func()
// CHECK: [[RF:%[0-9]+]] = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref
// CHECK-NOT: destroy_value
// CHECK: [[RET:%[0-9]+]] = apply [[RF]]()
// CHECK-NOT: destroy_value
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime11reftype_argyyAA3RefCF : $@convention(thin) (@guaranteed Ref) -> () {
// CHECK: bb0([[A:%[0-9]+]] : @guaranteed $Ref):
// CHECK: [[AADDR:%[0-9]+]] = alloc_box ${ var Ref }
// CHECK: [[PA:%[0-9]+]] = project_box [[AADDR]]
// CHECK: [[A_COPY:%.*]] = copy_value [[A]]
// CHECK: store [[A_COPY]] to [init] [[PA]]
// CHECK: destroy_value [[AADDR]]
// CHECK-NOT: destroy_value [[A]]
// CHECK: return
// CHECK: } // end sil function '$s8lifetime11reftype_argyyAA3RefCF'
func reftype_arg(_ a: Ref) {
var a = a
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime26reftype_call_ignore_returnyyF
func reftype_call_ignore_return() {
reftype_func()
// CHECK: = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref
// CHECK-NEXT: [[R:%[0-9]+]] = apply
// CHECK: destroy_value [[R]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime27reftype_call_store_to_localyyF
func reftype_call_store_to_local() {
var a = reftype_func()
// CHECK: [[A:%[0-9]+]] = alloc_box ${ var Ref }
// CHECK-NEXT: [[PB:%.*]] = project_box [[A]]
// CHECK: = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref
// CHECK-NEXT: [[R:%[0-9]+]] = apply
// CHECK-NOT: copy_value [[R]]
// CHECK: store [[R]] to [init] [[PB]]
// CHECK-NOT: destroy_value [[R]]
// CHECK: destroy_value [[A]]
// CHECK-NOT: destroy_value [[R]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime16reftype_call_argyyF
func reftype_call_arg() {
reftype_func_with_arg(reftype_func())
// CHECK: [[RF:%[0-9]+]] = function_ref @$s8lifetime12reftype_func{{[_0-9a-zA-Z]*}}F
// CHECK: [[R1:%[0-9]+]] = apply [[RF]]
// CHECK: [[RFWA:%[0-9]+]] = function_ref @$s8lifetime21reftype_func_with_arg{{[_0-9a-zA-Z]*}}F
// CHECK: [[R2:%[0-9]+]] = apply [[RFWA]]([[R1]])
// CHECK: destroy_value [[R2]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime21reftype_call_with_arg{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[A1:%[0-9]+]] : @guaranteed $Ref):
// CHECK: [[AADDR:%[0-9]+]] = alloc_box ${ var Ref }
// CHECK: [[PB:%.*]] = project_box [[AADDR]]
// CHECK: [[A1_COPY:%.*]] = copy_value [[A1]]
// CHECK: store [[A1_COPY]] to [init] [[PB]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]]
// CHECK: [[A2:%[0-9]+]] = load [copy] [[READ]]
// CHECK: [[RFWA:%[0-9]+]] = function_ref @$s8lifetime21reftype_func_with_arg{{[_0-9a-zA-Z]*}}F
// CHECK: [[RESULT:%.*]] = apply [[RFWA]]([[A2]])
// CHECK: destroy_value [[RESULT]]
// CHECK: destroy_value [[AADDR]]
// CHECK-NOT: destroy_value [[A1]]
// CHECK: return
func reftype_call_with_arg(_ a: Ref) {
var a = a
reftype_func_with_arg(a)
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime16reftype_reassign{{[_0-9a-zA-Z]*}}F
func reftype_reassign(_ a: inout Ref, b: Ref) {
var b = b
// CHECK: bb0([[AADDR:%[0-9]+]] : $*Ref, [[B1:%[0-9]+]] : @guaranteed $Ref):
// CHECK: [[BADDR:%[0-9]+]] = alloc_box ${ var Ref }
// CHECK: [[PBB:%.*]] = project_box [[BADDR]]
a = b
// CHECK: destroy_value
// CHECK: return
}
func tuple_with_ref_elements() -> (Val, (Ref, Val), Ref) {}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime28tuple_with_ref_ignore_returnyyF
func tuple_with_ref_ignore_return() {
tuple_with_ref_elements()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime23tuple_with_ref_elementsAA3ValV_AA3RefC_ADtAFtyF
// CHECK: [[TUPLE:%[0-9]+]] = apply [[FUNC]]
// CHECK: ([[T0:%.*]], [[T1_0:%.*]], [[T1_1:%.*]], [[T2:%.*]]) = destructure_tuple [[TUPLE]]
// CHECK: destroy_value [[T2]]
// CHECK: destroy_value [[T1_0]]
// CHECK: return
}
struct Aleph {
var a:Ref
var b:Val
// -- loadable value constructor:
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime5AlephV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Ref, Val, @thin Aleph.Type) -> @owned Aleph
// CHECK: bb0([[A:%.*]] : @owned $Ref, [[B:%.*]] : $Val, {{%.*}} : $@thin Aleph.Type):
// CHECK-NEXT: [[RET:%.*]] = struct $Aleph ([[A]] : {{.*}}, [[B]] : {{.*}})
// CHECK-NEXT: return [[RET]]
}
struct Beth {
var a:Val
var b:Aleph
var c:Ref
func gimel() {}
}
protocol Unloadable {}
struct Daleth {
var a:Aleph
var b:Beth
var c:Unloadable
// -- address-only value constructor:
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime6DalethV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Aleph, @owned Beth, @in Unloadable, @thin Daleth.Type) -> @out Daleth {
// CHECK: bb0([[THIS:%.*]] : $*Daleth, [[A:%.*]] : @owned $Aleph, [[B:%.*]] : @owned $Beth, [[C:%.*]] : $*Unloadable, {{%.*}} : $@thin Daleth.Type):
// CHECK-NEXT: [[A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.a
// CHECK-NEXT: store [[A]] to [init] [[A_ADDR]]
// CHECK-NEXT: [[B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.b
// CHECK-NEXT: store [[B]] to [init] [[B_ADDR]]
// CHECK-NEXT: [[C_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.c
// CHECK-NEXT: copy_addr [take] [[C]] to [initialization] [[C_ADDR]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
class He {
// -- default allocator:
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick He.Type) -> @owned He {
// CHECK: bb0({{%.*}} : $@thick He.Type):
// CHECK-NEXT: [[THIS:%.*]] = alloc_ref $He
// CHECK-NEXT: // function_ref lifetime.He.init
// CHECK-NEXT: [[INIT:%.*]] = function_ref @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned He) -> @owned He
// CHECK-NEXT: [[THIS1:%.*]] = apply [[INIT]]([[THIS]])
// CHECK-NEXT: return [[THIS1]]
// CHECK-NEXT: }
// -- default initializer:
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned He) -> @owned He {
// CHECK: bb0([[SELF:%.*]] : @owned $He):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[UNINITIALIZED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]]
// CHECK-NEXT: [[UNINITIALIZED_SELF_COPY:%.*]] = copy_value [[UNINITIALIZED_SELF]]
// CHECK-NEXT: destroy_value [[UNINITIALIZED_SELF]]
// CHECK-NEXT: return [[UNINITIALIZED_SELF_COPY]]
// CHECK: } // end sil function '$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc'
init() { }
}
struct Waw {
var a:(Ref, Val)
var b:Val
// -- loadable value initializer with tuple destructuring:
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3WawV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Ref, Val, Val, @thin Waw.Type) -> @owned Waw
// CHECK: bb0([[A0:%.*]] : @owned $Ref, [[A1:%.*]] : $Val, [[B:%.*]] : $Val, {{%.*}} : $@thin Waw.Type):
// CHECK-NEXT: [[A:%.*]] = tuple ([[A0]] : {{.*}}, [[A1]] : {{.*}})
// CHECK-NEXT: [[RET:%.*]] = struct $Waw ([[A]] : {{.*}}, [[B]] : {{.*}})
// CHECK-NEXT: return [[RET]]
}
struct Zayin {
var a:(Unloadable, Val)
var b:Unloadable
// -- address-only value initializer with tuple destructuring:
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime5ZayinV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@in Unloadable, Val, @in Unloadable, @thin Zayin.Type) -> @out Zayin
// CHECK: bb0([[THIS:%.*]] : $*Zayin, [[A0:%.*]] : $*Unloadable, [[A1:%.*]] : $Val, [[B:%.*]] : $*Unloadable, {{%.*}} : $@thin Zayin.Type):
// CHECK-NEXT: [[THIS_A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.a
// CHECK-NEXT: [[THIS_A0_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 0
// CHECK-NEXT: [[THIS_A1_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 1
// CHECK-NEXT: copy_addr [take] [[A0]] to [initialization] [[THIS_A0_ADDR]]
// CHECK-NEXT: store [[A1]] to [trivial] [[THIS_A1_ADDR]]
// CHECK-NEXT: [[THIS_B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.b
// CHECK-NEXT: copy_addr [take] [[B]] to [initialization] [[THIS_B_ADDR]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
func fragile_struct_with_ref_elements() -> Beth {}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime29struct_with_ref_ignore_returnyyF
func struct_with_ref_ignore_return() {
fragile_struct_with_ref_elements()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime32fragile_struct_with_ref_elementsAA4BethVyF
// CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]]
// CHECK: destroy_value [[STRUCT]] : $Beth
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime28struct_with_ref_materializedyyF
func struct_with_ref_materialized() {
fragile_struct_with_ref_elements().gimel()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime32fragile_struct_with_ref_elementsAA4BethVyF
// CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]]
// CHECK: [[METHOD:%[0-9]+]] = function_ref @$s8lifetime4BethV5gimel{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[METHOD]]([[STRUCT]])
}
class RefWithProp {
var int_prop: Int { get {} set {} }
var aleph_prop: Aleph { get {} set {} }
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime015logical_lvalue_A0yyAA11RefWithPropC_SiAA3ValVtF : $@convention(thin) (@guaranteed RefWithProp, Int, Val) -> () {
func logical_lvalue_lifetime(_ r: RefWithProp, _ i: Int, _ v: Val) {
var r = r
var i = i
var v = v
// CHECK: [[RADDR:%[0-9]+]] = alloc_box ${ var RefWithProp }
// CHECK: [[PR:%[0-9]+]] = project_box [[RADDR]]
// CHECK: [[IADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PI:%[0-9]+]] = project_box [[IADDR]]
// CHECK: store %1 to [trivial] [[PI]]
// CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var Val }
// CHECK: [[PV:%[0-9]+]] = project_box [[VADDR]]
// -- Reference types need to be copy_valued as property method args.
r.int_prop = i
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PR]]
// CHECK: [[R1:%[0-9]+]] = load [copy] [[READ]]
// CHECK: [[SETTER_METHOD:%[0-9]+]] = class_method {{.*}} : $RefWithProp, #RefWithProp.int_prop!setter : (RefWithProp) -> (Int) -> (), $@convention(method) (Int, @guaranteed RefWithProp) -> ()
// CHECK: apply [[SETTER_METHOD]]({{.*}}, [[R1]])
// CHECK: destroy_value [[R1]]
r.aleph_prop.b = v
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PR]]
// CHECK: [[R2:%[0-9]+]] = load [copy] [[READ]]
// CHECK: [[R2BORROW:%[0-9]+]] = begin_borrow [[R2]]
// CHECK: [[MODIFY:%[0-9]+]] = class_method [[R2BORROW]] : $RefWithProp, #RefWithProp.aleph_prop!modify :
// CHECK: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]([[R2BORROW]])
// CHECK: end_apply [[TOKEN]]
}
func bar() -> Int {}
class Foo<T> {
var x : Int
var y = (Int(), Ref())
var z : T
var w = Ref()
class func makeT() -> T {}
// Class initializer
init() {
// -- allocating entry point
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC :
// CHECK: bb0([[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type):
// CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T>
// CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc
// CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[THIS]])
// CHECK: return [[INIT_THIS]]
// -- initializing entry point
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc :
// CHECK: bb0([[THISIN:%[0-9]+]] : @owned $Foo<T>):
// CHECK: [[THIS:%[0-9]+]] = mark_uninitialized
// -- initialization for y
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS_Y:%.*]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.y
// CHECK: [[Y_INIT:%[0-9]+]] = function_ref @$s8lifetime3FooC1ySi_AA3RefCtvpfi : $@convention(thin) <τ_0_0> () -> (Int, @owned Ref)
// CHECK: [[THIS_Y_0:%.*]] = tuple_element_addr [[THIS_Y]] : $*(Int, Ref), 0
// CHECK: [[THIS_Y_1:%.*]] = tuple_element_addr [[THIS_Y]] : $*(Int, Ref), 1
// CHECK: [[Y_VALUE:%[0-9]+]] = apply [[Y_INIT]]<T>()
// CHECK: ([[Y_EXTRACTED_0:%.*]], [[Y_EXTRACTED_1:%.*]]) = destructure_tuple
// CHECK: store [[Y_EXTRACTED_0]] to [trivial] [[THIS_Y_0]]
// CHECK: store [[Y_EXTRACTED_1]] to [init] [[THIS_Y_1]]
// CHECK: end_borrow [[BORROWED_THIS]]
// -- Initialization for w
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS_Z:%.*]] = ref_element_addr [[BORROWED_THIS]]
// CHECK: [[Z_FUNC:%.*]] = function_ref @$s{{.*}}8lifetime3FooC1wAA3RefCvpfi : $@convention(thin) <τ_0_0> () -> @owned Ref
// CHECK: [[Z_RESULT:%.*]] = apply [[Z_FUNC]]<T>()
// CHECK: store [[Z_RESULT]] to [init] [[THIS_Z]]
// CHECK: end_borrow [[BORROWED_THIS]]
// -- Initialization for x
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.x
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_X]] : $*Int
// CHECK: assign {{.*}} to [[WRITE]]
// CHECK: end_borrow [[BORROWED_THIS]]
x = bar()
z = Foo<T>.makeT()
// CHECK: [[FOOMETA:%[0-9]+]] = metatype $@thick Foo<T>.Type
// CHECK: [[MAKET:%[0-9]+]] = class_method [[FOOMETA]] : {{.*}}, #Foo.makeT :
// CHECK: ref_element_addr
// -- cleanup this lvalue and return this
// CHECK: [[THIS_RESULT:%.*]] = copy_value [[THIS]]
// -- TODO: This copy should be unnecessary.
// CHECK: destroy_value [[THIS]]
// CHECK: return [[THIS_RESULT]]
}
init(chi:Int) {
var chi = chi
z = Foo<T>.makeT()
// -- allocating entry point
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC :
// CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type):
// CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T>
// CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc
// CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[CHI]], [[THIS]])
// CHECK: return [[INIT_THIS]]
// -- initializing entry point
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC3chiACyxGSi_tcfc : $@convention(method) <T> (Int, @owned Foo<T>) -> @owned Foo<T> {
// CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[THISIN:%[0-9]+]] : @owned $Foo<T>):
// CHECK: [[THIS:%[0-9]+]] = mark_uninitialized [rootself] [[THISIN]]
// -- First we initialize #Foo.y.
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS_Y:%.*]] = ref_element_addr [[BORROWED_THIS]] : $Foo<T>, #Foo.y
// CHECK: [[THIS_Y_1:%.*]] = tuple_element_addr [[THIS_Y]] : $*(Int, Ref), 0
// CHECK: [[THIS_Y_2:%.*]] = tuple_element_addr [[THIS_Y]] : $*(Int, Ref), 1
// CHECK: store {{.*}} to [trivial] [[THIS_Y_1]] : $*Int
// CHECK: store {{.*}} to [init] [[THIS_Y_2]] : $*Ref
// CHECK: end_borrow [[BORROWED_THIS]]
// -- Then we create a box that we will use to perform a copy_addr into #Foo.x a bit later.
// CHECK: [[CHIADDR:%[0-9]+]] = alloc_box ${ var Int }, var, name "chi"
// CHECK: [[PCHI:%[0-9]+]] = project_box [[CHIADDR]]
// CHECK: store [[CHI]] to [trivial] [[PCHI]]
// -- Then we initialize #Foo.z
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS_Z:%.*]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.z
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_Z]] : $*T
// CHECK: copy_addr [take] {{.*}} to [[WRITE]]
// CHECK: end_borrow [[BORROWED_THIS]]
// -- Then initialize #Foo.x using the earlier stored value of CHI to THIS_Z.
x = chi
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PCHI]]
// CHECK: [[X:%.*]] = load [trivial] [[READ]]
// CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.x
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_X]] : $*Int
// CHECK: assign [[X]] to [[WRITE]]
// CHECK: end_borrow [[BORROWED_THIS]]
// -- cleanup chi
// CHECK: destroy_value [[CHIADDR]]
// -- Then begin the epilogue sequence
// CHECK: [[THIS_RETURN:%.*]] = copy_value [[THIS]]
// CHECK: destroy_value [[THIS]]
// CHECK: return [[THIS_RETURN]]
// CHECK: } // end sil function '$s8lifetime3FooC3chiACyxGSi_tcfc'
}
// -- allocating entry point
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC :
// CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc
// -- initializing entry point
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc :
init<U:Intifiable>(chi:U) {
z = Foo<T>.makeT()
x = chi.intify()
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooCfd : $@convention(method) <T> (@guaranteed Foo<T>) -> @owned Builtin.NativeObject
deinit {
// CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $Foo<T>):
bar()
// CHECK: function_ref @$s8lifetime3barSiyF
// CHECK: apply
// -- don't need to destroy_value x because it's trivial
// CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #Foo.x
// -- destroy_value y
// CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.y
// CHECK: [[YADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[YADDR]]
// CHECK: destroy_addr [[YADDR_ACCESS]]
// CHECK: end_access [[YADDR_ACCESS]]
// -- destroy_value z
// CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.z
// CHECK: [[ZADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[ZADDR]]
// CHECK: destroy_addr [[ZADDR_ACCESS]]
// CHECK: end_access [[ZADDR_ACCESS]]
// -- destroy_value w
// CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.w
// CHECK: [[WADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[WADDR]]
// CHECK: destroy_addr [[WADDR_ACCESS]]
// CHECK: end_access [[WADDR_ACCESS]]
// -- return back this
// CHECK: [[PTR:%.*]] = unchecked_ref_cast [[THIS]] : $Foo<T> to $Builtin.NativeObject
// CHECK: [[PTR_OWNED:%.*]] = unchecked_ownership_conversion [[PTR]] : $Builtin.NativeObject, @guaranteed to @owned
// CHECK: return [[PTR_OWNED]]
// CHECK: } // end sil function '$s8lifetime3FooCfd'
}
// Deallocating destructor for Foo.
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooCfD : $@convention(method) <T> (@owned Foo<T>) -> ()
// CHECK: bb0([[SELF:%[0-9]+]] : @owned $Foo<T>):
// CHECK: [[DESTROYING_REF:%[0-9]+]] = function_ref @$s8lifetime3FooCfd : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject
// CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK-NEXT: [[RESULT_SELF:%[0-9]+]] = apply [[DESTROYING_REF]]<T>([[BORROWED_SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject
// CHECK-NEXT: end_borrow [[BORROWED_SELF]]
// CHECK-NEXT: end_lifetime [[SELF]]
// CHECK-NEXT: [[SELF:%[0-9]+]] = unchecked_ref_cast [[RESULT_SELF]] : $Builtin.NativeObject to $Foo<T>
// CHECK-NEXT: dealloc_ref [[SELF]] : $Foo<T>
// CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: } // end sil function '$s8lifetime3FooCfD'
}
class FooSubclass<T> : Foo<T> {
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime11FooSubclassCfd : $@convention(method) <T> (@guaranteed FooSubclass<T>) -> @owned Builtin.NativeObject
// CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $FooSubclass<T>):
// -- base dtor
// CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $Foo<T>
// CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime3FooCfd : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject
// CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]<T>([[BASE]])
// CHECK: [[BORROWED_PTR:%.*]] = begin_borrow [[PTR]]
// CHECK: end_borrow [[BORROWED_PTR]]
// CHECK: return [[PTR]]
deinit {
bar()
}
}
class ImplicitDtor {
var x:Int
var y:(Int, Ref)
var w:Ref
init() { }
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime12ImplicitDtorCfd
// CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtor):
// -- don't need to destroy_value x because it's trivial
// CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.x
// -- destroy_value y
// CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.y
// CHECK: [[YADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[YADDR]]
// CHECK: destroy_addr [[YADDR_ACCESS]]
// CHECK: end_access [[YADDR_ACCESS]]
// -- destroy_value w
// CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.w
// CHECK: [[WADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[WADDR]]
// CHECK: destroy_addr [[WADDR_ACCESS]]
// CHECK: end_access [[WADDR_ACCESS]]
// CHECK: return
}
class ImplicitDtorDerived<T> : ImplicitDtor {
var z:T
init(z : T) {
super.init()
self.z = z
}
// CHECK: sil hidden [ossa] @$s8lifetime19ImplicitDtorDerivedCfd : $@convention(method) <T> (@guaranteed ImplicitDtorDerived<T>) -> @owned Builtin.NativeObject {
// CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtorDerived<T>):
// -- base dtor
// CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtor
// CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime12ImplicitDtorCfd
// CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]([[BASE]])
// -- destroy_value z
// CHECK: [[BORROWED_PTR:%.*]] = begin_borrow [[PTR]]
// CHECK: [[CAST_BORROWED_PTR:%.*]] = unchecked_ref_cast [[BORROWED_PTR]] : $Builtin.NativeObject to $ImplicitDtorDerived<T>
// CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[CAST_BORROWED_PTR]] : {{.*}}, #ImplicitDtorDerived.z
// CHECK: [[ZADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[ZADDR]]
// CHECK: destroy_addr [[ZADDR_ACCESS]]
// CHECK: end_access [[ZADDR_ACCESS]]
// CHECK: end_borrow [[BORROWED_PTR]]
// -- epilog
// CHECK-NOT: unchecked_ref_cast
// CHECK-NOT: unchecked_ownership_conversion
// CHECK: return [[PTR]]
}
class ImplicitDtorDerivedFromGeneric<T> : ImplicitDtorDerived<Int> {
init() { super.init(z: 5) }
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime30ImplicitDtorDerivedFromGenericC{{[_0-9a-zA-Z]*}}fc
// CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtorDerivedFromGeneric<T>):
// -- base dtor
// CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtorDerived<Int>
// CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime19ImplicitDtorDerivedCfd
// CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]<Int>([[BASE]])
// CHECK: return [[PTR]]
}
protocol Intifiable {
func intify() -> Int
}
struct Bar {
var x:Int
// Loadable struct initializer
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3BarV{{[_0-9a-zA-Z]*}}fC
init() {
// CHECK: bb0([[METATYPE:%[0-9]+]] : $@thin Bar.Type):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Bar }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
x = bar()
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]]
// CHECK: [[SELF_X:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bar, #Bar.x
// CHECK: assign {{.*}} to [[SELF_X]]
// -- load and return this
// CHECK: [[SELF_VAL:%[0-9]+]] = load [trivial] [[PB_BOX]]
// CHECK: destroy_value [[MARKED_SELF_BOX]]
// CHECK: return [[SELF_VAL]]
}
init<T:Intifiable>(xx:T) {
x = xx.intify()
}
}
struct Bas<T> {
var x:Int
var y:T
// Address-only struct initializer
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3BasV{{[_0-9a-zA-Z]*}}fC
init(yy:T) {
// CHECK: bb0([[THISADDRPTR:%[0-9]+]] : $*Bas<T>, [[YYADDR:%[0-9]+]] : $*T, [[META:%[0-9]+]] : $@thin Bas<T>.Type):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var Bas<τ_0_0> } <T>
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
x = bar()
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]]
// CHECK: [[SELF_X:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bas<T>, #Bas.x
// CHECK: assign {{.*}} to [[SELF_X]]
y = yy
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]]
// CHECK: [[SELF_Y:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bas<T>, #Bas.y
// CHECK: copy_addr {{.*}} to [[SELF_Y]]
// CHECK: destroy_value
// -- 'self' was emplaced into indirect return slot
// CHECK: return
}
init<U:Intifiable>(xx:U, yy:T) {
x = xx.intify()
y = yy
}
}
class B { init(y:Int) {} }
class D : B {
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime1DC1x1yACSi_Sitcfc
// CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : @owned $D):
init(x: Int, y: Int) {
var x = x
var y = y
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var D }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%[0-9]+]] = project_box [[MARKED_SELF_BOX]]
// CHECK: store [[SELF]] to [init] [[PB_BOX]]
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PX:%[0-9]+]] = project_box [[XADDR]]
// CHECK: store [[X]] to [trivial] [[PX]]
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PY:%[0-9]+]] = project_box [[YADDR]]
// CHECK: store [[Y]] to [trivial] [[PY]]
super.init(y: y)
// CHECK: [[THIS1:%[0-9]+]] = load [take] [[PB_BOX]]
// CHECK: [[THIS1_SUP:%[0-9]+]] = upcast [[THIS1]] : ${{.*}} to $B
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PY]]
// CHECK: [[Y:%[0-9]+]] = load [trivial] [[READ]]
// CHECK: [[SUPER_CTOR:%[0-9]+]] = function_ref @$s8lifetime1BC1yACSi_tcfc : $@convention(method) (Int, @owned B) -> @owned B
// CHECK: [[THIS2_SUP:%[0-9]+]] = apply [[SUPER_CTOR]]([[Y]], [[THIS1_SUP]])
// CHECK: [[THIS2:%[0-9]+]] = unchecked_ref_cast [[THIS2_SUP]] : $B to $D
// CHECK: [[THIS1:%[0-9]+]] = load [copy] [[PB_BOX]]
// CHECK: destroy_value [[MARKED_SELF_BOX]]
}
func foo() {}
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime8downcast{{[_0-9a-zA-Z]*}}F
func downcast(_ b: B) {
var b = b
// CHECK: [[BADDR:%[0-9]+]] = alloc_box ${ var B }
// CHECK: [[PB:%[0-9]+]] = project_box [[BADDR]]
(b as! D).foo()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]]
// CHECK: [[B:%[0-9]+]] = load [copy] [[READ]]
// CHECK: [[D:%[0-9]+]] = unconditional_checked_cast [[B]] : {{.*}} to D
// CHECK: apply {{.*}}([[D]])
// CHECK-NOT: destroy_value [[B]]
// CHECK: destroy_value [[D]]
// CHECK: destroy_value [[BADDR]]
// CHECK: return
}
func int(_ x: Int) {}
func ref(_ x: Ref) {}
func tuple() -> (Int, Ref) { return (1, Ref()) }
func tuple_explosion() {
int(tuple().0)
// CHECK: [[F:%[0-9]+]] = function_ref @$s8lifetime5tupleSi_AA3RefCtyF
// CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]()
// CHECK: ({{%.*}}, [[T1:%.*]]) = destructure_tuple [[TUPLE]]
// CHECK: destroy_value [[T1]]
// CHECK-NOT: destructure_tuple [[TUPLE]]
// CHECK-NOT: tuple_extract [[TUPLE]]
// CHECK-NOT: destroy_value
ref(tuple().1)
// CHECK: [[F:%[0-9]+]] = function_ref @$s8lifetime5tupleSi_AA3RefCtyF
// CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]()
// CHECK: ({{%.*}}, [[T1:%.*]]) = destructure_tuple [[TUPLE]]
// CHECK: destroy_value [[T1]]
// CHECK-NOT: destructure_tuple [[TUPLE]]
// CHECK-NOT: tuple_extract [[TUPLE]]
// CHECK-NOT: destroy_value [[TUPLE]]
}
|
apache-2.0
|
7eeee8bd5c35daf3cc5339859a45e6ef
| 39.111825 | 194 | 0.54914 | 3.042211 | false | false | false | false |
testpress/ios-app
|
ios-app/UI/PostCategoriesTableViewCell.swift
|
1
|
2681
|
//
// PostCategoriesTableViewCell.swift
// ios-app
//
/// Copyright © 2017 Testpress. 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 UIKit
class PostCategoriesTableViewCell: UITableViewCell {
@IBOutlet weak var contentViewCell: UIView!
@IBOutlet weak var categoryName: UILabel!
@IBOutlet weak var categoryColor: UIView!
var parentViewController: PostCategoriesTableViewController! = nil
var category: Category!
func initCell(_ category: Category, viewController: PostCategoriesTableViewController) {
self.category = category
parentViewController = viewController
categoryName.text = category.name
categoryColor.backgroundColor = Colors.getRGB(category.color)
let tapRecognizer = UITapGestureRecognizer(target: self,
action: #selector(self.onItemClick))
contentViewCell.addGestureRecognizer(tapRecognizer)
}
@objc func onItemClick() {
let storyboard = UIStoryboard(name: Constants.POST_STORYBOARD, bundle: nil)
let navigationController = storyboard.instantiateViewController(withIdentifier:
Constants.POSTS_LIST_NAVIGATION_CONTROLLER) as! UINavigationController
let viewController = navigationController.viewControllers.first as! PostTableViewController
viewController.category = category
viewController.categories = parentViewController.categories
parentViewController.present(navigationController, animated: true, completion: nil)
}
}
|
mit
|
a0e7ecd948717628840057e8118a5902
| 42.225806 | 99 | 0.720149 | 5.214008 | false | false | false | false |
gperdomor/MoyaModelMapper
|
Sources/MoyaModelMapper/Response+ModelMapper.swift
|
1
|
4231
|
//
// Response+ModelMapper.swift
// MoyaModelMapper
//
// Created by Gustavo Perdomo on 2/19/17.
// Copyright (c) 2017 Gustavo Perdomo. Licensed under the MIT license, as follows:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Moya
import Mapper
public extension Response {
/// Maps data received from the server into an object which implements the Mappable protocol.
///
/// - Parameter type: Type of the object which implements the Mappable protocol.
/// - Returns: The mappable object instance.
/// - Throws: MoyaError if the response can't be mapped.
public func map<T: Mappable>(to type: T.Type) throws -> T {
guard let jsonDictionary = try mapJSON() as? NSDictionary,
let object = T.from(jsonDictionary) else {
throw MoyaError.jsonMapping(self)
}
return object
}
/// Maps data received from the server into an object which implements the Mappable protocol.
///
/// - Parameters:
/// - type: Type of the object which implements the Mappable protocol.
/// - keyPath: Key of the inner json. This json will be used to map the object.
/// - Returns: The mappable object instance.
/// - Throws: MoyaError if the response can't be mapped.
public func map<T: Mappable>(to type: T.Type, fromKey keyPath: String?) throws -> T {
guard let keyPath = keyPath else { return try map(to: type) }
guard let jsonDictionary = try mapJSON() as? NSDictionary,
let objectDictionary = jsonDictionary.value(forKeyPath: keyPath) as? NSDictionary,
let object = T.from(objectDictionary) else {
throw MoyaError.jsonMapping(self)
}
return object
}
/// Maps data received from the server into an array of objects which implements the Mappable protocol.
///
/// - Parameter type: Type of the object which implements the Mappable protocol.
/// - Returns: The mappable object instance.
/// - Throws: MoyaError if the response can't be mapped.
public func map<T: Mappable>(to type: [T.Type]) throws -> [T] {
guard let data = try mapJSON() as? NSArray,
let object = T.from(data) else {
throw MoyaError.jsonMapping(self)
}
return object
}
/// Maps data received from the server into an array of object which implements the Mappable protocol.
///
/// - Parameters:
/// - type: Type of the object which implements the Mappable protocol.
/// - keyPath: Key of the inner json. This json will be used to map the array of object.
/// - Returns: The mappable object instance.
/// - Throws: MoyaError if the response can't be mapped.
public func map<T: Mappable>(to type: [T.Type], fromKey keyPath: String? = nil) throws -> [T] {
guard let keyPath = keyPath else { return try map(to: type) }
guard let data = try mapJSON() as? NSDictionary,
let objectArray = data.value(forKeyPath: keyPath) as? NSArray,
let object = T.from(objectArray) else {
throw MoyaError.jsonMapping(self)
}
return object
}
}
|
mit
|
6db52df6c4875599767dfb404a687a2c
| 42.173469 | 107 | 0.671236 | 4.510661 | false | false | false | false |
AlanAherne/BabyTunes
|
BabyTunes/BabyTunes/Modules/Main/Home/View controllers/RevealViewController.swift
|
1
|
7817
|
import UIKit
import AVFoundation
class RevealViewController: UIViewController, AVAudioPlayerDelegate, UIScrollViewDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var playPauseButton: UIButton!
@IBOutlet weak var currentTimeLabel: UILabel!
@IBOutlet weak var remainingTimeLabel: UILabel!
@IBOutlet weak var visualizerView: UIView!
var song: Song?
var swipeInteractionController: SwipeInteractionController?
var visualizerTimer:Timer! = Timer()
var audioVisualizer: ATAudioVisualizer!
var lowPassResults1:Double! = 0.0
var lowPassResult:Double! = 0.0
var audioPlayer:AVAudioPlayer!
var songTitel = ""
let visualizerAnimationDuration = 0.01
override func viewDidLoad() {
super.viewDidLoad()
guard let revealSong = song else {
NSLog("no song set in the card view controller")
return
}
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 5.0
let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapSinlge(recognizer:)))
singleTapGesture.numberOfTapsRequired = 1
self.scrollView.addGestureRecognizer(singleTapGesture)
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapDouble(recognizer:)))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapGesture.numberOfTouchesRequired = 1
self.scrollView.addGestureRecognizer(doubleTapGesture)
imageView.image = UIImage(named: (revealSong.title) + ".jpg")
view.backgroundColor = revealSong.languageEnum.languageTintColor()
swipeInteractionController = SwipeInteractionController(viewController: self)
self.initAudioPlayer()
self.initAudioVisualizer()
}
override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.post(name: .pauseBGMusic, object: nil)
self.audioPlayer.play()
startAudioVisualizer()
}
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.post(name: .playBGMusic, object: nil)
self.audioPlayer.stop()
stopAudioVisualizer()
}
@objc func tapSinlge(recognizer: UITapGestureRecognizer) {
if !self.audioPlayer.isPlaying{
self.audioPlayer.play()
startAudioVisualizer()
}
}
@objc func tapDouble(recognizer: UITapGestureRecognizer) {
if (self.scrollView!.zoomScale == self.scrollView!.minimumZoomScale) {
let center = recognizer.location(in: self.scrollView!)
let size = self.imageView!.image!.size
let zoomRect = CGRect(x:center.x, y:center.y, width:(size.width / 2), height:(size.height / 2))
self.scrollView!.zoom(to: zoomRect, animated: true)
} else {
self.scrollView!.setZoomScale(self.scrollView!.minimumZoomScale, animated: true)
}
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
@IBAction func dismissPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
func initAudioPlayer() {
let urlpath = Bundle.main.path(forResource: song?.title, ofType: "mp3")
let url = URL(fileURLWithPath: urlpath!)
let _: NSError?
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: url)
}
catch let error {
print(error)
}
audioPlayer.isMeteringEnabled = true
self.audioPlayer.delegate = self
audioPlayer.prepareToPlay()
}
func initAudioVisualizer() {
if (self.audioVisualizer == nil){
var frame = visualizerView.frame
frame.origin.x = 0
frame.origin.y = 0
let visualizerColor = UIColor(red: 255.0 / 255.0, green: 84.0 / 255.0, blue: 116.0 / 255.0, alpha: 1.0)
self.audioVisualizer = ATAudioVisualizer(barsNumber: 11, frame: frame, andColor: visualizerColor)
visualizerView.addSubview(audioVisualizer)
}
}
func startAudioVisualizer() {
if visualizerTimer != nil
{
visualizerTimer.invalidate()
visualizerTimer = nil
}
Timer.scheduledTimer(timeInterval: visualizerAnimationDuration, target: self, selector: #selector(visualizerTimerChanged), userInfo: nil, repeats: true)
}
func stopAudioVisualizer()
{
if visualizerTimer != nil
{
visualizerTimer.invalidate()
visualizerTimer = nil
}
audioVisualizer.stop()
}
@objc func visualizerTimerChanged(_ timer:CADisplayLink)
{
audioPlayer.updateMeters()
let ALPHA: Double = 1.05
let averagePower: Double = Double(audioPlayer.averagePower(forChannel: 0))
let averagePowerForChannel: Double = pow(10, (0.05 * averagePower))
lowPassResult = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassResult
let averagePowerForChannel1: Double = pow(10, (0.05 * Double(audioPlayer.averagePower(forChannel: 1))))
lowPassResults1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassResults1
audioVisualizer.animate(withChannel0Level: self._normalizedPowerLevelFromDecibels(audioPlayer.averagePower(forChannel: 0)), andChannel1Level: self._normalizedPowerLevelFromDecibels(audioPlayer.averagePower(forChannel: 1)))
self.updateLabels()
}
func updateLabels() {
self.currentTimeLabel.text! = self.convertSeconds(Float(audioPlayer.currentTime))
self.remainingTimeLabel.text! = self.convertSeconds(Float(audioPlayer.duration) - Float(audioPlayer.currentTime))
}
func convertSeconds(_ secs: Float) -> String {
var currentSecs = secs
if currentSecs < 0.1 {
currentSecs = 0
}
var totalSeconds = Int(secs)
if currentSecs > 0.45 {
totalSeconds += 1
}
let seconds = totalSeconds % 60
let minutes = (totalSeconds / 60) % 60
let hours = totalSeconds / 3600
if hours > 0 {
return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}
return String(format: "%02d:%02d", minutes, seconds)
}
func _normalizedPowerLevelFromDecibels(_ decibels: Float) -> Float {
if decibels < -60.0 || decibels == 0.0 {
return 0.0
}
return powf((powf(10.0, 0.05 * decibels) - powf(10.0, 0.05 * -60.0)) * (1.0 / (1.0 - powf(10.0, 0.05 * -60.0))), 1.0 / 2.0)
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print("audioPlayerDidFinishPlaying")
playPauseButton.setImage(UIImage(named: "play_")!, for: UIControlState())
playPauseButton.setImage(UIImage(named: "play")!, for: .highlighted)
playPauseButton.isSelected = false
self.currentTimeLabel.text! = "00:00"
self.remainingTimeLabel.text! = self.convertSeconds(Float(audioPlayer.duration))
self.stopAudioVisualizer()
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
print("audioPlayerDecodeErrorDidOccur")
playPauseButton.setImage(UIImage(named: "play_")!, for: UIControlState())
playPauseButton.setImage(UIImage(named: "play")!, for: .highlighted)
playPauseButton.isSelected = false
self.currentTimeLabel.text! = "00:00"
self.remainingTimeLabel.text! = "00:00"
self.stopAudioVisualizer()
}
}
|
mit
|
e53526a8ea9525881578cccd18041046
| 37.318627 | 230 | 0.640143 | 4.622708 | false | false | false | false |
AvcuFurkan/ColorMatchTabs
|
ColorMatchTabs/Classes/ViewController/PopoverViewController.swift
|
1
|
7896
|
//
// PopoverViewController.swift
// ColorMatchTabs
//
// Created by Serhii Butenko on 27/6/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
private let ContentPadding: CGFloat = 20
@objc public protocol PopoverViewControllerDelegate: class {
func popoverViewController(_ popoverViewController: PopoverViewController, didSelectItemAt index: Int)
}
@objc public protocol PopoverViewControllerDataSource: class {
func numberOfItems(inPopoverViewController popoverViewController: PopoverViewController) -> Int
func popoverViewController(_ popoverViewController: PopoverViewController, iconAt index: Int) -> UIImage
func popoverViewController(_ popoverViewController: PopoverViewController, hightlightedIconAt index: Int) -> UIImage
}
open class PopoverViewController: UIViewController {
open weak var dataSource: PopoverViewControllerDataSource?
open weak var delegate: PopoverViewControllerDelegate?
open let contentView = UIView()
var highlightedItemIndex: Int!
let menu: CircleMenu = CircleMenu()
fileprivate var icons: [UIImageView] = []
fileprivate var topConstraint: NSLayoutConstraint!
fileprivate var bottomConstraint: NSLayoutConstraint!
open override func viewDidLoad() {
super.viewDidLoad()
setupContentView()
setupMenu()
view.layoutIfNeeded()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
menu.triggerMenu()
}
open func reloadData() {
guard let dataSource = dataSource else {
return
}
icons.forEach { $0.removeFromSuperview() }
icons = []
for index in 0..<dataSource.numberOfItems(inPopoverViewController: self) {
let size = CGSize(width: menu.bounds.size.width / 2, height: menu.bounds.size.height / 2)
let origin = menu.centerOfItem(atIndex: index)
let iconImageView = UIImageView(frame: CGRect(origin: origin, size: size))
iconImageView.image = dataSource.popoverViewController(self, hightlightedIconAt: index)
iconImageView.contentMode = .center
iconImageView.isHidden = true
view.addSubview(iconImageView)
icons.append(iconImageView)
}
moveIconsToDefaultPositions()
}
}
// setup
private extension PopoverViewController {
func setupContentView() {
view.addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: ContentPadding).isActive = true
contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -ContentPadding).isActive = true
topConstraint = contentView.topAnchor.constraint(equalTo: view.topAnchor, constant: view.bounds.height)
bottomConstraint = contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: view.bounds.height)
topConstraint.isActive = true
bottomConstraint.isActive = true
}
func setupMenu() {
guard let image = UIImage(namedInCurrentBundle: "circle_menu") else {
return
}
menu.image = image
menu.delegate = self
view.addSubview(menu)
menu.addTarget(self, action: #selector(hidePopover(_:)), for: .touchUpInside)
menu.translatesAutoresizingMaskIntoConstraints = false
menu.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: PlusButtonButtonOffset).isActive = true
menu.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
menu.widthAnchor.constraint(equalToConstant: image.size.width).isActive = true
menu.heightAnchor.constraint(equalToConstant: image.size.height).isActive = true
}
}
// actions
private extension PopoverViewController {
@objc func hidePopover(_ sender: AnyObject? = nil) {
dismiss(animated: true, completion: nil)
}
}
// animation
private extension PopoverViewController {
func moveIconsToDefaultPositions() {
for (index, iconImageView) in icons.enumerated() {
UIView.animate(
withDuration: AnimationDuration,
delay: 0,
usingSpringWithDamping: 0.8,
initialSpringVelocity: 3,
options: [],
animations: {
iconImageView.center = CGPoint(
x: iconImageView.center.x,
y: iconImageView.center.y - self.view.frame.height / 2
)
let shouldHighlight = index == self.highlightedItemIndex
if shouldHighlight {
iconImageView.image = self.dataSource?.popoverViewController(self, hightlightedIconAt: index)
} else {
iconImageView.image = self.dataSource?.popoverViewController(self, iconAt: index)
}
},
completion: nil
)
}
}
func moveIconsToCircle() {
for (index, iconImageView) in icons.enumerated() {
iconImageView.isHidden = false
UIView.animate(
withDuration: AnimationDuration,
delay: 0,
usingSpringWithDamping: 0.95,
initialSpringVelocity: 3,
options: [],
animations: {
iconImageView.center = self.menu.centerOfItem(atIndex: index)
iconImageView.image = self.dataSource?.popoverViewController(self, hightlightedIconAt: index)
},
completion: nil
)
}
}
func showContentView() {
let count = dataSource!.numberOfItems(inPopoverViewController: self)
let center = menu.centerOfItem(atIndex: count / 2)
let bottomOffset = view.bounds.height - center.y + menu.itemDimension / 2 + ContentPadding
contentView.layer.add(CAAnimation.opacityAnimation(withDuration: AnimationDuration, initialValue: 0, finalValue: 1), forKey: nil)
contentView.alpha = 1
topConstraint.constant = ContentPadding
bottomConstraint.constant = -bottomOffset
UIView.animate(
withDuration: AnimationDuration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 3,
options: [],
animations: {
self.view.layoutIfNeeded()
},
completion: nil
)
}
func hideContentMenu() {
contentView.layer.add(CAAnimation.opacityAnimation(withDuration: AnimationDuration, initialValue: 1, finalValue: 0), forKey: nil)
contentView.alpha = 0
topConstraint.constant += view.bounds.height
bottomConstraint.constant += view.bounds.height
UIView.animate(
withDuration: AnimationDuration,
animations: {
self.view.layoutIfNeeded()
},
completion: nil
)
}
}
extension PopoverViewController: CircleMenuDelegate {
public func circleMenuWillDisplayItems(_ circleMenu: CircleMenu) {
moveIconsToCircle()
showContentView()
}
public func circleMenuWillHideItems(_ circleMenu: CircleMenu) {
moveIconsToDefaultPositions()
hideContentMenu()
}
public func circleMenu(_ circleMenu: CircleMenu, didSelectItemAt index: Int) {
hidePopover()
delegate?.popoverViewController(self, didSelectItemAt: index)
}
}
|
mit
|
176b3b120b570ad1386d7d09e23cc58c
| 33.326087 | 137 | 0.624699 | 5.643317 | false | false | false | false |
lingochamp/FuriganaTextView
|
src/FuriganaTextView.swift
|
1
|
6547
|
//
// FuriganaTextView.swift
// Tydus
//
// Created by Yan Li on 3/30/15.
// Copyright (c) 2015 Liulishuo.com. All rights reserved.
//
import UIKit
public struct FuriganaTextStyle
{
public let hostingLineHeightMultiple: CGFloat
public let textOffsetMultiple: CGFloat
}
// MARK: - Base Class
open class FuriganaTextView: UIView
{
// MARK: - Public
public var contentView: UITextView? {
return underlyingTextView
}
open var furiganaEnabled = true
open var furiganaTextStyle = FuriganaTextStyle(hostingLineHeightMultiple: 1.6, textOffsetMultiple: 0)
open var furiganas: [Furigana]?
open var contents: NSAttributedString?
{
set
{
mutableContents = newValue?.mutableCopy() as? NSMutableAttributedString
if furiganaEnabled
{
addFuriganaAttributes()
}
setup()
}
get
{
return mutableContents?.copy() as? NSAttributedString
}
}
// MARK: - Private
fileprivate var mutableContents: NSMutableAttributedString?
fileprivate weak var underlyingTextView: UITextView?
// [Yan Li]
// A strong reference is needed, because NSLayoutManagerDelegate is unowned by the manager
fileprivate var furiganaWordKerner: FuriganaWordKerner?
fileprivate func setup()
{
underlyingTextView?.removeFromSuperview()
if furiganaEnabled
{
setupFuriganaView()
}
else
{
setupRegularView()
}
}
fileprivate func setupFuriganaView()
{
if let validContents = mutableContents
{
let layoutManager = FuriganaLayoutManager()
layoutManager.textOffsetMultiple = furiganaTextStyle.textOffsetMultiple
let kerner = FuriganaWordKerner()
layoutManager.delegate = kerner
let textContainer = NSTextContainer()
layoutManager.addTextContainer(textContainer)
let fullTextRange = NSMakeRange(0, (validContents.string as NSString).length)
let paragrapStyle = NSMutableParagraphStyle()
paragrapStyle.alignment = alignment
paragrapStyle.lineHeightMultiple = furiganaTextStyle.hostingLineHeightMultiple
validContents.addAttribute(NSParagraphStyleAttributeName, value: paragrapStyle, range: fullTextRange)
let textStorage = NSTextStorage(attributedString: validContents)
textStorage.addLayoutManager(layoutManager)
let textView = textViewWithTextContainer(textContainer)
addSubview(textView)
addConstraints(fullLayoutConstraints(textView))
furiganaWordKerner = kerner
underlyingTextView = textView
}
}
fileprivate func setupRegularView()
{
if let validContents = mutableContents
{
let textView = textViewWithTextContainer(nil)
textView.attributedText = validContents
addSubview(textView)
addConstraints(fullLayoutConstraints(textView))
underlyingTextView = textView
}
}
fileprivate func textViewWithTextContainer(_ textContainer: NSTextContainer?) -> UITextView
{
let textView = UITextView(frame: bounds, textContainer: textContainer)
textView.isEditable = false
textView.isScrollEnabled = scrollEnabled
textView.alwaysBounceVertical = true
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
return textView
}
fileprivate func fullLayoutConstraints(_ view: UIView) -> [NSLayoutConstraint]
{
view.translatesAutoresizingMaskIntoConstraints = false
let vertical = NSLayoutConstraint.constraints(
withVisualFormat: "V:|-(0)-[view]-(0)-|",
options: [],
metrics: nil,
views: ["view" : view])
let horizontal = NSLayoutConstraint.constraints(
withVisualFormat: "H:|-(0)-[view]-(0)-|",
options: [],
metrics: nil,
views: ["view" : view])
return vertical + horizontal
}
// MARK: - Deprecated
@available(*, deprecated)
open var scrollEnabled: Bool = true
@available(*, deprecated)
open var alignment: NSTextAlignment = .left
}
// MARK: - Furigana Handling
extension FuriganaTextView
{
fileprivate func addFuriganaAttributes()
{
if let validContents = mutableContents
{
if let validFuriganas = furiganas
{
var inserted = 0
for (_, furigana) in validFuriganas.enumerated()
{
var furiganaRange = furigana.range
let furiganaValue = FuriganaStringRepresentation(furigana)
let furiganaLength = (furigana.text as NSString).length
let contentsLenght = furigana.range.length
if furiganaLength > contentsLenght
{
let currentAttributes = validContents.attributes(at: furiganaRange.location + inserted, effectiveRange: nil)
let kerningString = NSAttributedString(string: kDefaultFuriganaKerningControlCharacter, attributes: currentAttributes)
let endLocation = furigana.range.location + furigana.range.length + inserted
validContents.insert(kerningString, at: endLocation)
let startLocation = furigana.range.location + inserted
validContents.insert(kerningString, at: startLocation)
let insertedLength = (kDefaultFuriganaKerningControlCharacter as NSString).length * 2
inserted += insertedLength
furiganaRange.location = startLocation
furiganaRange.length += insertedLength
}
else
{
furiganaRange.location += inserted
}
validContents.addAttribute(kFuriganaAttributeName, value: furiganaValue, range: furiganaRange)
}
let fullTextRange = NSMakeRange(0, (validContents.string as NSString).length)
validContents.fixAttributes(in: fullTextRange)
mutableContents = validContents
}
}
}
}
// MARK: - Auto Layout
extension FuriganaTextView
{
override open var intrinsicContentSize: CGSize
{
if let textView = underlyingTextView
{
let intrinsicSize = textView.sizeThatFits(CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude))
// [Yan Li]
// There is a time that we have to multiply the result by the line height multiple
// to make it work, but it seems fine now.
// intrinsicSize.height *= furiganaTextStyle.hostingLineHeightMultiple
return intrinsicSize
}
else
{
return CGSize.zero
}
}
}
|
mit
|
8f6769e36c44792bc473ec4ff2aaaba7
| 26.624473 | 130 | 0.673133 | 4.944864 | false | false | false | false |
nheagy/WordPress-iOS
|
WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationSettingsViewController.swift
|
1
|
15873
|
import Foundation
import WordPressShared.WPStyleGuide
import WordPressComAnalytics
/**
* @class NotificationSettingsViewController
* @brief The purpose of this class is to retrieve the collection of NotificationSettings
* from WordPress.com Backend, and render the "Top Level" list.
* On Row Press, we'll push the list of available Streams, which will, in turn,
* push the Details View itself, which is in charge of rendering the actual available settings.
*/
public class NotificationSettingsViewController : UIViewController
{
// MARK: - View Lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
// Initialize Interface
setupNavigationItem()
setupTableView()
// Load Settings
reloadSettings()
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
WPAnalytics.track(.OpenedNotificationSettingsList)
// Manually deselect the selected row. This is required due to a bug in iOS7 / iOS8
tableView.deselectSelectedRowWithAnimation(true)
}
// MARK: - Setup Helpers
private func setupNavigationItem() {
title = NSLocalizedString("Notifications", comment: "Title displayed in the Notification settings")
navigationItem.backBarButtonItem = UIBarButtonItem(title: String(), style: .Plain, target: nil, action: nil)
}
private func setupTableView() {
// Register the cells
tableView.registerClass(WPBlogTableViewCell.self, forCellReuseIdentifier: blogReuseIdentifier)
tableView.registerClass(WPTableViewCell.self, forCellReuseIdentifier: defaultReuseIdentifier)
// Hide the separators, whenever the table is empty
tableView.tableFooterView = UIView()
// Style!
WPStyleGuide.configureColorsForView(view, andTableView: tableView)
tableView.cellLayoutMarginsFollowReadableWidth = false
}
// MARK: - Service Helpers
private func reloadSettings() {
let service = NotificationsService(managedObjectContext: ContextManager.sharedInstance().mainContext)
activityIndicatorView.startAnimating()
service.getAllSettings({ [weak self] (settings: [NotificationSettings]) in
self?.groupedSettings = self?.groupSettings(settings)
self?.activityIndicatorView.stopAnimating()
self?.tableView.reloadData()
},
failure: { [weak self] (error: NSError!) in
self?.handleLoadError()
})
}
private func groupSettings(settings: [NotificationSettings]) -> [[NotificationSettings]] {
// Find the Default Blog ID
let service = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext)
let defaultAccount = service.defaultWordPressComAccount()
let primaryBlogId = defaultAccount?.defaultBlog?.dotComID as? Int
// Proceed Grouping
var blogSettings = [NotificationSettings]()
var otherSettings = [NotificationSettings]()
var wpcomSettings = [NotificationSettings]()
for setting in settings {
switch setting.channel {
case let .Blog(blogId):
// Make sure that the Primary Blog is the first one in its category
if blogId == primaryBlogId {
blogSettings.insert(setting, atIndex: 0)
} else {
blogSettings.append(setting)
}
case .Other:
otherSettings.append(setting)
case .WordPressCom:
wpcomSettings.append(setting)
}
}
assert(otherSettings.count == 1)
assert(wpcomSettings.count == 1)
// Sections: Blogs + Other + WpCom
return [blogSettings, otherSettings, wpcomSettings]
}
// MARK: - Error Handling
private func handleLoadError() {
let title = NSLocalizedString("Oops!", comment: "")
let message = NSLocalizedString("There has been a problem while loading your Notification Settings",
comment: "Displayed after Notification Settings failed to load")
let cancelText = NSLocalizedString("Cancel", comment: "Cancel. Action.")
let retryText = NSLocalizedString("Try Again", comment: "Try Again. Action")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addCancelActionWithTitle(cancelText) { (action: UIAlertAction) in
self.navigationController?.popViewControllerAnimated(true)
}
alertController.addDefaultActionWithTitle(retryText) { (action: UIAlertAction) in
self.reloadSettings()
}
presentViewController(alertController, animated: true, completion: nil)
}
// MARK: - UITableView Datasource Methods
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return groupedSettings?.count ?? emptyCount
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .Blog where requiresBlogsPagination:
return displayMoreWasAccepted ? rowCountForBlogSection + 1 : loadMoreRowCount
default:
return groupedSettings![section].count
}
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = reusableIdentifierForIndexPath(indexPath)
let cell = tableView.dequeueReusableCellWithIdentifier(identifier)!
configureCell(cell, indexPath: indexPath)
return cell
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let isBlogSection = indexPath.section == Section.Blog.rawValue
let isNotPagination = !isPaginationRow(indexPath)
return isBlogSection && isNotPagination ? blogRowHeight : WPTableViewDefaultRowHeight
}
public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// Hide when the section is empty!
if isSectionEmpty(section) {
return nil
}
let theSection = Section(rawValue: section)!
let footerView = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Header)
footerView.title = theSection.headerText()
return footerView
}
public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Hide when the section is empty!
if isSectionEmpty(section) {
return CGFloat.min
}
let theSection = Section(rawValue: section)!
let width = view.frame.width
return WPTableViewSectionHeaderFooterView.heightForHeader(theSection.headerText(), width: width)
}
public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
// Hide when the section is empty!
if isSectionEmpty(section) {
return nil
}
let theSection = Section(rawValue: section)!
let footerView = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Footer)
footerView.title = theSection.footerText()
return footerView
}
public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// Hide when the section is empty!
if isSectionEmpty(section) {
return CGFloat.min
}
let section = Section(rawValue: section)!
let padding = section.footerPadding()
let height = WPTableViewSectionHeaderFooterView.heightForFooter(section.footerText(), width: view.frame.width)
return height + padding
}
// MARK: - UITableView Delegate Methods
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if isPaginationRow(indexPath) {
toggleDisplayMoreBlogs()
} else if let settings = settingsForRowAtIndexPath(indexPath) {
displayDetailsForSettings(settings)
} else {
tableView.deselectSelectedRowWithAnimation(true)
}
}
// MARK: - UITableView Helpers
private func reusableIdentifierForIndexPath(indexPath: NSIndexPath) -> String {
switch Section(rawValue: indexPath.section)! {
case .Blog where !isPaginationRow(indexPath):
return blogReuseIdentifier
default:
return defaultReuseIdentifier
}
}
private func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) {
// Pagination Rows don't really have a Settings entity
if isPaginationRow(indexPath) {
cell.textLabel?.text = paginationRowDescription(indexPath)
cell.textLabel?.textAlignment = .Left
cell.accessoryType = .None
WPStyleGuide.configureTableViewCell(cell)
return
}
// Proceed rendering the settings
let settings = settingsForRowAtIndexPath(indexPath)!
switch settings.channel {
case .Blog(_):
cell.textLabel?.text = settings.blog?.settings?.name ?? settings.channel.description()
cell.detailTextLabel?.text = settings.blog?.displayURL ?? String()
cell.accessoryType = .DisclosureIndicator
if let siteIconURL = settings.blog?.icon {
cell.imageView?.setImageWithSiteIcon(siteIconURL)
} else {
cell.imageView?.image = WPStyleGuide.Notifications.blavatarPlaceholderImage
}
WPStyleGuide.configureTableViewSmallSubtitleCell(cell)
default:
cell.textLabel?.text = settings.channel.description()
cell.textLabel?.textAlignment = .Left
cell.accessoryType = .DisclosureIndicator
WPStyleGuide.configureTableViewCell(cell)
}
}
private func settingsForRowAtIndexPath(indexPath: NSIndexPath) -> NotificationSettings? {
return groupedSettings?[indexPath.section][indexPath.row]
}
private func isSectionEmpty(sectionIndex: Int) -> Bool {
return groupedSettings == nil || groupedSettings?[sectionIndex].count == 0
}
// MARK: - Load More Helpers
private var rowCountForBlogSection : Int {
return groupedSettings?[Section.Blog.rawValue].count ?? 0
}
private var requiresBlogsPagination : Bool {
return rowCountForBlogSection > loadMoreRowIndex
}
private func isDisplayMoreRow(path: NSIndexPath) -> Bool {
let isDisplayMoreRow = path.section == Section.Blog.rawValue && path.row == loadMoreRowIndex
return requiresBlogsPagination && !displayMoreWasAccepted && isDisplayMoreRow
}
private func isDisplayLessRow(path: NSIndexPath) -> Bool {
let isDisplayLessRow = path.section == Section.Blog.rawValue && path.row == rowCountForBlogSection
return requiresBlogsPagination && displayMoreWasAccepted && isDisplayLessRow
}
private func isPaginationRow(path: NSIndexPath) -> Bool {
return isDisplayMoreRow(path) || isDisplayLessRow(path)
}
private func paginationRowDescription(path: NSIndexPath) -> String {
if isDisplayMoreRow(path) {
return NSLocalizedString("View all…", comment: "Displays More Rows")
}
return NSLocalizedString("View less…", comment: "Displays Less Rows")
}
private func toggleDisplayMoreBlogs() {
// Remember this action!
displayMoreWasAccepted = !displayMoreWasAccepted
// And refresh the section
let sections = NSIndexSet(index: Section.Blog.rawValue)
tableView.reloadSections(sections, withRowAnimation: .Fade)
}
// MARK: - Segue Helpers
private func displayDetailsForSettings(settings: NotificationSettings) {
switch settings.channel {
case .WordPressCom:
// WordPress.com Row will push the SettingDetails ViewController, directly
let detailsViewController = NotificationSettingDetailsViewController(settings: settings)
navigationController?.pushViewController(detailsViewController, animated: true)
default:
// Our Sites + 3rd Party Sites rows will push the Streams View
let streamsViewController = NotificationSettingStreamsViewController(settings: settings)
navigationController?.pushViewController(streamsViewController, animated: true)
}
}
// MARK: - Table Sections
private enum Section : Int {
case Blog = 0
case Other = 1
case WordPressCom = 2
func headerText() -> String {
switch self {
case .Blog:
return NSLocalizedString("Your Sites", comment: "Displayed in the Notification Settings View")
case .Other:
return NSLocalizedString("Other", comment: "Displayed in the Notification Settings View")
case .WordPressCom:
return String()
}
}
func footerText() -> String {
switch self {
case .Blog:
return NSLocalizedString("Customize your site settings for Likes, Comments, Follows, and more.",
comment: "Notification Settings for your own blogs")
case .Other:
return String()
case .WordPressCom:
return NSLocalizedString("We’ll always send important emails regarding your account, " +
"but you can get some helpful extras, too.",
comment: "Title displayed in the Notification Settings for WordPress.com")
}
}
func footerPadding() -> CGFloat {
switch self {
case .WordPressCom:
return UIDevice.isPad() ? Section.paddingWordPress : Section.paddingZero
default:
return Section.paddingZero
}
}
// MARK: - Private Constants
private static let paddingZero = CGFloat(0)
private static let paddingWordPress = CGFloat(40)
}
// MARK: - Private Outlets
@IBOutlet private var tableView : UITableView!
@IBOutlet private var activityIndicatorView : UIActivityIndicatorView!
// MARK: - Private Constants
private let blogReuseIdentifier = WPBlogTableViewCell.classNameWithoutNamespaces()
private let blogRowHeight = CGFloat(54.0)
private let defaultReuseIdentifier = WPTableViewCell.classNameWithoutNamespaces()
private let emptyCount = 0
private let loadMoreRowIndex = 3
private let loadMoreRowCount = 4
// MARK: - Private Properties
private var groupedSettings : [[NotificationSettings]]?
private var displayMoreWasAccepted = false
}
|
gpl-2.0
|
f7172ca0f3e69ba013353852f02f2ccc
| 38.081281 | 127 | 0.625197 | 5.867973 | false | false | false | false |
realm/SwiftLint
|
Tests/SwiftLintTestHelpers/TestHelpers.swift
|
1
|
25559
|
import Foundation
import SourceKittenFramework
@testable import SwiftLintFramework
import XCTest
// swiftlint:disable file_length
private let violationMarker = "↓"
private extension SwiftLintFile {
static func testFile(withContents contents: String, persistToDisk: Bool = false) -> SwiftLintFile {
let file: SwiftLintFile
if persistToDisk {
let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension("swift")
_ = try? contents.data(using: .utf8)!.write(to: url)
file = SwiftLintFile(path: url.path)!
} else {
file = SwiftLintFile(contents: contents)
}
file.markAsTestFile()
return file
}
func makeCompilerArguments() -> [String] {
let sdk = sdkPath()
let frameworks = URL(fileURLWithPath: sdk, isDirectory: true)
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("Library")
.appendingPathComponent("Frameworks")
.path
return [
"-F",
frameworks,
"-sdk", sdk,
"-j4", path!
]
}
}
public extension String {
func stringByAppendingPathComponent(_ pathComponent: String) -> String {
return bridge().appendingPathComponent(pathComponent)
}
}
public let allRuleIdentifiers = Set(primaryRuleList.list.keys)
public extension Configuration {
func applyingConfiguration(from example: Example) -> Configuration {
guard let exampleConfiguration = example.configuration,
case let .only(onlyRules) = self.rulesMode,
let firstRule = (onlyRules.first { $0 != "superfluous_disable_command" }),
case let configDict = ["only_rules": onlyRules, firstRule: exampleConfiguration],
let typedConfiguration = try? Configuration(dict: configDict) else { return self }
return merged(withChild: typedConfiguration, rootDirectory: rootDirectory)
}
}
public func violations(_ example: Example, config inputConfig: Configuration = Configuration.default,
requiresFileOnDisk: Bool = false) -> [StyleViolation] {
SwiftLintFile.clearCaches()
let config = inputConfig.applyingConfiguration(from: example)
let stringStrippingMarkers = example.removingViolationMarkers()
guard requiresFileOnDisk else {
let file = SwiftLintFile.testFile(withContents: stringStrippingMarkers.code)
let storage = RuleStorage()
let linter = Linter(file: file, configuration: config).collect(into: storage)
return linter.styleViolations(using: storage)
}
let file = SwiftLintFile.testFile(withContents: stringStrippingMarkers.code, persistToDisk: true)
let storage = RuleStorage()
let collecter = Linter(file: file, configuration: config, compilerArguments: file.makeCompilerArguments())
let linter = collecter.collect(into: storage)
return linter.styleViolations(using: storage).withoutFiles()
}
public extension Collection where Element == String {
func violations(config: Configuration = Configuration.default, requiresFileOnDisk: Bool = false)
-> [StyleViolation] {
return map { SwiftLintFile.testFile(withContents: $0, persistToDisk: requiresFileOnDisk) }
.violations(config: config, requiresFileOnDisk: requiresFileOnDisk)
}
func corrections(config: Configuration = Configuration.default, requiresFileOnDisk: Bool = false) -> [Correction] {
return map { SwiftLintFile.testFile(withContents: $0, persistToDisk: requiresFileOnDisk) }
.corrections(config: config, requiresFileOnDisk: requiresFileOnDisk)
}
}
public extension Collection where Element: SwiftLintFile {
func violations(config: Configuration = Configuration.default, requiresFileOnDisk: Bool = false)
-> [StyleViolation] {
let storage = RuleStorage()
let violations = map({ file in
Linter(file: file, configuration: config,
compilerArguments: requiresFileOnDisk ? file.makeCompilerArguments() : [])
}).map({ linter in
linter.collect(into: storage)
}).flatMap({ linter in
linter.styleViolations(using: storage)
})
return requiresFileOnDisk ? violations.withoutFiles() : violations
}
func corrections(config: Configuration = Configuration.default, requiresFileOnDisk: Bool = false) -> [Correction] {
let storage = RuleStorage()
let corrections = map({ file in
Linter(file: file, configuration: config,
compilerArguments: requiresFileOnDisk ? file.makeCompilerArguments() : [])
}).map({ linter in
linter.collect(into: storage)
}).flatMap({ linter in
linter.correct(using: storage)
})
return requiresFileOnDisk ? corrections.withoutFiles() : corrections
}
}
private extension Collection where Element == StyleViolation {
func withoutFiles() -> [StyleViolation] {
return map { violation in
let locationWithoutFile = Location(file: nil, line: violation.location.line,
character: violation.location.character)
return violation.with(location: locationWithoutFile)
}
}
}
private extension Collection where Element == Correction {
func withoutFiles() -> [Correction] {
return map { correction in
let locationWithoutFile = Location(file: nil, line: correction.location.line,
character: correction.location.character)
return Correction(ruleDescription: correction.ruleDescription, location: locationWithoutFile)
}
}
}
public extension Collection where Element == Example {
/// Returns a dictionary with SwiftLint violation markers (↓) removed from keys.
///
/// - returns: A new `Array`.
func removingViolationMarkers() -> [Element] {
return map { $0.removingViolationMarkers() }
}
}
private func cleanedContentsAndMarkerOffsets(from contents: String) -> (String, [Int]) {
var contents = contents.bridge()
var markerOffsets = [Int]()
var markerRange = contents.range(of: violationMarker)
while markerRange.location != NSNotFound {
markerOffsets.append(markerRange.location)
contents = contents.replacingCharacters(in: markerRange, with: "").bridge()
markerRange = contents.range(of: violationMarker)
}
return (contents.bridge(), markerOffsets.sorted())
}
private func render(violations: [StyleViolation], in contents: String) -> String {
var contents = StringView(contents).lines.map { $0.content }
for violation in violations.sorted(by: { $0.location > $1.location }) {
guard let line = violation.location.line,
let character = violation.location.character else { continue }
let message = String(repeating: " ", count: character - 1) + "^ " + [
"\(violation.severity.rawValue): ",
"\(violation.ruleName) Violation: ",
violation.reason,
" (\(violation.ruleIdentifier))"].joined()
if line >= contents.count {
contents.append(message)
} else {
contents.insert(message, at: line)
}
}
return """
```
\(contents.joined(separator: "\n"))
```
"""
}
private func render(locations: [Location], in contents: String) -> String {
var contents = StringView(contents).lines.map { $0.content }
for location in locations.sorted(by: > ) {
guard let line = location.line, let character = location.character else { continue }
let content = NSMutableString(string: contents[line - 1])
content.insert("↓", at: character - 1)
contents[line - 1] = content.bridge()
}
return """
```
\(contents.joined(separator: "\n"))
```
"""
}
private extension Configuration {
func assertCorrection(_ before: Example, expected: Example) {
let (cleanedBefore, markerOffsets) = cleanedContentsAndMarkerOffsets(from: before.code)
let file = SwiftLintFile.testFile(withContents: cleanedBefore, persistToDisk: true)
// expectedLocations are needed to create before call `correct()`
let expectedLocations = markerOffsets.map { Location(file: file, characterOffset: $0) }
let includeCompilerArguments = self.rules.contains(where: { $0 is AnalyzerRule })
let compilerArguments = includeCompilerArguments ? file.makeCompilerArguments() : []
let storage = RuleStorage()
let collecter = Linter(file: file, configuration: self, compilerArguments: compilerArguments)
let linter = collecter.collect(into: storage)
let corrections = linter.correct(using: storage).sorted { $0.location < $1.location }
if expectedLocations.isEmpty {
XCTAssertEqual(
corrections.count, before.code != expected.code ? 1 : 0, #function + ".expectedLocationsEmpty",
file: before.file, line: before.line)
} else {
XCTAssertEqual(
corrections.count,
expectedLocations.count,
#function + ".expected locations: \(expectedLocations.count)",
file: before.file, line: before.line
)
// With SwiftSyntax rewriters, the visitors get called with the new nodes after previous mutations have
// been applied, so it's not straightforward to translate those back into the original source positions.
// So only check the first locations
if let firstCorrection = corrections.first {
XCTAssertEqual(
firstCorrection.location,
expectedLocations.first,
#function + ".correction location",
file: before.file, line: before.line
)
}
}
XCTAssertEqual(
file.contents,
expected.code,
#function + ".file contents",
file: before.file, line: before.line)
let path = file.path!
do {
let corrected = try String(contentsOfFile: path, encoding: .utf8)
XCTAssertEqual(
corrected,
expected.code,
#function + ".corrected file equals expected",
file: before.file, line: before.line)
} catch {
XCTFail(
"couldn't read file at path '\(path)': \(error)",
file: before.file, line: before.line)
}
}
}
private extension String {
func toStringLiteral() -> String {
return "\"" + replacingOccurrences(of: "\n", with: "\\n") + "\""
}
}
public func makeConfig(_ ruleConfiguration: Any?, _ identifier: String,
skipDisableCommandTests: Bool = false) -> Configuration? {
let superfluousDisableCommandRuleIdentifier = SuperfluousDisableCommandRule.description.identifier
let identifiers: Set<String> = skipDisableCommandTests ? [identifier]
: [identifier, superfluousDisableCommandRuleIdentifier]
if let ruleConfiguration = ruleConfiguration, let ruleType = primaryRuleList.list[identifier] {
// The caller has provided a custom configuration for the rule under test
return (try? ruleType.init(configuration: ruleConfiguration)).flatMap { configuredRule in
let rules = skipDisableCommandTests ? [configuredRule] : [configuredRule, SuperfluousDisableCommandRule()]
return Configuration(
rulesMode: .only(identifiers),
allRulesWrapped: rules.map { ($0, false) }
)
}
}
return Configuration(rulesMode: .only(identifiers))
}
private func testCorrection(_ correction: (Example, Example),
configuration: Configuration,
testMultiByteOffsets: Bool) {
#if os(Linux)
guard correction.0.testOnLinux else {
return
}
#endif
var config = configuration
if let correctionConfiguration = correction.0.configuration,
case let .only(onlyRules) = configuration.rulesMode,
let ruleToConfigure = (onlyRules.first { $0 != SuperfluousDisableCommandRule.description.identifier }),
case let configDict = ["only_rules": onlyRules, ruleToConfigure: correctionConfiguration],
let typedConfiguration = try? Configuration(dict: configDict) {
config = configuration.merged(withChild: typedConfiguration, rootDirectory: configuration.rootDirectory)
}
config.assertCorrection(correction.0, expected: correction.1)
if testMultiByteOffsets && correction.0.testMultiByteOffsets {
config.assertCorrection(addEmoji(correction.0), expected: addEmoji(correction.1))
}
}
private func addEmoji(_ example: Example) -> Example {
return example.with(code: "/* 👨👩👧👦👨👩👧👦👨👩👧👦 */\n\(example.code)")
}
private func addShebang(_ example: Example) -> Example {
return example.with(code: "#!/usr/bin/env swift\n\(example.code)")
}
public extension XCTestCase {
var isRunningWithBazel: Bool { FileManager.default.currentDirectoryPath.contains("bazel-out") }
func verifyRule(_ ruleDescription: RuleDescription,
ruleConfiguration: Any? = nil,
commentDoesntViolate: Bool = true,
stringDoesntViolate: Bool = true,
skipCommentTests: Bool = false,
skipStringTests: Bool = false,
skipDisableCommandTests: Bool = false,
testMultiByteOffsets: Bool = true,
testShebang: Bool = true,
file: StaticString = #file,
line: UInt = #line) {
guard ruleDescription.minSwiftVersion <= .current else {
return
}
guard let config = makeConfig(
ruleConfiguration,
ruleDescription.identifier,
skipDisableCommandTests: skipDisableCommandTests) else {
XCTFail("Failed to create configuration", file: (file), line: line)
return
}
let disableCommands: [String]
if skipDisableCommandTests {
disableCommands = []
} else {
disableCommands = ruleDescription.allIdentifiers.map { "// swiftlint:disable \($0)\n" }
}
self.verifyLint(ruleDescription, config: config, commentDoesntViolate: commentDoesntViolate,
stringDoesntViolate: stringDoesntViolate, skipCommentTests: skipCommentTests,
skipStringTests: skipStringTests, disableCommands: disableCommands,
testMultiByteOffsets: testMultiByteOffsets, testShebang: testShebang)
self.verifyCorrections(ruleDescription, config: config, disableCommands: disableCommands,
testMultiByteOffsets: testMultiByteOffsets)
}
func verifyLint(_ ruleDescription: RuleDescription,
config: Configuration,
commentDoesntViolate: Bool = true,
stringDoesntViolate: Bool = true,
skipCommentTests: Bool = false,
skipStringTests: Bool = false,
disableCommands: [String] = [],
testMultiByteOffsets: Bool = true,
testShebang: Bool = true,
file: StaticString = #file,
line: UInt = #line) {
func verify(triggers: [Example], nonTriggers: [Example]) {
verifyExamples(triggers: triggers, nonTriggers: nonTriggers, configuration: config,
requiresFileOnDisk: ruleDescription.requiresFileOnDisk, file: file, line: line)
}
func makeViolations(_ example: Example) -> [StyleViolation] {
return violations(example, config: config, requiresFileOnDisk: ruleDescription.requiresFileOnDisk)
}
let ruleDescription = ruleDescription.focused()
let (triggers, nonTriggers) = (ruleDescription.triggeringExamples, ruleDescription.nonTriggeringExamples)
verify(triggers: triggers, nonTriggers: nonTriggers)
if testMultiByteOffsets {
verify(triggers: triggers.filter(\.testMultiByteOffsets).map(addEmoji),
nonTriggers: nonTriggers.filter(\.testMultiByteOffsets).map(addEmoji))
}
if testShebang {
verify(triggers: triggers.filter(\.testMultiByteOffsets).map(addShebang),
nonTriggers: nonTriggers.filter(\.testMultiByteOffsets).map(addShebang))
}
// Comment doesn't violate
if !skipCommentTests {
let triggersToCheck = triggers.filter(\.testWrappingInComment)
XCTAssertEqual(
triggersToCheck.flatMap { makeViolations($0.with(code: "/*\n " + $0.code + "\n */")) }.count,
commentDoesntViolate ? 0 : triggersToCheck.count,
"Violation(s) still triggered when code was nested inside a comment",
file: (file), line: line
)
}
// String doesn't violate
if !skipStringTests {
let triggersToCheck = triggers.filter(\.testWrappingInString)
XCTAssertEqual(
triggersToCheck.flatMap({ makeViolations($0.with(code: $0.code.toStringLiteral())) }).count,
stringDoesntViolate ? 0 : triggersToCheck.count,
"Violation(s) still triggered when code was nested inside a string literal",
file: (file), line: line
)
}
// Disabled rule doesn't violate and disable command isn't superfluous
for command in disableCommands {
let violationsPartionedByType = triggers
.filter { $0.testDisableCommand }
.map { $0.with(code: command + $0.code) }
.flatMap { makeViolations($0) }
.partitioned { $0.ruleIdentifier == SuperfluousDisableCommandRule.description.identifier }
XCTAssert(violationsPartionedByType.first.isEmpty,
"Violation(s) still triggered although rule was disabled",
file: (file), line: line)
XCTAssert(violationsPartionedByType.second.isEmpty,
"Disable command was superfluous since no violations(s) triggered",
file: (file), line: line)
}
}
func verifyCorrections(_ ruleDescription: RuleDescription, config: Configuration,
disableCommands: [String], testMultiByteOffsets: Bool,
parserDiagnosticsDisabledForTests: Bool = true) {
let ruleDescription = ruleDescription.focused()
SwiftLintFramework.parserDiagnosticsDisabledForTests = parserDiagnosticsDisabledForTests
// corrections
ruleDescription.corrections.forEach {
testCorrection($0, configuration: config, testMultiByteOffsets: testMultiByteOffsets)
}
// make sure strings that don't trigger aren't corrected
ruleDescription.nonTriggeringExamples.forEach {
testCorrection(($0, $0), configuration: config, testMultiByteOffsets: testMultiByteOffsets)
}
// "disable" commands do not correct
ruleDescription.corrections.forEach { before, _ in
for command in disableCommands {
let beforeDisabled = command + before.code
let expectedCleaned = before.with(code: cleanedContentsAndMarkerOffsets(from: beforeDisabled).0)
config.assertCorrection(expectedCleaned, expected: expectedCleaned)
}
}
}
private func verifyExamples(triggers: [Example], nonTriggers: [Example],
configuration config: Configuration, requiresFileOnDisk: Bool,
file callSiteFile: StaticString = #file,
line callSiteLine: UInt = #line) {
// Non-triggering examples don't violate
for nonTrigger in nonTriggers {
let unexpectedViolations = violations(nonTrigger, config: config,
requiresFileOnDisk: requiresFileOnDisk)
if unexpectedViolations.isEmpty { continue }
let nonTriggerWithViolations = render(violations: unexpectedViolations, in: nonTrigger.code)
XCTFail(
"nonTriggeringExample violated: \n\(nonTriggerWithViolations)",
file: nonTrigger.file,
line: nonTrigger.line)
}
// Triggering examples violate
for trigger in triggers {
let triggerViolations = violations(trigger, config: config,
requiresFileOnDisk: requiresFileOnDisk)
// Triggering examples with violation markers violate at the marker's location
let (cleanTrigger, markerOffsets) = cleanedContentsAndMarkerOffsets(from: trigger.code)
if markerOffsets.isEmpty {
if triggerViolations.isEmpty {
XCTFail(
"triggeringExample did not violate: \n```\n\(trigger.code)\n```",
file: trigger.file,
line: trigger.line)
}
continue
}
let file = SwiftLintFile.testFile(withContents: cleanTrigger)
let expectedLocations = markerOffsets.map { Location(file: file, characterOffset: $0) }
// Assert violations on unexpected location
let violationsAtUnexpectedLocation = triggerViolations
.filter { !expectedLocations.contains($0.location) }
if !violationsAtUnexpectedLocation.isEmpty {
XCTFail("triggeringExample violated at unexpected location: \n" +
"\(render(violations: violationsAtUnexpectedLocation, in: cleanTrigger))",
file: trigger.file,
line: trigger.line)
}
// Assert locations missing violation
let violatedLocations = triggerViolations.map { $0.location }
let locationsWithoutViolation = expectedLocations
.filter { !violatedLocations.contains($0) }
if !locationsWithoutViolation.isEmpty {
XCTFail("triggeringExample did not violate at expected location: \n" +
"\(render(locations: locationsWithoutViolation, in: cleanTrigger))",
file: trigger.file,
line: trigger.line)
}
XCTAssertEqual(triggerViolations.count, expectedLocations.count,
file: trigger.file, line: trigger.line)
for (triggerViolation, expectedLocation) in zip(triggerViolations, expectedLocations) {
XCTAssertEqual(
triggerViolation.location, expectedLocation,
"'\(trigger)' violation didn't match expected location.",
file: trigger.file,
line: trigger.line)
}
}
}
// file and line parameters are first so we can use trailing closure syntax with the closure
func checkError<T: Error & Equatable>(
file: StaticString = #file,
line: UInt = #line,
_ error: T,
closure: () throws -> Void) {
do {
try closure()
XCTFail("No error caught", file: (file), line: line)
} catch let rError as T {
if error != rError {
XCTFail("Wrong error caught. Got \(rError) but was expecting \(error)", file: (file), line: line)
}
} catch {
XCTFail("Wrong error caught", file: (file), line: line)
}
}
}
private struct FocusedRuleDescription {
let nonTriggeringExamples: [Example]
let triggeringExamples: [Example]
let corrections: [Example: Example]
init(rule: RuleDescription) {
let nonTriggering = rule.nonTriggeringExamples.filter(\.isFocused)
let triggering = rule.triggeringExamples.filter(\.isFocused)
let corrections = rule.corrections.filter { key, value in key.isFocused || value.isFocused }
let anyFocused = nonTriggering.isNotEmpty || triggering.isNotEmpty || corrections.isNotEmpty
if anyFocused {
self.nonTriggeringExamples = nonTriggering
self.triggeringExamples = triggering
self.corrections = corrections
#if DISABLE_FOCUSED_EXAMPLES
(nonTriggering + triggering + corrections.values).forEach { example in
XCTFail("Focused examples are disabled", file: example.file, line: example.line)
}
#endif
} else {
self.nonTriggeringExamples = rule.nonTriggeringExamples
self.triggeringExamples = rule.triggeringExamples
self.corrections = rule.corrections
}
}
}
private extension RuleDescription {
func focused() -> FocusedRuleDescription {
return FocusedRuleDescription(rule: self)
}
}
|
mit
|
293081ece505600fef41f7ec81da80b8
| 43.500873 | 119 | 0.620495 | 5.112069 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.