repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
slavapestov/swift | test/decl/var/properties.swift | 1 | 28925 | // RUN: %target-parse-verify-swift
func markUsed<T>(t: T) {}
struct X { }
var _x: X
class SomeClass {}
func takeTrailingClosure(fn: () -> ()) -> Int {}
func takeIntTrailingClosure(fn: () -> Int) -> Int {}
//===---
// Stored properties
//===---
var stored_prop_1: Int = 0
var stored_prop_2: Int = takeTrailingClosure {}
//===---
// Computed properties -- basic parsing
//===---
var a1: X {
get {
return _x
}
}
var a2: X {
get {
return _x
}
set {
_x = newValue
}
}
var a3: X {
get {
return _x
}
set(newValue) {
_x = newValue
}
}
var a4: X {
set {
_x = newValue
}
get {
return _x
}
}
var a5: X {
set(newValue) {
_x = newValue
}
get {
return _x
}
}
// Reading/writing properties
func accept_x(x: X) { }
func accept_x_inout(inout x: X) { }
func test_global_properties(x: X) {
accept_x(a1)
accept_x(a2)
accept_x(a3)
accept_x(a4)
accept_x(a5)
a1 = x // expected-error {{cannot assign to value: 'a1' is a get-only property}}
a2 = x
a3 = x
a4 = x
a5 = x
accept_x_inout(&a1) // expected-error {{cannot pass immutable value as inout argument: 'a1' is a get-only property}}
accept_x_inout(&a2)
accept_x_inout(&a3)
accept_x_inout(&a4)
accept_x_inout(&a5)
}
//===--- Implicit 'get'.
var implicitGet1: X {
return _x
}
var implicitGet2: Int {
var zzz = 0
// For the purpose of this test, any other function attribute work as well.
@noreturn
func foo() {}
return 0
}
var implicitGet3: Int {
@noreturn
func foo() {}
return 0
}
// Here we used apply weak to the getter itself, not to the variable.
var x15: Int {
// For the purpose of this test we need to use an attribute that cannot be
// applied to the getter.
weak
var foo: SomeClass? = SomeClass() // expected-warning {{variable 'foo' was written to, but never read}}
return 0
}
// Disambiguated as stored property with a trailing closure in the initializer.
//
// FIXME: QoI could be much better here.
var disambiguateGetSet1a: Int = 0 {
get {} // expected-error {{use of unresolved identifier 'get'}}
}
var disambiguateGetSet1b: Int = 0 {
get { // expected-error {{use of unresolved identifier 'get'}}
return 42
}
}
var disambiguateGetSet1c: Int = 0 {
set {} // expected-error {{use of unresolved identifier 'set'}}
}
var disambiguateGetSet1d: Int = 0 {
set(newValue) {} // expected-error {{use of unresolved identifier 'set'}} expected-error {{use of unresolved identifier 'newValue'}}
}
// Disambiguated as stored property with a trailing closure in the initializer.
func disambiguateGetSet2() {
func get(fn: () -> ()) {}
var a: Int = takeTrailingClosure {
get {}
}
// Check that the property is read-write.
a = a + 42
}
func disambiguateGetSet2Attr() {
func get(fn: () -> ()) {}
var a: Int = takeTrailingClosure {
@noreturn
func foo() {}
get {}
}
// Check that the property is read-write.
a = a + 42
}
// Disambiguated as stored property with a trailing closure in the initializer.
func disambiguateGetSet3() {
func set(fn: () -> ()) {}
var a: Int = takeTrailingClosure {
set {}
}
// Check that the property is read-write.
a = a + 42
}
func disambiguateGetSet3Attr() {
func set(fn: () -> ()) {}
var a: Int = takeTrailingClosure {
@noreturn
func foo() {}
set {}
}
// Check that the property is read-write.
a = a + 42
}
// Disambiguated as stored property with a trailing closure in the initializer.
func disambiguateGetSet4() {
func set(x: Int, fn: () -> ()) {}
let newValue: Int = 0
var a: Int = takeTrailingClosure {
set(newValue) {}
}
// Check that the property is read-write.
a = a + 42
}
func disambiguateGetSet4Attr() {
func set(x: Int, fn: () -> ()) {}
var newValue: Int = 0
var a: Int = takeTrailingClosure {
@noreturn
func foo() {}
set(newValue) {}
}
// Check that the property is read-write.
a = a + 42
}
// Disambiguated as stored property with a trailing closure in the initializer.
var disambiguateImplicitGet1: Int = 0 { // expected-error {{cannot call value of non-function type 'Int'}}
return 42
}
var disambiguateImplicitGet2: Int = takeIntTrailingClosure {
return 42
}
//===---
// Observed properties
//===---
class C {
var prop1 = 42 {
didSet { }
}
var prop2 = false {
willSet { }
}
var prop3: Int? = nil {
didSet { }
}
var prop4: Bool? = nil {
willSet { }
}
}
protocol TrivialInitType {
init()
}
class CT<T : TrivialInitType> {
var prop1 = 42 {
didSet { }
}
var prop2 = false {
willSet { }
}
var prop3: Int? = nil {
didSet { }
}
var prop4: Bool? = nil {
willSet { }
}
var prop5: T? = nil {
didSet { }
}
var prop6: T? = nil {
willSet { }
}
var prop7 = T() {
didSet { }
}
var prop8 = T() {
willSet { }
}
}
//===---
// Parsing problems
//===---
var computed_prop_with_init_1: X {
get {}
} = X() // expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{2-2=;}}
// FIXME: Redundant error below
var x2 { // expected-error{{computed property must have an explicit type}} expected-error{{type annotation missing in pattern}}
get {
return _x
}
}
var (x3): X { // expected-error{{getter/setter can only be defined for a single variable}}
get {
return _x
}
}
var duplicateAccessors1: X {
get { // expected-note {{previous definition of getter is here}}
return _x
}
set { // expected-note {{previous definition of setter is here}}
_x = value
}
get { // expected-error {{duplicate definition of getter}}
return _x
}
set(v) { // expected-error {{duplicate definition of setter}}
_x = v
}
}
var duplicateAccessors2: Int = 0 {
willSet { // expected-note {{previous definition of willSet is here}}
}
didSet { // expected-note {{previous definition of didSet is here}}
}
willSet { // expected-error {{duplicate definition of willSet}}
}
didSet { // expected-error {{duplicate definition of didSet}}
}
}
var extraTokensInAccessorBlock1: X {
get {}
a // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}}
}
var extraTokensInAccessorBlock2: X {
get {}
weak // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}}
a
}
var extraTokensInAccessorBlock3: X {
get {}
a = b // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}}
set {}
get {}
}
var extraTokensInAccessorBlock4: X {
get blah wibble // expected-error{{expected '{' to start getter definition}}
}
var extraTokensInAccessorBlock5: X {
set blah wibble // expected-error{{expected '{' to start setter definition}}
}
var extraTokensInAccessorBlock6: X {
willSet blah wibble // expected-error{{expected '{' to start willSet definition}}
}
var extraTokensInAccessorBlock7: X {
didSet blah wibble // expected-error{{expected '{' to start didSet definition}}
}
var extraTokensInAccessorBlock8: X {
foo // expected-error {{use of unresolved identifier 'foo'}}
get {} // expected-error{{use of unresolved identifier 'get'}}
set {} // expected-error{{use of unresolved identifier 'set'}}
}
var extraTokensInAccessorBlock9: Int {
get // expected-error {{expected '{' to start getter definition}}
var a = b
}
struct extraTokensInAccessorBlock10 {
var x: Int {
get // expected-error {{expected '{' to start getter definition}}
var a = b
}
init() {}
}
var x9: X {
get ( ) { // expected-error{{expected '{' to start getter definition}}
}
}
var x10: X {
set ( : ) { // expected-error{{expected setter parameter name}}
}
get {}
}
var x11 : X {
set { // expected-error{{variable with a setter must also have a getter}}
}
}
var x12: X {
set(newValue %) { // expected-error {{expected ')' after setter parameter name}} expected-note {{to match this opening '('}}
// expected-error@-1 {{expected '{' to start setter definition}}
}
}
var x13: X {} // expected-error {{computed property must have accessors specified}}
// Type checking problems
struct Y { }
var y: Y
var x20: X {
get {
return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}}
}
set {
y = newValue // expected-error{{cannot assign value of type 'X' to type 'Y'}}
}
}
var x21: X {
get {
return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}}
}
set(v) {
y = v // expected-error{{cannot assign value of type 'X' to type 'Y'}}
}
}
var x23: Int, x24: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}}
return 42
}
var x25: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}}
return 42
}, x26: Int
// Properties of struct/enum/extensions
struct S {
var _backed_x: X, _backed_x2: X
var x: X {
get {
return _backed_x
}
mutating
set(v) {
_backed_x = v
}
}
}
extension S {
var x2: X {
get {
return self._backed_x2
}
mutating
set {
_backed_x2 = newValue
}
}
var x3: X {
get {
return self._backed_x2
}
}
}
struct StructWithExtension1 {
var foo: Int
static var fooStatic = 4
}
extension StructWithExtension1 {
var fooExt: Int // expected-error {{extensions may not contain stored properties}}
static var fooExtStatic = 4
}
class ClassWithExtension1 {
var foo: Int = 0
class var fooStatic = 4 // expected-error {{class stored properties not yet supported in classes; did you mean 'static'?}}
}
extension ClassWithExtension1 {
var fooExt: Int // expected-error {{extensions may not contain stored properties}}
class var fooExtStatic = 4 // expected-error {{class stored properties not yet supported in classes; did you mean 'static'?}}
}
enum EnumWithExtension1 {
var foo: Int // expected-error {{enums may not contain stored properties}}
static var fooStatic = 4
}
extension EnumWithExtension1 {
var fooExt: Int // expected-error {{extensions may not contain stored properties}}
static var fooExtStatic = 4
}
protocol ProtocolWithExtension1 {
var foo: Int { get }
static var fooStatic : Int { get }
}
extension ProtocolWithExtension1 {
final var fooExt: Int // expected-error{{extensions may not contain stored properties}}
final static var fooExtStatic = 4 // expected-error{{static stored properties not yet supported in generic types}}
}
func getS() -> S {
let s: S
return s
}
func test_extension_properties(inout s: S, inout x: X) {
accept_x(s.x)
accept_x(s.x2)
accept_x(s.x3)
accept_x(getS().x)
accept_x(getS().x2)
accept_x(getS().x3)
s.x = x
s.x2 = x
s.x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}}
getS().x = x // expected-error{{cannot assign to property: 'getS' returns immutable value}}
getS().x2 = x // expected-error{{cannot assign to property: 'getS' returns immutable value}}
getS().x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}}
accept_x_inout(&getS().x) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}}
accept_x_inout(&getS().x2) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}}
accept_x_inout(&getS().x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}}
x = getS().x
x = getS().x2
x = getS().x3
accept_x_inout(&s.x)
accept_x_inout(&s.x2)
accept_x_inout(&s.x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}}
}
extension S {
mutating
func test(inout other_x: X) {
x = other_x
x2 = other_x
x3 = other_x // expected-error{{cannot assign to property: 'x3' is a get-only property}}
other_x = x
other_x = x2
other_x = x3
}
}
// Accessor on non-settable type
struct Aleph {
var b: Beth {
get {
return Beth(c: 1)
}
}
}
struct Beth {
var c: Int
}
func accept_int_inout(inout c: Int) { }
func accept_int(c: Int) { }
func test_settable_of_nonsettable(a: Aleph) {
a.b.c = 1 // expected-error{{cannot assign}}
let x:Int = a.b.c
_ = x
accept_int(a.b.c)
accept_int_inout(&a.b.c) // expected-error {{cannot pass immutable value as inout argument: 'b' is a get-only property}}
}
// TODO: Static properties are only implemented for nongeneric structs yet.
struct MonoStruct {
static var foo: Int = 0
static var (bar, bas): (String, UnicodeScalar) = ("zero", "0")
static var zim: UInt8 {
return 0
}
static var zang = UnicodeScalar()
static var zung: UInt16 {
get {
return 0
}
set {}
}
var a: Double
var b: Double
}
struct MonoStructOneProperty {
static var foo: Int = 22
}
enum MonoEnum {
static var foo: Int = 0
static var zim: UInt8 {
return 0
}
}
struct GenStruct<T> {
static var foo: Int = 0 // expected-error{{static stored properties not yet supported in generic types}}
}
class MonoClass {
class var foo: Int = 0 // expected-error{{class stored properties not yet supported in classes; did you mean 'static'?}}
}
protocol Proto {
static var foo: Int { get }
}
func staticPropRefs() -> (Int, Int, String, UnicodeScalar, UInt8) {
return (MonoStruct.foo, MonoEnum.foo, MonoStruct.bar, MonoStruct.bas,
MonoStruct.zim)
}
func staticPropRefThroughInstance(foo: MonoStruct) -> Int {
return foo.foo //expected-error{{static member 'foo' cannot be used on instance of type 'MonoStruct'}}
}
func memberwiseInitOnlyTakesInstanceVars() -> MonoStruct {
return MonoStruct(a: 1.2, b: 3.4)
}
func getSetStaticProperties() -> (UInt8, UInt16) {
MonoStruct.zim = 12 // expected-error{{cannot assign}}
MonoStruct.zung = 34
return (MonoStruct.zim, MonoStruct.zung)
}
var selfRefTopLevel: Int {
return selfRefTopLevel // expected-warning {{attempting to access 'selfRefTopLevel' within its own getter}}
}
var selfRefTopLevelSetter: Int {
get {
return 42
}
set {
markUsed(selfRefTopLevelSetter) // no-warning
selfRefTopLevelSetter = newValue // expected-warning {{attempting to modify 'selfRefTopLevelSetter' within its own setter}}
}
}
var selfRefTopLevelSilenced: Int {
get {
return properties.selfRefTopLevelSilenced // no-warning
}
set {
properties.selfRefTopLevelSilenced = newValue // no-warning
}
}
class SelfRefProperties {
var getter: Int {
return getter // expected-warning {{attempting to access 'getter' within its own getter}}
// expected-note@-1 {{access 'self' explicitly to silence this warning}} {{12-12=self.}}
}
var setter: Int {
get {
return 42
}
set {
markUsed(setter) // no-warning
var unused = setter + setter // expected-warning {{initialization of variable 'unused' was never used; consider replacing with assignment to '_' or removing it}} {{7-17=_}}
setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}}
// expected-note@-1 {{access 'self' explicitly to silence this warning}} {{7-7=self.}}
}
}
var silenced: Int {
get {
return self.silenced // no-warning
}
set {
self.silenced = newValue // no-warning
}
}
var someOtherInstance: SelfRefProperties = SelfRefProperties()
var delegatingVar: Int {
// This particular example causes infinite access, but it's easily possible
// for the delegating instance to do something else.
return someOtherInstance.delegatingVar // no-warning
}
}
func selfRefLocal() {
var getter: Int {
return getter // expected-warning {{attempting to access 'getter' within its own getter}}
}
var setter: Int {
get {
return 42
}
set {
markUsed(setter) // no-warning
setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}}
}
}
}
struct WillSetDidSetProperties {
var a: Int {
willSet {
markUsed("almost")
}
didSet {
markUsed("here")
}
}
var b: Int {
willSet {
markUsed(b)
markUsed(newValue)
}
}
var c: Int {
willSet(newC) {
markUsed(c)
markUsed(newC)
}
}
var d: Int {
didSet {
markUsed("woot")
}
get { // expected-error {{didSet variable may not also have a get specifier}}
return 4
}
}
var e: Int {
willSet {
markUsed("woot")
}
set { // expected-error {{willSet variable may not also have a set specifier}}
return 4
}
}
var f: Int {
willSet(5) {} // expected-error {{expected willSet parameter name}}
didSet(^) {} // expected-error {{expected didSet parameter name}}
}
var g: Int {
willSet(newValue 5) {} // expected-error {{expected ')' after willSet parameter name}} expected-note {{to match this opening '('}}
// expected-error@-1 {{expected '{' to start willSet definition}}
}
var h: Int {
didSet(oldValue ^) {} // expected-error {{expected ')' after didSet parameter name}} expected-note {{to match this opening '('}}
// expected-error@-1 {{expected '{' to start didSet definition}}
}
// didSet/willSet with initializers.
// Disambiguate trailing closures.
var disambiguate1: Int = 42 { // simple initializer, simple label
didSet {
markUsed("eek")
}
}
var disambiguate2: Int = 42 { // simple initializer, complex label
willSet(v) {
markUsed("eek")
}
}
var disambiguate3: Int = takeTrailingClosure {} { // Trailing closure case.
willSet(v) {
markUsed("eek")
}
}
var disambiguate4: Int = 42 {
willSet {}
}
var disambiguate5: Int = 42 {
didSet {}
}
var disambiguate6: Int = takeTrailingClosure {
@noreturn
func f() {}
return ()
}
var inferred1 = 42 {
willSet {
markUsed("almost")
}
didSet {
markUsed("here")
}
}
var inferred2 = 40 {
willSet {
markUsed(b)
markUsed(newValue)
}
}
var inferred3 = 50 {
willSet(newC) {
markUsed(c)
markUsed(newC)
}
}
}
// Disambiguated as accessor.
struct WillSetDidSetDisambiguate1 {
var willSet: Int
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet = 42 // expected-error {{expected '{' to start willSet definition}}
}
}
struct WillSetDidSetDisambiguate1Attr {
var willSet: Int
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet = 42 // expected-error {{expected '{' to start willSet definition}}
}
}
// Disambiguated as accessor.
struct WillSetDidSetDisambiguate2 {
func willSet(_: () -> Int) {}
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet {}
}
}
struct WillSetDidSetDisambiguate2Attr {
func willSet(_: () -> Int) {}
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet {}
}
}
// No need to disambiguate -- this is clearly a function call.
func willSet(_: () -> Int) {}
struct WillSetDidSetDisambiguate3 {
var x: Int = takeTrailingClosure({
willSet { 42 }
})
}
protocol ProtocolGetSet1 {
var a: Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
}
protocol ProtocolGetSet2 {
var a: Int {} // expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
}
protocol ProtocolGetSet3 {
var a: Int { get }
}
protocol ProtocolGetSet4 {
var a: Int { set } // expected-error {{variable with a setter must also have a getter}}
}
protocol ProtocolGetSet5 {
var a: Int { get set }
}
protocol ProtocolGetSet6 {
var a: Int { set get }
}
protocol ProtocolWillSetDidSet1 {
var a: Int { willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet2 {
var a: Int { didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet3 {
var a: Int { willSet didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet4 {
var a: Int { didSet willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}}
}
var globalDidsetWillSet: Int { // expected-error {{non-member observing properties require an initializer}}
didSet {}
}
var globalDidsetWillSet2 : Int = 42 {
didSet {}
}
class Box {
var num: Int
init(num: Int) {
self.num = num
}
}
func double(inout val: Int) {
val *= 2
}
class ObservingPropertiesNotMutableInWillSet {
var anotherObj : ObservingPropertiesNotMutableInWillSet
init() {}
var property: Int = 42 {
willSet {
// <rdar://problem/16826319> willSet immutability behavior is incorrect
anotherObj.property = 19 // ok
property = 19 // expected-warning {{attempting to store to property 'property' within its own willSet}}
double(&property) // expected-warning {{attempting to store to property 'property' within its own willSet}}
double(&self.property) // no-warning
}
}
// <rdar://problem/21392221> - call to getter through BindOptionalExpr was not viewed as a load
var _oldBox : Int
weak var weakProperty: Box? {
willSet {
_oldBox = weakProperty?.num ?? -1
}
}
func localCase() {
var localProperty: Int = 42 {
willSet {
localProperty = 19 // expected-warning {{attempting to store to property 'localProperty' within its own willSet}}
}
}
}
}
func doLater(fn : () -> ()) {}
// rdar://<rdar://problem/16264989> property not mutable in closure inside of its willSet
class MutableInWillSetInClosureClass {
var bounds: Int = 0 {
willSet {
let oldBounds = bounds
doLater { self.bounds = oldBounds }
}
}
}
// <rdar://problem/16191398> add an 'oldValue' to didSet so you can implement "didChange" properties
var didSetPropertyTakingOldValue : Int = 0 {
didSet(oldValue) {
markUsed(oldValue)
markUsed(didSetPropertyTakingOldValue)
}
}
// rdar://16280138 - synthesized getter is defined in terms of archetypes, not interface types
protocol AbstractPropertyProtocol {
associatedtype Index
var a : Index { get }
}
struct AbstractPropertyStruct<T> : AbstractPropertyProtocol {
typealias Index = T
var a : T
}
// Allow _silgen_name accessors without bodies.
var _silgen_nameGet1: Int {
@_silgen_name("get1") get
set { }
}
var _silgen_nameGet2: Int {
set { }
@_silgen_name("get2") get
}
var _silgen_nameGet3: Int {
@_silgen_name("get3") get
}
var _silgen_nameGetSet: Int {
@_silgen_name("get4") get
@_silgen_name("set4") set
}
// <rdar://problem/16375910> reject observing properties overriding readonly properties
class Base16375910 {
var x : Int { // expected-note {{attempt to override property here}}
return 42
}
var y : Int { // expected-note {{attempt to override property here}}
get { return 4 }
set {}
}
}
class Derived16375910 : Base16375910 {
override init() {}
override var x : Int { // expected-error {{cannot observe read-only property 'x'; it can't change}}
willSet {
markUsed(newValue)
}
}
}
// <rdar://problem/16382967> Observing properties have no storage, so shouldn't prevent initializer synth
class Derived16382967 : Base16375910 {
override var y : Int {
willSet {
markUsed(newValue)
}
}
}
// <rdar://problem/16659058> Read-write properties can be made read-only in a property override
class Derived16659058 : Base16375910 {
override var y : Int { // expected-error {{cannot override mutable property with read-only property 'y'}}
get { return 42 }
}
}
// <rdar://problem/16406886> Observing properties don't work with ownership types
struct PropertiesWithOwnershipTypes {
unowned var p1 : SomeClass {
didSet {
}
}
init(res: SomeClass) {
p1 = res
}
}
// <rdar://problem/16608609> Assert (and incorrect error message) when defining a constant stored property with observers
class Test16608609 {
let constantStored: Int = 0 { // expected-error {{'let' declarations cannot be observing properties}}
willSet {
}
didSet {
}
}
}
// <rdar://problem/16941124> Overriding property observers warn about using the property value "within its own getter"
class rdar16941124Base {
var x = 0
}
class rdar16941124Derived : rdar16941124Base {
var y = 0
override var x: Int {
didSet {
y = x + 1 // no warning.
}
}
}
// Overrides of properties with custom ownership.
class OwnershipBase {
class var defaultObject: AnyObject { fatalError("") }
var strongVar: AnyObject? // expected-note{{overridden declaration is here}}
weak var weakVar: AnyObject?
// FIXME: These should be optional to properly test overriding.
unowned var unownedVar: AnyObject = defaultObject
unowned(unsafe) var unownedUnsafeVar: AnyObject = defaultObject // expected-note{{overridden declaration is here}}
}
class OwnershipExplicitSub : OwnershipBase {
override var strongVar: AnyObject? {
didSet {}
}
override weak var weakVar: AnyObject? {
didSet {}
}
override unowned var unownedVar: AnyObject {
didSet {}
}
override unowned(unsafe) var unownedUnsafeVar: AnyObject {
didSet {}
}
}
class OwnershipImplicitSub : OwnershipBase {
override var strongVar: AnyObject? {
didSet {}
}
override weak var weakVar: AnyObject? {
didSet {}
}
override unowned var unownedVar: AnyObject {
didSet {}
}
override unowned(unsafe) var unownedUnsafeVar: AnyObject {
didSet {}
}
}
class OwnershipBadSub : OwnershipBase {
override weak var strongVar: AnyObject? { // expected-error {{cannot override strong property with weak property}}
didSet {}
}
override unowned var weakVar: AnyObject? { // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'AnyObject?'}}
didSet {}
}
override weak var unownedVar: AnyObject { // expected-error {{'weak' variable should have optional type 'AnyObject?'}}
didSet {}
}
override unowned var unownedUnsafeVar: AnyObject { // expected-error {{cannot override unowned(unsafe) property with unowned property}}
didSet {}
}
}
// <rdar://problem/17391625> Swift Compiler Crashes when Declaring a Variable and didSet in an Extension
class rdar17391625 {
var prop = 42 // expected-note {{overridden declaration is here}}
}
extension rdar17391625 {
var someStoredVar: Int // expected-error {{extensions may not contain stored properties}}
var someObservedVar: Int { // expected-error {{extensions may not contain stored properties}}
didSet {
}
}
}
class rdar17391625derived : rdar17391625 {
}
extension rdar17391625derived {
// Not a stored property, computed because it is an override.
override var prop: Int { // expected-error {{declarations in extensions cannot override yet}}
didSet {
}
}
}
// <rdar://problem/19874152> struct memberwise initializer violates new sanctity of previously set `let` property
struct r19874152S1 {
let number : Int = 42
}
_ = r19874152S1(number:64) // expected-error {{argument passed to call that takes no arguments}}
_ = r19874152S1() // Ok
struct r19874152S2 {
var number : Int = 42
}
_ = r19874152S2(number:64) // Ok, property is a var.
_ = r19874152S2() // Ok
struct r19874152S3 {
let number : Int = 42
let flavour : Int
}
_ = r19874152S3(number:64) // expected-error {{incorrect argument label in call (have 'number:', expected 'flavour:')}} {{17-23=flavour}}
_ = r19874152S3(number:64, flavour: 17) // expected-error {{extra argument 'number' in call}}
_ = r19874152S3(flavour: 17) // ok
_ = r19874152S3() // expected-error {{missing argument for parameter 'flavour' in call}}
struct r19874152S4 {
let number : Int? = nil
}
_ = r19874152S4(number:64) // expected-error {{argument passed to call that takes no arguments}}
_ = r19874152S4() // Ok
struct r19874152S5 {
}
_ = r19874152S5() // ok
struct r19874152S6 {
let (a,b) = (1,2) // Cannot handle implicit synth of this yet.
}
_ = r19874152S5() // ok
// <rdar://problem/24314506> QoI: Fix-it for dictionary initializer on required class var suggests [] instead of [:]
class r24314506 { // expected-error {{class 'r24314506' has no initializers}}
var myDict: [String: AnyObject] // expected-note {{stored property 'myDict' without initial value prevents synthesized initializers}} {{34-34= = [:]}}
}
| apache-2.0 | 298da64e6ad99e54e989f45b95716e36 | 23.450549 | 188 | 0.655592 | 3.748218 | false | false | false | false |
Erickson0806/AdaptivePhotos | AdaptivePhotosUsingUIKitTraitsandSizeClasses/AdaptiveCode/AdaptiveCode/AboutViewController.swift | 1 | 3889 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that shows text about this app, using readable margins.
*/
import UIKit
class AboutViewController: UIViewController {
// MARK: Properties
var headlineLabel: UILabel?
var label: UILabel?
// MARK: View Controller
override func loadView() {
let view = UIView()
view.backgroundColor = UIColor.whiteColor()
let headlineLabel = UILabel()
headlineLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
headlineLabel.numberOfLines = 1
headlineLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(headlineLabel)
self.headlineLabel = headlineLabel
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
label.numberOfLines = 0
if let url = NSBundle.mainBundle().URLForResource("Text", withExtension: "txt") {
do {
let text = try String(contentsOfURL: url, usedEncoding: nil)
label.text = text
} catch let error {
print("Error loading text: \(error)")
}
}
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
self.label = label
self.view = view
var constraints = [NSLayoutConstraint]()
let viewsAndGuides: [String: AnyObject] = [
"topLayoutGuide": topLayoutGuide,
"bottomLayoutGuide": bottomLayoutGuide,
"headlineLabel": headlineLabel,
"label": label
]
// Position our labels in the center, respecting the readableContentGuide if it is available
constraints += NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide]-[headlineLabel]-[label]-[bottomLayoutGuide]|", options: [], metrics: nil, views: viewsAndGuides)
if #available(iOS 9.0, *) {
// Use `readableContentGuide` on iOS 9.
let readableContentGuide = view.readableContentGuide
constraints += [
label.leadingAnchor.constraintEqualToAnchor(readableContentGuide.leadingAnchor),
label.trailingAnchor.constraintEqualToAnchor(readableContentGuide.trailingAnchor),
headlineLabel.leadingAnchor.constraintEqualToAnchor(readableContentGuide.leadingAnchor),
headlineLabel.trailingAnchor.constraintEqualToAnchor(readableContentGuide.trailingAnchor)
]
}
else {
// Fallback on earlier versions.
constraints += NSLayoutConstraint.constraintsWithVisualFormat("20-[label]-20|", options: [], metrics:nil, views: viewsAndGuides)
constraints += NSLayoutConstraint.constraintsWithVisualFormat("20-[headlineLabel]-20|", options: [], metrics:nil, views: viewsAndGuides)
}
NSLayoutConstraint.activateConstraints(constraints)
updateLabelsForTraitCollection(traitCollection)
}
// MARK: Transition
override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator:coordinator)
updateLabelsForTraitCollection(newCollection)
}
private func updateLabelsForTraitCollection(collection: UITraitCollection) {
if collection.horizontalSizeClass == .Regular {
headlineLabel?.text = "Regular Width"
}
else {
headlineLabel?.text = "Compact Width"
}
}
}
| apache-2.0 | 2ce09323cea65e05a5d4f33c887adff4 | 38.262626 | 186 | 0.6478 | 6.111635 | false | false | false | false |
LYM-mg/DemoTest | 其他功能/SwiftyDemo/SwiftyDemo/Extesion/Category(扩展)/CALayer+Extension.swift | 3 | 701 | //
// CALayer+Extension.swift
// MGDS_Swift
//
// Created by i-Techsys.com on 17/3/2.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
extension CALayer {
// 动画的暂停
func pauseAnimate() {
let pausedTime = self.convertTime(CACurrentMediaTime(), from: nil)
self.speed = 0.0;
self.timeOffset = pausedTime
}
// 动画的恢复
func resumeAnimate() {
let pausedTime = self.timeOffset
self.speed = 1.0;
self.timeOffset = 0.0;
self.beginTime = 0.0;
let timeSincePause = self.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
self.beginTime = timeSincePause;
}
}
| mit | 9b1ef50168d440158b8b752b824e3203 | 23.214286 | 91 | 0.613569 | 3.852273 | false | false | false | false |
xixijiushui/douyu | douyu/douyu/Classes/Main/View/PageTitleView.swift | 1 | 6182 | //
// PageTitleView.swift
// douyu
//
// Created by 赵伟 on 2016/11/7.
// Copyright © 2016年 赵伟. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate : NSObjectProtocol {
func pageTitleView(titleView : PageTitleView, selectedIndex index : Int)
}
// MARK:- 定义常量
private let kScrollLineH : CGFloat = 2
private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85)
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
class PageTitleView: UIView {
//MARK:- 属性
private var isScrollEnabled : Bool = false
private var titles : [String]
private var currentIndex = 0
weak var delegate : PageTitleViewDelegate?
//MARK:- 懒加载
private lazy var titleLabels : [UILabel] = [UILabel]()
private lazy var scrollView : UIScrollView = {
let scrollView : UIScrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
private lazy var scrollLine : UIView = {
let scrollLine : UIView = UIView()
scrollLine.backgroundColor = UIColor.orangeColor()
return scrollLine
}()
init(frame: CGRect, isScrollEnabled: Bool, titles: [String]) {
self.isScrollEnabled = isScrollEnabled
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:- 设置UI
extension PageTitleView {
private func setupUI() {
//1.添加scrollView
addSubview(scrollView)
scrollView.frame = bounds
//2.添加对应的label
setupTitleLabels()
//3.设置底线和滚动的滑块
setupBottomlineAndScrollline()
}
private func setupTitleLabels() {
//计算label的大小
let labelW = frame.width / CGFloat(titles.count)
let labelH = frame.height - kScrollLineH
let labelY : CGFloat = 0
for (index, title) in titles.enumerate() {
//创建label
let label = UILabel()
label.text = title
label.tag = index
label.font = UIFont.systemFontOfSize(16)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.textAlignment = .Center
let labelX : CGFloat = labelW * CGFloat(index)
label.frame = CGRectMake(labelX, labelY, labelW, labelH)
//添加label
scrollView.addSubview(label)
titleLabels.append(label)
//添加手势
label.userInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(PageTitleView.titleLabelClick(_:)))
label.addGestureRecognizer(tapGes)
}
}
private func setupBottomlineAndScrollline() {
// 1.添加底线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGrayColor()
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
// 2.添加scrollLine
// 2.1.获取第一个Label
guard let firstLabel = titleLabels.first else { return }
firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
// 2.2.设置scrollLine的属性
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH)
}
}
//MARK:- 监听label的点击
extension PageTitleView {
@objc private func titleLabelClick(tapGes : UITapGestureRecognizer) {
//获取当前点击的view
guard let currentLabel = tapGes.view as? UILabel else { return }
//判断是否重复点击
if currentLabel.tag == currentIndex { return }
// 2.获取之前的Label
let oldLabel = titleLabels[currentIndex]
//切换文字颜色
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
//保存位置值
currentIndex = currentLabel.tag
//滚动滚动条
let scrollLineX = CGFloat(currentIndex) * scrollLine.frame.width
UIView.animateWithDuration(0.15) {
self.scrollLine.frame.origin.x = scrollLineX
}
delegate?.pageTitleView(self, selectedIndex: currentIndex)
}
}
//MARK:- 暴露的方法(改变scrollLine的x)
extension PageTitleView {
func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) {
// 取出sourceLabel/targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
// 处理滑块的逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
// 3.颜色的渐变(复杂)
// 3.1.取出变化的范围
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
// 3.2.变化sourceLabel
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
// 3.2.变化targetLabel
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
// 4.记录最新的index
currentIndex = targetIndex
}
}
| mit | 87493650dc244cfc2934a05041b105aa | 30.524064 | 174 | 0.619508 | 4.761712 | false | false | false | false |
lixiangzhou/ZZKG | ZZKG/ZZKG/Classes/Lib/ZZLib/ZZExtension/ZZUIExtension/UITableView+ZZExtension.swift | 1 | 11261 | //
// UITableView+ZZExtension.swift
// ZZLib
//
// Created by lixiangzhou on 2017/4/4.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
/// cell 拖动的代理
protocol ZZTableViewMovableCellDelegate: NSObjectProtocol {
func zz_tableViewStartMoveWithOriginData(_ tableView: UITableView) -> [Any]
func zz_tableView(_ tableView: UITableView, didMoveWith newData: [Any])
}
extension UITableView {
/// 开启 cell 拖动功能
///
/// - Parameters:
/// - tag: cell 中可以拖动的View的 tag, 0 时则整个cell拖动
/// - pressTime: 触发拖动的最小时间
/// - movableDelegate: 拖动时的代理方法
/// - edgeScrollSpeed: 到达边界时滚动的速度,0 时不滚动
func zz_movableCell(withMovableViewTag tag: Int = 0, pressTime: TimeInterval, movableDelegate: ZZTableViewMovableCellDelegate, edgeScrollSpeed: Double = 0) {
self.movableViewTag = tag
movableLongPressGesture.minimumPressDuration = pressTime
movableLongPressGesture.delegate = self
self.movableDelegate = movableDelegate
edgeScrollDirection = .top
self.edgeScrollSpeed = edgeScrollSpeed > 0 ? edgeScrollSpeed : 0
addGestureRecognizer(movableLongPressGesture)
}
/// 取消拖动功能
func zz_disableMovableCell() {
removeGestureRecognizer(movableLongPressGesture)
}
}
extension UITableView: UIGestureRecognizerDelegate {
// MARK: 监听
func gestureProcess(gesture: UILongPressGestureRecognizer) {
let point = gesture.location(in: self)
// 如果超出了范围,就取消返回
guard let indexPath = indexPathForRow(at: point), isInMovableScrope else {
cancelOperation()
return
}
switch gesture.state {
case .began:
if let cell = cellForRow(at: indexPath) {
startCellSnap = UIImageView(frame: cell.frame)
startCellSnap.layer.masksToBounds = true
startCellSnap.image = cell.zz_snapshotImage()
startCellSnap.layer.shadowOffset = CGSize(width: 5, height: 5)
startCellSnap.layer.shadowRadius = 5
addSubview(startCellSnap)
cell.isHidden = true
UIView.animate(withDuration: 0.25, animations: {
self.startCellSnap.center.y = point.y
})
startIndexPath = indexPath
}
case .changed:
startCellSnap.center.y = point.y
if shouldEdgeScroll {
startEdgeScrollTimer()
} else {
stopEdgeScrollTimer()
}
if indexPath != startIndexPath {
exchangeIndexData(indexPath: indexPath)
}
default:
cancelOperation()
}
}
// MARK: UIGestureRecognizerDelegate
override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == movableLongPressGesture {
return isInMovableScrope
} else {
return super.gestureRecognizerShouldBegin(gestureRecognizer)
}
}
// MARK: 辅助
fileprivate enum EndgeScrollDirection {
case top, bottom
}
/// 是否在tag view 所在的范围
private var isInMovableScrope: Bool {
let point = movableLongPressGesture.location(in: self)
if let indexPath = indexPathForRow(at: point),
let cell = cellForRow(at: indexPath),
let tagView = cell.viewWithTag(self.movableViewTag) {
let tagFrame = cell == tagView ? cell.frame : cell.convert(tagView.frame, to: self)
return tagFrame.contains(point)
} else {
return false
}
}
/// 拖动时的数据处理
private func exchangeIndexData(indexPath: IndexPath) {
guard
let numberOfSections = dataSource?.numberOfSections!(in: self),
var originData = movableDelegate?.zz_tableViewStartMoveWithOriginData(self) else {
return
}
if numberOfSections > 1 {
// 同一组
if startIndexPath.section == indexPath.section,
var sectionData = originData[startIndexPath.section] as? [Any]
{
swap(§ionData[startIndexPath.row], §ionData[indexPath.row])
originData[startIndexPath.section] = sectionData
} else { // 不同组
guard // 获取cell上的数据
var originSectionData = originData[startIndexPath.section] as? [Any],
var currentSectionData = originData[indexPath.section] as? [Any] else {
return
}
let currentIndexData = currentSectionData[indexPath.row]
let originIndexData = originSectionData[startIndexPath.row]
// 交互数据
originSectionData[startIndexPath.row] = currentIndexData
currentSectionData[indexPath.row] = originIndexData
// 更新数据
originData[startIndexPath.section] = originSectionData
originData[indexPath.section] = currentSectionData
}
} else { // 只有一组
swap(&originData[startIndexPath.row], &originData[indexPath.row])
}
movableDelegate?.zz_tableView(self, didMoveWith: originData)
beginUpdates()
moveRow(at: startIndexPath, to: indexPath)
moveRow(at: indexPath, to: startIndexPath)
endUpdates()
startIndexPath = indexPath
}
/// 取消操作
private func cancelOperation() {
startCellSnap?.removeFromSuperview()
stopEdgeScrollTimer()
if
let startIndexPath = startIndexPath,
let cell = cellForRow(at: startIndexPath) {
cell.isHidden = false
}
}
/// 开启边界滚动
private func startEdgeScrollTimer() {
if timer == nil {
timer = CADisplayLink(target: self, selector: #selector(edgeScroll))
timer.add(to: RunLoop.main, forMode: .commonModes)
}
}
/// 停止边界滚动
private func stopEdgeScrollTimer() {
timer?.invalidate()
timer = nil
}
/// 在边界自动滚动
@objc private func edgeScroll() {
let factor: CGFloat = 1.5
switch edgeScrollDirection {
case .top:
if contentOffset.y > 0 {
contentOffset.y -= factor
startCellSnap.center.y -= factor
}
case .bottom:
if contentOffset.y + bounds.height < contentSize.height {
contentOffset.y += factor
startCellSnap.center.y += factor
}
}
// 防止边界自动滚动时没有自动更新界面和数据的问题
if let indexPath = indexPathForRow(at: startCellSnap.center), indexPath != startIndexPath {
exchangeIndexData(indexPath: indexPath)
}
}
/// 是否可以在边界滚动
private var shouldEdgeScroll: Bool {
if edgeScrollSpeed <= 0 {
return false
}
if startCellSnap.frame.minY < contentOffset.y {
edgeScrollDirection = .top
return true
}
if startCellSnap.frame.maxY > frame.height + contentOffset.y {
edgeScrollDirection = .bottom
return true
}
return false
}
}
// MARK: - 拖动属性 key
private var longPressGestureKey: Void?
private var startCellSnapKey: Void?
private var startIndexPathKey: Void?
private var edgeScrollDirectionKey: Void?
private var timerKey: Void?
private var movableDelegateKey: Void?
private var edgeScrollSpeedKey: Void?
private var movableViewTagKey: Void?
extension UITableView {
/// 拖动长按手势
fileprivate var movableLongPressGesture: UILongPressGestureRecognizer {
get {
var longPressGesture = objc_getAssociatedObject(self, &longPressGestureKey) as? UILongPressGestureRecognizer
if longPressGesture == nil {
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(gestureProcess))
objc_setAssociatedObject(self, &longPressGestureKey, longPressGesture, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return longPressGesture!
}
}
/// 开始拖动时cell的快照
fileprivate var startCellSnap: UIImageView! {
set {
objc_setAssociatedObject(self, &startCellSnapKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &startCellSnapKey) as! UIImageView
}
}
/// 开始拖动的IndexPath
fileprivate var startIndexPath: IndexPath! {
set {
objc_setAssociatedObject(self, &startIndexPathKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &startIndexPathKey) as! IndexPath
}
}
/// 拖动方向
fileprivate var edgeScrollDirection: EndgeScrollDirection {
set {
objc_setAssociatedObject(self, &edgeScrollDirectionKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &edgeScrollDirectionKey) as! EndgeScrollDirection
}
}
/// 自动滚动定时器
fileprivate var timer: CADisplayLink! {
set {
objc_setAssociatedObject(self, &timerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &timerKey) as? CADisplayLink
}
}
/// 拖动代理
fileprivate weak var movableDelegate: ZZTableViewMovableCellDelegate! {
set {
objc_setAssociatedObject(self, &movableDelegateKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
get {
return objc_getAssociatedObject(self, &movableDelegateKey) as! ZZTableViewMovableCellDelegate
}
}
/// 边界滚动速度
fileprivate var edgeScrollSpeed: Double {
set {
objc_setAssociatedObject(self, &edgeScrollSpeedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &edgeScrollSpeedKey) as! Double
}
}
/// cell 中可以拖动的View的 tag, 0 时则整个cell拖动
fileprivate var movableViewTag: Int {
set {
objc_setAssociatedObject(self, &movableViewTagKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &movableViewTagKey) as! Int
}
}
}
| mit | 42e16df8169cd01bb4952cd214e1c8f4 | 31.130952 | 161 | 0.592164 | 4.984303 | false | false | false | false |
kdw9/TIY-Assignments | In_Due_Time/In_Due_Time/AppDelegate.swift | 1 | 6102 | //
// AppDelegate.swift
// In_Due_Time
//
// Created by Keron Williams on 10/20/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// 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.tiy.In_Due_Time" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("In_Due_Time", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns 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
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.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
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// 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.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| cc0-1.0 | 2979ae9961ca3fd4e78ba65941d9b8d1 | 53.963964 | 291 | 0.718735 | 5.84387 | false | false | false | false |
goktugyil/EZSwiftExtensions | Sources/BlockButton.swift | 1 | 3450 | //
// BlockButton.swift
//
//
// Created by Cem Olcay on 12/08/15.
//
//
#if os(iOS) || os(tvOS)
import UIKit
public typealias BlockButtonAction = (_ sender: BlockButton) -> Void
///Make sure you use "[weak self] (sender) in" if you are using the keyword self inside the closure or there might be a memory leak
open class BlockButton: UIButton {
// MARK: Propeties
open var highlightLayer: CALayer?
open var action: BlockButtonAction?
// MARK: Init
public init() {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
defaultInit()
}
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
super.init(frame: CGRect(x: x, y: y, width: w, height: h))
defaultInit()
}
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, action: BlockButtonAction?) {
super.init (frame: CGRect(x: x, y: y, width: w, height: h))
self.action = action
defaultInit()
}
public init(action: @escaping BlockButtonAction) {
super.init(frame: CGRect.zero)
self.action = action
defaultInit()
}
public override init(frame: CGRect) {
super.init(frame: frame)
defaultInit()
}
public init(frame: CGRect, action: @escaping BlockButtonAction) {
super.init(frame: frame)
self.action = action
defaultInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
defaultInit()
}
private func defaultInit() {
addTarget(self, action: #selector(BlockButton.didPressed(_:)), for: UIControlEvents.touchUpInside)
addTarget(self, action: #selector(BlockButton.highlight), for: [UIControlEvents.touchDown, UIControlEvents.touchDragEnter])
addTarget(self, action: #selector(BlockButton.unhighlight), for: [
UIControlEvents.touchUpInside,
UIControlEvents.touchUpOutside,
UIControlEvents.touchCancel,
UIControlEvents.touchDragExit
])
setTitleColor(UIColor.black, for: UIControlState.normal)
setTitleColor(UIColor.blue, for: UIControlState.selected)
}
open func addAction(_ action: @escaping BlockButtonAction) {
self.action = action
}
// MARK: Action
@objc open func didPressed(_ sender: BlockButton) {
action?(sender)
}
// MARK: Highlight
@objc open func highlight() {
if action == nil {
return
}
let highlightLayer = CALayer()
highlightLayer.frame = layer.bounds
highlightLayer.backgroundColor = UIColor.black.cgColor
highlightLayer.opacity = 0.5
var maskImage: UIImage? = nil
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, 0)
if let context = UIGraphicsGetCurrentContext() {
layer.render(in: context)
maskImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
let maskLayer = CALayer()
maskLayer.contents = maskImage?.cgImage
maskLayer.frame = highlightLayer.frame
highlightLayer.mask = maskLayer
layer.addSublayer(highlightLayer)
self.highlightLayer = highlightLayer
}
@objc open func unhighlight() {
if action == nil {
return
}
highlightLayer?.removeFromSuperlayer()
highlightLayer = nil
}
}
#endif
| mit | 413476eb9a5644746ecbb0970f58e570 | 27.991597 | 132 | 0.628986 | 4.545455 | false | false | false | false |
KellenYangs/KLSwiftTest_05_05 | VC跳转/VC跳转/CustomPresentAnimationController.swift | 1 | 1590 | //
// CustomPresentAnimationController.swift
// VC跳转
//
// Created by bcmac3 on 16/5/30.
// Copyright © 2016年 KellenYangs. All rights reserved.
//
import UIKit
class CustomPresentAnimationController: NSObject {
}
// MARK: -- UIViewControllerAnimatedTransitioning
extension CustomPresentAnimationController: UIViewControllerAnimatedTransitioning {
/** 动画时长 */
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 2.5
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
let finalFrameForVC = transitionContext.finalFrameForViewController(toVC)
let containerView = transitionContext.containerView()
let bounds = UIScreen.mainScreen().bounds
toVC.view.frame = CGRectOffset(finalFrameForVC, 0, -bounds.size.height)
containerView?.addSubview(toVC.view)
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: .CurveLinear, animations: {
fromVC.view.alpha = 0.5
toVC.view.frame = finalFrameForVC
}) { (finished) in
transitionContext.completeTransition(true)
fromVC.view.alpha = 1.0
}
}
}
| mit | d51bd4cb12279c8ef62c5aee9486283a | 34.795455 | 180 | 0.704127 | 5.706522 | false | false | false | false |
6ag/WeiboSwift-mvvm | WeiboSwift/Classes/Utils/RefreshControl/JFRefreshView.swift | 1 | 2187 | //
// JFRefreshView.swift
// tableviewTest
//
// Created by zhoujianfeng on 2017/1/24.
// Copyright © 2017年 zhoujianfeng. All rights reserved.
//
import UIKit
class JFRefreshView: UIView {
/// 指示器
@IBOutlet weak var indicatorView: UIActivityIndicatorView!
/// 箭头图标
@IBOutlet weak var arrowIconView: UIImageView!
/// 刷新文本
@IBOutlet weak var refreshLabel: UILabel!
/// 刷新状态
var refreshState = JFRefreshState.normal {
didSet {
switch refreshState {
case .normal:
// 恢复状态
indicatorView.stopAnimating()
arrowIconView.isHidden = false
refreshLabel.text = "下拉刷新"
UIView.animate(withDuration: 0.25, animations: {
self.arrowIconView.transform = CGAffineTransform.identity
})
case .pulling:
refreshLabel.text = "释放更新"
UIView.animate(withDuration: 0.25, animations: {
self.arrowIconView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
})
case .willRefresh:
refreshLabel.text = "加载中..."
arrowIconView.isHidden = true
indicatorView.startAnimating()
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
refreshLabel.text = "下拉刷新"
}
/// 创建刷新视图
///
/// - Returns: 刷新视图
class func refreshView() -> JFRefreshView {
let nib = UINib(nibName: "JFRefreshView", bundle: nil)
return nib.instantiate(withOwner: nil, options: nil)[0] as! JFRefreshView
}
/// 将要添加到父控件时,将背景颜色和父控件背景颜色统一
///
/// - Parameter newSuperview: 新的父控件
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
guard let newSuperview = newSuperview else { return }
backgroundColor = newSuperview.backgroundColor
}
}
| mit | 3e0c46070b8be76b6f5514ec86a4e958 | 27.676056 | 98 | 0.570236 | 4.977995 | false | false | false | false |
abiaoLHB/LHBWeiBo-Swift | LHBWeibo/LHBWeibo/MainWibo/Tools/Emoticon/EmioticonViewCell.swift | 1 | 1584 | //
// EmioticonViewCell.swift
// 到处enmoci
//
// Created by LHB on 16/8/30.
// Copyright © 2016年 LHB. All rights reserved.
//
import UIKit
import UIKit
class EmioticonViewCell: UICollectionViewCell {
// MARK:- 懒加载属性
private lazy var emoticonBtn : UIButton = UIButton()
// MARK:- 定义的属性
var emoticon : Emoticon? {
didSet {
guard let emoticon = emoticon else {
return
}
// 1.设置emoticonBtn的内容
emoticonBtn.setImage(UIImage(contentsOfFile: emoticon.pngPath ?? ""), forState: .Normal)
emoticonBtn.setTitle(emoticon.emojiCode, forState: .Normal)
// 2.设置删除按钮
if emoticon.isRemove {
emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
}
}
}
// MARK:- 重写构造函数
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面内容
extension EmioticonViewCell {
private func setupUI() {
// 1.添加子控件
contentView.addSubview(emoticonBtn)
// 2.设置btn的frame
emoticonBtn.frame = contentView.bounds
// 3.设置btn属性
emoticonBtn.userInteractionEnabled = false
emoticonBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
}
}
| apache-2.0 | e543881f8d95d264c1d9c2cf9ccba863 | 23.783333 | 100 | 0.575656 | 4.646875 | false | false | false | false |
blkbrds/intern09_final_project_tung_bien | MyApp/Model/API/Api.Comment.swift | 1 | 1702 | //
// Api.Comment.swift
// MyApp
//
// Created by asiantech on 8/14/17.
// Copyright © 2017 Asian Tech Co., Ltd. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
extension Api.Comment {
struct QueryParams {
var pageToken: String
func toJson() -> Parameters {
return [
"pageToken": pageToken
]
}
}
@discardableResult
static func query(params: QueryParams, completion: @escaping ([Comment], String) -> Void) -> Request? {
let path = "https://www.googleapis.com/youtube/v3/commentThreads?part=snippet%2Creplies&videoId=Y72C9tHMv48&key=AIzaSyAk5CuJs78wbkTbYw8nPFr16N0fBgQdAXQ"
return api.requestForYoutube(method: .get, urlString: path, parameters: params.toJson(), completion: { (result) in
var comments: [Comment] = []
var pageToken = ""
guard let result = result.value as? JSObject,
let items = result["items"] as? JSArray else { return }
if let nextPageToken = result["nextPageToken"] as? String {
pageToken = nextPageToken
}
for item in items {
guard let snipet = item["snippet"] as? JSObject,
let topLevelComment = snipet["topLevelComment"] as? JSObject,
let snipetObject = topLevelComment["snippet"] as? JSObject else { return }
if let comment = Mapper<Comment>().map(JSON: snipetObject) {
comments.append(comment)
}
}
DispatchQueue.main.async {
completion(comments, pageToken)
}
})
}
}
| mit | 65b6fcece1b06e2b3f29f958f9033678 | 33.714286 | 160 | 0.579071 | 4.295455 | false | false | false | false |
eure/ReceptionApp | iOS/Pods/RxCocoa/RxCocoa/Common/Observables/NSObject+Rx.swift | 7 | 9103 | //
// NSObject+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
#if !DISABLE_SWIZZLING
var deallocatingSubjectTriggerContext: UInt8 = 0
var deallocatingSubjectContext: UInt8 = 0
#endif
var deallocatedSubjectTriggerContext: UInt8 = 0
var deallocatedSubjectContext: UInt8 = 0
/**
KVO is a tricky mechanism.
When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior.
When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior.
KVO with weak references is especially tricky. For it to work, some kind of swizzling is required.
That can be done by
* replacing object class dynamically (like KVO does)
* by swizzling `dealloc` method on all instances for a class.
* some third method ...
Both approaches can fail in certain scenarios:
* problems arise when swizzlers return original object class (like KVO does when nobody is observing)
* Problems can arise because replacing dealloc method isn't atomic operation (get implementation,
set implementation).
Second approach is chosen. It can fail in case there are multiple libraries dynamically trying
to replace dealloc method. In case that isn't the case, it should be ok.
*/
extension NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and retains `self` if `retainSelf` is set.
`rx_observe` is just a simple and performant wrapper around KVO mechanism.
* it can be used to observe paths starting from `self` or from ancestors in ownership graph (`retainSelf = false`)
* it can be used to observe paths starting from descendants in ownership graph (`retainSelf = true`)
* the paths have to consist only of `strong` properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc.
If support for weak properties is needed or observing arbitrary or unknown relationships in the
ownership tree, `rx_observeWeakly` is the preferred option.
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- parameter retainSelf: Retains self during observation if set `true`.
- returns: Observable sequence of objects on `keyPath`.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_observe<E>(type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions = [.New, .Initial], retainSelf: Bool = true) -> Observable<E?> {
return KVOObservable(object: self, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable()
}
}
#if !DISABLE_SWIZZLING
// KVO
extension NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and doesn't retain `self`.
It can be used in all cases where `rx_observe` can be used and additionally
* because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown
* it can be used to observe `weak` properties
**Since it needs to intercept object deallocation process it needs to perform swizzling of `dealloc` method on observed object.**
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- returns: Observable sequence of objects on `keyPath`.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_observeWeakly<E>(type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions = [.New, .Initial]) -> Observable<E?> {
return observeWeaklyKeyPathFor(self, keyPath: keyPath, options: options)
.map { n in
return n as? E
}
}
}
#endif
// Dealloc
extension NSObject {
/**
Observable sequence of object deallocated events.
After object is deallocated one `()` element will be produced and sequence will immediately complete.
- returns: Observable sequence of object deallocated events.
*/
public var rx_deallocated: Observable<Void> {
return rx_synchronized {
if let deallocObservable = objc_getAssociatedObject(self, &deallocatedSubjectContext) as? DeallocObservable {
return deallocObservable._subject
}
let deallocObservable = DeallocObservable()
objc_setAssociatedObject(self, &deallocatedSubjectContext, deallocObservable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return deallocObservable._subject
}
}
#if !DISABLE_SWIZZLING
/**
Observable sequence of message arguments that completes when object is deallocated.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
In case some argument is `nil`, instance of `NSNull()` will be sent.
- returns: Observable sequence of object deallocating events.
*/
public func rx_sentMessage(selector: Selector) -> Observable<[AnyObject]> {
return rx_synchronized {
// in case of dealloc selector replay subject behavior needs to be used
if selector == deallocSelector {
return rx_deallocating.map { _ in [] }
}
let rxSelector = RX_selector(selector)
let selectorReference = RX_reference_from_selector(rxSelector)
let subject: MessageSentObservable
if let existingSubject = objc_getAssociatedObject(self, selectorReference) as? MessageSentObservable {
subject = existingSubject
}
else {
subject = MessageSentObservable()
objc_setAssociatedObject(
self,
selectorReference,
subject,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
if subject.isActive {
return subject.asObservable()
}
var error: NSError?
let targetImplementation = RX_ensure_observing(self, selector, &error)
if targetImplementation == nil {
return Observable.error(error?.rxCocoaErrorForTarget(self) ?? RxCocoaError.Unknown)
}
subject.targetImplementation = targetImplementation
return subject.asObservable()
}
}
/**
Observable sequence of object deallocating events.
When `dealloc` message is sent to `self` one `()` element will be produced and after object is deallocated sequence
will immediately complete.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
- returns: Observable sequence of object deallocating events.
*/
public var rx_deallocating: Observable<()> {
return rx_synchronized {
let subject: DeallocatingObservable
if let existingSubject = objc_getAssociatedObject(self, rxDeallocatingSelectorReference) as? DeallocatingObservable {
subject = existingSubject
}
else {
subject = DeallocatingObservable()
objc_setAssociatedObject(
self,
rxDeallocatingSelectorReference,
subject,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
if subject.isActive {
return subject.asObservable()
}
var error: NSError?
let targetImplementation = RX_ensure_observing(self, deallocSelector, &error)
if targetImplementation == nil {
return Observable.error(error?.rxCocoaErrorForTarget(self) ?? RxCocoaError.Unknown)
}
subject.targetImplementation = targetImplementation
return subject.asObservable()
}
}
#endif
}
let deallocSelector = "dealloc" as Selector
let rxDeallocatingSelector = RX_selector("dealloc")
let rxDeallocatingSelectorReference = RX_reference_from_selector(rxDeallocatingSelector)
extension NSObject {
func rx_synchronized<T>(@noescape action: () -> T) -> T {
objc_sync_enter(self)
let result = action()
objc_sync_exit(self)
return result
}
}
extension NSObject {
/**
Helper to make sure that `Observable` returned from `createCachedObservable` is only created once.
This is important because there is only one `target` and `action` properties on `NSControl` or `UIBarButtonItem`.
*/
func rx_lazyInstanceObservable<T: AnyObject>(key: UnsafePointer<Void>, createCachedObservable: () -> T) -> T {
if let value = objc_getAssociatedObject(self, key) {
return value as! T
}
let observable = createCachedObservable()
objc_setAssociatedObject(self, key, observable, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return observable
}
} | mit | 8f50d8e4f7b5c28a2f76f319b757d602 | 36.929167 | 163 | 0.666227 | 5.076408 | false | false | false | false |
jpush/jchat-swift | JChat/Src/ContacterModule/ViewController/JCMoreResultViewController.swift | 1 | 8500 | //
// JCMoreResultViewController.swift
// JChat
//
// Created by JIGUANG on 2017/5/8.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
class JCMoreResultViewController: UIViewController {
var message: JMSGMessage?
var fromUser: JMSGUser!
weak var delegate: JCSearchResultViewController?
var searchResultView: JCSearchResultViewController!
var searchController: UISearchController!
var users: [JMSGUser] = []
var groups: [JMSGGroup] = []
fileprivate var selectGroup: JMSGGroup!
fileprivate var selectUser: JMSGUser!
//MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
_init()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.navigationBar.isHidden = true
if searchController != nil {
searchController.searchBar.isHidden = false
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.navigationBar.isHidden = false
}
deinit {
searchResultView.removeObserver(self, forKeyPath: "filteredUsersArray")
searchResultView.removeObserver(self, forKeyPath: "filteredGroupsArray")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "filteredUsersArray" {
users = searchResultView.filteredUsersArray
}
if keyPath == "filteredGroupsArray" {
groups = searchResultView.filteredGroupsArray
}
tableView.reloadData()
}
fileprivate lazy var tableView: UITableView = {
var tableView = UITableView(frame: CGRect(x: 0, y: 64, width: self.view.width, height: self.view.height - 64))
tableView.delegate = self
tableView.dataSource = self
tableView.keyboardDismissMode = .onDrag
tableView.register(JCContacterCell.self, forCellReuseIdentifier: "JCContacterCell")
return tableView
}()
//MARK: - private func
private func _init() {
navigationController?.automaticallyAdjustsScrollViewInsets = false
automaticallyAdjustsScrollViewInsets = false
navigationController?.navigationBar.isHidden = true
view.backgroundColor = UIColor(netHex: 0xe8edf3)
view.addSubview(tableView)
searchResultView.addObserver(self, forKeyPath: "filteredUsersArray", options: .new, context: nil)
searchResultView.addObserver(self, forKeyPath: "filteredGroupsArray", options: .new, context: nil)
}
fileprivate func sendBusinessCard() {
JCAlertView.bulid().setTitle("发送给:\(selectGroup.displayName())")
.setMessage(fromUser!.displayName() + "的名片")
.setDelegate(self)
.addCancelButton("取消")
.addButton("确定")
.setTag(10003)
.show()
}
fileprivate func forwardMessage(_ message: JMSGMessage) {
let alertView = JCAlertView.bulid().setJMessage(message)
.setDelegate(self)
.setTag(10001)
if selectUser == nil {
alertView.setTitle("发送给:\(selectGroup.displayName())")
} else {
alertView.setTitle("发送给:\(selectUser.displayName())")
}
alertView.show()
}
}
//Mark: -
extension JCMoreResultViewController: UITableViewDelegate, UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if users.count > 0 {
return users.count
}
return groups.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 55
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "JCContacterCell", for: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? JCContacterCell else {
return
}
if users.count > 0 {
cell.bindDate(users[indexPath.row])
} else {
cell.bindDateWithGroup(group: groups[indexPath.row])
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if users.count > 0 {
let user = users[indexPath.row]
selectUser = user
if let message = message {
forwardMessage(message)
return
}
if fromUser != nil {
sendBusinessCard()
return
}
let vc: UIViewController
if user.isEqual(to: JMSGUser.myInfo()) {
vc = JCMyInfoViewController()
} else {
let v = JCUserInfoViewController()
v.user = user
vc = v
}
if searchController != nil {
searchController.searchBar.resignFirstResponder()
searchController.searchBar.isHidden = true
}
navigationController?.navigationBar.isHidden = false
navigationController?.pushViewController(vc, animated: true)
} else {
let group = groups[indexPath.row]
selectGroup = group
if let message = message {
forwardMessage(message)
return
}
if fromUser != nil {
sendBusinessCard()
return
}
JMSGConversation.createGroupConversation(withGroupId: group.gid) { (result, error) in
let conv = result as! JMSGConversation
let vc = JCChatViewController(conversation: conv)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
if self.searchController != nil {
self.searchController.searchBar.resignFirstResponder()
self.searchController.searchBar.isHidden = true
}
self.navigationController?.navigationBar.isHidden = false
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
}
extension JCMoreResultViewController: UIAlertViewDelegate {
func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
if buttonIndex != 1 {
return
}
switch alertView.tag {
case 10001:
if selectUser != nil {
JMSGMessage.forwardMessage(message!, target: selectUser, optionalContent: JMSGOptionalContent.ex.default)
} else {
JMSGMessage.forwardMessage(message!, target: selectGroup, optionalContent: JMSGOptionalContent.ex.default)
}
case 10003:
if selectUser != nil {
JMSGConversation.createSingleConversation(withUsername: selectUser.username) { (result, error) in
if let conversation = result as? JMSGConversation {
let message = JMSGMessage.ex.createBusinessCardMessage(conversation, self.fromUser.username, self.fromUser.appKey ?? "")
JMSGMessage.send(message, optionalContent: JMSGOptionalContent.ex.default)
}
}
} else {
let msg = JMSGMessage.ex.createBusinessCardMessage(gid: selectGroup.gid, userName: fromUser!.username, appKey: fromUser!.appKey ?? "")
JMSGMessage.send(msg, optionalContent: JMSGOptionalContent.ex.default)
}
default:
break
}
MBProgressHUD_JChat.show(text: "已发送", view: view, 2)
let time: TimeInterval = 2
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kReloadAllMessage), object: nil)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) { [weak self] in
self?.delegate?.close()
}
}
}
| mit | f512fbd29ee36c3a9e7ac0aee5ad0c35 | 36.074561 | 151 | 0.614102 | 5.16687 | false | false | false | false |
proxyco/RxBluetoothKit | Source/RestoredState.swift | 1 | 2588 | //
// RestoredState.swift
// RxBluetoothKit
//
// Created by Kacper Harasim on 21.05.2016.
// Copyright © 2016 Polidea. All rights reserved.
//
import Foundation
import CoreBluetooth
/**
Convenience class which helps reading state of restored BluetoothManager
*/
#if os(iOS)
public struct RestoredState {
/**
Restored state dictionary
*/
public let restoredStateData: [String:AnyObject]
public unowned let bluetoothManager: BluetoothManager
/**
Creates restored state information based on CoreBluetooth's dictionary
- parameter restoredState: Core Bluetooth's restored state data
- parameter bluetoothManager: `BluetoothManager` instance of which state has been restored.
*/
init(restoredStateDictionary: [String:AnyObject], bluetoothManager: BluetoothManager) {
self.restoredStateData = restoredStateDictionary
self.bluetoothManager = bluetoothManager
}
/**
Array of `Peripheral` objects which have been restored. These are peripherals that were connected to the central manager (or had a connection pending) at the time the app was terminated by the system.
*/
public var peripherals: [Peripheral] {
let objects = restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [AnyObject]
guard let arrayOfAnyObjects = objects else { return [] }
return arrayOfAnyObjects.flatMap { $0 as? CBPeripheral }
.map { RxCBPeripheral(peripheral: $0) }
.map { Peripheral(manager: bluetoothManager, peripheral: $0) }
}
/**
Dictionary that contains all of the peripheral scan options that were being used by the central manager at the time the app was terminated by the system.
*/
public var scanOptions: [String : AnyObject]? {
return restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [String : AnyObject]
}
/**
Array of `Service` objects which have been restored. These are all the services the central manager was scanning for at the time the app was terminated by the system.
*/
public var services: [Service] {
let objects = restoredStateData[CBCentralManagerRestoredStateScanServicesKey] as? [AnyObject]
guard let arrayOfAnyObjects = objects else { return [] }
return arrayOfAnyObjects.flatMap { $0 as? CBService }
.map { RxCBService(service: $0) }
.map { Service(peripheral: Peripheral(manager: bluetoothManager,
peripheral: RxCBPeripheral(peripheral: $0.service.peripheral)), service: $0) }
}
}
#endif
| mit | 8530218d4e33480c4e15bf7bffcb6823 | 39.421875 | 205 | 0.708156 | 5.033074 | false | false | false | false |
raychrd/tada | tada/AppDelegate.swift | 1 | 3291 | //
// AppDelegate.swift
// tada
//
// Created by Ray on 15/1/24.
// Copyright (c) 2015年 Ray. All rights reserved.
//
import UIKit
import EventKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var eventStore:EKEventStore?
var events:[EKReminder] = Array()
var events2:[EKReminder] = Array()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//UINavigationBar.clipsToBounds = true
//UINavigationBar.appearance().tintColor = UIColor.whiteColor()
/*
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "HelveticaNeue", size: 22)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
//UINavigationBar.appearance().clipsToBounds = true
*/
/*
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
UINavigationBar.navigationController?.interactivePopGestureRecognizer.delegate = nil
}
*/
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
//appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
return true
}
/*
func application(application: UIApplication , didReceiveLocalNotification notification: EKEventStoreChangedNotification) {
alertView.show()
}
*/
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:.
println("BYE")
}
}
| mit | 1c22cc336a0cc7c83b4f7be2e98b6cae | 41.166667 | 285 | 0.719064 | 5.76007 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGAP/GAPServiceData128BitUUID.swift | 1 | 2431 | //
// GAPServiceData128BitUUID.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/13/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// The Service Data data type consists of a service UUID with the data associated with that service.
///
/// Size: 16 or more octets
/// The first 16 octets contain the 128 bit Service UUID followed by additional service data
@frozen
public struct GAPServiceData128BitUUID: GAPData, Equatable {
public static let dataType: GAPDataType = .serviceData128BitUUID
/// UUID
public let uuid: UUID
/// Service Data
public let serviceData: Data
public init(uuid: UUID,
serviceData: Data = Data()) {
self.uuid = uuid
self.serviceData = serviceData
}
}
public extension GAPServiceData128BitUUID {
init?(data: Data) {
guard data.count >= UInt128.length
else { return nil }
let uuid = UInt128(littleEndian: UInt128(bytes: (data[0],
data[1],
data[2],
data[3],
data[4],
data[5],
data[6],
data[7],
data[8],
data[9],
data[10],
data[11],
data[12],
data[13],
data[14],
data[15])))
let serviceData = data.subdata(in: UInt128.length ..< data.count)
self.init(uuid: UUID(uuid), serviceData: serviceData)
}
func append(to data: inout Data) {
data += UInt128(uuid: uuid).littleEndian
data += serviceData
}
var dataLength: Int {
return UInt128.length + serviceData.count
}
}
| mit | 360ee79604d005a7c79c2396d7d89b4f | 32.287671 | 101 | 0.397119 | 6 | false | false | false | false |
simonbengtsson/realmfire-swift | Demo/ViewController.swift | 1 | 2408 | import UIKit
import Firebase
import RealmSwift
class ViewController: UIViewController {
@IBOutlet weak var objectTypeSwitch: UISegmentedControl!
enum ObjectType: Int {
case dog, person
}
var objectType: ObjectType {
return ObjectType(rawValue: objectTypeSwitch.selectedSegmentIndex)!
}
var type: SyncObject.Type {
return objectType == .dog ? Dog.self : Person.self
}
@IBAction func create(_ sender: UIButton) {
let realm = try! Realm()
let obj = objectType == .dog ? Dog(debug: true) : Person(debug: true)
try! realm.write {
realm.add(obj)
RealmFire.markForSync(obj)
if let dog = obj as? Dog {
RealmFire.markForSync(dog.trainers)
RealmFire.markForSync(dog.owner!)
} else {
let person = obj as! Person
RealmFire.markForSync(person.dogs)
}
}
RealmFire.sync(realm: realm)
}
@IBAction func editClicked(_ sender: UIButton) {
let realm = try! Realm()
let obj = realm.objects(type).first!
try! realm.write {
if let dog = obj as? Dog {
dog.awardCount += 1
} else if let person = obj as? Person {
person.age += 1
}
realm.add(obj)
RealmFire.markForSync(obj)
}
RealmFire.sync()
}
@IBAction func deleteClicked(_ sender: UIButton) {
let realm = try! Realm()
let obj = realm.objects(type).first!
try! realm.write {
realm.delete(obj)
RealmFire.markForDeletion(obj)
}
}
@IBAction func clearAll(_ sender: UIButton) {
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
}
}
@IBAction func fetchCliced(_ sender: UIButton) {
RealmFire.sync()
}
@IBAction func uploadClicked(_ sender: UIButton) {
let realm = try! Realm()
try! realm.write {
for obj in realm.objects(Dog.self) {
obj.awardCount += 1
RealmFire.markForSync(obj)
}
for obj in realm.objects(Person.self) {
obj.age += 1
RealmFire.markForSync(obj)
}
}
}
}
| mit | 061d3d98cd0013518103fc636d7264ed | 26.363636 | 77 | 0.518688 | 4.543396 | false | false | false | false |
EZ-NET/ESSwim | Sources/Type/Optional.swift | 1 | 851 | //
// Optional.swift
// ESSwim
//
// Created by Tomohiro Kumagai on H27/08/04.
//
//
/// Throws wrapped error. If the instance has no error, this method do nothing.
extension Optional where Wrapped : ErrorType {
public func throwIfHaveError() throws {
if let error = self {
throw error
}
}
}
/// Compare two array<T?> for value equality.
public func == <C:CollectionType, T:Equatable where C.Generator.Element == Optional<T>>(lhs:C, rhs:C) -> Bool {
guard lhs.count == rhs.count else {
return false
}
return zip(lhs, rhs).findElement(==).isExists
}
/// Compare two array<T?> for value equality.
public func != <C:CollectionType, T:Equatable where C.Generator.Element == Optional<T>>(lhs:C, rhs:C) -> Bool {
guard lhs.count == rhs.count else {
return true
}
return zip(lhs, rhs).findElement(!=).isExists
}
| mit | 75709a6b83318ac423aa6b857c59b067 | 19.756098 | 111 | 0.663925 | 3.29845 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureDashboard/Sources/FeatureDashboardUI/WalletActionScreen/Custody/CustodyActionRouter.swift | 1 | 11582 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import FeatureTransactionUI
import MoneyKit
import PlatformKit
import PlatformUIKit
import RxRelay
import RxSwift
import RxToolKit
import ToolKit
public protocol BackupRouterAPI {
var completionRelay: PublishRelay<Void> { get }
func start()
}
public protocol WalletOperationsRouting {
func handleSwapCrypto(account: CryptoAccount?)
func handleSellCrypto(account: CryptoAccount?)
func handleBuyCrypto(account: CryptoAccount?)
func handleBuyCrypto(currency: CryptoCurrency)
func showCashIdentityVerificationScreen()
func showFundTrasferDetails(fiatCurrency: FiatCurrency, isOriginDeposit: Bool)
func switchTabToSwap()
}
public final class CustodyActionRouterProvider {
public init() {}
public func create(
backupRouterAPI: BackupRouterAPI,
tabSwapping: TabSwapping
) -> CustodyActionRouterAPI {
CustodyActionRouter(
backupRouterAPI: backupRouterAPI,
tabSwapping: tabSwapping
)
}
}
final class CustodyActionRouter: CustodyActionRouterAPI {
// MARK: - `Router` Properties
let completionRelay = PublishRelay<Void>()
let analyticsService: SimpleBuyAnalayticsServicing
let walletOperationsRouter: WalletOperationsRouting
private var stateService: CustodyActionStateServiceAPI!
private let backupRouterAPI: BackupRouterAPI
private let custodyWithdrawalRouter: CustodyWithdrawalRouterAPI
private var depositRouter: DepositRootRouting!
private let navigationRouter: NavigationRouterAPI
private var account: BlockchainAccount!
private var currency: CurrencyType! {
account?.currencyType
}
private let tabSwapping: TabSwapping
private let accountProviding: BlockchainAccountProviding
private let analyticsRecoder: AnalyticsEventRecorderAPI
private var disposeBag = DisposeBag()
convenience init(backupRouterAPI: BackupRouterAPI, tabSwapping: TabSwapping) {
self.init(
backupRouterAPI: backupRouterAPI,
tabSwapping: tabSwapping,
custodyWithdrawalRouter: CustodyWithdrawalRouter()
)
}
init(
backupRouterAPI: BackupRouterAPI,
tabSwapping: TabSwapping,
custodyWithdrawalRouter: CustodyWithdrawalRouterAPI,
navigationRouter: NavigationRouterAPI = resolve(),
accountProviding: BlockchainAccountProviding = resolve(),
analyticsService: SimpleBuyAnalayticsServicing = resolve(),
walletOperationsRouter: WalletOperationsRouting = resolve(),
analyticsRecoder: AnalyticsEventRecorderAPI = resolve()
) {
self.accountProviding = accountProviding
self.navigationRouter = navigationRouter
self.custodyWithdrawalRouter = custodyWithdrawalRouter
self.walletOperationsRouter = walletOperationsRouter
self.backupRouterAPI = backupRouterAPI
self.analyticsService = analyticsService
self.tabSwapping = tabSwapping
self.analyticsRecoder = analyticsRecoder
backupRouterAPI
.completionRelay
.bindAndCatch(weak: self, onNext: { (self, _) in
self.stateService.nextRelay.accept(())
})
.disposed(by: disposeBag)
custodyWithdrawalRouter
.completionRelay
.bindAndCatch(to: completionRelay)
.disposed(by: disposeBag)
custodyWithdrawalRouter
.internalSendRelay
.bindAndCatch(weak: self) { (self, _) in
self.showSend()
}
.disposed(by: disposeBag)
}
func start(with account: BlockchainAccount) {
// TODO: Would much prefer a different form of injection
// but we build our `Routers` in the AppCoordinator
self.account = account
stateService = CustodyActionStateService(recoveryStatusProviding: resolve())
stateService.action
.bindAndCatch(weak: self) { (self, action) in
switch action {
case .previous:
self.previous()
case .next(let state):
self.next(to: state)
case .dismiss:
self.navigationRouter.navigationControllerAPI?.dismiss(animated: true, completion: nil)
}
}
.disposed(by: disposeBag)
stateService.nextRelay.accept(())
}
func next(to state: CustodyActionState) {
switch state {
case .start:
showWalletActionSheet()
case .introduction:
/// The `topMost` screen is the `CustodyActionScreen`
dismiss { [weak self] in
guard let self = self else { return }
self.showIntroductionScreen()
}
case .backup,
.backupAfterIntroduction:
/// The `topMost` screen is the `CustodyActionScreen`
dismiss { [weak self] in
guard let self = self else { return }
self.backupRouterAPI.start()
}
case .send:
showSend()
case .receive:
showReceive()
case .activity:
showActivityScreen()
case .sell:
showSell()
case .swap:
showSwap()
case .buy:
showBuy()
case .deposit(isKYCApproved: let value):
switch value {
case true:
showDepositFlow()
case false:
showCashIdentityViewController()
}
case .withdrawalAfterBackup:
/// `Backup` has already been dismissed as `Backup`
/// has ended. `CustodyActionScreen` has been dismissed
/// prior to `Backup`. There is no `topMost` screen that
/// needs to be dismissed.
guard case .crypto(let currency) = currency else { return }
custodyWithdrawalRouter.start(with: currency)
case .withdrawal:
/// The `topMost` screen is the `CustodyActionScreen`
guard case .crypto(let currency) = currency else { return }
dismiss { [weak self] in
guard let self = self else { return }
self.custodyWithdrawalRouter.start(with: currency)
}
case .withdrawalFiat(let isKYCApproved):
analyticsRecoder.record(event: AnalyticsEvents.New.Withdrawal.withdrawalClicked(origin: .currencyPage))
if isKYCApproved {
guard case .fiat(let currency) = currency else { return }
showWithdrawFiatScreen(currency: currency)
} else {
showCashIdentityViewController()
}
case .end:
dismiss()
}
}
private func showSend() {
dismiss { [weak self] in
guard let self = self else {
return
}
self.tabSwapping.send(from: self.account)
}
}
private func showReceive() {
dismiss { [weak self] in
guard let self = self else {
return
}
if let account = self.account {
self.tabSwapping.receive(into: account)
} else {
self.tabSwapping.switchTabToReceive()
}
}
}
private func showWalletActionSheet() {
if case .crypto(let cryptoCurrency) = account.currencyType {
analyticsService.recordTradingWalletClicked(for: cryptoCurrency)
}
let interactor = WalletActionScreenInteractor(account: account)
let presenter = CustodialActionScreenPresenter(
using: interactor,
stateService: stateService
)
let controller = WalletActionScreenViewController(using: presenter)
controller.transitioningDelegate = sheetPresenter
controller.modalPresentationStyle = .custom
navigationRouter.topMostViewControllerProvider.topMostViewController?.present(controller, animated: true, completion: nil)
}
private func showActivityScreen() {
dismiss { [weak self] in
self?.tabSwapping.switchToActivity()
}
}
private func showCashIdentityViewController() {
guard case .fiat = currency else { return }
dismiss { [weak self] in
self?.walletOperationsRouter.showCashIdentityVerificationScreen()
}
}
private func showDepositFlow() {
dismiss { [weak self] in
guard let self = self else { return }
self.accountProviding
.accounts(for: self.currency)
.compactMap(\.first)
.observe(on: MainScheduler.instance)
.subscribe(onSuccess: { [weak self] account in
self?.tabSwapping.deposit(into: account)
})
.disposed(by: self.disposeBag)
}
}
private func showFundTransferDetails(_ currency: FiatCurrency) {
dismiss { [weak self] in
self?.walletOperationsRouter.showFundTrasferDetails(
fiatCurrency: currency,
isOriginDeposit: true
)
}
}
private func showSwap() {
dismiss { [walletOperationsRouter, account] in
walletOperationsRouter.handleSwapCrypto(account: account as? CryptoAccount)
}
}
private func showBuy() {
dismiss { [walletOperationsRouter, account] in
walletOperationsRouter.handleBuyCrypto(account: account as? CryptoAccount)
}
}
private func showSell() {
dismiss { [walletOperationsRouter, account] in
walletOperationsRouter.handleSellCrypto(account: account as? CryptoAccount)
}
}
private func showIntroductionScreen() {
let presenter = CustodyInformationScreenPresenter(stateService: stateService)
let controller = CustodyInformationViewController(presenter: presenter)
controller.isModalInPresentation = true
navigationRouter.present(viewController: controller, using: .modalOverTopMost)
}
private func showWithdrawFiatScreen(currency: FiatCurrency) {
showWithdrawTransactionFlow(currency)
}
private func showWithdrawTransactionFlow(_ currency: FiatCurrency) {
dismiss { [weak self] in
guard let self = self else { return }
self.accountProviding
.accounts(for: .fiat(currency))
.compactMap(\.first)
.observe(on: MainScheduler.instance)
.subscribe(onSuccess: { [weak self] account in
self?.tabSwapping.withdraw(from: account)
})
.disposed(by: self.disposeBag)
}
}
func previous() {
navigationRouter.dismiss()
}
/// Dismiss all presented ViewControllers and then execute callback.
private func dismiss(completion: (() -> Void)? = nil) {
var root: UIViewController? = navigationRouter.topMostViewControllerProvider.topMostViewController
while root?.presentingViewController != nil {
root = root?.presentingViewController
}
root?
.dismiss(
animated: true,
completion: {
completion?()
}
)
}
private lazy var sheetPresenter: BottomSheetPresenting = BottomSheetPresenting(ignoresBackgroundTouches: false)
}
| lgpl-3.0 | 7a06ead8c7acb5e41fc74c140ea06494 | 33.364985 | 130 | 0.619808 | 5.219018 | false | false | false | false |
modum-io/ios_client | PharmaSupplyChain/Parcel.swift | 1 | 4426 | //
// Parcel.swift
// PharmaSupplyChain
//
// Created by Yury Belevskiy on 24.02.17.
// Copyright © 2017 Modum. All rights reserved.
//
import ObjectMapper
enum ParcelStatus : String {
case inProgress = "In Progress"
case notWithinTemperatureRange = "Failed"
case successful = "Successful"
case undetermined = "Undetermined"
static func getStatus(isSuccess: Bool, isFailure: Bool, isReceived: Bool, localInterpretationStatus: Bool) -> ParcelStatus {
if !isReceived {
return .inProgress
} else if isSuccess && !isFailure {
return .successful
} else if !isSuccess && isFailure {
return .notWithinTemperatureRange
} else if localInterpretationStatus {
return .successful
} else {
return .undetermined
}
}
}
class Parcel : Mappable, CoreDataObject {
// MARK: Properties
var id: Int?
var tntNumber: String?
var senderCompany: String?
var receiverCompany: String?
var sensorID: String?
var isSuccess: Bool?
var isFailure: Bool?
var isSent: Bool?
var isReceived: Bool?
var dateSent: Date?
var dateReceived: Date?
var additionalInfo: String?
var localInterpretationSuccess: Bool?
/* On server-side should be replaced by TemperatureCategory object */
var minTemp: Int?
var maxTemp: Int?
var temperatureCategory: String?
var parcelStatus: ParcelStatus?
// MARK: Mappable
public required init?(map: Map) {}
public func mapping(map: Map) {
id <- map["id"]
temperatureCategory <- map["tempCategory"]
minTemp <- map["minTemp"]
maxTemp <- map["maxTemp"]
tntNumber <- map["tntNumber"]
senderCompany <- map["senderCompany"]
receiverCompany <- map["receiverCompany"]
sensorID <- map["sensorID"]
isReceived <- map["isReceived"]
isSent <- map["isSent"]
isSuccess <- map["isSuccess"]
isFailure <- map["isFailed"]
dateSent <- (map["dateSent"], ServerDateTransform())
dateReceived <- (map["dateReceived"], ServerDateTransform())
additionalInfo <- map["additionalInfo"]
localInterpretationSuccess <- map["localInterpretationSuccess"]
/* determining status */
if let isSuccess = isSuccess, let isFailure = isFailure, let isReceived = isReceived, let localInterpretationSuccess = localInterpretationSuccess {
parcelStatus = ParcelStatus.getStatus(isSuccess: isSuccess, isFailure: isFailure, isReceived: isReceived, localInterpretationStatus: localInterpretationSuccess)
}
}
// MARK: CoreDataObject
required public init?(WithCoreDataObject object: CDParcel) {
id = object.id
temperatureCategory = object.tempCategory
minTemp = object.minTemp
maxTemp = object.maxTemp
tntNumber = object.tntNumber
senderCompany = object.senderCompany
receiverCompany = object.receiverCompany
isReceived = object.isReceived
isSent = object.isSent
isSuccess = object.isSuccess
isFailure = object.isFailed
dateSent = object.dateSent
dateReceived = object.dateReceived
additionalInfo = object.additionalInfo
localInterpretationSuccess = object.localInterpretationSuccess
}
public func toCoreDataObject(object: CDParcel) {
if let id = id, let temperatureCategory = temperatureCategory, let minTemp = minTemp, let maxTemp = maxTemp, let tntNumber = tntNumber, let senderCompany = senderCompany, let receiverCompany = receiverCompany, let isReceived = isReceived, let isSent = isSent, let isFailure = isFailure, let isSuccess = isSuccess, let dateSent = dateSent {
object.id = id
object.tempCategory = temperatureCategory
object.minTemp = minTemp
object.maxTemp = maxTemp
object.tntNumber = tntNumber
object.senderCompany = senderCompany
object.receiverCompany = receiverCompany
object.isReceived = isReceived
object.isSent = isSent
object.isFailed = isFailure
object.isSuccess = isSuccess
object.dateSent = dateSent
object.dateReceived = dateReceived
object.additionalInfo = additionalInfo
}
}
}
| apache-2.0 | 69f5e88b8befdaa06ec374448dab510e | 34.97561 | 347 | 0.648136 | 4.80456 | false | false | false | false |
pauljohanneskraft/Math | CoreMath/Classes/Functions/Function.swift | 1 | 3397 | //
// Function.swift
// LinearAlgebra
//
// Created by Paul Kraft on 14.07.16.
// Copyright © 2016 pauljohanneskraft. All rights reserved.
//
import Foundation
public protocol Function: CustomStringConvertible, LaTeXConvertible {
// properties
var derivative: Function { get }
var integral: Function { get }
var reduced: Function { get }
var debugDescription: String { get }
// functions
func call(x: Double) -> Double
func coefficientDescription(first: Bool) -> String
func equals(to: Function) -> Bool
// operators
static func == (lhs: Function, rhs: Function) -> Bool
static func != (lhs: Function, rhs: Function) -> Bool
static func + (lhs: Function, rhs: Function) -> Function
static func - (lhs: Function, rhs: Function) -> Function
static func * (lhs: Function, rhs: Function) -> Function
static func / (lhs: Function, rhs: Function) -> Function
prefix static func - (lhs: Function) -> Function
}
extension Function {
// properties
public var debugDescription: String { return description }
// functions
public func coefficientDescription(first: Bool ) -> String { return first ? description : "+ \(description)" }
public func integral(c: Double ) -> Function { return integral + Constant(c) }
public func integral(from: Double, to: Double ) -> Double {
let int = self.integral
return int.call(x: from) - int.call(x: to)
}
}
extension Function {
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.equals(to: rhs)
}
}
public func * (lhs: Function, rhs: Function) -> Function {
if let l = lhs as? Equation {
var res: Function = Constant(0)
for f1 in l.terms { res = res + (f1 * rhs) }
return res.reduced
}
if let r = rhs as? Equation {
var res: Function = Constant(0)
for f1 in r.terms { res = res + (f1 * lhs) }
return res.reduced
}
if var l = lhs as? Term { l.factors.append(rhs); return l.reduced }
if var r = rhs as? Term { r.factors.append(lhs); return r.reduced }
return Term(lhs, rhs).reduced
}
public func + (lhs: Function, rhs: Function) -> Function {
let lhs = lhs.reduced
let rhs = rhs.reduced
if let l = lhs as? Equation {
if let r = rhs as? Equation { return Equation(l.terms + r.terms).reduced }
return Equation(l.terms + [rhs]).reduced
}
if let r = rhs as? Equation { return Equation([lhs] + r.terms).reduced }
return Equation(lhs, rhs).reduced
}
public prefix func - (lhs: Function) -> Function {
if let l = lhs as? Constant { return Constant(-(l.value)) }
return Constant(-1) * lhs
}
internal func == (lhs: [Function], rhs: [Function]) -> Bool {
guard lhs.count == rhs.count else { return false }
let l = lhs.sorted { $0.description < $1.description }
let r = rhs.sorted { $0.description < $1.description }
return !l.indices.contains { l[$0] != r[$0] }
}
public func *= (lhs: inout Function, rhs: Function) { lhs = lhs * rhs }
public func += (lhs: inout Function, rhs: Function) { lhs = lhs + rhs }
public func - (lhs: Function, rhs: Function) -> Function {
return lhs + (-rhs)
}
public func == (lhs: Function, rhs: Function) -> Bool {
return lhs.reduced.equals(to: rhs.reduced)
}
public func != (lhs: Function, rhs: Function) -> Bool {
return !(lhs == rhs)
}
public func / (lhs: Function, rhs: Function) -> Function {
return Fraction(numerator: lhs, denominator: rhs).reduced
}
| mit | 5b39a73c2d5e8c9f6e5e5a05a823890b | 29.594595 | 111 | 0.650177 | 3.379104 | false | false | false | false |
tjw/swift | stdlib/public/core/MutableCollection.swift | 1 | 10113 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A type that provides subscript access to its elements.
///
/// In most cases, it's best to ignore this protocol and use the
/// `MutableCollection` protocol instead, because it has a more complete
/// interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'MutableCollection' instead")
public typealias MutableIndexable = MutableCollection
/// A collection that supports subscript assignment.
///
/// Collections that conform to `MutableCollection` gain the ability to
/// change the value of their elements. This example shows how you can
/// modify one of the names in an array of students.
///
/// var students = ["Ben", "Ivy", "Jordell", "Maxime"]
/// if let i = students.index(of: "Maxime") {
/// students[i] = "Max"
/// }
/// print(students)
/// // Prints "["Ben", "Ivy", "Jordell", "Max"]"
///
/// In addition to changing the value of an individual element, you can also
/// change the values of a slice of elements in a mutable collection. For
/// example, you can sort *part* of a mutable collection by calling the
/// mutable `sort()` method on a subscripted subsequence. Here's an
/// example that sorts the first half of an array of integers:
///
/// var numbers = [15, 40, 10, 30, 60, 25, 5, 100]
/// numbers[0..<4].sort()
/// print(numbers)
/// // Prints "[10, 15, 30, 40, 60, 25, 5, 100]"
///
/// The `MutableCollection` protocol allows changing the values of a
/// collection's elements but not the length of the collection itself. For
/// operations that require adding or removing elements, see the
/// `RangeReplaceableCollection` protocol instead.
///
/// Conforming to the MutableCollection Protocol
/// ============================================
///
/// To add conformance to the `MutableCollection` protocol to your own
/// custom collection, upgrade your type's subscript to support both read
/// and write access.
///
/// A value stored into a subscript of a `MutableCollection` instance must
/// subsequently be accessible at that same position. That is, for a mutable
/// collection instance `a`, index `i`, and value `x`, the two sets of
/// assignments in the following code sample must be equivalent:
///
/// a[i] = x
/// let y = a[i]
///
/// // Must be equivalent to:
/// a[i] = x
/// let y = x
public protocol MutableCollection: Collection
where SubSequence: MutableCollection
{
// FIXME(ABI): Associated type inference requires this.
associatedtype Element
// FIXME(ABI): Associated type inference requires this.
associatedtype Index
// FIXME(ABI): Associated type inference requires this.
associatedtype SubSequence
/// Accesses the element at the specified position.
///
/// For example, you can replace an element of an array by using its
/// subscript.
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// streets[1] = "Butler"
/// print(streets[1])
/// // Prints "Butler"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one
/// past the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
subscript(position: Index) -> Element { get set }
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// streets[index!] = "Eustace"
/// print(streets[index!])
/// // Prints "Eustace"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
subscript(bounds: Range<Index>) -> SubSequence { get set }
/// Reorders the elements of the collection such that all the elements
/// that match the given predicate are after all the elements that don't
/// match.
///
/// After partitioning a collection, there is a pivot index `p` where
/// no element before `p` satisfies the `belongsInSecondPartition`
/// predicate and every element at or after `p` satisfies
/// `belongsInSecondPartition`.
///
/// In the following example, an array of numbers is partitioned by a
/// predicate that matches elements greater than 30.
///
/// var numbers = [30, 40, 20, 30, 30, 60, 10]
/// let p = numbers.partition(by: { $0 > 30 })
/// // p == 5
/// // numbers == [30, 10, 20, 30, 30, 60, 40]
///
/// The `numbers` array is now arranged in two partitions. The first
/// partition, `numbers[..<p]`, is made up of the elements that
/// are not greater than 30. The second partition, `numbers[p...]`,
/// is made up of the elements that *are* greater than 30.
///
/// let first = numbers[..<p]
/// // first == [30, 10, 20, 30, 30]
/// let second = numbers[p...]
/// // second == [60, 40]
///
/// - Parameter belongsInSecondPartition: A predicate used to partition
/// the collection. All elements satisfying this predicate are ordered
/// after all elements not satisfying it.
/// - Returns: The index of the first element in the reordered collection
/// that matches `belongsInSecondPartition`. If no elements in the
/// collection match `belongsInSecondPartition`, the returned index is
/// equal to the collection's `endIndex`.
///
/// - Complexity: O(*n*)
mutating func partition(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index
/// Exchanges the values at the specified indices of the collection.
///
/// Both parameters must be valid indices of the collection and not
/// equal to `endIndex`. Passing the same index as both `i` and `j` has no
/// effect.
///
/// - Parameters:
/// - i: The index of the first value to swap.
/// - j: The index of the second value to swap.
mutating func swapAt(_ i: Index, _ j: Index)
/// Call `body(p)`, where `p` is a pointer to the collection's
/// mutable contiguous storage. If no such storage exists, it is
/// first created. If the collection does not support an internal
/// representation in a form of mutable contiguous storage, `body` is not
/// called and `nil` is returned.
///
/// Often, the optimizer can eliminate bounds- and uniqueness-checks
/// within an algorithm, but when that fails, invoking the
/// same algorithm on `body`\ 's argument lets you trade safety for
/// speed.
mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R?
}
// TODO: swift-3-indexing-model - review the following
extension MutableCollection {
@inlinable
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return nil
}
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// streets[index!] = "Eustace"
/// print(streets[index!])
/// // Prints "Eustace"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
@inlinable
public subscript(bounds: Range<Index>) -> Slice<Self> {
get {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
set {
_writeBackMutableSlice(&self, bounds: bounds, slice: newValue)
}
}
/// Exchanges the values at the specified indices of the collection.
///
/// Both parameters must be valid indices of the collection that are not
/// equal to `endIndex`. Calling `swapAt(_:_:)` with the same index as both
/// `i` and `j` has no effect.
///
/// - Parameters:
/// - i: The index of the first value to swap.
/// - j: The index of the second value to swap.
@inlinable
public mutating func swapAt(_ i: Index, _ j: Index) {
guard i != j else { return }
let tmp = self[i]
self[i] = self[j]
self[j] = tmp
}
}
| apache-2.0 | 556e4da138ce3c3e23ef9d4157958fab | 39.452 | 110 | 0.645605 | 4.283355 | false | false | false | false |
tjw/swift | test/SourceKit/CursorInfo/rdar_34348776.swift | 4 | 731 | public struct MyStruct<T> {}
public typealias Alias<T> = MyStruct<T>
public typealias Aliased = Alias
// RUN: %sourcekitd-test -req=cursor -pos=3:18 %s -- %s | %FileCheck %s
// CHECK: source.lang.swift.decl.typealias (3:18-3:25)
// CHECK-NEXT: Aliased
// CHECK-NEXT: s:13rdar_343487767Aliaseda
// CHECK-NEXT: Alias.Type
// CHECK-NEXT: $S13rdar_343487765AliasamD
// CHECK-NEXT: <Declaration>public typealias Aliased = <Type usr="s:13rdar_343487765Aliasa">Alias</Type></Declaration>
// CHECK-NEXT: <decl.typealias><syntaxtype.keyword>public</syntaxtype.keyword> <syntaxtype.keyword>typealias</syntaxtype.keyword> <decl.name>Aliased</decl.name> = <ref.typealias usr="s:13rdar_343487765Aliasa">Alias</ref.typealias></decl.typealias>
| apache-2.0 | d917c659c0164b7bee04d23069afdc41 | 55.230769 | 247 | 0.74829 | 3.123932 | false | true | false | false |
turingcorp/gattaca | gattaca/View/Abstract/Generic/VMenu.swift | 1 | 1053 | import UIKit
class VMenu:UIView
{
weak var collectionView:UICollectionView!
private(set) weak var controller:ControllerParent!
var cellSize:CGSize?
let kDeselectTime:TimeInterval = 0.3
private let kBorderHeight:CGFloat = 1
init(controller:ControllerParent)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.white
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let border:VBorder = VBorder(
colour:UIColor.colourBackgroundDark.withAlphaComponent(0.2))
addSubview(border)
NSLayoutConstraint.topToTop(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:kBorderHeight)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
factoryCollection()
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit | c7901ae4592f3ac14c699d7979d8ef6c | 24.682927 | 72 | 0.617284 | 5.372449 | false | false | false | false |
lorentey/SipHash | SipHash/Primitive Types.swift | 1 | 5615 | //
// Primitive Types.swift
// SipHash
//
// Created by Károly Lőrentey on 2016-11-14.
// Copyright © 2016-2017 Károly Lőrentey.
//
extension SipHasher {
//MARK: Appending buffer slices
/// Add the contents of `slice` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ slice: Slice<UnsafeRawBufferPointer>) {
self.append(UnsafeRawBufferPointer(rebasing: slice))
}
//MARK: Appending Integers
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Bool) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Bool>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Int) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Int>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: UInt) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<UInt>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Int64) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Int64>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: UInt64) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<UInt64>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Int32) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Int32>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: UInt32) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<UInt32>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Int16) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Int16>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: UInt16) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<UInt16>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Int8) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Int8>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: UInt8) {
var data = value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<UInt8>.size))
}
}
extension SipHasher {
//MARK: Appending Floating Point Types
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Float) {
var data = value.isZero ? 0.0 : value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Float>.size))
}
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Double) {
var data = value.isZero ? 0.0 : value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<Double>.size))
}
#if arch(i386) || arch(x86_64)
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: Float80) {
var data = value.isZero ? 0.0 : value
// Float80 is 16 bytes wide but the last 6 are uninitialized.
let buffer = UnsafeRawBufferPointer(start: &data, count: 10)
append(buffer)
}
#endif
}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import CoreGraphics
extension SipHasher {
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append(_ value: CGFloat) {
var data = value.isZero ? 0.0 : value
append(UnsafeRawBufferPointer(start: &data, count: MemoryLayout<CGFloat>.size))
}
}
#endif
extension SipHasher {
//MARK: Appending Optionals
/// Add `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append<Value: Hashable>(_ value: Value?) {
if let value = value {
self.append(1 as UInt8)
self.append(value)
}
else {
self.append(0 as UInt8)
}
}
}
| mit | 28fc9f24145178d8621adbb1769c0135 | 31.807018 | 91 | 0.610339 | 4.214876 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/SetPinCode/SetupBiometrics/SetupBiometricsCoordinator.swift | 1 | 2859 | // File created from ScreenTemplate
// $ createScreen.sh SetPinCode/SetupBiometrics SetupBiometrics
/*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
final class SetupBiometricsCoordinator: SetupBiometricsCoordinatorType {
// MARK: - Properties
// MARK: Private
private let session: MXSession?
private var setupBiometricsViewModel: SetupBiometricsViewModelType
private let setupBiometricsViewController: SetupBiometricsViewController
private let viewMode: SetPinCoordinatorViewMode
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: SetupBiometricsCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession?, viewMode: SetPinCoordinatorViewMode, pinCodePreferences: PinCodePreferences = .shared) {
self.session = session
self.viewMode = viewMode
let setupBiometricsViewModel = SetupBiometricsViewModel(session: self.session, viewMode: viewMode, pinCodePreferences: pinCodePreferences)
let setupBiometricsViewController = SetupBiometricsViewController.instantiate(with: setupBiometricsViewModel)
self.setupBiometricsViewModel = setupBiometricsViewModel
self.setupBiometricsViewController = setupBiometricsViewController
}
// MARK: - Public methods
func start() {
self.setupBiometricsViewModel.coordinatorDelegate = self
}
func toPresentable() -> UIViewController {
return self.setupBiometricsViewController
}
}
// MARK: - SetupBiometricsViewModelCoordinatorDelegate
extension SetupBiometricsCoordinator: SetupBiometricsViewModelCoordinatorDelegate {
func setupBiometricsViewModelDidComplete(_ viewModel: SetupBiometricsViewModelType) {
self.delegate?.setupBiometricsCoordinatorDidComplete(self)
}
func setupBiometricsViewModelDidCompleteWithReset(_ viewModel: SetupBiometricsViewModelType, dueToTooManyErrors: Bool) {
self.delegate?.setupBiometricsCoordinatorDidCompleteWithReset(self, dueToTooManyErrors: dueToTooManyErrors)
}
func setupBiometricsViewModelDidCancel(_ viewModel: SetupBiometricsViewModelType) {
self.delegate?.setupBiometricsCoordinatorDidCancel(self)
}
}
| apache-2.0 | fce37a97d600653f188bb92ba70089db | 36.12987 | 146 | 0.757258 | 6.122056 | false | false | false | false |
lstomberg/swift-PerformanceTestKit | Tests/TestSupportTests.swift | 1 | 2905 | // MIT License
//
// Copyright (c) 2017 Lucas Stomberg
//
// 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 XCTest
class TestSupportTests: XCTestCase {
/*
* UNIQUE VARIABLES
*/
func test_stringUnique() {
var allString: [String] = [""]
for index in 0...1000 where index % 50 == 3 {
for length in 1...40 where length % 7 == 1 {
allString.append(Test.string(unique: index, length: length))
XCTAssertTrue(Test.string(unique: index, length: length) == Test.string(unique: index, length: length),
"Failed with unique \(index) and length \(length)")
}
}
XCTAssertTrue(allString.count == Set(allString).count, "Not all unique")
}
func test_intUnique() {
var allInt: [Int] = []
for index in 0...1000 where index % 51 == 7 {
allInt.append(Test.int(unique: index))
XCTAssertTrue(Test.int(unique: index) == Test.int(unique: index), "Failed with unique \(index)")
}
XCTAssertTrue(allInt.count == Set(allInt).count, "Not all unique")
}
func test_moduleUnique() {
var allModule: [Module] = []
for index in 0...1000 where index % 53 == 8 {
allModule.append(Test.module(unique: index, withSegment: false))
XCTAssertTrue(Test.module(unique: index, withSegment: false) == Test.module(unique: index, withSegment: false),
"Failed with unique \(index)")
}
for index in 0...1000 where index % 47 == 19 {
allModule.append(Test.module(unique: index, withSegment: true))
XCTAssertTrue(Test.module(unique: index, withSegment: true) == Test.module(unique: index, withSegment: true),
"Failed with unique \(index)")
}
XCTAssertTrue(allModule.count == Set(allModule).count, "Not all unique")
}
}
| mit | d04ca5e4f5a4e5c76422310e5791faff | 39.915493 | 120 | 0.656799 | 4.14408 | false | true | false | false |
Kofktu/KUIActionSheet | KUIActionSheet/Classes/KUIActionSheet.swift | 1 | 15042 | //
// KUIActionSheet.swift
// KUIActionSheet
//
// Created by kofktu on 2016. 7. 8..
// Copyright © 2016년 Kofktu. All rights reserved.
//
import UIKit
public protocol KUIActionSheetProtocol {
var backgroundColor: UIColor { get }
var showAnimationDuration: TimeInterval { get }
var dimissAnimationDuration: TimeInterval { get }
var blurEffectStyle: UIBlurEffect.Style { get }
var itemTheme: KUIActionSheetItemTheme { get }
}
public struct KUIActionSheetDefault: KUIActionSheetProtocol {
public var backgroundColor: UIColor {
return UIColor(white: 0.0, alpha: 0.4)
}
public var showAnimationDuration: TimeInterval {
return 0.25
}
public var dimissAnimationDuration: TimeInterval {
return 0.15
}
public var blurEffectStyle: UIBlurEffect.Style {
return .extraLight
}
public var itemTheme: KUIActionSheetItemTheme {
return KUIActionSheetItemDefaultTheme()
}
}
public protocol KUIActionSheetItemTheme {
var height: CGFloat { get }
var font: UIFont { get }
var titleColor: UIColor { get }
var destructiveTitleColor: UIColor { get }
}
public struct KUIActionSheetItemDefaultTheme: KUIActionSheetItemTheme {
public var height: CGFloat {
return 57.0
}
public var font: UIFont {
return UIFont.systemFont(ofSize: 20.0)
}
public var titleColor: UIColor {
return UIColor(red: 0/255.0, green: 118/255.0, blue: 255/255.0, alpha: 1.0)
}
public var destructiveTitleColor: UIColor {
return UIColor(red: 255/255.0, green: 69/255.0, blue: 57/255.0, alpha: 1.0)
}
}
public typealias KUIActionSheetItemAsyncTitleTask = (@escaping (String) -> Void) -> Void
public typealias KUIActionSheetItemHandler = (KUIActionSheetItem) -> Void
public struct KUIActionSheetItem {
public let title: String?
public let asyncTitle: KUIActionSheetItemAsyncTitleTask?
public let activityStyle: UIActivityIndicatorView.Style
public let destructive: Bool
public let handler: KUIActionSheetItemHandler?
public init(
title: String,
destructive: Bool = false,
handler: KUIActionSheetItemHandler?) {
self.title = title
self.asyncTitle = nil
self.activityStyle = .gray
self.destructive = destructive
self.handler = handler
}
public init(
asyncTitle: @escaping KUIActionSheetItemAsyncTitleTask,
activityStyle: UIActivityIndicatorView.Style = .gray,
destructive: Bool = false,
handler: KUIActionSheetItemHandler?) {
self.title = nil
self.asyncTitle = asyncTitle
self.activityStyle = activityStyle
self.destructive = destructive
self.handler = handler
}
}
public protocol KUIActionSheetItemViewProtocol {}
extension KUIActionSheetItemViewProtocol where Self: UIView {
public var actionSheet: KUIActionSheet? {
var responder: UIResponder? = self
while responder != nil {
if let sheet = responder as? KUIActionSheet {
return sheet
}
responder = responder?.next
}
return nil
}
}
public protocol KUIActionSheetNibLoadableView: class {
static var nibName: String { get }
}
extension KUIActionSheetNibLoadableView where Self: KUIActionSheet {
public static var nibName: String {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
public static func viewWithNib(parentViewController viewController: UIViewController, theme: KUIActionSheetProtocol? = nil) -> KUIActionSheetNibLoadableView? {
return viewWithNibName(nibFileName: nibName, parentViewController: viewController, theme: theme)
}
public static func viewWithNibName(nibFileName: String, parentViewController viewController: UIViewController, theme: KUIActionSheetProtocol?) -> KUIActionSheetNibLoadableView? {
guard let views = Bundle(for: self).loadNibNamed(nibFileName, owner: nil, options: nil) else { return nil }
let actionSheetTheme = theme ?? KUIActionSheetDefault()
for view in views {
if let view = view as? Self {
view.theme = actionSheetTheme
view.parentViewController = viewController
return view
}
}
return nil
}
}
private extension UIViewController {
var rootViewController: UIViewController {
var rootViewController: UIViewController = self
while let parentViewController = rootViewController.parent {
rootViewController = parentViewController
}
return rootViewController
}
}
open class KUIActionSheet: UIView {
@IBOutlet public weak var containerView: UIView!
@IBOutlet public weak var cancelButton: UIButton!
@IBOutlet public weak var cancelButtonBottom: NSLayoutConstraint!
open var theme: KUIActionSheetProtocol!
open var tapToDismiss: Bool = true
open fileprivate(set) var parentViewController: UIViewController!
fileprivate var showing: Bool = false
fileprivate var animating: Bool = false
fileprivate var lastViewBottom: NSLayoutConstraint?
public class func view(parentViewController viewController: UIViewController, theme: KUIActionSheetProtocol? = nil) -> KUIActionSheet? {
guard let views = Bundle(for: self).loadNibNamed("KUIActionSheet", owner: nil, options: nil) else { return nil }
let actionSheetTheme = theme ?? KUIActionSheetDefault()
for view in views {
if let view = view as? KUIActionSheet {
view.theme = actionSheetTheme
view.parentViewController = viewController
return view
}
}
return nil
}
convenience override init(frame: CGRect) {
fatalError("not support")
}
open override func awakeFromNib() {
super.awakeFromNib()
containerView.layer.cornerRadius = 8.0
cancelButton.layer.cornerRadius = 8.0
let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTap(_:)))
singleTap.delegate = self
addGestureRecognizer(singleTap)
}
open func show(viewController: UIViewController? = nil, completion: ((Bool) -> Void)? = nil) {
guard !showing else {
completion?(false)
return
}
let targetViewController: UIViewController = viewController ?? parentViewController.rootViewController
showing = true
animating = true
backgroundColor = theme.backgroundColor
targetViewController.view.endEditing(true)
translatesAutoresizingMaskIntoConstraints = false
targetViewController.view.addSubview(self)
targetViewController.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": self]))
targetViewController.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": self]))
let initialBottomSpace = cancelButtonBottom.constant
cancelButtonBottom.constant = -targetViewController.view.frame.height
layoutIfNeeded()
targetViewController.view.layoutIfNeeded()
cancelButtonBottom.constant = initialBottomSpace
UIView.animate(withDuration: theme.showAnimationDuration, delay: 0, options: UIView.AnimationOptions(rawValue: 7 << 16), animations: {
self.layoutIfNeeded()
}) { (finished) in
self.setAccessibility()
self.animating = false
completion?(finished)
}
}
open func dismiss(completion: ((Bool) -> Void)? = nil) {
guard showing else {
completion?(false)
return
}
showing = false
animating = true
isUserInteractionEnabled = false
cancelButtonBottom.constant = -parentViewController.rootViewController.view.frame.height
UIView.animate(withDuration: theme.dimissAnimationDuration, delay: 0, options: UIView.AnimationOptions(rawValue: 7 << 16), animations: {
self.backgroundColor = self.theme.backgroundColor.withAlphaComponent(0.0)
self.layoutIfNeeded()
}) { (finished) in
completion?(true)
self.animating = false
self.removeFromSuperview()
}
}
open func add(customView view: UIView?) {
if view?.translatesAutoresizingMaskIntoConstraints ?? false {
view?.translatesAutoresizingMaskIntoConstraints = false
if let view = view {
view.layoutIfNeeded()
view.addConstraint(NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: view.frame.height))
}
}
add(view: view)
}
open func add(item: KUIActionSheetItem) {
let itemTheme = theme.itemTheme
let button = KUIActionSheetItemButton.button(item)
button.titleLabel?.font = itemTheme.font
button.setTitleColor(item.destructive ? itemTheme.destructiveTitleColor : itemTheme.titleColor, for: [])
button.addConstraint(NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: itemTheme.height))
add(view: button)
}
fileprivate func add(view: UIView?) {
guard let view = view else { return }
let verticalGap = 1.0 / UIScreen.main.scale
let lastView = containerView.subviews.last
view.translatesAutoresizingMaskIntoConstraints = false
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: theme.blurEffectStyle))
visualEffectView.contentView.backgroundColor = UIColor.clear
visualEffectView.translatesAutoresizingMaskIntoConstraints = false
visualEffectView.contentView.addSubview(view)
visualEffectView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": view]))
visualEffectView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": view]))
containerView.addSubview(visualEffectView)
if let lastViewBottom = lastViewBottom {
containerView.removeConstraint(lastViewBottom)
self.lastViewBottom = nil
}
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": visualEffectView]))
if let lastView = lastView {
containerView.addConstraint(NSLayoutConstraint(item: visualEffectView, attribute: .top, relatedBy: .equal, toItem: lastView, attribute: .bottom, multiplier: 1.0, constant: verticalGap))
} else {
containerView.addConstraint(NSLayoutConstraint(item: visualEffectView, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1.0, constant: 0.0))
}
lastViewBottom = NSLayoutConstraint(item: visualEffectView, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1.0, constant: 0.0)
containerView.addConstraint(lastViewBottom!)
}
fileprivate func setAccessibility() {
guard UIAccessibility.isVoiceOverRunning else { return }
let itemButtons = containerView.subviews.compactMap { (view) -> UIView? in
return (view as? UIVisualEffectView)?.contentView.subviews.last
}
accessibilityElements = [itemButtons, cancelButton]
accessibilityViewIsModal = true
UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: self)
}
@objc internal func singleTap(_ gesture: UITapGestureRecognizer) {
guard !animating else { return }
guard gesture.location(in: self).y < containerView.frame.origin.y && tapToDismiss else { return }
dismiss()
}
@IBAction open func onClose(_ sender: UIButton) {
dismiss()
}
}
extension KUIActionSheet: UIGestureRecognizerDelegate {
// MARK: - UIGestureRecognizerDelegate
open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer.location(in: self).y < containerView.frame.origin.y else {
return false
}
return true
}
}
private class KUIActionSheetItemButton: UIButton, KUIActionSheetItemViewProtocol {
private lazy var activityView: UIActivityIndicatorView = {
let activityView = UIActivityIndicatorView(style: .gray)
activityView.translatesAutoresizingMaskIntoConstraints = false
return activityView
}()
private var item: KUIActionSheetItem! {
didSet {
updateItem()
}
}
class func button(_ item: KUIActionSheetItem) -> KUIActionSheetItemButton {
let button = KUIActionSheetItemButton(type: .custom)
button.initialized()
button.item = item
return button
}
// MARK: - Private
private func initialized() {
setupActivityView()
addTarget(self, action: #selector(onPressed(_:)), for: .touchUpInside)
}
private func setupActivityView() {
addSubview(activityView)
addConstraint(NSLayoutConstraint(item: activityView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0))
addConstraint(NSLayoutConstraint(item: activityView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0))
}
private func updateItem() {
if let title = item.title {
setTitle(title, for: [])
activityView.stopAnimating()
} else {
activityView.style = item.activityStyle
activityView.startAnimating()
item.asyncTitle? { [weak self] title in
self?.setTitle(title, for: [])
self?.activityView.stopAnimating()
}
}
}
// MARK: - Action
@objc func onPressed(_ sender: UIButton) {
item.handler?(item)
actionSheet?.dismiss()
}
}
| mit | 9d8179b2ef27e4637ee51d40cab9e3dd | 36.5975 | 211 | 0.660084 | 5.297288 | false | false | false | false |
chordsNcode/jsonperf | JsonPerf/FreddyImplementation.swift | 1 | 5704 | //
// File.swift
// JsonPerf
//
// Created by Matt Dias on 9/21/16.
//
import Foundation
import Freddy
/// Parsing a Github repo object using Freddy (https://github.com/bignerdranch/Freddy)
extension Repo: JSONDecodable {
public init(json value: JSON) throws {
self.id = try value.getInt(at: "id")
self.name = try value.getString(at: "name")
self.fullName = try value.getString(at: "full_name")
self.isPrivate = try value.getBool(at: "private")
self.htmlUrl = try value.getString(at: "html_url")
self.description = try value.getString(at: "description")
self.isForked = try value.getBool(at: "fork")
self.url = try value.getString(at: "url")
self.forksUrl = try value.getString(at: "forks_url")
self.keysUrl = try value.getString(at: "keys_url")
self.collaboratorsUrl = try value.getString(at: "collaborators_url")
self.teamsUrl = try value.getString(at: "teams_url")
self.hooksUrl = try value.getString(at: "hooks_url")
self.issueEventsUrl = try value.getString(at: "issue_events_url")
self.eventsUrl = try value.getString(at: "events_url")
self.assigneesUrl = try value.getString(at: "assignees_url")
self.branchesUrl = try value.getString(at: "branches_url")
self.tagsUrl = try value.getString(at: "tags_url")
self.blobsUrl = try value.getString(at: "blobs_url")
self.gitTagsUrls = try value.getString(at: "git_tags_url")
self.gitRefsUrl = try value.getString(at: "git_refs_url")
self.treesUrl = try value.getString(at: "trees_url")
self.statusesUrl = try value.getString(at: "statuses_url")
self.languagesUrl = try value.decode(at: "languages_url")
self.stargazersUrl = try value.getString(at: "stargazers_url")
self.contributorsUrl = try value.getString(at: "contributors_url")
self.subscribersUrl = try value.getString(at: "subscribers_url")
self.subscriptionUrl = try value.getString(at: "subscription_url")
self.commitsUrl = try value.getString(at: "commits_url")
self.gitCommitsUrl = try value.getString(at: "git_commits_url")
self.commentsUrl = try value.getString(at: "comments_url")
self.issueCommentUrl = try value.getString(at: "issue_comment_url")
self.contentsUrl = try value.getString(at: "contents_url")
self.compareUrl = try value.getString(at: "compare_url")
self.mergesUrl = try value.getString(at: "merges_url")
self.archiveUrl = try value.getString(at: "archive_url")
self.downloadsUrl = try value.getString(at: "downloads_url")
self.issuesUrl = try value.getString(at: "issues_url")
self.pullsUrl = try value.getString(at: "pulls_url")
self.milestonesUrl = try value.getString(at: "milestones_url")
self.notificationsUrl = try value.getString(at: "notifications_url")
self.labelsUrl = try value.getString(at: "labels_url")
self.releasesUrl = try value.getString(at: "releases_url")
self.deploymentsUrl = try value.getString(at: "deployments_url")
self.createdAt = try value.getString(at: "created_at")
self.updatedAt = try value.getString(at: "updated_at")
self.pushedAt = try value.getString(at: "pushed_at")
self.gitUrl = try value.getString(at: "git_url")
self.sshUrl = try value.getString(at: "ssh_url")
self.cloneUrl = try value.getString(at: "clone_url")
self.svnUrl = try value.getString(at: "svn_url")
self.size = try value.getInt(at: "size")
self.stargazersCount = try value.getInt(at: "stargazers_count")
self.watchersCount = try value.getInt(at: "watchers_count")
self.language = try value.getString(at: "language")
self.hasIssues = try value.getBool(at: "has_issues")
self.hasPages = try value.getBool(at: "has_pages")
self.forksCount = try value.getInt(at: "forks_count")
self.openIssues = try value.getInt(at: "open_issues")
self.watchers = try value.getInt(at: "watchers")
self.defaultBranch = try value.getString(at: "default_branch")
self.score = try value.getInt(at: "score")
let ownerJson = try JSON(value.getDictionary(at: "owner"))
self.owner = try Owner(json: ownerJson)
self.mirrorUrl = try value.getString(at: "mirror_url", alongPath: .NullBecomesNil)
self.homepage = try value.getString(at: "homepage", alongPath: .NullBecomesNil)
}
}
extension Owner: JSONDecodable {
public init(json value: JSON) throws {
self.login = try value.getString(at: "login")
self.id = try value.getInt(at: "id")
self.avatarUrl = try value.getString(at: "avatar_url")
self.url = try value.getString(at: "url")
self.htmlUrl = try value.getString(at: "html_url")
self.followersUrl = try value.getString(at: "followers_url")
self.followingUrl = try value.getString(at: "following_url")
self.gistsUrl = try value.getString(at: "gists_url")
self.starredUrl = try value.getString(at: "starred_url")
self.subscriptionsUrl = try value.getString(at: "subscriptions_url")
self.organizationsUrl = try value.getString(at: "organizations_url")
self.reposUrl = try value.getString(at: "repos_url")
self.eventsUrl = try value.getString(at: "events_url")
self.receivedEventsUrls = try value.getString(at: "received_events_url")
self.type = try value.getString(at: "type")
self.siteAdmin = try value.getBool(at: "site_admin")
self.gravatarId = try value.getString(at: "gravatar_id", alongPath: .NullBecomesNil)
}
}
| mit | 03c27ca4e610597d99be7039d41c8395 | 51.330275 | 92 | 0.660063 | 3.571697 | false | false | false | false |
liukunpengiOS/PaperHouse | Unite/Easing/PHEasingValue.swift | 1 | 3246 | //
// PHEasingValue.swift
// PaperHouse
//
// Created by kunpeng on 2017/6/18.
// Copyright © 2017年 liukunpeng. All rights reserved.
//
import UIKit
class EasingValue: NSObject {
// MARK: var
/// 动画函数
var function : EasingFunction!
/// 关键帧点数
var frameCount : size_t!
// MARK: init
override init() {
super.init()
function = EasingFunction.sineEaseIn
frameCount = 60
}
init(withFunction : EasingFunction, frameCount : size_t) {
super.init()
self.function = withFunction
self.frameCount = frameCount
}
// MARK: func
/**
计算关键帧
- parameter fromValue: 起始值
- parameter toValue: 结束值
- returns: 关键帧值数组
*/
func frameValueWith(fromValue : Double, toValue : Double) -> [AnyObject] {
let values = NSMutableArray(capacity: frameCount)
var t : Double = 0.0
let dt : Double = 1.0 / (Double(frameCount) - 1)
for _ in 0 ..< frameCount {
let value = fromValue + (function.value())(t) * (toValue - fromValue)
values.add(value)
t += dt
}
return values as [AnyObject]
}
/**
计算关键帧点
- parameter fromPoint: 起始点
- parameter toPoint: 结束点
- returns: 关键帧点数组
*/
func pointValueWith(fromPoint : CGPoint, toPoint : CGPoint) -> [AnyObject] {
let values = NSMutableArray(capacity: frameCount)
var t : Double = 0.0
let dt : Double = 1.0 / (Double(frameCount) - 1)
for _ in 0 ..< frameCount {
let x : Double = Double(fromPoint.x) + (function.value())(t) * (Double(toPoint.x) - Double(fromPoint.x))
let y : Double = Double(fromPoint.y) + (function.value())(t) * (Double(toPoint.y) - Double(fromPoint.y))
let point : CGPoint = CGPoint(x : x, y : y)
values.add(NSValue(cgPoint: point))
t += dt
}
return values as [AnyObject]
}
/**
计算关键帧尺寸
- parameter fromSize: 起始尺寸
- parameter toSize: 结束尺寸
- returns: 关键帧尺寸数组
*/
func sizeValueWith(fromSize : CGSize, toSize : CGSize) -> [AnyObject] {
let values = NSMutableArray(capacity: frameCount)
var t : Double = 0.0
let dt : Double = 1.0 / (Double(frameCount) - 1)
for _ in 0 ..< frameCount {
let width : Double = Double(fromSize.width) + (function.value())(t) * (Double(toSize.width) - Double(fromSize.width))
let height : Double = Double(fromSize.height) + (function.value())(t) * (Double(toSize.height) - Double(fromSize.height))
let size : CGSize = CGSize(width: width, height: height)
values.add(NSValue(cgSize : size))
t += dt
}
return values as [AnyObject]
}
}
| mit | 0040cd92ab57a511889a2ad7a3d95802 | 24.5 | 133 | 0.507875 | 4.204054 | false | false | false | false |
airspeedswift/swift | test/IRGen/prespecialized-metadata/enum-inmodule-4argument-1distinct_use.swift | 3 | 6779 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueOyS4iGWV" = linkonce_odr hidden constant %swift.enum_vwtable {
// CHECK-SAME: i8* bitcast ({{([^@]+@"\$s4main5ValueOyS4iGwCP+[^\)]+ to i8\*|[^@]+@__swift_memcpy[0-9]+_[0-9]+[^\)]+ to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_noop_void_return{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS4iGwet{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS4iGwst{{[^)]+}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS4iGwug{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS4iGwup{{[^)]+}} to i8*),
// CHECK-SAME i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS4iGwui{{[^)]+}} to i8*)
// CHECK-SAME: }, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueOyS4iGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5ValueOyS4iGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: [[INT]] {{32|16}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Value<First, Second, Third, Fourth> {
case first(First)
case second(First, Second)
case third(First, Second, Third)
case fourth(First, Second, Third, Fourth)
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOyS4iGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Value.fourth(13, 14, 15, 16) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, i8** %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_BUFFER:%[0-9]+]] = bitcast i8** %1 to i8*
// CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_1]]:
// CHECK: [[ERASED_TYPE_ADDRESS_1:%[0-9]+]] = getelementptr i8*, i8** %1, i64 0
// CHECK: [[ERASED_TYPE_1:%\".*\"]] = load i8*, i8** [[ERASED_TYPE_ADDRESS_1]]
// CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]]
// CHECK: [[ERASED_TYPE_ADDRESS_2:%[0-9]+]] = getelementptr i8*, i8** %1, i64 1
// CHECK: [[ERASED_TYPE_2:%\".*\"]] = load i8*, i8** [[ERASED_TYPE_ADDRESS_2]]
// CHECK: [[EQUAL_TYPE_1_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_1_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_1]], [[EQUAL_TYPE_1_2]]
// CHECK: [[ERASED_TYPE_ADDRESS_3:%[0-9]+]] = getelementptr i8*, i8** %1, i64 2
// CHECK: [[ERASED_TYPE_3:%\".*\"]] = load i8*, i8** [[ERASED_TYPE_ADDRESS_3]]
// CHECK: [[EQUAL_TYPE_1_3:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_3]]
// CHECK: [[EQUAL_TYPES_1_3:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_2]], [[EQUAL_TYPE_1_3]]
// CHECK: [[ERASED_TYPE_ADDRESS_4:%[0-9]+]] = getelementptr i8*, i8** %1, i64 3
// CHECK: [[ERASED_TYPE_4:%\".*\"]] = load i8*, i8** [[ERASED_TYPE_ADDRESS_4]]
// CHECK: [[EQUAL_TYPE_1_4:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_4]]
// CHECK: [[EQUAL_TYPES_1_4:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_3]], [[EQUAL_TYPE_1_4]]
// CHECK: br i1 [[EQUAL_TYPES_1_4]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED_1]]:
// CHECK: ret %swift.metadata_response {
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOyS4iGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] 0
// CHECK-SAME: }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @swift_getGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_BUFFER]],
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | a330f8e8cc642cd79f4fc8bec68b6ef7 | 47.078014 | 157 | 0.546098 | 2.800083 | false | false | false | false |
Alloc-Studio/Hypnos | Hypnos/Hypnos/Controller/Heart/TodayHeartRateViewController.swift | 1 | 1757 | //
// TodayHeartRateViewController.swift
// Hypnos
//
// Created by Fay on 16/5/25.
// Copyright © 2016年 DMT312. All rights reserved.
//
import UIKit
import PNChart
class TodayHeartRateViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var sleepTime: UILabel!
@IBOutlet weak var averRate: UILabel!
var dataArr:[UInt32] = []
override func viewDidLoad() {
super.viewDidLoad()
drawLine()
averRate.text = "\(arc4random_uniform(70)+60)Bmp"
sleepTime.text = randomTime()
}
// 画折线图
func drawLine() {
let lineChart = PNLineChart(frame: self.containerView.bounds)
lineChart.showCoordinateAxis = true
lineChart.axisColor = UIColor.grayColor()
lineChart.setXLabels(["3","6","9","12","15","18","21","24"], withWidth: 40)
for _ in 0..<8 {
let random = (arc4random_uniform(90)+60)
dataArr.append(random)
}
let data = PNLineChartData()
data.color = HypnosConfig.DefaultThemeColor
data.itemCount = (UInt)(dataArr.count)
data.showPointLabel = false
data.getData = ({(index:UInt)->PNLineChartDataItem in
let y:CGFloat = (CGFloat)(self.dataArr[(Int)(index)])
return PNLineChartDataItem(y: y)
})
lineChart.chartData = [data]
lineChart.strokeChart()
containerView.addSubview(lineChart)
}
}
// 睡眠时间
private func randomTime() -> String {
let random = arc4random_uniform(360)+240
let hour = random / 60
let min = random % 60
return "\(hour)小时\(min)分"
}
| mit | 10cb3843afd90698d7cb61b87df70755 | 24.470588 | 83 | 0.586028 | 4.234719 | false | false | false | false |
AlexHmelevski/AHFuture | Example/Pods/EitherResult/ALResult/Classes/ALResultEquatable.swift | 1 | 835 | //
// ALResult_Equatable.swift
// ALResult
//
// Created by Piyush Sharma on 2019-03-20.
//
import Foundation
extension ALResult: Equatable where R: Equatable {
public static func == (lhs: ALResult<R>, rhs: ALResult<R>) -> Bool {
switch (lhs, rhs) {
case let (.right(valL), .right(valR)): return valL == valR
case let (.wrong(errorL), .wrong(errorR)): return errorL.localizedDescription == errorR.localizedDescription
default: return false
}
}
public static func != (lhs: ALResult<R>, rhs: ALResult<R>) -> Bool {
switch (lhs, rhs) {
case let (.right(valL), .right(valR)): return valL != valR
case let (.wrong(errorL), .wrong(errorR)): return errorL.localizedDescription != errorR.localizedDescription
default: return false
}
}
}
| mit | 19bac1e4f262c75a262ea210a707c41a | 31.115385 | 116 | 0.620359 | 3.69469 | false | false | false | false |
corinnekrych/aerogear-ios-sync | AeroGearSync/ClientSyncEngine.swift | 2 | 5621 | import Foundation
/**
The client side implementation of a Differential Synchronization Engine.
*/
public class ClientSyncEngine<CS:ClientSynchronizer, D:DataStore where CS.T == D.T> {
typealias T = CS.T
let synchronizer: CS
let dataStore: D
var callbacks = Dictionary<String, (ClientDocument<T>) -> ()>()
public init(synchronizer: CS, dataStore: D) {
self.synchronizer = synchronizer
self.dataStore = dataStore
}
public func addDocument(clientDocument: ClientDocument<T>, callback: ClientDocument<T> -> ()) {
dataStore.saveClientDocument(clientDocument)
let shadow = ShadowDocument(clientVersion: 0, serverVersion: 0, clientDocument: clientDocument)
dataStore.saveShadowDocument(shadow)
dataStore.saveBackupShadowDocument(BackupShadowDocument(version: 0, shadowDocument: shadow))
callbacks[clientDocument.id] = callback
}
public func diff(clientDocument: ClientDocument<T>) -> PatchMessage? {
if let shadow = dataStore.getShadowDocument(clientDocument.id, clientId: clientDocument.clientId) {
let edit = diffAgainstShadow(clientDocument, shadow: shadow)
dataStore.saveEdits(edit)
let patched = synchronizer.patchShadow(edit, shadow: shadow)
dataStore.saveShadowDocument(incrementClientVersion(patched))
let edits = dataStore.getEdits(clientDocument.id, clientId: clientDocument.clientId)
return PatchMessage(id: clientDocument.id, clientId: clientDocument.clientId, edits: edits!)
}
return Optional.None
}
public func patch(patchMessage: PatchMessage) {
if let patched = patchShadow(patchMessage) {
let callback = callbacks[patchMessage.documentId]!
callback(patchDocument(patched)!)
dataStore.saveBackupShadowDocument(BackupShadowDocument(version: patched.clientVersion, shadowDocument: patched))
}
}
private func patchShadow(patchMessage: PatchMessage) -> ShadowDocument<T>? {
if var shadow = dataStore.getShadowDocument(patchMessage.documentId, clientId: patchMessage.clientId) {
for edit in patchMessage.edits {
if (edit.clientVersion < shadow.clientVersion && !self.isSeedVersion(edit)) {
shadow = restoreBackup(shadow, edit: edit)!
continue
}
if edit.serverVersion < shadow.serverVersion {
dataStore.removeEdit(edit)
continue
}
if edit.serverVersion == shadow.serverVersion && edit.clientVersion == shadow.clientVersion || isSeedVersion(edit) {
let patched = synchronizer.patchShadow(edit, shadow: shadow)
dataStore.removeEdit(edit)
if isSeedVersion(edit) {
shadow = saveShadow(seededShadowDocument(patched))
} else {
shadow = saveShadow(incrementServerVersion(patched))
}
}
}
return shadow
}
return Optional.None
}
private func seededShadowDocument(from: ShadowDocument<T>) -> ShadowDocument<T> {
return ShadowDocument(clientVersion: 0, serverVersion: from.serverVersion, clientDocument: from.clientDocument)
}
private func incrementClientVersion(shadow: ShadowDocument<T>) -> ShadowDocument<T> {
return ShadowDocument(clientVersion: shadow.clientVersion + 1, serverVersion: shadow.serverVersion, clientDocument: shadow.clientDocument)
}
private func incrementServerVersion(shadow: ShadowDocument<T>) -> ShadowDocument<T> {
return ShadowDocument(clientVersion: shadow.clientVersion, serverVersion: shadow.serverVersion + 1, clientDocument: shadow.clientDocument)
}
private func saveShadow(shadow: ShadowDocument<T>) -> ShadowDocument<T> {
dataStore.saveShadowDocument(shadow)
return shadow
}
private func restoreBackup(shadow: ShadowDocument<T>, edit: Edit) -> ShadowDocument<T>? {
if let backup = dataStore.getBackupShadowDocument(edit.documentId, clientId: edit.clientId) {
if edit.clientVersion == backup.version {
let patchedShadow = synchronizer.patchShadow(edit, shadow: ShadowDocument(clientVersion: shadow.clientVersion, serverVersion: shadow.serverVersion, clientDocument: shadow.clientDocument))
dataStore.removeEdits(edit.documentId, clientId: edit.clientId)
dataStore.saveShadowDocument(patchedShadow)
return patchedShadow
}
}
return Optional.None
}
private func isSeedVersion(edit: Edit) -> Bool {
return edit.clientVersion == -1
}
private func diffAgainstShadow(clientDocument: ClientDocument<T>, shadow: ShadowDocument<T>) -> Edit {
return synchronizer.serverDiff(clientDocument, shadow: shadow)
}
private func patchDocument(shadow: ShadowDocument<T>) -> ClientDocument<T>? {
if let document = dataStore.getClientDocument(shadow.clientDocument.id, clientId: shadow.clientDocument.clientId) {
let edit = synchronizer.clientDiff(document, shadow: shadow)
let patched = synchronizer.patchDocument(edit, clientDocument: document)
dataStore.saveClientDocument(patched)
dataStore.saveBackupShadowDocument(BackupShadowDocument(version: shadow.clientVersion, shadowDocument: shadow))
return patched
}
return Optional.None
}
}
| apache-2.0 | 91ff79a5d6d9d3bd1a8c09987bfaad2a | 45.454545 | 203 | 0.669454 | 4.837349 | false | false | false | false |
ssnhitfkgd/baseProject | BaseProject/Classes/Request/FileClient.swift | 1 | 1490 | //
// FileClient.swift
// BaseProject
//
// Created by wangyong on 15/2/3.
// Copyright (c) 2015年 wang yong. All rights reserved.
//
import UIKit
class FileClient: RequestConfig {
var _networking_state : Int = 0;
class var shareInstance: FileClient {
get {
struct Static {
static var instance: FileClient? = nil
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token, {
Static.instance = FileClient()
})
return Static.instance!
}
}
override init() {
super.init()
let reachability = Reachability.reachabilityForInternetConnection()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
reachability.startNotifier()
}
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as Reachability
if reachability.isReachable() {
if reachability.isReachableViaWiFi() {
_networking_state = 0
println("Reachable via WiFi")
} else {
_networking_state = 1
println("Reachable via Cellular")
}
} else {
_networking_state = 2
println("Not reachable")
}
}
}
| unlicense | faaa7ca2b38b677a5a472e8fcb892890 | 25.571429 | 157 | 0.549059 | 5.333333 | false | false | false | false |
tscholze/nomster-ios | Nomster/ListViewController.swift | 1 | 3842 | //
// ListViewController.swift
// Nomster
//
// Created by Tobias Scholze on 24.02.15.
// Copyright (c) 2015 Tobias Scholze. All rights reserved.
//
import UIKit
class ListViewcontroller: UITableViewController {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
// Setup table view
refreshControl = UIRefreshControl()
refreshControl!.attributedTitle = NSAttributedString(string: "Pull to update")
refreshControl!.addTarget(self, action: "updateListViewDataSource:", forControlEvents: UIControlEvents.ValueChanged)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.toolbarHidden = true
self.tabBarController?.tabBar.hidden = false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "showSuggestion") {
let vc = segue.destinationViewController as! DetailViewController
let index = tableView.indexPathForSelectedRow()
vc.suggestion = appDelegate.suggestions.objectAtIndex(index!.row) as! Suggestion
}
}
// MARK: - Helper
func updateListViewDataSource(sender:AnyObject) -> Void {
appDelegate.setSuggestionsByRemoteDataSource()
tableView.reloadData()
refreshControl?.endRefreshing()
}
}
// MARK: - UITableViewDelegate
extension ListViewcontroller: UITableViewDelegate {
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle,
forRowAtIndexPath indexPath: NSIndexPath) {
// Required for the following methods
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
let selectedSuggestion = appDelegate.suggestions.objectAtIndex(indexPath.row) as! Suggestion
let titleShareButton = selectedSuggestion.isSubscribed ? "Unsubscribe" : "Subscribe"
var subscribeAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: titleShareButton , handler: {
(action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
selectedSuggestion.isSubscribed = !selectedSuggestion.isSubscribed
// TODO: send update to the server
self.tableView.editing = false
})
subscribeAction.backgroundColor = UIColor.grayColor()
var deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete" , handler: {
(action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
self.appDelegate.suggestions.removeObject(selectedSuggestion)
self.tableView.reloadData()
// TODO: send update to the server
self.tableView.editing = false
})
return [subscribeAction,deleteAction]
}
}
// MARK: - UITableViewDataSource
extension ListViewcontroller: UITableViewDataSource {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return appDelegate.suggestions.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as! SuggestionTableViewCell
let currentSuggestion: Suggestion = appDelegate.suggestions.objectAtIndex(indexPath.row) as! Suggestion
cell.useSuggestion(currentSuggestion)
return cell
}
}
| mit | ec5fbacac05213f745716bb337e7a8ea | 37.808081 | 129 | 0.69443 | 5.874618 | false | false | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/optionset/main.swift | 1 | 1977 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
import Foundation
struct Options : OptionSet {
let rawValue: Int
}
struct ComputedOptions : OptionSet {
init(rawValue: Int) { storedValue = rawValue }
let storedValue: Int
var rawValue: Int {
get { return storedValue }
}
}
func use<T>(_ t: T) {}
func main() {
var user_option = Options(rawValue: 123456)
var computed_option = ComputedOptions(rawValue: 789)
var sdk_option_exhaustive: NSBinarySearchingOptions = [.firstEqual, .insertionIndex]
var sdk_option_nonexhaustive = NSBinarySearchingOptions(rawValue: 257)
var sdk_option_nonevalid = NSBinarySearchingOptions(rawValue: 12)
use((user_option, computed_option, // break here
sdk_option_exhaustive, sdk_option_nonexhaustive,
sdk_option_nonevalid)) //%self.expect('frame variable user_option', substrs=['rawValue = 123456'])
//%self.expect('frame variable computed_option', substrs=['storedValue', '789'])
//%self.expect('expression user_option', substrs=['rawValue = 123456'])
//%self.expect('frame variable sdk_option_exhaustive', substrs=['[.firstEqual, .insertionIndex]'])
//%self.expect('expression sdk_option_exhaustive', substrs=['[.firstEqual, .insertionIndex]'])
//%self.expect('frame variable sdk_option_nonexhaustive', substrs=['[.firstEqual, 0x1]'])
//%self.expect('expression sdk_option_nonexhaustive', substrs=['[.firstEqual, 0x1]'])
//%self.expect('frame variable sdk_option_nonevalid', substrs=['rawValue = 12'])
//%self.expect('expression sdk_option_nonevalid', substrs=['rawValue = 12'])
}
main()
| apache-2.0 | 91ed1ffbdd9e1a4f2d054cd7a48f044e | 41.06383 | 104 | 0.691452 | 3.961924 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Tests/Mocks/MockUser+Convenience.swift | 1 | 2810 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
/**
* A class that facilitates writing snapshot tests with mock users.
*
* It allows you to create team and non-team users with appropriate initial
* parameters.
*/
extension MockUser {
/**
* Creates a self-user with the specified name and team membership.
* - parameter name: The name of the user.
* - parameter teamID: The ID of the team of the user, or `nil` if they're not on a team.
* - returns: A configured mock user object to use as a self-user.
* - note: The accent color of a self user is red by default.
*/
static func createSelfUser(name: String, inTeam teamID: UUID?) -> MockUser {
let user = MockUser()
user.name = name
user.displayName = name
user.initials = PersonName.person(withName: name, schemeTagger: nil).initials
user.isSelfUser = true
user.isTeamMember = teamID != nil
user.teamIdentifier = teamID
user.teamRole = teamID != nil ? .member : .none
user.accentColorValue = .vividRed
user.remoteIdentifier = UUID()
return user
}
/**
* Creates a connected user with the specified name and team membership.
* - parameter name: The name of the user.
* - parameter teamID: The ID of the team of the user, or `nil` if they're not on a team.
* - returns: A configured mock user object to use as a user the self-user can interact with.
* - note: The accent color of a self user is orange by default.
*/
static func createConnectedUser(name: String, inTeam teamID: UUID?) -> MockUser {
let user = MockUser()
user.name = name
user.displayName = name
user.initials = PersonName.person(withName: name, schemeTagger: nil).initials
user.isConnected = true
user.isTeamMember = teamID != nil
user.teamIdentifier = teamID
user.teamRole = teamID != nil ? .member : .none
user.accentColorValue = .brightOrange
user.emailAddress = teamID != nil ? "[email protected]" : nil
user.remoteIdentifier = UUID()
return user
}
}
| gpl-3.0 | f79f7dc6ee907f9a56e83838d82a514f | 36.466667 | 97 | 0.666192 | 4.219219 | false | false | false | false |
rastogigaurav/mTV | mTV/mTV/General/Constants.swift | 1 | 1155 | //
// Constants.swift
// mTV
//
// Created by Gaurav Rastogi on 6/22/17.
// Copyright © 2017 Gaurav Rastogi. All rights reserved.
//
import UIKit
let apiKey:String = "bbef065ad8676ba25e11a5daaa10a6aa"
let baseUrl:String = "https://api.themoviedb.org"
let imageBaseUrl:String = "https://image.tmdb.org/t/"
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
let aspectHeight = 225
let aspectWidth = 150
let expectedPosterWidthForCell = Int((screenWidth-35)/2)
let expectedPosterHeightForCell = (aspectHeight * expectedPosterWidthForCell)/aspectWidth
let maximumRowsInSectionOnHomePage = 6
let years_1950_2017:[Int] = [1950,1951,1952,1952,1954,1955,1955,1957,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,1969,1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017
]
let menuRevealWidth : CGFloat = (screenWidth*4)/5 //menu view will always cover 4/5th part of total screen
let pageSize = 20
| mit | 4e296ec7d80e9acf7baf06ef22b8ec08 | 36.225806 | 368 | 0.774697 | 3.005208 | false | false | false | false |
the-grid/Disc | Disc/Models/Provider.swift | 1 | 419 | import Argo
import Ogra
/// An identity provider.
public enum Provider: String {
case Facebook = "facebook"
case Google = "google"
case GitHub = "github"
case GitHubPublic = "github_public"
case GitHubPrivate = "github_private"
case Twitter = "twitter"
case Email = "email"
}
// Mark: - Decodable
extension Provider: Decodable {}
// Mark: - Encodable
extension Provider: Encodable {}
| mit | 5afb55fafe97fd62ab36a8bf58547601 | 17.217391 | 41 | 0.673031 | 3.990476 | false | false | false | false |
iosdevelopershq/Camille | Sources/CamilleServices/Swift/SwiftService.swift | 1 | 3051 | import Foundation
import Chameleon
struct CodeMatcher: Matcher {
func match(against input: String) -> Match? {
guard input.hasPrefix("`") && input.hasSuffix("`") else { return nil }
let code = input.trim(characters: ["`"]).stringByDecodingHTMLEntities
guard !code.isEmpty else { return nil }
return Match(key: nil, value: code, matched: input)
}
var matcherDescription: String {
return "(code)"
}
}
public class SwiftService: SlackBotMessageService, HelpRepresentable {
private let network: Network
private let token: String
public let topic = "Swift Code"
public let description = "Execute some Swift code and see the result"
public let pattern: [Matcher] = [["execute", "run"].any, "\n".orNone, CodeMatcher().using(key: Keys.code)]
enum Keys {
static let code = "code"
}
public init(network: Network, token: String) {
self.network = network
self.token = token
}
public func configure(slackBot: SlackBot) {
slackBot.registerHelp(item: self)
configureMessageService(slackBot: slackBot)
}
public func onMessage(slackBot: SlackBot, message: MessageDecorator, previous: MessageDecorator?) throws {
try slackBot.route(message, matching: self) { bot, msg, match in
let result = try request(code: match.value(key: Keys.code))
let response = try msg.respond()
response.text(["Output:"]).newLine()
if !result.stderr.isEmpty {
response.text([result.stderr.pre])
} else {
response.text([result.stdout.quote])
}
try bot.send(response.makeChatMessage())
}
}
private func request(code: String) throws -> GlotResponse {
let body: [String: Any] = [
"files": [
[
"name": "main.swift",
"content": code,
]
]
]
let request = NetworkRequest(
method: .POST,
url: "https://run.glot.io/languages/swift/latest",
headers: [
"Authorization": "Token \(token)",
"Content-type": "application/json",
],
body: body.makeData()
)
let response = try network.perform(request: request)
guard let json = response.jsonDictionary
else { throw NetworkError.invalidResponse(response) }
let decoder = Decoder(data: json)
return try GlotResponse(decoder: decoder)
}
}
private struct GlotResponse {
let stdout: String
let stderr: String
let error: String
}
extension GlotResponse: Common.Decodable {
init(decoder: Common.Decoder) throws {
self = try decode {
return GlotResponse(
stdout: try decoder.value(at: ["stdout"]),
stderr: try decoder.value(at: ["stderr"]),
error: try decoder.value(at: ["error"])
)
}
}
}
| mit | 3db755d74ec892927cab346cbc01ce97 | 28.057143 | 110 | 0.572927 | 4.486765 | false | false | false | false |
grantmagdanz/SnapBoard | Keyboard/SnapBoard.swift | 1 | 6147 | //
// Snapboard.swift
//
// Created by Grant Magdanz on 9/24/15.
// Copyright (c) 2015 Apple. All rights reserved.
//
import UIKit
class Snapboard: KeyboardViewController {
let CONTEXT_BEFORE_INSERTION_KEY = "contextBefore"
let ATTEMPTED_CHARACTER_KEY = "attemptedCharacter"
let AUTOWRAP_WAIT_TIME = 0.05
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
NSUserDefaults.standardUserDefaults()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func contextChanged() {
self.setCapsIfNeeded()
if let context = self.textDocumentProxy.documentContextBeforeInput {
if context[context.endIndex.predecessor()] == " " {
self.autoPeriodState = .FirstSpace
return
}
}
self.autoPeriodState = .NoSpace
}
override func keyPressed(key: Key) {
let textDocumentProxy = self.textDocumentProxy
let keyOutput = key.outputForCase(self.shiftState.uppercase())
let contextBeforeTextInsertionOpt = textDocumentProxy.documentContextBeforeInput
if key.type == .Return && contextBeforeTextInsertionOpt != nil && contextBeforeTextInsertionOpt!.characters.last == " " {
self.textDocumentProxy.deleteBackward()
}
self.textDocumentProxy.insertText(keyOutput)
if key.type == .Character || key.type == .SpecialCharacter || key.type == .Period || key.type == .Space {
if let contextBeforeTextInsertion = contextBeforeTextInsertionOpt {
// The Snapchat app itself is stopping extra characters from being added. Calling documentContextBeforeInput after a textInsert makes it appear that the character was inserted correctly even if it was not inserted at all (at least from the view of the Snapchat user). So in order to see if we need to autowrap, a brief timer is put onto the call to let Snapchat do its thing and then we test if the character was actually added.
NSTimer.scheduledTimerWithTimeInterval(AUTOWRAP_WAIT_TIME, target: self, selector: "autoWrapIfNeeded:", userInfo: [CONTEXT_BEFORE_INSERTION_KEY: contextBeforeTextInsertion, ATTEMPTED_CHARACTER_KEY: keyOutput], repeats: false)
}
}
}
/* PRE: This method assumes a few things!
1) timer.userInfo is a [String: String]
2) timer.userInfo[CONTEXT_BEFORE_INSERTION_KEY] != nil
3) timer.userInfo[ATTEMPTED_CHARACTER_KEY] != nil
This will crash if any of those are violated
This is kind of jenky and is tied to a scheduledTiemrWithTimeInterval call at the time of writing this. It tests if the previous character was infact inserted into the documentProxy and, if not, adds in a new line and the character.
Used for autowrapping in Snapchat.
*/
func autoWrapIfNeeded(timer: NSTimer) {
if !NSUserDefaults.standardUserDefaults().boolForKey(kWrapLines) {
return
}
let userInfo = timer.userInfo as! [String: String]
let contextBeforeTextInsertion = userInfo[CONTEXT_BEFORE_INSERTION_KEY]!
if let contextAfterTextInsertion = self.textDocumentProxy.documentContextBeforeInput {
if contextBeforeTextInsertion == contextAfterTextInsertion {
// the character was not added. Add in a new line and the character.
let typedCharacter = userInfo[ATTEMPTED_CHARACTER_KEY]!
self.autoWrappedMidSentence = !isFirstWord()
// if the previous character was a space, we just want to add in the new line and the character without wrapping a word
var positionAdjustment = 0
if contextBeforeTextInsertion.characters.last! != " " {
// we need to wrap a word!
let words = contextBeforeTextInsertion.characters.split{$0 == " "}.map(String.init)
let lastWord = words.last!
positionAdjustment = lastWord.characters.count
} else {
// the space adds some issues at the end of lines, so let's just get rid of it
self.textDocumentProxy.deleteBackward()
}
setCapsIfNeeded()
// reminder: positionAdjustment == 0 if the last character was a space
self.textDocumentProxy.adjustTextPositionByCharacterOffset(-positionAdjustment)
self.textDocumentProxy.insertText("\u{200B}\n")
self.textDocumentProxy.adjustTextPositionByCharacterOffset(positionAdjustment)
self.textDocumentProxy.insertText(typedCharacter)
if typedCharacter == " " {
self.handleAutoPeriod(Key(.Space))
}
}
}
}
func isFirstWord() -> Bool {
if let context = self.textDocumentProxy.documentContextBeforeInput {
let words = context.characters.split{$0 == " "}.map(String.init)
if words.count > 1 {
let previousWord: String
if context.characters.last! != " " {
previousWord = words[words.count - 2]
} else {
// this is the special case where the user is typing the first letter of a word so when we split on spaces we actually want the last index, not the second to last
previousWord = words[words.count - 1]
}
let charView = String(previousWord.characters.last!)
return ".?!".rangeOfString(charView) != nil
}
}
return true
}
override func createBanner() -> ExtraView? {
return Banner(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode())
}
}
| bsd-3-clause | d1bb58b9f8dee7e23101af5b4a41a2a0 | 46.284615 | 444 | 0.621929 | 5.118235 | false | false | false | false |
MsrButterfly/Msr.LibSwift | UI/MSRLoadMoreControl.swift | 2 | 5674 | import UIKit
@objc class MSRLoadMoreControl: UIControl {
private(set) var loadingMore: Bool = false
convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: 0, height: 40))
backgroundColor = UIColor.clearColor()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func beginLoadingMore() {
if !loadingMore {
loadingMore = true
scrollView!.contentInset.bottom += self.triggerHeight
}
}
func endLoadingMore() {
loadingMore = false
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if object === scrollView {
if keyPath == "contentOffset" {
// let offset = (change![NSKeyValueChangeNewKey] as! NSValue).CGPointValue
transform = CGAffineTransformMakeTranslation(0, scrollView!.contentSize.height + overHeight - frame.height)
if !loadingMore {
alpha = min(max(overHeight, 0), frame.height) / frame.height
if overHeight > 0 {
setNeedsDisplay()
if overHeight > triggerHeight && !loadingMore && !scrollView!.dragging {
loadingMore = true
beginLoadingMore()
sendActionsForControlEvents(.ValueChanged)
}
}
} else {
alpha = 1
}
} else if keyPath == "frame" {
let frame = (change![NSKeyValueChangeNewKey] as! NSValue).CGRectValue()
self.frame.size.width = frame.width
}
}
}
override func drawRect(rect: CGRect) {
let space = CGFloat(14)
let lineWidth = CGFloat(2)
let lineHeight = CGFloat(5.5)
let context = UIGraphicsGetCurrentContext()
let color = tintColor
CGContextSetLineCap(context, .Round)
CGContextSetLineWidth(context, lineWidth)
CGContextTranslateCTM(context, frame.width / 2, frame.height / 2)
if !loadingMore {
let percentage = min(max(overHeight, 0), triggerHeight) / triggerHeight
CGContextSetStrokeColorWithColor(context, color.CGColor)
let numberOfLines = Int(percentage * 11) + 1
if numberOfLines > 0 {
for _ in 1...numberOfLines {
CGContextMoveToPoint(context, 0, space / 2)
CGContextAddLineToPoint(context, 0, space / 2 + lineHeight)
CGContextStrokePath(context)
CGContextRotateCTM(context, CGFloat(M_PI) * 2 / 12)
}
}
} else {
// CGContextRotateCTM(context, CGFloat(M_PI) * 2 / 12 * CGFloat(arc4random_uniform(12)))
for i in 0..<12 {
CGContextSetStrokeColorWithColor(context, color.colorWithAlphaComponent(CGFloat(1) / CGFloat(i)).CGColor)
CGContextMoveToPoint(context, 0, space / 2)
CGContextAddLineToPoint(context, 0, space / 2 + lineHeight)
CGContextStrokePath(context)
CGContextRotateCTM(context, CGFloat(M_PI) * 2 / 12)
}
}
}
override func willMoveToSuperview(newSuperview: UIView?) {
if let scrollView = superview as? UIScrollView {
if scrollView !== newSuperview {
scrollView.removeObserver(self, forKeyPath: "contentOffset")
scrollView.removeObserver(self, forKeyPath: "frame")
}
}
}
private weak var _scrollView: UIScrollView? = nil
private weak var scrollView: UIScrollView? {
get {
return _scrollView
}
set {
_scrollView?.removeObserver(self, forKeyPath: "contentOffset")
_scrollView?.removeObserver(self, forKeyPath: "frame")
_scrollView = newValue
_scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
_scrollView?.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
}
}
private let triggerHeight = CGFloat(100)
private var overHeight: CGFloat {
if scrollView!.contentSize.height < scrollView!.bounds.height {
return scrollView!.contentOffset.y + scrollView!.contentInset.top
} else {
return scrollView!.contentOffset.y + scrollView!.bounds.height - scrollView!.contentInset.bottom - scrollView!.contentSize.height
}
}
}
var _UITableViewControllerMSRLoadMoreControlAssociationKey: UnsafePointer<Void> {
struct _Static {
static var key = CChar()
}
return UnsafePointer<Void>(msr_memory: &_Static.key)
}
extension UITableViewController {
@objc var msr_loadMoreControl: MSRLoadMoreControl? {
set {
self.msr_loadMoreControl?.removeFromSuperview()
self.msr_loadMoreControl?.scrollView = nil
objc_setAssociatedObject(self, _UITableViewControllerMSRLoadMoreControlAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN)
if newValue != nil {
tableView.insertSubview(newValue!, belowSubview: tableView.subviews[0])
newValue!.scrollView = tableView
}
}
get {
return objc_getAssociatedObject(self, _UITableViewControllerMSRLoadMoreControlAssociationKey) as? MSRLoadMoreControl
}
}
}
| gpl-2.0 | 319950615c7ea88c32358f490f483be2 | 41.661654 | 157 | 0.59147 | 5.27814 | false | false | false | false |
evering7/Speak | iSpeaking/SpeakData.swift | 1 | 27971 | //
// Data.swift
// iSpeaking
//
// Created by JianFei Li on 05/05/2017.
// Copyright © 2017 JianFei Li. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class SpeakData: NSObject {
var sourceFeedList : [SourceFeedMem] = []
var feedSubItemList : [FeedSubItemMem] = []
// var sourceRSSList_totalCount : Int = 0
// var sourceRSSList_downloadedCount : Int = 0
func checkFeedURLAddedBefore_InDisk(feedURL: String) -> Bool {
// check if the URL exist in the db
// if it does, return true
// if it doesn't, return false
// if some error, return true
// 1. get context
guard let app = UIApplication.shared.delegate as? AppDelegate else {
return false
}
let context = app.coreDataStack.persistentContainer.newBackgroundContext()
// 2. declare the request for the data
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
fetchRequest.fetchLimit = 2
// 3. declare an entity structure
let EntityName = "SourceFeedDisk"
let entity:NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: context)
fetchRequest.entity = entity
// Todo:done save the url in utf8 encoding, and use utf8 encoding to compare
// jianfei 2017 May 18th
// 4. set the conditional for query
let tempFeedURL : String = feedURL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
let predicate = NSPredicate.init(format: "feed_URL = %@ ", tempFeedURL)
fetchRequest.predicate = predicate
// 5. Query operation
do {
let fetchedObjects = try context.fetch(fetchRequest) as! [SourceFeedDisk]
if fetchedObjects.count == 1 {
return true
}else if fetchedObjects.count >= 2 {
printLog(message: "There are more than 2 records for a same feed URL. \(feedURL)")
return true
}else { return false } // no record
}catch {
let nsError = error as NSError
fatalError("Query error \(nsError), \(nsError.userInfo)")
// return true
}
}
func AddlySaveFeed_FromMem_ToDisk(sourceFeed: SourceFeedMem){
// check 1 thing the feed url is unique
let tempFeedURL = sourceFeed.feed_URL
if checkFeedURLAddedBefore_InDisk(feedURL: tempFeedURL){
printLog(message: "Failed to verify the feed URL never added before, in other words, the url exist in the database. \(sourceFeed.feed_URL)")
return
}
// first get db_ID
let db_ID = getMinimumAvailableFeedDBid_InDisk()
if db_ID < 0 {
fatalError("Can't get an effective minimum available db_ID for Feeds")
}
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
// 1
let managedContext = appDelegate.coreDataStack.persistentContainer.newBackgroundContext()
// add two things
// check 1 thing
// the feed url is unique
// get minimum id auto, without need to manually set it
// 2
let entity = NSEntityDescription.entity(forEntityName: "SourceFeedDisk", in: managedContext)
let managedSourceFeed = NSManagedObject(entity: entity!, insertInto: managedContext)
// 3
managedSourceFeed.setValue(sourceFeed.feed_Title, forKey: "feed_Title")
managedSourceFeed.setValue(sourceFeed.feed_Language, forKey: "feed_Language")
// first let feed_URL converted to a utf8 encoding string
let tmpFeedURL : String = sourceFeed.feed_URL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
managedSourceFeed.setValue(tmpFeedURL, forKey: "feed_URL")
managedSourceFeed.setValue(sourceFeed.feed_Author, forKey: "feed_Author")
managedSourceFeed.setValue(sourceFeed.feed_Tags, forKey: "feed_Tags") // important
managedSourceFeed.setValue(sourceFeed.svr_Likes, forKey: "svr_Likes")
managedSourceFeed.setValue(sourceFeed.svr_Dislikes, forKey: "svr_Dislikes")
managedSourceFeed.setValue(sourceFeed.svr_SubscribeCount, forKey: "svr_SubscribeCount")
managedSourceFeed.setValue(db_ID, forKey: "db_ID")
managedSourceFeed.setValue(sourceFeed.db_DownloadedXMLFileName, forKey: "db_DownloadedXMLFileName")
managedSourceFeed.setValue(sourceFeed.feed_UpdateTime, forKey: "feed_UpdateTime")
// managedSourceFeed.setValue(sourceFeed.isLastUpdateSuccess, forKey:"isLastUpdateSuccess")
managedSourceFeed.setValue((sourceFeed.feed_IsDownloadSuccess), forKey: "feed_IsDownloadSuccess")
managedSourceFeed.setValue(sourceFeed.feed_DownloadTime, forKey:"feed_DownloadTime")
// could this line be executed correctly? need checking!
managedSourceFeed.setValue((sourceFeed.feed_IsRSSorAtom), forKey: "feed_IsRSSorAtom")
// total 14, db 2, feed 9, server 3
// 4
do {
try managedContext.save()
}catch let error as NSError {
printLog(message: "Could not save. \(error), \(error.userInfo)")
}
}
func getMinimumAvailableFeedDBid_InDisk() -> Int64 {
// 1. get context
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return -1
}
// 1-2.
let managedContext = appDelegate.coreDataStack.persistentContainer.newBackgroundContext()
// 2. declare the request for data
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
// fetchRequest.fetchLimit = 10
let highestSortDescriptor = NSSortDescriptor(key: "db_ID",ascending: false)
fetchRequest.sortDescriptors = [highestSortDescriptor]
// 3. declare an entity
let EntityName = "SourceFeedDisk"
let entity: NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: managedContext)
fetchRequest.entity = entity
// 4. setup query condition
let predicate = NSPredicate.init(format: " %K >= %@ ", "db_ID", "0")
fetchRequest.predicate = predicate
// 5. do query operation
do {
let fetchedObjects = try managedContext.fetch(fetchRequest) as! [SourceFeedDisk]
if fetchedObjects.count == 0 {
return 0 // no field exist before
} else {
return (fetchedObjects[0].db_ID + 1)
}
}catch {
let nsError = error as NSError
fatalError("query error: \(nsError), \(nsError.userInfo)")
}
}
func getFeedSubItem_FromDisk_PendingToMemory() -> [FeedSubItemDisk]{
// get the feed sub item to memory
// 1. get a new context
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "can not get an appDelegate object")
return []
}
let context = app.coreDataStack.privateUserContext
// 2. get fetch request
let fetchRequest = NSFetchRequest<FeedSubItemDisk>(entityName: "FeedSubItemDisk")
// 3. do the fetch
var localFeedSubItemList : [FeedSubItemDisk] = []
do {
localFeedSubItemList = try context.fetch(fetchRequest)
return localFeedSubItemList
}catch {
printLog(message: "Could not fetch. \(error.localizedDescription)")
return []
}
}
// todo: delete ? for better running
func getSourceFeed_FromDisk_PendingToMemory() -> [SourceFeedDisk] {
// 1
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return []
}
let managedContext = appDelegate.coreDataStack.privateUserContext
// 2
let fetchRequest = NSFetchRequest<SourceFeedDisk>(entityName: "SourceFeedDisk")
var localFeedList: [SourceFeedDisk] = []
// 3
do {
localFeedList = try managedContext.fetch(fetchRequest)
return localFeedList
}catch let error as NSError {
printLog(message: "Could not fetch. \(error), \(error.userInfo)")
return []
}
}
func getSourceRSSCount() -> Int? {
// 1
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return nil
}
let managedContext = appDelegate.coreDataStack.privateUserContext
let fetchRequest: NSFetchRequest<SourceFeedDisk> = SourceFeedDisk.fetchRequest()
do {
// go get the results
let searchResults = try managedContext.fetch(fetchRequest)
// Todo, more simplified solution to search for
// I like to check the size of the returned results
printLog(message: "num of results = \(searchResults.count)")
return searchResults.count
// You need to convert to NSManagedObject to use for loops
// for source in searchResults as [NSManagedObject] {
// // get the Key Value pairs
// print("\(String(describing: source.value(forKey: "author")))")
// }
}catch {
print("Error with request : \(error)")
return nil
}
}
func insertSomeDefaultSourceFeed(){
// Add code to save coredata
let sourceFeedObject : SourceFeedMem = SourceFeedMem()
// sourceFeedObject.initialize()
// sourceFeedObject.db_ID = 1
sourceFeedObject.feed_URL = "http://blog.sina.com.cn/rss/1462466974.xml"
// test if could check the exist record
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// 20170520. Test ok of the addly save feed
// self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
//sourceFeedObject.db_ID = 2
sourceFeedObject.feed_URL = "https://lijinghe.com/feed/"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 3
sourceFeedObject.feed_URL = "http://www.767stock.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 4
sourceFeedObject.feed_URL = "http://www.huxiu.com/rss/"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 5
sourceFeedObject.feed_URL = "http://blog.caixin.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 6
sourceFeedObject.feed_URL = "http://next.36kr.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 7
sourceFeedObject.feed_URL = "http://www.goingconcern.cn/feed.xml"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 8
sourceFeedObject.feed_URL = "http://feeds.appinn.com/appinns/"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 9
sourceFeedObject.feed_URL = "http://sspai.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 10
sourceFeedObject.feed_URL = "http://zhan.renren.com/zhihujx/rss"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 11
sourceFeedObject.feed_URL = "http://www.ifanr.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
//Todo: add more from a text file, so the usability improved
// Finally, should get the content again.
}
func loadFeedList_FromDisk_ToMemory(diskList: [SourceFeedDisk], memList: inout [SourceFeedMem]){
if diskList.count == 0 {
printLog(message: "No need to copy, disklist is 0-length")
return
}
for sourceFeed: SourceFeedDisk in diskList {
let memSourceFeed = sourceFeed.loadSourceFeed_FromDisk_ToMemory()
memList.append(memSourceFeed)
}
}
func loadFeedSubItemList_FromDisk_ToMemory(diskList: [FeedSubItemDisk], memList: inout [FeedSubItemMem]){
// load
// load feed sub item list one by one from disk db to memory
// check count of disk list
if diskList.count == 0 {
printLog(message: "No need to copy, feed sub item disklist is 0-length")
return
}
// iteration through the disk list to get full new list
for feedSubItem: FeedSubItemDisk in diskList {
let memFeedSubItem = feedSubItem.loadFeedSubItemClass_FromDisk_ToMemory()
memList.append(memFeedSubItem)
}
}
func UpdatelySaveFeedMemData_ToDisk(sourceFeedClass: SourceFeedMem) -> Bool
{
// TODO: simplify these two lines as a func
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "Return failure because cannot get appDelegate")
return false // failure
}
// let managedContext =
let managedContext = app.coreDataStack.privateUserContext
// let fetchRequest = NSFetchRequest<SourceFeed>(entityName: "SourceFeed")
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
fetchRequest.fetchLimit = 2
// fetchRequest.fetchOffset = 0
let EntityName = "SourceFeedDisk"
let entity: NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: managedContext)
fetchRequest.entity = entity
let predicate = NSPredicate(format: "db_ID = %lld", sourceFeedClass.db_ID)
fetchRequest.predicate = predicate
do {
let fetchResults = try managedContext.fetch(fetchRequest) as! [SourceFeedDisk]
if fetchResults.count == 1 {
// Here, Modify the data
// let sourceFeed: SourceFeed = fetchResults[0]
// todo: add feed_SubItemCount = 10 in the future
fetchResults[0].db_DownloadedXMLFileName = sourceFeedClass.db_DownloadedXMLFileName
// sourceFeed.db_ID
fetchResults[0].feed_Author = sourceFeedClass.feed_Author
fetchResults[0].feed_DownloadTime = sourceFeedClass.feed_DownloadTime as NSDate
fetchResults[0].feed_IsDownloadSuccessBool = sourceFeedClass.feed_IsDownloadSuccess
fetchResults[0].feed_IsRSSorAtomBool = sourceFeedClass.feed_IsRSSorAtom
fetchResults[0].feed_Language = sourceFeedClass.feed_Language
fetchResults[0].feed_Tags = sourceFeedClass.feed_Tags
fetchResults[0].feed_Title = sourceFeedClass.feed_Title
fetchResults[0].feed_UpdateTime = sourceFeedClass.feed_UpdateTime as NSDate
fetchResults[0].feed_URL = sourceFeedClass.feed_URL
fetchResults[0].svr_Likes = sourceFeedClass.svr_Likes
fetchResults[0].svr_Dislikes = sourceFeedClass.svr_Dislikes
fetchResults[0].svr_SubscribeCount = sourceFeedClass.svr_SubscribeCount
app.coreDataStack.saveContext()
printLog(message: "return as success truely")
return true // success
}else {
printLog(message: "return because fields count not equal 1")
return false // failure
}
// }else {
// printLog(message: "unwrap the fetchResults failure")
// return false
// }
}catch {
printLog(message: "\(error.localizedDescription)")
return false
}
// let entity = NSEntityDescription.entity(forEntityName: "SourceFeed", in: managedContext)
//
// let managedSourceFeed = NSManagedObject(entity: entity!, insertInto: managedContext)
}
// todo: From here 2017.5.10. still working on name modification
func UpdateOrAdd_SaveFeedSubItemData_ToDisk(sourceFeedClass: SourceFeedMem) -> Bool {
// Steps: It should be circle
// 1. Do a query, check if exist a title-same article / subitem or not
// 2. if exist, update the feed sub item
// 3. if not exist, add the feed sub item
// 4. if success, return true
// frame 1. a check for rss or atom
// frame 2. loop
// Step 1. Do a query, to check if exist a title-same article.
if sourceFeedClass.feed_IsRSSorAtom == true {
// rss feed
// do a loop
if let items = sourceFeedClass.mem_rssFeed.items{
for item: RSSFeedItem in items {
let db_SubItemID = getCurrentlyExistIDForItem_InMem(subItem: item) // query mem data
if db_SubItemID < 0 {
// indicating no sub item id
Addly_SaveFeedSubItemData_ToDisk(rssFeedItem: item, sourceFeedClass: sourceFeedClass)
} else {
// indicating existing the sub item id
// todo here
Update_SaveFeedSubItemData_ToDisk(rssFeedItem: item, sourceFeedClass: sourceFeedClass)
}
}
}
}else{
// atom
}
return false
}
func getCurrentlyExistIDForItem_InMem(subItem: RSSFeedItem) -> Int64 {
// For use of RSSFeed
// get the existing id from
// search the maximum id
if self.feedSubItemList.count == 0 {
return -1 // no exist the id
}
// search for the exist id
for feedSubItem : FeedSubItemMem in self.feedSubItemList {
// search the Article URL
if let subLink = subItem.link {
if feedSubItem.item_ArticleURL == subLink {
return feedSubItem.db_SubItemID
}
}
}
return -2 // search but no exist
}
func getCurrentlyExistIDForItem_InDisk(subItem: RSSFeedItem ) -> Int64 {
// return -1 means unsuccessful to get an existing FeedItem
// do a query by title and link
// step 1. get the data context
// TODO: simplify these two lines as a func
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "Return failure because cannot get appDelegate")
return -1 // failure
}
let context = app.coreDataStack.privateUserContext
// step 2. declare the data search request
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
fetchRequest.fetchLimit = 2
fetchRequest.fetchOffset = 0
// step 3. declare an entity
let EntityName = "FeedSubItemDisk"
let entity:NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: context)
fetchRequest.entity = entity
// step 4. setup conditional form for search
let predicate = NSPredicate.init(format: "item_ArticleURL = %@ ", subItem.link!)
fetchRequest.predicate = predicate
// step 5. query operation
do {
let fetchedObjects = try context.fetch(fetchRequest) as! [FeedSubItemDisk]
// iterate the query results
if fetchedObjects.count == 1 {
// Only one is the correct state
return fetchedObjects[0].db_SubItemID
}else if fetchedObjects.count >= 2 {
printLog(message: "Unexpected: the query results count exceed 1. \(fetchedObjects.count)")
return fetchedObjects[0].db_SubItemID
}else {
// return -1 indicate no records are found
return -1
}
}catch {
fatalError("Query Error: \(error.localizedDescription)")
// return -2 // means error indeed
}
}
func Update_SaveFeedSubItemData_ToDisk(rssFeedItem: RSSFeedItem, sourceFeedClass: SourceFeedMem) -> Bool{
return true
}
func Addly_SaveFeedSubItemData_ToDisk(rssFeedItem: RSSFeedItem, sourceFeedClass: SourceFeedMem) -> Bool{
// function: add a feeditem to feeditem disk database
// step 1. get the data context
// TODO: simplify these two lines as a func
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "Return failure because cannot get appDelegate")
return false // failure
}
let context = app.coreDataStack.privateUserContext
// step 2. create a FeedSubItem object
let EntityName = "FeedSubItemDisk"
let oneItem = NSEntityDescription.insertNewObject(forEntityName: EntityName, into: context) as! FeedSubItemDisk
// step 3. assign value to the object
// TODO: add a real file name
oneItem.db_DownloadedHtmlFileName = ""
oneItem.db_SubItemID = getAvailableMinimumSubItemID() // TODO: Add this function
return false
}
func getAvailableMinimumSubItemID() -> Int64 {
// Todo
return 1
}
func parseFeedXmlAndUpdateMemData(sourceFeedClass: SourceFeedMem){
// let singleSourceRSS = speakData.sourceRSSList[0]
let fileURL = getRSSxmlFileURLfromLastComponent(lastPathCompo:
sourceFeedClass.db_DownloadedXMLFileName)
let feedParser = FeedParser(URL: fileURL)
let result = feedParser?.parse()
if let newResult = result {
switch newResult {
case Result.rss (let rssFeed):
printLog(message: "url: \(sourceFeedClass.feed_URL)")
printLog(message: "link \(String(describing: rssFeed.link))")
// Start to convert things in rssfeed
sourceFeedClass.feed_Title = rssFeed.title ?? "no title"
sourceFeedClass.feed_Language = rssFeed.language ?? "no specified lang"
// url blank
sourceFeedClass.feed_Author = rssFeed.managingEditor ?? "no editor/author"
sourceFeedClass.feed_Tags = String(describing: rssFeed.categories)
// skip: likes, dislikes, subscribeCount, id, downloadedXMLFileName,
let upDate: Date
if rssFeed.pubDate != nil {
upDate = (rssFeed.pubDate)!
}else{
upDate = getDefaultTime()
}
sourceFeedClass.feed_UpdateTime = upDate
sourceFeedClass.feed_IsRSSorAtom = true
sourceFeedClass.mem_rssFeed = rssFeed
// sourceFeedClass.isLastUpdateSuccess = true
// skip: isDownloadSuccess, lastDownloadTime
// Here: should convert items into RSSArticleItem
if let rssFeedItems = rssFeed.items {
let isSuccess = self.addFeedSubItems_FromNetFeed_ToMemoryList(rssFeedItems: rssFeedItems)
if !isSuccess {
printLog(message: "fail to add RSS Feed Item to MemList")
}
}
case Result.atom (let atomFeed):
printLog(message: "url: \(sourceFeedClass.feed_URL)")
printLog(message: "link: \(String(describing: atomFeed.links))")
sourceFeedClass.feed_Title = atomFeed.title ?? "no title"
sourceFeedClass.feed_Language = "unkown language"
sourceFeedClass.feed_Author = String(describing: atomFeed.authors)
sourceFeedClass.feed_Tags = String(describing: atomFeed.categories)
sourceFeedClass.feed_UpdateTime = (atomFeed.updated) ?? getDefaultTime()
sourceFeedClass.feed_IsRSSorAtom = false
sourceFeedClass.mem_atomFeed = atomFeed
// sourceFeedClass.isLastUpdateSuccess = true
if let atomFeedItems = atomFeed.entries {
let isSuccess = self.addFeedSubItems_FromNetFeed_ToMemoryList(atomFeedItems: atomFeedItems)
if !isSuccess {
printLog(message: "fail to add atom feed to MemList")
}
}
// atomFeed.links?[0].attributes?.title
case Result.failure(let error):
printLog(message: error)
}
}else { // result is nil
printLog(message: "error in parsing the result: the result is nil")
}
}
func addFeedSubItems_FromNetFeed_ToMemoryList(rssFeedItems: [RSSFeedItem]) -> Bool{
// from rssFeedItmes to articleOfRSSList
for singleRSSFeedItem: RSSFeedItem in rssFeedItems {
let feedSubItemClass = singleRSSFeedItem.loadFeedSubItem_FromNetFeed_ToMemory()
self.feedSubItemList.append(feedSubItemClass)
}
return true
}
func addFeedSubItems_FromNetFeed_ToMemoryList(atomFeedItems: [AtomFeedEntry]) -> Bool {
for singleAtomFeedItem: AtomFeedEntry in atomFeedItems{
let feedSubItemClass = singleAtomFeedItem.loadFeedSubItem_FromNetFeed_ToMemory()
self.feedSubItemList.append(feedSubItemClass)
}
return true
}
class func getAvailabeMinimumIDofFeedSubItem_InMem() -> Int64 {
// todo: may be here need to add disk id
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var maxID: Int64 = 0
for singleArticleItem in appDelegate.speakData.feedSubItemList {
if maxID < (singleArticleItem.db_SubItemID) {
maxID = (singleArticleItem.db_SubItemID)
}
}
return (maxID + 1) // minimum available id
}
class func getAvailableMinimumSubItemID() -> Int64 {
// ToDo: Add this function
return 1
}
}
| mit | f5be837f5c5c2d06de39b0b2eb70dae0 | 36.644684 | 152 | 0.582159 | 4.95922 | false | false | false | false |
ddimitrov90/EverliveSDK | Tests/Pods/EverliveSDK/EverliveSDK/UsersGenericHandler.swift | 2 | 1785 | //
// GenericRequestHandler.swift
// EverliveSwift
//
// Created by Dimitar Dimitrov on 3/23/16.
// Copyright © 2016 ddimitrov. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
public class UsersGenericHandler : BaseHandler {
var method:String
var body:JSON?
public init(method:String, urlPath:String, connection:EverliveConnection){
self.method = method
super.init(connection: connection, typeName: urlPath)
}
public init(method:String, urlPath:String, body:JSON?, connection: EverliveConnection){
self.method = method
self.body = body
super.init(connection: connection, typeName: urlPath)
}
required public init(connection: EverliveConnection, typeName: String) {
fatalError("init(connection:typeName:) has not been implemented")
}
public func execute(completionHandler: (Bool, EverliveError?) -> Void){
let url = self.prepareUrl()
let genericRequest = EverliveRequest(httpMethod: self.method, url: url)
if let bodyData = self.body {
let body: String = bodyData.rawString(NSUTF8StringEncoding, options: NSJSONWritingOptions(rawValue: 0))!
let data = body.dataUsingEncoding(NSUTF8StringEncoding)
genericRequest.setBodyData(data!)
genericRequest.setValue("application/json", forHeader: "Content-Type")
}
self.connection.executeRequest(genericRequest) { (response: Result<GenericResult<Int>, NSError>) -> Void in
if let result = response.value {
completionHandler(result.isTrue, result.getErrorObject())
}
}
}
override public func prepareUrl() -> String {
return self.typeName
}
} | mit | 7ecde3fbbcca6d51efa302c8bd14836f | 32.679245 | 116 | 0.664798 | 4.657963 | false | false | false | false |
TwoRingSoft/shared-utils | Examples/Pippin/Pods/PinpointKit/PinpointKit/PinpointKit/Sources/Core/SystemLogCollector.swift | 1 | 1795 | //
// SystemLogCollector.swift
// PinpointKit
//
// Created by Brian Capps on 2/5/16.
// Copyright © 2016 Lickability. All rights reserved.
//
/// A log collector that uses [Apple System Logger](https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/LoggingErrorsAndWarnings.html) API to retrieve messages logged to the console with `NSLog`.
open class SystemLogCollector: LogCollector {
/**
The type of logs to collect.
*/
public enum LoggingType {
/// Logs from the application target.
case application
/// Logs from the testing target.
case testing
}
private let logger: ASLLogger
/**
Creates a new system logger.
- parameter loggingType: Specifies the type of logs to collect.
- warning: This initializer returns `nil` on iOS 10.0+. When running on iOS 10.0+, ASL is superseded by unified logging, for which there are no APIs to search or read log messages.
- seealso: https://developer.apple.com/reference/os/logging
*/
public init?(loggingType: LoggingType = .application) {
if #available(iOS 10.0, *), loggingType == .application {
return nil
}
switch loggingType {
case .application:
logger = ASLLogger(bundleIdentifier: Bundle.main.bundleIdentifier ?? "")
case .testing:
logger = ASLLogger(senderName: "xctest")
}
}
// MARK: - LogCollector
/**
Retrieves and returns logs as an ordered list of strings.
- returns: Logs as an ordered list of strings, sorted by descending recency.
*/
open func retrieveLogs() -> [String] {
return logger.retrieveLogs()
}
}
| mit | d75e482865b7d9a5a23efe1c9d49edba | 31.035714 | 240 | 0.633222 | 4.564885 | false | true | false | false |
Holmusk/WDStarRatingView | WDStarRatingView/ViewController.swift | 1 | 3320 | //
// ViewController.swift
// WDStarRatingViewSample
//
// Created by Wu Di on 10/7/15.
// Copyright (c) 2015 Wu Di. All rights reserved.
//
import UIKit
class ViewController: UIViewController, WDStarRatingDelegate {
private var starRatingView: WDStarRatingView!
private var ratingOverlay: RatingOverlayLabel!
override func viewDidLoad() {
super.viewDidLoad()
self.starRatingView = WDStarRatingView(frame: CGRectMake(50, 200, 200, 50))
self.starRatingView.delegate = self
self.starRatingView.maximumValue = 10
self.starRatingView.minimumValue = 0
self.starRatingView.value = 4.5
self.starRatingView.tintColor = UIColor.redColor()
self.starRatingView.addTarget(self, action: "didChangeValue:", forControlEvents: .ValueChanged)
self.view.addSubview(starRatingView)
self.ratingOverlay = RatingOverlayLabel(frame: CGRectMake(50, 170, 120, 60))
self.ratingOverlay.translatesAutoresizingMaskIntoConstraints = false
self.ratingOverlay.backgroundColor = UIColor.clearColor()
self.view.addSubview(self.ratingOverlay)
self.ratingOverlay.alpha = 0.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didChangeValue(sender: WDStarRatingView) {
NSLog("Changed rating to %.1f", sender.value)
}
func starRatingView(starRatingView: WDStarRatingView, didDrawStarsWithValue value: CGFloat) {
if value >= CGFloat(starRatingView.minimumValue) && value <= CGFloat(starRatingView.maximumValue) {
let frame = starRatingView.starForValue(value)
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.ratingOverlay.center = self.getRatingOverlayCenter(frame!)
})
ratingOverlay.setPropertiesForValue(value)
}
}
func starRatingView(starRatingView: WDStarRatingView, didStartTracking tracking: Bool) {
if tracking {
showRatingOverlay()
}
}
func starRatingView(starRatingView: WDStarRatingView, didStopTracking tracking: Bool) {
if tracking {
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.hideRatingOverlay()
})
}
}
private func getRatingOverlayCenter(starFrame: CGRect) -> CGPoint {
let starOrigin = starRatingView.convertPoint(starFrame.origin, toView: self.view)
let xPos = starOrigin.x + starFrame.width / 2
let starViewOrigin = self.view.convertPoint(starRatingView.frame.origin, toView: self.view)
let yPos = starViewOrigin.y - ratingOverlay.frame.height / 2
return CGPoint(x: xPos, y: yPos)
}
private func showRatingOverlay() {
UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveEaseInOut,
animations: { () -> Void in
self.ratingOverlay.alpha = 1.0
}, completion: nil)
}
private func hideRatingOverlay() {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.ratingOverlay.alpha = 0.0
})
}
}
| mit | 8e4adeb653327041d29246c76813f674 | 33.947368 | 107 | 0.663855 | 4.566713 | false | false | false | false |
quangvu1994/Exchange | Exchange/Helper/EXPhotoHelper.swift | 1 | 4044 | //
// EXPhotoHelper.swift
// Exchange
//
// Created by Quang Vu on 7/8/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import UIKit
import MobileCoreServices
class EXPhotoHelper: NSObject {
var completionHandler: ((UIImage) -> Void)?
var selectedImage: UIImage?
var imageIdentifier: Int = 0
/**
Present the action sheet
*/
func presentActionSheet(from viewController: UIViewController){
// Create an UIAlertController
let alertController = UIAlertController(title: nil, message: "Post Picture", preferredStyle: .actionSheet)
// Camera available -> Add photo¡ UIAlertAction
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let capturePhotoAction = UIAlertAction(title: "Take a photo", style: .default, handler: { (action) in
// Display camera
self.presentImagePickerController(with: .camera, from: viewController)
})
alertController.addAction(capturePhotoAction)
}
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let photoLibraryAciton = UIAlertAction(title: "Upload photo", style: .default, handler: { (action) in
// Display photo library
self.presentImagePickerController(with: .photoLibrary, from: viewController)
})
alertController.addAction(photoLibraryAciton)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
// Present the options
viewController.present(alertController, animated: true, completion: nil)
}
/**
Present a image picker controller: Capture photo or Photo library
*/
func presentImagePickerController(with sourceType: UIImagePickerControllerSourceType, from viewController: UIViewController){
DispatchQueue.main.async(execute: {
let imagePickerController = UIImagePickerController()
imagePickerController.mediaTypes = [kUTTypeImage as String]
imagePickerController.sourceType = sourceType
// Set the image picker controller delegate to handle the selected image
imagePickerController.delegate = self
imagePickerController.allowsEditing = false
// Present
viewController.present(imagePickerController, animated: true, completion: nil)
})
}
/**
Resize an image to the new specific size
*/
func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage? {
let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
extension EXPhotoHelper: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let handler = completionHandler else {
print("No image handler")
return
}
// Grab the selected image
if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
guard let resizedImage = resizeImage(image: selectedImage, newWidth: 800) else {
self.selectedImage = selectedImage
return handler(selectedImage)
}
self.selectedImage = resizedImage
handler(resizedImage)
}
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
| mit | 83a5bdd5c593b56ac80861afb423ade0 | 37.495238 | 129 | 0.654379 | 5.892128 | false | false | false | false |
mcudich/TemplateKit | Tests/DiffTests.swift | 1 | 3343 | //
// DiffTests.swift
// TemplateKit
//
// Created by Matias Cudich on 10/30/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import XCTest
import TemplateKit
struct FakeItem: Hashable {
let value: Int
let eValue: Int
var hashValue: Int {
return value.hashValue
}
}
func ==(lhs: FakeItem, rhs: FakeItem) -> Bool {
return lhs.eValue == rhs.eValue
}
func ==(lhs: (from: Int, to: Int), rhs: (from: Int, to: Int)) -> Bool {
return lhs.0 == rhs.0 && lhs.1 == rhs.1
}
class DiffTests: XCTestCase {
func testEmptyArrays() {
let o = [Int]()
let n = [Int]()
let result = diff(o, n)
XCTAssertEqual(0, result.count)
}
func testDiffingFromEmptyArray() {
let o = [Int]()
let n = [1]
let result = diff(o, n)
XCTAssertEqual(.insert(0), result[0])
XCTAssertEqual(1, result.count)
}
func testDiffingToEmptyArray() {
let o = [1]
let n = [Int]()
let result = diff(o, n)
XCTAssertEqual(.delete(0), result[0])
XCTAssertEqual(1, result.count)
}
func testSwapHasMoves() {
let o = [1, 2, 3]
let n = [2, 3, 1]
let result = diff(o, n)
XCTAssertEqual([.delete(2), .delete(1), .delete(0), .insert(0), .insert(1), .insert(2)], result)
}
func testMovingTogether() {
let o = [1, 2, 3, 3, 4]
let n = [2, 3, 1, 3, 4]
let result = diff(o, n)
XCTAssertEqual([.delete(2), .delete(1), .delete(0), .insert(0), .insert(1), .insert(2)], result)
}
func testSwappedValuesHaveMoves() {
let o = [1, 2, 3, 4]
let n = [2, 4, 5, 3]
let result = diff(o, n)
XCTAssertEqual([.delete(3), .delete(2), .delete(0), .insert(1), .insert(2), .insert(3)], result)
}
func testUpdates() {
let o = [
FakeItem(value: 0, eValue: 0),
FakeItem(value: 1, eValue: 1),
FakeItem(value: 2, eValue: 2)
]
let n = [
FakeItem(value: 0, eValue: 1),
FakeItem(value: 1, eValue: 2),
FakeItem(value: 2, eValue: 3)
]
let result = diff(o, n)
XCTAssertEqual([.update(0), .update(1), .update(2)], result)
}
func testDeletionLeadingToInsertionDeletionMoves() {
let o = [0, 1, 2, 3, 4, 5, 6, 7, 8]
let n = [0, 2, 3, 4, 7, 6, 9, 5, 10]
let result = diff(o, n)
XCTAssertEqual([.delete(8), .delete(7), .delete(5), .delete(1), .insert(4), .insert(6), .insert(7), .insert(8)], result)
}
func testMovingWithEqualityChanges() {
let o = [
FakeItem(value: 0, eValue: 0),
FakeItem(value: 1, eValue: 1),
FakeItem(value: 2, eValue: 2)
]
let n = [
FakeItem(value: 2, eValue: 3),
FakeItem(value: 1, eValue: 1),
FakeItem(value: 0, eValue: 0)
]
let result = diff(o, n)
XCTAssertEqual([.delete(2), .delete(0), .insert(0), .insert(2), .update(0)], result)
}
func testDeletingEqualObjects() {
let o = [0, 0, 0, 0]
let n = [0, 0]
let result = diff(o, n)
XCTAssertEqual(2, result.count)
}
func testInsertingEqualObjects() {
let o = [0, 0]
let n = [0, 0, 0, 0]
let result = diff(o, n)
XCTAssertEqual(2, result.count)
}
func testInsertingWithOldArrayHavingMultipleCopies() {
let o = [NSObject(), NSObject(), NSObject(), 49, 33, "cat", "cat", 0, 14] as [AnyHashable]
var n = o
n.insert("cat", at: 5)
let result = diff(o, n)
XCTAssertEqual(1, result.count)
}
}
| mit | ea771f38fd043a4a2a495978e1820b59 | 24.318182 | 124 | 0.575105 | 2.983929 | false | true | false | false |
khizkhiz/swift | test/1_stdlib/UnicodeScalarDiagnostics.swift | 2 | 2868 | // RUN: %target-parse-verify-swift
func isString(s: inout String) {}
func test_UnicodeScalarDoesNotImplementArithmetic(us: UnicodeScalar, i: Int) {
var a1 = "a" + "b" // OK
isString(&a1)
let a2 = "a" - "b" // expected-error {{binary operator '-' cannot be applied to two 'String' operands}}
// expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists:}}
let a3 = "a" * "b" // expected-error {{binary operator '*' cannot be applied to two 'String' operands}}
// expected-note @-1 {{overloads for '*' exist with these partially matching parameter lists:}}
let a4 = "a" / "b" // expected-error {{binary operator '/' cannot be applied to two 'String' operands}}
// expected-note @-1 {{overloads for '/' exist with these partially matching parameter lists:}}
let b1 = us + us // expected-error {{binary operator '+' cannot be applied to two 'UnicodeScalar' operands}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}}
let b2 = us - us // expected-error {{binary operator '-' cannot be applied to two 'UnicodeScalar' operands}}
// expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists:}}
let b3 = us * us // expected-error {{binary operator '*' cannot be applied to two 'UnicodeScalar' operands}}
// expected-note @-1 {{overloads for '*' exist with these partially matching parameter lists:}}
let b4 = us / us // expected-error {{binary operator '/' cannot be applied to two 'UnicodeScalar' operands}}
// expected-note @-1 {{overloads for '/' exist with these partially matching parameter lists:}}
let c1 = us + i // expected-error {{binary operator '+' cannot be applied to operands of type 'UnicodeScalar' and 'Int'}} expected-note{{overloads for '+' exist with these partially matching parameter lists:}}
let c2 = us - i // expected-error {{binary operator '-' cannot be applied to operands of type 'UnicodeScalar' and 'Int'}} expected-note{{overloads for '-' exist with these partially matching parameter lists:}}
let c3 = us * i // expected-error {{cannot convert value of type 'UnicodeScalar' to expected argument type 'Int'}}
let c4 = us / i // expected-error {{cannot convert value of type 'UnicodeScalar' to expected argument type 'Int'}}
let d1 = i + us // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UnicodeScalar'}} expected-note{{overloads for '+' exist with these partially matching parameter lists:}}
let d2 = i - us // expected-error {{cannot convert value of type 'UnicodeScalar' to expected argument type 'Int'}}
let d3 = i * us // expected-error {{cannot convert value of type 'UnicodeScalar' to expected argument type 'Int'}}
let d4 = i / us // expected-error {{cannot convert value of type 'UnicodeScalar' to expected argument type 'Int'}}
}
| apache-2.0 | ba9662098b1c75891654655197b09a49 | 83.352941 | 211 | 0.701883 | 4.293413 | false | false | false | false |
imranjutt/IJPopup | IJPopup/Classes/IJPopupView/IJAlertPopup.swift | 1 | 3006 | //
// IJAlertPopup.swift
// Pods
//
// Created by M Imran on 07/07/2017.
//
//
import UIKit
public class IJAlertPopup: UIView {
// MARK: properties
var customView:IJCustomView?
var callBack: ((_ sender: AnyObject) -> Void)?
// MARK: initializer
public init(withTitle:String, message:String, topBarColor:UIColor = UIColor(red:25.0/255.0, green:189.0/255.0, blue:72.0/255.0, alpha:1.0), buttonColor:UIColor = UIColor(red:25.0/255.0, green:189.0/255.0, blue:72.0/255.0, alpha:1.0), completionBlock:@escaping (AnyObject)->Void) {
super.init(frame: CGRect.zero)
self.loadCustomView()
customView!.titleLabel.text = withTitle
customView!.messageLabel.text = message
customView!.okayButton.addTarget(self, action: #selector(hideView(button:)), for: .touchUpInside)
customView!.okayButton.backgroundColor = buttonColor
customView!.topBarView.backgroundColor = topBarColor
self.callBack = completionBlock
}
// MARK: private methods
private func loadCustomView() {
customView = Bundle(for: IJAlertPopup.self).loadNibNamed(String(describing: IJCustomView.self), owner: nil, options: nil)?.first as? IJCustomView
self.addSubview(customView!)
customView?.translatesAutoresizingMaskIntoConstraints = false
let left = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: customView, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: customView, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: customView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: customView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)
self.addConstraints([left, right, top, bottom])
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//MARK: public methods
public func showInView(_ superView:UIView) {
self.frame = superView.frame;
superView.addSubview(self)
self.alpha = 0
UIView.animate(withDuration: 0.5) {
self.alpha = 1
}
}
func hideView(button:UIButton) {
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 0
}) { (true) in
self.removeFromSuperview()
if let completionBlock = self.callBack {
completionBlock(self)
}
}
}
}
| mit | ca5a0d962fb7307381e58850e8b6d2a8 | 35.658537 | 284 | 0.650366 | 4.59633 | false | false | false | false |
br1sk/brisk-ios | Brisk iOS/Login/OpenRadarViewController.swift | 1 | 1611 | import UIKit
import InterfaceBacked
protocol OpenRadarViewDelegate: class {
func openSafariTapped()
func continueTapped(token: String)
func skipTapped()
}
final class OpenRadarViewController: UITableViewController, StoryboardBacked {
// MARK: - Properties
@IBOutlet weak var tokenField: UITextField!
weak var delegate: OpenRadarViewDelegate?
let openSafariRow = 0
let fieldRow = 1
let finishRow = 2
// MARK: - User Actions
@IBAction func skipTapped() { delegate?.skipTapped() }
// MARK: - UITableViewController Methods
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
switch indexPath.row {
case fieldRow: return false
case finishRow:
let token = tokenField.text ?? ""
let validator = Token(token)
return validator.isValid
default: return true
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let selectable = self.tableView(tableView, shouldHighlightRowAt: indexPath)
cell.contentView.alpha = selectable || indexPath.row == fieldRow ? 1.0 : 0.5
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case openSafariRow: delegate?.openSafariTapped()
case finishRow: delegate?.continueTapped(token: tokenField.text ?? "")
default: break
}
}
}
// MARK: - UITextFieldDelegate Methods
extension OpenRadarViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | 8f1e6ae34e252b386c294afda7724a90 | 24.171875 | 118 | 0.754811 | 4.195313 | false | false | false | false |
hoangton/mobile | plugins/cordova-plugin-iosrtc/src/PluginGetMediaDevices.swift | 2 | 1346 | import Foundation
import AVFoundation
/**
* Doc: https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVCaptureDevice_Class/index.html
*/
class PluginGetMediaDevices {
class func call(callback: (data: NSDictionary) -> Void) {
NSLog("PluginGetMediaDevices#call()")
let devices = AVCaptureDevice.devices() as! Array<AVCaptureDevice>
var json: NSMutableDictionary = [
"devices": NSMutableDictionary()
]
for device: AVCaptureDevice in devices {
var position: String
let hasAudio = device.hasMediaType(AVMediaTypeAudio)
let hasVideo = device.hasMediaType(AVMediaTypeVideo)
switch device.position {
case AVCaptureDevicePosition.Unspecified:
position = "unknown"
case AVCaptureDevicePosition.Back:
position = "back"
case AVCaptureDevicePosition.Front:
position = "front"
}
NSLog("- device [uniqueID:'\(device.uniqueID)', localizedName:'\(device.localizedName)', position:\(position), audio:\(hasAudio), video:\(hasVideo), connected:\(device.connected)")
if device.connected == false || (hasAudio == false && hasVideo == false) {
continue
}
(json["devices"] as! NSMutableDictionary)[device.uniqueID] = [
"deviceId": device.uniqueID,
"kind": hasAudio ? "audio" : "video",
"label": device.localizedName
]
}
callback(data: json)
}
}
| agpl-3.0 | 71b7df5bfddcec5950a7fcac60d790ac | 26.469388 | 183 | 0.708024 | 4.066465 | false | false | false | false |
bparish628/iFarm-Health | iOS/iFarm-Health/Pods/Charts/Source/Charts/Components/AxisBase.swift | 4 | 12130 | //
// AxisBase.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 Foundation
import CoreGraphics
/// Base class for all axes
@objc(ChartAxisBase)
open class AxisBase: ComponentBase
{
public override init()
{
super.init()
}
/// Custom formatter that is used instead of the auto-formatter if set
fileprivate var _axisValueFormatter: IAxisValueFormatter?
@objc open var labelFont = NSUIFont.systemFont(ofSize: 10.0)
@objc open var labelTextColor = NSUIColor.black
@objc open var axisLineColor = NSUIColor.gray
@objc open var axisLineWidth = CGFloat(0.5)
@objc open var axisLineDashPhase = CGFloat(0.0)
@objc open var axisLineDashLengths: [CGFloat]!
@objc open var gridColor = NSUIColor.gray.withAlphaComponent(0.9)
@objc open var gridLineWidth = CGFloat(0.5)
@objc open var gridLineDashPhase = CGFloat(0.0)
@objc open var gridLineDashLengths: [CGFloat]!
@objc open var gridLineCap = CGLineCap.butt
@objc open var drawGridLinesEnabled = true
@objc open var drawAxisLineEnabled = true
/// flag that indicates of the labels of this axis should be drawn or not
@objc open var drawLabelsEnabled = true
fileprivate var _centerAxisLabelsEnabled = false
/// Centers the axis labels instead of drawing them at their original position.
/// This is useful especially for grouped BarChart.
@objc open var centerAxisLabelsEnabled: Bool
{
get { return _centerAxisLabelsEnabled && entryCount > 0 }
set { _centerAxisLabelsEnabled = newValue }
}
@objc open var isCenterAxisLabelsEnabled: Bool
{
get { return centerAxisLabelsEnabled }
}
/// array of limitlines that can be set for the axis
fileprivate var _limitLines = [ChartLimitLine]()
/// Are the LimitLines drawn behind the data or in front of the data?
///
/// **default**: false
@objc open var drawLimitLinesBehindDataEnabled = false
/// the flag can be used to turn off the antialias for grid lines
@objc open var gridAntialiasEnabled = true
/// the actual array of entries
@objc open var entries = [Double]()
/// axis label entries only used for centered labels
@objc open var centeredEntries = [Double]()
/// the number of entries the legend contains
@objc open var entryCount: Int { return entries.count }
/// the number of label entries the axis should have
///
/// **default**: 6
fileprivate var _labelCount = Int(6)
/// the number of decimal digits to use (for the default formatter
@objc open var decimals: Int = 0
/// When true, axis labels are controlled by the `granularity` property.
/// When false, axis values could possibly be repeated.
/// This could happen if two adjacent axis values are rounded to same value.
/// If using granularity this could be avoided by having fewer axis values visible.
@objc open var granularityEnabled = false
fileprivate var _granularity = Double(1.0)
/// The minimum interval between axis values.
/// This can be used to avoid label duplicating when zooming in.
///
/// **default**: 1.0
@objc open var granularity: Double
{
get
{
return _granularity
}
set
{
_granularity = newValue
// set this to `true` if it was disabled, as it makes no sense to set this property with granularity disabled
granularityEnabled = true
}
}
/// The minimum interval between axis values.
@objc open var isGranularityEnabled: Bool
{
get
{
return granularityEnabled
}
}
/// if true, the set number of y-labels will be forced
@objc open var forceLabelsEnabled = false
@objc open func getLongestLabel() -> String
{
var longest = ""
for i in 0 ..< entries.count
{
let text = getFormattedLabel(i)
if longest.characters.count < text.characters.count
{
longest = text
}
}
return longest
}
/// - returns: The formatted label at the specified index. This will either use the auto-formatter or the custom formatter (if one is set).
@objc open func getFormattedLabel(_ index: Int) -> String
{
if index < 0 || index >= entries.count
{
return ""
}
return valueFormatter?.stringForValue(entries[index], axis: self) ?? ""
}
/// Sets the formatter to be used for formatting the axis labels.
/// If no formatter is set, the chart will automatically determine a reasonable formatting (concerning decimals) for all the values that are drawn inside the chart.
/// Use `nil` to use the formatter calculated by the chart.
@objc open var valueFormatter: IAxisValueFormatter?
{
get
{
if _axisValueFormatter == nil ||
(_axisValueFormatter is DefaultAxisValueFormatter &&
(_axisValueFormatter as! DefaultAxisValueFormatter).hasAutoDecimals &&
(_axisValueFormatter as! DefaultAxisValueFormatter).decimals != decimals)
{
_axisValueFormatter = DefaultAxisValueFormatter(decimals: decimals)
}
return _axisValueFormatter
}
set
{
_axisValueFormatter = newValue ?? DefaultAxisValueFormatter(decimals: decimals)
}
}
@objc open var isDrawGridLinesEnabled: Bool { return drawGridLinesEnabled }
@objc open var isDrawAxisLineEnabled: Bool { return drawAxisLineEnabled }
@objc open var isDrawLabelsEnabled: Bool { return drawLabelsEnabled }
/// Are the LimitLines drawn behind the data or in front of the data?
///
/// **default**: false
@objc open var isDrawLimitLinesBehindDataEnabled: Bool { return drawLimitLinesBehindDataEnabled }
/// Extra spacing for `axisMinimum` to be added to automatically calculated `axisMinimum`
@objc open var spaceMin: Double = 0.0
/// Extra spacing for `axisMaximum` to be added to automatically calculated `axisMaximum`
@objc open var spaceMax: Double = 0.0
/// Flag indicating that the axis-min value has been customized
@objc internal var _customAxisMin: Bool = false
/// Flag indicating that the axis-max value has been customized
@objc internal var _customAxisMax: Bool = false
/// Do not touch this directly, instead, use axisMinimum.
/// This is automatically calculated to represent the real min value,
/// and is used when calculating the effective minimum.
@objc internal var _axisMinimum = Double(0)
/// Do not touch this directly, instead, use axisMaximum.
/// This is automatically calculated to represent the real max value,
/// and is used when calculating the effective maximum.
@objc internal var _axisMaximum = Double(0)
/// the total range of values this axis covers
@objc open var axisRange = Double(0)
/// the number of label entries the axis should have
/// max = 25,
/// min = 2,
/// default = 6,
/// be aware that this number is not fixed and can only be approximated
@objc open var labelCount: Int
{
get
{
return _labelCount
}
set
{
_labelCount = newValue
if _labelCount > 25
{
_labelCount = 25
}
if _labelCount < 2
{
_labelCount = 2
}
forceLabelsEnabled = false
}
}
@objc open func setLabelCount(_ count: Int, force: Bool)
{
self.labelCount = count
forceLabelsEnabled = force
}
/// - returns: `true` if focing the y-label count is enabled. Default: false
@objc open var isForceLabelsEnabled: Bool { return forceLabelsEnabled }
/// Adds a new ChartLimitLine to this axis.
@objc open func addLimitLine(_ line: ChartLimitLine)
{
_limitLines.append(line)
}
/// Removes the specified ChartLimitLine from the axis.
@objc open func removeLimitLine(_ line: ChartLimitLine)
{
for i in 0 ..< _limitLines.count
{
if _limitLines[i] === line
{
_limitLines.remove(at: i)
return
}
}
}
/// Removes all LimitLines from the axis.
@objc open func removeAllLimitLines()
{
_limitLines.removeAll(keepingCapacity: false)
}
/// - returns: The LimitLines of this axis.
@objc open var limitLines : [ChartLimitLine]
{
return _limitLines
}
// MARK: Custom axis ranges
/// By calling this method, any custom minimum value that has been previously set is reseted, and the calculation is done automatically.
@objc open func resetCustomAxisMin()
{
_customAxisMin = false
}
@objc open var isAxisMinCustom: Bool { return _customAxisMin }
/// By calling this method, any custom maximum value that has been previously set is reseted, and the calculation is done automatically.
@objc open func resetCustomAxisMax()
{
_customAxisMax = false
}
@objc open var isAxisMaxCustom: Bool { return _customAxisMax }
/// This property is deprecated - Use `axisMinimum` instead.
@objc @available(*, deprecated: 1.0, message: "Use axisMinimum instead.")
open var axisMinValue: Double
{
get { return axisMinimum }
set { axisMinimum = newValue }
}
/// This property is deprecated - Use `axisMaximum` instead.
@objc @available(*, deprecated: 1.0, message: "Use axisMaximum instead.")
open var axisMaxValue: Double
{
get { return axisMaximum }
set { axisMaximum = newValue }
}
/// The minimum value for this axis.
/// If set, this value will not be calculated automatically depending on the provided data.
/// Use `resetCustomAxisMin()` to undo this.
@objc open var axisMinimum: Double
{
get
{
return _axisMinimum
}
set
{
_customAxisMin = true
_axisMinimum = newValue
axisRange = abs(_axisMaximum - newValue)
}
}
/// The maximum value for this axis.
/// If set, this value will not be calculated automatically depending on the provided data.
/// Use `resetCustomAxisMax()` to undo this.
@objc open var axisMaximum: Double
{
get
{
return _axisMaximum
}
set
{
_customAxisMax = true
_axisMaximum = newValue
axisRange = abs(newValue - _axisMinimum)
}
}
/// Calculates the minimum, maximum and range values of the YAxis with the given minimum and maximum values from the chart data.
/// - parameter dataMin: the y-min value according to chart data
/// - parameter dataMax: the y-max value according to chart
@objc open func calculate(min dataMin: Double, max dataMax: Double)
{
// if custom, use value as is, else use data value
var min = _customAxisMin ? _axisMinimum : (dataMin - spaceMin)
var max = _customAxisMax ? _axisMaximum : (dataMax + spaceMax)
// temporary range (before calculations)
let range = abs(max - min)
// in case all values are equal
if range == 0.0
{
max = max + 1.0
min = min - 1.0
}
_axisMinimum = min
_axisMaximum = max
// actual range
axisRange = abs(max - min)
}
}
| apache-2.0 | 99842e2b7af7c384b5783d4a2daf3ce2 | 31.175066 | 168 | 0.610965 | 5.079564 | false | false | false | false |
Jean-Daniel/PhoneNumberKit | PhoneNumberKit/ParseManager.swift | 1 | 7128 | //
// ParseManager.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 01/11/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import Foundation
/**
Manager for parsing flow.
*/
final class ParseManager {
weak var metadataManager: MetadataManager?
let parser: PhoneNumberParser
weak var regexManager: RegexManager?
init(metadataManager: MetadataManager, regexManager: RegexManager) {
self.metadataManager = metadataManager
self.parser = PhoneNumberParser(regex: regexManager, metadata: metadataManager)
self.regexManager = regexManager
}
/**
Parse a string into a phone number object with a custom region. Can throw.
- Parameter numberString: String to be parsed to phone number struct.
- Parameter region: ISO 639 compliant region code.
- parameter ignoreType: Avoids number type checking for faster performance.
*/
func parse(_ numberString: String, withRegion region: String, ignoreType: Bool) throws -> PhoneNumber {
guard let metadataManager = metadataManager, let regexManager = regexManager else { throw PhoneNumberError.generalError }
// Make sure region is in uppercase so that it matches metadata (1)
let region = region.uppercased()
// Extract number (2)
var nationalNumber = numberString
let match = try regexManager.phoneDataDetectorMatch(numberString)
let matchedNumber = nationalNumber.substring(with: match.range)
nationalNumber = matchedNumber
// Strip and extract extension (3)
var numberExtension: String?
if let rawExtension = parser.stripExtension(&nationalNumber) {
numberExtension = parser.normalizePhoneNumber(rawExtension)
}
// Country code parse (4)
guard var regionMetadata = metadataManager.territoriesByCountry[region] else {
throw PhoneNumberError.invalidCountryCode
}
var countryCode: UInt64 = 0
do {
countryCode = try parser.extractCountryCode(nationalNumber, nationalNumber: &nationalNumber, metadata: regionMetadata)
} catch {
let plusRemovedNumberString = regexManager.replaceStringByRegex(PhoneNumberPatterns.leadingPlusCharsPattern, string: nationalNumber as String)
countryCode = try parser.extractCountryCode(plusRemovedNumberString, nationalNumber: &nationalNumber, metadata: regionMetadata)
}
if countryCode == 0 {
countryCode = regionMetadata.countryCode
}
// Nomralized number (5)
let normalizedNationalNumber = parser.normalizePhoneNumber(nationalNumber)
nationalNumber = normalizedNationalNumber
// If country code is not default, grab correct metadata (6)
if countryCode != regionMetadata.countryCode, let countryMetadata = metadataManager.mainTerritoryByCode[countryCode] {
regionMetadata = countryMetadata
}
// National Prefix Strip (7)
parser.stripNationalPrefix(&nationalNumber, metadata: regionMetadata)
// Test number against general number description for correct metadata (8)
if let generalNumberDesc = regionMetadata.generalDesc, (regexManager.hasValue(generalNumberDesc.nationalNumberPattern) == false || parser.isNumberMatchingDesc(nationalNumber, numberDesc: generalNumberDesc) == false) {
throw PhoneNumberError.notANumber
}
// Finalize remaining parameters and create phone number object (9)
let leadingZero = nationalNumber.hasPrefix("0")
guard let finalNationalNumber = UInt64(nationalNumber) else {
throw PhoneNumberError.notANumber
}
// Check if the number if of a known type (10)
var type: PhoneNumberType = .unknown
if ignoreType == false {
if let regionCode = getRegionCode(of: finalNationalNumber, countryCode: countryCode, leadingZero: leadingZero), let foundMetadata = metadataManager.territoriesByCountry[regionCode] {
regionMetadata = foundMetadata
}
type = parser.checkNumberType(String(nationalNumber), metadata: regionMetadata, leadingZero: leadingZero)
if type == .unknown {
throw PhoneNumberError.unknownType
}
}
let phoneNumber = PhoneNumber(numberString: numberString, countryCode: countryCode, leadingZero: leadingZero, nationalNumber: finalNationalNumber, numberExtension: numberExtension, type: type, regionID: regionMetadata.codeID)
return phoneNumber
}
// Parse task
/**
Fastest way to parse an array of phone numbers. Uses custom region code.
- Parameter numberStrings: An array of raw number strings.
- Parameter region: ISO 639 compliant region code.
- parameter ignoreType: Avoids number type checking for faster performance.
- Returns: An array of valid PhoneNumber objects.
*/
func parseMultiple(_ numberStrings: [String], withRegion region: String, ignoreType: Bool, shouldReturnFailedEmptyNumbers: Bool = false) -> [PhoneNumber] {
var hasError = false
var multiParseArray = [PhoneNumber](repeating: PhoneNumber.notPhoneNumber(), count: numberStrings.count)
DispatchQueue.concurrentPerform(iterations: numberStrings.count) { [unowned self] in
let numberString = numberStrings[$0]
do {
let phoneNumber = try self.parse(numberString, withRegion: region, ignoreType: ignoreType)
multiParseArray[$0] = phoneNumber
} catch {
hasError = true
}
}
if hasError && !shouldReturnFailedEmptyNumbers {
multiParseArray = multiParseArray.filter { $0.type != .notParsed }
}
return multiParseArray
}
/// Get correct ISO 639 compliant region code for a number.
///
/// - Parameters:
/// - nationalNumber: national number.
/// - countryCode: country code.
/// - leadingZero: whether or not the number has a leading zero.
/// - Returns: ISO 639 compliant region code.
func getRegionCode(of nationalNumber: UInt64, countryCode: UInt64, leadingZero: Bool) -> String? {
guard let regexManager = regexManager, let metadataManager = metadataManager, let regions = metadataManager.territoriesByCode[countryCode] else { return nil }
if regions.count == 1 {
return regions[0].codeID
}
let nationalNumberString = String(nationalNumber)
for region in regions {
if let leadingDigits = region.leadingDigits {
if regexManager.matchesAtStart(leadingDigits, string: nationalNumberString) {
return region.codeID
}
}
if leadingZero && parser.checkNumberType("0" + nationalNumberString, metadata: region) != .unknown {
return region.codeID
}
if parser.checkNumberType(nationalNumberString, metadata: region) != .unknown {
return region.codeID
}
}
return nil
}
}
| mit | b6f070c1a98537e91fba8e9731d82bf8 | 44.107595 | 233 | 0.677985 | 5.248159 | false | false | false | false |
ddaguro/clintonconcord | OIMApp/Accounts.swift | 1 | 2276 | //
// Accounts.swift
// OIMApp
//
// Created by Linh NGUYEN on 5/19/15.
// Copyright (c) 2015 Persistent Systems. All rights reserved.
//
import Foundation
class Accounts {
var count : String!
var cursor : String!
var limit : String!
var applications : Applications!
var entitlements : Entitlements!
var roles : Roles!
init(data : NSDictionary){
self.count = Utils.getStringFromJSON(data, key: "count")
self.cursor = Utils.getStringFromJSON(data, key: "cursor")
self.limit = Utils.getStringFromJSON(data, key: "limit")
if let appData = data["userAccounts"]!["userAppInstances"] as? NSDictionary {
self.applications = Applications(data: appData)
}
if let entData = data["userEntitlements"] as? NSDictionary {
self.entitlements = Entitlements(data: entData)
}
if let roleData = data["userRoles"] as? NSDictionary {
self.roles = Roles(data: roleData)
}
}
}
/*
class Accounts {
var appInstances = Applications()
var entitlements = Entitlements()
var roles = Roles()
init(data : NSDictionary){
var app : String?
app = Utils.getStringFromJSON(data, key: "appInstanceKey")
if let result = app {
self.appInstances.applicationInstanceName = Utils.getStringFromJSON(data, key: "applicationInstanceName")
}
var ent : String?
ent = Utils.getStringFromJSON(data, key: "entitlementKey")
if let result = ent {
self.entitlements.entitlementName = Utils.getStringFromJSON(data, key: "entitlementName")
}
var role : String?
role = Utils.getStringFromJSON(data, key: "roleKey")
if let result = role {
self.roles.roleName = Utils.getStringFromJSON(data, key: "roleName")
}
}
}
class Applications{
var appInstanceKey : String!
var applicationInstanceName : String!
}
class Entitlements {
var entitlementKey : String!
var entitlementName : String!
var entitlementDescription : String!
}
class Roles {
var roleKey : String!
var roleName : String!
}
*/ | mit | f819bd5f17c0703cb6489b46a5ab9f4d | 24.021978 | 117 | 0.603251 | 4.385356 | false | false | false | false |
shepting/AppleToast | Billboard/Toast/UIViewExtensions.swift | 1 | 3485 | //
// UIViewExtensions.swift
// Toast
//
// Created by Steven Hepting on 10/20/16.
// Copyright © 2016 Hepting. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
func fillSuperview(padding: CGFloat = 0.0) -> Void {
if let superview = self.superview {
let topBottomPadding = padding - 2
superview.leftAnchor.constraint(equalTo: leftAnchor, constant: -padding).isActive = true
superview.rightAnchor.constraint(equalTo: rightAnchor, constant: padding).isActive = true
superview.topAnchor.constraint(equalTo: topAnchor, constant: -topBottomPadding).isActive = true
superview.bottomAnchor.constraint(equalTo: bottomAnchor, constant: topBottomPadding).isActive = true
} else {
print("Not in a superview! No constraints being added.")
}
}
func fillHorizontally() -> Void {
if let superview = self.superview {
superview.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
superview.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
} else {
print("Not in a superview! No constraints being added.")
}
}
func fillVertically() -> Void {
if let superview = self.superview {
superview.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
superview.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
} else {
print("Not in a superview! No constraints being added.")
}
}
func constrainNearTop() {
if let superview = self.superview {
superview.topAnchor.constraint(equalTo: self.topAnchor, constant: -50).isActive = true
superview.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
} else {
print("Not in a superview! No constraints being added.")
}
}
func constrainNearBottom() {
if let superview = self.superview {
superview.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 150).isActive = true
superview.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
print("constraining near bottom")
} else {
print("Not in a superview! No constraints being added.")
}
}
func placeOnRightSide() {
if let superview = self.superview {
superview.topAnchor.constraint(equalTo: self.topAnchor, constant: -50).isActive = true
superview.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
print("constraining near bottom")
} else {
print("Not in a superview! No constraints being added.")
}
}
}
extension UIView {
func fadeInFromTransparent() {
self.alpha = 0
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 1.0
})
}
func fadeOutAfterDelay() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0) {
self.fadeOut()
}
}
func fadeOut() {
UIView.animate(withDuration: 0.3, animations: {
self.alpha = 0
})
}
func addSubviewToTop(_ view: UIView, completion: @escaping () -> ()) {
self.addSubview(view)
DispatchQueue.main.async {
self.bringSubview(toFront: view)
completion()
}
}
}
| mit | 190ececd5b2a980ca00d8a60a3c5ce3b | 32.5 | 112 | 0.620551 | 4.812155 | false | false | false | false |
wuyezhiguhun/DDSwift | DDSwift/音乐电台/Main/DDMRNavigationController.swift | 1 | 1642 | //
// DDMRNavigationController.swift
// DDSwift
//
// Created by 王允顶 on 17/7/25.
// Copyright © 2017年 王允顶. All rights reserved.
//
import UIKit
class DDMRNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.setSwiftTransparence()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//设置导航栏透明
func setSwiftTransparence() -> Void {
// self.navigationBar.isTranslucent = true
let navBar = UINavigationBar.appearance()
let imageSize = CGSize(width: self.view.width, height: 64)
UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale)
UIColor.clear.set()
UIRectFill(CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let pressedColorImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
navBar.setBackgroundImage(pressedColorImg, for: UIBarMetrics.default)
self.navigationBar.clipsToBounds = true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | c82b7e03d44fae107149aac176c11981 | 32.604167 | 106 | 0.688779 | 4.902736 | false | false | false | false |
crazytonyli/GeoNet-iOS | GeoNet/App/AppDelegate.swift | 1 | 2604 | //
// AppDelegate.swift
// GeoNet
//
// Created by Tony Li on 18/11/16.
// Copyright © 2016 Tony Li. All rights reserved.
//
import UIKit
enum AppTab {
case Quakes
case Shaking
case ReportShaking
case Volcanoes
case News
var tabName: String {
switch self {
case .Quakes: return "Quakes"
case .Shaking: return "Shaking"
case .ReportShaking: return "Felt It?"
case .Volcanoes: return "Volcanoes"
case .News: return "News"
}
}
var viewController: UIViewController.Type {
switch self {
case .Quakes: return QuakesViewController.self
case .Shaking: return ShakingViewController.self
case .ReportShaking: return ReportShakingViewController.self
case .Volcanoes: return VolcanoesViewController.self
case .News: return NewsViewController.self
}
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var selectedNavigationController: UINavigationController {
// swiftlint:disable force_cast
return (window?.rootViewController as! UITabBarController).selectedViewController as! UINavigationController
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let tab = GeoNetTabBarController()
tab.viewControllers = [AppTab.Quakes, .Shaking, .ReportShaking, .Volcanoes, .News]
.map { tab in
let controller = GeoNetNavigationController(rootViewController: tab.viewController.init())
controller.tabBarItem = UITabBarItem(title: tab.tabName, image: nil, tag: 0)
return controller
}
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = .white
window?.rootViewController = tab
window?.makeKeyAndVisible()
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if let quakeIdentifier = (url.host == "quake" && url.pathComponents.count == 2 ? url.pathComponents.last : nil) {
// TODO show & hide HUD
URLSession.API.quake(quakeIdentifier) {
if case .success(let quake) = $0 {
self.selectedNavigationController.pushViewController(QuakeMapViewController(quake: quake), animated: true)
}
}
return true
}
return false
}
}
| mit | fb8eb36f55be8769c26f7dfb349d70ec | 29.623529 | 126 | 0.641567 | 5.015414 | false | false | false | false |
davedelong/DDMathParser | MathParser/Sources/MathParser/LocalizedNumberExtractor.swift | 1 | 2309 | //
// LocalizedNumberExtractor.swift
// DDMathParser
//
// Created by Dave DeLong on 8/31/15.
//
//
import Foundation
internal struct LocalizedNumberExtractor: TokenExtractor {
private let decimalNumberFormatter = NumberFormatter()
internal init(locale: Locale) {
decimalNumberFormatter.locale = locale
decimalNumberFormatter.numberStyle = .decimal
}
func matchesPreconditions(_ buffer: TokenCharacterBuffer, configuration: Configuration) -> Bool {
return buffer.peekNext() != nil
}
func extract(_ buffer: TokenCharacterBuffer, configuration: Configuration) -> Tokenizer.Result {
let start = buffer.currentIndex
var indexBeforeDecimal: Int?
var soFar = ""
while let peek = buffer.peekNext(), peek.isWhitespace == false {
let test = soFar + String(peek)
if indexBeforeDecimal == nil && test.hasSuffix(decimalNumberFormatter.decimalSeparator) {
indexBeforeDecimal = buffer.currentIndex
}
if canParseString(test) || (start == 0 && isValidPrefix(test)) {
soFar = test
buffer.consume()
} else {
break
}
}
if let indexBeforeDecimal = indexBeforeDecimal, soFar.hasSuffix(decimalNumberFormatter.decimalSeparator) {
buffer.resetTo(indexBeforeDecimal)
soFar = buffer[start ..< indexBeforeDecimal]
}
let indexAfterNumber = buffer.currentIndex
let range: Range<Int> = start ..< indexAfterNumber
if range.isEmpty {
let error = MathParserError(kind: .cannotParseNumber, range: range)
return .error(error)
}
let token = LocalizedNumberToken(string: soFar, range: range)
return .value(token)
}
/// - Returns: True if the string is a valid prefix of a localized number.
private func isValidPrefix(_ string: String) -> Bool {
return string == decimalNumberFormatter.decimalSeparator
}
private func canParseString(_ string: String) -> Bool {
guard let _ = decimalNumberFormatter.number(from: string) else { return false }
return true
}
}
| mit | 600213dc3b9454d5007e04eb14157678 | 31.985714 | 114 | 0.610221 | 5.247727 | false | true | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Blog Dashboard/ViewModel/DashboardStatsViewModel.swift | 1 | 904 | import Foundation
class DashboardStatsViewModel {
// MARK: Private Variables
private var apiResponse: BlogDashboardRemoteEntity
// MARK: Initializer
init(apiResponse: BlogDashboardRemoteEntity) {
self.apiResponse = apiResponse
}
// MARK: Public Variables
var todaysViews: String {
apiResponse.todaysStats?.views?.abbreviatedString(forHeroNumber: true) ?? "0"
}
var todaysVisitors: String {
apiResponse.todaysStats?.visitors?.abbreviatedString(forHeroNumber: true) ?? "0"
}
var todaysLikes: String {
apiResponse.todaysStats?.likes?.abbreviatedString(forHeroNumber: true) ?? "0"
}
var shouldDisplayNudge: Bool {
guard let todaysStats = apiResponse.todaysStats else {
return false
}
return todaysStats.views == 0 && todaysStats.visitors == 0 && todaysStats.likes == 0
}
}
| gpl-2.0 | 30153056ce32e175e0843152bfd0a40d | 24.111111 | 92 | 0.667035 | 4.588832 | false | false | false | false |
LightD/ivsa-server | Sources/App/Models/IVSAUser.swift | 1 | 8177 | //
// User.swift
// ivsa
//
// Created by Light Dream on 14/11/2016.
//
//
import Foundation
import Vapor
import Fluent
import Turnstile
import TurnstileCrypto
import Transport
import SMTP
enum ApplicationStatus: String, NodeInitializable, NodeRepresentable {
case nonApplicant
case inReview
case newApplicant
case accepted
case rejected
case confirmedRejected
init(node: Node, in context: Context) throws {
// TODO: Add proper error handling here, instead of force unwrapping
let status = node.string!
self = ApplicationStatus(rawValue: status)!
}
func makeNode(context: Context) throws -> Node {
return Node(stringLiteral: self.rawValue)
}
}
//struct ProofOfPayment: NodeInitializable, NodeRepresentable {
// var congressPaymentPaidDate: String
// var congressPaymentRemarks: String
//
// var postcongressPaidDate: String
// var postcongressPaidRemarks: String
//
// init(node: Node, in context: Context) throws {
// self.congressPaymentPaidDate = try node.extract("congress_payment_date")
// self.congressPaymentRemarks = try node.extract("congress_payment_remarks")
// self.postcongressPaidDate = try node.extract("post_congress_payment_date")
// self.postcongressPaidRemarks = try node.extract("post_congress_payment_remarks")
// }
//
// func makeNode(context: Context) throws -> Node {
//
// return try Node(node: [
// "congress_payment_date": congressPaymentPaidDate,
// "congress_payment_remarks": congressPaymentRemarks,
// "post_congress_payment_date": postcongressPaidDate,
// "post_congress_payment_remarks": postcongressPaidRemarks
// ])
// }
//}
final class IVSAUser: Model, NodeInitializable {
// this is for fluent ORM
var exists: Bool = false
var id: Node?
var email: String
var password: String
var accessToken: String? // when it's nil, the user is logged out
var applicationStatus: ApplicationStatus = .nonApplicant
var registrationDetails: RegistrationData? // this is nil before the user registers.
var isVerified: Bool
var verificationToken: String = URandom().secureToken
var didSendCorrectionEmail: Bool = false
var isPasswordResetting: Bool = false
var resetPasswordToken: String = URandom().secureToken
init() {
self.email = ""
self.password = ""
self.isVerified = false
self.didSendCorrectionEmail = false
}
init(node: Node) throws {
id = try node.extract("_id") // that's mongo's ID
email = try node.extract("email")
password = try node.extract("password")
accessToken = try node.extract("access_token")
applicationStatus = try node.extract("application_status")
registrationDetails = try node.extract("registration_details")
isVerified = try node.extract("is_verified")
verificationToken = try node.extract("verification_token")
do {
isPasswordResetting = try node.extract("is_resetting_password")
}
catch { isPasswordResetting = false }
do {
resetPasswordToken = try node.extract("reset_password_token")
}
catch { resetPasswordToken = URandom().secureToken }
do {
didSendCorrectionEmail = try node.extract("correction_email_sent")
} catch { didSendCorrectionEmail = false }
}
init(node: Node, in context: Context) throws {
id = try node.extract("_id") // that's mongo's ID
email = try node.extract("email")
password = try node.extract("password")
accessToken = try node.extract("access_token")
applicationStatus = try node.extract("application_status")
registrationDetails = try node.extract("registration_details")
isVerified = try node.extract("is_verified")
verificationToken = try node.extract("verification_token")
do {
isPasswordResetting = try node.extract("is_resetting_password")
}
catch { isPasswordResetting = false }
do {
resetPasswordToken = try node.extract("reset_password_token")
}
catch { resetPasswordToken = URandom().secureToken }
do {
didSendCorrectionEmail = try node.extract("correction_email_sent")
} catch { didSendCorrectionEmail = false }
}
init(credentials: UsernamePassword) {
self.email = credentials.username
self.password = BCrypt.hash(password: credentials.password)
self.accessToken = BCrypt.hash(password: credentials.password)
self.isVerified = false
}
func updatePassword(pass: String) {
self.password = BCrypt.hash(password: pass)
self.isPasswordResetting = false
}
func generateAccessToken() {
self.accessToken = BCrypt.hash(password: self.password)
}
func generateResetPasswordToken() {
self.resetPasswordToken = URandom().secureToken
self.isPasswordResetting = true
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"_id": id,
"email": email,
"password": password,
"access_token": accessToken,
"application_status": applicationStatus,
"registration_details": registrationDetails,
"is_verified": isVerified,
"verification_token": verificationToken,
"correction_email_sent": didSendCorrectionEmail,
"reset_password_token": resetPasswordToken,
"is_resetting_password": isPasswordResetting
])
}
}
/// Since we are dealing with mongo, we don't need to implement this
extension IVSAUser: Preparation {
static func prepare(_ database: Database) throws { }
static func revert(_ database: Database) throws { }
}
import Auth
extension IVSAUser: Auth.User {
static func authenticate(credentials: Credentials) throws -> Auth.User {
var user: IVSAUser?
debugPrint("authenticating user with credentials: \(credentials)")
switch credentials {
case let credentials as Identifier:
user = try IVSAUser.find(credentials.id)
case let credentials as UsernamePassword:
let alldadings = try IVSAUser.query()
.filter("email", credentials.username)
.run()
debugPrint(alldadings)
let fetchedUser = try IVSAUser.query()
.filter("email", credentials.username)
.first()
if let password = fetchedUser?.password,
password != "",
(try? BCrypt.verify(password: credentials.password, matchesHash: password)) == true {
user = fetchedUser
}
case let credentials as AccessToken:
user = try IVSAUser
.query()
.filter("access_token", "\(credentials.string)")
.first()
default:
throw Abort.custom(status: .badRequest, message: "Unsupported credentials.")
}
guard let u = user else {
throw Abort.custom(status: .badRequest, message: "Incorrect credentials.")
}
return u
}
static func register(credentials: Credentials) throws -> Auth.User {
// create a user and
var newUser: IVSAUser
switch credentials {
case let credentials as UsernamePassword:
newUser = IVSAUser(credentials: credentials)
default:
throw Abort.custom(status: .badRequest, message: "Unsupported credentials.")
}
if try IVSAUser.query().filter("email", newUser.email).first() == nil {
try newUser.save()
return newUser
} else {
throw Abort.custom(status: .badRequest, message: "This email is already in use, please login instead!")
}
}
}
import HTTP
extension Request {
func user() throws -> IVSAUser {
return try ivsaAuth.user()
}
}
| mit | 6aa3f2fc9cb9a89408bc7f6a317391ce | 30.941406 | 115 | 0.624679 | 4.542778 | false | false | false | false |
fuzongjian/SwiftStudy | SwiftStudy/Basis/CollectionTypesController.swift | 1 | 5563 | //
// CollectionTypesController.swift
// SwiftBasisStudy
//
// Created by 陈舒澳 on 16/5/3.
// Copyright © 2016年 speeda. All rights reserved.
//
/** 集合类型
* Swift提供了两种集合类型来存放多个值——数组(Array)和字典(Dictionary)。
* 数据把相同类型的值存放在一个有序链表里,字典把相同类型的值存放在一个无序集合里,这些值可以通过唯一标识符来引用和查找
* 在Swift里,数据和字典里所能存放的值的类型是明确的
*
*
*
*/
import UIKit
class CollectionTypesController: SuperViewController {
override func viewDidLoad() {
super.viewDidLoad()
// testArray()
testDictionary()
// Do any additional setup after loading the view.
}
func testDictionary(){
//字典初始化
var airports: Dictionary<String,String> = ["TYO": "Tokyo","DUB": "Dublin"]
let airportsecond = ["TYO": "Tokyo","DUB": "Dublin"]
print("字典初始化 airports == \(airports)\n airportsecond==\(airportsecond)")
//字典的存取与修改
//获取元素数量
print("the dictionary of airports contains \(airports.count) items")
// 添加元素(可以使用下标语法向字典中添加新的元素。以一个合适类型的新键作为下标索引,并且赋给它一个合适类型的值:)
airports["fu"] = "zong"
print("add the newDictionary is \(airports)")
// 修改元素(也可以使用下标语法来改动某个键对应的值:)
airports["fu"] = "jian"
print("update the newDictionary is \(airports)")
// updateValue(forKey:)
// 如果oldValue的值存在,则表明更新前该键有相应的值,否则无。可以检测是否发生了值得更新
// 同时可以检测是否存在该键
if let oldValue = airports.updateValue("yang", forKey: "fu"){
print("the old value for fu was \(oldValue)")
}
// removeValueForKey
// 删除键值对 如果该键值对存在的话,就返回删掉的值,否则返回nil
if let removeValue = airports.removeValueForKey("fu"){
print("removeValue = \(removeValue)")
}
print("delete the newDictionary is \(airports)")
// 也可以将键对应的值置为nil来删除键值对
airports["TYO"] = nil
print("delete the newDictionary is \(airports)")
// 将字典所有键和值放在一个Array中
let airKeys = Array(airports.keys)
let airValues = Array(airports.values)
print(airKeys)
print(airValues)
}
func testArray (){
//数组的创建与初始化
var someInts = [Int]()
someInts.append(2)
print("数组的创建与初始化 \(someInts)")
someInts = []//现在成为了一个空数组,但其类型仍然是Int[]
print("数组的创建与初始化 \(someInts)")
// Swift数组还提供了一个生成若干个重复元素组成的数组的初始化函数
let someseond = [Double](count: 3, repeatedValue: 0.0)
print("一个生成若干个重复元素组成的数组的初始化函数\(someseond)")
// 数组的声明
var arrayOne: [String] = ["fu","zong","jian"]
let arrayTwo = ["egg","milk","pig"]
print("the arrayOne contains \(arrayOne.count) items the arrayTwo contains \(arrayTwo.count) items" )
// 数组的存取和修改
// 使用Boolean型的isEmpty属性,可以快速检查count属性是否为0:
if arrayOne.isEmpty {
print("empty")
}else{
print("there is something")
}
//往数组的末尾添加一个元素,可以调用数组的append方法:
arrayOne.append("dayday")
print("arrayOne.append == \(arrayOne)")
// 使用下标语法取值
let second = arrayOne[2]
print("使用下标语法取值arrayOne[2]= \(second)")
//通过下标索引修改已经存在的值
arrayOne[1] = "up"
print("通过下标索引修改已经存在的值\(arrayOne)")
//一次性修改指定范围的值
arrayOne[1...2] = ["one","two"]
print("一次性修改指定范围的值 \(arrayOne)")
//将元素插入到指定位置(该位置及该位置后面的值依次后移)
arrayOne.insert("perfect", atIndex: 2)
print("将元素插入到指定位置 \(arrayOne)")
// 删除指定位置的值
let removeItem = arrayOne.removeAtIndex(0)
let firstItem = arrayOne[0]
print("删除指定位置的值 removeItem = \(removeItem)\n firstItem = \(firstItem)\n arrayOne = \(arrayOne)")
// 数据的迭代访问
for item in arrayOne{
print(item)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
}
| apache-2.0 | 1d5746f8ef35b12ebb381565d14e98f0 | 29.950355 | 109 | 0.586389 | 3.791486 | false | false | false | false |
Rochester-Ting/DouyuTVDemo | RRDouyuTV/RRDouyuTV/Classes/Home(首页)/RAchorModel.swift | 1 | 829 | //
// RAchorModel.swift
// RRDouyuTV
//
// Created by 丁瑞瑞 on 15/10/16.
// Copyright © 2016年 Rochester. All rights reserved.
//
import UIKit
class RAchorModel: NSObject {
// 主播名字
var nickname : String = ""
// 房间名字
var room_name : String = ""
// 背景图片
var vertical_src :String = ""
// 在线观看人数
var online : Int = 0
// 房间ID
var room_id : Int = 0
// 是否是手机直播
var isVertical : Int = 0
// 所属游戏分组
var game_name : String = ""
/// 房间ID
// 所在地区
var anchor_city : String = ""
init(dict : [String : NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| mit | 95d94bbe585adc1471c651a8e299e055 | 17.55 | 72 | 0.537736 | 3.483568 | false | false | false | false |
opfeffer/swift-sodium | Sodium/Box.swift | 1 | 22129 | //
// Box.swift
// Sodium
//
// Created by Frank Denis on 12/28/14.
// Copyright (c) 2014 Frank Denis. All rights reserved.
//
import Foundation
import libsodium
public class Box {
public let SeedBytes = Int(crypto_box_seedbytes())
public let PublicKeyBytes = Int(crypto_box_publickeybytes())
public let SecretKeyBytes = Int(crypto_box_secretkeybytes())
public let NonceBytes = Int(crypto_box_noncebytes())
public let MacBytes = Int(crypto_box_macbytes())
public let Primitive = String.init(validatingUTF8:crypto_box_primitive())
public let BeforenmBytes = Int(crypto_box_beforenmbytes())
public let SealBytes = Int(crypto_box_sealbytes())
public typealias PublicKey = Data
public typealias SecretKey = Data
public typealias Nonce = Data
public typealias MAC = Data
public typealias Beforenm = Data
public struct KeyPair {
public let publicKey: PublicKey
public let secretKey: SecretKey
public init(publicKey: PublicKey, secretKey: SecretKey) {
self.publicKey = publicKey
self.secretKey = secretKey
}
}
/**
Generates an encryption secret key and a corresponding public key.
- Returns: A key pair containing the secret key and public key.
*/
public func keyPair() -> KeyPair? {
var pk = Data(count: PublicKeyBytes)
var sk = Data(count: SecretKeyBytes)
let result = pk.withUnsafeMutableBytes { pkPtr in
return sk.withUnsafeMutableBytes { skPtr in
return crypto_box_keypair(pkPtr, skPtr)
}
}
if result != 0 {
return nil
}
return KeyPair(publicKey: pk, secretKey: sk)
}
/**
Generates an encryption secret key and a corresponding public key derived from a seed.
- Parameter seed: The value from which to derive the secret and public key.
- Returns: A key pair containing the secret key and public key.
*/
public func keyPair(seed: Data) -> KeyPair? {
if seed.count != SeedBytes {
return nil
}
var pk = Data(count: PublicKeyBytes)
var sk = Data(count: SecretKeyBytes)
let result = pk.withUnsafeMutableBytes { pkPtr in
return sk.withUnsafeMutableBytes { skPtr in
return seed.withUnsafeBytes { seedPtr in
return crypto_box_seed_keypair(pkPtr, skPtr, seedPtr)
}
}
}
if result != 0 {
return nil
}
return KeyPair(publicKey: pk, secretKey: sk)
}
public func nonce() -> Nonce {
var nonce = Data(count: NonceBytes)
nonce.withUnsafeMutableBytes { noncePtr in
randombytes_buf(noncePtr, nonce.count)
}
return nonce
}
/**
Encrypts a message with a recipient's public key and a sender's secret key.
- Parameter message: The message to encrypt.
- Parameter recipientPublicKey: The recipient's public key.
- Parameter senderSecretKey: The sender's secret key.
- Returns: A `Data` object containing the nonce and authenticated ciphertext.
*/
public func seal(message: Data, recipientPublicKey: PublicKey, senderSecretKey: SecretKey) -> Data? {
guard let (authenticatedCipherText, nonce): (Data, Nonce) = seal(message: message, recipientPublicKey: recipientPublicKey, senderSecretKey: senderSecretKey) else {
return nil
}
var nonceAndAuthenticatedCipherText = nonce
nonceAndAuthenticatedCipherText.append(authenticatedCipherText)
return nonceAndAuthenticatedCipherText
}
/**
Encrypts a message with a recipient's public key and a sender's secret key using a user-provided nonce.
- Parameter message: The message to encrypt.
- Parameter recipientPublicKey: The recipient's public key.
- Parameter senderSecretKey: The sender's secret key.
- Paramter nonce: The user-specified nonce.
- Returns: The authenticated ciphertext.
*/
public func seal(message: Data, recipientPublicKey: PublicKey, senderSecretKey: SecretKey, nonce: Nonce) -> Data? {
guard recipientPublicKey.count == PublicKeyBytes, senderSecretKey.count == SecretKeyBytes, nonce.count == NonceBytes else { return nil }
var authenticatedCipherText = Data(count: message.count + MacBytes)
let result = authenticatedCipherText.withUnsafeMutableBytes { authenticatedCipherTextPtr in
return message.withUnsafeBytes { messagePtr in
return nonce.withUnsafeBytes { noncePtr in
return recipientPublicKey.withUnsafeBytes { recipientPublicKeyPtr in
return senderSecretKey.withUnsafeBytes { senderSecretKeyPtr in
return crypto_box_easy(
authenticatedCipherTextPtr,
messagePtr,
CUnsignedLongLong(message.count),
noncePtr,
recipientPublicKeyPtr,
senderSecretKeyPtr)
}
}
}
}
}
if result != 0 {
return nil
}
return authenticatedCipherText
}
/**
Encrypts a message with a recipient's public key and a sender's secret key.
- Parameter message: The message to encrypt.
- Parameter recipientPublicKey: The recipient's public key.
- Parameter senderSecretKey: The sender's secret key.
- Returns: The authenticated ciphertext and encryption nonce.
*/
public func seal(message: Data, recipientPublicKey: PublicKey, senderSecretKey: SecretKey) -> (authenticatedCipherText: Data, nonce: Nonce)? {
if recipientPublicKey.count != PublicKeyBytes || senderSecretKey.count != SecretKeyBytes {
return nil
}
var authenticatedCipherText = Data(count: message.count + MacBytes)
let nonce = self.nonce()
let result = authenticatedCipherText.withUnsafeMutableBytes { authenticatedCipherTextPtr in
return message.withUnsafeBytes { messagePtr in
return nonce.withUnsafeBytes { noncePtr in
return recipientPublicKey.withUnsafeBytes { recipientPublicKeyPtr in
return senderSecretKey.withUnsafeBytes { senderSecretKeyPtr in
return crypto_box_easy(
authenticatedCipherTextPtr,
messagePtr,
CUnsignedLongLong(message.count),
noncePtr,
recipientPublicKeyPtr,
senderSecretKeyPtr)
}
}
}
}
}
if result != 0 {
return nil
}
return (authenticatedCipherText: authenticatedCipherText, nonce: nonce)
}
/**
Encrypts a message with a recipient's public key and a sender's secret key (detached mode).
- Parameter message: The message to encrypt.
- Parameter recipientPublicKey: The recipient's public key.
- Parameter senderSecretKey: The sender's secret key.
- Returns: The authenticated ciphertext, encryption nonce, and authentication tag.
*/
public func seal(message: Data, recipientPublicKey: PublicKey, senderSecretKey: SecretKey) -> (authenticatedCipherText: Data, nonce: Nonce, mac: MAC)? {
if recipientPublicKey.count != PublicKeyBytes || senderSecretKey.count != SecretKeyBytes {
return nil
}
var authenticatedCipherText = Data(count: message.count)
var mac = Data(count: MacBytes)
let nonce = self.nonce()
let result = authenticatedCipherText.withUnsafeMutableBytes { authenticatedCipherTextPtr in
return mac.withUnsafeMutableBytes { macPtr in
return message.withUnsafeBytes { messagePtr in
return nonce.withUnsafeBytes { noncePtr in
return recipientPublicKey.withUnsafeBytes { recipientPublicKeyPtr in
return senderSecretKey.withUnsafeBytes { senderSecretKeyPtr in
return crypto_box_detached(
authenticatedCipherTextPtr,
macPtr,
messagePtr,
CUnsignedLongLong(message.count),
noncePtr,
recipientPublicKeyPtr,
senderSecretKeyPtr)
}
}
}
}
}
}
if result != 0 {
return nil
}
return (authenticatedCipherText: authenticatedCipherText, nonce: nonce as Nonce, mac: mac as MAC)
}
/**
Decrypts a message with a sender's public key and the recipient's secret key.
- Parameter nonceAndAuthenticatedCipherText: A `Data` object containing the nonce and authenticated ciphertext.
- Parameter senderPublicKey: The sender's public key.
- Parameter recipientSecretKey: The recipient's secret key.
- Returns: The decrypted message.
*/
public func open(nonceAndAuthenticatedCipherText: Data, senderPublicKey: PublicKey, recipientSecretKey: SecretKey) -> Data? {
if nonceAndAuthenticatedCipherText.count < NonceBytes + MacBytes {
return nil
}
let nonce = nonceAndAuthenticatedCipherText.subdata(in: 0..<NonceBytes) as Nonce
let authenticatedCipherText = nonceAndAuthenticatedCipherText.subdata(in: NonceBytes..<nonceAndAuthenticatedCipherText.count)
return open(authenticatedCipherText: authenticatedCipherText, senderPublicKey: senderPublicKey, recipientSecretKey: recipientSecretKey, nonce: nonce)
}
/**
Decrypts a message with a sender's public key, recipient's secret key, and encryption nonce.
- Parameter authenticatedCipherText: The authenticated ciphertext.
- Parameter senderPublicKey: The sender's public key.
- Parameter recipientSecretKey: The recipient's secret key.
- Parameter nonce: The encryption nonce.
- Returns: The decrypted message.
*/
public func open(authenticatedCipherText: Data, senderPublicKey: PublicKey, recipientSecretKey: SecretKey, nonce: Nonce) -> Data? {
if nonce.count != NonceBytes || authenticatedCipherText.count < MacBytes {
return nil
}
if senderPublicKey.count != PublicKeyBytes || recipientSecretKey.count != SecretKeyBytes {
return nil
}
var message = Data(count: authenticatedCipherText.count - MacBytes)
let result = message.withUnsafeMutableBytes { messagePtr in
return authenticatedCipherText.withUnsafeBytes { authenticatedCipherTextPtr in
return nonce.withUnsafeBytes { noncePtr in
return senderPublicKey.withUnsafeBytes { senderPublicKeyPtr in
return recipientSecretKey.withUnsafeBytes { recipientSecretKeyPtr in
return crypto_box_open_easy(
messagePtr,
authenticatedCipherTextPtr,
CUnsignedLongLong(authenticatedCipherText.count),
noncePtr,
senderPublicKeyPtr,
recipientSecretKeyPtr)
}
}
}
}
}
if result != 0 {
return nil
}
return message
}
/**
Decrypts a message with a sender's public key, recipient's secret key, encryption nonce, and authentication tag.
- Parameter authenticatedCipherText: The authenticated ciphertext.
- Parameter senderPublicKey: The sender's public key.
- Parameter recipientSecretKey: The recipient's secret key.
- Parameter nonce: The encryption nonce.
- Parameter mac: The authentication tag.
- Returns: The decrypted message.
*/
public func open(authenticatedCipherText: Data, senderPublicKey: PublicKey, recipientSecretKey: SecretKey, nonce: Nonce, mac: MAC) -> Data? {
if nonce.count != NonceBytes || mac.count != MacBytes {
return nil
}
if senderPublicKey.count != PublicKeyBytes || recipientSecretKey.count != SecretKeyBytes {
return nil
}
var message = Data(count: authenticatedCipherText.count)
let result = message.withUnsafeMutableBytes { messagePtr in
return authenticatedCipherText.withUnsafeBytes { authenticatedCipherTextPtr in
return mac.withUnsafeBytes { macPtr in
return nonce.withUnsafeBytes { noncePtr in
return senderPublicKey.withUnsafeBytes { senderPublicKeyPtr in
return recipientSecretKey.withUnsafeBytes { recipientSecretKeyPtr in
return crypto_box_open_detached(
messagePtr,
authenticatedCipherTextPtr,
macPtr,
CUnsignedLongLong(authenticatedCipherText.count),
noncePtr,
senderPublicKeyPtr,
recipientSecretKeyPtr)
}
}
}
}
}
}
if result != 0 {
return nil
}
return message
}
/**
Computes a shared secret key given a public key and a secret key.
Applications that send several messages to the same receiver or receive several messages from the same sender can gain speed by calculating the shared key only once, and reusing it in subsequent operations.
- Parameter recipientPublicKey: The recipient's public key.
- Parameter senderSecretKey: The sender's secret key.
- Returns: The computed shared secret key
*/
public func beforenm(recipientPublicKey: PublicKey, senderSecretKey: SecretKey) -> Data? {
var key = Data(count: BeforenmBytes)
let result = key.withUnsafeMutableBytes { keyPtr in
return recipientPublicKey.withUnsafeBytes { recipientPublicKeyPtr in
return senderSecretKey.withUnsafeBytes { senderSecretKeyPtr in
return crypto_box_beforenm(keyPtr, recipientPublicKeyPtr, senderSecretKeyPtr)
}
}
}
if result != 0 {
return nil
}
return key
}
/**
Encrypts a message with the shared secret key generated from a recipient's public key and a sender's secret key using `beforenm()`.
- Parameter message: The message to encrypt.
- Parameter beforenm: The shared secret key.
- Returns: The authenticated ciphertext and encryption nonce.
*/
public func seal(message: Data, beforenm: Beforenm) -> (authenticatedCipherText: Data, nonce: Nonce)? {
if beforenm.count != BeforenmBytes {
return nil
}
var authenticatedCipherText = Data(count: message.count + MacBytes)
let nonce = self.nonce()
let result = authenticatedCipherText.withUnsafeMutableBytes { authenticatedCipherTextPtr in
return message.withUnsafeBytes { messagePtr in
return nonce.withUnsafeBytes { noncePtr in
return beforenm.withUnsafeBytes { beforenmPtr in
return crypto_box_easy_afternm(
authenticatedCipherTextPtr,
messagePtr,
CUnsignedLongLong(message.count),
noncePtr,
beforenmPtr)
}
}
}
}
if result != 0 {
return nil
}
return (authenticatedCipherText: authenticatedCipherText, nonce: nonce)
}
/**
Decrypts a message with the shared secret key generated from a recipient's public key and a sender's secret key using `beforenm()`.
- Parameter nonceAndAuthenticatedCipherText: A `Data` object containing the nonce and authenticated ciphertext.
- Parameter beforenm: The shared secret key.
- Returns: The decrypted message.
*/
public func open(nonceAndAuthenticatedCipherText: Data, beforenm: Beforenm) -> Data? {
if nonceAndAuthenticatedCipherText.count < NonceBytes + MacBytes {
return nil
}
let nonce = nonceAndAuthenticatedCipherText.subdata(in: 0..<NonceBytes) as Nonce
let authenticatedCipherText = nonceAndAuthenticatedCipherText.subdata(in: NonceBytes..<nonceAndAuthenticatedCipherText.count)
return open(authenticatedCipherText: authenticatedCipherText, beforenm: beforenm, nonce: nonce)
}
/**
Decrypts a message and encryption nonce with the shared secret key generated from a recipient's public key and a sender's secret key using `beforenm()`.
- Parameter authenticatedCipherText: The authenticated ciphertext.
- Parameter beforenm: The shared secret key.
- Parameter nonce: The encryption nonce.
- Returns: The decrypted message.
*/
public func open(authenticatedCipherText: Data, beforenm: Beforenm, nonce: Nonce) -> Data? {
if nonce.count != NonceBytes || authenticatedCipherText.count < MacBytes {
return nil
}
if beforenm.count != BeforenmBytes {
return nil
}
var message = Data(count: authenticatedCipherText.count - MacBytes)
let result = message.withUnsafeMutableBytes { messagePtr in
return authenticatedCipherText.withUnsafeBytes { authenticatedCipherTextPtr in
return nonce.withUnsafeBytes { noncePtr in
return beforenm.withUnsafeBytes { beforenmPtr in
return crypto_box_open_easy_afternm(
messagePtr,
authenticatedCipherTextPtr,
CUnsignedLongLong(authenticatedCipherText.count),
noncePtr,
beforenmPtr)
}
}
}
}
if result != 0 {
return nil
}
return message
}
/**
Encrypts a message with the shared secret key generated from a recipient's public key and a sender's secret key using `beforenm()`.
- Parameter message: The message to encrypt.
- Parameter beforenm: The shared secret key.
- Returns: A `Data` object containing the encryption nonce and authenticated ciphertext.
*/
public func seal(message: Data, beforenm: Beforenm) -> Data? {
guard let (authenticatedCipherText, nonce): (Data, Nonce) = seal(message: message, beforenm: beforenm) else {
return nil
}
var nonceAndAuthenticatedCipherText = nonce
nonceAndAuthenticatedCipherText.append(authenticatedCipherText)
return nonceAndAuthenticatedCipherText
}
/**
Encrypts a message with a recipient's public key.
- Parameter message: The message to encrypt.
- Parameter recipientPublicKey: The recipient's public key.
- Returns: The anonymous ciphertext.
*/
public func seal(message: Data, recipientPublicKey: Box.PublicKey) -> Data? {
if recipientPublicKey.count != PublicKeyBytes {
return nil
}
var anonymousCipherText = Data(count: SealBytes + message.count)
let result = anonymousCipherText.withUnsafeMutableBytes { anonymousCipherTextPtr in
return message.withUnsafeBytes { messagePtr in
return recipientPublicKey.withUnsafeBytes { recipientPublicKeyPtr in
return crypto_box_seal(
anonymousCipherTextPtr,
messagePtr,
CUnsignedLongLong(message.count),
recipientPublicKeyPtr)
}
}
}
if result != 0 {
return nil
}
return anonymousCipherText
}
/**
Decrypts a message with the recipient's public key and secret key.
- Parameter anonymousCipherText: A `Data` object containing the anonymous ciphertext.
- Parameter senderPublicKey: The recipient's public key.
- Parameter recipientSecretKey: The recipient's secret key.
- Returns: The decrypted message.
*/
public func open(anonymousCipherText: Data, recipientPublicKey: PublicKey, recipientSecretKey: SecretKey) -> Data? {
if recipientPublicKey.count != PublicKeyBytes || recipientSecretKey.count != SecretKeyBytes || anonymousCipherText.count < SealBytes {
return nil
}
var message = Data(count: anonymousCipherText.count - SealBytes)
let result = message.withUnsafeMutableBytes { messagePtr in
return anonymousCipherText.withUnsafeBytes { anonymousCipherTextPtr in
return recipientPublicKey.withUnsafeBytes { recipientPublicKeyPtr in
return recipientSecretKey.withUnsafeBytes { recipientSecretKeyPtr in
return crypto_box_seal_open(
messagePtr,
anonymousCipherTextPtr,
CUnsignedLongLong(anonymousCipherText.count),
recipientPublicKeyPtr,
recipientSecretKeyPtr)
}
}
}
}
if result != 0 {
return nil
}
return message
}
}
| isc | 2a5fd07b715b6a386b293b49e8fa7da3 | 38.305506 | 211 | 0.608613 | 5.669741 | false | false | false | false |
kharrison/CodeExamples | Container/Container-code/Container/LocationDataSource.swift | 2 | 3324 | //
// LocationDataSource.swift
// Container
//
// Created by Keith Harrison http://useyourloaf.com
// Copyright (c) 2017 Keith Harrison. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import UIKit
final class LocationDataSource: NSObject {
private let tableView: UITableView
private var locations = [Location]()
init(tableView: UITableView, from path: String) {
self.tableView = tableView
super.init()
readFromPlist(name: path)
tableView.dataSource = self
tableView.reloadData()
}
func locationAtIndexPath(_ indexPath: IndexPath) -> Location? {
return indexPath.row < locations.count ? locations[indexPath.row] : nil
}
private func readFromPlist(name: String) {
guard let items = NSArray(contentsOfFile: name) as? [Dictionary<String,String>] else {
return
}
for item in items {
if let location = Location(dictionary: item) {
locations.append(location)
}
}
}
}
extension LocationDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locations.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: LocationCell.reuseIdentifier, for: indexPath)
configure(cell: cell, indexPath: indexPath)
return cell
}
private func configure(cell: UITableViewCell, indexPath: IndexPath) {
if let cell = cell as? LocationCell {
let object = locations[indexPath.row]
cell.configure(object: object)
}
}
}
| bsd-3-clause | 6651eb47347be6946eeeac7f24d8de28 | 36.772727 | 110 | 0.704573 | 4.789625 | false | false | false | false |
chromatic-seashell/weibo | 新浪微博/新浪微博/classes/GDWNewfeatureViewController.swift | 1 | 5637 | //
// GDWNewfeatureViewController.swift
// 新浪微博
//
// Created by apple on 15/11/13.
// Copyright © 2015年 apple. All rights reserved.
//
import UIKit
import SnapKit
class GDWNewfeatureViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
// 新特性界面总数
let maxImageCount = 4
override func viewDidLoad() {
super.viewDidLoad()
}
func newfeatureViewController() -> GDWNewfeatureViewController{
let sb = UIStoryboard(name: "GDWNewfeatureViewController", bundle: nil)
let newVc = sb.instantiateInitialViewController() as! GDWNewfeatureViewController
return newVc
}
// MARK: - UICollectionViewDataSource
// 告诉系统当前组有多少行
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return maxImageCount
}
// 告诉系统当前行显示什么内容
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("newfeatureCell", forIndexPath: indexPath) as! GDWCollectionViewCell
cell.index = indexPath.item
// 以下代码, 主要为了避免重用问题
cell.startButton.hidden = true
// cell.tag = indexPath.item
return cell
}
// MAKR: - UICollectionViewDelegate
// 当一个cell完全显示之后就会调用
func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
// 注意: 该方法传递给我们的是上一页的索引
// 0 1 2
// 3 2 1
// 1.获取当前展现在眼前的cell对应的索引
let path = collectionView.indexPathsForVisibleItems().last!
// 2.根据索引获取当前展现在眼前cell
let cell = collectionView.cellForItemAtIndexPath(path) as! GDWCollectionViewCell
// 3.判断是否是最后一页
if path.item == maxImageCount - 1
{
cell.startButton.hidden = false
// 禁用按钮交互
// usingSpringWithDamping 的范围为 0.0f 到 1.0f ,数值越小「弹簧」的振动效果越明显。
// initialSpringVelocity 则表示初始的速度,数值越大一开始移动越快, 值得注意的是,初始速度取值较高而时间较短时,也会出现反弹情况。
cell.startButton.userInteractionEnabled = false
cell.startButton.transform = CGAffineTransformMakeScale(0.0, 0.0)
UIView.animateWithDuration(2.0, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 10.0, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
cell.startButton.transform = CGAffineTransformIdentity
}, completion: { (_) -> Void in
cell.startButton.userInteractionEnabled = true
})
}
}
}
class GDWCollectionViewCell: UICollectionViewCell {
/// 保存图片索引
var index: Int = 0
{
didSet{
iconView.image = UIImage(named: "new_feature_\(index + 1)")
}
}
override init(frame: CGRect) {
super.init(frame: frame)
// 初始化UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// 初始化UI
setupUI()
}
// MARK: - 内部控制方法
private func setupUI()
{
// 添加子控件
contentView.addSubview(iconView)
contentView.addSubview(startButton)
// 布局子控件
iconView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(0)
}
startButton.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(contentView)
make.bottom.equalTo(contentView.snp_bottom).offset(-160)
}
}
@objc private func startBtnClick()
{
// 发送通知, 通知AppDelegate切换根控制器
NSNotificationCenter.defaultCenter().postNotificationName(GDWChangeRootViewControllerNotification, object: self, userInfo: nil)
}
// MARK: - 懒加载
/// 大图容器
private lazy var iconView = UIImageView()
/// 开始按钮
private lazy var startButton: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(UIImage(named: "new_feature_button"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "new_feature_button_highlighted"), forState: UIControlState.Highlighted)
btn.addTarget(self, action: Selector("startBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
btn.sizeToFit()
return btn
}()
}
// 注意: Swift中一个文件中是可以定义多个类
class GDWFlowLayout: UICollectionViewFlowLayout {
// 准备布局
override func prepareLayout() {
super.prepareLayout()
itemSize = collectionView!.bounds.size
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView?.bounces = false
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.showsVerticalScrollIndicator = false
collectionView?.pagingEnabled = true
}
}
| apache-2.0 | b2924cd619a5071b7a9d1d552ab34606 | 30.469136 | 187 | 0.638093 | 4.930368 | false | false | false | false |
pozi119/Valine | Valine/Manager.swift | 1 | 3852 | //
// Manager.swift
// Valine
//
// Created by Valo on 15/12/23.
// Copyright © 2015年 Valo. All rights reserved.
//
import UIKit
public class Manager: NSObject {
//MARK: 公共属性
/// 当前页面
public var currentViewController: UIViewController? {return viewControllers.last}
/// 当前导航页
public var currentNaviController: UINavigationController? {
if viewControllers.last?.navigationController != nil {
return viewControllers.last?.navigationController
}
return naviControllers.last
}
/// 第一个页面
public var rootViewController: UIViewController? {return viewControllers.first}
/// 第一个导航页
public var rootNaviController: UINavigationController? {return naviControllers.first}
public var appearExtraHandler:((UIViewController)->Void)?
public var disappearExtraHandler:((UIViewController)->Void)?
/// 调试level,0-不打印任何信息,>0每次页面切换时打印层次
public var debugLevel:Int
//MARK: 私有属性
/// 当前页面层次(不含导航页)
private var viewControllers:[UIViewController]
/// 当前导航页面层次
private var naviControllers:[UINavigationController]
/// 不作记录的页面
private var ignoreControllers:[String]
/// 注册URLScheme的页面
private var registerList:[UIViewController]
//MARK: 管理器,单例
public static let sharedManager: Manager = {
return Manager()
}()
//MARK: 初始化
override init() {
viewControllers = []
naviControllers = []
registerList = []
debugLevel = 0
ignoreControllers = ["UIInputWindowController",
"UICompatibilityInputViewController",
"UIKeyboardCandidateGridCollectionViewController",
"UIInputViewController",
"UIApplicationRotationFollowingControllerNoTouches",
"_UIRemoteInputViewController",
"PLUICameraViewController"]
UIViewController.record()
}
//MARK: 公共方法
func addViewController(viewController:UIViewController) {
if viewController.isKindOfClass(UINavigationController.classForKeyedUnarchiver()){
naviControllers.append(viewController as! UINavigationController)
}
let vcName = NSStringFromClass(viewController.classForKeyedArchiver!)
var ignore = false
for ignoreName in ignoreControllers{
if vcName.containsString(ignoreName){
ignore = true
break
}
}
if !ignore {
viewControllers.append(viewController)
appearExtraHandler?(viewController)
debugPrint("Appear")
}
}
func removeViewController(viewController:UIViewController) {
if viewController.isKindOfClass(UINavigationController.classForKeyedUnarchiver()){
let navi = viewController as! UINavigationController
let idx = naviControllers.indexOf(navi)
if idx >= 0 && idx < naviControllers.count {
naviControllers.removeAtIndex(idx!)
}
}
let idx = viewControllers.indexOf(viewController)
if idx >= 0 && idx < viewControllers.count {
debugPrint("Disappear")
viewControllers.removeAtIndex(idx!)
disappearExtraHandler?(viewController)
}
}
//MARK: 私有方法
private func debugPrint(tag:String?){
if debugLevel > 0{
var padding = ""
for var idx=0; idx<viewControllers.count; ++idx {
padding += "--"
}
print("\(tag):\(padding)>\(viewControllers.last?.description)")
}
}
}
| gpl-2.0 | 68e30e46b1d1beed44dd9f6d4eec0d8d | 28.039683 | 90 | 0.621208 | 5.453055 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKitUI/view model/TKUISectionedAlertViewModel.swift | 1 | 4461 | //
// TKUISectionedAlertViewModel.swift
// TripKitUI-iOS
//
// Created by Kuan Lun Huang on 15/3/18.
// Copyright © 2018 SkedGo. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
import TripKit
class TKUISectionedAlertViewModel {
enum State {
case loading
case content([Section])
}
let state: Driver<State>
private let disposeBag = DisposeBag()
init(
region: TKRegion,
searchText: Observable<String>
) {
let allRouteAlerts = TKBuzzInfoProvider.rx
.fetchTransitAlertMappings(forRegion: region)
.map { TKUISectionedAlertViewModel.groupAlertMappings($0) }
state = Observable.combineLatest(allRouteAlerts.asObservable(), searchText.startWith("")) { TKUISectionedAlertViewModel.buildSections(from: $0, filter: $1) }
.asDriver(onErrorJustReturn: [])
.map { sections -> State in
return .content(sections)
}
.startWith(.loading)
}
// MARK:
struct Item {
let alertGroup: RouteAlerts
var alerts: [TKAPI.Alert] {
return alertGroup.alerts
}
}
struct Section {
let modeGroup: ModeGroup
var items: [Item]
var header: String? { return modeGroup.title }
var color: UIColor? { return modeGroup.color }
}
// MARK: -
static func groupAlertMappings(_ mappings: [TKAPI.AlertMapping]) -> [ModeGroup: [RouteAlerts]] {
// Firstly, we group all alerts by their mode
let groupedModes = Dictionary(grouping: mappings) { mapping -> ModeGroup in
if let modeInfo = mapping.modeInfo ?? mapping.routes?.first?.modeInfo {
return ModeGroup(modeInfo)
} else {
return ModeGroup.dummy
}
}
// Secondly, within each mode, we group alerts by route
return groupedModes.mapValues { mappings -> [RouteAlerts] in
// Mappings are `[Alert: [AlertRouteMapping]]`. Here we invert this to `[AlertRouteMapping: [Alert]]`
let alertsByRoute: [String: (TKAPI.AlertRouteMapping, [TKAPI.Alert])] = mappings.reduce(into: [:]) { acc, mapping in
mapping.routes?.forEach { route in
let previously = acc[route.id, default: (route, [])]
acc[route.id] = (previously.0, previously.1 + [mapping.alert])
}
}
return alertsByRoute.map {
return RouteAlerts(route: $0.value.0, alerts: $0.value.1)
}
}
}
private static func buildSections(from alertGroupsByMode: [ModeGroup: [RouteAlerts]], filter: String) -> [Section] {
return alertGroupsByMode.reduce(into: []) { acc, tuple in
let filtered = tuple.1.filter { filter.isEmpty || $0.title.contains(filter) }
guard !filtered.isEmpty else { return }
let sorted = filtered.sorted(by: {$0.title < $1.title})
let items = sorted.map { Item(alertGroup: $0) }
acc.append(Section(modeGroup: tuple.0, items: items))
}
}
}
// MARK: -
extension TKAPI.AlertRouteMapping {
var title: String {
return number ?? name ?? id
}
}
// MARK: -
struct ModeGroup {
let title: String
let color: TKColor?
init(_ modeInfo: TKModeInfo) {
self.title = modeInfo.descriptor ?? modeInfo.alt
self.color = modeInfo.color
}
private init() {
self.title = ""
self.color = nil
}
fileprivate static let dummy = ModeGroup()
}
func == (lhs: ModeGroup, rhs: ModeGroup) -> Bool {
return lhs.title == rhs.title
}
extension ModeGroup: Equatable {}
extension ModeGroup: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(title)
}
}
// MARK: -
struct RouteAlerts {
/// Each group is identifiable by a route. The route is affected
/// by the alerts in the group.
let route: TKAPI.AlertRouteMapping
/// These are the alerts affecting the route.
var alerts: [TKAPI.Alert]
/// Title for the group. This is mainly used for sorting mapping groups.
var title: String { return route.title }
}
extension RouteAlerts {
func alerts(ofType type: TKAPI.Alert.Severity) -> [TKAPI.Alert] {
return alerts.filter {
if case type = $0.severity {
return true
} else {
return false
}
}
}
}
// MARK: - RxDataSources protocol conformance
extension TKUISectionedAlertViewModel.Section: SectionModelType {
typealias Item = TKUISectionedAlertViewModel.Item
init(original: TKUISectionedAlertViewModel.Section, items: [Item]) {
self = original
self.items = items
}
}
| apache-2.0 | c20a374d53a9c75b5bb3461e0b2b1103 | 24.05618 | 161 | 0.65157 | 3.950399 | false | false | false | false |
izotx/iTenWired-Swift | Conference App/FNBJSocialFeed/FNBJSocialFeedViewController.swift | 1 | 12301 | //
// FNBJSocialFeedViewController.swift
// FNBJSocialFeed
//
// Created by Felipe on 5/31/16.
// Copyright © 2016 Academic Technology Center. All rights reserved.
//
import UIKit
import ALTextInputBar
class FNBJSocialFeedViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, ALTextInputBarDelegate {
var feed: [FNBJSocialFeedFeedObject] = []
var currentFeed : FNBJSocialFeedFeedObject? = nil
var controller : FNBJSocialFeed!
var paging = false
let textInputBar = ALTextInputBar()
let keyboardObserver = ALKeyboardObservingView()
var currentEditingIndexPath: NSIndexPath?
@IBOutlet weak var tableView: UITableView!
var newFeedButton: UIButton!
// This is how we observe the keyboard position
override var inputAccessoryView: UIView? {
get {
return keyboardObserver
}
}
// This is also required
override func canBecomeFirstResponder() -> Bool {
return true
}
override func viewDidLayoutSubviews() {
textInputBar.hidden = true
}
func checkForNewFeed(){
print("Cheking for new feed...")
controller.checkForNewFeed { (hasNewFeed) in
if hasNewFeed{
self.newFeedButton.hidden = false
}
}
}
func updateWithNewContent(){
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
self.newFeedButton.hidden = true
if controller.hasViewPermissions(){
controller.getFeed { (feed) in
self.feed = []
self.feed.appendContentsOf(feed)
self.feed.sortInPlace({$0.date.isGreaterThanDate($1.date)})
self.tableView.reloadData()
}
}else{
controller.loginWithReadPermissions(self, completion: {
self.controller.getFeed { (feed) in
self.feed = []
self.feed.appendContentsOf(feed)
self.feed.sortInPlace({$0.date.isGreaterThanDate($1.date)})
self.tableView.reloadData()
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
}
})
}
}
override func viewWillDisappear(animated: Bool) {
if let timer = timer where timer.valid
{
timer.invalidate()
}
}
var timer:NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
button.backgroundColor = .blueColor()
button.setTitle("New Feed Available", forState: .Normal)
button.addTarget(self, action: #selector(updateWithNewContent), forControlEvents: .TouchUpInside)
self.newFeedButton = button
button.layer.cornerRadius = 10
button.hidden = true
self.view.addSubview(button)
self.controller = FNBJSocialFeed(facebookPageID: "itenwired", twitterHashtag: "#itenwired16")
self.textInputBar.delegate = self
configureInputBar()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FNBJSocialFeedViewController.keyboardFrameChanged(_:)), name: ALKeyboardFrameDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FNBJSocialFeedViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FNBJSocialFeedViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
// Tableview Delegate
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.estimatedRowHeight = 300
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.setNeedsLayout()
self.tableView.layoutIfNeeded()
if controller.hasViewPermissions(){
controller.getFeed { (feed) in
self.feed.appendContentsOf(feed)
self.feed.sortInPlace({$0.date.isGreaterThanDate($1.date)})
self.tableView.reloadData()
}
}else{
controller.loginWithReadPermissions(self, completion: {
self.controller.getFeed { (feed) in
self.feed.appendContentsOf(feed)
self.feed.sortInPlace({$0.date.isGreaterThanDate($1.date)})
self.tableView.reloadData()
}
})
}
}
override func viewWillAppear(animated: Bool) {
self.textInputBar.hidden = true
if let timer = timer where timer.valid
{
}
else{
//create a new timer
timer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: #selector(checkForNewFeed), userInfo: nil, repeats: true)
}
}
override func viewDidAppear(animated: Bool) {
//self.tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feed.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let index = self.currentEditingIndexPath{
if indexPath != index {
let cell = tableView.dequeueReusableCellWithIdentifier("graycell")
return cell!
}
}
if indexPath.row + 5 > feed.count && paging != true{
paging = true
controller.getFeedPaging({ (feed) in
var f = feed
f.sortInPlace({$0.date.isGreaterThanDate($1.date)})
self.feed.appendContentsOf(feed)
self.tableView.reloadData()
self.paging = false
})
}
let f = feed[indexPath.row]
if f.feed is FNBJSocialFeedFacebookPost{
let post = f.feed as? FNBJSocialFeedFacebookPost
//TODO: Create Enum
if post!.type == "photo" || post!.type == "link"{
let cell = tableView.dequeueReusableCellWithIdentifier("FacebookCell", forIndexPath: indexPath) as? FacebookCell
cell?.build(post!)
cell?.setNeedsDisplay()
cell?.layoutIfNeeded()
return cell!
}
let cell = tableView.dequeueReusableCellWithIdentifier("FNBJSocialFeedFacebookCellTextOnly", forIndexPath: indexPath) as? FNBJSocialFeedFacebookCellTextOnly
cell?.build(post!)
cell?.setNeedsDisplay()
cell?.layoutIfNeeded()
return cell!
}else{
let tweet = f.feed as? FNBJSocialFeedTwitterTweet
let cell = tableView.dequeueReusableCellWithIdentifier("FNBJtwitterCell", forIndexPath: indexPath) as? TwitterCell
cell?.build(tweet!, indexPath: indexPath, callback: showKeyboard)
cell?.setNeedsDisplay()
cell?.layoutIfNeeded()
return cell!
}
}
//TODO: Rename
func showKeyboard(feed: FNBJSocialFeedFeedObject, indexPath: NSIndexPath){
self.textInputBar.hidden = false
self.textInputBar.textView.becomeFirstResponder()
if feed.feed is FNBJSocialFeedTwitterTweet{
let tweet = feed.feed as? FNBJSocialFeedTwitterTweet
if let unwrapedScreenName = tweet?.user.screenName {
let screenName = "@\(unwrapedScreenName) "
self.textInputBar.textView.text = screenName
self.textInputBar.textView.placeholder = ""
}
self.currentFeed = feed
if let button = self.textInputBar.rightView as? UIButton{
button.addTarget(self, action: #selector(replyToTweet), forControlEvents: .TouchUpInside)
}
}
self.currentEditingIndexPath = indexPath
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(endTyping))
self.tableView.scrollEnabled = false
self.tableView.separatorColor = UIColor.whiteColor()
self.tableView.reloadRowsAtIndexPaths(self.tableView.indexPathsForVisibleRows!, withRowAnimation: .Automatic)
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
}
internal func endTyping(){
self.tableView.scrollEnabled = true
self.currentFeed = nil
self.view.endEditing(true)
self.textInputBar.hidden = true
self.currentEditingIndexPath = nil
self.tableView.reloadData()
navigationItem.rightBarButtonItem = nil
}
func tableView(tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
func replyToTweet(sender: AnyObject){
let message = self.textInputBar.textView.text
let tweet = FNBJSocialFeedTwitterTweet()
tweet.text = message
let inReplyTo = self.currentFeed?.feed as? FNBJSocialFeedTwitterTweet
self.controller.replyToTweet(tweet, inReplyTo: inReplyTo!)
self.endTyping()
}
}
//MARK: ALTextInputBar
extension FNBJSocialFeedViewController{
func configureInputBar() {
// Configure send button
let rightButton = UIButton(frame: CGRectMake(100, 100, 80, 50))
rightButton.setTitle("Send", forState: .Normal)
rightButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
keyboardObserver.userInteractionEnabled = false
textInputBar.showTextViewBorder = true
textInputBar.rightView = rightButton
textInputBar.frame = CGRectMake(0, view.frame.size.height - textInputBar.defaultHeight, view.frame.size.width, textInputBar.defaultHeight)
textInputBar.backgroundColor = UIColor(white: 0.95, alpha: 1)
textInputBar.keyboardObserver = keyboardObserver
view.addSubview(textInputBar)
}
func keyboardFrameChanged(notification: NSNotification) {
if let userInfo = notification.userInfo {
let frame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
textInputBar.frame.origin.y = frame.origin.y
}
}
func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
let frame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
textInputBar.frame.origin.y = frame.origin.y
self.textInputBar.hidden = false
}
}
func keyboardWillHide(notification: NSNotification) {
if let userInfo = notification.userInfo {
let frame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
textInputBar.frame.origin.y = frame.origin.y + textInputBar.frame.size.height
}
self.textInputBar.hidden = true
}
}
extension FNBJSocialFeedViewController{
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
textInputBar.frame.size.width = view.bounds.size.width
}
}
| bsd-2-clause | b02f0d4ba490e57cbf8563c143355c09 | 32.153639 | 195 | 0.596423 | 5.755732 | false | false | false | false |
notbenoit/StepColor | Tests/StepColor_iOS Tests/StepColor_iOS_Tests.swift | 1 | 2781 | //
// StepColorTests.swift
// StepColorTests
//
// Created by Benoit Layer on 23/01/2015.
// Copyright (c) 2015 Benoit Layer. All rights reserved.
//
import UIKit
import XCTest
import StepColor
class StepColor_iOS_Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testInit() {
let stepColor = SColor(colors: UIColor.redColor(), UIColor.blueColor())
XCTAssert(true, "Pass")
}
func testInitWithStepColors() {
let stepColor = SColor(colors: [UIColor.redColor(), UIColor.blueColor()], steps: [0.3, 0.9])
XCTAssert(true, "Pass")
}
func testInitWithSingleColor() {
let stepColor = SColor(colors: [UIColor.redColor()])
let halfColor = stepColor.colorForStep(0.5)
var red: CGFloat = 0.0
halfColor.getRed(&red, green: nil, blue: nil, alpha: nil)
println("Red : \(red)")
XCTAssert(red == 1.0, "Pass")
}
func testMiddleRedBlueColor() {
//Test with default steps
let stepColor = SColor(colors: [UIColor.redColor(), UIColor.blueColor()])
let halfColor = stepColor.colorForStep(0.5)
var red: CGFloat = 0.0
halfColor.getRed(&red, green: nil, blue: nil, alpha: nil)
println("Red : \(red)")
XCTAssert(red == 0.5, "Pass")
}
func testLeftRedColor() {
//Test with default steps
let stepColor = SColor(colors: [UIColor.redColor(), UIColor.blueColor()])
let halfColor = stepColor.colorForStep(0.0)
var red: CGFloat = 0.0
halfColor.getRed(&red, green: nil, blue: nil, alpha: nil)
println("Red : \(red)")
XCTAssert(red == 1.0, "Pass")
}
func testRightBlueColor() {
//Test with default steps
let stepColor = SColor(colors: [UIColor.redColor(), UIColor.blueColor()])
let halfColor = stepColor.colorForStep(1.0)
var red: CGFloat = 0.0
halfColor.getRed(&red, green: nil, blue: nil, alpha: nil)
println("Red : \(red)")
XCTAssert(red == 0.0, "Pass")
}
func testMidleColor() {
let stepColor = SColor(colors: UIColor.orangeColor(), UIColor.greenColor(), UIColor.redColor(), UIColor.redColor(), UIColor.redColor())
var red: CGFloat = 0.0
let halfColor = stepColor.colorForStep(0.5)
halfColor.getRed(&red, green: nil, blue: nil, alpha: nil)
println("Red : \(red)")
XCTAssert(red == 1, "Pass")
}
}
| mit | c2d28b26e03c982bd46c818c636263c3 | 32.914634 | 143 | 0.602661 | 3.922426 | false | true | false | false |
yichizhang/Keyboard | KeyboardExtension/LetterKey.swift | 2 | 3231 | //
// LetterKey.swift
// Keyboard
//
// Created by Matt Zanchelli on 6/16/14.
// Copyright (c) 2014 Matt Zanchelli. All rights reserved.
//
import UIKit
class LetterKey: KeyboardKey {
/// The letter to display on the key.
/// This will truncate to one letter.
var letter: NSString {
get {
let text = label.text
// return capitalized ? text.uppercaseString : text.lowercaseString
return text!
}
set {
let letter = newValue.substringToIndex(1)
label.text = letter
keyDownLabel.text = letter
// let text = capitalized ? letter.uppercaseString : letter.lowercaseString
// label.text = text
// keyDownLabel.text = text
}
}
/// A Boolean value representing whether or not the letter is capitalized
var capitalized: Bool = false {
didSet {
// let text = capitalized ? label.text.uppercaseString : label.text.lowercaseString
// label.text = text
// keyDownLabel.text = text
}
}
var textColor: UIColor {
get {
return self.label.textColor
}
set {
self.label.textColor = textColor
self.keyDownLabel.textColor = textColor
}
}
/// A change in appearance when highlighted is set.
override var highlighted: Bool {
didSet {
self.keyDownView.hidden = !highlighted
}
}
convenience init(letter: NSString) {
self.init()
self.letter = letter
}
convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: 22, height: 19))
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(label)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[label]|", options: nil, metrics: nil, views: ["label": label]))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|", options: nil, metrics: nil, views: ["label": label]))
label.textAlignment = .Center
label.font = KeyboardAppearance.keyboardLetterFont()
label.textColor = KeyboardAppearance.primaryButtonColorForAppearance(.Default)
keyDownView.addSubview(keyDownLabel)
keyDownView.hidden = true
self.addSubview(keyDownView)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
let label = UILabel()
let keyDownView: UIView = {
let view = UIView(frame: CGRect(x: -14, y: -57, width: 62, height: 101))
let iv = UIImageView(frame: CGRect(x: 0, y: 0, width: 62, height: 101))
iv.image = UIImage(named: "LetterKeyDown")
view.addSubview(iv)
return view
}()
let keyDownLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 0, y: 12, width: 62, height: 43))
label.textAlignment = .Center
label.font = KeyboardAppearance.keyboardLetterFont().fontWithSize(36)
label.textColor = KeyboardAppearance.primaryButtonColorForAppearance(.Default)
return label
}()
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
return pointInside(point, withEvent: event) ? self : nil
}
override func pointInside(point: CGPoint, withEvent event: UIEvent!) -> Bool {
// var frameAboutOrigin = self.frame
// frameAboutOrigin.origin = CGPoint(x: 0, y: 0)
return CGRectContainsPoint(self.label.frame, point)
}
}
| mit | bed9c48d5878f395b38053d0a578cd10 | 26.151261 | 137 | 0.708759 | 3.59 | false | false | false | false |
LedgerHQ/u2f-ble-test-ios | u2f-ble-test-ios/Utils/TransportHelper.swift | 1 | 3671 | //
// TransportHelper.swift
// u2f-ble-test-ios
//
// Created by Nicolas Bigot on 16/05/2016.
// Copyright © 2016 Ledger. All rights reserved.
//
import Foundation
final class TransportHelper {
enum CommandType: UInt8 {
case Ping = 0x81
case KeepAlive = 0x82
case Message = 0x83
case Error = 0xbf
}
enum ChunkType {
case Ping
case KeepAlive
case Message
case Error
case Continuation
case Unknown
}
static func getChunkType(data: NSData) -> ChunkType {
let reader = DataReader(data: data)
guard let byte = reader.readNextUInt8() else {
return .Unknown
}
if byte & 0x80 == 0 {
return .Continuation
}
switch byte {
case CommandType.Ping.rawValue: return .Ping
case CommandType.KeepAlive.rawValue: return .KeepAlive
case CommandType.Message.rawValue: return .Message
case CommandType.Error.rawValue: return .Error
default: return .Unknown
}
}
static func split(data: NSData, command: CommandType, chuncksize: Int) -> [NSData]? {
guard chuncksize >= 8 && data.length > 0 && data.length <= Int(UInt16.max) else { return nil }
var chunks: [NSData] = []
var remainingLength = data.length
var firstChunk = true
var sequence: UInt8 = 0
var offset = 0
while remainingLength > 0 {
var length = 0
let writer = DataWriter()
if firstChunk {
writer.writeNextUInt8(command.rawValue)
writer.writeNextBigEndianUInt16(UInt16(remainingLength))
length = min(chuncksize - 3, remainingLength)
}
else {
writer.writeNextUInt8(sequence)
length = min(chuncksize - 1, remainingLength)
}
writer.writeNextData(data.subdataWithRange(NSMakeRange(offset, length)))
remainingLength -= length
offset += length
chunks.append(writer.data)
if !firstChunk {
sequence += 1
}
firstChunk = false
}
return chunks
}
static func join(chunks: [NSData], command: CommandType) -> NSData? {
let writer = DataWriter()
var sequence: UInt8 = 0
var length = -1
var firstChunk = true
for chunk in chunks {
let reader = DataReader(data: chunk)
if firstChunk {
guard
let readCommand = reader.readNextUInt8(),
let readLength = reader.readNextBigEndianUInt16()
where
readCommand == command.rawValue
else
{ return nil }
length = Int(readLength)
writer.writeNextData(chunk.subdataWithRange(NSMakeRange(3, chunk.length - 3)))
length -= chunk.length - 3
firstChunk = false
}
else {
guard
let readSequence = reader.readNextUInt8()
where
readSequence == sequence
else
{ return nil }
writer.writeNextData(chunk.subdataWithRange(NSMakeRange(1, chunk.length - 1)))
length -= chunk.length - 1
sequence += 1
}
}
if length != 0 {
return nil
}
return writer.data
}
} | apache-2.0 | 717c17e156c4a7c34b05dd3fc4497201 | 28.845528 | 102 | 0.512534 | 4.986413 | false | false | false | false |
Jgzhu/DouYUZhiBo-Swift | DouYUZhiBo-Swift/DouYUZhiBo-Swift/Classes/Main/View/PageTitleView.swift | 1 | 5582 | //
// PageTitleView.swift
// DouYuZhiBo-Swift
//
// Created by 江贵铸 on 2016/11/18.
// Copyright © 2016年 江贵铸. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate: class {
func pageTitleViewClick(titleView:PageTitleView,selectIndex:Int)
}
private let kNormalColor:(CGFloat,CGFloat,CGFloat) = (85, 85, 85)
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
class PageTitleView: UIView {
weak var delegate : PageTitleViewDelegate?
fileprivate var titles : [String]
fileprivate var currentIndex: Int = 0
fileprivate lazy var ScrollView : UIScrollView = {
let scrollview = UIScrollView()
scrollview.showsHorizontalScrollIndicator = false
scrollview.scrollsToTop = false
scrollview.bounces = false
return scrollview
}()
fileprivate lazy var shortline: UIView = {
let shortline = UIView()
shortline.backgroundColor = UIColor(red: kSelectColor.0 / 255.0, green: kSelectColor.1 / 255.0, blue: kSelectColor.2 / 255.0, alpha: 1)
return shortline
}()
fileprivate lazy var titleLables: [UILabel] = [UILabel]()
init(frame: CGRect,titles: [String]) {
self.titles = titles
super.init(frame: frame)
//更新UI
SetUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView{
fileprivate func SetUI(){
//添加ScrollView
addSubview(ScrollView)
ScrollView.frame = bounds
//设置TitleLable
SetTitleToTitleView()
}
fileprivate func SetTitleToTitleView(){
var LableX: CGFloat = 0
let LableY: CGFloat = 0
let titlesCount: CGFloat = CGFloat(titles.count)
let LableW: CGFloat = UIScreen.main.bounds.width/titlesCount
for (index, titlestring) in titles.enumerated() {
//创建label
let titlelabel = UILabel()
titlelabel.text = titlestring
titlelabel.tag = index
titlelabel.font = UIFont.systemFont(ofSize: 16)
titlelabel.textColor = UIColor(red: kNormalColor.0 / 255.0, green: kNormalColor.1 / 255.0, blue: kNormalColor.2 / 255.0, alpha: 1)
titlelabel.textAlignment = .center
//设置label的Frame
var frame = titlelabel.frame
frame.origin.x = LableX
frame.origin.y = LableY
frame.size.height = self.frame.size.height-1
frame.size.width = LableW
titlelabel.frame = frame
LableX += titlelabel.bounds.size.width
//添加到scrollview
ScrollView.addSubview(titlelabel)
titleLables.append(titlelabel)
//添加Label点击
titlelabel.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_:)))
titlelabel.addGestureRecognizer(tap)
}
//添加长下划线
let longline = UIView()
longline.backgroundColor = UIColor.lightGray
longline.frame = CGRect(x: 0, y: self.frame.size.height-1, width: self.frame.size.width, height: 1)
self.addSubview(longline)
//添加短下划线
let firstLabel = titleLables[0]
firstLabel.textColor = UIColor(red: kSelectColor.0 / 255.0, green: kSelectColor.1 / 255.0, blue: kSelectColor.2 / 255.0, alpha: 1)
shortline.frame = CGRect(x: 0, y: self.frame.size.height-3, width: firstLabel.bounds.size.width, height: 2)
ScrollView.addSubview(shortline)
}
//点击title
@objc private func titleLabelClick(_ tap: UITapGestureRecognizer) {
print("\(tap.view?.tag)")
guard let tapview = tap.view else{return}
let index = tapview.tag
if index==currentIndex {return}
ScrollTitle(souceIndex: currentIndex, targetIndex: index, progress: 1)
delegate?.pageTitleViewClick(titleView: self, selectIndex: index)
}
}
extension PageTitleView{
//滚动title
func ScrollTitle(souceIndex: Int, targetIndex: Int, progress: CGFloat){
var tempprogress = progress
if tempprogress>0.9 {
tempprogress=CGFloat(1)
}
let newLabel = titleLables[targetIndex]
let oldLabel = titleLables[souceIndex]
currentIndex = targetIndex
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
newLabel.textColor = UIColor(red: (kNormalColor.0+colorDelta.0*tempprogress) / 255.0, green: (kNormalColor.1+colorDelta.1*tempprogress) / 255.0, blue: (kNormalColor.2+colorDelta.2*tempprogress) / 255.0, alpha: 1)
oldLabel.textColor = UIColor(red: (kSelectColor.0-colorDelta.0*tempprogress) / 255.0, green: (kSelectColor.1-colorDelta.1*tempprogress) / 255.0, blue: (kSelectColor.2-colorDelta.2*tempprogress) / 255.0, alpha: 1)
var NewX: CGFloat = 0
if (newLabel.frame.origin.x-oldLabel.frame.origin.x)>0 {
NewX = oldLabel.frame.origin.x + (newLabel.frame.origin.x-oldLabel.frame.origin.x)*tempprogress
}else{
NewX = oldLabel.frame.origin.x - (oldLabel.frame.origin.x-newLabel.frame.origin.x)*tempprogress
}
UIView.animate(withDuration: 0.25, animations: {
self.shortline.frame.origin.x = NewX
self.shortline.frame.size.width = newLabel.frame.size.width
})
}
}
| mit | 87f7566c640e8bdb507d35bc8d0d40e5 | 37.725352 | 220 | 0.639207 | 4.128378 | false | false | false | false |
3DprintFIT/octoprint-ios-client | OctoPhoneTests/VIew Related/Logs/LogsViewModelTests.swift | 1 | 2682 | //
// LogsViewModelTests.swift
// OctoPhone
//
// Created by Josef Dolezal on 18/03/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import Nimble
import Quick
import RealmSwift
import ReactiveSwift
@testable import OctoPhone
class LogsViewModelTests: QuickSpec {
override func spec() {
let provider = OctoPrintProvider(baseURL: URL(string: "http://localhost")!)
let contextManager = InMemoryContextManager()
var subject: LogsViewModelType!
var currentCount = 0
var disposable: Disposable!
beforeEach {
subject = LogsViewModel(delegate: self, provider: provider, contextManager: contextManager)
currentCount = 0
let realm = try! contextManager.createContext()
try! realm.write{ realm.deleteAll() }
}
afterEach {
subject = nil
disposable?.dispose()
disposable = nil
}
it("displays provides correct count of logs") {
expect(subject.outputs.logsCount) == 0
disposable = subject.outputs.logsListChanged.startWithValues { currentCount = subject.outputs.logsCount }
let first = self.createLog("first")
let second = self.createLog("second")
let realm = try! contextManager.createContext()
try! realm.write {
realm.add(first)
realm.add(second)
}
expect(subject.outputs.logsCount) == 2
expect(currentCount).toEventually(equal(2)) // evenutaly -> async
}
it("provides correct log model for index") {
var firstName = ""
var secondName = ""
let first = self.createLog("first")
let second = self.createLog("second")
let realm = try! contextManager.createContext()
try! realm.write {
realm.add(first)
realm.add(second)
}
let model = subject.outputs.logCellViewModel(for: 0)
model.outputs.name.startWithValues{ firstName = $0 }
model.outputs.size.startWithValues{ secondName = $0 }
expect(firstName).toEventually(equal("first"))
expect(secondName).toEventually(equal("1 KB"))
}
}
/// Creates new log with given key
private func createLog(_ primaryKey: String) -> Log {
return Log(name: "\(primaryKey)", size: 1234, lastModified: 5678,
remotePath: "RP\(primaryKey)", referencePath: "RF\(primaryKey)")
}
}
extension LogsViewModelTests: LogsViewControllerDelegate {
func selectedLog(_ log: Log) {
}
}
| mit | acb1af36489b78f4461357cd06fbf61b | 29.123596 | 117 | 0.5953 | 4.910256 | false | false | false | false |
petrusalin/APLfm | APLfm/Classes/LastfmRequest.swift | 1 | 3316 | //
// LastfmRequest.swift
// Kindio
//
// Created by Alin Petrus on 5/10/16.
// Copyright © 2016 Alin Petrus. All rights reserved.
//
import UIKit
import AFNetworking
import CryptoSwift
/*!
* Structure used to hold the data used by Lastfm to identify a client
*/
public struct LastfmCredential {
var appKey : String!
var secret : String!
public init(key : String, secret : String) {
self.appKey = key
self.secret = secret
}
}
/*!
* Base class that defines the data and processing required by any lastfm request
* It should not be used directly as it does not handle things like signing requests that require it
* All requests use the JSON format
*/
public class LastfmRequest: NSObject {
internal var credential : LastfmCredential!
internal var sessionToken : String!
internal var lastfmMethod: LastfmMethod?
internal var baseURL : String {
return "http://ws.audioscrobbler.com/2.0/"
}
public class var maxRequestsPerBatch : Int {
get {
return 50
}
}
internal init(credential: LastfmCredential) {
self.credential = credential
}
public func executeWithCompletionBlock(completion: (response: AnyObject?, error: NSError?) -> Void) {
let manager = AFHTTPSessionManager()
manager.POST(self.baseURL,
parameters: self.lastfmMethod!.parameters,
progress: { (progress) in },
success: { (dataTask, dictionary) in
completion(response: dictionary, error: nil)
}) { (dataTask, error) in
completion(response: nil, error: error)
}
}
internal func prepareForExecute() {
if self.lastfmMethod != nil {
self.lastfmMethod!.parameters[LastfmKeys.Signature.rawValue] = self.signature(self.lastfmMethod!.parameters)
self.lastfmMethod!.parameters[LastfmKeys.Format.rawValue] = "json"
}
}
internal func signature(dictionary: [String : AnyObject]) -> String {
let parameters = dictionary.keys
let sortedParameters = parameters.sort () {$0 < $1}
var concatenatedString = ""
for key in sortedParameters {
if let value = dictionary[key] {
let signable = Signable(data: value)
concatenatedString = signable.concatenateToString(concatenatedString, withKey: key)
} else {
print(dictionary[key])
}
}
concatenatedString += self.credential.secret.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
return concatenatedString.md5()
}
internal func updateParameters(parameters: [String : AnyObject]) {
var dict = parameters
for (key, value) in parameters {
if let array = value as? [AnyObject] {
dict.removeValueForKey(key)
for (index, val) in array.enumerate() {
let adjustedKey = "\(key)[\(index)]"
dict[adjustedKey] = val
}
}
}
self.lastfmMethod!.parameters.update(dict)
}
}
| mit | a2015eccd2b5b6d99d204926fffd26b3 | 29.981308 | 150 | 0.596078 | 4.776657 | false | false | false | false |
CNKCQ/oschina | OSCHINA/Application/BaseTabBarController.swift | 1 | 1504 | //
// BaseTabBarController.swift
// OSCHINA
//
// Created by KingCQ on 16/8/9.
// Copyright © 2016年 KingCQ. All rights reserved.
//
import UIKit
class BaseTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
UITabBar.appearance().tintColor = appColor
selectedIndex = 0
let controller1 = NewsList()
let controller2 = DiscoverController()
controller2.title = "发现"
let controller3 = MineController()
controller3.title = "我"
let controllers: [(String, UIImage, UIImage, UIViewController)] = [
(title: "综合", imge: UIImage(named: "tabbar-news")!, simage: UIImage(named: "tabbar-news-selected")!, controller1),
(title: "发现", imge: UIImage(named: "tabbar-discover")!, simage: UIImage(named: "tabbar-discover-selected")!, controller2),
(title: "我", imge: UIImage(named: "tabbar-me")!, simage: UIImage(named: "tabbar-me-selected")!, controller3)
]
controllers.forEach {
self.append($3, title: $0, image: $1, selectedImage: $2)
}
}
func append(_ controller: UIViewController, title: String? = nil, image: UIImage? = nil, selectedImage: UIImage? = nil) {
controller.tabBarItem.title = title
controller.tabBarItem.image = image
controller.tabBarItem.selectedImage = selectedImage
addChildViewController(UINavigationController(rootViewController: controller))
}
}
| mit | 61212048173378d5f61509fdb4f62c6f | 39.135135 | 134 | 0.648485 | 4.279539 | false | false | false | false |
yscode001/YSExtension | YSExtension/YSExtension/YSExtension/UIKit/UIImage+ysExtension.swift | 1 | 4904 | import UIKit
extension UIImage{
public var ys_width:CGFloat{
get{
return size.width
}
}
public var ys_height:CGFloat{
get{
return size.height
}
}
}
extension UIImage{
/// 创建图片
public static func ys_create(color:UIColor,size:CGSize) -> UIImage?{
if size == CGSize.zero{
return nil
}
guard let context = UIGraphicsGetCurrentContext() else{
return nil
}
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(size)
context.setFillColor(color.cgColor)
context.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
/// 等比例缩放
public func ys_scale(width:CGFloat) -> UIImage?{
if width <= 0{
return nil
}
let scaleHeight = width / size.width * size.height
let scaleSize = CGSize(width: width, height: scaleHeight)
UIGraphicsBeginImageContextWithOptions(scaleSize, false, 0)
draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
/// 异步裁切
public func ys_corner(size:CGSize,fillColor:UIColor,callBack:((UIImage) -> ())?){
if size.width <= 0 || size.height <= 0{
callBack?(self)
return
}
DispatchQueue.global().async {
UIGraphicsBeginImageContextWithOptions(size, true, 0)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
fillColor.setFill()
UIRectFill(rect)
let path = UIBezierPath(ovalIn: rect)
path.addClip()
self.draw(in: rect)
if let img = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext()
DispatchQueue.main.sync {
callBack?(img)
}
} else{
UIGraphicsEndImageContext()
DispatchQueue.main.sync {
callBack?(self)
}
}
}
}
/// 颜色填充
public func ys_tint(color:UIColor) -> UIImage?{
guard let context = UIGraphicsGetCurrentContext() else{
return nil
}
guard let cgImg = cgImage else{
return nil
}
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context.setBlendMode(.normal)
context.draw(cgImg, in: rect)
context.setBlendMode(.sourceIn)
color.setFill()
context.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
extension UIImage{
/// 生成二维码
public static func ys_qrCode(code:String,width:CGFloat,height:CGFloat) -> UIImage?{
// 1、创建滤镜:CIQRCodeGenerator
guard let filter = CIFilter(name: "CIQRCodeGenerator") else{
return nil
}
// 2、设置属性:先设置默认、再设置自定义选项
filter.setDefaults()
filter.setValue(code.data(using: .utf8), forKey: "inputMessage")
// 3、根据滤镜生成图片
guard var ciImage = filter.outputImage else{
return nil
}
// 4、设置缩放,要不模糊
let scaleX = width / ciImage.extent.size.width
let scaleY = height / ciImage.extent.size.height
ciImage = ciImage.transformed(by: CGAffineTransform.identity.scaledBy(x: scaleX, y: scaleY))
return UIImage(ciImage: ciImage)
}
/// 生成条形码
public static func ys_barCode(code:String,width:CGFloat,height:CGFloat) -> UIImage?{
guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else{
return nil
}
filter.setDefaults()
filter.setValue(code.data(using: .utf8), forKey: "inputMessage")
guard var ciImage = filter.outputImage else{
return nil
}
let scaleX = width / ciImage.extent.size.width
let scaleY = height / ciImage.extent.size.height
ciImage = ciImage.transformed(by: CGAffineTransform.identity.scaledBy(x: scaleX, y: scaleY))
return UIImage(ciImage: ciImage)
}
}
| mit | 8fb9eb41c181f5b37819e227a3a6950e | 28.202454 | 100 | 0.554622 | 4.973877 | false | false | false | false |
dn-m/PathTools | PathTools/Path+Arrowhead.swift | 1 | 855 | //
// Path+Arrowhead.swift
// PathTools
//
// Created by James Bean on 6/11/16.
//
//
import GeometryTools
extension Path {
// MARK: - Arrowhead
public static func arrowhead(
tip: Point = Point(),
height: Double = 100,
width: Double = 25,
barbProportion: Double = 0.25,
rotation: Angle = .zero
) -> Path
{
let builder = Path.builder
.move(to: Point(x: 0.5 * width, y: 0))
.addLine(to: Point(x: width, y: height))
.addLine(to: Point(x: 0.5 * width, y: height - (barbProportion * height)))
.addLine(to: Point(x: 0, y: height))
.close()
let path = builder.build()
guard rotation == .zero else {
return path.rotated(by: rotation)
}
return path
}
}
| mit | 7c44d339d16c5e98f34668e339c89b24 | 20.923077 | 86 | 0.502924 | 3.717391 | false | false | false | false |
yangligeryang/codepath | labs/FacebookDemo/FacebookDemo/LoginViewController.swift | 1 | 4386 | //
// LoginViewController.swift
// FacebookDemo
//
// Created by Yang Yang on 10/20/16.
// Copyright © 2016 Yang Yang. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var fieldSuperView: UIView!
@IBOutlet weak var labelSuperView: UIView!
@IBOutlet weak var fbLogoImageView: UIImageView!
@IBOutlet weak var loginLoading: UIActivityIndicatorView!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
var initialFormCenter: CGPoint!
var offsetFormCenter: CGPoint!
var initialLabelCenter: CGPoint!
var offsetLabelCenter: CGPoint!
var initialLogoCenter: CGPoint!
var offsetLogoCenter: CGPoint!
private func enableLogin() {
if (emailField.text!.isEmpty) || (passwordField.text!.isEmpty) {
loginButton.isEnabled = false
} else {
loginButton.isEnabled = true
}
}
private func showLoginError() {
loginButton.isEnabled = false
let alertController = UIAlertController(title: "Your email or password is wrong", message: "Please fix to log into Facebook", preferredStyle: .alert)
let okAction = UIAlertAction(title: "ok", style: .default, handler: { (UIAlertAction) in
})
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
initialLogoCenter = fbLogoImageView.center
offsetLogoCenter = CGPoint(x: initialLogoCenter.x, y: initialLogoCenter.y - 12)
initialFormCenter = fieldSuperView.center
offsetFormCenter = CGPoint(x: initialFormCenter.x, y: initialFormCenter.y - 36)
initialLabelCenter = labelSuperView.center
offsetLabelCenter = CGPoint(x: initialLabelCenter.x, y: initialLabelCenter.y - 190)
loginButton.isEnabled = false
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillShow, object: nil, queue: OperationQueue.main) { (Notification) in
print("Keyboard has shown")
self.fbLogoImageView.center.y = self.offsetLogoCenter.y
self.fieldSuperView.center.y = self.offsetFormCenter.y
self.labelSuperView.center.y = self.offsetLabelCenter.y
}
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardDidHide, object: nil, queue: OperationQueue.main) { (Notification) in
self.fbLogoImageView.center.y = self.initialLogoCenter.y
self.fieldSuperView.center.y = self.initialFormCenter.y
self.labelSuperView.center.y = self.initialLabelCenter.y
print("Keyboard is hidden")
}
}
@IBAction func didTap(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}
@IBAction func onEmailEditing(_ sender: UITextField) {
enableLogin()
}
@IBAction func onPasswordEditing(_ sender: UITextField) {
enableLogin()
}
@IBAction func didLogin(_ sender: UIButton) {
loginLoading.startAnimating()
loginButton.isSelected = true
delay(2) {
self.loginLoading.stopAnimating()
self.loginButton.isSelected = false
if self.emailField.text == "test" {
if self.passwordField.text == "password" {
let defaults = UserDefaults.standard
defaults.set("existing user", forKey: "user")
self.performSegue(withIdentifier: "loginSegue", sender: nil)
} else {
self.showLoginError()
}
} else if self.emailField.text == "newUser" {
if self.passwordField.text == "password" {
let defaults = UserDefaults.standard
defaults.set("new user", forKey: "user")
self.performSegue(withIdentifier: "loginSegue", sender: nil)
} else {
self.showLoginError()
}
} else {
self.showLoginError()
}
}
}
}
| apache-2.0 | 7577ac02d8f7705104ced4e3841ba352 | 34.942623 | 157 | 0.612999 | 5.034443 | false | false | false | false |
kesun421/firefox-ios | Client/Frontend/AuthenticationManager/RequirePasscodeIntervalViewController.swift | 4 | 3142 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SwiftKeychainWrapper
/// Screen presented to the user when selecting the time interval before requiring a passcode
class RequirePasscodeIntervalViewController: UITableViewController {
let intervalOptions: [PasscodeInterval] = [
.immediately,
.oneMinute,
.fiveMinutes,
.tenMinutes,
.fifteenMinutes,
.oneHour
]
fileprivate let BasicCheckmarkCell = "BasicCheckmarkCell"
fileprivate var authenticationInfo: AuthenticationKeychainInfo?
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = AuthenticationStrings.requirePasscode
tableView.accessibilityIdentifier = "AuthenticationManager.passcodeIntervalTableView"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: BasicCheckmarkCell)
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
let headerFooterFrame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.view.frame.width, height: UIConstants.TableViewHeaderFooterHeight))
let headerView = SettingsTableSectionHeaderFooterView(frame: headerFooterFrame)
headerView.showTopBorder = false
headerView.showBottomBorder = true
let footerView = SettingsTableSectionHeaderFooterView(frame: headerFooterFrame)
footerView.showTopBorder = true
footerView.showBottomBorder = false
tableView.tableHeaderView = headerView
tableView.tableFooterView = footerView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.authenticationInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo()
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: BasicCheckmarkCell, for: indexPath)
let option = intervalOptions[indexPath.row]
let intervalTitle = NSAttributedString.tableRowTitle(option.settingTitle, enabled: true)
cell.textLabel?.attributedText = intervalTitle
cell.accessoryType = authenticationInfo?.requiredPasscodeInterval == option ? .checkmark : .none
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return intervalOptions.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
authenticationInfo?.updateRequiredPasscodeInterval(intervalOptions[indexPath.row])
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo)
tableView.reloadData()
}
}
| mpl-2.0 | 13ca1c45dc7d0143618acb17964ade01 | 39.805195 | 153 | 0.734882 | 5.797048 | false | false | false | false |
ZhiQiang-Yang/pppt | v2exProject 2/Pods/Kingfisher/Sources/KingfisherManager.swift | 20 | 10627 | //
// KingfisherManager.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(OSX)
import AppKit
#else
import UIKit
#endif
public typealias DownloadProgressBlock = ((receivedSize: Int64, totalSize: Int64) -> ())
public typealias CompletionHandler = ((image: Image?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ())
/// RetrieveImageTask represents a task of image retrieving process.
/// It contains an async task of getting image from disk and from network.
public class RetrieveImageTask {
// If task is canceled before the download task started (which means the `downloadTask` is nil),
// the download task should not begin.
var cancelledBeforeDownlodStarting: Bool = false
/// The disk retrieve task in this image task. Kingfisher will try to look up in cache first. This task represent the cache search task.
public var diskRetrieveTask: RetrieveImageDiskTask?
/// The network retrieve task in this image task.
public var downloadTask: RetrieveImageDownloadTask?
/**
Cancel current task. If this task does not begin or already done, do nothing.
*/
public func cancel() {
// From Xcode 7 beta 6, the `dispatch_block_cancel` will crash at runtime.
// It fixed in Xcode 7.1.
// See https://github.com/onevcat/Kingfisher/issues/99 for more.
if let diskRetrieveTask = diskRetrieveTask {
dispatch_block_cancel(diskRetrieveTask)
}
if let downloadTask = downloadTask {
downloadTask.cancel()
} else {
cancelledBeforeDownlodStarting = true
}
}
}
/// Error domain of Kingfisher
public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
private let instance = KingfisherManager()
/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache.
/// You can use this class to retrieve an image via a specified URL from web or cache.
public class KingfisherManager {
/// Shared manager used by the extensions across Kingfisher.
public class var sharedManager: KingfisherManager {
return instance
}
/// Cache used by this manager
public var cache: ImageCache
/// Downloader used by this manager
public var downloader: ImageDownloader
/**
Default init method
- returns: A Kingfisher manager object with default cache, default downloader, and default prefetcher.
*/
public convenience init() {
self.init(downloader: ImageDownloader.defaultDownloader, cache: ImageCache.defaultCache)
}
init(downloader: ImageDownloader, cache: ImageCache) {
self.downloader = downloader
self.cache = cache
}
/**
Get an image with resource.
If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`.
These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
- parameter completionHandler: Called when the whole retrieving process finished.
- returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
*/
public func retrieveImageWithResource(resource: Resource,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
let task = RetrieveImageTask()
if let optionsInfo = optionsInfo where optionsInfo.forceRefresh {
downloadAndCacheImageWithURL(resource.downloadURL,
forKey: resource.cacheKey,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: optionsInfo)
} else {
tryToRetrieveImageFromCacheForKey(resource.cacheKey,
withURL: resource.downloadURL,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: optionsInfo)
}
return task
}
/**
Get an image with `URL.absoluteString` as the key.
If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
If not found, it will download the image at URL and cache it with `URL.absoluteString` value as its key.
If you need to specify the key other than `URL.absoluteString`, please use resource version of this API with `resource.cacheKey` set to what you want.
These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
- parameter URL: The image URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
- parameter completionHandler: Called when the whole retrieving process finished.
- returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
*/
public func retrieveImageWithURL(URL: NSURL,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return retrieveImageWithResource(Resource(downloadURL: URL), optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler)
}
func downloadAndCacheImageWithURL(URL: NSURL,
forKey key: String,
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
options: KingfisherOptionsInfo?) -> RetrieveImageDownloadTask?
{
let downloader = options?.downloader ?? self.downloader
return downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options,
progressBlock: { receivedSize, totalSize in
progressBlock?(receivedSize: receivedSize, totalSize: totalSize)
},
completionHandler: { image, error, imageURL, originalData in
let targetCache = options?.targetCache ?? self.cache
if let error = error where error.code == KingfisherError.NotModified.rawValue {
// Not modified. Try to find the image from cache.
// (The image should be in cache. It should be guaranteed by the framework users.)
targetCache.retrieveImageForKey(key, options: options, completionHandler: { (cacheImage, cacheType) -> () in
completionHandler?(image: cacheImage, error: nil, cacheType: cacheType, imageURL: URL)
})
return
}
if let image = image, originalData = originalData {
targetCache.storeImage(image, originalData: originalData, forKey: key, toDisk: !(options?.cacheMemoryOnly ?? false), completionHandler: nil)
}
completionHandler?(image: image, error: error, cacheType: .None, imageURL: URL)
})
}
func tryToRetrieveImageFromCacheForKey(key: String,
withURL URL: NSURL,
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
options: KingfisherOptionsInfo?)
{
let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in
// Break retain cycle created inside diskTask closure below
retrieveImageTask.diskRetrieveTask = nil
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
let targetCache = options?.targetCache ?? cache
let diskTask = targetCache.retrieveImageForKey(key, options: options,
completionHandler: { image, cacheType in
if image != nil {
diskTaskCompletionHandler(image: image, error: nil, cacheType:cacheType, imageURL: URL)
} else {
self.downloadAndCacheImageWithURL(URL,
forKey: key,
retrieveImageTask: retrieveImageTask,
progressBlock: progressBlock,
completionHandler: diskTaskCompletionHandler,
options: options)
}
})
retrieveImageTask.diskRetrieveTask = diskTask
}
}
| apache-2.0 | b7e6911c346369113bd2493d1058e2e4 | 45.406114 | 162 | 0.65343 | 5.676816 | false | false | false | false |
changanli/LCAExtension | LCAExtension/Classes/UIAlertController+Additions.swift | 1 | 1899 | //
// UIAlertController+Additions.swift
// Extensions
//
// Created by lichangan on 2017/9/12.
// Copyright © 2017年 com.cnlod.cn. All rights reserved.
//
import UIKit
public extension UIAlertController {
/**
* 确定 取消操作
*
* @param target 目标
* @param title 提示的标题
* @param message 提示的消息
* @param confirmHandler 确定的操作
*/
class func chooseAlert(target:UIViewController,title:String?,message:String?,cancel:String?="取消",confirm:String?="确认",confirmHandler:@escaping (()->Void)){
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: cancel ?? "取消", style: .cancel, handler: nil)
let confirmAction = UIAlertAction(title: confirm ?? "确认", style: .default) {(_) in
confirmHandler()
}
alertVC.addAction(confirmAction)
alertVC.addAction(cancelAction)
target.present(alertVC, animated: true) {
}
}
/**
* 简单的警告提示框
*
* @param title 提示标题
* @param message 提示消息
* @param confirm 确认标题
* @param confirmHandler 确定的操作
* @param target 目标
*/
class func simpleAlert(target:UIViewController,title:String?,message:String?,confirm:String,confirmHandler:@escaping (()->Void)) {
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: confirm, style: .default) {(_) in
target.dismiss(animated: true, completion: {
})
confirmHandler()
}
alertVC.addAction(confirmAction)
target.present(alertVC, animated: true) {
}
}
}
| mit | 6b18e3f189b71fb411558fa64efa25eb | 30.22807 | 159 | 0.601685 | 4.299517 | false | false | false | false |
Sorix/CloudCore | Source/Classes/Save/CoreDataListener.swift | 1 | 4644 | //
// CoreDataChangesListener.swift
// CloudCore
//
// Created by Vasily Ulianov on 02.02.17.
// Copyright © 2017 Vasily Ulianov. All rights reserved.
//
import Foundation
import CoreData
import CloudKit
/// Class responsible for taking action on Core Data save notifications
class CoreDataListener {
var container: NSPersistentContainer
let converter = ObjectToRecordConverter()
let cloudSaveOperationQueue = CloudSaveOperationQueue()
let cloudContextName = "CloudCoreSync"
// Used for errors delegation
weak var delegate: CloudCoreDelegate?
public init(container: NSPersistentContainer) {
self.container = container
converter.errorBlock = { [weak self] in
self?.delegate?.error(error: $0, module: .some(.saveToCloud))
}
}
/// Observe Core Data willSave and didSave notifications
func observe() {
NotificationCenter.default.addObserver(self, selector: #selector(self.willSave(notification:)), name: .NSManagedObjectContextWillSave, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.didSave(notification:)), name: .NSManagedObjectContextDidSave, object: nil)
}
/// Remove Core Data observers
func stopObserving() {
NotificationCenter.default.removeObserver(self)
}
deinit {
stopObserving()
}
@objc private func willSave(notification: Notification) {
guard let context = notification.object as? NSManagedObjectContext else { return }
// Ignore saves that are generated by FetchAndSaveController
if context.name == CloudCore.config.contextName { return }
// Upload only for changes in root context that will be saved to persistentStore
if context.parent != nil { return }
converter.setUnconfirmedOperations(inserted: context.insertedObjects,
updated: context.updatedObjects,
deleted: context.deletedObjects)
}
@objc private func didSave(notification: Notification) {
guard let context = notification.object as? NSManagedObjectContext else { return }
if context.name == CloudCore.config.contextName { return }
if context.parent != nil { return }
if converter.notConfirmedConvertOperations.isEmpty && converter.recordIDsToDelete.isEmpty { return }
DispatchQueue.global(qos: .utility).async { [weak self] in
guard let listener = self else { return }
CloudCore.delegate?.willSyncToCloud()
let backgroundContext = listener.container.newBackgroundContext()
backgroundContext.name = listener.cloudContextName
let records = listener.converter.confirmConvertOperationsAndWait(in: backgroundContext)
listener.cloudSaveOperationQueue.errorBlock = { listener.handle(error: $0, parentContext: backgroundContext) }
listener.cloudSaveOperationQueue.addOperations(recordsToSave: records.recordsToSave, recordIDsToDelete: records.recordIDsToDelete)
listener.cloudSaveOperationQueue.waitUntilAllOperationsAreFinished()
do {
if backgroundContext.hasChanges {
try backgroundContext.save()
}
} catch {
listener.delegate?.error(error: error, module: .some(.saveToCloud))
}
CloudCore.delegate?.didSyncToCloud()
}
}
private func handle(error: Error, parentContext: NSManagedObjectContext) {
guard let cloudError = error as? CKError else {
delegate?.error(error: error, module: .some(.saveToCloud))
return
}
switch cloudError.code {
// Zone was accidentally deleted (NOT PURGED), we need to reupload all data accroding Apple Guidelines
case .zoneNotFound:
cloudSaveOperationQueue.cancelAllOperations()
// Create CloudCore Zone
let createZoneOperation = CreateCloudCoreZoneOperation()
createZoneOperation.errorBlock = {
self.delegate?.error(error: $0, module: .some(.saveToCloud))
self.cloudSaveOperationQueue.cancelAllOperations()
}
// Subscribe operation
#if !os(watchOS)
let subscribeOperation = SubscribeOperation()
subscribeOperation.errorBlock = { self.delegate?.error(error: $0, module: .some(.saveToCloud)) }
subscribeOperation.addDependency(createZoneOperation)
cloudSaveOperationQueue.addOperation(subscribeOperation)
#endif
// Upload all local data
let uploadOperation = UploadAllLocalDataOperation(parentContext: parentContext, managedObjectModel: container.managedObjectModel)
uploadOperation.errorBlock = { self.delegate?.error(error: $0, module: .some(.saveToCloud)) }
cloudSaveOperationQueue.addOperations([createZoneOperation, uploadOperation], waitUntilFinished: true)
case .operationCancelled: return
default: delegate?.error(error: cloudError, module: .some(.saveToCloud))
}
}
}
| mit | 87d119c5b23cc7626a4b69b5b1b970f7 | 35.273438 | 149 | 0.750377 | 4.359624 | false | false | false | false |
andrewjclark/VDLConceptGraph | VDLConceptWeb/VDLConceptWeb/VDLConceptGraph.swift | 1 | 5126 | //
// VDLConceptGraph.swift
// Voidology Concept Web
//
// Created by Andrew J Clark on 20/04/2015.
// Copyright (c) 2015 Andrew J Clark. All rights reserved.
//
import Foundation
public class VDLConceptGraph: Printable {
var concepts = Dictionary<String, VDLConceptObject>()
class var sharedInstance: VDLConceptGraph {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: VDLConceptGraph? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = VDLConceptGraph()
}
return Static.instance!
}
public var description: String {
var conceptsString = "VDLConceptGraph contains \(concepts.count) concepts..."
for (uid, concept) in concepts {
conceptsString += "\n- \(concept) (key: \(uid))"
}
return conceptsString
}
init() {
if let filePath = NSBundle.mainBundle().pathForResource("ConceptIndex", ofType:"conceptindex") {
let loadedString = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil)
let conceptStringArray = loadedString!.componentsSeparatedByString("\n")
for conceptString in conceptStringArray {
// If this object is empty or starts with "//" then skip it
var skipLine = false
if count(conceptString) <= 2 {
skipLine = true
} else if count(conceptString) > 2 {
let endIndex = advance(conceptString.startIndex, 2)
let firstTwoChars = conceptString.substringToIndex(endIndex)
if firstTwoChars == "//" {
skipLine = true
}
}
if skipLine == false {
let stringArray = conceptString.componentsSeparatedByString(" ")
// Get the concept with this UID from self (may or may not be a new concept)
if count(stringArray) >= 1 {
let idString = stringArray[0]
var newItem = self.conceptWithUid(idString)
// Get the relativeTo objects
if count(stringArray) >= 2 {
let relativeToString = stringArray[1]
if count(relativeToString) > 0 {
let conceptUids = relativeToString.componentsSeparatedByString(",")
for conceptUid in conceptUids {
var concept = self.conceptWithUid(conceptUid)
if concept != newItem {
newItem.relatedConcepts.insert(concept)
// Set the relativeOf in the inverse direction.
concept.relativeOfConcepts.insert(newItem)
}
}
}
}
// Get the images
if count(stringArray) >= 3 {
let imagesString = stringArray[2]
for image in imagesString.componentsSeparatedByString(",") {
newItem.images.insert(image)
}
}
}
}
}
}
}
public func probabilitySetForConcept(concept: VDLConceptObject, requireImages: Bool) -> VDLConceptProbabilitySet {
// Introspect the provided concept and return a VDLConceptProbabilitySet
return concept.introspectRelatedConcepts(Set<VDLConceptObject>(), requireImages: requireImages)
}
public func probabilitySetForConceptWithUid(conceptUid: String, requireImages: Bool) -> VDLConceptProbabilitySet {
let concept = self.conceptWithUid(conceptUid)
// Introspect the provided concept and return a VDLConceptProbabilitySet
return probabilitySetForConcept(concept, requireImages: requireImages)
}
public func conceptWithUid(uid: String) -> VDLConceptObject {
// Return the VDLConceptObject with the provided UID, creating it first if necessary.
if let concept = concepts[uid] {
return concept
} else {
var newConcept = VDLConceptObject()
newConcept.uid = uid
concepts[uid] = newConcept
return newConcept
}
}
} | mit | 1777b866f0dd14a17f718ab339579819 | 37.261194 | 118 | 0.482247 | 6.243605 | false | false | false | false |
CartoDB/mobile-ios-samples | AdvancedMap.Swift/Feature Demo/TransportModePopupContent.swift | 1 | 5063 | //
// TransportModePopupContent.swift
// AdvancedMap.Swift
//
// Created by Aare Undo on 17/11/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
import UIKit
class TransportModePopupContent: UIView, UITableViewDataSource {
let IDENTIFIER = "TransportModeCell"
var table: UITableView!
var modes: [TransportMode] = [TransportMode]()
init() {
super.init(frame: CGRect.zero)
var mode = TransportMode(title: "Pedestrian", description: "Standard walking route that excludes roads without pedestrian access, walkways and footpaths are slightly favored", mode: "pedestrian")
modes.append(mode)
mode = TransportMode(title: "Car", description: "Standard costing for driving routes by car, motorcycle, truck, and so on that obeys automobile driving rules, such as access and turn restrictions. ", mode: "auto")
modes.append(mode)
mode = TransportMode(title: "Bicycle", description: "Standard costing for travel by bicycle, with a slight preference for using cycleways or roads with bicycle lanes.", mode: "bicycle")
modes.append(mode)
// mode = TransportMode(title: "MultiModal", description: "Pedestrian and transit. In the future, multimodal will support a combination of all of the above.", mode: "multimodal")
// modes.append(mode)
table = UITableView()
table.dataSource = self
table.register(TransportModeCell.self, forCellReuseIdentifier: IDENTIFIER)
table.rowHeight = 70
addSubview(table)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
table.frame = bounds
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return modes.count
}
var initialHighlightSet = false
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let mode = modes[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: IDENTIFIER, for: indexPath as IndexPath) as! TransportModeCell
cell.selectionStyle = .none
cell.update(mode: mode)
if (!initialHighlightSet && cell.mode?.mode == "pedestrian") {
initialHighlightSet = true
cell.activate()
}
return cell
}
var previous: TransportModeCell?
func highlightRow(at: IndexPath) -> TransportModeCell {
for cell in table.visibleCells {
(cell as! TransportModeCell).normalize()
}
let cell = table.cellForRow(at: at) as! TransportModeCell
cell.activate()
return cell
}
}
class TransportModeCell: UITableViewCell {
let titleLabel = UILabel()
let descriptionLabel = UILabel()
let checkMark = UIImageView()
var mode: TransportMode?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 13)
titleLabel.textColor = UIColor.darkGray
addSubview(titleLabel)
descriptionLabel.font = UIFont(name: "HelveticaNeue", size: 11)
descriptionLabel.textColor = UIColor.lightGray
descriptionLabel.lineBreakMode = .byWordWrapping
descriptionLabel.numberOfLines = 0;
addSubview(descriptionLabel)
checkMark.image = UIImage(named: "icon_checkmark_green.png")
addSubview(checkMark)
normalize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
let padding: CGFloat = 5
let x = padding
var y = padding
let w = frame.width - 2 * padding
let h = (frame.height - 2 * padding) / 2
titleLabel.frame = CGRect(x: x, y: y, width: w, height: h)
let checkHeight = h / 1.3
checkMark.frame = CGRect(x: frame.width - (checkHeight + padding), y: y, width: checkHeight, height: checkHeight * 1.27)
y += h
descriptionLabel.frame = CGRect(x: x, y: y, width: w, height: h)
}
func update(mode: TransportMode) {
self.mode = mode
titleLabel.text = mode.title
descriptionLabel.text = mode.description
}
func activate() {
checkMark.isHidden = false
}
func normalize() {
checkMark.isHidden = true
}
}
class TransportMode {
var title = ""
var description = ""
var mode = ""
init(title: String, description: String, mode: String) {
self.title = title
self.description = description
self.mode = mode
}
}
| bsd-2-clause | a4b7c2069b30516cba8db2eca28d9025 | 28.776471 | 221 | 0.617938 | 4.695733 | false | false | false | false |
Senspark/ee-x | src/ios/ee/ad_mob/AdMobRewardedAd.swift | 1 | 4604 | //
// AdMobRewardedAd.swift
// ee-x-366f64ba
//
// Created by eps on 6/24/20.
//
import GoogleMobileAds
private let kTag = "\(AdMobRewardedAd.self)"
internal class AdMobRewardedAd: NSObject, IFullScreenAd, GADFullScreenContentDelegate {
private let _bridge: IMessageBridge
private let _logger: ILogger
private let _adId: String
private let _messageHelper: MessageHelper
private var _helper: FullScreenAdHelper?
private var _isLoaded = false
private var _ad: GADRewardedAd?
private var _rewarded = false
init(_ bridge: IMessageBridge,
_ logger: ILogger,
_ adId: String) {
_bridge = bridge
_logger = logger
_adId = adId
_messageHelper = MessageHelper("AdMobRewardedAd", _adId)
super.init()
_helper = FullScreenAdHelper(_bridge, self, _messageHelper)
registerHandlers()
}
func destroy() {
deregisterHandlers()
}
func registerHandlers() {
_helper?.registerHandlers()
}
func deregisterHandlers() {
_helper?.deregisterHandlers()
}
var isLoaded: Bool {
return _isLoaded
}
func load() {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
GADRewardedAd.load(withAdUnitID: self._adId, request: GADRequest()) { ad, error in
if let error = error {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): failed id = \(self._adId) message = \(error.localizedDescription)")
self._bridge.callCpp(self._messageHelper.onFailedToLoad, EEJsonUtils.convertDictionary(toString: [
"code": (error as NSError).code,
"message": error.localizedDescription
]))
}
} else {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): succeeded id = \(self._adId)")
self._isLoaded = true
self._ad = ad
self._ad?.fullScreenContentDelegate = self
self._bridge.callCpp(self._messageHelper.onLoaded)
}
}
}
}
}
func show() {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
guard let ad = self._ad else {
assert(false, "Ad is not initialized")
self._bridge.callCpp(self._messageHelper.onFailedToShow, EEJsonUtils.convertDictionary(toString: [
"code": -1,
"message": "Null ad"
]))
return
}
guard let rootView = Utils.getCurrentRootViewController() else {
assert(false, "Current rootView is null")
self._bridge.callCpp(self._messageHelper.onFailedToShow, EEJsonUtils.convertDictionary(toString: [
"code": -1,
"message": "Null root view"
]))
return
}
self._rewarded = false
ad.present(fromRootViewController: rootView) {
Thread.runOnMainThread {
self._rewarded = true
}
}
}
}
func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
}
}
func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId) message = \(error.localizedDescription)")
self._isLoaded = false
self._ad = nil
self._bridge.callCpp(self._messageHelper.onFailedToShow, EEJsonUtils.convertDictionary(toString: [
"code": (error as NSError).code,
"message": error.localizedDescription
]))
}
}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
self._isLoaded = false
self._ad = nil
self._bridge.callCpp(self._messageHelper.onClosed, Utils.toString(self._rewarded))
}
}
}
| mit | 7febcb3d824e9cf62a9f35c5ce907f5c | 34.689922 | 134 | 0.53649 | 4.961207 | false | false | false | false |
MModel/MetaModel | lib/metamodel/template/association/has_many_association.swift | 1 | 5959 | //
// <%= association.class_name %>.swift
// MetaModel
//
// Created by MetaModel.
// Copyright © 2016 metamodel. All rights reserved.
//
import Foundation
typealias <%= association.reverse_class_name %> = <%= association.class_name %>
struct <%= association.class_name %> {
var privateId: Int = 0
var <%= association.major_model_id %>: Int = 0
var <%= association.secondary_model_id %>: Int = 0
enum Association: String, CustomStringConvertible {
case privateId = "private_id"
case <%= association.major_model_id %> = "<%= association.major_model_id.underscore %>"
case <%= association.secondary_model_id %> = "<%= association.secondary_model_id.underscore %>"
var description: String { get { return self.rawValue } }
}
<% [association.major_model, association.secondary_model].zip([association.secondary_model, association.major_model]).each do |first, second| %>
static func fetch<%= first.table_name.camelize %>(<%= second.foreign_id %>: Int, first: Bool = false) -> [<%= first.name %>] {
var query = "SELECT * FROM <%= first.table_name %> WHERE <%= first.table_name %>.private_id IN (" +
"SELECT private_id " +
"FROM \(tableName) " +
"WHERE \(Association.<%= second.foreign_id %>) = \(<%= second.foreign_id %>)" +
")"
if first { query += "LIMIT 1" }
return MetaModels.fromQuery(query)
}
<% end %><% [association.major_model, association.secondary_model].each do |model| %>
static func findBy(<%= model.foreign_id %>: Int) -> [<%= association.class_name %>] {
let query = "SELECT * FROM \(tableName) WHERE <%= model.foreign_id.underscore %> = \(<%= model.foreign_id %>)"
return MetaModels.fromQuery(query)
}
<% end %>
var delete: Void {
get {
executeSQL("DELETE * FROM \(<%= association.class_name %>.tableName) WHERE private_id = \(privateId)")
}
}
}
extension <%= association.class_name %> {
static func create(<%= association.major_model_id %>: Int, <%= association.secondary_model_id %>: Int) {
executeSQL("INSERT INTO \(<%= association.class_name %>.tableName) (<%= association.major_model_id.underscore %>, <%= association.secondary_model_id.underscore %>) VALUES (\(<%= association.major_model_id %>), \(<%= association.secondary_model_id %>))")
}
}
extension <%= association.class_name %> {
static let tableName = "<%= association.class_name.underscore %>"
static func initialize() {
let initializeTableSQL = "CREATE TABLE \(tableName)(" +
"private_id INTEGER PRIMARY KEY, " +
"<%= association.major_model_id.underscore %> INTEGER NOT NULL, " +
"<%= association.secondary_model_id.underscore %> INTEGER NOT NULL, " +
"FOREIGN KEY(<%= association.major_model_id.underscore %>) REFERENCES <%= association.major_model.table_name %>(private_id)," +
"FOREIGN KEY(<%= association.secondary_model_id.underscore %>) REFERENCES <%= association.secondary_model.table_name %>(private_id)" +
");"
executeSQL(initializeTableSQL)
initializeTrigger()
}
static func deinitialize() {
let dropTableSQL = "DROP TABLE \(tableName)"
executeSQL(dropTableSQL)
deinitializeTrigger()
}
static func initializeTrigger() {
let majorDeleteTrigger = "CREATE TRIGGER <%= association.major_model.name.underscore %>_delete_trigger " +
"AFTER DELETE ON <%= association.major_model.table_name %> " +
"FOR EACH ROW BEGIN " +
"DELETE FROM \(tableName) WHERE private_id = OLD.private_id; " +
"END;";
let secondaryDeleteTrigger = "CREATE TRIGGER <%= association.secondary_model.name.underscore %>_delete_trigger " +
"AFTER DELETE ON <%= association.secondary_model.table_name %> " +
"FOR EACH ROW BEGIN " +
"DELETE FROM \(tableName) WHERE private_id = OLD.private_id; " +
"END;";
executeSQL(majorDeleteTrigger)
executeSQL(secondaryDeleteTrigger)
}
static func deinitializeTrigger() {
let dropMajorTrigger = "DROP TRIGGER IF EXISTS <%= association.major_model.name.underscore %>_delete_trigger;"
executeSQL(dropMajorTrigger)
let dropSecondaryTrigger = "DROP TRIGGER IF EXISTS <%= association.secondary_model.name.underscore %>_delete_trigger;"
executeSQL(dropSecondaryTrigger)
}
}
public extension <%= association.major_model.name %> {
var <%= association.name %>: [<%= association.secondary_model.name %>] {
get {
return <%= association.class_name %>.fetch<%= association.secondary_model.name.tableize.camelize %>(<%= association.major_model.foreign_id %>: privateId)
}
set {
<%= association.class_name %>.findBy(<%= association.major_model_id %>: privateId).forEach { $0.delete }
newValue.forEach { <%= association.class_name %>.create(<%= association.major_model_id %>: privateId, <%= association.secondary_model_id %>: $0.privateId) }
}
}
@discardableResult func create<%= association.secondary_model.name %>(<%= association.secondary_model.property_key_type_pairs %>) -> <%= association.secondary_model.name %>? {
guard let result = <%= association.secondary_model.name %>.create(<%= association.secondary_model.property_key_value_pairs %>) else { return nil }
<%= association.class_name %>.create(<%= association.major_model_id %>: privateId, <%= association.secondary_model_id %>: result.privateId)
return result
}
@discardableResult func append<%= association.secondary_model.name %>(<%= association.secondary_model.property_key_type_pairs %>) -> <%= association.secondary_model.name %>? {
return create<%= association.secondary_model.name %>(<%= association.secondary_model.property_key_value_pairs %>)
}
}
| mit | 6833b4123b18a9892455aa2f2aa1d294 | 48.65 | 261 | 0.629406 | 3.961436 | false | false | false | false |
jcheng77/missfit-ios | missfit/missfit/RegisterViewController.swift | 1 | 10773 | //
// RegisterViewController.swift
// missfit
//
// Created by Hank Liang on 4/15/15.
// Copyright (c) 2015 Hank Liang. All rights reserved.
//
import UIKit
class RegisterViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var verifycodeButton: UIButton!
@IBOutlet weak var phoneNumberTextField: UITextField!
@IBOutlet weak var passcodeTextField: UITextField!
@IBOutlet weak var verifyCodeTextField: UITextField!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var submitButton: UIButton!
var timer: NSTimer?
let maxTimerSeconds = 20
override func viewDidLoad() {
super.viewDidLoad()
self.phoneNumberTextField.layer.borderWidth = 1.0
self.phoneNumberTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.passcodeTextField.layer.borderWidth = 1.0
self.passcodeTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.verifyCodeTextField.layer.borderWidth = 1.0
self.verifyCodeTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.nameTextField.layer.borderWidth = 1.0
self.nameTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@IBAction func hideKeyboard(sender: AnyObject) {
phoneNumberTextField.resignFirstResponder()
passcodeTextField.resignFirstResponder()
verifyCodeTextField.resignFirstResponder()
nameTextField.resignFirstResponder()
}
func keyboardWillShow(notifiction: NSNotification) {
var keyboardEndFrame: CGRect = CGRectZero
(notifiction.userInfo! as NSDictionary).valueForKey(UIKeyboardFrameEndUserInfoKey)!.getValue(&keyboardEndFrame)
let keyboardHeight: CGFloat = keyboardEndFrame.size.height
let buttonBottomPointY = submitButton.frame.origin.y + submitButton.frame.size.height
let keyboardTopPointY = self.view.frame.size.height - keyboardHeight
let offsetY = keyboardTopPointY - buttonBottomPointY
let oldFrame = self.view.frame
self.view.frame = CGRectMake(oldFrame.origin.x, min(offsetY, 0.0), oldFrame.size.width, oldFrame.size.height)
}
func keyboardWillHide(notification: NSNotification) {
let oldFrame = self.view.frame
self.view.frame = CGRectMake(oldFrame.origin.x, 0, oldFrame.size.width, oldFrame.size.height)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backButtonClicked(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func updateVerifyCodeButtonTimer() {
let remainingSeconds = verifycodeButton.titleForState(.Disabled)!.toInt()! - 1
if remainingSeconds > 0 {
verifycodeButton.setTitle(String(remainingSeconds), forState: .Disabled)
} else {
timer!.invalidate()
timer = nil
updateVerifyCodeButton(true)
}
}
func updateVerifyCodeButton(enabled: Bool) {
if enabled {
verifycodeButton.enabled = true
verifycodeButton.setTitle("获取验证码", forState: .Normal)
verifycodeButton.backgroundColor = MissFitTheme.theme.colorPink
} else {
verifycodeButton.enabled = false
verifycodeButton.setTitle(String(maxTimerSeconds), forState: .Disabled)
verifycodeButton.backgroundColor = MissFitTheme.theme.colorDisabled
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateVerifyCodeButtonTimer"), userInfo: nil, repeats: true)
}
}
@IBAction func submitButtonClicked(sender: AnyObject) {
self.hideKeyboard(self)
var regex: NSRegularExpression = NSRegularExpression(pattern: "(\\d{11})", options: NSRegularExpressionOptions.CaseInsensitive, error: nil)!
let result = regex.firstMatchInString(self.phoneNumberTextField.text!, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, count(self.phoneNumberTextField.text!.utf16)))
if result != nil && !NSEqualRanges(result!.range, NSMakeRange(NSNotFound, 0)) {
let phoneNumber: String = (self.phoneNumberTextField.text! as NSString).substringWithRange(result!.rangeAtIndex(1))
var verifyCode: String = self.verifyCodeTextField.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if verifyCode == "" {
KVNProgress.showErrorWithStatus("验证码不能为空")
} else {
var passcode: String = self.passcodeTextField.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if passcode == "" {
KVNProgress.showErrorWithStatus("密码不能为空")
} else {
var name: String = self.nameTextField.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if name == "" {
KVNProgress.showErrorWithStatus("姓名不能为空")
} else {
var manager: AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
var endpoint: String = MissFitBaseURL + MissFitRegisterURI
var code: Int = verifyCode.toInt()!
var parameters = ["username": phoneNumber, "password": passcode, "code": code, "name": name]
KVNProgress.show()
manager.POST(endpoint, parameters: parameters, success: { (operation, responseObject) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
KVNProgress.showSuccessWithStatus("恭喜您注册成功!")
UmengHelper.event(AnalyticsRegisterSucceed)
//注册成功
}, failure: { (operation, error) -> Void in
//注册失败
UmengHelper.event(AnalyticsRegisterFail)
if error.userInfo?[AFNetworkingOperationFailingURLResponseDataErrorKey] != nil {
// Need to get the status and message
let json = JSON(data: error.userInfo![AFNetworkingOperationFailingURLResponseDataErrorKey] as! NSData)
let message: String? = json["message"].string
KVNProgress.showErrorWithStatus(message)
} else {
KVNProgress.showErrorWithStatus("注册失败")
}
})
}
}
}
} else {
KVNProgress.showErrorWithStatus("请填写正确的手机号码!")
}
}
@IBAction func verifyCodeButtonClicked(sender: AnyObject) {
var regex: NSRegularExpression = NSRegularExpression(pattern: "(\\d{11})", options: NSRegularExpressionOptions.CaseInsensitive, error: nil)!
let result = regex.firstMatchInString(self.phoneNumberTextField.text!, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, count(self.phoneNumberTextField.text!.utf16)))
if result != nil && !NSEqualRanges(result!.range, NSMakeRange(NSNotFound, 0)) {
let phoneNumber: String = (self.phoneNumberTextField.text! as NSString).substringWithRange(result!.rangeAtIndex(1))
var manager: AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
var endpoint: String = MissFitBaseURL + MissFitVerifyCodeURI + phoneNumber
manager.POST(endpoint, parameters: nil, success: { (operation, responseObject) -> Void in
//验证码获取成功
self.updateVerifyCodeButton(false)
}, failure: { (operation, error) -> Void in
//验证码获取失败
})
} else {
KVNProgress.showErrorWithStatus("请填写正确的手机号码!")
}
}
func textFieldDidBeginEditing(textField: UITextField) {
if self.phoneNumberTextField.isFirstResponder() {
self.phoneNumberTextField.layer.borderColor = MissFitTheme.theme.colorPink.CGColor
self.passcodeTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.verifyCodeTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.nameTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
}
if self.passcodeTextField.isFirstResponder() {
self.phoneNumberTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.passcodeTextField.layer.borderColor = MissFitTheme.theme.colorPink.CGColor
self.verifyCodeTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.nameTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
}
if self.verifyCodeTextField.isFirstResponder() {
self.phoneNumberTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.passcodeTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.verifyCodeTextField.layer.borderColor = MissFitTheme.theme.colorPink.CGColor
self.nameTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
}
if self.nameTextField.isFirstResponder() {
self.phoneNumberTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.passcodeTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.verifyCodeTextField.layer.borderColor = MissFitTheme.theme.colorTextFieldBorder.CGColor
self.nameTextField.layer.borderColor = MissFitTheme.theme.colorPink.CGColor
}
}
}
| mit | 0a887e43624c9decdf8dc1a372e631b7 | 52.873096 | 188 | 0.663243 | 5.579916 | false | false | false | false |
EasySwift/EasySwift | Carthage/Checkouts/ReactiveKit/Tests/ReactiveKitTests/ResultTests.swift | 8 | 553 | //
// ResultTests.swift
// ReactiveKit
//
// Created by Srdan Rasic on 22/10/2016.
// Copyright © 2016 Srdan Rasic. All rights reserved.
//
import XCTest
import ReactiveKit
class ResultTests: XCTestCase {
func testSuccess() {
let result = Result<Int, TestError>(5)
XCTAssert(result.error == nil)
XCTAssert(result.value != nil && result.value! == 5)
}
func testFailured() {
let result = Result<Int, TestError>(.Error)
XCTAssert(result.error != nil && result.error! == .Error)
XCTAssert(result.value == nil)
}
}
| apache-2.0 | 7434362f577bac560f03a0734342897e | 19.444444 | 61 | 0.655797 | 3.704698 | false | true | false | false |
tardieu/swift | test/ClangImporter/attr-swift_private.swift | 1 | 5324 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -typecheck %s -verify -verify-ignore-unknown
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -Xllvm -new-mangling-for-tests -I %S/Inputs/custom-modules -emit-ir %s -D IRGEN | %FileCheck %s
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -print-module -source-filename="%s" -module-to-print SwiftPrivateAttr > %t.txt
// RUN: %FileCheck -check-prefix=GENERATED-NEGATIVE %s < %t.txt
// RUN: diff -U3 %S/Inputs/SwiftPrivateAttr.txt %t.txt
// Look for identifiers with "Priv" in them that haven't been prefixed.
// GENERATED-NEGATIVE-NOT: {{[^A-Za-z0-9_][A-Za-z0-9]*[Pp]riv}}
// REQUIRES: objc_interop
import SwiftPrivateAttr
// Note: The long-term plan is for these to only be available from the Swift
// half of a module, or from an overlay. At that point we should test that these
// are available in that case and /not/ in the normal import case.
// CHECK-LABEL: define{{( protected)?}} void @{{.+}}12testProperty
public func testProperty(_ foo: Foo) {
// CHECK: @"\01L_selector(setPrivValue:)"
_ = foo.__privValue
foo.__privValue = foo
// CHECK: @"\01L_selector(setPrivClassValue:)"
_ = Foo.__privClassValue
Foo.__privClassValue = foo
#if !IRGEN
_ = foo.privValue // expected-error {{value of type 'Foo' has no member 'privValue'}}
#endif
}
// CHECK-LABEL: define{{( protected)?}} void @{{.+}}11testMethods
public func testMethods(_ foo: Foo) {
// CHECK: @"\01L_selector(noArgs)"
foo.__noArgs()
// CHECK: @"\01L_selector(oneArg:)"
foo.__oneArg(1)
// CHECK: @"\01L_selector(twoArgs:other:)"
foo.__twoArgs(1, other: 2)
}
// CHECK-LABEL: define{{( protected)?}} void @{{.+}}16testInitializers
public func testInitializers() {
// Checked below; look for "CSo3Bar".
_ = Bar(__noArgs: ())
_ = Bar(__oneArg: 1)
_ = Bar(__twoArgs: 1, other: 2)
_ = Bar(__: 1)
}
// CHECK-LABEL: define{{( protected)?}} void @{{.+}}18testFactoryMethods
public func testFactoryMethods() {
// CHECK: @"\01L_selector(fooWithOneArg:)"
_ = Foo(__oneArg: 1)
// CHECK: @"\01L_selector(fooWithTwoArgs:other:)"
_ = Foo(__twoArgs: 1, other: 2)
// CHECK: @"\01L_selector(foo:)"
_ = Foo(__: 1)
}
#if !IRGEN
public func testSubscript(_ foo: Foo) {
_ = foo[foo] // expected-error {{type 'Foo' has no subscript members}}
_ = foo[1] // expected-error {{type 'Foo' has no subscript members}}
}
#endif
// CHECK-LABEL: define{{( protected)?}} void @{{.+}}12testTopLevel
public func testTopLevel() {
// Checked below; look for "PrivFooSub".
let foo = __PrivFooSub()
_ = foo as __PrivProto
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_PrivProto"
foo.conforms(to: __PrivProto.self)
// CHECK: call void @privTest()
__privTest()
_ = __PrivS1()
#if !IRGEN
let _ = PrivFooSub() // expected-error {{use of unresolved identifier}}
privTest() // expected-error {{use of unresolved identifier}}
PrivS1() // expected-error {{use of unresolved identifier}}
#endif
}
// CHECK-LABEL: define linkonce_odr hidden %swift.type* @_T0So12__PrivFooSubCMa{{.*}} {
// CHECK: %objc_class** @"OBJC_CLASS_REF_$_PrivFooSub"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarCSQyABGs5Int32V2___tcfcTO
// CHECK: @"\01L_selector(init:)"
// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarCSQyABGs5Int32V9__twoArgs_AD5othertcfcTO
// CHECK: @"\01L_selector(initWithTwoArgs:other:)"
// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarCSQyABGs5Int32V8__oneArg_tcfcTO
// CHECK: @"\01L_selector(initWithOneArg:)"
// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarCSQyABGyt8__noArgs_tcfcTO
// CHECK: @"\01L_selector(initWithNoArgs)"
_ = __PrivAnonymousA
_ = __E0PrivA
_ = __PrivE1A as __PrivE1
_ = NSEnum.__privA
_ = NSEnum.B
_ = NSOptions.__privA
_ = NSOptions.B
func makeSureAnyObject(_: AnyObject) {}
#if !IRGEN
func testUnavailableRefs() {
var x: __PrivCFTypeRef // expected-error {{'__PrivCFTypeRef' has been renamed to '__PrivCFType'}}
var y: __PrivCFSubRef // expected-error {{'__PrivCFSubRef' has been renamed to '__PrivCFSub'}}
}
#endif
func testCF(_ a: __PrivCFType, b: __PrivCFSub, c: __PrivInt) {
makeSureAnyObject(a)
makeSureAnyObject(b)
#if !IRGEN
makeSureAnyObject(c) // expected-error {{argument type '__PrivInt' (aka 'Int32') does not conform to expected type 'AnyObject'}}
#endif
}
extension __PrivCFType {}
extension __PrivCFSub {}
_ = 1 as __PrivInt
#if !IRGEN
func testRawNames() {
let _ = Foo.__fooWithOneArg(0) // expected-error {{'__fooWithOneArg' is unavailable: use object construction 'Foo(__oneArg:)'}}
let _ = Foo.__foo // expected-error{{'__foo' is unavailable: use object construction 'Foo(__:)'}}
}
#endif
// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected note produced: '__PrivCFTypeRef' was obsoleted in Swift 3
// <unknown>:0: error: unexpected note produced: '__PrivCFSubRef' was obsoleted in Swift 3
// <unknown>:0: error: unexpected note produced: '__fooWithOneArg' has been explicitly marked unavailable here
// <unknown>:0: error: unexpected note produced: '__foo' has been explicitly marked unavailable here
| apache-2.0 | 9cbe5df1f1f65aedd8f3c6ff67afc084 | 35.217687 | 183 | 0.673554 | 3.268263 | false | true | false | false |
nanthi1990/CVCalendar | CVCalendar/CVCalendarContentViewController.swift | 8 | 7345 | //
// CVCalendarContentViewController.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 12/04/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
public typealias Identifier = String
public class CVCalendarContentViewController: UIViewController {
// MARK: - Constants
public let Previous = "Previous"
public let Presented = "Presented"
public let Following = "Following"
// MARK: - Public Properties
public let calendarView: CalendarView
public let scrollView: UIScrollView
public var presentedMonthView: MonthView
public var bounds: CGRect {
return scrollView.bounds
}
public var currentPage = 1
public var pageChanged: Bool {
get {
return currentPage == 1 ? false : true
}
}
public var pageLoadingEnabled = true
public var presentationEnabled = true
public var lastContentOffset: CGFloat = 0
public var direction: CVScrollDirection = .None
public init(calendarView: CalendarView, frame: CGRect) {
self.calendarView = calendarView
scrollView = UIScrollView(frame: frame)
presentedMonthView = MonthView(calendarView: calendarView, date: NSDate())
presentedMonthView.updateAppearance(frame)
super.init(nibName: nil, bundle: nil)
scrollView.contentSize = CGSizeMake(frame.width * 3, frame.height)
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.layer.masksToBounds = true
scrollView.pagingEnabled = true
scrollView.delegate = self
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI Refresh
extension CVCalendarContentViewController {
public func updateFrames(frame: CGRect) {
if frame != CGRectZero {
scrollView.frame = frame
scrollView.removeAllSubviews()
scrollView.contentSize = CGSizeMake(frame.size.width * 3, frame.size.height)
}
calendarView.hidden = false
}
}
// MARK: - Abstract methods
/// UIScrollViewDelegate
extension CVCalendarContentViewController: UIScrollViewDelegate { }
/// Convenience API.
extension CVCalendarContentViewController {
public func performedDayViewSelection(dayView: DayView) { }
public func togglePresentedDate(date: NSDate) { }
public func presentNextView(view: UIView?) { }
public func presentPreviousView(view: UIView?) { }
public func updateDayViews(hidden: Bool) { }
}
// MARK: - Contsant conversion
extension CVCalendarContentViewController {
public func indexOfIdentifier(identifier: Identifier) -> Int {
let index: Int
switch identifier {
case Previous: index = 0
case Presented: index = 1
case Following: index = 2
default: index = -1
}
return index
}
}
// MARK: - Date management
extension CVCalendarContentViewController {
public func dateBeforeDate(date: NSDate) -> NSDate {
let components = Manager.componentsForDate(date)
let calendar = NSCalendar.currentCalendar()
components.month -= 1
let dateBefore = calendar.dateFromComponents(components)!
return dateBefore
}
public func dateAfterDate(date: NSDate) -> NSDate {
let components = Manager.componentsForDate(date)
let calendar = NSCalendar.currentCalendar()
components.month += 1
let dateAfter = calendar.dateFromComponents(components)!
return dateAfter
}
public func matchedMonths(lhs: Date, _ rhs: Date) -> Bool {
return lhs.year == rhs.year && lhs.month == rhs.month
}
public func matchedWeeks(lhs: Date, _ rhs: Date) -> Bool {
return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.week == rhs.week)
}
public func matchedDays(lhs: Date, _ rhs: Date) -> Bool {
return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day)
}
}
// MARK: - AutoLayout Management
extension CVCalendarContentViewController {
private func layoutViews(views: [UIView], toHeight height: CGFloat) {
scrollView.frame.size.height = height
var superStack = [UIView]()
var currentView: UIView = calendarView
while let currentSuperview = currentView.superview where !(currentSuperview is UIWindow) {
superStack += [currentSuperview]
currentView = currentSuperview
}
for view in views + superStack {
view.layoutIfNeeded()
}
}
public func updateHeight(height: CGFloat, animated: Bool) {
if calendarView.shouldAnimateResizing {
var viewsToLayout = [UIView]()
if let calendarSuperview = calendarView.superview {
for constraintIn in calendarSuperview.constraints() {
if let constraint = constraintIn as? NSLayoutConstraint {
if let firstItem = constraint.firstItem as? UIView, let secondItem = constraint.secondItem as? CalendarView {
viewsToLayout.append(firstItem)
}
}
}
}
for constraintIn in calendarView.constraints() {
if let constraint = constraintIn as? NSLayoutConstraint where constraint.firstAttribute == NSLayoutAttribute.Height {
constraint.constant = height
if animated {
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {
self.layoutViews(viewsToLayout, toHeight: height)
}) { _ in
self.presentedMonthView.frame.size = self.presentedMonthView.potentialSize
self.presentedMonthView.updateInteractiveView()
}
} else {
layoutViews(viewsToLayout, toHeight: height)
presentedMonthView.updateInteractiveView()
presentedMonthView.frame.size = presentedMonthView.potentialSize
presentedMonthView.updateInteractiveView()
}
break
}
}
}
}
public func updateLayoutIfNeeded() {
if presentedMonthView.potentialSize.height != scrollView.bounds.height {
updateHeight(presentedMonthView.potentialSize.height, animated: true)
} else if presentedMonthView.frame.size != scrollView.frame.size {
presentedMonthView.frame.size = presentedMonthView.potentialSize
presentedMonthView.updateInteractiveView()
}
}
}
extension UIView {
public func removeAllSubviews() {
for subview in subviews {
if let view = subview as? UIView {
view.removeFromSuperview()
}
}
}
} | mit | 12a60509b93908de55f46b680ea9f2c7 | 32.09009 | 133 | 0.606535 | 5.765306 | false | false | false | false |
pandaApe/HLTabPagerViewController | HLTabPagerViewController/Classes/HLTabScrollView.swift | 1 | 11870 | //
// HLTabScrollView.swift
// HLTabPagerViewController
//
// Created by PandaApe ([email protected]) on 5/29/17.
// Copyright © 2017 PandaApe. All rights reserved.
//
import Foundation
import UIKit
@objc protocol HLTabScrollDelegate {
func tabScrollView(_ tabScrollView: HLTabScrollView, didSelectTabAtIndex index: Int) -> Void
}
class HLTabScrollView: UIScrollView {
fileprivate var tabViews: [UIView]!
fileprivate var tabsView: UIView!
fileprivate var tabIndicator: UIView?
fileprivate var tabsLeadingConstraint: NSLayoutConstraint!
fileprivate var tabsTrailingConstraint: NSLayoutConstraint!
fileprivate var indicatorWidthConstraint: NSLayoutConstraint!
fileprivate var indicatorCenterConstraint: NSLayoutConstraint!
weak var tabScrollDelegate: HLTabScrollDelegate?
}
extension HLTabScrollView {
func selectTab(atIndex index:Int, animated:Bool = true) {
var animatedDuration:CGFloat = 0.0;
if animated {
animatedDuration = 0.4
}
self.indicatorCenterConstraint = self.replace(constraint: self.indicatorCenterConstraint, withNewToItem: self.tabViews[index])
self.indicatorWidthConstraint = self.replace(constraint: self.indicatorWidthConstraint, withNewToItem: self.tabViews[index])
UIView.animate(withDuration: TimeInterval(animatedDuration)) {
self.layoutIfNeeded()
self.scrollToSelectedTab()
}
}
}
extension HLTabScrollView {
convenience init(frame: CGRect, tabViews: [UIView], color: UIColor, bottomLineHeight: CGFloat, selectedTabIndex index: Int = 0) {
self.init(frame: frame)
self.showsHorizontalScrollIndicator = false
self.bounces = false
self.tabViews = tabViews
let contentView = UIView()
contentView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(contentView)
self.tabsView = contentView
let bottomLine = UIView(frame: self.bounds)
bottomLine.translatesAutoresizingMaskIntoConstraints = false
bottomLine.backgroundColor = color
self.addSubview(bottomLine)
self.addConstraints(toContentView: contentView,
bottomLine: bottomLine,
bottomLineHeight: bottomLineHeight)
self.addTabs(fromTabViews: tabViews, toContentView: contentView)
self.addIndicators(toContentView: contentView, withColor: color)
self.selectTab(atIndex: index, animated: false)
}
public override var frame: CGRect {
didSet{
self.setNeedsUpdateConstraints()
self.scrollToSelectedTab()
}
}
override public func updateConstraints() {
var offset:CGFloat = 0
if self.bounds.size.width > self.tabsView.frame.size.width {
offset = (self.bounds.size.width - self.tabsView.frame.size.width)/CGFloat(2.0)
}
self.tabsLeadingConstraint.constant = offset
self.tabsTrailingConstraint.constant = -offset
super.updateConstraints()
}
fileprivate func addConstraints(toContentView contentView: UIView, bottomLine: UIView, bottomLineHeight: CGFloat) {
let views = ["contentView": contentView, "bottomLine": bottomLine]
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[bottomLine]-0-|",
options: [],
metrics: nil,
views: views))
let format = "V:|-0-[contentView]-0-[bottomLine(bottomLineHeight)]-0-|"
let metrics = ["bottomLineHeight": bottomLineHeight]
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format,
options: [],
metrics: metrics,
views: views))
self.addConstraint(NSLayoutConstraint(item: contentView,
attribute: .height,
relatedBy: .equal,
toItem: self,
attribute: .height,
multiplier: 1.0,
constant: -bottomLineHeight))
self.tabsLeadingConstraint = NSLayoutConstraint(item: contentView,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1.0,
constant: 0)
self.tabsTrailingConstraint = NSLayoutConstraint(item: contentView,
attribute: .trailing,
relatedBy: .equal,
toItem: self,
attribute: .trailing,
multiplier: 1.0,
constant: 0)
self.addConstraints([self.tabsTrailingConstraint, self.tabsLeadingConstraint])
}
fileprivate func addIndicators(toContentView contentView: UIView, withColor color: UIColor) {
let tabIndicator = UIView()
tabIndicator.translatesAutoresizingMaskIntoConstraints = false
tabIndicator.backgroundColor = color
contentView.addSubview(tabIndicator)
self.tabIndicator = tabIndicator
let format = "V:[tabIndicator(3)]-0-|"
let views = ["tabIndicator":tabIndicator]
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format,
options: [],
metrics: nil,
views: views))
self.indicatorWidthConstraint = NSLayoutConstraint(item: tabIndicator,
attribute: .width,
relatedBy: .equal,
toItem: self.tabViews.first,
attribute: .width,
multiplier: 1.0,
constant: 10.0)
self.indicatorCenterConstraint = NSLayoutConstraint(item: tabIndicator,
attribute: .centerX,
relatedBy: .equal,
toItem: self.tabViews.first,
attribute: .centerX,
multiplier: 1.0,
constant: 0.0)
contentView.addConstraints([self.indicatorWidthConstraint, self.indicatorCenterConstraint])
}
fileprivate func addTabs(fromTabViews tabViews: [UIView], toContentView contentView: UIView) {
var VFL = "H:|"
var tabViewsDict = [String:UIView]()
for index in 0 ..< tabViews.count {
let tab = tabViews[index]
tab.translatesAutoresizingMaskIntoConstraints = false
tab.isUserInteractionEnabled = true
contentView.addSubview(tab)
VFL += "-10-[T\(index)]"
tabViewsDict["T\(index)"] = tab
let tabsGapCons = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[T]-0-|",
options: [],
metrics: nil,
views: ["T":tab])
contentView.addConstraints(tabsGapCons)
let tabTapGes = UITapGestureRecognizer(target: self,
action: #selector(tabTapHandler(gestureRecognizer:)))
tab.addGestureRecognizer(tabTapGes)
}
VFL += "-10-|"
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: VFL,
options: [],
metrics: nil,
views: tabViewsDict))
}
func tabTapHandler(gestureRecognizer: UITapGestureRecognizer) {
let index = self.tabViews.index(of: gestureRecognizer.view!)!
self.tabScrollDelegate?.tabScrollView(self, didSelectTabAtIndex: index)
self.selectTab(atIndex: index)
}
fileprivate func replace(constraint oldConstraint: NSLayoutConstraint, withNewToItem itemView: UIView) -> NSLayoutConstraint {
let newConstraint = NSLayoutConstraint(item: oldConstraint.firstItem,
attribute: oldConstraint.firstAttribute,
relatedBy: oldConstraint.relation,
toItem: itemView,
attribute: oldConstraint.secondAttribute,
multiplier: oldConstraint.multiplier,
constant: oldConstraint.constant)
newConstraint.priority = oldConstraint.priority
newConstraint.shouldBeArchived = oldConstraint.shouldBeArchived
newConstraint.identifier = oldConstraint.identifier
NSLayoutConstraint.deactivate([oldConstraint])
NSLayoutConstraint.activate([newConstraint])
return newConstraint
}
fileprivate func scrollToSelectedTab() {
guard let tabIndicator = self.tabIndicator else {
return;
}
let indicatorRect = tabIndicator.convert(tabIndicator.bounds, to: self.superview)
var diff:CGFloat = 0
if indicatorRect.origin.x < 0 {
diff = indicatorRect.origin.x - 5
}else if indicatorRect.maxX > self.frame.size.width {
diff = indicatorRect.maxX - self.frame.size.width + 5
}else {
diff = 0
}
if diff != 0 {
let xOffset = self.contentOffset.x + diff
self.contentOffset = CGPoint(x: xOffset, y: self.contentOffset.y)
}
}
}
| mit | 3f7d95182996d80f4f29aa65d0f65140 | 41.694245 | 135 | 0.479737 | 6.900581 | false | false | false | false |
edx/edx-app-ios | Source/UserProfileView.swift | 1 | 10731 | //
// UserProfileView.swift
// edX
//
// Created by Akiva Leffert on 4/4/16.
// Copyright © 2016 edX. All rights reserved.
//
class UserProfileView : UIView, UIScrollViewDelegate {
private let margin = 4
private class SystemLabel: UILabel {
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines).insetBy(dx: 10, dy: 0)
}
override func drawText(in rect: CGRect) {
let newRect = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
super.drawText(in: rect.inset(by: newRect))
}
}
typealias Environment = OEXSessionProvider & OEXStylesProvider
private var environment : Environment
private let scrollView = UIScrollView()
private let usernameLabel = UILabel()
private let messageLabel = UILabel()
private let countryLabel = UILabel()
private let languageLabel = UILabel()
private let bioText = UITextView()
private let tabs = TabContainerView()
private let bioSystemMessage = SystemLabel()
private let avatarImage = ProfileImageView()
private let header = ProfileBanner()
private let bottomBackground = UIView()
init(environment: Environment, frame: CGRect) {
self.environment = environment
super.init(frame: frame)
self.addSubview(scrollView)
setupViews()
setupConstraints()
setAccessibilityIdentifiers()
}
private func setupViews() {
scrollView.backgroundColor = environment.styles.primaryBaseColor()
scrollView.delegate = self
avatarImage.borderWidth = 3.0
scrollView.addSubview(avatarImage)
usernameLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
scrollView.addSubview(usernameLabel)
messageLabel.numberOfLines = 0
messageLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
scrollView.addSubview(messageLabel)
languageLabel.accessibilityHint = Strings.Profile.languageAccessibilityHint
languageLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
scrollView.addSubview(languageLabel)
countryLabel.accessibilityHint = Strings.Profile.countryAccessibilityHint
countryLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
scrollView.addSubview(countryLabel)
bioText.backgroundColor = UIColor.clear
bioText.textAlignment = .natural
bioText.isScrollEnabled = false
bioText.isEditable = false
bioText.textContainer.lineFragmentPadding = 0;
bioText.textContainerInset = UIEdgeInsets.zero
tabs.layoutMargins = UIEdgeInsets(top: StandardHorizontalMargin, left: StandardHorizontalMargin, bottom: StandardHorizontalMargin, right: StandardHorizontalMargin)
tabs.items = [bioTab]
scrollView.addSubview(tabs)
bottomBackground.backgroundColor = bioText.backgroundColor
scrollView.insertSubview(bottomBackground, belowSubview: tabs)
bioSystemMessage.isHidden = true
bioSystemMessage.numberOfLines = 0
bioSystemMessage.backgroundColor = environment.styles.neutralXLight()
scrollView.insertSubview(bioSystemMessage, aboveSubview: tabs)
header.style = .LightContent
header.backgroundColor = scrollView.backgroundColor
header.isHidden = true
self.addSubview(header)
bottomBackground.backgroundColor = environment.styles.standardBackgroundColor()
}
private func setAccessibilityIdentifiers() {
accessibilityIdentifier = "UserProfileView:"
scrollView.accessibilityIdentifier = "UserProfileView:scroll-view"
usernameLabel.accessibilityIdentifier = "UserProfileView:username-label"
messageLabel.accessibilityIdentifier = "UserProfileView:message-label"
countryLabel.accessibilityIdentifier = "UserProfileView:country-label"
languageLabel.accessibilityIdentifier = "UserProfileView:language-label"
bioText.accessibilityIdentifier = "UserProfileView:bio-text-view"
bioSystemMessage.accessibilityIdentifier = "UserProfileView:bio-system-message-label"
header.accessibilityIdentifier = "UserProfileView:profile-header-view"
bottomBackground.accessibilityIdentifier = "UserProfileView:bottom-background-view"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupConstraints() {
scrollView.snp.makeConstraints { make in
make.edges.equalTo(self)
}
avatarImage.snp.makeConstraints { make in
make.width.equalTo(avatarImage.snp.height)
make.width.equalTo(166)
make.centerX.equalTo(scrollView)
make.top.equalTo(scrollView.snp.topMargin).offset(20)
}
usernameLabel.snp.makeConstraints { make in
make.top.equalTo(avatarImage.snp.bottom).offset(margin)
make.centerX.equalTo(scrollView)
}
messageLabel.snp.makeConstraints { make in
make.top.equalTo(usernameLabel.snp.bottom).offset(margin).priority(.high)
make.centerX.equalTo(scrollView)
}
languageLabel.snp.makeConstraints { make in
make.top.equalTo(messageLabel.snp.bottom)
make.centerX.equalTo(scrollView)
}
countryLabel.snp.makeConstraints { make in
make.top.equalTo(languageLabel.snp.bottom)
make.centerX.equalTo(scrollView)
}
tabs.snp.makeConstraints { make in
make.top.equalTo(countryLabel.snp.bottom).offset(35).priority(.high)
make.bottom.equalTo(scrollView)
make.leading.equalTo(scrollView)
make.trailing.equalTo(scrollView)
make.width.equalTo(scrollView)
}
bioSystemMessage.snp.makeConstraints { make in
make.top.equalTo(tabs)
make.bottom.greaterThanOrEqualTo(self)
make.leading.equalTo(scrollView)
make.trailing.equalTo(scrollView)
make.width.equalTo(scrollView)
}
bottomBackground.snp.makeConstraints { make in
make.edges.equalTo(bioSystemMessage)
}
header.snp.makeConstraints { make in
make.top.equalTo(scrollView)
make.leading.equalTo(scrollView)
make.trailing.equalTo(scrollView)
make.height.equalTo(56)
}
}
private func setMessage(message: String?) {
guard let message = message else {
messageLabel.text = nil
return
}
let messageStyle = OEXTextStyle(weight: .light, size: .xSmall, color: environment.styles.neutralWhiteT())
messageLabel.attributedText = messageStyle.attributedString(withText: message)
}
private func messageForProfile(profile : UserProfile, editable : Bool) -> String? {
if profile.sharingLimitedProfile {
return editable ? (profile.parentalConsent == false ? Strings.Profile.showingLimited : nil) : nil
} else {
return nil
}
}
private var bioTab : TabItem {
return TabItem(name: "About", view: bioText, identifier: "bio")
}
private func setDefaultValues() {
bioText.text = nil
countryLabel.text = nil
languageLabel.text = nil
}
func populateFields(profile: UserProfile, editable : Bool, networkManager : NetworkManager) {
let usernameStyle = OEXTextStyle(weight : .normal, size: .xxLarge, color: environment.styles.neutralWhiteT())
let infoStyle = OEXTextStyle(weight: .light, size: .xSmall, color: environment.styles.neutralWhiteT())
let bioStyle = environment.styles.textAreaBodyStyle
let messageStyle = OEXMutableTextStyle(weight: .bold, size: .large, color: environment.styles.neutralXDark())
messageStyle.alignment = .center
usernameLabel.attributedText = usernameStyle.attributedString(withText: profile.username)
bioSystemMessage.isHidden = true
avatarImage.remoteImage = profile.image(networkManager: networkManager)
setDefaultValues()
setMessage(message: messageForProfile(profile: profile, editable: editable))
if profile.sharingLimitedProfile { }
else {
if let language = profile.language {
let icon = Icon.Language.attributedTextWithStyle(style: infoStyle.withSize(.small))
let langText = infoStyle.attributedString(withText: language)
languageLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [icon, langText])
}
if let country = profile.country {
let icon = Icon.Country.attributedTextWithStyle(style: infoStyle.withSize(.small))
let countryText = infoStyle.attributedString(withText: country)
countryLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [icon, countryText])
}
if let bio = profile.bio {
bioText.attributedText = bioStyle.attributedString(withText: bio)
bioText.isAccessibilityElement = true
bioText.accessibilityLabel = Strings.Accessibility.Account.bioLabel
} else {
let message = messageStyle.attributedString(withText: Strings.Profile.noBio)
bioSystemMessage.attributedText = message
bioSystemMessage.isHidden = false
let accessibilityLabelText = "\(Strings.Accessibility.Account.bioLabel), \(Strings.Profile.noBio)"
bioSystemMessage.accessibilityLabel = accessibilityLabelText
bioSystemMessage.isAccessibilityElement = true
bioText.isAccessibilityElement = false
}
}
header.showProfile(profile: profile, networkManager: networkManager)
}
var extraTabs : [ProfileTabItem] = [] {
didSet {
let instantiatedTabs = extraTabs.map {tab in tab(scrollView) }
tabs.items = [bioTab] + instantiatedTabs
}
}
@objc func scrollViewDidScroll(_ scrollView: UIScrollView) {
UIView.animate(withDuration: 0.25) {
self.header.isHidden = scrollView.contentOffset.y < self.avatarImage.frame.maxY
}
}
func chooseTab(identifier: String) {
tabs.showTab(withIdentifier: identifier)
}
}
| apache-2.0 | 9516cc1d3835c75579427d1860a1b40f | 39.798479 | 171 | 0.673812 | 5.27532 | false | false | false | false |
atl009/WordPress-iOS | WordPress/Classes/ViewRelated/Aztec/Helpers/AztecVerificationPromptHelper.swift | 1 | 4435 | import UIKit
class AztecVerificationPromptHelper: NSObject {
private let accountService: AccountService
private let wpComAccount: WPAccount
private weak var displayedAlert: FancyAlertViewController?
private var completionBlock: AztecVerificationPromptCompletion?
typealias AztecVerificationPromptCompletion = (Bool) -> ()
init?(account: WPAccount?) {
guard let passedAccount = account,
let managedObjectContext = account?.managedObjectContext else {
return nil
}
accountService = AccountService(managedObjectContext: managedObjectContext)
guard accountService.isDefaultWordPressComAccount(passedAccount),
!passedAccount.emailVerified.boolValue else {
// if the post the user is trying to compose isn't on a WP.com account,
// or they're already verified, then the verification prompt is irrelevant.
return nil
}
wpComAccount = passedAccount
super.init()
NotificationCenter.default.addObserver(self,
selector: #selector(updateVerificationStatus),
name: .UIApplicationDidBecomeActive,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func neeedsVerification(before action: PostEditorAction) -> Bool {
guard action == .publish else {
return false
}
return !wpComAccount.emailVerified.boolValue
}
/// - parameter presentingViewController: UIViewController that the prompt should be presented from.
/// - parameter then: Completion callback to be called after the user dismisses the prompt.
/// **Note**: The callback fires only when the user tapped "OK" or we silently verified the account in background. It isn't fired when user attempts to resend the verification email.
func displayVerificationPrompt(from presentingViewController: UIViewController,
then: AztecVerificationPromptCompletion?) {
let fancyAlert = FancyAlertViewController.verificationPromptController { [weak self] in
then?(self?.wpComAccount.emailVerified.boolValue ?? false)
}
fancyAlert.modalPresentationStyle = .custom
fancyAlert.transitioningDelegate = self
presentingViewController.present(fancyAlert, animated: true)
updateVerificationStatus()
// Silently kick off the request to make sure the user still actually needs to be verified.
// If in the meantime user has been verified, we'll dismiss the prompt,
// call the completion block and let caller handle the new situation.
displayedAlert = fancyAlert
completionBlock = then
}
func updateVerificationStatus() {
accountService.updateUserDetails(for: wpComAccount,
success: { [weak self] in
// Let's make sure the alert is still on the screen and
// the verification status has changed, before we call the callback.
guard let displayedAlert = self?.displayedAlert,
let updatedAccount = self?.accountService.defaultWordPressComAccount(),
updatedAccount.emailVerified.boolValue else {
return
}
displayedAlert.dismiss(animated: true, completion: nil)
self?.completionBlock?(updatedAccount.emailVerified.boolValue)
}, failure: nil)
}
}
// MARK: - UIViewControllerTransitioningDelegate
//
extension AztecVerificationPromptHelper: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
guard presented is FancyAlertViewController else {
return nil
}
return FancyAlertPresentationController(presentedViewController: presented, presenting: presenting)
}
}
| gpl-2.0 | 42d143b5ce506397881a046be2404bf3 | 42.480392 | 186 | 0.619166 | 6.580119 | false | false | false | false |
belatrix/iOSAllStarsRemake | AllStars/AllStars/iPhone/Classes/Activity/Logic/ActivityBC.swift | 1 | 2986 | //
// ActivityBC.swift
// AllStars
//
// Created by Ricardo Hernan Herrera Valle on 7/25/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import Foundation
struct ActivityBC {
func listActivities(withCompletion completion : (arrayActivities : [Activity]?, nextPage : String?) -> Void) {
let objUser = LogInBC.getCurrenteUserSession()
if let userID = objUser?.user_pk,
let token = objUser?.user_token {
OSPWebModel.listActivities(userID.stringValue, withToken: token) { (arrayActivities, nextPage, errorResponse, successful) in
if (arrayActivities != nil) {
completion(arrayActivities: arrayActivities!, nextPage: nextPage)
} else if (errorResponse != nil) {
OSPUserAlerts.showSimpleAlert("generic_title_problem".localized, withMessage: errorResponse!.message!, withAcceptButton: "ok".localized)
completion(arrayActivities: [Activity](), nextPage: nil)
} else {
OSPUserAlerts.showSimpleAlert("generic_title_problem".localized, withMessage: "server_error".localized, withAcceptButton: "ok".localized)
completion(arrayActivities: [Activity](), nextPage: nil)
}
}
} else {
OSPUserAlerts.showSimpleAlert("app_name".localized, withMessage: "token_invalid".localized, withAcceptButton: "ok".localized)
completion(arrayActivities: [Activity](), nextPage: nil)
}
}
func listActivitiesToPage(page : String, withCompletion completion : (arrayActivities : [Activity]?, nextPage : String?) -> Void) {
let objUser = LogInBC.getCurrenteUserSession()
if let token = objUser?.user_token {
OSPWebModel.listActivitiesToPage(page, withToken: token) { (arrayActivities, nextPage, errorResponse, successful) in
if (arrayActivities != nil) {
completion(arrayActivities: arrayActivities!, nextPage: nextPage)
} else if (errorResponse != nil) {
OSPUserAlerts.showSimpleAlert("generic_title_problem".localized, withMessage: errorResponse!.message!, withAcceptButton: "ok".localized)
completion(arrayActivities: [Activity](), nextPage: nil)
} else {
OSPUserAlerts.showSimpleAlert("generic_title_problem".localized, withMessage: "server_error".localized, withAcceptButton: "ok".localized)
completion(arrayActivities: [Activity](), nextPage: nil)
}
}
} else {
OSPUserAlerts.showSimpleAlert("app_name".localized, withMessage: "token_invalid".localized, withAcceptButton: "ok".localized)
completion(arrayActivities: [Activity](), nextPage: nil)
}
}
} | mit | 6c43d70e2d7002468ddfc5976b18d9f5 | 46.396825 | 157 | 0.60603 | 5.067912 | false | false | false | false |
Dimillian/HackerSwifter | Hacker Swifter/Hacker Swifter/Models/Comment.swift | 1 | 6542 | //
// Comment.swift
// HackerSwifter
//
// Created by Tosin Afolabi on 17/07/2014.
// Copyright (c) 2014 Thomas Ricouard. All rights reserved.
//
import Foundation
@objc public class Comment: NSObject, NSCoding {
public var type: CommentFilter?
public var text: String?
public var username: String?
public var depth: Int = 0
public var commentId: String?
public var parentId: String?
public var prettyTime: String?
public var links: [NSURL]?
public var replyURLString: String?
public var upvoteURLAddition: String?
public var downvoteURLAddition: String?
public enum CommentFilter: String {
case Default = "default"
case Ask = "ask"
case Jobs = "jobs"
}
internal enum serialization: String {
case text = "text"
case username = "username"
case depth = "depth"
case commentId = "commentId"
case parentId = "parentId"
case prettyTime = "prettyTime"
case links = "links"
case replyURLString = "replyURLString"
case upvoteURLAddition = "upvoteURLAddition"
case downvoteURLAddition = "downvoteURLAddition"
static let values = [text, username, depth, commentId, parentId, prettyTime, links,
replyURLString, upvoteURLAddition, downvoteURLAddition]
}
public override init(){
super.init()
}
public init(html: String, type: Post.PostFilter) {
super.init()
self.parseHTML(html, withType: type)
}
public required init?(coder aDecoder: NSCoder) {
super.init()
for key in serialization.values {
setValue(aDecoder.decodeObjectForKey(key.rawValue), forKey: key.rawValue)
}
}
public func encodeWithCoder(aCoder: NSCoder) {
for key in serialization.values {
if let value: AnyObject = self.valueForKey(key.rawValue) {
aCoder.encodeObject(value, forKey: key.rawValue)
}
}
}
}
//MARK: Equatable implementation
public func ==(larg: Comment, rarg: Comment) -> Bool {
return larg.commentId == rarg.commentId
}
//MARK: Network
public extension Comment {
typealias Response = (comments: [Comment]!, error: Fetcher.ResponseError!, local: Bool) -> Void
public class func fetch(forPost post: Post, completion: Response) {
let ressource = "item?id=" + post.postId!
Fetcher.Fetch(ressource,
parsing: {(html) in
var type = post.type
if type == nil {
type = Post.PostFilter.Default
}
if let realHtml = html {
let comments = self.parseCollectionHTML(realHtml, withType: type!)
return comments
}
else {
return nil
}
},
completion: {(object, error, local) in
if let realObject: AnyObject = object {
completion(comments: realObject as! [Comment], error: error, local: local)
}
else {
completion(comments: nil, error: error, local: local)
}
})
}
}
//MARK: HTML
internal extension Comment {
internal class func parseCollectionHTML(html: String, withType type: Post.PostFilter) -> [Comment] {
var components = html.componentsSeparatedByString("<tr><td class='ind'><img src=\"s.gif\"")
var comments: [Comment] = []
if (components.count > 0) {
if (type == Post.PostFilter.Ask) {
let scanner = NSScanner(string: components[0])
let comment = Comment()
comment.type = CommentFilter.Ask
comment.commentId = scanner.scanTag("<span id=\"score_", endTag: ">")
comment.username = scanner.scanTag("by <a href=\"user?id=", endTag: "\">")
comment.prettyTime = scanner.scanTag("</a> ", endTag: "ago") + "ago"
comment.text = String.stringByRemovingHTMLEntities(scanner.scanTag("</tr><tr><td></td><td>", endTag: "</td>"))
comment.depth = 0
comments.append(comment)
}
else if (type == Post.PostFilter.Jobs) {
let scanner = NSScanner(string: components[0])
let comment = Comment()
comment.depth = 0
comment.text = String.stringByRemovingHTMLEntities(scanner.scanTag("</tr><tr><td></td><td>", endTag: "</td>"))
comment.type = CommentFilter.Jobs
comments.append(comment)
}
var index = 0
for component in components {
if index != 0 && index != components.count - 1 {
comments.append(Comment(html: component, type: type))
}
index++
}
}
return comments
}
internal func parseHTML(html: String, withType type: Post.PostFilter) {
let scanner = NSScanner(string: html)
let level = scanner.scanTag("height=\"1\" width=\"", endTag: ">")
if let unwrappedLevel = Int(level.substringToIndex(level.startIndex.advancedBy(level.characters.count - 1))) {
self.depth = unwrappedLevel / 40
} else {
self.depth = 0
}
let username = scanner.scanTag("<a href=\"user?id=", endTag: "\">")
self.username = username.utf16.count > 0 ? username : "[deleted]"
self.commentId = scanner.scanTag("<a href=\"item?id=", endTag: "\">")
self.prettyTime = scanner.scanTag(">", endTag: "</a>")
if (html.rangeOfString("[deleted]")?.startIndex != nil) {
self.text = "[deleted]"
} else {
let textTemp = scanner.scanTag("<font color=", endTag: "</font>") as String
if (textTemp.characters.count>0) {
self.text = String.stringByRemovingHTMLEntities(textTemp.substringFromIndex(textTemp.startIndex.advancedBy(10)))
}
else {
self.text = ""
}
}
//LOL, it whould always work, as I strip a Hex color, which is always the same length
self.replyURLString = scanner.scanTag("<font size=1><u><a href=\"", endTag: "\">reply")
self.type = CommentFilter.Default
}
}
| mit | 1ebc2520221794cdfef77c34419ebf33 | 34.172043 | 128 | 0.55243 | 4.623322 | false | false | false | false |
agrippa1994/iOS-PLC | Pods/Charts/Charts/Classes/Charts/ChartViewBase.swift | 4 | 34839 | //
// ChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
// Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880
import Foundation
import UIKit
@objc
public protocol ChartViewDelegate
{
/// Called when a value has been selected inside the chart.
/// - parameter entry: The selected Entry.
/// - parameter dataSetIndex: The index in the datasets array of the data object the Entrys DataSet is in.
optional func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight)
// Called when nothing has been selected or an "un-select" has been made.
optional func chartValueNothingSelected(chartView: ChartViewBase)
// Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
optional func chartScaled(chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat)
// Callbacks when the chart is moved / translated via drag gesture.
optional func chartTranslated(chartView: ChartViewBase, dX: CGFloat, dY: CGFloat)
}
public class ChartViewBase: UIView, ChartAnimatorDelegate
{
// MARK: - Properties
/// custom formatter that is used instead of the auto-formatter if set
internal var _valueFormatter = NSNumberFormatter()
/// the default value formatter
internal var _defaultValueFormatter = NSNumberFormatter()
/// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied
internal var _data: ChartData!
/// If set to true, chart continues to scroll after touch up
public var dragDecelerationEnabled = true
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
private var _dragDecelerationFrictionCoef: CGFloat = 0.9
/// font object used for drawing the description text in the bottom right corner of the chart
public var descriptionFont: UIFont? = UIFont(name: "HelveticaNeue", size: 9.0)
public var descriptionTextColor: UIColor! = UIColor.blackColor()
/// font object for drawing the information text when there are no values in the chart
public var infoFont: UIFont! = UIFont(name: "HelveticaNeue", size: 12.0)
public var infoTextColor: UIColor! = UIColor(red: 247.0/255.0, green: 189.0/255.0, blue: 51.0/255.0, alpha: 1.0) // orange
/// description text that appears in the bottom right corner of the chart
public var descriptionText = "Description"
/// flag that indicates if the chart has been fed with data yet
internal var _dataNotSet = true
/// if true, units are drawn next to the values in the chart
internal var _drawUnitInChart = false
/// the number of x-values the chart displays
internal var _deltaX = CGFloat(1.0)
internal var _chartXMin = Double(0.0)
internal var _chartXMax = Double(0.0)
/// the legend object containing all data associated with the legend
internal var _legend: ChartLegend!
/// delegate to receive chart events
public weak var delegate: ChartViewDelegate?
/// text that is displayed when the chart is empty
public var noDataText = "No chart data available."
/// text that is displayed when the chart is empty that describes why the chart is empty
public var noDataTextDescription: String?
internal var _legendRenderer: ChartLegendRenderer!
/// object responsible for rendering the data
public var renderer: ChartDataRendererBase?
internal var _highlighter: ChartHighlighter?
/// object that manages the bounds and drawing constraints of the chart
internal var _viewPortHandler: ChartViewPortHandler!
/// object responsible for animations
internal var _animator: ChartAnimator!
/// flag that indicates if offsets calculation has already been done or not
private var _offsetsCalculated = false
/// array of Highlight objects that reference the highlighted slices in the chart
internal var _indicesToHightlight = [ChartHighlight]()
/// if set to true, the marker is drawn when a value is clicked
public var drawMarkers = true
/// the view that represents the marker
public var marker: ChartMarker?
private var _interceptTouchEvents = false
/// An extra offset to be appended to the viewport's top
public var extraTopOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's right
public var extraRightOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's bottom
public var extraBottomOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's left
public var extraLeftOffset: CGFloat = 0.0
public func setExtraOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
extraLeftOffset = left
extraTopOffset = top
extraRightOffset = right
extraBottomOffset = bottom
}
// MARK: - Initializers
public override init(frame: CGRect)
{
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
initialize()
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initialize()
}
deinit
{
self.removeObserver(self, forKeyPath: "bounds")
self.removeObserver(self, forKeyPath: "frame")
}
internal func initialize()
{
_animator = ChartAnimator()
_animator.delegate = self
_viewPortHandler = ChartViewPortHandler()
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
_legend = ChartLegend()
_legendRenderer = ChartLegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend)
_defaultValueFormatter.minimumIntegerDigits = 1
_defaultValueFormatter.maximumFractionDigits = 1
_defaultValueFormatter.minimumFractionDigits = 1
_defaultValueFormatter.usesGroupingSeparator = true
_valueFormatter = _defaultValueFormatter.copy() as! NSNumberFormatter
self.addObserver(self, forKeyPath: "bounds", options: .New, context: nil)
self.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
}
// MARK: - ChartViewBase
/// The data for the chart
public var data: ChartData?
{
get
{
return _data
}
set
{
if (newValue == nil || newValue?.yValCount == 0)
{
print("Charts: data argument is nil on setData()", terminator: "\n")
return
}
_dataNotSet = false
_offsetsCalculated = false
_data = newValue
// calculate how many digits are needed
calculateFormatter(min: _data.getYMin(), max: _data.getYMax())
notifyDataSetChanged()
}
}
/// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()).
public func clear()
{
_data = nil
_dataNotSet = true
setNeedsDisplay()
}
/// Removes all DataSets (and thereby Entries) from the chart. Does not remove the x-values. Also refreshes the chart by calling setNeedsDisplay().
public func clearValues()
{
if (_data !== nil)
{
_data.clearValues()
}
setNeedsDisplay()
}
/// - returns: true if the chart is empty (meaning it's data object is either null or contains no entries).
public func isEmpty() -> Bool
{
if (_data == nil)
{
return true
}
else
{
if (_data.yValCount <= 0)
{
return true
}
else
{
return false
}
}
}
/// Lets the chart know its underlying data has changed and should perform all necessary recalculations.
public func notifyDataSetChanged()
{
fatalError("notifyDataSetChanged() cannot be called on ChartViewBase")
}
/// calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position
internal func calculateOffsets()
{
fatalError("calculateOffsets() cannot be called on ChartViewBase")
}
/// calcualtes the y-min and y-max value and the y-delta and x-delta value
internal func calcMinMax()
{
fatalError("calcMinMax() cannot be called on ChartViewBase")
}
/// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter
internal func calculateFormatter(min min: Double, max: Double)
{
// check if a custom formatter is set or not
var reference = Double(0.0)
if (_data == nil || _data.xValCount < 2)
{
let absMin = fabs(min)
let absMax = fabs(max)
reference = absMin > absMax ? absMin : absMax
}
else
{
reference = fabs(max - min)
}
let digits = ChartUtils.decimals(reference)
_defaultValueFormatter.maximumFractionDigits = digits
_defaultValueFormatter.minimumFractionDigits = digits
}
public override func drawRect(rect: CGRect)
{
let context = UIGraphicsGetCurrentContext()
let frame = self.bounds
if (_dataNotSet || _data === nil || _data.yValCount == 0)
{ // check if there is data
CGContextSaveGState(context)
// if no data, inform the user
ChartUtils.drawText(context: context, text: noDataText, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor])
if (noDataTextDescription != nil && (noDataTextDescription!).characters.count > 0)
{
let textOffset = -infoFont.lineHeight / 2.0
ChartUtils.drawText(context: context, text: noDataTextDescription!, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0 + textOffset), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor])
}
return
}
if (!_offsetsCalculated)
{
calculateOffsets()
_offsetsCalculated = true
}
}
/// draws the description text in the bottom right corner of the chart
internal func drawDescription(context context: CGContext?)
{
if (descriptionText.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) == 0)
{
return
}
let frame = self.bounds
var attrs = [String : AnyObject]()
var font = descriptionFont
if (font == nil)
{
font = UIFont.systemFontOfSize(UIFont.systemFontSize())
}
attrs[NSFontAttributeName] = font
attrs[NSForegroundColorAttributeName] = descriptionTextColor
ChartUtils.drawText(context: context, text: descriptionText, point: CGPoint(x: frame.width - _viewPortHandler.offsetRight - 10.0, y: frame.height - _viewPortHandler.offsetBottom - 10.0 - font!.lineHeight), align: .Right, attributes: attrs)
}
// MARK: - Highlighting
/// - returns: the array of currently highlighted values. This might be null or empty if nothing is highlighted.
public var highlighted: [ChartHighlight]
{
return _indicesToHightlight
}
/// Checks if the highlight array is null, has a length of zero or if the first object is null.
/// - returns: true if there are values to highlight, false if there are no values to highlight.
public func valuesToHighlight() -> Bool
{
return _indicesToHightlight.count > 0
}
/// Highlights the values at the given indices in the given DataSets. Provide
/// null or an empty array to undo all highlighting.
/// This should be used to programmatically highlight values.
/// This DOES NOT generate a callback to the delegate.
public func highlightValues(highs: [ChartHighlight]?)
{
// set the indices to highlight
_indicesToHightlight = highs ?? [ChartHighlight]()
if (_indicesToHightlight.isEmpty)
{
self.lastHighlighted = nil
}
// redraw the chart
setNeedsDisplay()
}
/// Highlights the value at the given x-index in the given DataSet.
/// Provide -1 as the x-index to undo all highlighting.
public func highlightValue(xIndex xIndex: Int, dataSetIndex: Int, callDelegate: Bool)
{
if (xIndex < 0 || dataSetIndex < 0 || xIndex >= _data.xValCount || dataSetIndex >= _data.dataSetCount)
{
highlightValue(highlight: nil, callDelegate: callDelegate)
}
else
{
highlightValue(highlight: ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex), callDelegate: callDelegate)
}
}
/// Highlights the value selected by touch gesture.
public func highlightValue(highlight highlight: ChartHighlight?, callDelegate: Bool)
{
var entry: ChartDataEntry?
var h = highlight
if (h == nil)
{
_indicesToHightlight.removeAll(keepCapacity: false)
}
else
{
// set the indices to highlight
entry = _data.getEntryForHighlight(h!)
if (entry === nil || entry!.xIndex != h?.xIndex)
{
h = nil
entry = nil
_indicesToHightlight.removeAll(keepCapacity: false)
}
else
{
_indicesToHightlight = [h!]
}
}
// redraw the chart
setNeedsDisplay()
if (callDelegate && delegate != nil)
{
if (h == nil)
{
delegate!.chartValueNothingSelected?(self)
}
else
{
// notify the listener
delegate!.chartValueSelected?(self, entry: entry!, dataSetIndex: h!.dataSetIndex, highlight: h!)
}
}
}
/// The last value that was highlighted via touch.
public var lastHighlighted: ChartHighlight?
// MARK: - Markers
/// draws all MarkerViews on the highlighted positions
internal func drawMarkers(context context: CGContext?)
{
// if there is no marker view or drawing marker is disabled
if (marker === nil || !drawMarkers || !valuesToHighlight())
{
return
}
for (var i = 0, count = _indicesToHightlight.count; i < count; i++)
{
let highlight = _indicesToHightlight[i]
let xIndex = highlight.xIndex
if (xIndex <= Int(_deltaX) && xIndex <= Int(_deltaX * _animator.phaseX))
{
let e = _data.getEntryForHighlight(highlight)
if (e === nil || e!.xIndex != highlight.xIndex)
{
continue
}
let pos = getMarkerPosition(entry: e!, highlight: highlight)
// check bounds
if (!_viewPortHandler.isInBounds(x: pos.x, y: pos.y))
{
continue
}
// callbacks to update the content
marker!.refreshContent(entry: e!, highlight: highlight)
let markerSize = marker!.size
if (pos.y - markerSize.height <= 0.0)
{
let y = markerSize.height - pos.y
marker!.draw(context: context, point: CGPoint(x: pos.x, y: pos.y + y))
}
else
{
marker!.draw(context: context, point: pos)
}
}
}
}
/// - returns: the actual position in pixels of the MarkerView for the given Entry in the given DataSet.
public func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
fatalError("getMarkerPosition() cannot be called on ChartViewBase")
}
// MARK: - Animation
/// - returns: the animator responsible for animating chart values.
public var animator: ChartAnimator!
{
return _animator
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingX: an easing function for the animation on the x axis
/// - parameter easingY: an easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOptionX: the easing function for the animation on the x axis
/// - parameter easingOptionY: the easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(yAxisDuration yAxisDuration: NSTimeInterval)
{
_animator.animate(yAxisDuration: yAxisDuration)
}
// MARK: - Accessors
/// - returns: the total value (sum) of all y-values across all DataSets
public var yValueSum: Double
{
return _data.yValueSum
}
/// - returns: the current y-max value across all DataSets
public var chartYMax: Double
{
return _data.yMax
}
/// - returns: the current y-min value across all DataSets
public var chartYMin: Double
{
return _data.yMin
}
public var chartXMax: Double
{
return _chartXMax
}
public var chartXMin: Double
{
return _chartXMin
}
/// - returns: the average value of all values the chart holds
public func getAverage() -> Double
{
return yValueSum / Double(_data.yValCount)
}
/// - returns: the average value for a specific DataSet (with a specific label) in the chart
public func getAverage(dataSetLabel dataSetLabel: String) -> Double
{
let ds = _data.getDataSetByLabel(dataSetLabel, ignorecase: true)
if (ds == nil)
{
return 0.0
}
return ds!.yValueSum / Double(ds!.entryCount)
}
/// - returns: the total number of values the chart holds (across all DataSets)
public var getValueCount: Int
{
return _data.yValCount
}
/// *Note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)*
/// - returns: the center point of the chart (the whole View) in pixels.
public var midPoint: CGPoint
{
let bounds = self.bounds
return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0)
}
/// - returns: the center of the chart taking offsets under consideration. (returns the center of the content rectangle)
public var centerOffsets: CGPoint
{
return _viewPortHandler.contentCenter
}
/// - returns: the Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend.
public var legend: ChartLegend
{
return _legend
}
/// - returns: the renderer object responsible for rendering / drawing the Legend.
public var legendRenderer: ChartLegendRenderer!
{
return _legendRenderer
}
/// - returns: the rectangle that defines the borders of the chart-value surface (into which the actual values are drawn).
public var contentRect: CGRect
{
return _viewPortHandler.contentRect
}
/// Sets the formatter to be used for drawing the values inside the chart.
/// If no formatter is set, the chart will automatically determine a reasonable
/// formatting (concerning decimals) for all the values that are drawn inside
/// the chart. Set this to nil to re-enable auto formatting.
public var valueFormatter: NSNumberFormatter!
{
get
{
return _valueFormatter
}
set
{
if (newValue === nil)
{
_valueFormatter = _defaultValueFormatter.copy() as! NSNumberFormatter
}
else
{
_valueFormatter = newValue
}
}
}
/// - returns: the x-value at the given index
public func getXValue(index: Int) -> String!
{
if (_data == nil || _data.xValCount <= index)
{
return nil
}
else
{
return _data.xVals[index]
}
}
/// Get all Entry objects at the given index across all DataSets.
public func getEntriesAtIndex(xIndex: Int) -> [ChartDataEntry]
{
var vals = [ChartDataEntry]()
for (var i = 0, count = _data.dataSetCount; i < count; i++)
{
let set = _data.getDataSetByIndex(i)
let e = set.entryForXIndex(xIndex)
if (e !== nil)
{
vals.append(e!)
}
}
return vals
}
/// - returns: the percentage the given value has of the total y-value sum
public func percentOfTotal(val: Double) -> Double
{
return val / _data.yValueSum * 100.0
}
/// - returns: the ViewPortHandler of the chart that is responsible for the
/// content area of the chart and its offsets and dimensions.
public var viewPortHandler: ChartViewPortHandler!
{
return _viewPortHandler
}
/// - returns: the bitmap that represents the chart.
public func getChartImage(transparent transparent: Bool) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque || !transparent, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size)
if (opaque || !transparent)
{
// Background color may be partially transparent, we must fill with white if we want to output an opaque image
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillRect(context, rect)
if (self.backgroundColor !== nil)
{
CGContextSetFillColorWithColor(context, self.backgroundColor?.CGColor)
CGContextFillRect(context, rect)
}
}
layer.renderInOptionalContext(context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public enum ImageFormat
{
case JPEG
case PNG
}
/// Saves the current chart state with the given name to the given path on
/// the sdcard leaving the path empty "" will put the saved file directly on
/// the SD card chart is saved as a PNG image, example:
/// saveToPath("myfilename", "foldername1/foldername2")
///
/// - parameter filePath: path to the image to save
/// - parameter format: the format to save
/// - parameter compressionQuality: compression quality for lossless formats (JPEG)
///
/// - returns: true if the image was saved successfully
public func saveToPath(path: String, format: ImageFormat, compressionQuality: Double) -> Bool
{
let image = getChartImage(transparent: format != .JPEG)
var imageData: NSData!
switch (format)
{
case .PNG:
imageData = UIImagePNGRepresentation(image)
break
case .JPEG:
imageData = UIImageJPEGRepresentation(image, CGFloat(compressionQuality))
break
}
return imageData.writeToFile(path, atomically: true)
}
/// Saves the current state of the chart to the camera roll
public func saveToCameraRoll()
{
UIImageWriteToSavedPhotosAlbum(getChartImage(transparent: false), nil, nil, nil)
}
internal typealias VoidClosureType = () -> ()
internal var _sizeChangeEventActions = [VoidClosureType]()
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
{
if (keyPath == "bounds" || keyPath == "frame")
{
let bounds = self.bounds
if (_viewPortHandler !== nil &&
(bounds.size.width != _viewPortHandler.chartWidth ||
bounds.size.height != _viewPortHandler.chartHeight))
{
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
// Finish any pending viewport changes
while (!_sizeChangeEventActions.isEmpty)
{
_sizeChangeEventActions.removeAtIndex(0)()
}
notifyDataSetChanged()
}
}
}
public func clearPendingViewPortChanges()
{
_sizeChangeEventActions.removeAll(keepCapacity: false)
}
/// if true, value highlighting is enabled
public var highlightEnabled: Bool
{
get
{
return _data === nil ? true : _data.highlightEnabled
}
set
{
if (_data !== nil)
{
_data.highlightEnabled = newValue
}
}
}
/// if true, value highlightning is enabled
public var isHighlightEnabled: Bool { return highlightEnabled }
/// **default**: true
/// - returns: true if chart continues to scroll after touch up, false if not.
public var isDragDecelerationEnabled: Bool
{
return dragDecelerationEnabled
}
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
///
/// **default**: true
public var dragDecelerationFrictionCoef: CGFloat
{
get
{
return _dragDecelerationFrictionCoef
}
set
{
var val = newValue
if (val < 0.0)
{
val = 0.0
}
if (val >= 1.0)
{
val = 0.999
}
_dragDecelerationFrictionCoef = val
}
}
// MARK: - ChartAnimatorDelegate
public func chartAnimatorUpdated(chartAnimator: ChartAnimator)
{
setNeedsDisplay()
}
public func chartAnimatorStopped(chartAnimator: ChartAnimator)
{
}
// MARK: - Touches
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesBegan(touches, withEvent: event)
}
}
public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesMoved(touches, withEvent: event)
}
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesEnded(touches, withEvent: event)
}
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesCancelled(touches, withEvent: event)
}
}
} | mit | b767ef5b7a53e5765478f20d84ae9ba3 | 35.405434 | 265 | 0.623267 | 5.346685 | false | false | false | false |
google/iosched-ios | Source/IOsched/Screens/Schedule/ScheduleViewController.swift | 1 | 16598 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import AlamofireImage
import Firebase
import Foundation
import GoogleSignIn
import MaterialComponents
class ScheduleViewController: BaseCollectionViewController {
fileprivate enum TooltipsConstants {
static let titleColor = "#424242"
}
private let agendaDataSource = AgendaDataSource()
private lazy var filterBar: FilterBar = self.setupFilterBar()
private lazy var filterButton: MDCFloatingButton = self.setupFilterFloatingButton()
private lazy var switchBarButton: MDCFlatButton = MDCFlatButton()
private var showBookmarkedAndReserved: Bool = false
private lazy var tabBar: MDCTabBar = self.setupTabBar()
private lazy var emptyMyIOView = ScheduleCollectionEmptyView()
var selectedTabIndex = 0 {
didSet {
scheduleViewModel.collectionView(collectionView, scrollToDay: selectedTabIndex)
updateBackgroundView()
logSelectedDay()
}
}
func selectDay(day: Int) {
if day < tabBar.items.count {
tabBar.selectedItem = tabBar.items[day]
selectedTabIndex = day
}
}
let scheduleViewModel: ScheduleDisplayableViewModel
init(viewModel: ScheduleDisplayableViewModel,
searchViewController: SearchCollectionViewController) {
self.scheduleViewModel = viewModel
self.searchViewController = searchViewController
let layout = SideHeaderCollectionViewLayout()
layout.headerReferenceSize = CGSize(width: 60, height: 8)
layout.estimatedItemSize = CGSize(width: UIScreen.main.bounds.size.width, height: 120)
super.init(collectionViewLayout: SideHeaderCollectionViewLayout())
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .white
collectionView?.dataSource = scheduleViewModel
registerForViewUpdates()
registerForDynamicTypeUpdates()
refreshContent()
collectionView.showsVerticalScrollIndicator = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
logSelectedDay()
}
func registerForViewUpdates() {
scheduleViewModel.onUpdate { [weak self] indexPath in
self?.performViewUpdate(indexPath: indexPath)
}
}
func performViewUpdate(indexPath: IndexPath?) {
if indexPath != nil {
self.collectionView?.reloadData()
}
else {
self.refreshUI()
}
}
private func updateTabBarItems() {
let items = scheduleViewModel.conferenceDays.map {
UITabBarItem(title: $0.dayString, image: nil, tag: 0)
}
tabBar.items = items
}
func refreshUI() {
var selectedIndex = 0
if let selectedItem = tabBar.selectedItem {
selectedIndex = tabBar.items.index(of: selectedItem) ?? 0
}
if scheduleViewModel.conferenceDays.count > 0 {
updateTabBarItems()
tabBar.selectedItem = tabBar.items[selectedIndex]
}
updateBackgroundView()
self.collectionView?.reloadData()
if let filterString = scheduleViewModel.wrappedModel.filterViewModel.filterString {
filterBar.isFilterVisible = true
filterBar.filterText = filterString
} else {
filterBar.isFilterVisible = false
}
// Update header bar height, in case filters have changed.
let headerView = appBar.headerView
headerView.minimumHeight = minHeaderHeight
headerView.maximumHeight = maxHeaderHeight
appBar.headerStackView.setNeedsLayout()
}
private func updateBackgroundView() {
if scheduleViewModel.wrappedModel.shouldShowOnlySavedItems &&
scheduleViewModel.isEmpty() {
collectionView?.backgroundView = emptyMyIOView.configureForMyIO()
} else if scheduleViewModel.wrappedModel.filterViewModel.filterString != nil &&
scheduleViewModel.isEmpty() {
collectionView?.backgroundView = emptyMyIOView.configureForEmptyFilter()
} else {
collectionView?.backgroundView = nil
}
}
// MARK: - View setup
fileprivate enum Constants {
static let filterButtonTitle = NSLocalizedString("Filter", comment: "Title for filter button")
static let title = NSLocalizedString("Schedule", comment: "Title for schedule page")
static let myIOToggleAccessibilityLabelOff =
NSLocalizedString("Show only your events", comment: "Accessibility label for my IO toggle")
static let myIOToggleAccessibilityLabelOn =
NSLocalizedString("Show all events", comment: "Accessibility label for my IO toggle")
static let headerFilterHeight: CGFloat = 56
static let bottomButtonOffset: CGFloat = 17.0
static let headerForegroundColor: UIColor = MDCPalette.grey.tint800
}
@objc override var minHeaderHeight: CGFloat {
return super.minHeaderHeight + (filterBar.isFilterVisible ? Constants.headerFilterHeight : 0)
}
@objc override var maxHeaderHeight: CGFloat {
return super.maxHeaderHeight
}
@objc override func setupViews() {
super.setupViews()
self.title = Constants.title
self.setupCollectionView()
self.setupNavigationBarActions()
view.addSubview(filterButton)
setupConstraints()
// 3D touch
setup3DTouch()
}
func setupConstraints() {
filterButton.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor,
constant: -(Constants.bottomButtonOffset)).isActive = true
filterButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor,
constant: -(Constants.bottomButtonOffset)).isActive = true
}
func setupNavigationBarActions() {
navigationItem.leftBarButtonItem = setupSwitchBarButton()
navigationItem.rightBarButtonItem = setupSearchButton()
}
@objc override func setupAppBar() -> MDCAppBarViewController {
let appBar = super.setupAppBar()
appBar.headerStackView.topBar = nil
let stack = HeaderStack()
stack.add(view: appBar.navigationBar)
stack.add(view: tabBar)
stack.add(view: filterBar)
appBar.headerStackView.bottomBar = stack
appBar.headerStackView.setNeedsLayout()
// Update header bar height.
let headerView = appBar.headerView
headerView.minimumHeight = minHeaderHeight
headerView.maximumHeight = maxHeaderHeight
return appBar
}
func setupTabBar() -> MDCTabBar {
let tabBar = MDCTabBar()
tabBar.alignment = .justified
tabBar.tintColor = tabBarTintColor
tabBar.selectedItemTintColor = UIColor(hex: TooltipsConstants.titleColor)
tabBar.unselectedItemTintColor = headerForegroundColor
tabBar.itemAppearance = .titles
tabBar.titleTextTransform = .none
tabBar.delegate = self
return tabBar
}
func setupFilterBar() -> FilterBar {
let filterBar = FilterBar(frame: .zero, viewModel: scheduleViewModel.wrappedModel)
return filterBar
}
func setupFilterFloatingButton() -> MDCFloatingButton {
filterButton = MDCFloatingButton()
filterButton.translatesAutoresizingMaskIntoConstraints = false
filterButton.addTarget(self, action: #selector(filterAction), for: .touchUpInside)
filterButton.backgroundColor = UIColor(red: 26 / 255, green: 115 / 255, blue: 232 / 255, alpha: 1)
let filterImage = UIImage(named: "ic_filter_selected")?.withRenderingMode(.alwaysTemplate)
filterButton.setImage(filterImage, for: .normal)
filterButton.tintColor = UIColor.white
filterButton.accessibilityLabel =
NSLocalizedString("Filter schedule events.",
comment: "Accessibility label for users to filter schedule events.")
return filterButton
}
func setupSwitchBarButton() -> UIBarButtonItem {
switchBarButton.setImage(UIImage(named: "ic_myio_off"), for: .normal)
switchBarButton.imageView?.contentMode = .scaleAspectFit
switchBarButton.imageEdgeInsets = UIEdgeInsets(top: -4, left: -8, bottom: -4, right: -8)
switchBarButton.contentHorizontalAlignment = .fill
switchBarButton.contentVerticalAlignment = .fill
switchBarButton.addTarget(self, action: #selector(switchButtonTapped), for: .touchUpInside)
switchBarButton.accessibilityLabel = Constants.myIOToggleAccessibilityLabelOff
switchBarButton.sizeToFit()
let barButtonContainerView: BarButtonContainerView = BarButtonContainerView(view: switchBarButton)
return UIBarButtonItem(customView: barButtonContainerView)
}
func setupSearchButton() -> UIBarButtonItem {
let button = MDCFlatButton()
button.setImage(UIImage(named: "ic_search"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.addTarget(self, action: #selector(showSearchController(_:)), for: .touchUpInside)
button.accessibilityLabel =
NSLocalizedString("Search",
comment: "Accessibility label for the search button")
button.sizeToFit()
let barButtonContainerView: BarButtonContainerView = BarButtonContainerView(view: button)
return UIBarButtonItem(customView: barButtonContainerView)
}
public let searchViewController: SearchCollectionViewController
func setupCollectionView() {
collectionView?.register(ScheduleViewCollectionViewCell.self,
forCellWithReuseIdentifier: ScheduleViewCollectionViewCell.reuseIdentifier())
collectionView?.register(ScheduleSectionHeaderReusableView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: ScheduleSectionHeaderReusableView.reuseIdentifier())
collectionView?.register(AgendaSectionHeaderReusableView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: AgendaSectionHeaderReusableView.reuseIdentifier())
collectionView?.register(AgendaCollectionViewCell.self,
forCellWithReuseIdentifier: AgendaCollectionViewCell.reuseIdentifier())
styler.cellStyle = .default
styler.shouldAnimateCellsOnAppearance = false
}
// MARK: - Analytics
fileprivate func logSelectedDay() {
guard let itemID = screenName else { return }
Application.sharedInstance.analytics.logEvent(AnalyticsEventSelectContent, parameters: [
AnalyticsParameterContentType: AnalyticsParameters.screen,
AnalyticsParameterItemID: itemID
])
}
override var screenName: String? {
switch selectedTabIndex {
case 0 ..< tabBar.items.count:
return AnalyticsParameters.itemID(forSelectedDay: selectedTabIndex)
case _:
return nil
}
}
}
// MARK: - MDCTabBarDelegate
extension ScheduleViewController: MDCTabBarDelegate {
func tabBar(_ tabBar: MDCTabBar, didSelect item: UITabBarItem) {
guard let itemIndex = tabBar.items.index(of: item) else { return }
selectedTabIndex = itemIndex
}
func tabBar(_ tabBar: MDCTabBar, shouldSelect item: UITabBarItem) -> Bool {
guard let itemIndex = tabBar.items.index(of: item) else { return false }
let section = Int(itemIndex)
let sectionIsEmpty = scheduleViewModel.isEmpty(forDayWithIndex: section)
return !sectionIsEmpty
}
}
// MARK: - Actions
extension ScheduleViewController {
@objc func filterAction() {
scheduleViewModel.filterSelected()
}
@objc func switchButtonTapped() {
if !showBookmarkedAndReserved {
self.switchBarButton.setImage(UIImage(named: "ic_myio_on"), for: .normal)
self.showBookmarkedAndReserved = true
scheduleViewModel.showOnlySavedEvents()
switchBarButton.accessibilityLabel = Constants.myIOToggleAccessibilityLabelOn
} else {
self.switchBarButton.setImage(UIImage(named: "ic_myio_off"), for: .normal)
self.showBookmarkedAndReserved = false
scheduleViewModel.showAllEvents()
switchBarButton.accessibilityLabel = Constants.myIOToggleAccessibilityLabelOff
}
self.refreshUI()
}
@objc func showSearchController(_ sender: Any) {
navigationController?.pushViewController(searchViewController, animated: true)
}
func refreshContent() {
scheduleViewModel.updateModel()
}
}
// MARK: - UICollectionView Layout
extension ScheduleViewController {
override func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
referenceSizeForHeaderInSection section: Int) -> CGSize {
var size = scheduleViewModel.sizeForHeader(inSection: section, inFrame: collectionView.bounds)
guard size.height > 0 else { return size }
size.height = 8 // hack
return size
}
override func collectionView(_ collectionView: UICollectionView,
cellHeightAt indexPath: IndexPath) -> CGFloat {
let leftInset = (collectionViewLayout as? SideHeaderCollectionViewLayout)?.dateWidth ?? 0
var frame = collectionView.bounds
frame.size.width -= leftInset
return scheduleViewModel.heightForCell(at: indexPath, inFrame: frame)
}
override func collectionView(_ collectionView: UICollectionView,
shouldHideHeaderBackgroundForSection section: Int) -> Bool {
return true
}
}
// MARK: - UICollectionViewDelegate
extension ScheduleViewController {
override func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
super.collectionView(collectionView, didSelectItemAt: indexPath)
scheduleViewModel.collectionView(collectionView, didSelectItemAt: indexPath)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView)
guard let collectionView = scrollView as? UICollectionView else { return }
// Updates the tab bar's selection without scrolling if the user scrolls to the
// next day.
guard scrollView.isDragging else { return }
guard let firstVisibleItem = collectionView.indexPathsForVisibleItems.first else { return }
let dayForItem = scheduleViewModel.dayForSection(firstVisibleItem.section)
if tabBar.selectedItem != tabBar.items[dayForItem] {
tabBar.setSelectedItem(tabBar.items[dayForItem], animated: true)
}
}
}
extension ScheduleViewController: UIViewControllerPreviewingDelegate {
func setup3DTouch() {
if let collectionView = collectionView {
registerForPreviewing(with: self, sourceView: collectionView)
}
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing,
viewControllerForLocation location: CGPoint) -> UIViewController? {
if let indexPath = collectionView?.indexPathForItem(at: location), let cellAttributes = collectionView?.layoutAttributesForItem(at: indexPath) {
// This will show the cell clearly and blur the rest of the screen for our peek.
previewingContext.sourceRect = cellAttributes.frame
return scheduleViewModel.previewViewControllerForItemAt(indexPath: indexPath)
}
return nil
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing,
commit viewControllerToCommit: UIViewController) {
self.navigationController?.pushViewController(viewControllerToCommit, animated: true)
}
}
// MARK: - Dynamic type
extension ScheduleViewController {
func registerForDynamicTypeUpdates() {
NotificationCenter.default.addObserver(self,
selector: #selector(dynamicTypeTextSizeDidChange(_:)),
name: UIContentSizeCategory.didChangeNotification,
object: nil)
}
@objc func dynamicTypeTextSizeDidChange(_ sender: Any) {
scheduleViewModel.invalidateHeights()
collectionView?.collectionViewLayout.invalidateLayout()
collectionView?.reloadData()
}
}
| apache-2.0 | 8e946517c971ac35d1717516f1787ace | 34.465812 | 148 | 0.726112 | 5.350741 | false | false | false | false |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtlocation/src/3rdparty/mapbox-gl-native/platform/ios/Mapbox.playground/Contents.swift | 1 | 8744 | import UIKit
#if swift(>=3)
import PlaygroundSupport
#else
import XCPlayground
#endif
import Mapbox
let width: CGFloat = 700
let height: CGFloat = 800
class Responder: NSObject {
var mapView: MGLMapView?
func togglePitch(sender: UISwitch) {
let camera = mapView!.camera
#if swift(>=3)
camera.pitch = sender.isOn ? 60 : 0
#else
camera.pitch = sender.on ? 60 : 0
#endif
mapView!.setCamera(camera, animated: false)
}
}
//: A control panel
let panelWidth: CGFloat = 200
let panel = UIView(frame: CGRect(x: width - panelWidth, y: 0, width: 200, height: 100))
panel.alpha = 0.8
#if swift(>=3)
panel.backgroundColor = .white
#else
panel.backgroundColor = UIColor.whiteColor()
#endif
// Delete markers
let deleteSwitchLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
deleteSwitchLabel.adjustsFontSizeToFitWidth = true
deleteSwitchLabel.text = "Delete Markers"
let deleteMarkerSwitchView = UISwitch(frame: CGRect(x: panelWidth - panelWidth / 2.0, y:0, width: 100, height: 50))
panel.addSubview(deleteSwitchLabel)
panel.addSubview(deleteMarkerSwitchView)
// Hide markers
let hideSwitchLabel = UILabel(frame: CGRect(x: 0, y: 30, width: 100, height: 30))
hideSwitchLabel.adjustsFontSizeToFitWidth = true
hideSwitchLabel.text = "Hide Markers"
let hideMarkerSwitchView = UISwitch(frame: CGRect(x: panelWidth - panelWidth / 2.0, y: 30, width: 100, height: 50))
panel.addSubview(hideSwitchLabel)
panel.addSubview(hideMarkerSwitchView)
// Pitch map
let pitchLabel = UILabel(frame: CGRect(x: 0, y: 60, width: 100, height: 30))
pitchLabel.text = "Pitch"
let pitchSwitch = UISwitch(frame: CGRect(x: panelWidth-panelWidth / 2.0, y: 60, width: 100, height: 50))
let responder = Responder()
#if swift(>=3)
pitchSwitch.addTarget(responder, action: #selector(responder.togglePitch(sender:)), for: .valueChanged)
#else
pitchSwitch.addTarget(responder, action: #selector(responder.togglePitch(_:)), forControlEvents: .ValueChanged)
#endif
panel.addSubview(pitchLabel)
panel.addSubview(pitchSwitch)
//: # Mapbox Maps
/*:
Put your access token into a plain text file called `token`. Then select the “token” placeholder below, go to Editor ‣ Insert File Literal, and select the `token` file.
*/
var accessToken = try String(contentsOfURL: <#token#>)
MGLAccountManager.setAccessToken(accessToken)
class PlaygroundAnnotationView: MGLAnnotationView {
override func prepareForReuse() {
#if swift(>=3)
isHidden = hideMarkerSwitchView.isOn
#else
hidden = hideMarkerSwitchView.on
#endif
}
}
//: Define a map delegate
class MapDelegate: NSObject, MGLMapViewDelegate {
var annotationViewByAnnotation = [MGLPointAnnotation: PlaygroundAnnotationView]()
#if swift(>=3)
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "annotation") as? PlaygroundAnnotationView
if (annotationView == nil) {
let av = PlaygroundAnnotationView(reuseIdentifier: "annotation")
av.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
av.centerOffset = CGVector(dx: -15, dy: -15)
let centerView = UIView(frame: av.bounds.insetBy(dx: 3, dy: 3))
centerView.backgroundColor = .white
av.addSubview(centerView)
av.backgroundColor = .purple
annotationView = av
} else {
annotationView!.subviews.first?.backgroundColor = .green
}
annotationViewByAnnotation[annotation as! MGLPointAnnotation] = annotationView
return annotationView
}
#else
func mapView(mapView: MGLMapView, viewForAnnotation annotation: MGLAnnotation) -> MGLAnnotationView? {
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("annotation") as? PlaygroundAnnotationView
if (annotationView == nil) {
let av = PlaygroundAnnotationView(reuseIdentifier: "annotation")
av.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
av.centerOffset = CGVector(dx: -15, dy: -15)
let centerView = UIView(frame: CGRectInset(av.bounds, 3, 3))
centerView.backgroundColor = UIColor.whiteColor()
av.addSubview(centerView)
av.backgroundColor = UIColor.purpleColor()
annotationView = av
} else {
annotationView!.subviews.first?.backgroundColor = UIColor.greenColor()
}
annotationViewByAnnotation[annotation as! MGLPointAnnotation] = annotationView
return annotationView
}
#endif
#if swift(>=3)
func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
let pointAnnotation = annotation as! MGLPointAnnotation
let annotationView: PlaygroundAnnotationView = annotationViewByAnnotation[pointAnnotation]!
for view in annotationViewByAnnotation.values {
view.layer.zPosition = -1
}
annotationView.layer.zPosition = 1
UIView.animate(withDuration: 1.25, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.6, options: .curveEaseOut, animations: {
annotationView.transform = CGAffineTransform(scaleX: 1.8, y: 1.8)
}) { _ in
annotationView.transform = CGAffineTransform(scaleX: 1, y: 1)
if deleteMarkerSwitchView.isOn {
mapView.removeAnnotation(pointAnnotation)
return
}
if hideMarkerSwitchView.isOn {
annotationView.isHidden = true
}
}
}
#else
func mapView(mapView: MGLMapView, didSelectAnnotation annotation: MGLAnnotation) {
let pointAnnotation = annotation as! MGLPointAnnotation
let annotationView: PlaygroundAnnotationView = annotationViewByAnnotation[pointAnnotation]!
for view in annotationViewByAnnotation.values {
view.layer.zPosition = -1
}
annotationView.layer.zPosition = 1
UIView.animateWithDuration(1.25, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.6, options: .CurveEaseOut, animations: {
annotationView.transform = CGAffineTransformMakeScale(1.8, 1.8)
}) { _ in
annotationView.transform = CGAffineTransformMakeScale(1, 1)
if deleteMarkerSwitchView.on {
mapView.removeAnnotation(pointAnnotation)
return
}
if hideMarkerSwitchView.on {
annotationView.hidden = true
}
}
}
#endif
func handleTap(press: UILongPressGestureRecognizer) {
let mapView: MGLMapView = press.view as! MGLMapView
#if swift(>=3)
let isRecognized = press.state == .recognized
#else
let isRecognized = press.state == .Recognized
#endif
if (isRecognized) {
#if swift(>=3)
let coordinate: CLLocationCoordinate2D = mapView.convert(press.location(in: mapView), toCoordinateFrom: mapView)
#else
let coordinate: CLLocationCoordinate2D = mapView.convertPoint(press.locationInView(mapView), toCoordinateFromView: mapView)
#endif
let annotation = MGLPointAnnotation()
annotation.title = "Dropped Marker"
annotation.coordinate = coordinate
mapView.addAnnotation(annotation)
mapView.showAnnotations([annotation], animated: true)
}
}
}
//: Create a map and its delegate
let centerCoordinate = CLLocationCoordinate2D(latitude: 37.174057, longitude: -104.490984)
let mapView = MGLMapView(frame: CGRect(x: 0, y: 0, width: width, height: height))
mapView.frame = CGRect(x: 0, y: 0, width: width, height: height)
#if swift(>=3)
PlaygroundPage.current.liveView = mapView
#else
XCPlaygroundPage.currentPage.liveView = mapView
#endif
let mapDelegate = MapDelegate()
mapView.delegate = mapDelegate
responder.mapView = mapView
let tapGesture = UILongPressGestureRecognizer(target: mapDelegate, action: #selector(mapDelegate.handleTap))
mapView.addGestureRecognizer(tapGesture)
//: Zoom in to a location
#if swift(>=3)
mapView.setCenter(centerCoordinate, zoomLevel: 12, animated: false)
#else
mapView.setCenterCoordinate(centerCoordinate, zoomLevel: 12, animated: false)
#endif
//: Add control panel
mapView.addSubview(panel)
| gpl-3.0 | a5620ebb3418c2316ee86add96dea7f2 | 34.811475 | 169 | 0.660449 | 4.700377 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.