repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Eric217/-OnSale
打折啦/打折啦/ELNavigationBar.swift
1
1817
// // ELNavigationBar.swift // 打折啦 // // Created by Eris on 2017/8/16. // Copyright © 2017年 INGStudio. All rights reserved. // import Foundation import SnapKit ///仅提供了基本功能:title,背景色,透明度。 class ELBaseNavigationBar: UIView { var gradient: CAGradientLayer! var title: String? var titleLabel: UILabel? override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear gradient = CAGradientLayer() setupGradient(gradient) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setAlpha_(_ alp: CGFloat, withTitle: Bool = false) { let c0 = gradient.colors?[0] as! CGColor if c0.alpha == alp { return } if withTitle { titleLabel?.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: alp) } gradient.colors = [c0.copy(alpha: alp) ?? UIColor.white.cgColor, (gradient.colors?[1] as! CGColor).copy(alpha: alp) ?? UIColor.white.cgColor] } func setupTitle(_ title: String) { titleLabel = UILabel() titleLabel?.text = title titleLabel?.font = UIFont.boldSystemFont(ofSize: 19) titleLabel?.textAlignment = .center addSubview(titleLabel!) titleLabel?.snp.makeConstraints{ make in make.width.equalTo(80) make.height.equalTo(44) make.centerY.equalTo(42) make.centerX.equalTo(self) } } func setBackColor(_ color: UIColor, by: CGFloat = 0.55) { let color1 = color.getWhiter(by: by) gradient.colors = [color.cgColor, color1.cgColor] } }
apache-2.0
ae56b5d2e384312403b5f28b70a6a6c6
20.095238
149
0.580135
4.12093
false
false
false
false
uasys/swift
test/SILGen/objc_ownership_conventions.swift
1
14318
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import gizmo // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions5test3So8NSObjectCyF func test3() -> NSObject { // initializer returns at +1 return Gizmo() // CHECK: [[CTOR:%[0-9]+]] = function_ref @_T0So5GizmoC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick Gizmo.Type) -> @owned Optional<Gizmo> // CHECK-NEXT: [[GIZMO_META:%[0-9]+]] = metatype $@thick Gizmo.Type // CHECK-NEXT: [[GIZMO:%[0-9]+]] = apply [[CTOR]]([[GIZMO_META]]) : $@convention(method) (@thick Gizmo.Type) -> @owned Optional<Gizmo> // CHECK: [[GIZMO_NS:%[0-9]+]] = upcast [[GIZMO:%[0-9]+]] : $Gizmo to $NSObject // CHECK: return [[GIZMO_NS]] : $NSObject // CHECK-LABEL: sil shared [serializable] @_T0So5GizmoC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick Gizmo.Type) -> @owned Optional<Gizmo> // alloc is implicitly ns_returns_retained // init is implicitly ns_consumes_self and ns_returns_retained // CHECK: bb0([[GIZMO_META:%[0-9]+]] : @trivial $@thick Gizmo.Type): // CHECK-NEXT: [[GIZMO_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[GIZMO_META]] : $@thick Gizmo.Type to $@objc_metatype Gizmo.Type // CHECK-NEXT: [[GIZMO:%[0-9]+]] = alloc_ref_dynamic [objc] [[GIZMO_META_OBJC]] : $@objc_metatype Gizmo.Type, $Gizmo // CHECK-NEXT: // function_ref // CHECK-NEXT: [[INIT_CTOR:%[0-9]+]] = function_ref @_T0So5GizmoC{{[_0-9a-zA-Z]*}}fcTO // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[INIT_CTOR]]([[GIZMO]]) : $@convention(method) (@owned Gizmo) -> @owned Optional<Gizmo> // CHECK-NEXT: return [[RESULT]] : $Optional<Gizmo> } // Normal message send with argument, no transfers. // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions5test5{{[_0-9a-zA-Z]*}}F func test5(_ g: Gizmo) { var g = g Gizmo.inspect(g) // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo): // CHECK: [[GIZMO_BOX:%.*]] = alloc_box ${ var Gizmo } // CHECK: [[GIZMO_BOX_PB:%.*]] = project_box [[GIZMO_BOX]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: store [[ARG_COPY]] to [init] [[GIZMO_BOX_PB]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[CLASS:%.*]] = metatype $@thick Gizmo.Type // CHECK: [[METHOD:%.*]] = class_method [volatile] [[CLASS]] : {{.*}}, #Gizmo.inspect!1.foreign // CHECK: [[OBJC_CLASS:%[0-9]+]] = thick_to_objc_metatype [[CLASS]] : $@thick Gizmo.Type to $@objc_metatype Gizmo.Type // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[GIZMO_BOX_PB]] : $*Gizmo // CHECK: [[V:%.*]] = load [copy] [[READ]] // CHECK: [[G:%.*]] = enum $Optional<Gizmo>, #Optional.some!enumelt.1, [[V]] // CHECK: apply [[METHOD]]([[G]], [[OBJC_CLASS]]) // CHECK: destroy_value [[G]] // CHECK: destroy_value [[GIZMO_BOX]] // CHECK: destroy_value [[ARG]] } // CHECK: } // end sil function '_T026objc_ownership_conventions5test5{{[_0-9a-zA-Z]*}}F' // The argument to consume is __attribute__((ns_consumed)). // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions5test6{{[_0-9a-zA-Z]*}}F func test6(_ g: Gizmo) { var g = g Gizmo.consume(g) // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo): // CHECK: [[GIZMO_BOX:%.*]] = alloc_box ${ var Gizmo } // CHECK: [[GIZMO_BOX_PB:%.*]] = project_box [[GIZMO_BOX]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: store [[ARG_COPY]] to [init] [[GIZMO_BOX_PB]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[CLASS:%.*]] = metatype $@thick Gizmo.Type // CHECK: [[METHOD:%.*]] = class_method [volatile] [[CLASS]] : {{.*}}, #Gizmo.consume!1.foreign // CHECK: [[OBJC_CLASS:%.*]] = thick_to_objc_metatype [[CLASS]] : $@thick Gizmo.Type to $@objc_metatype Gizmo.Type // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[GIZMO_BOX_PB]] : $*Gizmo // CHECK: [[V:%.*]] = load [copy] [[READ]] // CHECK: [[G:%.*]] = enum $Optional<Gizmo>, #Optional.some!enumelt.1, [[V]] // CHECK: apply [[METHOD]]([[G]], [[OBJC_CLASS]]) // CHECK-NOT: destroy_value [[G]] // CHECK: destroy_value [[GIZMO_BOX]] // CHECK-NOT: destroy_value [[G]] // CHECK: destroy_value [[ARG]] // CHECK-NOT: destroy_value [[G]] } // CHECK: } // end sil function '_T026objc_ownership_conventions5test6{{[_0-9a-zA-Z]*}}F' // fork is __attribute__((ns_consumes_self)). // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions5test7{{[_0-9a-zA-Z]*}}F func test7(_ g: Gizmo) { var g = g g.fork() // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo): // CHECK: [[GIZMO_BOX:%.*]] = alloc_box ${ var Gizmo } // CHECK: [[GIZMO_BOX_PB:%.*]] = project_box [[GIZMO_BOX]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: store [[ARG_COPY]] to [init] [[GIZMO_BOX_PB]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[GIZMO_BOX_PB]] : $*Gizmo // CHECK: [[G:%.*]] = load [copy] [[READ]] // CHECK: [[BORROWED_G:%.*]] = begin_borrow [[G]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_G]] : {{.*}}, #Gizmo.fork!1.foreign // CHECK: apply [[METHOD]]([[G]]) // CHECK-NOT: destroy_value [[G]] // CHECK: destroy_value [[GIZMO_BOX]] // CHECK-NOT: destroy_value [[G]] // CHECK: destroy_value [[ARG]] // CHECK-NOT: destroy_value [[G]] } // CHECK: } // end sil function '_T026objc_ownership_conventions5test7{{[_0-9a-zA-Z]*}}F' // clone is __attribute__((ns_returns_retained)). // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions5test8{{[_0-9a-zA-Z]*}}F func test8(_ g: Gizmo) -> Gizmo { return g.clone() // CHECK: bb0([[G:%.*]] : @owned $Gizmo): // CHECK-NOT: copy_value // CHECK: [[BORROWED_G:%.*]] = begin_borrow [[G]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_G]] : {{.*}}, #Gizmo.clone!1.foreign // CHECK-NOT: copy_value [[RESULT]] // CHECK: bb2([[RESULT:%.*]] : @owned $Gizmo): // CHECK-NOT: copy_value [[RESULT]] // CHECK: end_borrow [[BORROWED_G]] from [[G]] // CHECK-NEXT: destroy_value [[G]] // CHECK-NEXT: return [[RESULT]] } // duplicate returns an autoreleased object at +0. // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions5test9{{[_0-9a-zA-Z]*}}F func test9(_ g: Gizmo) -> Gizmo { return g.duplicate() // CHECK: bb0([[G:%.*]] : @owned $Gizmo): // CHECK-NOT: copy_value [[G:%0]] // CHECK: [[BORROWED_G:%.*]] = begin_borrow [[G]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_G]] : {{.*}}, #Gizmo.duplicate!1.foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[BORROWED_G]]) // CHECK-NOT: copy_value [[RESULT]] // CHECK: bb2([[RESULT:%.*]] : @owned $Gizmo): // CHECK-NOT: copy_value [[RESULT]] // CHECK: end_borrow [[BORROWED_G]] from [[G]] // CHECK-NEXT: destroy_value [[G]] // CHECK-NEXT: return [[RESULT]] } // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions6test10{{[_0-9a-zA-Z]*}}F func test10(_ g: Gizmo) -> AnyClass { // CHECK: bb0([[G:%[0-9]+]] : @owned $Gizmo): // CHECK: [[BORROWED_G:%.*]] = begin_borrow [[G]] // CHECK: [[G_COPY:%.*]] = copy_value [[BORROWED_G]] // CHECK-NEXT: [[NS_G_COPY:%[0-9]+]] = upcast [[G_COPY]] : $Gizmo to $NSObject // CHECK-NEXT: [[BORROWED_NS_G_COPY:%.*]] = begin_borrow [[NS_G_COPY]] // CHECK-NEXT: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_NS_G_COPY]] : $NSObject, #NSObject.classProp!getter.1.foreign : (NSObject) -> () -> AnyObject.Type!, $@convention(objc_method) (NSObject) -> Optional<@objc_metatype AnyObject.Type> // CHECK-NEXT: end_borrow [[BORROWED_NS_G_COPY]] // CHECK-NEXT: [[OPT_OBJC:%.*]] = apply [[GETTER]]([[NS_G_COPY]]) : $@convention(objc_method) (NSObject) -> Optional<@objc_metatype AnyObject.Type> // CHECK-NEXT: switch_enum [[OPT_OBJC]] : $Optional<{{.*}}>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[OBJC:%.*]] : @trivial $@objc_metatype AnyObject.Type): // CHECK-NEXT: [[THICK:%.*]] = objc_to_thick_metatype [[OBJC]] // CHECK: [[T0:%.*]] = enum $Optional<@thick AnyObject.Type>, #Optional.some!enumelt.1, [[THICK]] // CHECK: bb5([[RES:%.*]] : @trivial $@thick AnyObject.Type): // CHECK: destroy_value [[NS_G_COPY]] : $NSObject // CHECK: destroy_value [[G]] : $Gizmo // CHECK-NEXT: return [[RES]] : $@thick AnyObject.Type return g.classProp } // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions6test11{{[_0-9a-zA-Z]*}}F func test11(_ g: Gizmo) -> AnyClass { // CHECK: bb0([[G:%[0-9]+]] : @owned $Gizmo): // CHECK: [[BORROWED_G:%.*]] = begin_borrow [[G]] // CHECK: [[G_COPY:%.*]] = copy_value [[BORROWED_G]] // CHECK: [[NS_G_COPY:%[0-9]+]] = upcast [[G_COPY:%[0-9]+]] : $Gizmo to $NSObject // CHECK: [[BORROWED_NS_G_COPY:%.*]] = begin_borrow [[NS_G_COPY]] // CHECK-NEXT: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_NS_G_COPY]] : $NSObject, #NSObject.qualifiedClassProp!getter.1.foreign : (NSObject) -> () -> NSAnsing.Type!, $@convention(objc_method) (NSObject) -> Optional<@objc_metatype NSAnsing.Type> // CHECK-NEXT: end_borrow [[BORROWED_NS_G_COPY]] // CHECK-NEXT: [[OPT_OBJC:%.*]] = apply [[GETTER]]([[NS_G_COPY]]) : $@convention(objc_method) (NSObject) -> Optional<@objc_metatype NSAnsing.Type> // CHECK-NEXT: switch_enum [[OPT_OBJC]] : $Optional<{{.*}}>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[OBJC:%.*]] : @trivial $@objc_metatype NSAnsing.Type): // CHECK-NEXT: [[THICK:%.*]] = objc_to_thick_metatype [[OBJC]] // CHECK: [[T0:%.*]] = enum $Optional<@thick NSAnsing.Type>, #Optional.some!enumelt.1, [[THICK]] // CHECK: bb5([[RES:%.*]] : @trivial $@thick NSAnsing.Type): // CHECK: [[OPENED:%.*]] = open_existential_metatype [[RES]] // CHECK: [[RES_ANY:%.*]] = init_existential_metatype [[OPENED]] // CHECK: destroy_value [[NS_G_COPY]] : $NSObject // CHECK: destroy_value [[G]] : $Gizmo // CHECK-NEXT: return [[RES_ANY]] : $@thick AnyObject.Type return g.qualifiedClassProp } // ObjC blocks should have cdecl calling convention and follow C/ObjC // ownership conventions, where the callee, arguments, and return are all +0. // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions10applyBlock{{[_0-9a-zA-Z]*}}F func applyBlock(_ f: @convention(block) (Gizmo) -> Gizmo, x: Gizmo) -> Gizmo { // CHECK: bb0([[BLOCK:%.*]] : @owned $@convention(block) (Gizmo) -> @autoreleased Gizmo, [[ARG:%.*]] : @owned $Gizmo): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[BORROWED_BLOCK_COPY:%.*]] = begin_borrow [[BLOCK_COPY]] // CHECK: [[BLOCK_COPY_COPY:%.*]] = copy_value [[BORROWED_BLOCK_COPY]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[RESULT:%.*]] = apply [[BLOCK_COPY_COPY]]([[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[BLOCK_COPY_COPY]] // CHECK: end_borrow [[BORROWED_BLOCK_COPY]] from [[BLOCK_COPY]] // CHECK: destroy_value [[ARG]] // CHECK: destroy_value [[BLOCK_COPY]] // CHECK: destroy_value [[BLOCK]] // CHECK: return [[RESULT]] return f(x) } // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions15maybeApplyBlock{{[_0-9a-zA-Z]*}}F func maybeApplyBlock(_ f: (@convention(block) (Gizmo) -> Gizmo)?, x: Gizmo) -> Gizmo? { // CHECK: bb0([[BLOCK:%.*]] : @owned $Optional<@convention(block) (Gizmo) -> @autoreleased Gizmo>, [[ARG:%.*]] : @owned $Gizmo): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] return f?(x) } func useInnerPointer(_ p: UnsafeMutableRawPointer) {} // Handle inner-pointer methods by autoreleasing self after the call. // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions18innerPointerMethodySo5GizmoCF : $@convention(thin) (@owned Gizmo) -> () { // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo): // CHECK: [[USE:%.*]] = function_ref @_T026objc_ownership_conventions15useInnerPointer{{[_0-9a-zA-Z]*}}F // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.getBytes!1.foreign : (Gizmo) -> () -> UnsafeMutableRawPointer, $@convention(objc_method) (Gizmo) -> @unowned_inner_pointer UnsafeMutableRawPointer // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // => SEMANTIC ARC TODO: The apply below /should/ be on ARG_COPY. It is safe how // it is today though since we are using a reference type. // CHECK: [[PTR:%.*]] = apply [[METHOD]]([[BORROWED_ARG]]) // CHECK: autorelease_value [[ARG_COPY]] // CHECK: apply [[USE]]([[PTR]]) // CHECK: destroy_value [[ARG]] func innerPointerMethod(_ g: Gizmo) { useInnerPointer(g.getBytes()) } // CHECK-LABEL: sil hidden @_T026objc_ownership_conventions20innerPointerPropertyySo5GizmoCF : $@convention(thin) (@owned Gizmo) -> () { // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo): // CHECK: [[USE:%.*]] = function_ref @_T026objc_ownership_conventions15useInnerPointer{{[_0-9a-zA-Z]*}}F // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.innerProperty!getter.1.foreign : (Gizmo) -> () -> UnsafeMutableRawPointer, $@convention(objc_method) (Gizmo) -> @unowned_inner_pointer UnsafeMutableRawPointer // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // => SEMANTIC ARC TODO: The apply below should be on ARG_COPY. It is benign since objc objects are reference types. // CHECK: [[PTR:%.*]] = apply [[METHOD]]([[BORROWED_ARG]]) // CHECK: autorelease_value [[ARG_COPY]] // CHECK: apply [[USE]]([[PTR]]) // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T026objc_ownership_conventions20innerPointerPropertyySo5GizmoCF' func innerPointerProperty(_ g: Gizmo) { useInnerPointer(g.innerProperty) }
apache-2.0
a93d629b74f55070a87c3ca0ffeb30fd
57.203252
260
0.596173
3.241567
false
true
false
false
feighter09/Cloud9
SoundCloud Pro/Track.swift
1
3846
// // Track.swift // SoundCloud Pro // // Created by Austin Feight on 7/11/15. // Copyright © 2015 Lost in Flight. All rights reserved. // import SwiftyJSON import Parse @objc class Track: NSObject, NSCoding { let title: String let artist: String let duration: Double let streamURL: String init(json: JSON) { // I wish I could just save jsonData to json or json["origin"] but that doesn't work if json["origin"].dictionary != nil { title = json["origin"]["title"].string! artist = json["origin"]["user"]["username"].string! duration = json["origin"]["duration"].doubleValue / 1000 streamURL = json["origin"]["stream_url"].string! + "?client_id=\(kSoundCloudClientID)" } else { title = json["title"].string! artist = json["user"]["username"].string! duration = json["duration"].double! / 1000 streamURL = json["stream_url"].string! + "?client_id=\(kSoundCloudClientID)" } super.init() } required init?(coder aDecoder: NSCoder) { title = aDecoder.decodeObjectForKey(kTitleKey) as! String artist = aDecoder.decodeObjectForKey(kArtistKey) as! String duration = aDecoder.decodeDoubleForKey(kDurationKey) streamURL = aDecoder.decodeObjectForKey(kStreamURLKey) as! String } private init(object: PFObject) { title = object[kTitleKey] as! String artist = object[kArtistKey] as! String duration = object[kDurationKey] as! Double streamURL = object[kStreamURLKey] as! String } } // MARK: - Interface extension Track { func serializeToParseObject() -> PFObject { let track = PFObject(className: "Track") track[kTitleKey] = title track[kArtistKey] = artist track[kDurationKey] = duration track[kStreamURLKey] = streamURL return track } class func serializeFromParseObject(track: PFObject) -> Track { assert(track.parseClassName == "Track", "Can only serialize from Parse Track objects") return Track(object: track) } } // MARK: - Public Helpers extension Track { class func isStreamable(json: JSON) -> Bool { return json["streamable"].boolValue || json["origin"]["streamable"].boolValue || json["streamURL"].string != nil || json["origin"]["streamURL"].string != nil } } // MARK: - Helpers extension Track { private func milliToString(milliSeconds: Double?) -> String! { return "" } } // MARK: - NSCoding let kTrackJSON = "json" let kTitleKey = "title" let kArtistKey = "artist" let kDurationKey = "duration" let kStreamURLKey = "streamURL" extension Track { func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(title, forKey: kTitleKey) aCoder.encodeObject(artist, forKey: kArtistKey) aCoder.encodeDouble(duration, forKey: kDurationKey) aCoder.encodeObject(streamURL, forKey: kStreamURLKey) } } // MARK: - Equatable extension Track {} func ==(lhs: Track, rhs: Track) -> Bool { // NSLog("\(lhs) == \(rhs)? \((lhs.title == rhs.title && lhs.artist == rhs.artist) || lhs.streamURL == rhs.streamURL)") return (lhs.title == rhs.title && lhs.artist == rhs.artist) || lhs.streamURL == rhs.streamURL } func !=(lhs: Track, rhs: Track) -> Bool { return !(lhs == rhs) } func ==(lhs: AnyObject, rhs: Track) -> Bool { if lhs is Track { return lhs as! Track == rhs } return false } func ==(lhs: Track, rhs: AnyObject) -> Bool { return rhs == lhs } func ===(lhs: Track, rhs: Track) -> Bool { return lhs == rhs } func ==(lhs: PFObject, rhs: Track) -> Bool { return Track(object: lhs) == rhs } // MARK: - Hashable extension Track { override var hashValue: Int { return title.hashValue } // This doesn't work } // MARK: - Debug Printing extension Track { override var description: String { return "\(artist): \(title)" } override var debugDescription: String { return description } }
lgpl-3.0
229ab87d42d4e2f2ef4b0bbd2aa62ba6
24.64
120
0.661378
3.8335
false
false
false
false
xedin/swift
test/Interpreter/dynamicReplacement_property_observer.swift
8
3186
// RUN: %empty-directory(%t) // RUN: %target-build-swift-dylib(%t/%target-library-name(TestDidWillSet)) -module-name TestDidWillSet -emit-module -emit-module-path %t/TestDidWillSet.swiftmodule -swift-version 5 %S/Inputs/dynamic_replacement_property_observer_orig.swift -Xfrontend -enable-private-imports -Xfrontend -enable-implicit-dynamic // RUN: %target-build-swift-dylib(%t/%target-library-name(TestDidWillSet2)) -I%t -L%t -lTestDidWillSet %target-rpath(%t) -module-name TestDidWillSet2 -swift-version 5 %S/Inputs/dynamic_replacement_property_observer_repl.swift // RUN: %target-build-swift -I%t -L%t -lTestDidWillSet -o %t/main %target-rpath(%t) %s -swift-version 5 // RUN: %target-codesign %t/main %t/%target-library-name(TestDidWillSet) %t/%target-library-name(TestDidWillSet2) // RUN: %target-run %t/main %t/%target-library-name(TestDidWillSet) %t/%target-library-name(TestDidWillSet) // REQUIRES: executable_test // UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic @_private(sourceFile: "dynamic_replacement_property_observer_orig.swift") import TestDidWillSet #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) import Glibc #elseif os(Windows) import MSVCRT import WinSDK #else #error("Unsupported platform") #endif private func target_library_name(_ name: String) -> String { #if os(iOS) || os(macOS) || os(tvOS) || os(watchOS) return "lib\(name).dylib" #elseif os(Windows) return "\(name).dll" #else return "lib\(name).so" #endif } var s = Stored(i: 5, y: 5, z: 5) var h = HeapStored() // CHECK: Stored.i.didSet from 5 to 10 original s.i = 10 // CHECK: Stored.y.willSet from 5 to 11 original s.y = 11 // CHECK: Stored.z.willSet from 5 to 12 original // CHECK: Stored.z.didSet from 5 to 12 original s.z = 12 // CHECK: HeapStored.z.willSet from 5 to 16 original // CHECK: HeapStored.z.didSet from 5 to 16 original h.z = 16 // CHECK: myglobal.didSet from 1 to 13 original myglobal = 13 // CHECK: myglobal2.willSet from 1 to 14 original myglobal2 = 14 // CHECK: myglobal3.willSet from 1 to 15 original // CHECK: myglobal3.didSet from 1 to 15 original myglobal3 = 15 var executablePath = CommandLine.arguments[0] executablePath.removeLast(4) // Now, test with the module containing the replacements. #if os(Linux) _ = dlopen(target_library_name("Module2"), RTLD_NOW) #elseif os(Windows) _ = LoadLibraryA(target_library_name("Module2")) #else _ = dlopen(executablePath+target_library_name("Module2"), RTLD_NOW) #endif // CHECK: Stored.i.didSet from 5 to 10 replacement s.i = 10 // CHECK: Stored.y.willSet from 5 to 11 replacement s.y = 11 // CHECK: Stored.z.willSet from 5 to 12 replacement // CHECK: Stored.z.didSet from 5 to 12 replacement s.z = 12 // CHECK: HeapStored.z.willSet from 5 to 16 replacement // CHECK: HeapStored.z.didSet from 5 to 16 replacement h.z = 16 // CHECK: myglobal.didSet from 1 to 13 replacement myglobal = 13 // CHECK: myglobal2.willSet from 1 to 14 replacement myglobal2 = 14 // CHECK: myglobal3.willSet from 1 to 15 replacement // CHECK: myglobal3.didSet from 1 to 15 replacement myglobal3 = 15
apache-2.0
2908fb806ad6c25651b680b35fe9b6e0
34.797753
310
0.728186
3.25102
false
true
false
false
stephencelis/SQLite.swift
Tests/SQLiteTests/Core/BlobTests.swift
1
1519
import XCTest import SQLite class BlobTests: XCTestCase { func test_toHex() { let blob = Blob(bytes: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 250, 255]) XCTAssertEqual(blob.toHex(), "000a141e28323c46505a6496faff") } func test_toHex_empty() { let blob = Blob(bytes: []) XCTAssertEqual(blob.toHex(), "") } func test_description() { let blob = Blob(bytes: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 250, 255]) XCTAssertEqual(blob.description, "x'000a141e28323c46505a6496faff'") } func test_description_empty() { let blob = Blob(bytes: []) XCTAssertEqual(blob.description, "x''") } func test_init_array() { let blob = Blob(bytes: [42, 43, 44]) XCTAssertEqual([UInt8](blob.data), [42, 43, 44]) } func test_init_unsafeRawPointer() { let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 3) pointer.initialize(repeating: 42, count: 3) let blob = Blob(bytes: pointer, length: 3) XCTAssertEqual([UInt8](blob.data), [42, 42, 42]) } func test_equality() { let blob1 = Blob(bytes: [42, 42, 42]) let blob2 = Blob(bytes: [42, 42, 42]) let blob3 = Blob(bytes: [42, 42, 43]) XCTAssertEqual(Blob(bytes: []), Blob(bytes: [])) XCTAssertEqual(blob1, blob2) XCTAssertNotEqual(blob1, blob3) } func XXX_test_init_with_mutable_data_fails() { _ = Blob(data: NSMutableData()) } }
mit
aa87a5f77c7e981d7c2060bf20c5fdae
28.784314
91
0.581303
3.390625
false
true
false
false
crazypoo/PTools
Pods/InAppViewDebugger/InAppViewDebugger/ViewControllerUtils.swift
1
1271
// // ViewUtils.swift // InAppViewDebugger // // Created by Indragie Karunaratne on 4/4/19. // Copyright © 2019 Indragie Karunaratne. All rights reserved. // import UIKit func getNearestAncestorViewController(responder: UIResponder) -> UIViewController? { if let viewController = responder as? UIViewController { return viewController } else if let nextResponder = responder.next { return getNearestAncestorViewController(responder: nextResponder) } return nil } func topViewController(rootViewController: UIViewController?) -> UIViewController? { guard let rootViewController = rootViewController else { return nil } guard let presentedViewController = rootViewController.presentedViewController else { return rootViewController } if let navigationController = presentedViewController as? UINavigationController { return topViewController(rootViewController: navigationController.viewControllers.last) } else if let tabBarController = presentedViewController as? UITabBarController { return topViewController(rootViewController: tabBarController.selectedViewController) } else { return topViewController(rootViewController: presentedViewController) } }
mit
ab05f1f73c7340c2817165987ec99101
35.285714
95
0.75748
6.076555
false
false
false
false
piemonte/Twinkle
Twinkle/TwinkleTV/ViewController.swift
1
2857
// ViewController.swift // // Created by patrick piemonte on 2/20/15. // // The MIT License (MIT) // // Copyright (c) 2015-present patrick piemonte (http://patrickpiemonte.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class ViewController: UIViewController { private var textLabel: UILabel! // MARK: object lifecycle convenience init() { self.init(nibName: nil, bundle:nil) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } // MARK: view lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.autoresizingMask = ([UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]) self.view.backgroundColor = UIColor(red: 81/255, green: 0, blue: 97/255, alpha: 1) let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:))) tapGestureRecognizer.allowedPressTypes = [NSNumber(value: UIPress.PressType.playPause.rawValue)]; self.view.addGestureRecognizer(tapGestureRecognizer) textLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 800, height: 150)) textLabel.center = self.view.center textLabel.text = "Play/Pause to Twinkle" textLabel.textColor = UIColor.white textLabel.font = UIFont(name: "AvenirNext-Regular", size: 72) self.view.addSubview(textLabel) } // MARK: UIButton handler @objc func handleTap(_ button: UITapGestureRecognizer!) { textLabel.twinkle() } }
mit
266826bf4c1ec4a1c282158221ea9447
38.680556
144
0.697935
4.549363
false
false
false
false
appsquickly/Typhoon-Swift-Example
PocketForecast/Dao/WeatherReportDaoFileSystemImpl.swift
1
1337
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Typhoon Framework Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import Foundation public class WeatherReportDaoFileSystemImpl : NSObject, WeatherReportDao { public func getReportForCityName(cityName: String) -> WeatherReport? { let filePath = self.filePathFor(cityName: cityName) let weatherReport : WeatherReport? = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? WeatherReport return weatherReport } public func saveReport(weatherReport: WeatherReport!) { NSKeyedArchiver.archiveRootObject(weatherReport, toFile: self.filePathFor(cityName: weatherReport.cityDisplayName)) } private func filePathFor(cityName : String) -> String { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentsDirectory = paths[0] let filePath = documentsDirectory + "weatherReport~>$\(cityName)" return filePath } }
apache-2.0
de95c3116961b0edf587c14834d8ed2b
37.2
123
0.628272
5.713675
false
false
false
false
ryan-blunden/ga-mobile
Recipes/Recipes/HomeViewController.swift
2
2035
// // HomeViewController.swift // Recipes // // Created by Ryan Blunden on 4/06/2015. // Copyright (c) 2015 RabbitBird Pty Ltd. All rights reserved. // import UIKit class HomeViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate { private var recipes:[Recipe] = [] override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self recipes = RecipeDataManager.sharedManager.findAll() } override func viewWillAppear(animated: Bool) { setupNavBar() } private func setupNavBar() { navigationController?.navigationBar.barTintColor = UIColor.darkGrayColor() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return recipes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let recipe = recipes[indexPath.row] var tableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "") tableViewCell.textLabel?.text = recipe.title tableViewCell.detailTextLabel?.text = recipe.description return tableViewCell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let recipe = recipes[indexPath.row] performSegueWithIdentifier(recipe.segue, sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case Constants.segueToAboutWebView: if let aboutViewController = segue.destinationViewController as? UIWebViewControllerLocalGeneric { aboutViewController.webFile = "about" } case Constants.segueToContactWebView: if let aboutViewController = segue.destinationViewController as? UIWebViewControllerLocalGeneric { aboutViewController.webFile = "contact" } default: return } } } }
gpl-3.0
5ba7aa0e5cc37541ccd6dcc509eeff78
30.796875
116
0.716462
5.355263
false
false
false
false
NachoNachev/ActiveRecord
ActiveRecord/NSManagedObject+FetchedResultsController.swift
1
12422
// // NSManagedObject+FetchedResultsController.swift // ActiveRecord // // Created by Nacho Nachev on 11/18/14. // Copyright (c) 2014 Nacho Nachev. All rights reserved. // import CoreData extension NSManagedObject { class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortedBy attribute: String, ascending: Bool) -> NSFetchedResultsController { return fetchedResultsControllerWithDelegate(delegate, sortedBy: attribute, ascending: ascending, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: nil, cacheName: nil) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortedBy attribute: String, ascending: Bool, sectionNameKeyPath: String) -> NSFetchedResultsController { return fetchedResultsControllerWithDelegate(delegate, sortedBy: attribute, ascending: ascending, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortedBy attribute: String, ascending: Bool, sectionNameKeyPath: String, cacheName: String) -> NSFetchedResultsController { return fetchedResultsControllerWithDelegate(delegate, sortedBy: attribute, ascending: ascending, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortedBy attribute: String, ascending: Bool, inContext context: NSManagedObjectContext) -> NSFetchedResultsController { return fetchedResultsControllerWithDelegate(delegate, sortedBy: attribute, ascending: ascending, inContext: context, sectionNameKeyPath: nil, cacheName: nil) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortedBy attribute: String, ascending: Bool, inContext context: NSManagedObjectContext, sectionNameKeyPath: String) -> NSFetchedResultsController { return fetchedResultsControllerWithDelegate(delegate, sortedBy: attribute, ascending: ascending, inContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortedBy attribute: String, ascending: Bool, inContext context: NSManagedObjectContext, sectionNameKeyPath: String?, cacheName: String?) -> NSFetchedResultsController { let sortDescriptors = [ NSSortDescriptor(key: attribute, ascending: ascending) ] return fetchedResultsControllerWithPredicate(nil, delegate: delegate, sortDescriptors: sortDescriptors, inContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor]) -> NSFetchedResultsController { return fetchedResultsControllerWithDelegate(delegate, sortDescriptors: sortDescriptors, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: nil, cacheName: nil) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], sectionNameKeyPath: String) -> NSFetchedResultsController { return fetchedResultsControllerWithDelegate(delegate, sortDescriptors: sortDescriptors, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], sectionNameKeyPath: String, cacheName: String) -> NSFetchedResultsController { return fetchedResultsControllerWithDelegate(delegate, sortDescriptors: sortDescriptors, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], inContext context: NSManagedObjectContext) -> NSFetchedResultsController { return fetchedResultsControllerWithDelegate(delegate, sortDescriptors: sortDescriptors, inContext: context, sectionNameKeyPath: nil, cacheName: nil) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], inContext context: NSManagedObjectContext, sectionNameKeyPath: String) -> NSFetchedResultsController { return fetchedResultsControllerWithDelegate(delegate, sortDescriptors: sortDescriptors, inContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil) } class func fetchedResultsControllerWithDelegate(delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], inContext context: NSManagedObjectContext, sectionNameKeyPath: String?, cacheName: String?) -> NSFetchedResultsController { return fetchedResultsControllerWithPredicate(nil, delegate: delegate, sortDescriptors: sortDescriptors, inContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortedBy sortAttribute: String, ascending: Bool) -> NSFetchedResultsController { return fetchedResultsControllerByAttribute(attribute, withValue: value, delegate: delegate, sortedBy: sortAttribute, ascending: ascending, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: nil, cacheName: nil) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortedBy sortAttribute: String, ascending: Bool, inContext context: NSManagedObjectContext) -> NSFetchedResultsController { return fetchedResultsControllerByAttribute(attribute, withValue: value, delegate: delegate, sortedBy: sortAttribute, ascending: ascending, inContext: context, sectionNameKeyPath: nil, cacheName: nil) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortedBy sortAttribute: String, ascending: Bool, sectionNameKeyPath: String) -> NSFetchedResultsController { return fetchedResultsControllerByAttribute(attribute, withValue: value, delegate: delegate, sortedBy: sortAttribute, ascending: ascending, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortedBy sortAttribute: String, ascending: Bool, inContext context: NSManagedObjectContext, sectionNameKeyPath: String) -> NSFetchedResultsController { return fetchedResultsControllerByAttribute(attribute, withValue: value, delegate: delegate, sortedBy: sortAttribute, ascending: ascending, inContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortedBy sortAttribute: String, ascending: Bool, sectionNameKeyPath: String?, cacheName: String?) -> NSFetchedResultsController { return fetchedResultsControllerByAttribute(attribute, withValue: value, delegate: delegate, sortedBy: sortAttribute, ascending: ascending, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortedBy sortAttribute: String, ascending: Bool, inContext context: NSManagedObjectContext, sectionNameKeyPath: String?, cacheName: String?) -> NSFetchedResultsController { let predicate = self.predicateWithAttribute(attribute, withValue: value) let sortDescriptors = [ NSSortDescriptor(key: sortAttribute, ascending: ascending) ] return fetchedResultsControllerWithPredicate(predicate, delegate: delegate, sortDescriptors: sortDescriptors, inContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor]) -> NSFetchedResultsController { return fetchedResultsControllerByAttribute(attribute, withValue: value, delegate: delegate, sortDescriptors: sortDescriptors, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: nil, cacheName: nil) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], inContext context: NSManagedObjectContext) -> NSFetchedResultsController { return fetchedResultsControllerByAttribute(attribute, withValue: value, delegate: delegate, sortDescriptors: sortDescriptors, inContext: context, sectionNameKeyPath: nil, cacheName: nil) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], sectionNameKeyPath: String) -> NSFetchedResultsController { return fetchedResultsControllerByAttribute(attribute, withValue: value, delegate: delegate, sortDescriptors: sortDescriptors, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], inContext context: NSManagedObjectContext, sectionNameKeyPath: String) -> NSFetchedResultsController { return fetchedResultsControllerByAttribute(attribute, withValue: value, delegate: delegate, sortDescriptors: sortDescriptors, inContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], sectionNameKeyPath: String?, cacheName: String?) -> NSFetchedResultsController { return fetchedResultsControllerByAttribute(attribute, withValue: value, delegate: delegate, sortDescriptors: sortDescriptors, inContext: NSManagedObjectContext.contextForCurrentThread, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } class func fetchedResultsControllerByAttribute(attribute: String, withValue value: CVarArgType, delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], inContext context: NSManagedObjectContext, sectionNameKeyPath: String?, cacheName: String?) -> NSFetchedResultsController { let predicate = self.predicateWithAttribute(attribute, withValue: value) return fetchedResultsControllerWithPredicate(predicate, delegate: delegate, sortDescriptors: sortDescriptors, inContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } class func fetchedResultsControllerWithPredicate(predicate: NSPredicate?, delegate: NSFetchedResultsControllerDelegate, sortDescriptors: [NSSortDescriptor], inContext context: NSManagedObjectContext, sectionNameKeyPath: String?, cacheName: String?) -> NSFetchedResultsController { let request = NSFetchRequest(entityName: self.entityName) request.predicate = predicate request.sortDescriptors = sortDescriptors let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) controller.delegate = delegate return controller } }
mit
a36cc4f1f2546b595d98145c74865ce1
99.177419
318
0.820238
6.963004
false
false
false
false
MrSongzj/MSDouYuZB
MSDouYuZB/MSDouYuZB/Classes/Home/Presenter/GamePresenter.swift
1
1074
// // GamePresenter.swift // MSDouYuZB // // Created by jiayuan on 2017/8/8. // Copyright © 2017年 mrsong. All rights reserved. // import Foundation class GamePresenter { // MARK: - 属性 lazy var gameCateArr = [GameCateModel]() // MARK: - Public Methods func requestGameCate(responseCallback: (() -> ())? = nil ) { NetworkTools.get(urlString: "http://capi.douyucdn.cn/api/v1/getColumnDetail", parameters: ["shortName": "game"]) { (result) in // 将 result 转成字典 guard let responseData = result as? [String: Any] else { return } // 获取字典里的 data 数据 guard let dataArray = responseData["data"] as? [[String: NSObject]] else { return } // 遍历数组里的字典,转成 model 对象 for dict in dataArray { self.gameCateArr.append(GameCateModel.init(dict: dict)) } // 回调 if let callback = responseCallback { callback() } } } }
mit
84f3e1b51f9a5771d2b7573f2db031d2
27.083333
134
0.549951
4.143443
false
false
false
false
ps2/rileylink_ios
OmniKitUI/Views/DeliveryUncertaintyRecoveryView.swift
1
4746
// // DeliveryUncertaintyRecoveryView.swift // OmniKit // // Created by Pete Schwamb on 8/17/20. // Copyright © 2020 LoopKit Authors. All rights reserved. // import SwiftUI import LoopKitUI import RileyLinkBLEKit struct DeliveryUncertaintyRecoveryView: View { let model: DeliveryUncertaintyRecoveryViewModel @ObservedObject var rileyLinkListDataSource: RileyLinkListDataSource var handleRileyLinkSelection: (RileyLinkDevice) -> Void @Environment(\.guidanceColors) var guidanceColors var body: some View { GuidePage(content: { Text(String(format: LocalizedString("%1$@ has been unable to communicate with the pod on your body since %2$@.\n\nWithout communication with the pod, the app cannot continue to send commands for insulin delivery or display accurate, recent information about your active insulin or the insulin being delivered by the Pod.\n\nMonitor your glucose closely for the next 6 or more hours, as there may or may not be insulin actively working in your body that %3$@ cannot display.", comment: "Format string for main text of delivery uncertainty recovery page. (1: app name)(2: date of command)(3: app name)"), self.model.appName, self.uncertaintyDateLocalizedString, self.model.appName)) .padding([.top, .bottom]) Section(header: HStack { FrameworkLocalText("Devices", comment: "Header for devices section of RileyLinkSetupView") Spacer() ProgressView() }) { ForEach(rileyLinkListDataSource.devices, id: \.peripheralIdentifier) { device in Toggle(isOn: rileyLinkListDataSource.autoconnectBinding(for: device)) { HStack { Text(device.name ?? "Unknown") Spacer() if rileyLinkListDataSource.autoconnectBinding(for: device).wrappedValue { if device.isConnected { Text(formatRSSI(rssi:device.rssi)).foregroundColor(.secondary) } else { Image(systemName: "wifi.exclamationmark") .imageScale(.large) .foregroundColor(guidanceColors.warning) } } } .contentShape(Rectangle()) .onTapGesture { handleRileyLinkSelection(device) } } } } .onAppear { rileyLinkListDataSource.isScanningEnabled = true model.respondToRecovery = true } .onDisappear { rileyLinkListDataSource.isScanningEnabled = false model.respondToRecovery = false } }) { VStack { Text(LocalizedString("Attemping to re-establish communication", comment: "Description string above progress indicator while attempting to re-establish communication from an unacknowledged command")).padding(.top) ProgressIndicatorView(state: .indeterminantProgress) Button(action: { self.model.podDeactivationChosen() }) { Text(LocalizedString("Deactivate Pod", comment: "Button title to deactive pod on uncertain program")) .actionButtonStyle(.destructive) .padding() } } } .navigationBarTitle(Text(LocalizedString("Unable to Reach Pod", comment: "Title of delivery uncertainty recovery page")), displayMode: .large) .navigationBarItems(leading: backButton) } private var uncertaintyDateLocalizedString: String { DateFormatter.localizedString(from: model.uncertaintyStartedAt, dateStyle: .none, timeStyle: .short) } var decimalFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.minimumFractionDigits = 0 formatter.maximumFractionDigits = 2 return formatter }() private func formatRSSI(rssi: Int?) -> String { if let rssi = rssi, let rssiStr = decimalFormatter.decibleString(from: rssi) { return rssiStr } else { return "" } } private var backButton: some View { Button(LocalizedString("Back", comment: "Back button text on DeliveryUncertaintyRecoveryView"), action: { self.model.onDismiss?() }) } }
mit
daf83a45e75a595bab2a6f0a0761d57e
43.345794
692
0.586512
5.608747
false
false
false
false
rohgar/quick-text-copy
QuickText/BaseObject.swift
1
9797
// // QuickTextMenuBaseController.swift // Quick Text // // Created by RohGar on 8/5/17. // Copyright © 2017 Rovag. All rights reserved. // import Cocoa import Magnet import Foundation class MenuItem: NSMenuItem { var val: String! } class BaseObject: NSObject { let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) // user defaults let menu = NSMenu() let userDefaults = UserDefaults.standard let KEY_PROPERTY_FILE = "propertyfile" var userSelectedFile : String? = nil private let SEPARATOR = "separator" override func awakeFromNib() { // set the icon let icon = NSImage(named: "StatusBarIcon") icon?.isTemplate = true // best for dark mode if let button = statusItem.button { button.image = icon button.title = "" } // load the user selected file userSelectedFile = userDefaults.string(forKey: KEY_PROPERTY_FILE) if let file = userSelectedFile { initializeMenu(enableItems: true) populateMenuFromFile(file) } else { initializeMenu() } // shortcut if let keyCombo = KeyCombo(key: .c, carbonModifiers: 768) { let hotKey = HotKey(identifier: "CommandShiftC", keyCombo: keyCombo) { hotKey in // Called when ⌘ + Shift + C is pressed self.menu.popUp(positioning: nil, at: NSEvent.mouseLocation, in: nil) } hotKey.register() } } // MARK: Selector Functions @objc func getNewFile(sender: MenuItem) { let newFile = Utils.selectFile() if let file = newFile { initializeMenu(enableItems: true) populateMenuFromFile(file) userSelectedFile = file userDefaults.set(userSelectedFile, forKey: KEY_PROPERTY_FILE) } } @objc func refreshFile(sender: MenuItem) { initializeMenu(enableItems: true) if let file = userSelectedFile { populateMenuFromFile(file) } } @objc func reset(sender: MenuItem) { userSelectedFile = nil initializeMenu() } @objc func clickedItem(sender: MenuItem) { // copy the item to clipboard let pasteBoard = NSPasteboard.general pasteBoard.clearContents() pasteBoard.writeObjects([sender.val as NSString]) // paste by simulating "cmd + v" print(0x09) let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState) let event1 = CGEvent(keyboardEventSource: src, virtualKey: 0x09, keyDown: true) event1?.flags = CGEventFlags.maskCommand; event1?.post(tap: .cghidEventTap) let event2 = CGEvent(keyboardEventSource: src, virtualKey: 0x09, keyDown: false) event2?.flags = CGEventFlags.maskCommand; event2?.post(tap: .cghidEventTap) print("Done") } @objc func aboutApp(sender: MenuItem) -> Bool { let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String let alert: NSAlert = NSAlert() alert.messageText = "Quick Text Copy" if let version = appVersion { alert.informativeText = "Version " + version } alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "OK") return alert.runModal() == .alertFirstButtonReturn } @objc func quitApp(sender: MenuItem) { NSApplication.shared.terminate(self) } // MARK: Private Functions private func initializeMenu(enableItems: Bool = false) { menu.removeAllItems() statusItem.menu = menu statusItem.menu!.autoenablesItems = enableItems // Load File let loadMenuItem = MenuItem(title: "Load File ...", action: #selector(getNewFile), keyEquivalent: "l") // Refresh File let refreshMenuItem = MenuItem(title: "Refresh ...", action: #selector(refreshFile), keyEquivalent: "r") refreshMenuItem.isEnabled = false // Clear File let clearMenuItem = MenuItem(title: "Clear ...", action: #selector(reset), keyEquivalent: "c") clearMenuItem.isEnabled = false // separator statusItem.menu!.addItem(MenuItem.separator()) // About let aboutMenuItem = MenuItem(title: "About", action: #selector(aboutApp), keyEquivalent: "a") // Quit let quitMenuItem = MenuItem(title: "Quit", action: #selector(quitApp), keyEquivalent: "q") let items = [loadMenuItem, refreshMenuItem, clearMenuItem, MenuItem.separator(), aboutMenuItem, MenuItem.separator(), quitMenuItem] for item in items { statusItem.menu!.addItem(item) } for item in statusItem.menu!.items { item.target = self } } private func populateMenuFromFile(_ chosenFile: String) { let splitArray = chosenFile.split(separator: ".") let fileExtension = splitArray[splitArray.count - 1] switch fileExtension { case "properties": populateMenuFromPropertiesFile(chosenFile) case "json": populateMenuFromJSONfile(chosenFile) default: populateMenuFromPropertiesFile(chosenFile) } } // Assumes that the user did select a file private func populateMenuFromPropertiesFile(_ chosenFile: String) { var isPropertyFile = false; if (chosenFile.hasSuffix("properties")) { isPropertyFile = true } // Read the contents of the file into an array of Strings do { let content = try NSString(contentsOfFile: chosenFile, encoding: String.Encoding.utf8.rawValue) // load the file contents let lines = content.components(separatedBy: "\n") var index = 0 var shortcutIndex = 0 // add values from the file for _line in lines { if (_line.isEmpty) { statusItem.menu!.insertItem(MenuItem.separator(), at: index) } else { var shortcut = "" if (shortcutIndex < 10) { shortcut = "\(shortcutIndex)" } var key : String var value : String if (isPropertyFile) { let _keyval = _line.split(separator: "=", maxSplits: 1) let onlyKeyPresent = (_keyval.count == 1) key = String(_keyval[0]) value = onlyKeyPresent ? key : String(_keyval[1]) } else { key = _line value = key } let item = MenuItem(title: key, action: #selector(clickedItem), keyEquivalent: shortcut) item.val = value item.target = self statusItem.menu!.insertItem(item, at: index) shortcutIndex += 1 } index += 1 } // add separator statusItem.menu!.insertItem(NSMenuItem.separator(), at: index) } catch { let nsError = error as NSError print(nsError.localizedDescription) } } private func populateMenuFromJSONfile(_ chosenFile: String) { let jsonData = JSONUtils.readJSONData(fromFile: chosenFile) if let jsonObject = JSONUtils.decode(jsonData: jsonData!) { let elements = jsonObject.elements let submenus = jsonObject.submenus var shortcutIndex = 0 for (index, element) in elements.enumerated() { if (element.key == SEPARATOR) { statusItem.menu!.insertItem(MenuItem.separator(), at: index) } else { let shortcut = (shortcutIndex < 10) ? "" : "\(shortcutIndex)" let item = MenuItem(title: element.key, action: #selector(clickedItem), keyEquivalent: shortcut) item.val = element.value item.target = self statusItem.menu!.insertItem(item, at: index) shortcutIndex += 1 } } for (index, sm) in submenus.enumerated() { let menuDropdown = NSMenuItem(title: sm.name, action: nil, keyEquivalent: "") menu.insertItem(menuDropdown, at: elements.count + index) let submenu = NSMenu() for smelement in sm.elements { if (smelement.key == SEPARATOR) { statusItem.menu!.insertItem(MenuItem.separator(), at: index) } else { let subItem = MenuItem(title: smelement.key, action: #selector(clickedItem), keyEquivalent: "") subItem.val = smelement.value subItem.target = self submenu.addItem(subItem) } } menu.setSubmenu(submenu, for: menuDropdown) } } else { let alert = NSAlert.init() alert.messageText = "JSON Error!" alert.informativeText = "There was an error while reading JSON content, please verify that your input JSON file is valid." alert.addButton(withTitle: "OK") alert.runModal() } } }
gpl-3.0
04b8259e10153a4069df16da7f870018
36.669231
134
0.553196
5.025141
false
false
false
false
wisonlin/OpenGLESTutorial
Hello-Metal_3_Starter/HelloMetal/BufferProvider.swift
1
1600
// // BufferProvider.swift // HelloMetal // // Created by Andriy K. on 4/3/16. // Copyright © 2016 Razeware LLC. All rights reserved. // import Metal class BufferProvider { // 1 let inflightBuffersCount: Int // 2 private var uniformsBuffers: [MTLBuffer] // 3 private var avaliableBufferIndex: Int = 0 var avaliableResourcesSemaphore: DispatchSemaphore init(device:MTLDevice, inflightBuffersCount: Int, sizeOfUniformsBuffer: Int){ avaliableResourcesSemaphore = DispatchSemaphore(value: inflightBuffersCount) self.inflightBuffersCount = inflightBuffersCount uniformsBuffers = [MTLBuffer]() for _ in 0...inflightBuffersCount-1 { let uniformsBuffer = device.makeBuffer(length: sizeOfUniformsBuffer, options: []) uniformsBuffers.append(uniformsBuffer) } } deinit{ for _ in 0...self.inflightBuffersCount{ self.avaliableResourcesSemaphore.signal() } } func nextUniformsBuffer(projectionMatrix: Matrix4, modelViewMatrix: Matrix4) -> MTLBuffer { // 1 let buffer = uniformsBuffers[avaliableBufferIndex] // 2 let bufferPointer = buffer.contents() // 3 memcpy(bufferPointer, modelViewMatrix.raw(), MemoryLayout<Float>.size*Matrix4.numberOfElements()) memcpy(bufferPointer + MemoryLayout<Float>.size*Matrix4.numberOfElements(), projectionMatrix.raw(), MemoryLayout<Float>.size*Matrix4.numberOfElements()) // 4 avaliableBufferIndex += 1 if avaliableBufferIndex == inflightBuffersCount{ avaliableBufferIndex = 0 } return buffer } }
mit
fefb280b4324efaa664eb24c78338385
25.213115
156
0.70419
4.454039
false
false
false
false
usbong/UsbongKit
UsbongKit/Usbong/UsbongAnswersGenerator.swift
2
7120
// // UsbongAnswersGenerator.swift // UsbongKit // // Created by Joe Amanse on 12/03/2016. // Copyright © 2016 Usbong Social Systems, Inc. All rights reserved. // import Foundation /// Generate answers based on `UsbongNodeState`s public protocol UsbongAnswersGenerator { associatedtype OutputType var states: [UsbongNodeState] { get } /// Create an instance of `UsbongAnswersGenerator` type init(states: [UsbongNodeState]) /// Generate output of type `OutputType` func generateOutput() -> OutputType /// Generate output of type `NSData` func generateOutputData() -> Data? } extension UsbongAnswersGenerator { func generateOutputData() -> Data? { return nil } } /// Generate answers to default CSV format open class UsbongAnswersGeneratorDefaultCSVString: UsbongAnswersGenerator { /// A collection of `UsbongNodeState`s that the output will be based upon open let states: [UsbongNodeState] /// Create an instance of `UsbongAnswersGeneratorDefaultCSVString` public required init(states: [UsbongNodeState]) { self.states = states } /// Generate an output of type `String` open func generateOutput() -> String { var finalString = "" for state in states { let transitionName = state.transitionName var currentEntry = ""; // Get first character of transition name or index let firstCharacter: String if let taskNodeType = state.taskNodeType { switch taskNodeType { case .RadioButtons, .Link: // Use selected index for first character let selectedIndex = (state.fields["selectedIndices"] as? [Int])?.first ?? 0 firstCharacter = String(selectedIndex) default: // By default, use first character of transition name firstCharacter = String(transitionName.characters.first ?? Character("")) } } else { // By default, use first character of transition name firstCharacter = String(transitionName.characters.first ?? Character("")) } // Add first character to current entry currentEntry += firstCharacter // Get additional fields for current entry if let taskNodeType = state.taskNodeType { switch taskNodeType { case .TextField, .TextFieldNumerical, .TextFieldWithUnit, .TextFieldWithAnswer, .TextArea, .TextAreaWithAnswer: // Get text input field let textInput = (state.fields["textInput"] as? String) ?? "" currentEntry += "," + textInput case .Date: let date = (state.fields["date"] as? Date) ?? Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" currentEntry += "," + dateFormatter.string(from: date) default: break } } // Add entry in final string finalString += currentEntry + ";" } return finalString } /// Generate an output of type `NSData` open func generateOutputData() -> Data? { let string = generateOutput() return string.data(using: String.Encoding.utf8) } } // Extend functionality of UsbongTree public extension UsbongTree { /** Generate output of current `UsbongNodeState`s - parameter generatorType: Type of an `UsbongAnswersGenerator` - returns: Generated answers of type `OutputType` */ func generateOutput<T: UsbongAnswersGenerator>(_ generatorType: T.Type) -> T.OutputType { return generatorType.init(states: usbongNodeStates).generateOutput() } /** Generate output of current `UsbongNodeState`s - parameter generatorType: Type of an `UsbongAnswersGenerator` - returns: Generated answers of type `NSData` */ func generateOutputData<T: UsbongAnswersGenerator>(_ generatorType: T.Type) -> Data? { return generatorType.init(states: usbongNodeStates).generateOutputData() } /** Write output of current `UsbongNodeState`s to file - parameters: - generatorType: Type of an `UsbongAnswersGenerator` - path: Where the output will be written - completion: Handler for when the writing completes, whether successful or not */ func writeOutputData<T: UsbongAnswersGenerator>(_ generatorType: T.Type, toFilePath path: String, completion: ((_ success: Bool) -> Void)?) { guard let data = generateOutputData(generatorType) else { completion?(false) return } let backgroundQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background) backgroundQueue.async { let writeSuccess = FileManager.default.createFile(atPath: path, contents: data, attributes: nil) DispatchQueue.main.async { completion?(writeSuccess) } } } /** Save output of current `UsbongNodeState`s to `Documents/Answers/{timeStamp}.csv` - parameters: - generatorType: Type of an `UsbongAnswersGenerator` - completion: Handler for when the writing completes, whether successful or not */ func saveOutputData<T: UsbongAnswersGenerator>(_ generatorType: T.Type, completion: ((_ success: Bool, _ filePath: String) -> Void)?) { let fileManager = FileManager.default let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) let documentsURL = urls[urls.count - 1] let answersURL = documentsURL.appendingPathComponent("Answers", isDirectory: true) var isDirectory: ObjCBool = false let fileExists = fileManager.fileExists(atPath: answersURL.path, isDirectory: &isDirectory) // If Answers directory doesn't exist (or it exists but not a directory), create directory if !fileExists || (fileExists && !isDirectory.boolValue) { do { try fileManager.createDirectory(at: answersURL, withIntermediateDirectories: true, attributes: nil) } catch { print("Failed to create Answers directory") } } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" let fileName = dateFormatter.string(from: Date()) + ".csv" let targetFilePath = answersURL.appendingPathComponent(fileName).path writeOutputData(generatorType, toFilePath: targetFilePath) { (success) -> Void in completion?(success, targetFilePath) } } }
apache-2.0
477eaf4f29877bb550b33c3270bb9828
36.078125
145
0.601068
5.114224
false
false
false
false
bastienFalcou/SoundWave
Example/SoundWave/AudioRecorderManager.swift
1
5108
// // AudioRecorderManager.swift // ela // // Created by Bastien Falcou on 4/14/16. // Copyright © 2016 Fueled. All rights reserved. // import Foundation import AVFoundation let audioPercentageUserInfoKey = "percentage" final class AudioRecorderManager: NSObject { let audioFileNamePrefix = "org.cocoapods.demo.SoundWave-Example-Audio-" let encoderBitRate: Int = 320000 let numberOfChannels: Int = 2 let sampleRate: Double = 44100.0 static let shared = AudioRecorderManager() var isPermissionGranted = false var isRunning: Bool { guard let recorder = self.recorder, recorder.isRecording else { return false } return true } var currentRecordPath: URL? private var recorder: AVAudioRecorder? private var audioMeteringLevelTimer: Timer? func askPermission(completion: ((Bool) -> Void)? = nil) { AVAudioSession.sharedInstance().requestRecordPermission { [weak self] granted in self?.isPermissionGranted = granted completion?(granted) print("Audio Recorder did not grant permission") } } func startRecording(with audioVisualizationTimeInterval: TimeInterval = 0.05, completion: @escaping (URL?, Error?) -> Void) { func startRecordingReturn() { do { completion(try internalStartRecording(with: audioVisualizationTimeInterval), nil) } catch { completion(nil, error) } } if !self.isPermissionGranted { self.askPermission { granted in startRecordingReturn() } } else { startRecordingReturn() } } fileprivate func internalStartRecording(with audioVisualizationTimeInterval: TimeInterval) throws -> URL { if self.isRunning { throw AudioErrorType.alreadyPlaying } let recordSettings = [ AVFormatIDKey: NSNumber(value:kAudioFormatAppleLossless), AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue, AVEncoderBitRateKey : self.encoderBitRate, AVNumberOfChannelsKey: self.numberOfChannels, AVSampleRateKey : self.sampleRate ] as [String : Any] guard let path = URL.documentsPath(forFileName: self.audioFileNamePrefix + NSUUID().uuidString) else { print("Incorrect path for new audio file") throw AudioErrorType.audioFileWrongPath } try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: .defaultToSpeaker) try AVAudioSession.sharedInstance().setActive(true) self.recorder = try AVAudioRecorder(url: path, settings: recordSettings) self.recorder!.delegate = self self.recorder!.isMeteringEnabled = true if !self.recorder!.prepareToRecord() { print("Audio Recorder prepare failed") throw AudioErrorType.recordFailed } if !self.recorder!.record() { print("Audio Recorder start failed") throw AudioErrorType.recordFailed } self.audioMeteringLevelTimer = Timer.scheduledTimer(timeInterval: audioVisualizationTimeInterval, target: self, selector: #selector(AudioRecorderManager.timerDidUpdateMeter), userInfo: nil, repeats: true) print("Audio Recorder did start - creating file at index: \(path.absoluteString)") self.currentRecordPath = path return path } func stopRecording() throws { self.audioMeteringLevelTimer?.invalidate() self.audioMeteringLevelTimer = nil if !self.isRunning { print("Audio Recorder did fail to stop") throw AudioErrorType.notCurrentlyPlaying } self.recorder!.stop() print("Audio Recorder did stop successfully") } func reset() throws { if self.isRunning { print("Audio Recorder tried to remove recording before stopping it") throw AudioErrorType.alreadyRecording } self.recorder?.deleteRecording() self.recorder = nil self.currentRecordPath = nil print("Audio Recorder did remove current record successfully") } @objc func timerDidUpdateMeter() { if self.isRunning { self.recorder!.updateMeters() let averagePower = recorder!.averagePower(forChannel: 0) let percentage: Float = pow(10, (0.05 * averagePower)) NotificationCenter.default.post(name: .audioRecorderManagerMeteringLevelDidUpdateNotification, object: self, userInfo: [audioPercentageUserInfoKey: percentage]) } } } extension AudioRecorderManager: AVAudioRecorderDelegate { func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { NotificationCenter.default.post(name: .audioRecorderManagerMeteringLevelDidFinishNotification, object: self) print("Audio Recorder finished successfully") } func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) { NotificationCenter.default.post(name: .audioRecorderManagerMeteringLevelDidFailNotification, object: self) print("Audio Recorder error") } } extension Notification.Name { static let audioRecorderManagerMeteringLevelDidUpdateNotification = Notification.Name("AudioRecorderManagerMeteringLevelDidUpdateNotification") static let audioRecorderManagerMeteringLevelDidFinishNotification = Notification.Name("AudioRecorderManagerMeteringLevelDidFinishNotification") static let audioRecorderManagerMeteringLevelDidFailNotification = Notification.Name("AudioRecorderManagerMeteringLevelDidFailNotification") }
mit
04d1711ae7f821adbd9ba25d3d12760c
31.528662
163
0.770511
4.298822
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Components/Views/UserCell.swift
1
12963
// // Wire // Copyright (C) 2018 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 UIKit import WireCommonComponents import WireSyncEngine extension UIImageView { func setUpIconImageView(accessibilityIdentifier: String? = nil) { translatesAutoresizingMaskIntoConstraints = false contentMode = .center self.accessibilityIdentifier = accessibilityIdentifier isHidden = true } } class UserCell: SeparatorCollectionViewCell, SectionListCellType { var hidesSubtitle: Bool = false typealias IconColors = SemanticColors.Icon let avatarSpacer = UIView() let avatar = BadgeUserImageView() let titleLabel = DynamicFontLabel(fontSpec: .normalLightFont, color: .textForeground) let subtitleLabel = DynamicFontLabel(fontSpec: .smallRegularFont, color: .sectionText) let connectButton = IconButton() let accessoryIconView = UIImageView() let userTypeIconView = IconImageView() let verifiedIconView = UIImageView() let videoIconView = IconImageView() let checkmarkIconView = UIImageView() let microphoneIconView = PulsingIconImageView() var contentStackView: UIStackView! var titleStackView: UIStackView! var iconStackView: UIStackView! fileprivate var avatarSpacerWidthConstraint: NSLayoutConstraint? weak var user: UserType? static let boldFont: FontSpec = .smallRegularFont static let lightFont: FontSpec = .smallLightFont static let defaultAvatarSpacing: CGFloat = 64 /// Specify a custom avatar spacing var avatarSpacing: CGFloat? { get { return avatarSpacerWidthConstraint?.constant } set { avatarSpacerWidthConstraint?.constant = newValue ?? UserCell.defaultAvatarSpacing } } var sectionName: String? var cellIdentifier: String? let iconColor = IconColors.foregroundDefault override var isSelected: Bool { didSet { checkmarkIconView.image = isSelected ? StyleKitIcon.checkmark.makeImage(size: 12, color: IconColors.foregroundCheckMarkSelected) : nil checkmarkIconView.backgroundColor = isSelected ? IconColors.backgroundCheckMarkSelected : IconColors.backgroundCheckMark checkmarkIconView.layer.borderColor = isSelected ? UIColor.clear.cgColor : IconColors.borderCheckMark.cgColor setupAccessibility() } } override var isHighlighted: Bool { didSet { backgroundColor = isHighlighted ? SemanticColors.View.backgroundUserCellHightLighted : SemanticColors.View.backgroundUserCell } } override func prepareForReuse() { super.prepareForReuse() UIView.performWithoutAnimation { hidesSubtitle = false userTypeIconView.isHidden = true verifiedIconView.isHidden = true videoIconView.isHidden = true microphoneIconView.isHidden = true connectButton.isHidden = true accessoryIconView.isHidden = true checkmarkIconView.image = nil checkmarkIconView.layer.borderColor = IconColors.borderCheckMark.cgColor checkmarkIconView.isHidden = true } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) guard previousTraitCollection?.userInterfaceStyle != traitCollection.userInterfaceStyle else { return } // Border colors are not dynamically updating for Dark Mode // When you use adaptive colors with CALayers you’ll notice that these colors, // are not updating when switching appearance live in the app. // That's why we use the traitCollectionDidChange(_:) method. checkmarkIconView.layer.borderColor = IconColors.borderCheckMark.cgColor } override func setUp() { super.setUp() backgroundColor = SemanticColors.View.backgroundUserCell userTypeIconView.setUpIconImageView() microphoneIconView.setUpIconImageView() videoIconView.setUpIconImageView() userTypeIconView.set(size: .tiny, color: iconColor) microphoneIconView.set(size: .tiny, color: iconColor) videoIconView.set(size: .tiny, color: iconColor) verifiedIconView.image = WireStyleKit.imageOfShieldverified verifiedIconView.setUpIconImageView(accessibilityIdentifier: "img.shield") connectButton.setIcon(.plusCircled, size: .tiny, for: .normal) connectButton.setIconColor(iconColor, for: .normal) connectButton.imageView?.contentMode = .center connectButton.isHidden = true checkmarkIconView.layer.borderWidth = 2 checkmarkIconView.contentMode = .center checkmarkIconView.layer.cornerRadius = 12 checkmarkIconView.backgroundColor = IconColors.backgroundCheckMark checkmarkIconView.isHidden = true accessoryIconView.setUpIconImageView() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.accessibilityIdentifier = "user_cell.name" titleLabel.applyStyle(.primaryCellLabel) subtitleLabel.translatesAutoresizingMaskIntoConstraints = false subtitleLabel.accessibilityIdentifier = "user_cell.username" subtitleLabel.applyStyle(.secondaryCellLabel) avatar.userSession = ZMUserSession.shared() avatar.initialsFont = .avatarInitial avatar.size = .small avatar.translatesAutoresizingMaskIntoConstraints = false avatarSpacer.addSubview(avatar) avatarSpacer.translatesAutoresizingMaskIntoConstraints = false iconStackView = UIStackView(arrangedSubviews: [videoIconView, microphoneIconView, userTypeIconView, verifiedIconView, connectButton, checkmarkIconView, accessoryIconView]) iconStackView.spacing = 16 iconStackView.axis = .horizontal iconStackView.distribution = .fill iconStackView.alignment = .center iconStackView.translatesAutoresizingMaskIntoConstraints = false iconStackView.setContentHuggingPriority(.required, for: .horizontal) titleStackView = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel]) titleStackView.axis = .vertical titleStackView.distribution = .equalSpacing titleStackView.alignment = .leading titleStackView.translatesAutoresizingMaskIntoConstraints = false contentStackView = UIStackView(arrangedSubviews: [avatarSpacer, titleStackView, iconStackView]) contentStackView.axis = .horizontal contentStackView.distribution = .fill contentStackView.alignment = .center contentStackView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(contentStackView) createConstraints() } private func createConstraints() { let avatarSpacerWidthConstraint = avatarSpacer.widthAnchor.constraint(equalToConstant: UserCell.defaultAvatarSpacing) self.avatarSpacerWidthConstraint = avatarSpacerWidthConstraint NSLayoutConstraint.activate([ checkmarkIconView.widthAnchor.constraint(equalToConstant: 24), checkmarkIconView.heightAnchor.constraint(equalToConstant: 24), avatar.widthAnchor.constraint(equalToConstant: 28), avatar.heightAnchor.constraint(equalToConstant: 28), avatarSpacerWidthConstraint, avatarSpacer.heightAnchor.constraint(equalTo: avatar.heightAnchor), avatarSpacer.centerXAnchor.constraint(equalTo: avatar.centerXAnchor), avatarSpacer.centerYAnchor.constraint(equalTo: avatar.centerYAnchor), contentStackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), contentStackView.topAnchor.constraint(equalTo: contentView.topAnchor), contentStackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), contentStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16) ]) } private func setupAccessibility() { typealias ContactsList = L10n.Accessibility.ContactsList typealias ServicesList = L10n.Accessibility.ServicesList typealias ClientsList = L10n.Accessibility.ClientsList typealias CreateConversation = L10n.Accessibility.CreateConversation guard let title = titleLabel.text, let subtitle = subtitleLabel.text else { isAccessibilityElement = false return } isAccessibilityElement = true accessibilityTraits = .button var content = "\(title), \(subtitle)" if let userType = userTypeIconView.accessibilityLabel, !userTypeIconView.isHidden { content += ", \(userType)" } if !verifiedIconView.isHidden { content += ", " + ClientsList.DeviceVerified.description } accessibilityLabel = content if !checkmarkIconView.isHidden { accessibilityHint = isSelected ? CreateConversation.SelectedUser.hint : CreateConversation.UnselectedUser.hint } else if let user = user, user.isServiceUser { accessibilityHint = ServicesList.ServiceCell.hint } else { accessibilityHint = ContactsList.UserCell.hint } } override func applyColorScheme(_ colorSchemeVariant: ColorSchemeVariant) { super.applyColorScheme(colorSchemeVariant) accessoryIconView.setTemplateIcon(.disclosureIndicator, size: 12) accessoryIconView.tintColor = IconColors.foregroundDefault updateTitleLabel() } private func updateTitleLabel(selfUser: UserType? = nil) { guard let user = user, let selfUser = selfUser else { return } var attributedTitle = user.nameIncludingAvailability( color: SemanticColors.Label.textCellTitle, selfUser: selfUser) if user.isSelfUser, let title = attributedTitle { attributedTitle = title + "user_cell.title.you_suffix".localized } titleLabel.attributedText = attributedTitle } func configure(with user: UserType, selfUser: UserType, subtitle overrideSubtitle: NSAttributedString? = nil, conversation: GroupDetailsConversationType? = nil) { let subtitle: NSAttributedString? if overrideSubtitle == nil { subtitle = self.subtitle(for: user) } else { subtitle = overrideSubtitle } self.user = user avatar.user = user updateTitleLabel(selfUser: selfUser) let style = UserTypeIconStyle(conversation: conversation, user: user, selfUser: selfUser) userTypeIconView.set(style: style) verifiedIconView.isHidden = !user.isVerified if let subtitle = subtitle, !subtitle.string.isEmpty, !hidesSubtitle { subtitleLabel.isHidden = false subtitleLabel.attributedText = subtitle } else { subtitleLabel.isHidden = true } setupAccessibility() } } // MARK: - Subtitle extension UserCell: UserCellSubtitleProtocol {} extension UserCell { func subtitle(for user: UserType) -> NSAttributedString? { if user.isServiceUser, let service = user as? SearchServiceUser { return subtitle(forServiceUser: service) } else { return subtitle(forRegularUser: user) } } private func subtitle(forServiceUser service: SearchServiceUser) -> NSAttributedString? { guard let summary = service.summary else { return nil } return summary && UserCell.boldFont.font! } static var correlationFormatters: [ColorSchemeVariant: AddressBookCorrelationFormatter] = [:] } // MARK: - Availability extension UserType { func nameIncludingAvailability(color: UIColor, selfUser: UserType) -> NSAttributedString? { if selfUser.isTeamMember { return AvailabilityStringBuilder.string(for: self, with: .list, color: color) } else if let name = name { return name && color } return nil } }
gpl-3.0
c7d23031887733cb6a5c078fb377f784
37.574405
179
0.694159
5.729885
false
false
false
false
3lvis/Formatter
Archived/Sources/CardExpirationDateFormatter.swift
1
879
public struct CardExpirationDateFormatter: Formattable { public init() { } public func formatString(_ string: String, reverse: Bool = false) -> String { var formattedString = String() let normalizedString = string.replacingOccurrences(of: "/", with: "") if reverse { formattedString = normalizedString } else { var idx = 0 var character: Character while idx < normalizedString.characters.count { let index = normalizedString.characters.index(normalizedString.startIndex, offsetBy: idx) character = normalizedString[index] formattedString.append(character) if idx == 1{ formattedString.append("/") } idx += 1 } } return formattedString } }
mit
46413cb0bc670e3c1ea97ae58eb20ba4
31.555556
105
0.557452
5.821192
false
false
false
false
danydev/DORateLimit
Tests/Tests/RateLimitTests.swift
1
10461
// // RateLimitTests.swift // RateLimit Tests // // Created by Daniele Orrù on 31/10/15. // Copyright © 2015 Daniele Orru'. All rights reserved. // import XCTest class RateLimitTests: XCTestCase { func testDebounceTriggersOnceWhenContinuoslyCalledBeforeThreshold() { let threshold = 1.0 var closureCallsCount = 0 let readyExpectation = expectation(description: "ready") let startTimestamp = Date().timeIntervalSince1970 var currentTimestamp = Date().timeIntervalSince1970 while((currentTimestamp - startTimestamp) < threshold - 0.5) { // Action: Call debounce multiple times for (threshold - 0.5) seconds RateLimit.debounce("debounceKey_t1", threshold: threshold) { closureCallsCount += 1 } currentTimestamp = Date().timeIntervalSince1970 } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64((threshold + 0.5) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // Expectation: The closure has been called just 1 time XCTAssertEqual(1, closureCallsCount) readyExpectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testDebounceTriggersOnceWhenContinuoslyCalledAfterThreshold() { let threshold = 1.0 var closureCallsCount = 0 let readyExpectation = expectation(description: "ready") let startTimestamp = Date().timeIntervalSince1970 var currentTimestamp = Date().timeIntervalSince1970 while((currentTimestamp - startTimestamp) < threshold + 0.5) { // Action: Call debounce multiple times for (threshold + 0.5) seconds RateLimit.debounce("debounceKey_t2", threshold: threshold) { closureCallsCount += 1 } currentTimestamp = Date().timeIntervalSince1970 } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64((threshold + 0.5) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // Expectation: The closure has been called just 1 time XCTAssertEqual(1, closureCallsCount) readyExpectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testDebounceTriggersWhenCalledAfterThreshold() { let threshold = 1.0 var closureCallsCount = 0 let readyExpectation = expectation(description: "ready") let callThrottle = { RateLimit.debounce("debounceKey_t3", threshold: threshold) { closureCallsCount += 1 } } // Action: Call the closure 1 time callThrottle() // Action: Call again the closure after *waiting* (threshold + 0.5) seconds DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64((threshold + 0.5) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { callThrottle() // Expectation: The closure has been called 2 times XCTAssertEqual(2, closureCallsCount) readyExpectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testDebounceRespectsTriggerAtBeginDisabled() { let threshold = 1.0 var closureCallsCount = 0 let readyExpectation = expectation(description: "ready") // Action: debounce with atBegin false RateLimit.debounce("debounceKey_t4", threshold: threshold, atBegin: false) { closureCallsCount += 1 } // Expectation: Closure should have NOT been called at this time XCTAssertEqual(0, closureCallsCount) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64((threshold + 0.5) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // Expectation: After (threshold + 0.5) seconds, the closure has been called XCTAssertEqual(1, closureCallsCount) readyExpectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testDebounceRespectsTriggerAtBeginEnabled() { let threshold = 1.0 var closureCallsCount = 0 // Action: debounce with atBegin true RateLimit.debounce("debounceKey_t5", threshold: threshold) { closureCallsCount += 1 } // Expectation: Closure should have been immediately called XCTAssertEqual(1, closureCallsCount) } func testDebounceRespectsDifferentKeys() { let threshold = 1.0 var closureCallsCount = 0 // Action: call debounce twice with different keys RateLimit.debounce("debounceKey_t6_1", threshold: threshold) { closureCallsCount += 1 } RateLimit.debounce("debounceKey_t6_2", threshold: threshold) { closureCallsCount += 1 } // Expectation: Closure should have been called 1 time each XCTAssertEqual(2, closureCallsCount) } func testThrottleIgnoresTriggerWhenContinuoslyCalledBeforeThreshold() { let threshold = 1.0 var closureCallsCount = 0 let readyExpectation = expectation(description: "ready") let startTimestamp = Date().timeIntervalSince1970 var currentTimestamp = Date().timeIntervalSince1970 while((currentTimestamp - startTimestamp) < threshold - 0.5) { // Action: Call throttle multiple times for (threshold - 0.5) seconds RateLimit.throttle("throttleKey_t1", threshold: threshold) { closureCallsCount += 1 } currentTimestamp = Date().timeIntervalSince1970 } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64((threshold + 0.5) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // Expectation: The closure has been called 1 time XCTAssertEqual(1, closureCallsCount) readyExpectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testThrottleTriggersWhenContinuoslyCalledAfterThreshold() { let threshold = 1.0 var closureCallsCount = 0 let readyExpectation = expectation(description: "ready") let startTimestamp = Date().timeIntervalSince1970 var currentTimestamp = Date().timeIntervalSince1970 while((currentTimestamp - startTimestamp) < threshold + 0.5) { // Action: Call throttle continuosly for (threshold + 0.5) seconds RateLimit.throttle("throttleKey_t2", threshold: threshold) { closureCallsCount += 1 } currentTimestamp = Date().timeIntervalSince1970 } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64((threshold + 0.5) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // Expectation: Closure should have been called 2 times XCTAssertEqual(2, closureCallsCount) readyExpectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testThrottleAllowsTriggerAfterThreshold() { let threshold = 1.0 var closureCallsCount = 0 let readyExpectation = expectation(description: "ready") let callThrottle = { RateLimit.throttle("throttleKey_t3", threshold: threshold) { closureCallsCount += 1 } } // Action: Call the closure 1 time callThrottle() // Action: Call again the closure after *waiting* (threshold + 0.5) seconds DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64((threshold + 0.5) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { callThrottle() // Expectation: The closure has been called 2 times XCTAssertEqual(2, closureCallsCount) readyExpectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testThrottleRespectsTrailingEnabled() { let threshold = 1.0 var closureCallsCount = 0 let readyExpectation = expectation(description: "ready") // Action: Call throttle twice for _ in 1...2 { RateLimit.throttle("throttleKey_t4", threshold: threshold, trailing: true) { closureCallsCount += 1 } } // Expectation: Closure should have been called 1 time at this point XCTAssertEqual(1, closureCallsCount) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64((threshold + 0.5) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // Expectation: Trailing is enabled, that means that another trailing closure trigger should have been performed at this point XCTAssertEqual(2, closureCallsCount) readyExpectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testThrottleRespectsTrailingDisabled() { let threshold = 1.0 var closureCallsCount = 0 let readyExpectation = expectation(description: "ready") // Action: Call throttle twice for _ in 1...2 { RateLimit.throttle("throttleKey_t5", threshold: threshold) { closureCallsCount += 1 } } // Expectation: The closure has been already called 1 time at this point XCTAssertEqual(1, closureCallsCount) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64((threshold + 0.5) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // Expectation: Trailing is disabled, the closure should haven't been called more than once XCTAssertEqual(1, closureCallsCount) readyExpectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testThrottleRespectsDifferentKeys() { let threshold = 1.0 var closureCallsCount = 0 // Action: call debounce twice with different keys RateLimit.throttle("throttleKey_t6_1", threshold: threshold) { closureCallsCount += 1 } RateLimit.throttle("throttleKey_t6_2", threshold: threshold) { closureCallsCount += 1 } // Expectation: Closure should have been called 1 time each XCTAssertEqual(2, closureCallsCount) } }
mit
d6763600ec3bfb7978930f66603f3726
35.065517
150
0.630557
4.935819
false
true
false
false
ioveracker/Tycoon
Tycoon/NewItemViewController.swift
1
11348
import Eureka import RealmSwift class NewItemViewController: FormViewController { var item: Item! var editingItem = false var notificationToken: NotificationToken? @IBAction func cancelButtonTapped(_ sender: UIBarButtonItem) { // Only delete the item on cancel if this is the first time the item is being added, not // when it is being edited. if !editingItem { item.delete() } dismiss() } struct RowTags { static let description = "description" static let brand = "brand" static let size = "size" static let cost = "cost" static let dateListed = "dateListed" static let listPrice = "listPrice" static let shippingCost = "shippingCost" static let suppliesCost = "suppliesCost" static let breakEven = "breakEven" static let fee = "fee" static let profit = "profit" static let sold = "sold" } override func viewDidLoad() { super.viewDidLoad() if item != nil { editingItem = true title = "Edit Item" } else { item = Item() let realm = try! Realm() try! realm.write { realm.add(item) } } form +++ Section("Image") <<< ItemImageRow() { row in }.onCellSelection() { cell, row in let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = true alert.addAction(UIAlertAction(title: "Take New Photo", style: .default) { _ in imagePicker.sourceType = .camera imagePicker.cameraCaptureMode = .photo self.present(imagePicker, animated: true) }) alert.addAction(UIAlertAction(title: "Choose From Camera Roll", style: .default) { _ in imagePicker.sourceType = .photoLibrary self.present(imagePicker, animated: true) }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) self.present(alert, animated: true) }.cellUpdate() { cell, row in cell.itemImageView.image = UIImage(contentsOfFile: self.item.imagePath) cell.tapToAddPhotoLabel.isHidden = cell.itemImageView.image != nil } +++ Section("Item Details") <<< TextRow() { row in row.title = "Description" row.placeholder = "Cute T-Rex Sweater" row.tag = RowTags.description if item.itemDescription.characters.count > 0 { row.value = item.itemDescription } }.onChange { row in if let value = row.value { let realm = try! Realm() try! realm.write { self.item.itemDescription = value } } } <<< TextRow() { row in row.title = "Brand" row.placeholder = "Carters" row.tag = RowTags.brand if item.brand.characters.count > 0 { row.value = item.brand } }.onChange { row in if let value = row.value { try! Realm().write { self.item.brand = value } } } <<< TextRow() { row in row.title = "Size" row.placeholder = "2T" row.tag = RowTags.size if item.size.characters.count > 0 { row.value = item.size } }.onChange { row in if let value = row.value { try! Realm().write { self.item.size = value } } } <<< DateInlineRow() { row in row.title = "Date Listed" row.tag = RowTags.dateListed row.value = item.dateListed }.onChange { row in if let value = row.value { try! Realm().write { self.item.dateListed = value } } } <<< SwitchRow() { row in row.title = "Sold?" row.tag = RowTags.sold if let item = item { row.value = item.sold } }.onChange { row in if let value = row.value { try! Realm().write { self.item.sold = value } } } +++ Section("Costs") <<< DecimalRow() { row in row.title = "Item Cost" row.tag = RowTags.cost if let value = item.cost.value { row.value = value } }.onChange { row in let value = row.value ?? 0.0 try! Realm().write { self.item.cost.value = value } } <<< DecimalRow() { row in row.title = "Shipping" row.tag = RowTags.shippingCost if let value = item.shippingCost.value { row.value = value } }.onChange { row in let value = row.value ?? 0.0 try! Realm().write { self.item.shippingCost.value = value } } <<< DecimalRow() { row in row.title = "Supplies" row.tag = RowTags.suppliesCost if let value = item.suppliesCost.value { row.value = value } }.onChange { row in let value = row.value ?? 0.0 try! Realm().write { self.item.suppliesCost.value = value } } +++ Section("Pricing") <<< LabelRow() { row in row.title = "Break Even At" row.tag = RowTags.breakEven row.value = self.item.breakEven.presentableString }.cellUpdate { cell, row in row.value = self.item.breakEven.presentableString cell.update() } <<< DecimalRow() { row in row.title = "List Price" row.tag = RowTags.listPrice if let value = item.listPrice.value { row.value = value } }.onChange { row in let value = row.value ?? 0.0 try! Realm().write { self.item.listPrice.value = value } } <<< LabelRow() { row in row.title = "Kidizen Fee" row.tag = RowTags.fee row.value = self.item.fee.presentableString }.cellUpdate { cell, row in row.value = self.item.fee.presentableString cell.update() } <<< LabelRow() { row in row.title = "Profit" row.tag = RowTags.profit row.value = self.item.profit.presentableString }.cellUpdate { cell, row in row.value = self.item.profit.presentableString cell.update() } +++ Section() <<< ButtonRow() { row in row.title = item == nil ? "Add" : "Save" }.onCellSelection() { (buttonCell, buttonRow) in self.dismiss() } +++ Section() <<< ButtonRow() { row in row.title = "Delete" row.cell.tintColor = UIColor.red row.tag = "delete" row.hidden = Condition.function([]) { form in return !self.editingItem } }.onCellSelection() { (cell, row) in let alert = UIAlertController( title: "Do you want to delete this item?", message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil)) alert.addAction(UIAlertAction(title: "Yes", style: .destructive) { _ in self.item.delete() self.dismiss() }) self.present(alert, animated: true, completion: nil) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) notificationToken = try! Realm().addNotificationBlock() { _, _ in if self.item.isInvalidated { return } DispatchQueue.main.async { if let profitRow = self.form.rowBy(tag: RowTags.profit) as? LabelRow { profitRow.updateCell() } if let feeRow = self.form.rowBy(tag: RowTags.fee) as? LabelRow { feeRow.updateCell() } if let breakEvenRow = self.form.rowBy(tag: RowTags.breakEven) as? LabelRow { breakEvenRow.updateCell() } if let deleteRow = self.form.rowBy(tag: "delete") as? ButtonRow { deleteRow.updateCell() } } } } override func viewWillDisappear(_ animated: Bool) { notificationToken?.stop() notificationToken = nil super.viewWillDisappear(animated) } } extension NewItemViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { var imageMaybe: UIImage? if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage { imageMaybe = editedImage } else if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage { imageMaybe = originalImage } guard let image = imageMaybe else { return } try! UIImagePNGRepresentation(image)?.write(to: item.imageURL, options: .atomic) dismiss(animated: true) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true) } } fileprivate extension NewItemViewController { func dismiss(then: (() -> Void)? = nil) { presentingViewController?.dismiss(animated: true, completion: then) } } extension Double { static let numberFormatter = NumberFormatter() var presentableString: String { Double.numberFormatter.numberStyle = .currency return Double.numberFormatter.string(from: self as NSNumber) ?? "" } }
mit
8f5c6009de16791549174af073925231
32.573964
119
0.475502
5.261011
false
false
false
false
Nyx0uf/MPDRemote
src/iOS/controllers/PlaylistDetailVC.swift
1
13015
// PlaylistDetailVC.swift // Copyright (c) 2017 Nyx0uf // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit final class PlaylistDetailVC : UIViewController { // MARK: - Public properties // Selected album var playlist: Playlist // MARK: - Private properties // Header view (cover + album name, artist) @IBOutlet private var headerView: UIImageView! = nil // Header height constraint @IBOutlet private var headerHeightConstraint: NSLayoutConstraint! = nil // Dummy view for shadow @IBOutlet private var dummyView: UIView! = nil // Tableview for song list @IBOutlet private var tableView: TracksListTableView! = nil // Underlaying color view @IBOutlet private var colorView: UIView! = nil // Label in the navigationbar private var titleView: UILabel! = nil // Random button private var btnRandom: UIBarButtonItem! = nil // Repeat button private var btnRepeat: UIBarButtonItem! = nil // MARK: - Initializers required init?(coder aDecoder: NSCoder) { // Dummy self.playlist = Playlist(name: "") super.init(coder: aDecoder) } // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() // Navigation bar title titleView = UILabel(frame: CGRect(.zero, 100.0, 44.0)) titleView.numberOfLines = 2 titleView.textAlignment = .center titleView.isAccessibilityElement = false titleView.textColor = #colorLiteral(red: 0.1298420429, green: 0.1298461258, blue: 0.1298439503, alpha: 1) navigationItem.titleView = titleView // Album header view let coverSize = NSKeyedUnarchiver.unarchiveObject(with: Settings.shared.data(forKey: kNYXPrefCoversSize)!) as! NSValue headerHeightConstraint.constant = coverSize.cgSizeValue.height // Dummy tableview host, to create a nice shadow effect dummyView.layer.shadowPath = UIBezierPath(rect: CGRect(-2.0, 5.0, view.width + 4.0, 4.0)).cgPath dummyView.layer.shadowRadius = 3.0 dummyView.layer.shadowOpacity = 1.0 dummyView.layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor dummyView.layer.masksToBounds = false // Tableview tableView.useDummy = true tableView.tableFooterView = UIView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Add navbar shadow if let navigationBar = navigationController?.navigationBar { navigationBar.layer.shadowPath = UIBezierPath(rect: CGRect(-2.0, navigationBar.frame.height - 2.0, navigationBar.frame.width + 4.0, 4.0)).cgPath navigationBar.layer.shadowRadius = 3.0 navigationBar.layer.shadowOpacity = 1.0 navigationBar.layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor navigationBar.layer.masksToBounds = false let loop = Settings.shared.bool(forKey: kNYXPrefMPDRepeat) btnRepeat = UIBarButtonItem(image: #imageLiteral(resourceName: "btn-repeat").withRenderingMode(.alwaysTemplate), style: .plain, target: self, action: #selector(toggleRepeatAction(_:))) btnRepeat.tintColor = loop ? #colorLiteral(red: 0.004859850742, green: 0.09608627111, blue: 0.5749928951, alpha: 1) : #colorLiteral(red: 0, green: 0.5898008943, blue: 1, alpha: 1) btnRepeat.accessibilityLabel = NYXLocalizedString(loop ? "lbl_repeat_disable" : "lbl_repeat_enable") let rand = Settings.shared.bool(forKey: kNYXPrefMPDShuffle) btnRandom = UIBarButtonItem(image: #imageLiteral(resourceName: "btn-random").withRenderingMode(.alwaysTemplate), style: .plain, target: self, action: #selector(toggleRandomAction(_:))) btnRandom.tintColor = rand ? #colorLiteral(red: 0.004859850742, green: 0.09608627111, blue: 0.5749928951, alpha: 1) : #colorLiteral(red: 0, green: 0.5898008943, blue: 1, alpha: 1) btnRandom.accessibilityLabel = NYXLocalizedString(rand ? "lbl_random_disable" : "lbl_random_enable") navigationItem.rightBarButtonItems = [btnRandom, btnRepeat] } // Update header updateHeader() // Get songs list if needed if let tracks = playlist.tracks { updateNavigationTitle() tableView.tracks = tracks } else { MusicDataSource.shared.getTracksForPlaylist(playlist) { DispatchQueue.main.async { self.updateNavigationTitle() self.tableView.tracks = self.playlist.tracks! } } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Remove navbar shadow if let navigationBar = navigationController?.navigationBar { navigationBar.layer.shadowPath = nil navigationBar.layer.shadowRadius = 0.0 navigationBar.layer.shadowOpacity = 0.0 } } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } override var preferredStatusBarStyle: UIStatusBarStyle { return .default } // MARK: - Private private func updateHeader() { // Update header view let backgroundColor = UIColor(rgb: playlist.name.djb2()) headerView.backgroundColor = backgroundColor colorView.backgroundColor = backgroundColor if let img = generateCoverFromString(playlist.name, size: headerView.size) { headerView.image = img } } private func updateNavigationTitle() { if let tracks = playlist.tracks { let total = tracks.reduce(Duration(seconds: 0)){$0 + $1.duration} let minutes = total.seconds / 60 let attrs = NSMutableAttributedString(string: "\(tracks.count) \(tracks.count == 1 ? NYXLocalizedString("lbl_track") : NYXLocalizedString("lbl_tracks"))\n", attributes:[NSAttributedStringKey.font : UIFont(name: "HelveticaNeue-Medium", size: 14.0)!]) attrs.append(NSAttributedString(string: "\(minutes) \(minutes == 1 ? NYXLocalizedString("lbl_minute") : NYXLocalizedString("lbl_minutes"))", attributes: [NSAttributedStringKey.font : UIFont(name: "HelveticaNeue", size: 13.0)!])) titleView.attributedText = attrs } } private func renamePlaylistAction() { let alertController = UIAlertController(title: "\(NYXLocalizedString("lbl_rename_playlist")) \(playlist.name)", message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NYXLocalizedString("lbl_save"), style: .default, handler: { alert -> Void in let textField = alertController.textFields![0] as UITextField if String.isNullOrWhiteSpace(textField.text) { let errorAlert = UIAlertController(title: NYXLocalizedString("lbl_error"), message: NYXLocalizedString("lbl_playlist_create_emptyname"), preferredStyle: .alert) errorAlert.addAction(UIAlertAction(title: NYXLocalizedString("lbl_ok"), style: .cancel, handler: { alert -> Void in })) self.present(errorAlert, animated: true, completion: nil) } else { MusicDataSource.shared.renamePlaylist(playlist: self.playlist, newName: textField.text!) { (result: ActionResult<Void>) in if result.succeeded { MusicDataSource.shared.getListForDisplayType(.playlists) { DispatchQueue.main.async { self.updateNavigationTitle() } } } else { DispatchQueue.main.async { MessageView.shared.showWithMessage(message: result.messages.first!) } } } } })) alertController.addAction(UIAlertAction(title: NYXLocalizedString("lbl_cancel"), style: .cancel, handler: nil)) alertController.addTextField(configurationHandler: { (textField) -> Void in textField.placeholder = NYXLocalizedString("lbl_rename_playlist_placeholder") textField.textAlignment = .left }) self.present(alertController, animated: true, completion: nil) } // MARK: - Buttons actions @objc func toggleRandomAction(_ sender: Any?) { let prefs = Settings.shared let random = !prefs.bool(forKey: kNYXPrefMPDShuffle) btnRandom.tintColor = random ? #colorLiteral(red: 0.004859850742, green: 0.09608627111, blue: 0.5749928951, alpha: 1) : #colorLiteral(red: 0, green: 0.5898008943, blue: 1, alpha: 1) btnRandom.accessibilityLabel = NYXLocalizedString(random ? "lbl_random_disable" : "lbl_random_enable") prefs.set(random, forKey: kNYXPrefMPDShuffle) prefs.synchronize() PlayerController.shared.setRandom(random) } @objc func toggleRepeatAction(_ sender: Any?) { let prefs = Settings.shared let loop = !prefs.bool(forKey: kNYXPrefMPDRepeat) btnRepeat.tintColor = loop ? #colorLiteral(red: 0.004859850742, green: 0.09608627111, blue: 0.5749928951, alpha: 1) : #colorLiteral(red: 0, green: 0.5898008943, blue: 1, alpha: 1) btnRepeat.accessibilityLabel = NYXLocalizedString(loop ? "lbl_repeat_disable" : "lbl_repeat_enable") prefs.set(loop, forKey: kNYXPrefMPDRepeat) prefs.synchronize() PlayerController.shared.setRepeat(loop) } } // MARK: - UITableViewDelegate extension PlaylistDetailVC : UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: { tableView.deselectRow(at: indexPath, animated: true) }) // Dummy cell guard let tracks = playlist.tracks else {return} if indexPath.row >= tracks.count { return } // Toggle play / pause for the current track if let currentPlayingTrack = PlayerController.shared.currentTrack { let selectedTrack = tracks[indexPath.row] if selectedTrack == currentPlayingTrack { PlayerController.shared.togglePause() return } } PlayerController.shared.playPlaylist(playlist, shuffle: Settings.shared.bool(forKey: kNYXPrefMPDShuffle), loop: Settings.shared.bool(forKey: kNYXPrefMPDRepeat), position: UInt32(indexPath.row)) } @available(iOS 11.0, *) func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { // Dummy cell guard let tracks = playlist.tracks else { return nil } if indexPath.row >= tracks.count { return nil } let action = UIContextualAction(style: .normal, title: NYXLocalizedString("lbl_remove_from_playlist"), handler: { (action, view, completionHandler ) in MusicDataSource.shared.removeTrackFromPlaylist(playlist: self.playlist, track: tracks[indexPath.row]) { (result: ActionResult<Void>) in if result.succeeded == false { DispatchQueue.main.async { MessageView.shared.showWithMessage(message: result.messages.first!) } } else { MusicDataSource.shared.getTracksForPlaylist(self.playlist) { DispatchQueue.main.async { self.updateNavigationTitle() self.tableView.tracks = self.playlist.tracks! } } } } completionHandler(true) }) action.image = #imageLiteral(resourceName: "btn-trash") action.backgroundColor = #colorLiteral(red: 0, green: 0.5898008943, blue: 1, alpha: 1) return UISwipeActionsConfiguration(actions: [action]) } } // MARK: - Peek & Pop extension PlaylistDetailVC { override var previewActionItems: [UIPreviewActionItem] { let playAction = UIPreviewAction(title: NYXLocalizedString("lbl_play"), style: .default) { (action, viewController) in PlayerController.shared.playPlaylist(self.playlist, shuffle: false, loop: false) MiniPlayerView.shared.stayHidden = false } let shuffleAction = UIPreviewAction(title: NYXLocalizedString("lbl_alert_playalbum_shuffle"), style: .default) { (action, viewController) in PlayerController.shared.playPlaylist(self.playlist, shuffle: true, loop: false) MiniPlayerView.shared.stayHidden = false } let renameAction = UIPreviewAction(title: NYXLocalizedString("lbl_rename_playlisr"), style: .default) { (action, viewController) in self.renamePlaylistAction() MiniPlayerView.shared.stayHidden = false } let deleteAction = UIPreviewAction(title: NYXLocalizedString("lbl_delete_playlist"), style: .destructive) { (action, viewController) in MusicDataSource.shared.deletePlaylist(name: self.playlist.name) { (result: ActionResult<Void>) in if result.succeeded == false { MessageView.shared.showWithMessage(message: result.messages.first!) } } MiniPlayerView.shared.stayHidden = false } return [playAction, shuffleAction, renameAction, deleteAction] } }
mit
0e4f5153003c6cf4f5e4c1ccfb4a5103
35.456583
252
0.73738
3.786733
false
false
false
false
BluefinSolutions/ODataParser
ODataParser/ODataServiceManager.swift
1
3175
// // ODataServiceManager.swift // Demo Jam // // Created by Brenton O'Callaghan on 09/10/2014. // Completely open source without any warranty to do with what you like :-) // import Foundation class ODataServiceManager: NSObject, ODataCollectionDelegate{ internal var _entitiesAvailable: NSMutableArray = NSMutableArray() internal var _collectionListLoaded: Bool = false; // The local oData requestor. internal var _oDataRequester: ODataCollectionManager? // Callsback to the passed in function with a list of the available collections in the oData service. class func getCollectionList() -> NSMutableArray{ // This would be so much better as a class variable with async calls but Swift does not // support class variables yet :-( /*var serviceManager: ODataServiceManager = ODataServiceManager() serviceManager._oDataRequester?.makeRequestToCollection(OdataFilter()) while (!serviceManager._collectionListLoaded){ sleep(1) } return serviceManager._entitiesAvailable*/ return NSMutableArray() } // Create a collection manager object used to make all the requests to a particular collection. class func createCollectionManagerForCollection(collectionName:NSString, andDelegate:ODataCollectionDelegate) -> ODataCollectionManager{ // New instance of a collection. var newCollectionManager: ODataCollectionManager = ODataCollectionManager(); // Set the delegate and the collection name. newCollectionManager.setDelegate(andDelegate) newCollectionManager.setCollectionName(collectionName) // Return to the user :-) return newCollectionManager } // ====================================================================== // MARK: - Internal Private instance methods. // ====================================================================== override init() { // Always do the super. super.init() // Create an odata request to the service with no specific collection. self._oDataRequester = ODataServiceManager.createCollectionManagerForCollection("", andDelegate: self) } func didRecieveResponse(results: NSDictionary){ let queryDictionary = results.objectForKey("d") as NSMutableDictionary let queryResults = queryDictionary.objectForKey("EntitySets") as NSMutableArray for singleResult in queryResults{ // Create and initialise the new entity object. self._entitiesAvailable.addObject(singleResult as NSString) } // Very important if we want to exit the infinite loop above! // There has to be a better way to do this!!! :) self._collectionListLoaded = true } func requestFailedWithError(error: NSString){ println("=== ERROR ERROR ERROR ===") println("Unable to request entity listing from OData service - is it an odata server??") println("Error: " + error) } }
apache-2.0
6077b41715c584f28e7266ca463a32ac
35.505747
140
0.630866
5.541012
false
false
false
false
LoopKit/LoopKit
LoopKitTests/SettingsStoreTests.swift
1
43109
// // SettingsStoreTests.swift // LoopKitTests // // Created by Darin Krauss on 1/2/20. // Copyright © 2020 LoopKit Authors. All rights reserved. // import XCTest import HealthKit @testable import LoopKit class SettingsStorePersistenceTests: PersistenceControllerTestCase, SettingsStoreDelegate { var settingsStore: SettingsStore! override func setUp() { super.setUp() settingsStoreHasUpdatedSettingsDataHandler = nil settingsStore = SettingsStore(store: cacheStore, expireAfter: .hours(1)) settingsStore.delegate = self } override func tearDown() { settingsStore.delegate = nil settingsStore = nil settingsStoreHasUpdatedSettingsDataHandler = nil super.tearDown() } // MARK: - SettingsStoreDelegate var settingsStoreHasUpdatedSettingsDataHandler: ((_ : SettingsStore) -> Void)? func settingsStoreHasUpdatedSettingsData(_ settingsStore: SettingsStore) { settingsStoreHasUpdatedSettingsDataHandler?(settingsStore) } // MARK: - func testStoreSettings() { let storeSettingsHandler = expectation(description: "Store settings handler") let storeSettingsCompletion = expectation(description: "Store settings completion") var handlerInvocation = 0 settingsStoreHasUpdatedSettingsDataHandler = { settingsStore in handlerInvocation += 1 switch handlerInvocation { case 1: storeSettingsHandler.fulfill() default: XCTFail("Unexpected handler invocation") } } settingsStore.storeSettings(StoredSettings()) { _ in storeSettingsCompletion.fulfill() } wait(for: [storeSettingsHandler, storeSettingsCompletion], timeout: 2, enforceOrder: true) } func testStoreSettingsMultiple() { let storeSettingsHandler1 = expectation(description: "Store settings handler 1") let storeSettingsHandler2 = expectation(description: "Store settings handler 2") let storeSettingsCompletion1 = expectation(description: "Store settings completion 1") let storeSettingsCompletion2 = expectation(description: "Store settings completion 2") var handlerInvocation = 0 settingsStoreHasUpdatedSettingsDataHandler = { settingsStore in handlerInvocation += 1 switch handlerInvocation { case 1: storeSettingsHandler1.fulfill() case 2: storeSettingsHandler2.fulfill() default: XCTFail("Unexpected handler invocation") } } settingsStore.storeSettings(StoredSettings()) { _ in storeSettingsCompletion1.fulfill() } settingsStore.storeSettings(StoredSettings()) { _ in storeSettingsCompletion2.fulfill() } wait(for: [storeSettingsHandler1, storeSettingsCompletion1, storeSettingsHandler2, storeSettingsCompletion2], timeout: 2, enforceOrder: true) } // MARK: - func testSettingsObjectEncodable() throws { cacheStore.managedObjectContext.performAndWait { do { let object = SettingsObject(context: cacheStore.managedObjectContext) object.data = try PropertyListEncoder().encode(StoredSettings.test) object.date = dateFormatter.date(from: "2100-01-02T03:03:00Z")! object.modificationCounter = 123 try assertSettingsObjectEncodable(object, encodesJSON: """ { "data" : { "automaticDosingStrategy" : 1, "basalRateSchedule" : { "items" : [ { "startTime" : 0, "value" : 1 }, { "startTime" : 21600, "value" : 1.5 }, { "startTime" : 64800, "value" : 1.25 } ], "referenceTimeInterval" : 0, "repeatInterval" : 86400, "timeZone" : { "identifier" : "GMT-0700" } }, "bloodGlucoseUnit" : "mg/dL", "carbRatioSchedule" : { "unit" : "g", "valueSchedule" : { "items" : [ { "startTime" : 0, "value" : 15 }, { "startTime" : 32400, "value" : 14 }, { "startTime" : 72000, "value" : 18 } ], "referenceTimeInterval" : 0, "repeatInterval" : 86400, "timeZone" : { "identifier" : "GMT-0700" } } }, "cgmDevice" : { "firmwareVersion" : "CGM Firmware Version", "hardwareVersion" : "CGM Hardware Version", "localIdentifier" : "CGM Local Identifier", "manufacturer" : "CGM Manufacturer", "model" : "CGM Model", "name" : "CGM Name", "softwareVersion" : "CGM Software Version", "udiDeviceIdentifier" : "CGM UDI Device Identifier" }, "controllerDevice" : { "model" : "Controller Model", "modelIdentifier" : "Controller Model Identifier", "name" : "Controller Name", "systemName" : "Controller System Name", "systemVersion" : "Controller System Version" }, "controllerTimeZone" : { "identifier" : "America/Los_Angeles" }, "date" : "2020-05-14T22:48:15Z", "defaultRapidActingModel" : { "actionDuration" : 21600, "delay" : 600, "modelType" : "rapidAdult", "peakActivity" : 10800 }, "deviceToken" : "Device Token String", "dosingEnabled" : true, "glucoseTargetRangeSchedule" : { "override" : { "end" : "2020-05-14T14:48:15Z", "start" : "2020-05-14T12:48:15Z", "value" : { "maxValue" : 115, "minValue" : 105 } }, "rangeSchedule" : { "unit" : "mg/dL", "valueSchedule" : { "items" : [ { "startTime" : 0, "value" : { "maxValue" : 110, "minValue" : 100 } }, { "startTime" : 25200, "value" : { "maxValue" : 100, "minValue" : 90 } }, { "startTime" : 75600, "value" : { "maxValue" : 120, "minValue" : 110 } } ], "referenceTimeInterval" : 0, "repeatInterval" : 86400, "timeZone" : { "identifier" : "GMT-0700" } } } }, "insulinSensitivitySchedule" : { "unit" : "mg/dL", "valueSchedule" : { "items" : [ { "startTime" : 0, "value" : 45 }, { "startTime" : 10800, "value" : 40 }, { "startTime" : 54000, "value" : 50 } ], "referenceTimeInterval" : 0, "repeatInterval" : 86400, "timeZone" : { "identifier" : "GMT-0700" } } }, "insulinType" : 1, "maximumBasalRatePerHour" : 3.5, "maximumBolus" : 10, "notificationSettings" : { "alertSetting" : "disabled", "alertStyle" : "banner", "announcementSetting" : "enabled", "authorizationStatus" : "authorized", "badgeSetting" : "enabled", "carPlaySetting" : "notSupported", "criticalAlertSetting" : "enabled", "lockScreenSetting" : "disabled", "notificationCenterSetting" : "notSupported", "providesAppNotificationSettings" : true, "scheduledDeliverySetting" : "disabled", "showPreviewsSetting" : "whenAuthenticated", "soundSetting" : "enabled", "timeSensitiveSetting" : "enabled" }, "overridePresets" : [ { "duration" : { "finite" : { "duration" : 3600 } }, "id" : "2A67A303-5203-4CB8-8263-79498265368E", "name" : "Apple", "settings" : { "insulinNeedsScaleFactor" : 2, "targetRangeInMgdl" : { "maxValue" : 140, "minValue" : 130 } }, "symbol" : "🍎" } ], "preMealOverride" : { "actualEnd" : { "type" : "natural" }, "context" : "preMeal", "duration" : "indefinite", "enactTrigger" : "local", "settings" : { "insulinNeedsScaleFactor" : 0.5, "targetRangeInMgdl" : { "maxValue" : 90, "minValue" : 80 } }, "startDate" : "2020-05-14T14:38:39Z", "syncIdentifier" : "2A67A303-5203-1234-8263-79498265368E" }, "preMealTargetRange" : { "maxValue" : 90, "minValue" : 80 }, "pumpDevice" : { "firmwareVersion" : "Pump Firmware Version", "hardwareVersion" : "Pump Hardware Version", "localIdentifier" : "Pump Local Identifier", "manufacturer" : "Pump Manufacturer", "model" : "Pump Model", "name" : "Pump Name", "softwareVersion" : "Pump Software Version", "udiDeviceIdentifier" : "Pump UDI Device Identifier" }, "scheduleOverride" : { "actualEnd" : { "type" : "natural" }, "context" : "preMeal", "duration" : { "finite" : { "duration" : 3600 } }, "enactTrigger" : { "remote" : { "address" : "127.0.0.1" } }, "settings" : { "insulinNeedsScaleFactor" : 1.5, "targetRangeInMgdl" : { "maxValue" : 120, "minValue" : 110 } }, "startDate" : "2020-05-14T14:48:19Z", "syncIdentifier" : "2A67A303-1234-4CB8-8263-79498265368E" }, "suspendThreshold" : { "unit" : "mg/dL", "value" : 75 }, "syncIdentifier" : "2A67A303-1234-4CB8-1234-79498265368E", "workoutTargetRange" : { "maxValue" : 160, "minValue" : 150 } }, "date" : "2100-01-02T03:03:00Z", "modificationCounter" : 123 } """ ) } catch let error { XCTFail("Unexpected failure: \(error)") } } } private func assertSettingsObjectEncodable(_ original: SettingsObject, encodesJSON string: String) throws { let data = try encoder.encode(original) XCTAssertEqual(String(data: data, encoding: .utf8), string) } private let dateFormatter = ISO8601DateFormatter() private let encoder: JSONEncoder = { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] encoder.dateEncodingStrategy = .iso8601 return encoder }() } class SettingsStoreQueryAnchorTests: XCTestCase { var rawValue: SettingsStore.QueryAnchor.RawValue = [ "modificationCounter": Int64(123) ] func testInitializerDefault() { let queryAnchor = SettingsStore.QueryAnchor() XCTAssertEqual(queryAnchor.modificationCounter, 0) } func testInitializerRawValue() { let queryAnchor = SettingsStore.QueryAnchor(rawValue: rawValue) XCTAssertNotNil(queryAnchor) XCTAssertEqual(queryAnchor?.modificationCounter, 123) } func testInitializerRawValueMissingModificationCounter() { rawValue["modificationCounter"] = nil XCTAssertNil(SettingsStore.QueryAnchor(rawValue: rawValue)) } func testInitializerRawValueInvalidModificationCounter() { rawValue["modificationCounter"] = "123" XCTAssertNil(SettingsStore.QueryAnchor(rawValue: rawValue)) } func testRawValueWithDefault() { let rawValue = SettingsStore.QueryAnchor().rawValue XCTAssertEqual(rawValue.count, 1) XCTAssertEqual(rawValue["modificationCounter"] as? Int64, Int64(0)) } func testRawValueWithNonDefault() { var queryAnchor = SettingsStore.QueryAnchor() queryAnchor.modificationCounter = 123 let rawValue = queryAnchor.rawValue XCTAssertEqual(rawValue.count, 1) XCTAssertEqual(rawValue["modificationCounter"] as? Int64, Int64(123)) } } class SettingsStoreQueryTests: PersistenceControllerTestCase { var settingsStore: SettingsStore! var completion: XCTestExpectation! var queryAnchor: SettingsStore.QueryAnchor! var limit: Int! override func setUp() { super.setUp() settingsStore = SettingsStore(store: cacheStore, expireAfter: .hours(1)) completion = expectation(description: "Completion") queryAnchor = SettingsStore.QueryAnchor() limit = Int.max } override func tearDown() { limit = nil queryAnchor = nil completion = nil settingsStore = nil super.tearDown() } // MARK: - func testEmptyWithDefaultQueryAnchor() { settingsStore.executeSettingsQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let data): XCTAssertEqual(anchor.modificationCounter, 0) XCTAssertEqual(data.count, 0) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testEmptyWithMissingQueryAnchor() { queryAnchor = nil settingsStore.executeSettingsQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let data): XCTAssertEqual(anchor.modificationCounter, 0) XCTAssertEqual(data.count, 0) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testEmptyWithNonDefaultQueryAnchor() { queryAnchor.modificationCounter = 1 settingsStore.executeSettingsQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let data): XCTAssertEqual(anchor.modificationCounter, 1) XCTAssertEqual(data.count, 0) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDataWithUnusedQueryAnchor() { let syncIdentifiers = [generateSyncIdentifier(), generateSyncIdentifier(), generateSyncIdentifier()] addData(withSyncIdentifiers: syncIdentifiers) settingsStore.executeSettingsQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let data): XCTAssertEqual(anchor.modificationCounter, 3) XCTAssertEqual(data.count, 3) for (index, syncIdentifier) in syncIdentifiers.enumerated() { XCTAssertEqual(data[index].syncIdentifier, syncIdentifier) } } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDataWithStaleQueryAnchor() { let syncIdentifiers = [generateSyncIdentifier(), generateSyncIdentifier(), generateSyncIdentifier()] addData(withSyncIdentifiers: syncIdentifiers) queryAnchor.modificationCounter = 2 settingsStore.executeSettingsQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let data): XCTAssertEqual(anchor.modificationCounter, 3) XCTAssertEqual(data.count, 1) XCTAssertEqual(data[0].syncIdentifier, syncIdentifiers[2]) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDataWithCurrentQueryAnchor() { let syncIdentifiers = [generateSyncIdentifier(), generateSyncIdentifier(), generateSyncIdentifier()] addData(withSyncIdentifiers: syncIdentifiers) queryAnchor.modificationCounter = 3 settingsStore.executeSettingsQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let data): XCTAssertEqual(anchor.modificationCounter, 3) XCTAssertEqual(data.count, 0) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDataWithLimitZero() { let syncIdentifiers = [generateSyncIdentifier(), generateSyncIdentifier(), generateSyncIdentifier()] addData(withSyncIdentifiers: syncIdentifiers) limit = 0 settingsStore.executeSettingsQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let data): XCTAssertEqual(anchor.modificationCounter, 0) XCTAssertEqual(data.count, 0) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDataWithLimitCoveredByData() { let syncIdentifiers = [generateSyncIdentifier(), generateSyncIdentifier(), generateSyncIdentifier()] addData(withSyncIdentifiers: syncIdentifiers) limit = 2 settingsStore.executeSettingsQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let data): XCTAssertEqual(anchor.modificationCounter, 2) XCTAssertEqual(data.count, 2) XCTAssertEqual(data[0].syncIdentifier, syncIdentifiers[0]) XCTAssertEqual(data[1].syncIdentifier, syncIdentifiers[1]) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } private func addData(withSyncIdentifiers syncIdentifiers: [UUID]) { let semaphore = DispatchSemaphore(value: 0) for syncIdentifier in syncIdentifiers { self.settingsStore.storeSettings(StoredSettings(syncIdentifier: syncIdentifier)) { _ in semaphore.signal() } } for _ in syncIdentifiers { semaphore.wait() } } private func generateSyncIdentifier() -> UUID { UUID() } } class SettingsStoreCriticalEventLogTests: PersistenceControllerTestCase { var settingsStore: SettingsStore! var outputStream: MockOutputStream! var progress: Progress! override func setUp() { super.setUp() let settings = [StoredSettings(date: dateFormatter.date(from: "2100-01-02T03:08:00Z")!, controllerTimeZone: TimeZone(identifier: "America/Los_Angeles")!, syncIdentifier: UUID(uuidString: "18CF3948-0B3D-4B12-8BFE-14986B0E6784")!), StoredSettings(date: dateFormatter.date(from: "2100-01-02T03:10:00Z")!, controllerTimeZone: TimeZone(identifier: "America/Los_Angeles")!, syncIdentifier: UUID(uuidString: "C86DEB61-68E9-464E-9DD5-96A9CB445FD3")!), StoredSettings(date: dateFormatter.date(from: "2100-01-02T03:04:00Z")!, controllerTimeZone: TimeZone(identifier: "America/Los_Angeles")!, syncIdentifier: UUID(uuidString: "2B03D96C-6F5D-4140-99CD-80C3E64D6010")!), StoredSettings(date: dateFormatter.date(from: "2100-01-02T03:06:00Z")!, controllerTimeZone: TimeZone(identifier: "America/Los_Angeles")!, syncIdentifier: UUID(uuidString: "FF1C4F01-3558-4FB2-957E-FA1522C4735E")!), StoredSettings(date: dateFormatter.date(from: "2100-01-02T03:02:00Z")!, controllerTimeZone: TimeZone(identifier: "America/Los_Angeles")!, syncIdentifier: UUID(uuidString: "71B699D7-0E8F-4B13-B7A1-E7751EB78E74")!)] settingsStore = SettingsStore(store: cacheStore, expireAfter: .hours(1)) let dispatchGroup = DispatchGroup() dispatchGroup.enter() settingsStore.addStoredSettings(settings: settings) { error in XCTAssertNil(error) dispatchGroup.leave() } dispatchGroup.wait() outputStream = MockOutputStream() progress = Progress() } override func tearDown() { settingsStore = nil super.tearDown() } func testExportProgressTotalUnitCount() { switch settingsStore.exportProgressTotalUnitCount(startDate: dateFormatter.date(from: "2100-01-02T03:03:00Z")!, endDate: dateFormatter.date(from: "2100-01-02T03:09:00Z")!) { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let progressTotalUnitCount): XCTAssertEqual(progressTotalUnitCount, 3 * 11) } } func testExportProgressTotalUnitCountEmpty() { switch settingsStore.exportProgressTotalUnitCount(startDate: dateFormatter.date(from: "2100-01-02T03:00:00Z")!, endDate: dateFormatter.date(from: "2100-01-02T03:01:00Z")!) { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let progressTotalUnitCount): XCTAssertEqual(progressTotalUnitCount, 0) } } func testExport() { XCTAssertNil(settingsStore.export(startDate: dateFormatter.date(from: "2100-01-02T03:03:00Z")!, endDate: dateFormatter.date(from: "2100-01-02T03:09:00Z")!, to: outputStream, progress: progress)) XCTAssertEqual(outputStream.string, """ [ {"data":{"automaticDosingStrategy":0,"bloodGlucoseUnit":"mg/dL","controllerTimeZone":{"identifier":"America/Los_Angeles"},"date":"2100-01-02T03:08:00.000Z","dosingEnabled":false,"syncIdentifier":"18CF3948-0B3D-4B12-8BFE-14986B0E6784"},"date":"2100-01-02T03:08:00.000Z","modificationCounter":1}, {"data":{"automaticDosingStrategy":0,"bloodGlucoseUnit":"mg/dL","controllerTimeZone":{"identifier":"America/Los_Angeles"},"date":"2100-01-02T03:04:00.000Z","dosingEnabled":false,"syncIdentifier":"2B03D96C-6F5D-4140-99CD-80C3E64D6010"},"date":"2100-01-02T03:04:00.000Z","modificationCounter":3}, {"data":{"automaticDosingStrategy":0,"bloodGlucoseUnit":"mg/dL","controllerTimeZone":{"identifier":"America/Los_Angeles"},"date":"2100-01-02T03:06:00.000Z","dosingEnabled":false,"syncIdentifier":"FF1C4F01-3558-4FB2-957E-FA1522C4735E"},"date":"2100-01-02T03:06:00.000Z","modificationCounter":4} ] """ ) XCTAssertEqual(progress.completedUnitCount, 3 * 11) } func testExportEmpty() { XCTAssertNil(settingsStore.export(startDate: dateFormatter.date(from: "2100-01-02T03:00:00Z")!, endDate: dateFormatter.date(from: "2100-01-02T03:01:00Z")!, to: outputStream, progress: progress)) XCTAssertEqual(outputStream.string, "[]") XCTAssertEqual(progress.completedUnitCount, 0) } func testExportCancelled() { progress.cancel() XCTAssertEqual(settingsStore.export(startDate: dateFormatter.date(from: "2100-01-02T03:03:00Z")!, endDate: dateFormatter.date(from: "2100-01-02T03:09:00Z")!, to: outputStream, progress: progress) as? CriticalEventLogError, CriticalEventLogError.cancelled) } private let dateFormatter = ISO8601DateFormatter() } class StoredSettingsCodableTests: XCTestCase { func testStoredSettingsCodable() throws { try assertStoredSettingsCodable(StoredSettings.test, encodesJSON: """ { "automaticDosingStrategy" : 1, "basalRateSchedule" : { "items" : [ { "startTime" : 0, "value" : 1 }, { "startTime" : 21600, "value" : 1.5 }, { "startTime" : 64800, "value" : 1.25 } ], "referenceTimeInterval" : 0, "repeatInterval" : 86400, "timeZone" : { "identifier" : "GMT-0700" } }, "bloodGlucoseUnit" : "mg/dL", "carbRatioSchedule" : { "unit" : "g", "valueSchedule" : { "items" : [ { "startTime" : 0, "value" : 15 }, { "startTime" : 32400, "value" : 14 }, { "startTime" : 72000, "value" : 18 } ], "referenceTimeInterval" : 0, "repeatInterval" : 86400, "timeZone" : { "identifier" : "GMT-0700" } } }, "cgmDevice" : { "firmwareVersion" : "CGM Firmware Version", "hardwareVersion" : "CGM Hardware Version", "localIdentifier" : "CGM Local Identifier", "manufacturer" : "CGM Manufacturer", "model" : "CGM Model", "name" : "CGM Name", "softwareVersion" : "CGM Software Version", "udiDeviceIdentifier" : "CGM UDI Device Identifier" }, "controllerDevice" : { "model" : "Controller Model", "modelIdentifier" : "Controller Model Identifier", "name" : "Controller Name", "systemName" : "Controller System Name", "systemVersion" : "Controller System Version" }, "controllerTimeZone" : { "identifier" : "America/Los_Angeles" }, "date" : "2020-05-14T22:48:15Z", "defaultRapidActingModel" : { "actionDuration" : 21600, "delay" : 600, "modelType" : "rapidAdult", "peakActivity" : 10800 }, "deviceToken" : "Device Token String", "dosingEnabled" : true, "glucoseTargetRangeSchedule" : { "override" : { "end" : "2020-05-14T14:48:15Z", "start" : "2020-05-14T12:48:15Z", "value" : { "maxValue" : 115, "minValue" : 105 } }, "rangeSchedule" : { "unit" : "mg/dL", "valueSchedule" : { "items" : [ { "startTime" : 0, "value" : { "maxValue" : 110, "minValue" : 100 } }, { "startTime" : 25200, "value" : { "maxValue" : 100, "minValue" : 90 } }, { "startTime" : 75600, "value" : { "maxValue" : 120, "minValue" : 110 } } ], "referenceTimeInterval" : 0, "repeatInterval" : 86400, "timeZone" : { "identifier" : "GMT-0700" } } } }, "insulinSensitivitySchedule" : { "unit" : "mg/dL", "valueSchedule" : { "items" : [ { "startTime" : 0, "value" : 45 }, { "startTime" : 10800, "value" : 40 }, { "startTime" : 54000, "value" : 50 } ], "referenceTimeInterval" : 0, "repeatInterval" : 86400, "timeZone" : { "identifier" : "GMT-0700" } } }, "insulinType" : 1, "maximumBasalRatePerHour" : 3.5, "maximumBolus" : 10, "notificationSettings" : { "alertSetting" : "disabled", "alertStyle" : "banner", "announcementSetting" : "enabled", "authorizationStatus" : "authorized", "badgeSetting" : "enabled", "carPlaySetting" : "notSupported", "criticalAlertSetting" : "enabled", "lockScreenSetting" : "disabled", "notificationCenterSetting" : "notSupported", "providesAppNotificationSettings" : true, "scheduledDeliverySetting" : "disabled", "showPreviewsSetting" : "whenAuthenticated", "soundSetting" : "enabled", "timeSensitiveSetting" : "enabled" }, "overridePresets" : [ { "duration" : { "finite" : { "duration" : 3600 } }, "id" : "2A67A303-5203-4CB8-8263-79498265368E", "name" : "Apple", "settings" : { "insulinNeedsScaleFactor" : 2, "targetRangeInMgdl" : { "maxValue" : 140, "minValue" : 130 } }, "symbol" : "🍎" } ], "preMealOverride" : { "actualEnd" : { "type" : "natural" }, "context" : "preMeal", "duration" : "indefinite", "enactTrigger" : "local", "settings" : { "insulinNeedsScaleFactor" : 0.5, "targetRangeInMgdl" : { "maxValue" : 90, "minValue" : 80 } }, "startDate" : "2020-05-14T14:38:39Z", "syncIdentifier" : "2A67A303-5203-1234-8263-79498265368E" }, "preMealTargetRange" : { "maxValue" : 90, "minValue" : 80 }, "pumpDevice" : { "firmwareVersion" : "Pump Firmware Version", "hardwareVersion" : "Pump Hardware Version", "localIdentifier" : "Pump Local Identifier", "manufacturer" : "Pump Manufacturer", "model" : "Pump Model", "name" : "Pump Name", "softwareVersion" : "Pump Software Version", "udiDeviceIdentifier" : "Pump UDI Device Identifier" }, "scheduleOverride" : { "actualEnd" : { "type" : "natural" }, "context" : "preMeal", "duration" : { "finite" : { "duration" : 3600 } }, "enactTrigger" : { "remote" : { "address" : "127.0.0.1" } }, "settings" : { "insulinNeedsScaleFactor" : 1.5, "targetRangeInMgdl" : { "maxValue" : 120, "minValue" : 110 } }, "startDate" : "2020-05-14T14:48:19Z", "syncIdentifier" : "2A67A303-1234-4CB8-8263-79498265368E" }, "suspendThreshold" : { "unit" : "mg/dL", "value" : 75 }, "syncIdentifier" : "2A67A303-1234-4CB8-1234-79498265368E", "workoutTargetRange" : { "maxValue" : 160, "minValue" : 150 } } """ ) } private func assertStoredSettingsCodable(_ original: StoredSettings, encodesJSON string: String) throws { let data = try encoder.encode(original) XCTAssertEqual(String(data: data, encoding: .utf8), string) let decoded = try decoder.decode(StoredSettings.self, from: data) XCTAssertEqual(decoded, original) } private let dateFormatter = ISO8601DateFormatter() private let encoder: JSONEncoder = { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] encoder.dateEncodingStrategy = .iso8601 return encoder }() private let decoder: JSONDecoder = { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 return decoder }() } fileprivate extension StoredSettings { static var test: StoredSettings { let controllerTimeZone = TimeZone(identifier: "America/Los_Angeles")! let scheduleTimeZone = TimeZone(secondsFromGMT: TimeZone(identifier: "America/Phoenix")!.secondsFromGMT())! let dosingEnabled = true let glucoseTargetRangeSchedule = GlucoseRangeSchedule(rangeSchedule: DailyQuantitySchedule(unit: .milligramsPerDeciliter, dailyItems: [RepeatingScheduleValue(startTime: .hours(0), value: DoubleRange(minValue: 100.0, maxValue: 110.0)), RepeatingScheduleValue(startTime: .hours(7), value: DoubleRange(minValue: 90.0, maxValue: 100.0)), RepeatingScheduleValue(startTime: .hours(21), value: DoubleRange(minValue: 110.0, maxValue: 120.0))], timeZone: scheduleTimeZone)!, override: GlucoseRangeSchedule.Override(value: DoubleRange(minValue: 105.0, maxValue: 115.0), start: dateFormatter.date(from: "2020-05-14T12:48:15Z")!, end: dateFormatter.date(from: "2020-05-14T14:48:15Z")!)) let preMealTargetRange = DoubleRange(minValue: 80.0, maxValue: 90.0).quantityRange(for: .milligramsPerDeciliter) let workoutTargetRange = DoubleRange(minValue: 150.0, maxValue: 160.0).quantityRange(for: .milligramsPerDeciliter) let overridePresets = [TemporaryScheduleOverridePreset(id: UUID(uuidString: "2A67A303-5203-4CB8-8263-79498265368E")!, symbol: "🍎", name: "Apple", settings: TemporaryScheduleOverrideSettings(unit: .milligramsPerDeciliter, targetRange: DoubleRange(minValue: 130.0, maxValue: 140.0), insulinNeedsScaleFactor: 2.0), duration: .finite(.minutes(60)))] let scheduleOverride = TemporaryScheduleOverride(context: .preMeal, settings: TemporaryScheduleOverrideSettings(unit: .milligramsPerDeciliter, targetRange: DoubleRange(minValue: 110.0, maxValue: 120.0), insulinNeedsScaleFactor: 1.5), startDate: dateFormatter.date(from: "2020-05-14T14:48:19Z")!, duration: .finite(.minutes(60)), enactTrigger: .remote("127.0.0.1"), syncIdentifier: UUID(uuidString: "2A67A303-1234-4CB8-8263-79498265368E")!) let preMealOverride = TemporaryScheduleOverride(context: .preMeal, settings: TemporaryScheduleOverrideSettings(unit: .milligramsPerDeciliter, targetRange: DoubleRange(minValue: 80.0, maxValue: 90.0), insulinNeedsScaleFactor: 0.5), startDate: dateFormatter.date(from: "2020-05-14T14:38:39Z")!, duration: .indefinite, enactTrigger: .local, syncIdentifier: UUID(uuidString: "2A67A303-5203-1234-8263-79498265368E")!) let maximumBasalRatePerHour = 3.5 let maximumBolus = 10.0 let suspendThreshold = GlucoseThreshold(unit: .milligramsPerDeciliter, value: 75.0) let deviceToken = "Device Token String" let insulinType = InsulinType.humalog let defaultRapidActingModel = StoredInsulinModel(modelType: .rapidAdult, delay: .minutes(10), actionDuration: .hours(6), peakActivity: .hours(3)) let basalRateSchedule = BasalRateSchedule(dailyItems: [RepeatingScheduleValue(startTime: .hours(0), value: 1.0), RepeatingScheduleValue(startTime: .hours(6), value: 1.5), RepeatingScheduleValue(startTime: .hours(18), value: 1.25)], timeZone: scheduleTimeZone) let insulinSensitivitySchedule = InsulinSensitivitySchedule(unit: .milligramsPerDeciliter, dailyItems: [RepeatingScheduleValue(startTime: .hours(0), value: 45.0), RepeatingScheduleValue(startTime: .hours(3), value: 40.0), RepeatingScheduleValue(startTime: .hours(15), value: 50.0)], timeZone: scheduleTimeZone) let carbRatioSchedule = CarbRatioSchedule(unit: .gram(), dailyItems: [RepeatingScheduleValue(startTime: .hours(0), value: 15.0), RepeatingScheduleValue(startTime: .hours(9), value: 14.0), RepeatingScheduleValue(startTime: .hours(20), value: 18.0)], timeZone: scheduleTimeZone) let notificationSettings = NotificationSettings(authorizationStatus: .authorized, soundSetting: .enabled, badgeSetting: .enabled, alertSetting: .disabled, notificationCenterSetting: .notSupported, lockScreenSetting: .disabled, carPlaySetting: .notSupported, alertStyle: .banner, showPreviewsSetting: .whenAuthenticated, criticalAlertSetting: .enabled, providesAppNotificationSettings: true, announcementSetting: .enabled, timeSensitiveSetting: .enabled, scheduledDeliverySetting: .disabled) let controllerDevice = StoredSettings.ControllerDevice(name: "Controller Name", systemName: "Controller System Name", systemVersion: "Controller System Version", model: "Controller Model", modelIdentifier: "Controller Model Identifier") let cgmDevice = HKDevice(name: "CGM Name", manufacturer: "CGM Manufacturer", model: "CGM Model", hardwareVersion: "CGM Hardware Version", firmwareVersion: "CGM Firmware Version", softwareVersion: "CGM Software Version", localIdentifier: "CGM Local Identifier", udiDeviceIdentifier: "CGM UDI Device Identifier") let pumpDevice = HKDevice(name: "Pump Name", manufacturer: "Pump Manufacturer", model: "Pump Model", hardwareVersion: "Pump Hardware Version", firmwareVersion: "Pump Firmware Version", softwareVersion: "Pump Software Version", localIdentifier: "Pump Local Identifier", udiDeviceIdentifier: "Pump UDI Device Identifier") let bloodGlucoseUnit = HKUnit.milligramsPerDeciliter return StoredSettings(date: dateFormatter.date(from: "2020-05-14T22:48:15Z")!, controllerTimeZone: controllerTimeZone, dosingEnabled: dosingEnabled, glucoseTargetRangeSchedule: glucoseTargetRangeSchedule, preMealTargetRange: preMealTargetRange, workoutTargetRange: workoutTargetRange, overridePresets: overridePresets, scheduleOverride: scheduleOverride, preMealOverride: preMealOverride, maximumBasalRatePerHour: maximumBasalRatePerHour, maximumBolus: maximumBolus, suspendThreshold: suspendThreshold, deviceToken: deviceToken, insulinType: insulinType, defaultRapidActingModel: defaultRapidActingModel, basalRateSchedule: basalRateSchedule, insulinSensitivitySchedule: insulinSensitivitySchedule, carbRatioSchedule: carbRatioSchedule, notificationSettings: notificationSettings, controllerDevice: controllerDevice, cgmDevice: cgmDevice, pumpDevice: pumpDevice, bloodGlucoseUnit: bloodGlucoseUnit, automaticDosingStrategy: .automaticBolus, syncIdentifier: UUID(uuidString: "2A67A303-1234-4CB8-1234-79498265368E")!) } private static let dateFormatter = ISO8601DateFormatter() }
mit
5793cd5bf4dc74847f3ba5f64909d999
37.68851
294
0.533446
4.889834
false
false
false
false
ifcheung2012/lotteForeCast
LottForecast/SideTableViewCell.swift
1
1350
// // SideTableViewCell.swift // LottForecast // // Created by IfCheung on 15/8/8. // Copyright (c) 2015年 IfCheung. All rights reserved. // import UIKit class SideTableViewCell: BaseTableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.commonSetup() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonSetup() } func commonSetup() { let backgroundView = UIView(frame: self.bounds) backgroundView.autoresizingMask = .FlexibleHeight | .FlexibleWidth backgroundView.backgroundColor = UIColor.darkGrayColor() self.backgroundView = backgroundView self.textLabel?.textAlignment = NSTextAlignment.Center self.textLabel?.backgroundColor = UIColor.clearColor() self.textLabel?.textColor = UIColor.lightTextColor() self.textLabel?.font = UIFont(name:"Arial", size: 13) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
eaa20b14f461d7a6cb83f1fb75a5bcd2
24.433962
74
0.655045
4.901818
false
false
false
false
grandiere/box
box/Metal/Space/MetalProjection.swift
1
520
import UIKit class MetalProjection { let minY:Float let maxY:Float let minX:Float let maxX:Float let projectionBuffer:MTLBuffer init(device:MTLDevice) { let projectionMatrix:MetalProjectionMatrix = MetalProjectionMatrix() projectionBuffer = device.generateBuffer( bufferable:projectionMatrix) minY = projectionMatrix.minY maxY = projectionMatrix.maxY minX = projectionMatrix.minX maxX = projectionMatrix.maxX } }
mit
4649a186e636281a9f411db52709f12a
22.636364
76
0.663462
5.306122
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/SQLite.swift/Sources/SQLite/Typed/AggregateFunctions.swift
46
7969
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // extension ExpressionType where UnderlyingType : Value { /// Builds a copy of the expression prefixed with the `DISTINCT` keyword. /// /// let name = Expression<String>("name") /// name.distinct /// // DISTINCT "name" /// /// - Returns: A copy of the expression prefixed with the `DISTINCT` /// keyword. public var distinct: Expression<UnderlyingType> { return Expression("DISTINCT \(template)", bindings) } /// Builds a copy of the expression wrapped with the `count` aggregate /// function. /// /// let name = Expression<String?>("name") /// name.count /// // count("name") /// name.distinct.count /// // count(DISTINCT "name") /// /// - Returns: A copy of the expression wrapped with the `count` aggregate /// function. public var count: Expression<Int> { return wrap(self) } } extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Value { /// Builds a copy of the expression prefixed with the `DISTINCT` keyword. /// /// let name = Expression<String?>("name") /// name.distinct /// // DISTINCT "name" /// /// - Returns: A copy of the expression prefixed with the `DISTINCT` /// keyword. public var distinct: Expression<UnderlyingType> { return Expression("DISTINCT \(template)", bindings) } /// Builds a copy of the expression wrapped with the `count` aggregate /// function. /// /// let name = Expression<String?>("name") /// name.count /// // count("name") /// name.distinct.count /// // count(DISTINCT "name") /// /// - Returns: A copy of the expression wrapped with the `count` aggregate /// function. public var count: Expression<Int> { return wrap(self) } } extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype : Comparable { /// Builds a copy of the expression wrapped with the `max` aggregate /// function. /// /// let age = Expression<Int>("age") /// age.max /// // max("age") /// /// - Returns: A copy of the expression wrapped with the `max` aggregate /// function. public var max: Expression<UnderlyingType?> { return wrap(self) } /// Builds a copy of the expression wrapped with the `min` aggregate /// function. /// /// let age = Expression<Int>("age") /// age.min /// // min("age") /// /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var min: Expression<UnderlyingType?> { return wrap(self) } } extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Value, UnderlyingType.WrappedType.Datatype : Comparable { /// Builds a copy of the expression wrapped with the `max` aggregate /// function. /// /// let age = Expression<Int?>("age") /// age.max /// // max("age") /// /// - Returns: A copy of the expression wrapped with the `max` aggregate /// function. public var max: Expression<UnderlyingType> { return wrap(self) } /// Builds a copy of the expression wrapped with the `min` aggregate /// function. /// /// let age = Expression<Int?>("age") /// age.min /// // min("age") /// /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var min: Expression<UnderlyingType> { return wrap(self) } } extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype : Number { /// Builds a copy of the expression wrapped with the `avg` aggregate /// function. /// /// let salary = Expression<Double>("salary") /// salary.average /// // avg("salary") /// /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var average: Expression<Double?> { return "avg".wrap(self) } /// Builds a copy of the expression wrapped with the `sum` aggregate /// function. /// /// let salary = Expression<Double>("salary") /// salary.sum /// // sum("salary") /// /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var sum: Expression<UnderlyingType?> { return wrap(self) } /// Builds a copy of the expression wrapped with the `total` aggregate /// function. /// /// let salary = Expression<Double>("salary") /// salary.total /// // total("salary") /// /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var total: Expression<Double> { return wrap(self) } } extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Value, UnderlyingType.WrappedType.Datatype : Number { /// Builds a copy of the expression wrapped with the `avg` aggregate /// function. /// /// let salary = Expression<Double?>("salary") /// salary.average /// // avg("salary") /// /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var average: Expression<Double?> { return "avg".wrap(self) } /// Builds a copy of the expression wrapped with the `sum` aggregate /// function. /// /// let salary = Expression<Double?>("salary") /// salary.sum /// // sum("salary") /// /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var sum: Expression<UnderlyingType> { return wrap(self) } /// Builds a copy of the expression wrapped with the `total` aggregate /// function. /// /// let salary = Expression<Double?>("salary") /// salary.total /// // total("salary") /// /// - Returns: A copy of the expression wrapped with the `min` aggregate /// function. public var total: Expression<Double> { return wrap(self) } } extension ExpressionType where UnderlyingType == Int { static func count(_ star: Star) -> Expression<UnderlyingType> { return wrap(star(nil, nil)) } } /// Builds an expression representing `count(*)` (when called with the `*` /// function literal). /// /// count(*) /// // count(*) /// /// - Returns: An expression returning `count(*)` (when called with the `*` /// function literal). public func count(_ star: Star) -> Expression<Int> { return Expression.count(star) }
mit
9af60b1a3355ff2ec2f12d37cf719ae2
30.74502
149
0.612324
4.438997
false
false
false
false
kosicki123/eidolon
Kiosk/App/Networking/XAppAuthentication.swift
1
1853
import Foundation import ISO8601DateFormatter import Moya /// Request to fetch and store new XApp token if the current token is missing or expired. private func XAppTokenRequest(defaults: NSUserDefaults) -> RACSignal { // I don't like an extension of a class referencing what is essentially a singleton of that class. var appToken = XAppToken(defaults: defaults) let newTokenSignal = Provider.sharedProvider.request(ArtsyAPI.XApp, parameters: ArtsyAPI.XApp.defaultParameters).filterSuccessfulStatusCodes().mapJSON().doNext({ (response) -> Void in if let dictionary = response as? NSDictionary { let formatter = ISO8601DateFormatter() appToken.token = dictionary["xapp_token"] as String? appToken.expiry = formatter.dateFromString(dictionary["expires_in"] as String?) } }).logError().ignoreValues() // Signal that returns whether our current token is valid let validTokenSignal = RACSignal.`return`(appToken.isValid) // If the token is valid, just return an empty signal, otherwise return a signal that fetches new tokens return RACSignal.`if`(validTokenSignal, then: RACSignal.empty(), `else`: newTokenSignal) } /// Request to fetch a given target. Ensures that valid XApp tokens exist before making request public func XAppRequest(token: ArtsyAPI, provider: ReactiveMoyaProvider<ArtsyAPI> = Provider.sharedProvider, method: Moya.Method = Moya.DefaultMethod(), parameters: [String: AnyObject] = Moya.DefaultParameters(), defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()) -> RACSignal { // First perform XAppTokenRequest(). When it completes, then the signal returned from the closure will be subscribed to. return XAppTokenRequest(defaults).then { return provider.request(token, method: method, parameters: parameters) } }
mit
201f6c6216e47193880f1d341827fd73
50.5
294
0.745818
4.994609
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Mapper/UserMapper.swift
1
5103
// // UserMapper.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import ObjectMapper class UserMapper: Mappable { var identifier: String? var username: String? var displayName: String? var listName: String? var name: String? var role: String? var lastBubbledAt: Date? var lastCommentedAt: Date? var createdAt: Date? var updatedAt: Date? var avatarUrl: String? var countryCode: String? var countryName: String? var age: String? var shortUrl: String? var bubblesCount: Int? var bubblesOnCreationsCount: Int? var addedBubblesCount: Int? var activitiesCount: Int? var commentsCount: Int? var creationsCount: Int? var creatorsCount: Int? var galleriesCount: Int? var managersCount: Int? var homeSchooling: Bool? var signedUpAsInstructor: Bool? var gender: String? var customStyleRelationship: RelationshipMapper? var whatDoYouTeach: String? var interests: String? var interestsList: Array<String>? var followersCount: Int? var followedUsersCount: Int? var followedHashtagsCount: Int? // MARK: - Mappable required init?(map: Map) { /* Intentionally left empty */ } func mapping(map: Map) { identifier <- map["id"] username <- map["attributes.username"] displayName <- map["attributes.display_name"] listName <- map["attributes.list_name"] name <- map["attributes.name"] role <- map["attributes.role"] lastBubbledAt <- (map["attributes.last_bubbled_at"], APIClientDateTransform.sharedTransform) lastCommentedAt <- (map["attributes.last_commented_at"], APIClientDateTransform.sharedTransform) createdAt <- (map["attributes.created_at"], APIClientDateTransform.sharedTransform) updatedAt <- (map["attributes.updated_at"], APIClientDateTransform.sharedTransform) avatarUrl <- map["attributes.avatar_url"] let countryCodeMap = map["attributes.country_code"] if countryCodeMap.isKeyPresent { countryCode <- countryCodeMap } else { countryCode <- map["attributes.country"] } countryName <- map["attributes.country_name"] age <- map["attributes.age"] shortUrl <- map["attributes.short_url"] bubblesCount <- map["attributes.bubbles_count"] bubblesOnCreationsCount <- map["attributes.bubbles_on_creations_count"] addedBubblesCount <- map["attributes.added_bubbles_count"] activitiesCount <- map["attributes.activities_count"] commentsCount <- map["attributes.comments_count"] creationsCount <- map["attributes.creations_count"] galleriesCount <- map["attributes.galleries_count"] creatorsCount <- map["attributes.creators_count"] managersCount <- map["attributes.managers_count"] homeSchooling <- map["attributes.home_schooling"] signedUpAsInstructor <- map["attributes.signed_up_as_instructor"] gender <- map["attributes.gender"] customStyleRelationship <- map["relationships.custom_style.data"] whatDoYouTeach <- map["attributes.what_do_you_teach"] interests <- map["attributes.interests"] interestsList <- map["attributes.interest_list"] followersCount <- map["attributes.followers_count"] followedUsersCount <- map["attributes.followed_users_count"] followedHashtagsCount <- map["attributes.followed_hashtags_count"] } // MARK: - Parsing func parseRole() -> Role { switch self.role { case "parent": return Role.parent case "instructor": return Role.instructor case "creator": return Role.creator default: return Role.creator } } func parseGender() -> Gender { if gender == "male" { return .male } if gender == "female" { return .female } return .unknown } }
mit
f356c5aa2fe24bc99ad16ab43e86b25e
36.8
104
0.673721
4.456769
false
false
false
false
rwebaz/Simple-Swift-OS
iOs8PlayGrounds/LyndaiOS8StringInterpolation.playground/section-1.swift
1
859
// Lynda.com iOS 8 String Interpolation by Simon Allardice import UIKit // Declare variables and constants let city = "Scottsdale"; var day = "Monday"; var temp = "98"; // Print to console a string w inserted variables // Use the "\(x)" backslash, parenthesis, insert variable name format println("The high for \(city) on \(day) was \(temp) degrees F."); // Declare variables and constants var quantity = 12; var unitPrice = 7; // Print to console a string w inserted operands println("The amount due is $\(quantity * unitPrice)."); // What if unitPrice is inferred to be a double, or 64-bit floating point // Declare variables and constants // Change unitPrice to a double var unitPrice2 = 7.50; // Envelope the variable quantity in a double function to create a like product println("The amount due is $\(Double(quantity) * unitPrice2)");
agpl-3.0
308627e9a3692d8fa00d67aab29451c2
21.605263
79
0.719441
3.886878
false
false
false
false
curiousurick/BluetoothBackupSensor-iOS
CSS427Bluefruit_Connect/BLE Test/DeviceListViewController.swift
1
18827
// // DeviceListViewController.swift // Adafruit Bluefruit LE Connect // // Created by Collin Cunningham on 10/15/14. // Copyright (c) 2014 Adafruit Industries. All rights reserved. // import Foundation import UIKit import CoreBluetooth protocol DeviceListViewControllerDelegate: HelpViewControllerDelegate, UIAlertViewDelegate { var connectionMode:ConnectionMode { get } var warningLabel:UILabel! { get } func connectPeripheral(peripheral:CBPeripheral, mode:ConnectionMode) func launchDFU(peripheral:CBPeripheral) func stopScan() func startScan() } class DeviceListViewController : UIViewController, UITableViewDelegate, UITableViewDataSource { var delegate:DeviceListViewControllerDelegate? @IBOutlet var tableView:UITableView! @IBOutlet var helpViewController:HelpViewController! @IBOutlet var deviceCell:DeviceCell! @IBOutlet var attributeCell:AttributeCell! var devices:[BLEDevice] = [] private var tableIsLoading = false private var signalImages:[UIImage]! enum DeviceType { case Sensor case Receiver } internal var currentConnectingDeviceType: DeviceType? convenience init(aDelegate:DeviceListViewControllerDelegate){ //Separate NIBs for iPhone 3.5", iPhone 4", & iPad var nibName:NSString if IS_IPHONE{ nibName = "DeviceListViewController_iPhone" } else{ //IPAD nibName = "DeviceListViewController_iPad" } self.init(nibName: nibName as String, bundle: NSBundle.mainBundle()) self.delegate = aDelegate self.title = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleDisplayName") as? String self.signalImages = [UIImage](arrayLiteral: UIImage(named: "signalStrength-0.png")!, UIImage(named: "signalStrength-1.png")!, UIImage(named: "signalStrength-2.png")!, UIImage(named: "signalStrength-3.png")!, UIImage(named: "signalStrength-4.png")!) } override func viewDidLoad() { super.viewDidLoad() tableView.separatorStyle = UITableViewCellSeparatorStyle.None self.helpViewController.delegate = delegate //Add pull-to-refresh functionality let tvc = UITableViewController(style: UITableViewStyle.Plain) tvc.tableView = tableView let refresh = UIRefreshControl() refresh.addTarget(self, action: Selector("refreshWasPulled:"), forControlEvents: UIControlEvents.ValueChanged) tvc.refreshControl = refresh } func cellButtonTapped(sender: UIButton) { // println("\(self.classForCoder.description()) cellButtonTapped: \(sender.tag)") if tableIsLoading == true { printLog(self, funcName: "cellButtonTapped", logString: "ignoring tap during table load") return } //find relevant indexPaths let indexPath:NSIndexPath = indexPathForSubview(sender) var attributePathArray:[NSIndexPath] = [] for i in 1...(devices[indexPath.section].advertisementArray.count) { attributePathArray.append(NSIndexPath(forRow: i, inSection: indexPath.section)) } //if same button is tapped as previous, close the cell let senderCell = tableView.cellForRowAtIndexPath(indexPath) as! DeviceCell animateCellSelection(tableView.cellForRowAtIndexPath(indexPath)!) tableView.beginUpdates() if (senderCell.isOpen == true) { // println("- - - -"); println("sections \(indexPath.section) has \(tableView.numberOfRowsInSection(indexPath.section)) rows"); println("deleting \(attributePathArray.count) rows"); println("- - - -") senderCell.isOpen = false tableView.deleteRowsAtIndexPaths(attributePathArray, withRowAnimation: UITableViewRowAnimation.Fade) } else { senderCell.isOpen = true tableView.insertRowsAtIndexPaths(attributePathArray, withRowAnimation: UITableViewRowAnimation.Fade) } tableView.endUpdates() } func connectButtonTapped(sender: UIButton) { printLog(self, funcName: "connectButtonTapped", logString: "\(sender.tag)") if tableIsLoading == true { printLog(self, funcName: "connectButtonTapped", logString: "ignoring button while table loads") } let device = devices[sender.tag] /* // If device is not uart capable, go straight to Info mode if device.isUART == false { connectInMode(ConnectionMode.Info, peripheral: device.peripheral) return } */ //Show connection options for UART capable devices var style = UIAlertControllerStyle.ActionSheet if IS_IPAD { style = UIAlertControllerStyle.Alert } let alertController = UIAlertController(title: "Connect to \(device.name)", message: "Choose mode:", preferredStyle: style) // Cancel button let aaCancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (aa:UIAlertAction!) -> Void in } alertController.addAction(aaCancel) // // Info button // let aaInfo = UIAlertAction(title: "Info", style: UIAlertActionStyle.Default) { (aa:UIAlertAction!) -> Void in // self.connectInMode(ConnectionMode.Info, peripheral: device.peripheral) // } // alertController.addAction(aaInfo) if (device.isUART) { let sensorController = UIAlertAction(title: "Sensor", style: .Default, handler: { (action) in self.currentConnectingDeviceType = .Sensor self.nameDeviceBeforeConnecting(device) self.connectInMode(.BackupSensor, peripheral: device.peripheral) }) let receiverController = UIAlertAction(title: "Receiver", style: .Default, handler: { (action) in self.currentConnectingDeviceType = .Receiver self.nameDeviceBeforeConnecting(device) self.connectInMode(.BackupSensor, peripheral: device.peripheral) }) if (device.name == "Sensor" || device.name == "Receiver") { let connectAction = UIAlertAction(title: "Reconnect", style: .Default, handler: { (action) in if (device.name == "Sensor") { self.currentConnectingDeviceType = .Sensor } else if (device.name == "Receiver") { self.currentConnectingDeviceType = .Receiver } self.connectInMode(.BackupSensor, peripheral: device.peripheral) }) alertController.addAction(connectAction) } alertController.addAction(sensorController) alertController.addAction(receiverController) } // DFU button let aaUpdater = UIAlertAction(title: "Firmware Updater", style: UIAlertActionStyle.Default) { (aa:UIAlertAction!) -> Void in self.delegate?.launchDFU(device.peripheral) } alertController.addAction(aaUpdater) self.presentViewController(alertController, animated: true) { () -> Void in } } func nameDeviceBeforeConnecting(device: BLEDevice) { if (currentConnectingDeviceType != nil) { let defaults = NSUserDefaults.standardUserDefaults() var allDevices = defaults.valueForKey("devices") as! [String:String] if currentConnectingDeviceType == .Sensor { allDevices[device.peripheral.identifier.UUIDString] = "Sensor" } else if currentConnectingDeviceType == .Receiver { allDevices[device.peripheral.identifier.UUIDString] = "Receiver" } defaults.setValue(allDevices, forKey: "devices") } } func connectInMode(mode:ConnectionMode, peripheral:CBPeripheral) { // println("\(self.classForCoder.description()) connectInMode") switch mode { case ConnectionMode.UART, ConnectionMode.PinIO, ConnectionMode.Info, ConnectionMode.Controller, ConnectionMode.BackupSensor: delegate?.connectPeripheral(peripheral, mode: mode) default: break } } func didFindPeripheral(peripheral:CBPeripheral!, advertisementData:[NSObject : AnyObject]!, RSSI:NSNumber!) { // println("\(self.classForCoder.description()) didFindPeripheral") //If device is already listed, just update RSSI let newID = peripheral.identifier for device in devices { if device.identifier == newID { // println(" \(self.classForCoder.description()) updating device RSSI") device.RSSI = RSSI return } } let defaults = NSUserDefaults.standardUserDefaults() if (defaults.valueForKey("devices") == nil) { let devices = [String:String]() defaults.setValue(devices, forKey: "devices") } var devicesIdsAndNames = defaults.valueForKey("devices") as! [String:String] if (devicesIdsAndNames[newID.UUIDString] == nil && peripheral.name != nil) { devicesIdsAndNames[newID.UUIDString] = peripheral.name! } else if (devicesIdsAndNames[newID.UUIDString] == nil) { devicesIdsAndNames[newID.UUIDString] = "Unknown Device" } defaults.setValue(devicesIdsAndNames, forKey: "devices") //Add reference to new device let newDevice = BLEDevice(peripheral: peripheral, advertisementData: advertisementData, RSSI: RSSI) if (devicesIdsAndNames[newID.UUIDString] != nil) { newDevice.name = devicesIdsAndNames[newID.UUIDString]! } newDevice.printAdData() devices.append(newDevice) //Reload tableview to show new device if tableView != nil { tableIsLoading = true tableView.reloadData() tableIsLoading = false } delegate?.warningLabel.text = "" } func didConnectPeripheral(peripheral:CBPeripheral!) { currentConnectingDeviceType = nil } func refreshWasPulled(sender:UIRefreshControl) { delegate?.stopScan() tableView.beginUpdates() tableView.deleteSections(NSIndexSet(indexesInRange: NSMakeRange(0, tableView.numberOfSections)), withRowAnimation: UITableViewRowAnimation.Fade) devices.removeAll(keepCapacity: false) tableView.endUpdates() delay(0.45, closure: { () -> () in sender.endRefreshing() delay(0.25, closure: { () -> () in self.tableIsLoading = true self.tableView.reloadData() self.tableIsLoading = false self.delegate?.warningLabel.text = "No peripherals found" self.delegate?.startScan() }) }) } func clearDevices() { delegate?.stopScan() tableView.beginUpdates() tableView.deleteSections(NSIndexSet(indexesInRange: NSMakeRange(0, tableView.numberOfSections)), withRowAnimation: UITableViewRowAnimation.Fade) devices.removeAll(keepCapacity: false) tableView.endUpdates() tableIsLoading = true tableView.reloadData() tableIsLoading = false delegate?.startScan() delegate?.warningLabel.text = "No peripherals found" } //MARK: TableView functions func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Each device has its own section // row 0 is the device cell // additional rows are advertisement attributes //Device Cell if indexPath.row == 0 { //Check if cell already exists let testCell = devices[indexPath.section].deviceCell if testCell != nil { return testCell! } //Create Device Cell from NIB let cellData = NSKeyedArchiver.archivedDataWithRootObject(deviceCell) let cell:DeviceCell = NSKeyedUnarchiver.unarchiveObjectWithData(cellData) as! DeviceCell //Assign properties via view tags set in IB cell.nameLabel = cell.viewWithTag(100) as! UILabel cell.rssiLabel = cell.viewWithTag(101) as! UILabel cell.connectButton = cell.viewWithTag(102) as! UIButton cell.connectButton.addTarget(self, action: Selector("connectButtonTapped:"), forControlEvents: UIControlEvents.TouchUpInside) cell.connectButton.layer.cornerRadius = 4.0 cell.toggleButton = cell.viewWithTag(103) as! UIButton cell.toggleButton.addTarget(self, action: Selector("cellButtonTapped:"), forControlEvents: UIControlEvents.TouchUpInside) cell.signalImageView = cell.viewWithTag(104) as! UIImageView cell.uartCapableLabel = cell.viewWithTag(105) as! UILabel //set tag to indicate digital pin number cell.toggleButton.tag = indexPath.section // Button tags are now device indexes, not view references cell.connectButton.tag = indexPath.section cell.signalImages = signalImages //Ensure cell is within device array range if indexPath.section <= (devices.count-1) { devices[indexPath.section].deviceCell = cell } return cell } //Attribute Cell else { //Create Device Cell from NIB let cellData = NSKeyedArchiver.archivedDataWithRootObject(attributeCell) let cell:AttributeCell = NSKeyedUnarchiver.unarchiveObjectWithData(cellData) as! AttributeCell //Assign properties via tags cell.label = cell.viewWithTag(100) as! UILabel cell.button = cell.viewWithTag(103) as! UIButton cell.button.addTarget(self, action: Selector("selectAttributeCell:"), forControlEvents: UIControlEvents.TouchUpInside) cell.dataStrings = devices[indexPath.section].advertisementArray[indexPath.row - 1] return cell } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let device:BLEDevice? = devices[section] let cell = device?.deviceCell if (cell == nil) || (cell?.isOpen == false) { //When table is first loaded return 1 } else { let rows = devices[section].advertisementArray.count + 1 return rows } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { //Each DeviceCell gets its own section return devices.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 0 { return 50.0 } else { return 24.0 } } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 46.0 } else { return 0.5 } } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == (devices.count-1) { return 22.0 } else { return 0.5 } } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if (section == 0){ return "Peripherals" } else{ return nil } } //MARK: Helper functions func indexPathForSubview(theView:UIView) ->NSIndexPath{ //Find the indexpath for the cell which contains theView var indexPath: NSIndexPath? var counter = 0 let limit = 20 var aView:UIView? = theView while (indexPath == nil) { if (counter > limit) { break } if aView?.superview is UITableViewCell { let theCell = aView?.superview as! UITableViewCell indexPath = tableView.indexPathForCell(theCell) } else { aView = theView.superview } counter += 1; } return indexPath! } func selectAttributeCell(sender: UIButton){ let indexPath = indexPathForSubview(sender) let cell = tableView.cellForRowAtIndexPath(indexPath) as! AttributeCell tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None) //Show full view of attribute data let ttl = cell.dataStrings[0] var msg = "" for s in cell.dataStrings { //compose message from attribute strings if s == "nil" || s == ttl { continue } else { msg += "\n" msg += s } } // var style = UIAlertControllerStyle.ActionSheet // if IS_IPAD { let style = UIAlertControllerStyle.Alert // } let alertController = UIAlertController(title: ttl, message: msg, preferredStyle: style) // Cancel button let aaCancel = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel) { (aa:UIAlertAction!) -> Void in } alertController.addAction(aaCancel) // Info button // let aaInfo = UIAlertAction(title: "Info", style: UIAlertActionStyle.Default) { (aa:UIAlertAction!) -> Void in // self.connectInMode(ConnectionMode.Info, peripheral: device.peripheral) // } self.presentViewController(alertController, animated: true) { () -> Void in } } }
mit
d05432dd99249875f65ae0bc71f62526
34.324578
211
0.59404
5.511417
false
false
false
false
Henryforce/KRActivityIndicatorView
KRActivityIndicatorView/KRActivityIndicatorAnimationPacman.swift
1
4985
// // KRActivityIndicatorAnimationPacman.swift // KRActivityIndicatorViewDemo // // The MIT License (MIT) // Originally written to work in iOS by Vinh Nguyen in 2016 // Adapted to OSX by Henry Serrano in 2017 // 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 Cocoa class KRActivityIndicatorAnimationPacman: KRActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) { circleInLayer(layer, size: size, color: color) pacmanInLayer(layer, size: size, color: color) } func pacmanInLayer(_ layer: CALayer, size: CGSize, color: NSColor) { let pacmanSize = 2 * size.width / 3 let pacmanDuration: CFTimeInterval = 0.5 let timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default) // Stroke start animation let strokeStartAnimation = CAKeyframeAnimation(keyPath: "strokeStart") strokeStartAnimation.keyTimes = [0, 0.5, 1] strokeStartAnimation.timingFunctions = [timingFunction, timingFunction] strokeStartAnimation.values = [0.125, 0, 0.125] strokeStartAnimation.duration = pacmanDuration // Stroke end animation let strokeEndAnimation = CAKeyframeAnimation(keyPath: "strokeEnd") strokeEndAnimation.keyTimes = [0, 0.5, 1] strokeEndAnimation.timingFunctions = [timingFunction, timingFunction] strokeEndAnimation.values = [0.875, 1, 0.875] strokeEndAnimation.duration = pacmanDuration // Animation let animation = CAAnimationGroup() animation.animations = [strokeStartAnimation, strokeEndAnimation] animation.duration = pacmanDuration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw pacman let pacman = KRActivityIndicatorShape.pacman.layerWith(size: CGSize(width: pacmanSize, height: pacmanSize), color: color) let frame = CGRect( x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - pacmanSize) / 2, width: pacmanSize, height: pacmanSize ) pacman.frame = frame pacman.add(animation, forKey: "animation") layer.addSublayer(pacman) } func circleInLayer(_ layer: CALayer, size: CGSize, color: NSColor) { let circleSize = size.width / 5 let circleDuration: CFTimeInterval = 1 // Translate animation let translateAnimation = CABasicAnimation(keyPath: "transform.translation.x") translateAnimation.fromValue = 0 translateAnimation.toValue = -size.width / 2 translateAnimation.duration = circleDuration // Opacity animation let opacityAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.fromValue = 1 opacityAnimation.toValue = 0.7 opacityAnimation.duration = circleDuration // Animation let animation = CAAnimationGroup() animation.animations = [translateAnimation, opacityAnimation] animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) animation.duration = circleDuration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles let circle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect( x: (layer.bounds.size.width - size.width) / 2 + size.width - circleSize, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize ) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
dbed29d7491ee34b359e93bc2a998c3b
39.860656
129
0.67342
5.214435
false
false
false
false
leloupnicolas/UIKitExtensions
UIKitExtensions/UIViewExtension.swift
1
3569
// // UIViewExtension.swift // application // // Created by Nicolas LELOUP on 02/09/2015. // Copyright (c) 2015 Nicolas LELOUP - Buzznative. All rights reserved. // import Foundation import UIKit typealias AnimationCompletionBlock = ((Bool) -> Void) extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(cgColor: layer.borderColor!) } set { layer.borderColor = newValue?.cgColor } } // MARK: Fading animations func fadeInNow() { self.fadeInNowWithCallback(nil) } func fadeOutNow() { self.fadeOutNowWithCallback(nil) } func fadeInNowWithCallback(_ completion: AnimationCompletionBlock?) { UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: { self.alpha = 1.0 }, completion: completion) } func fadeOutNowWithCallback(_ completion: AnimationCompletionBlock?) { UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: { self.alpha = 0.0 }, completion: completion) } func flash() { UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseOut, animations: { () -> Void in self.alpha = 1 }) { (param) -> Void in UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseOut, animations: { self.alpha = 0 }, completion: nil) } } // MARK: Resizing animations func resizeWithFactor(_ factor: CGFloat) { self.resizeWithFactor(factor, completion: nil) } func resizeWithFactor(_ factor: CGFloat, completion: AnimationCompletionBlock?) { let currentFrame = self.frame let width = currentFrame.size.width * factor let height = currentFrame.size.height * factor let leftOffset = (currentFrame.origin.x + (currentFrame.size.width * (1.0 - factor))) / 2 let topOffset = (currentFrame.origin.y + (currentFrame.size.height * (1.0 - factor))) / 2 let newFrame : CGRect = CGRect(x: leftOffset, y: topOffset, width: width, height: height) UIView.animate(withDuration: 0.4, delay: 0, options: .curveEaseOut, animations: { self.frame = newFrame }, completion: completion) } // MARK: Sliding animations func slideUp() { self.slideUp(nil) } func slideUp(_ completion: ((Bool) -> Void)?) { let screenBound = UIScreen.main.bounds let currentFrame = self.frame let newFrame : CGRect = CGRect(x: currentFrame.origin.x, y: currentFrame.origin.y - screenBound.size.height, width: currentFrame.size.width, height: currentFrame.size.height) UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: { self.frame = newFrame }, completion: completion) } func slideDown() { self.slideDown(nil) } func slideDown(_ completion: ((Bool) -> Void)?) { let screenBound = UIScreen.main.bounds let currentFrame = self.frame let newFrame : CGRect = CGRect(x: currentFrame.origin.x, y: currentFrame.origin.y + screenBound.size.height, width: currentFrame.size.width, height: currentFrame.size.height) UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: { self.frame = newFrame }, completion: completion) } }
mit
75b1857f3e0c267acc8dff104b977b16
28.991597
178
0.663491
4.060296
false
false
false
false
darrinhenein/firefox-ios
Client/Frontend/Settings/SettingsTableViewController.swift
1
9024
/* 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 Base32 import UIKit class SettingsTableViewController: UITableViewController { let SectionAccount = 0 let ItemAccountStatus = 0 let ItemAccountDisconnect = 1 let SectionSearch = 1 let NumberOfSections = 2 var profile: Profile! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Settings", comment: "Settings") navigationItem.leftBarButtonItem = UIBarButtonItem( title: NSLocalizedString("Done", comment: "Settings"), style: UIBarButtonItemStyle.Done, target: navigationController, action: "SELdone") } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: UITableViewCell if indexPath.section == SectionAccount { if indexPath.item == ItemAccountStatus { cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: nil) cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator updateCell(cell, toReflectAccount: profile.getAccount()) } else if indexPath.item == ItemAccountDisconnect { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.textLabel?.text = NSLocalizedString("Disconnect", comment: "Settings") } else { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) } } else if indexPath.section == SectionSearch { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.textLabel?.text = NSLocalizedString("Search", comment: "Settings") } else { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) } // So that the seperator line goes all the way to the left edge. cell.separatorInset = UIEdgeInsetsZero return cell } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return NumberOfSections } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == SectionAccount { if profile.getAccount() == nil { // Just "Sign in". return 1 } else { // Account state, and "Disconnect." return 2 } } else if section == SectionSearch { return 1 } else { return 0 } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == SectionAccount { return nil } else if section == SectionSearch { return NSLocalizedString("Search Settings", comment: "Title for search settings section.") } else { return nil } } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if indexPath.section == SectionAccount { switch indexPath.item { case ItemAccountStatus: let viewController = FxAContentViewController() viewController.delegate = self if let account = profile.getAccount() { switch account.getActionNeeded() { case .None, .NeedsVerification: let cs = NSURLComponents(URL: profile.accountConfiguration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .NeedsPassword: let cs = NSURLComponents(URL: profile.accountConfiguration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .NeedsUpgrade: // In future, we'll want to link to an upgrade page. break } } else { viewController.url = profile.accountConfiguration.signInURL } navigationController?.pushViewController(viewController, animated: true) case ItemAccountDisconnect: maybeDisconnectAccount() default: break } } else if indexPath.section == SectionSearch { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines navigationController?.pushViewController(viewController, animated: true) } return nil } func updateCell(cell: UITableViewCell, toReflectAccount account: FirefoxAccount?) { if let account = account { cell.textLabel?.text = account.email cell.detailTextLabel?.text = nil switch account.getActionNeeded() { case .None: break case .NeedsVerification: cell.detailTextLabel?.text = NSLocalizedString("Verify your email address.", comment: "Settings") case .NeedsPassword: // This assumes we never recycle cells. cell.detailTextLabel?.textColor = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) // Firefox orange! cell.detailTextLabel?.text = NSLocalizedString("Enter your password to connect.", comment: "Settings") case .NeedsUpgrade: cell.detailTextLabel?.textColor = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) // Firefox orange! cell.detailTextLabel?.text = NSLocalizedString("Upgrade Firefox to connect.", comment: "Settings") cell.accessoryType = UITableViewCellAccessoryType.None } } else { cell.textLabel?.text = NSLocalizedString("Sign in", comment: "Settings") } } func maybeDisconnectAccount() { let alertController = UIAlertController( title: NSLocalizedString("Disconnect Firefox Account?", comment: "Settings"), message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Settings"), preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction( UIAlertAction(title: NSLocalizedString("Cancel", comment: "Settings"), style: .Cancel) { (action) in // Do nothing. }) alertController.addAction( UIAlertAction(title: NSLocalizedString("Disconnect", comment: "Settings"), style: .Destructive) { (action) in self.profile.setAccount(nil) self.tableView.reloadData() }) presentViewController(alertController, animated: true, completion: nil) } } extension SettingsTableViewController: FxAContentViewControllerDelegate { func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) { if data["keyFetchToken"].asString? == nil || data["unwrapBKey"].asString? == nil { // The /settings endpoint sends a partial "login"; ignore it entirely. NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.") return } // TODO: Error handling. let state = FirefoxAccountState.Engaged( verified: data["verified"].asBool ?? false, sessionToken: data["sessionToken"].asString!.hexDecodedData, keyFetchToken: data["keyFetchToken"].asString!.hexDecodedData, unwrapkB: data["unwrapBKey"].asString!.hexDecodedData ) let account = FirefoxAccount( email: data["email"].asString!, uid: data["uid"].asString!, authEndpoint: profile.accountConfiguration.authEndpointURL, contentEndpoint: profile.accountConfiguration.profileEndpointURL, oauthEndpoint: profile.accountConfiguration.oauthEndpointURL, state: state ) profile.setAccount(account) tableView.reloadData() navigationController?.popToRootViewControllerAnimated(true) } func contentViewControllerDidCancel(viewController: FxAContentViewController) { NSLog("didCancel") navigationController?.popToRootViewControllerAnimated(true) } }
mpl-2.0
37bb9ab6f8408c0057a1dc0051eea247
44.11
167
0.625249
5.916066
false
false
false
false
sman591/JSSAlertView
JSSAlertView.swift
1
17650
// // JSSAlertView // JSSAlertView // // Created by Jay Stakelon on 9/16/14. // Copyright (c) 2014 Jay Stakelon / https://github.com/stakes - all rights reserved. // // Inspired by and modeled after https://github.com/vikmeup/SCLAlertView-Swift // by Victor Radchenko: https://github.com/vikmeup // import Foundation import UIKit class JSSAlertView: UIViewController { var containerView:UIView! var alertBackgroundView:UIView! var dismissButton:UIButton! var cancelButton:UIButton! var buttonLabel:UILabel! var cancelButtonLabel:UILabel! var titleLabel:UILabel! var textView:UITextView! var rootViewController:UIViewController! var iconImage:UIImage! var iconImageView:UIImageView! var closeAction:(()->Void)! var cancelAction:(()->Void)! var isAlertOpen:Bool = false enum FontType { case Title, Text, Button } var titleFont = "HelveticaNeue-Light" var textFont = "HelveticaNeue" var buttonFont = "HelveticaNeue-Bold" var defaultColor = UIColorFromHex(0xF2F4F4, alpha: 1) enum TextColorTheme { case Dark, Light } var darkTextColor = UIColorFromHex(0x000000, alpha: 0.75) var lightTextColor = UIColorFromHex(0xffffff, alpha: 0.9) let baseHeight:CGFloat = 160.0 var alertWidth:CGFloat = 290.0 let buttonHeight:CGFloat = 70.0 let padding:CGFloat = 20.0 var viewWidth:CGFloat? var viewHeight:CGFloat? // Allow alerts to be closed/renamed in a chainable manner class JSSAlertViewResponder { let alertview: JSSAlertView init(alertview: JSSAlertView) { self.alertview = alertview } func addAction(action: ()->Void) { self.alertview.addAction(action) } func addCancelAction(action: ()->Void) { self.alertview.addCancelAction(action) } func setTitleFont(fontStr: String) { self.alertview.setFont(fontStr, type: .Title) } func setTextFont(fontStr: String) { self.alertview.setFont(fontStr, type: .Text) } func setButtonFont(fontStr: String) { self.alertview.setFont(fontStr, type: .Button) } func setTextTheme(theme: TextColorTheme) { self.alertview.setTextTheme(theme) } func close() { self.alertview.closeView(false) } } func setFont(fontStr: String, type: FontType) { switch type { case .Title: self.titleFont = fontStr if let font = UIFont(name: self.titleFont, size: 24) { self.titleLabel.font = font } else { self.titleLabel.font = UIFont.systemFontOfSize(24) } case .Text: if self.textView != nil { self.textFont = fontStr if let font = UIFont(name: self.textFont, size: 16) { self.textView.font = font } else { self.textView.font = UIFont.systemFontOfSize(16) } } case .Button: self.buttonFont = fontStr if let font = UIFont(name: self.buttonFont, size: 24) { self.buttonLabel.font = font } else { self.buttonLabel.font = UIFont.systemFontOfSize(24) } } // relayout to account for size changes self.viewDidLayoutSubviews() } func setTextTheme(theme: TextColorTheme) { switch theme { case .Light: recolorText(lightTextColor) case .Dark: recolorText(darkTextColor) } } func recolorText(color: UIColor) { titleLabel.textColor = color if textView != nil { textView.textColor = color } buttonLabel.textColor = color if cancelButtonLabel != nil { cancelButtonLabel.textColor = color } } required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } required override init() { super.init() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewWillLayoutSubviews() let size = UIScreen.mainScreen().bounds.size self.viewWidth = size.width self.viewHeight = size.height var yPos:CGFloat = 0.0 var contentWidth:CGFloat = self.alertWidth - (self.padding*2) // position the icon image view, if there is one if self.iconImageView != nil { yPos += iconImageView.frame.height var centerX = (self.alertWidth-self.iconImageView.frame.width)/2 self.iconImageView.frame.origin = CGPoint(x: centerX, y: self.padding) yPos += padding } // position the title let titleString = titleLabel.text! as NSString let titleAttr = [NSFontAttributeName:titleLabel.font] let titleSize = CGSize(width: contentWidth, height: 90) let titleRect = titleString.boundingRectWithSize(titleSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: titleAttr, context: nil) yPos += padding self.titleLabel.frame = CGRect(x: self.padding, y: yPos, width: self.alertWidth - (self.padding*2), height: ceil(titleRect.size.height)) yPos += ceil(titleRect.size.height) // position text if self.textView != nil { let textString = textView.text! as NSString let textAttr = [NSFontAttributeName:textView.font] let textSize = CGSize(width: contentWidth, height: 90) let textRect = textString.boundingRectWithSize(textSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textAttr, context: nil) self.textView.frame = CGRect(x: self.padding, y: yPos, width: self.alertWidth - (self.padding*2), height: ceil(textRect.size.height)*2) yPos += ceil(textRect.size.height) + padding/2 } // position the buttons yPos += self.padding var buttonWidth = self.alertWidth if self.cancelButton != nil { buttonWidth = self.alertWidth/2 self.cancelButton.frame = CGRect(x: 0, y: yPos, width: buttonWidth-0.5, height: self.buttonHeight) if self.cancelButtonLabel != nil { self.cancelButtonLabel.frame = CGRect(x: self.padding, y: (self.buttonHeight/2) - 15, width: buttonWidth - (self.padding*2), height: 30) } } var buttonX = buttonWidth == self.alertWidth ? 0 : buttonWidth self.dismissButton.frame = CGRect(x: buttonX, y: yPos, width: buttonWidth, height: self.buttonHeight) if self.buttonLabel != nil { self.buttonLabel.frame = CGRect(x: self.padding, y: (self.buttonHeight/2) - 15, width: buttonWidth - (self.padding*2), height: 30) } // set button fonts if self.buttonLabel != nil { buttonLabel.font = UIFont(name: self.buttonFont, size: 20) } if self.cancelButtonLabel != nil { cancelButtonLabel.font = UIFont(name: self.buttonFont, size: 20) } yPos += self.buttonHeight // size the background view self.alertBackgroundView.frame = CGRect(x: 0, y: 0, width: self.alertWidth, height: yPos) // size the container that holds everything together self.containerView.frame = CGRect(x: (self.viewWidth!-self.alertWidth)/2, y: (self.viewHeight! - yPos)/2, width: self.alertWidth, height: yPos) } func info(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder { var alertview = self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0x3498db, alpha: 1)) alertview.setTextTheme(.Light) return alertview } func success(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder { return self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0x2ecc71, alpha: 1)) } func warning(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder { return self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0xf1c40f, alpha: 1)) } func danger(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder { var alertview = self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0xe74c3c, alpha: 1)) alertview.setTextTheme(.Light) return alertview } func show(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil, color: UIColor?=nil, iconImage: UIImage?=nil) -> JSSAlertViewResponder { self.rootViewController = viewController.view.window!.rootViewController self.rootViewController.addChildViewController(self) self.rootViewController.view.addSubview(view) self.view.backgroundColor = UIColorFromHex(0x000000, alpha: 0.7) var baseColor:UIColor? if let customColor = color { baseColor = customColor } else { baseColor = self.defaultColor } var textColor = self.darkTextColor let sz = UIScreen.mainScreen().bounds.size self.viewWidth = sz.width self.viewHeight = sz.height // Container for the entire alert modal contents self.containerView = UIView() self.view.addSubview(self.containerView!) // Background view/main color self.alertBackgroundView = UIView() alertBackgroundView.backgroundColor = baseColor alertBackgroundView.layer.cornerRadius = 4 alertBackgroundView.layer.masksToBounds = true self.containerView.addSubview(alertBackgroundView!) // Icon self.iconImage = iconImage if self.iconImage != nil { self.iconImageView = UIImageView(image: self.iconImage) self.containerView.addSubview(iconImageView) } // Title self.titleLabel = UILabel() titleLabel.textColor = textColor titleLabel.numberOfLines = 0 titleLabel.textAlignment = .Center titleLabel.font = UIFont(name: self.titleFont, size: 24) titleLabel.text = title self.containerView.addSubview(titleLabel) // View text if let text = text? { self.textView = UITextView() self.textView.userInteractionEnabled = false textView.editable = false textView.textColor = textColor textView.textAlignment = .Center textView.font = UIFont(name: self.textFont, size: 16) textView.backgroundColor = UIColor.clearColor() textView.text = text self.containerView.addSubview(textView) } // Button self.dismissButton = UIButton() let buttonColor = UIImage.withColor(adjustBrightness(baseColor!, 0.8)) let buttonHighlightColor = UIImage.withColor(adjustBrightness(baseColor!, 0.9)) dismissButton.setBackgroundImage(buttonColor, forState: .Normal) dismissButton.setBackgroundImage(buttonHighlightColor, forState: .Highlighted) dismissButton.addTarget(self, action: "buttonTap", forControlEvents: .TouchUpInside) alertBackgroundView!.addSubview(dismissButton) // Button text self.buttonLabel = UILabel() buttonLabel.textColor = textColor buttonLabel.numberOfLines = 1 buttonLabel.textAlignment = .Center if let text = buttonText { buttonLabel.text = text } else { buttonLabel.text = "OK" } dismissButton.addSubview(buttonLabel) // Second cancel button if let btnText = cancelButtonText { self.cancelButton = UIButton() let buttonColor = UIImage.withColor(adjustBrightness(baseColor!, 0.8)) let buttonHighlightColor = UIImage.withColor(adjustBrightness(baseColor!, 0.9)) cancelButton.setBackgroundImage(buttonColor, forState: .Normal) cancelButton.setBackgroundImage(buttonHighlightColor, forState: .Highlighted) cancelButton.addTarget(self, action: "cancelButtonTap", forControlEvents: .TouchUpInside) alertBackgroundView!.addSubview(cancelButton) // Button text self.cancelButtonLabel = UILabel() cancelButtonLabel.alpha = 0.7 cancelButtonLabel.textColor = textColor cancelButtonLabel.numberOfLines = 1 cancelButtonLabel.textAlignment = .Center if let text = cancelButtonText { cancelButtonLabel.text = text } cancelButton.addSubview(cancelButtonLabel) } // Animate it in self.view.alpha = 0 UIView.animateWithDuration(0.2, animations: { self.view.alpha = 1 }) self.containerView.frame.origin.x = self.rootViewController.view.center.x self.containerView.center.y = -500 UIView.animateWithDuration(0.5, delay: 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: nil, animations: { self.containerView.center = self.rootViewController.view.center }, completion: { finished in }) isAlertOpen = true return JSSAlertViewResponder(alertview: self) } func addAction(action: ()->Void) { self.closeAction = action } func buttonTap() { closeView(true); } func addCancelAction(action: ()->Void) { self.cancelAction = action } func cancelButtonTap() { closeView(false); } func closeView(withCallback:Bool) { UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: nil, animations: { self.containerView.center.y = self.rootViewController.view.center.y + self.viewHeight! }, completion: { finished in UIView.animateWithDuration(0.1, animations: { self.view.alpha = 0 }, completion: { finished in if withCallback == true { if let action = self.closeAction? { action() } } self.removeView() }) }) } func removeView() { isAlertOpen = false self.view.removeFromSuperview() if let action = self.cancelAction? { action() } } } // Utility methods + extensions // Extend UIImage with a method to create // a UIImage from a solid color // // See: http://stackoverflow.com/questions/20300766/how-to-change-the-highlighted-color-of-a-uibutton extension UIImage { class func withColor(color: UIColor) -> UIImage { let rect = CGRectMake(0, 0, 1, 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } // For any hex code 0xXXXXXX and alpha value, // return a matching UIColor func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor { let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0 let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0 let blue = CGFloat(rgbValue & 0xFF)/256.0 return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha)) } // For any UIColor and brightness value where darker <1 // and lighter (>1) return an altered UIColor. // // See: http://a2apps.com.au/lighten-or-darken-a-uicolor/ func adjustBrightness(color:UIColor, amount:CGFloat) -> UIColor { var hue:CGFloat = 0 var saturation:CGFloat = 0 var brightness:CGFloat = 0 var alpha:CGFloat = 0 if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { brightness += (amount-1.0) brightness = max(min(brightness, 1.0), 0.0) return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) } return color }
mit
a5a690e3431469d5f8cb9b52b63e2bc3
36.794433
210
0.620113
4.765119
false
false
false
false
zhuyunfeng1224/XiheMtxx
XiheMtxx/VC/ToolBarItem.swift
1
2467
// // ToolBarItem.swift // EasyCard // // Created by echo on 2017/2/14. // Copyright © 2017年 羲和. All rights reserved. // import UIKit class ToolBarItem: UIView { var item: ToolBarItemObject! lazy var itemButton: VerticalButton = { let _itemButton = VerticalButton() _itemButton.translatesAutoresizingMaskIntoConstraints = false _itemButton.setTitleColor(UIColor.darkGray, for: .normal) _itemButton.setTitleColor(UIColor.colorWithHexString(hex: "#578fff"), for: .highlighted) _itemButton.titleLabel?.font = UIFont.systemFont(ofSize: 10) _itemButton.imageView?.contentMode = .center _itemButton.addTarget(self, action: #selector(touch(sender:)), for: .touchUpInside) _itemButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 5, right: 0) return _itemButton }() override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { super.updateConstraints() let itemButtonHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[itemButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["itemButton": self.itemButton]) self.addConstraints(itemButtonHConstraints) let itemButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-1-[itemButton]-1-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["itemButton": self.itemButton]) self.addConstraints(itemButtonVConstraints) } convenience init(frame: CGRect, itemObject: ToolBarItemObject) { self.init(frame: frame) self.addSubview(self.itemButton) self.setNeedsUpdateConstraints() self.item = itemObject self.itemButton.setImage(UIImage(named: self.item.imageName!), for: .normal) self.itemButton.setImage(UIImage(named: self.item.highlightImageName!), for: .highlighted) self.itemButton.setTitle(self.item.titleName, for: .normal) } func touch(sender:ToolBarItem) -> Void { if let action = self.item.action { action() } } } class ToolBarItemObject: NSObject { var imageName: String? var highlightImageName: String? var titleName: String? var action: (() -> ())? }
mit
564ab2ca4d8dc0284f828295b1e1cb8d
35.716418
210
0.668699
4.416517
false
false
false
false
khizkhiz/swift
test/expr/capture/top-level-guard.swift
9
1253
// RUN: %target-swift-frontend -dump-ast %s 2>&1 | FileCheck %s // RUN: %target-swift-frontend -emit-ir %s > /dev/null // RUN: %target-swift-frontend -dump-ast -DVAR %s 2>&1 | FileCheck %s // RUN: %target-swift-frontend -emit-ir -DVAR %s > /dev/null // CHECK: (top_level_code_decl // CHECK: (guard_stmt #if VAR guard var x = Optional(0) else { fatalError() } #else guard let x = Optional(0) else { fatalError() } #endif // CHECK: (top_level_code_decl _ = 0 // intervening code // CHECK-LABEL: (func_decl "function()" type='() -> ()' access=internal captures=(x<direct>) func function() { _ = x } // CHECK-LABEL: (closure_expr // CHECK: location={{.*}}top-level-guard.swift:[[@LINE+3]] // CHECK: captures=(x<direct>) // CHECK: (var_decl "closure" let closure: () -> Void = { _ = x } // CHECK-LABEL: (capture_list // CHECK: location={{.*}}top-level-guard.swift:[[@LINE+5]] // CHECK: (closure_expr // CHECK: location={{.*}}top-level-guard.swift:[[@LINE+3]] // CHECK: captures=(x) // CHECK: (var_decl "closureCapture" let closureCapture: () -> Void = { [x] in _ = x } // CHECK-LABEL: (defer_stmt // CHECK-NEXT: (func_decl implicit "$defer()" type='() -> ()' access=private captures=(x<direct><noescape>) defer { _ = x } #if VAR x = 5 #endif
apache-2.0
e8370f2316b2290d6b9d47d90bc59d93
24.571429
107
0.62091
2.88046
false
false
false
false
PartiuUFAL/partiuufal-ios
#PartiuUfal/#PartiuUfal/AppDelegate.swift
1
3324
// // AppDelegate.swift // #PartiuUfal // // Created by Rubens Pessoa on 18/06/17. // Copyright © 2017 Rubens Pessoa. All rights reserved. // import UIKit import Fabric import Crashlytics import Firebase import Parse import ParseFacebookUtilsV4 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { Fabric.with([Crashlytics.self]) FirebaseApp.configure() PUParseManager.setupParse() PFFacebookUtils.initializeFacebook(applicationLaunchOptions: launchOptions) self.window = UIWindow(frame: UIScreen.main.bounds) self.window!.backgroundColor = UIColor.white if PUUser.current() != nil { PUUser.current()?.fetchInBackground() let controller = PUMainViewController() controller.title = "#partiuUFAL" self.window!.rootViewController = UINavigationController(rootViewController: controller) } else { self.window!.rootViewController = PULoginViewController() } self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { FBSDKAppEvents.activateApp() // 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:. } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { let handled = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) return handled } }
agpl-3.0
2b1745c5e1c848165fe2d1ed5df1da8b
44.520548
285
0.724646
5.584874
false
false
false
false
tkremenek/swift
test/SILGen/async_builtins.swift
1
8716
// RUN: %target-swift-frontend -emit-silgen %s -module-name test -swift-version 5 -enable-experimental-concurrency -disable-availability-checking -parse-stdlib -sil-verify-all | %FileCheck %s // REQUIRES: concurrency import Swift public struct X { // CHECK-LABEL: sil hidden [ossa] @$s4test1XV14getCurrentTaskBoyYaF func getCurrentTask() async -> Builtin.NativeObject { // CHECK: builtin "getCurrentAsyncTask"() : $Builtin.NativeObject return Builtin.getCurrentAsyncTask() } // CHECK-LABEL: sil hidden [ossa] @$s4test1XV8doCancel4taskyBo_tF : $@convention(method) (@guaranteed Builtin.NativeObject, X) -> () func doCancel(task: Builtin.NativeObject) { // CHECK: builtin "cancelAsyncTask"(%0 : $Builtin.NativeObject) : $() Builtin.cancelAsyncTask(task) } // CHECK-LABEL: sil hidden [ossa] @$s4test1XV12launchFutureyyxlF : $@convention(method) <T> (@in_guaranteed T, X) -> () func launchFuture<T>(_ value: T) { // CHECK: builtin "createAsyncTask"<T>([[ZERO:%.*]] : $Int, [[FN:%.*]] : $@async @callee_guaranteed @substituted <τ_0_0> () -> (@out τ_0_0, @error Error) for <T>) : $(Builtin.NativeObject, Builtin.RawPointer) _ = Builtin.createAsyncTask(0) { () async throws -> T in return value } } // CHECK-LABEL: sil hidden [ossa] @$s4test1XV16launchGroupChild_5groupyx_BptlF : $@convention(method) <T> (@in_guaranteed T, Builtin.RawPointer, X) -> () { func launchGroupChild<T>(_ value: T, group: Builtin.RawPointer) { // CHECK: builtin "createAsyncTaskInGroup"<T>([[ZERO:%.*]] : $Int, [[GROUP:%.*]] : $Builtin.RawPointer, [[FN:%.*]] : $@async @callee_guaranteed @substituted <τ_0_0> () -> (@out τ_0_0, @error Error) for <T>) : $(Builtin.NativeObject, Builtin.RawPointer) _ = Builtin.createAsyncTaskInGroup(0, group) { () async throws -> T in return value } } public func launchRocker<T>(closure: @escaping () async throws -> T) { _ = Builtin.createAsyncTask(0, closure) } } // CHECK-LABEL: sil [ossa] @$s4test26usesWithUnsafeContinuationyyYaF : $@convention(thin) @async () -> () { public func usesWithUnsafeContinuation() async { // trivial resume type let _: Int = await Builtin.withUnsafeContinuation { c in } // CHECK: [[FN:%.*]] = function_ref @$s4test26usesWithUnsafeContinuationyyYaFyBcXEfU_ : $@convention(thin) (Builtin.RawUnsafeContinuation) -> () // CHECK: [[TMP:%.*]] = convert_function [[FN]] : $@convention(thin) (Builtin.RawUnsafeContinuation) -> () to $@convention(thin) @noescape (Builtin.RawUnsafeContinuation) -> () // CHECK: [[CLOSURE:%.*]] = thin_to_thick_function [[TMP]] // CHECK: [[BOX:%.*]] = alloc_stack $Int // CHECK: [[CC:%.*]] = get_async_continuation_addr Int, [[BOX]] : $*Int // CHECK: apply [[CLOSURE]]([[CC]]) : $@noescape @callee_guaranteed (Builtin.RawUnsafeContinuation) -> () // CHECK: await_async_continuation [[CC]] : $Builtin.RawUnsafeContinuation, resume bb1 // CHECK: bb1: // CHECK: [[RESULT:%.*]] = load [trivial] [[BOX]] : $*Int // CHECK: dealloc_stack [[BOX]] // loadable resume type let _: String = await Builtin.withUnsafeContinuation { c in } // CHECK: [[FN:%.*]] = function_ref @$s4test26usesWithUnsafeContinuationyyYaFyBcXEfU0_ : $@convention(thin) (Builtin.RawUnsafeContinuation) -> () // CHECK: [[TMP:%.*]] = convert_function [[FN]] : $@convention(thin) (Builtin.RawUnsafeContinuation) -> () to $@convention(thin) @noescape (Builtin.RawUnsafeContinuation) -> () // CHECK: [[CLOSURE:%.*]] = thin_to_thick_function [[TMP]] // CHECK: [[BOX:%.*]] = alloc_stack $String // CHECK: [[CC:%.*]] = get_async_continuation_addr String, [[BOX]] : $*String // CHECK: apply [[CLOSURE]]([[CC]]) : $@noescape @callee_guaranteed (Builtin.RawUnsafeContinuation) -> () // CHECK: await_async_continuation [[CC]] : $Builtin.RawUnsafeContinuation, resume bb2 // CHECK: bb2: // CHECK: [[RESULT:%.*]] = load [take] [[BOX]] : $*String // CHECK: destroy_value [[RESULT]] // CHECK: dealloc_stack [[BOX]] // address-only resume type let _: Any = await Builtin.withUnsafeContinuation { c in } // CHECK: [[FN:%.*]] = function_ref @$s4test26usesWithUnsafeContinuationyyYaFyBcXEfU1_ : $@convention(thin) (Builtin.RawUnsafeContinuation) -> () // CHECK: [[TMP:%.*]] = convert_function [[FN]] : $@convention(thin) (Builtin.RawUnsafeContinuation) -> () to $@convention(thin) @noescape (Builtin.RawUnsafeContinuation) -> () // CHECK: [[CLOSURE:%.*]] = thin_to_thick_function [[TMP]] // CHECK: [[BOX:%.*]] = alloc_stack $Any // CHECK: [[CC:%.*]] = get_async_continuation_addr Any, [[BOX]] : $*Any // CHECK: apply [[CLOSURE]]([[CC]]) : $@noescape @callee_guaranteed (Builtin.RawUnsafeContinuation) -> () // CHECK: await_async_continuation [[CC]] : $Builtin.RawUnsafeContinuation, resume bb3 // CHECK: bb3: // CHECK: [[COPY:%.*]] = alloc_stack $Any // CHECK: copy_addr [take] [[BOX]] to [initialization] [[COPY]] // CHECK: destroy_addr [[COPY]] // CHECK: dealloc_stack [[COPY]] // CHECK: dealloc_stack [[BOX]] } // CHECK-LABEL: sil [ossa] @$s4test34usesWithUnsafeThrowingContinuationyyYaKF : $@convention(thin) @async () -> @error Error { public func usesWithUnsafeThrowingContinuation() async throws { let _: Int = try await Builtin.withUnsafeThrowingContinuation { c in } // CHECK: [[FN:%.*]] = function_ref @$s4test34usesWithUnsafeThrowingContinuationyyYaKFyBcXEfU_ : $@convention(thin) (Builtin.RawUnsafeContinuation) -> () // CHECK: [[TMP:%.*]] = convert_function [[FN]] : $@convention(thin) (Builtin.RawUnsafeContinuation) -> () to $@convention(thin) @noescape (Builtin.RawUnsafeContinuation) -> () // CHECK: [[CLOSURE:%.*]] = thin_to_thick_function [[TMP]] // CHECK: [[BOX:%.*]] = alloc_stack $Int // CHECK: [[CC:%.*]] = get_async_continuation_addr [throws] Int, [[BOX]] : $*Int // CHECK: apply [[CLOSURE]]([[CC]]) : $@noescape @callee_guaranteed (Builtin.RawUnsafeContinuation) -> () // CHECK: await_async_continuation [[CC]] : $Builtin.RawUnsafeContinuation, resume bb1, error bb2 // CHECK: bb1: // CHECK: [[RESULT:%.*]] = load [trivial] [[BOX]] : $*Int // CHECK: dealloc_stack [[BOX]] // CHECK: bb2([[ERROR:%.*]] : @owned $Error): // CHECK: builtin "willThrow"([[ERROR]] : $Error) : $() // CHECK: dealloc_stack [[BOX]] // CHECK: throw [[ERROR]] } // Make sure we do the right thing when the closure value is non-trivial, // because it has captures and was formed by a partial_apply. public func usesWithUnsafeContinuationCaptures(fn: (Builtin.RawUnsafeContinuation) -> ()) async throws { let _: Int = await Builtin.withUnsafeContinuation { c in fn(c) } } // CHECK-LABEL: sil [ossa] @$s4test29resumeNonThrowingContinuationyyBc_SSntF public func resumeNonThrowingContinuation(_ cont: Builtin.RawUnsafeContinuation, _ value: __owned String) { // CHECK: bb0(%0 : $Builtin.RawUnsafeContinuation, %1 : @owned $String): // CHECK: [[BORROW:%.*]] = begin_borrow %1 : $String // CHECK-NEXT: [[COPY:%.*]] = copy_value [[BORROW]] : $String // CHECK-NEXT: builtin "resumeNonThrowingContinuationReturning"<String>(%0 : $Builtin.RawUnsafeContinuation, [[COPY]] : $String) // CHECK-NEXT: end_borrow [[BORROW]] : $String // CHECK-NEXT: destroy_value %1 : $String Builtin.resumeNonThrowingContinuationReturning(cont, value) } // CHECK-LABEL: sil [ossa] @$s4test26resumeThrowingContinuationyyBc_SSntF public func resumeThrowingContinuation(_ cont: Builtin.RawUnsafeContinuation, _ value: __owned String) { // CHECK: bb0(%0 : $Builtin.RawUnsafeContinuation, %1 : @owned $String): // CHECK: [[BORROW:%.*]] = begin_borrow %1 : $String // CHECK-NEXT: [[COPY:%.*]] = copy_value [[BORROW]] : $String // CHECK-NEXT: builtin "resumeThrowingContinuationReturning"<String>(%0 : $Builtin.RawUnsafeContinuation, [[COPY]] : $String) // CHECK-NEXT: end_borrow [[BORROW]] : $String // CHECK-NEXT: destroy_value %1 : $String Builtin.resumeThrowingContinuationReturning(cont, value) } // CHECK-LABEL: sil [ossa] @$s4test026resumeThrowingContinuationC0yyBc_s5Error_pntF public func resumeThrowingContinuationThrowing(_ cont: Builtin.RawUnsafeContinuation, _ error: __owned Error) { // CHECK: bb0(%0 : $Builtin.RawUnsafeContinuation, %1 : @owned $Error): // CHECK: [[BORROW:%.*]] = begin_borrow %1 : $Error // CHECK-NEXT: [[COPY:%.*]] = copy_value [[BORROW]] : $Error // CHECK-NEXT: builtin "resumeThrowingContinuationThrowing"(%0 : $Builtin.RawUnsafeContinuation, [[COPY]] : $Error) // CHECK-NEXT: end_borrow [[BORROW]] : $Error // CHECK-NEXT: destroy_value %1 : $Error Builtin.resumeThrowingContinuationThrowing(cont, error) }
apache-2.0
fe3ee3742e6053850fd03471111c3fbd
55.571429
256
0.657025
3.740661
false
true
false
false
prebid/prebid-mobile-ios
PrebidMobile/AdUnits/Native/NativeAdMarkupAsset.swift
1
2757
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation @objcMembers public class NativeAdMarkupAsset: NSObject, JsonDecodable { /// Optional if asseturl/dcourl is being used; required if embeded asset is being used public var id: Int? /// Set to 1 if asset is required. (bidder requires it to be displayed). public var required: Int? /// Title object for title assets. /// See TitleObject definition. public var title: NativeTitle? /// Image object for image assets. /// See ImageObject definition. public var img: NativeImage? /// Data object for ratings, prices etc. public var data: NativeData? /// Link object for call to actions. /// The link object applies if the asset item is activated (clicked). /// If there is no link object on the asset, the parent link object on the bid response applies. public var link: NativeLink? /// This object is a placeholder that may contain custom JSON agreed to by the parties to support /// flexibility beyond the standard defined in this specification public var ext: [String: Any]? public required init(jsonDictionary: [String: Any]) { guard !jsonDictionary.isEmpty else { Log.warn("The native title json dicitonary is empty") return } self.id = jsonDictionary["id"] as? Int self.required = jsonDictionary["required"] as? Int self.ext = jsonDictionary["ext"] as? [String: Any] if let titleDictionary = jsonDictionary["title"] as? [String: Any] { self.title = NativeTitle(jsonDictionary: titleDictionary) } else if let imgDictionary = jsonDictionary["img"] as? [String: Any] { self.img = NativeImage(jsonDictionary: imgDictionary) } else if let dataDictionary = jsonDictionary["data"] as? [String: Any] { self.data = NativeData(jsonDictionary: dataDictionary) } if let linkDictionary = jsonDictionary["link"] as? [String: Any] { self.link = NativeLink(jsonDictionary: linkDictionary) } } public override init() { super.init() } }
apache-2.0
2ebcca3a8e06c0b209921299a42619a4
36.616438
101
0.667881
4.599665
false
false
false
false
taoalpha/XMate
appcode/X-Mates/AppDelegate.swift
1
6343
// // AppDelegate.swift // X-Mates // // Created by Jiangyu Mao on 3/5/16. // Copyright © 2016 CloudGroup. All rights reserved. // import UIKit import CoreData import FBSDKCoreKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate { var window: UIWindow? var xmate = XMateManager() var picture = UIImage() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return FBSDKApplicationDelegate.sharedInstance().application( application, didFinishLaunchingWithOptions: launchOptions) } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application( application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } 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 "Cloud.X_Mates" 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("X_Mates", 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() } } } }
mit
4bbedf97557049d1914cebf7aa3f648f
49.736
288
0.756071
5.402044
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/SolutionsTests/Medium/Medium_092_Reverse_Linked_List_II_Test.swift
1
4760
// // Medium_092_Reverse_Linked_List_II_Test.swift // Solutions // // Created by Di Wu on 10/28/15. // Copyright © 2015 diwu. All rights reserved. // import XCTest class Medium_092_Reverse_Linked_List_II_Test: XCTestCase, SolutionsTestCase { private typealias Node = Medium_092_Reverse_Linked_List_II.Node private typealias ObjC_Node = ObjC_Medium_092_Reverse_Linked_List_II_Node func test_001() { let input0: [Int] = [1, 2, 3, 4, 5] let input1: Int = 2 let input2: Int = 4 let expected: [Int] = [1, 4, 3, 2, 5] asyncHelper(input0: input0, input1: input1, input2: input2, expected: expected) } func test_002() { let input0: [Int] = [1] let input1: Int = 1 let input2: Int = 1 let expected: [Int] = [1] asyncHelper(input0: input0, input1: input1, input2: input2, expected: expected) } func test_003() { let input0: [Int] = [1, 2, 3, 4, 5] let input1: Int = 4 let input2: Int = 5 let expected: [Int] = [1, 2, 3, 5, 4] asyncHelper(input0: input0, input1: input1, input2: input2, expected: expected) } func test_004() { let input0: [Int] = [1, 2] let input1: Int = 1 let input2: Int = 1 let expected: [Int] = [1, 2] asyncHelper(input0: input0, input1: input1, input2: input2, expected: expected) } func test_005() { let input0: [Int] = [1, 2] let input1: Int = 2 let input2: Int = 2 let expected: [Int] = [1, 2] asyncHelper(input0: input0, input1: input1, input2: input2, expected: expected) } func test_006() { let input0: [Int] = [1, 2, 3, 4, 5] let input1: Int = 2 let input2: Int = 3 let expected: [Int] = [1, 3, 2, 4, 5] asyncHelper(input0: input0, input1: input1, input2: input2, expected: expected) } func test_007() { let input0: [Int] = [1, 2, 3, 4, 5] let input1: Int = 1 let input2: Int = 2 let expected: [Int] = [2, 1, 3, 4, 5] asyncHelper(input0: input0, input1: input1, input2: input2, expected: expected) } func asyncHelper(input0: [Int], input1: Int, input2: Int, expected: [Int]) { weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName()) serialQueue().async(execute: { () -> Void in let result_swift: [Int] = self.helper2(Medium_092_Reverse_Linked_List_II.reverseBetween(self.helper1(input0), m: input1, n: input2)) assertHelper(expected == result_swift, problemName:self.problemName(), input: input0, resultValue: result_swift, expectedValue: expected) let result_objc: [Int] = self.objc_helper2(ObjC_Medium_092_Reverse_Linked_List_II.reverseBetween(self.objc_helper1(input0), m: input1, n: input2)) assertHelper(expected == result_objc, problemName:self.problemName(), input: input0, resultValue: result_objc, expectedValue: expected) if let unwrapped = expectation { unwrapped.fulfill() } }) waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in if error != nil { assertHelper(false, problemName:self.problemName(), input: input0, resultValue:self.timeOutName(), expectedValue: expected) } } } private func helper1(_ intArray: [Int]) -> Node? { var nodeArray: [Node] = [] for i in intArray { let node: Node = Node(value: i, next: nil) nodeArray.append(node) } if nodeArray.count == 0 { return nil } for i in 0..<nodeArray.count-1 { nodeArray[i].next = nodeArray[i+1] } return nodeArray[0] } private func helper2(_ head: Node?) -> [Int] { var res: [Int] = [] var localHead = head while localHead != nil { res.append(localHead!.value) localHead = localHead?.next } return res } private func objc_helper1(_ intArray: [Int]) -> ObjC_Node? { var nodeArray: [ObjC_Node] = [] for i in intArray { let node: ObjC_Node = ObjC_Node(i, next: nil) nodeArray.append(node) } if nodeArray.count == 0 { return nil } for i in 0..<nodeArray.count-1 { nodeArray[i].next = nodeArray[i+1] } return nodeArray[0] } private func objc_helper2(_ head: ObjC_Node?) -> [Int] { var res: [Int] = [] var localHead = head while localHead != nil { res.append(localHead!.value) localHead = localHead?.next } return res } }
mit
ed0a98f8e89c6db05d2cc375ee2a9bb8
36.769841
158
0.563144
3.556801
false
true
false
false
iThinkersTeam/Blog
SnapKitLoginScreen/Pods/SnapKit/Source/ConstraintAttributes.swift
1
7525
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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(iOS) || os(tvOS) import UIKit #else import AppKit #endif internal struct ConstraintAttributes: OptionSet { internal init(rawValue: UInt) { self.rawValue = rawValue } internal init(_ rawValue: UInt) { self.init(rawValue: rawValue) } internal init(nilLiteral: ()) { self.rawValue = 0 } private(set) internal var rawValue: UInt internal static var allZeros: ConstraintAttributes { return self.init(0) } internal static func convertFromNilLiteral() -> ConstraintAttributes { return self.init(0) } internal var boolValue: Bool { return self.rawValue != 0 } internal func toRaw() -> UInt { return self.rawValue } internal static func fromRaw(_ raw: UInt) -> ConstraintAttributes? { return self.init(raw) } internal static func fromMask(_ raw: UInt) -> ConstraintAttributes { return self.init(raw) } // normal internal static var none: ConstraintAttributes { return self.init(0) } internal static var left: ConstraintAttributes { return self.init(1) } internal static var top: ConstraintAttributes { return self.init(2) } internal static var right: ConstraintAttributes { return self.init(4) } internal static var bottom: ConstraintAttributes { return self.init(8) } internal static var leading: ConstraintAttributes { return self.init(16) } internal static var trailing: ConstraintAttributes { return self.init(32) } internal static var width: ConstraintAttributes { return self.init(64) } internal static var height: ConstraintAttributes { return self.init(128) } internal static var centerX: ConstraintAttributes { return self.init(256) } internal static var centerY: ConstraintAttributes { return self.init(512) } internal static var lastBaseline: ConstraintAttributes { return self.init(1024) } @available(iOS 8.0, OSX 10.11, *) internal static var firstBaseline: ConstraintAttributes { return self.init(2048) } @available(iOS 8.0, *) internal static var leftMargin: ConstraintAttributes { return self.init(4096) } @available(iOS 8.0, *) internal static var rightMargin: ConstraintAttributes { return self.init(8192) } @available(iOS 8.0, *) internal static var topMargin: ConstraintAttributes { return self.init(16384) } @available(iOS 8.0, *) internal static var bottomMargin: ConstraintAttributes { return self.init(32768) } @available(iOS 8.0, *) internal static var leadingMargin: ConstraintAttributes { return self.init(65536) } @available(iOS 8.0, *) internal static var trailingMargin: ConstraintAttributes { return self.init(131072) } @available(iOS 8.0, *) internal static var centerXWithinMargins: ConstraintAttributes { return self.init(262144) } @available(iOS 8.0, *) internal static var centerYWithinMargins: ConstraintAttributes { return self.init(524288) } // aggregates internal static var edges: ConstraintAttributes { return self.init(15) } internal static var size: ConstraintAttributes { return self.init(192) } internal static var center: ConstraintAttributes { return self.init(768) } @available(iOS 8.0, *) internal static var margins: ConstraintAttributes { return self.init(61440) } @available(iOS 8.0, *) internal static var centerWithinMargins: ConstraintAttributes { return self.init(786432) } internal var layoutAttributes: [NSLayoutAttribute] { var attrs = [NSLayoutAttribute]() if (self.contains(ConstraintAttributes.left)) { attrs.append(.left) } if (self.contains(ConstraintAttributes.top)) { attrs.append(.top) } if (self.contains(ConstraintAttributes.right)) { attrs.append(.right) } if (self.contains(ConstraintAttributes.bottom)) { attrs.append(.bottom) } if (self.contains(ConstraintAttributes.leading)) { attrs.append(.leading) } if (self.contains(ConstraintAttributes.trailing)) { attrs.append(.trailing) } if (self.contains(ConstraintAttributes.width)) { attrs.append(.width) } if (self.contains(ConstraintAttributes.height)) { attrs.append(.height) } if (self.contains(ConstraintAttributes.centerX)) { attrs.append(.centerX) } if (self.contains(ConstraintAttributes.centerY)) { attrs.append(.centerY) } if (self.contains(ConstraintAttributes.lastBaseline)) { attrs.append(.lastBaseline) } #if os(iOS) || os(tvOS) if (self.contains(ConstraintAttributes.firstBaseline)) { attrs.append(.firstBaseline) } if (self.contains(ConstraintAttributes.leftMargin)) { attrs.append(.leftMargin) } if (self.contains(ConstraintAttributes.rightMargin)) { attrs.append(.rightMargin) } if (self.contains(ConstraintAttributes.topMargin)) { attrs.append(.topMargin) } if (self.contains(ConstraintAttributes.bottomMargin)) { attrs.append(.bottomMargin) } if (self.contains(ConstraintAttributes.leadingMargin)) { attrs.append(.leadingMargin) } if (self.contains(ConstraintAttributes.trailingMargin)) { attrs.append(.trailingMargin) } if (self.contains(ConstraintAttributes.centerXWithinMargins)) { attrs.append(.centerXWithinMargins) } if (self.contains(ConstraintAttributes.centerYWithinMargins)) { attrs.append(.centerYWithinMargins) } #endif return attrs } } internal func + (left: ConstraintAttributes, right: ConstraintAttributes) -> ConstraintAttributes { return left.union(right) } internal func +=(left: inout ConstraintAttributes, right: ConstraintAttributes) { left.formUnion(right) } internal func -=(left: inout ConstraintAttributes, right: ConstraintAttributes) { left.subtract(right) } internal func ==(left: ConstraintAttributes, right: ConstraintAttributes) -> Bool { return left.rawValue == right.rawValue }
mit
28090fa965ccddfa49f9242cd2fa10ee
38.397906
99
0.672824
4.765674
false
false
false
false
Candyroot/DesignPattern
iterator/iterator/Menu.swift
1
1235
// // Menu.swift // iterator // // Created by Bing Liu on 11/27/14. // Copyright (c) 2014 UnixOSS. All rights reserved. // import Foundation class Menu: MenuComponent { var menuComponents = [MenuComponent]() let name: String let description: String init(name: String, description: String) { self.name = name self.description = description } override func add(menuComponent: MenuComponent) { menuComponents.append(menuComponent) } override func remove(menuComponent: MenuComponent) { for i in 0..<menuComponents.count { if menuComponents[i] === menuComponent { menuComponents.removeAtIndex(i) } } } override func getChild(i: Int) -> MenuComponent { return menuComponents[i] } override func getName() -> String { return name } override func getDescription() -> String { return description } override func print() { println("\n\(getName()), \(getDescription())") println("---------------------") for menuComponent in menuComponents { menuComponent.print() } } }
apache-2.0
8302f4ffed7eb21110ca5bc48d7d3950
21.454545
56
0.563563
4.786822
false
false
false
false
glorybird/KeepReading2
kr/Pods/YapDatabaseExtensions/YapDatabaseExtensions/Shared/Persistable/Persistable_ObjectWithNoMetadata.swift
3
7173
// // Persistable_ObjectWithNoMetadata.swift // YapDatabaseExtensions // // Created by Daniel Thorpe on 11/10/2015. // // import Foundation import ValueCoding // MARK: - Persistable extension Persistable where Self: NSCoding, Self.MetadataType == Void { // Writing /** Write the item using an existing transaction. - parameter transaction: a YapDatabaseReadWriteTransaction - returns: the receiver. */ public func write<WriteTransaction: WriteTransactionType>(transaction: WriteTransaction) -> Self { return transaction.write(self) } /** Write the item synchronously using a connection. - parameter connection: a YapDatabaseConnection - returns: the receiver. */ public func write<Connection: ConnectionType>(connection: Connection) -> Self { return connection.write(self) } /** Write the item asynchronously using a connection. - parameter connection: a YapDatabaseConnection - returns: a closure which receives as an argument the receiver of this function. */ public func asyncWrite<Connection: ConnectionType>(connection: Connection, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Self -> Void)? = .None) { return connection.asyncWrite(self, queue: queue, completion: completion) } /** Write the item synchronously using a connection as an NSOperation - parameter connection: a YapDatabaseConnection - returns: an `NSOperation` */ public func writeOperation<Connection: ConnectionType>(connection: Connection) -> NSOperation { return NSBlockOperation { connection.write(self) } } } extension SequenceType where Generator.Element: Persistable, Generator.Element: NSCoding, Generator.Element.MetadataType == Void { /** Write the items using an existing transaction. - parameter transaction: a WriteTransactionType e.g. YapDatabaseReadWriteTransaction - returns: the receiver. */ public func write<WriteTransaction: WriteTransactionType>(transaction: WriteTransaction) -> [Generator.Element] { return transaction.write(self) } /** Write the items synchronously using a connection. - parameter connection: a ConnectionType e.g. YapDatabaseConnection - returns: the receiver. */ public func write<Connection: ConnectionType>(connection: Connection) -> [Generator.Element] { return connection.write(self) } /** Write the items asynchronously using a connection. - parameter connection: a ConnectionType e.g. YapDatabaseConnection - returns: a closure which receives as an argument the receiver of this function. */ public func asyncWrite<Connection: ConnectionType>(connection: Connection, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Generator.Element] -> Void)? = .None) { return connection.asyncWrite(self, queue: queue, completion: completion) } /** Write the item synchronously using a connection as an NSOperation - parameter connection: a YapDatabaseConnection - returns: an `NSOperation` */ public func writeOperation<Connection: ConnectionType>(connection: Connection) -> NSOperation { return NSBlockOperation { connection.write(self) } } } // MARK: - Readable extension Readable where ItemType: NSCoding, ItemType: Persistable, ItemType.MetadataType == Void { func inTransaction(transaction: Database.Connection.ReadTransaction, atIndex index: YapDB.Index) -> ItemType? { return transaction.readAtIndex(index) } func inTransactionAtIndex(transaction: Database.Connection.ReadTransaction) -> YapDB.Index -> ItemType? { return { self.inTransaction(transaction, atIndex: $0) } } func atIndexInTransaction(index: YapDB.Index) -> Database.Connection.ReadTransaction -> ItemType? { return { self.inTransaction($0, atIndex: index) } } func atIndexesInTransaction< Indexes where Indexes: SequenceType, Indexes.Generator.Element == YapDB.Index>(indexes: Indexes) -> Database.Connection.ReadTransaction -> [ItemType] { let atIndex = inTransactionAtIndex return { indexes.flatMap(atIndex($0)) } } func inTransaction(transaction: Database.Connection.ReadTransaction, byKey key: String) -> ItemType? { return inTransaction(transaction, atIndex: ItemType.indexWithKey(key)) } func inTransactionByKey(transaction: Database.Connection.ReadTransaction) -> String -> ItemType? { return { self.inTransaction(transaction, byKey: $0) } } func byKeyInTransaction(key: String) -> Database.Connection.ReadTransaction -> ItemType? { return { self.inTransaction($0, byKey: key) } } func byKeysInTransaction(keys: [String]? = .None) -> Database.Connection.ReadTransaction -> [ItemType] { let byKey = inTransactionByKey return { transaction in let keys = keys ?? transaction.keysInCollection(ItemType.collection) return keys.flatMap(byKey(transaction)) } } /** Reads the item at a given index. - parameter index: a YapDB.Index - returns: an optional `ItemType` */ public func atIndex(index: YapDB.Index) -> ItemType? { return sync(atIndexInTransaction(index)) } /** Reads the items at the indexes. - parameter indexes: a SequenceType of YapDB.Index values - returns: an array of `ItemType` */ public func atIndexes< Indexes where Indexes: SequenceType, Indexes.Generator.Element == YapDB.Index>(indexes: Indexes) -> [ItemType] { return sync(atIndexesInTransaction(indexes)) } /** Reads the item at the key. - parameter key: a String - returns: an optional `ItemType` */ public func byKey(key: String) -> ItemType? { return sync(byKeyInTransaction(key)) } /** Reads the items by the keys. - parameter keys: a SequenceType of String values - returns: an array of `ItemType` */ public func byKeys< Keys where Keys: SequenceType, Keys.Generator.Element == String>(keys: Keys) -> [ItemType] { return sync(byKeysInTransaction(Array(keys))) } /** Reads all the `ItemType` in the database. - returns: an array of `ItemType` */ public func all() -> [ItemType] { return sync(byKeysInTransaction()) } /** Returns th existing items and missing keys.. - parameter keys: a SequenceType of String values - returns: a tuple of type `([ItemType], [String])` */ public func filterExisting(keys: [String]) -> (existing: [ItemType], missing: [String]) { let existingInTransaction = byKeysInTransaction(keys) return sync { transaction -> ([ItemType], [String]) in let existing = existingInTransaction(transaction) let existingKeys = existing.map(keyForPersistable) let missingKeys = keys.filter { !existingKeys.contains($0) } return (existing, missingKeys) } } }
apache-2.0
c1b9306002fd9dcf5258d069ad6bd251
30.88
185
0.674055
4.753479
false
false
false
false
nghialv/Sapporo
Example/Example/Source/Calendar/CalendarLayout.swift
1
6609
// // CalendarLayout.swift // Example // // Created by Le VanNghia on 6/29/15. // Copyright (c) 2015 Le Van Nghia. All rights reserved. // // http://www.objc.io/issues/3-views/collection-view-layouts import UIKit import Sapporo let DaysPerWeek: CGFloat = 7 let HoursPerDay: CGFloat = 24 let HorizontalSpacing: CGFloat = 10 let HeightPerHour: CGFloat = 50 let DayHeaderHeight: CGFloat = 40 let HourHeaderWidth: CGFloat = 100 final class CalendarLayout: SALayout { override var collectionViewContentSize: CGSize { let contentWidth = collectionView!.bounds.size.width let contentHeight = CGFloat(DayHeaderHeight + (HeightPerHour * HoursPerDay)) return CGSize(width: contentWidth, height: contentHeight) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributes = [UICollectionViewLayoutAttributes]() // Cells let visibleIndexPaths = indexPathsOfItemsInRect(rect) layoutAttributes += visibleIndexPaths.compactMap { self.layoutAttributesForItem(at: $0) } // Supplementary views let dayHeaderViewIndexPaths = indexPathsOfDayHeaderViewsInRect(rect) layoutAttributes += dayHeaderViewIndexPaths.compactMap { self.layoutAttributesForSupplementaryView(ofKind: CalendarHeaderType.day.rawValue, at: $0) } let hourHeaderViewIndexPaths = indexPathsOfHourHeaderViewsInRect(rect) layoutAttributes += hourHeaderViewIndexPaths.compactMap { self.layoutAttributesForSupplementaryView(ofKind: CalendarHeaderType.hour.rawValue, at: $0) } return layoutAttributes } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) if let event = (getCellModel(indexPath) as? CalendarEventCellModel)?.event { attributes.frame = frameForEvent(event) } return attributes } override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath) let totalWidth = collectionViewContentSize.width if elementKind == CalendarHeaderType.day.rawValue { let availableWidth = totalWidth - HourHeaderWidth let widthPerDay = availableWidth / DaysPerWeek attributes.frame = .init( x: HourHeaderWidth + (widthPerDay * CGFloat(indexPath.item)), y: 0, width: widthPerDay, height: DayHeaderHeight ) attributes.zIndex = -10 } else if elementKind == CalendarHeaderType.hour.rawValue { attributes.frame = .init( x: 0, y: DayHeaderHeight + HeightPerHour * CGFloat(indexPath.item), width: totalWidth, height: HeightPerHour ) attributes.zIndex = -10 } return attributes } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } } extension CalendarLayout { func indexPathsOfEventsBetweenMinDayIndex(_ minDayIndex: Int, maxDayIndex: Int, minStartHour: Int, maxStartHour: Int) -> [IndexPath] { guard let cellModels = getCellModels(0) as? [CalendarEventCellModel] else { return [] } var indexPaths: [IndexPath] = [] for (index, cellModel) in cellModels.enumerated() where cellModel.event.day >= minDayIndex && cellModel.event.day <= maxDayIndex && cellModel.event.startHour >= minStartHour && cellModel.event.startHour <= maxStartHour { let indexPath = IndexPath(item: index, section: 0) indexPaths.append(indexPath) } return indexPaths } func indexPathsOfItemsInRect(_ rect: CGRect) -> [IndexPath] { let minVisibleDay = dayIndexFromXCoordinate(rect.minX) let maxVisibleDay = dayIndexFromXCoordinate(rect.maxX) let minVisibleHour = hourIndexFromYCoordinate(rect.minY) let maxVisibleHour = hourIndexFromYCoordinate(rect.maxY) return indexPathsOfEventsBetweenMinDayIndex(minVisibleDay, maxDayIndex: maxVisibleDay, minStartHour: minVisibleHour, maxStartHour: maxVisibleHour) } func dayIndexFromXCoordinate(_ xPosition: CGFloat) -> Int { let contentWidth = collectionViewContentSize.width - HourHeaderWidth let widthPerDay = contentWidth / DaysPerWeek let dayIndex = max(0, Int((xPosition - HourHeaderWidth) / widthPerDay)) return dayIndex } func hourIndexFromYCoordinate(_ yPosition: CGFloat) -> Int { let hourIndex = max(0, Int((yPosition - DayHeaderHeight) / HeightPerHour)) return hourIndex } func indexPathsOfDayHeaderViewsInRect(_ rect: CGRect) -> [IndexPath] { if rect.minY > DayHeaderHeight { return [] } let minDayIndex = dayIndexFromXCoordinate(rect.minX) let maxDayIndex = dayIndexFromXCoordinate(rect.maxX) return (minDayIndex...maxDayIndex).map { index -> IndexPath in IndexPath(item: index, section: 0) } } func indexPathsOfHourHeaderViewsInRect(_ rect: CGRect) -> [IndexPath] { if rect.minX > HourHeaderWidth { return [] } let minHourIndex = hourIndexFromYCoordinate(rect.minY) let maxHourIndex = hourIndexFromYCoordinate(rect.maxY) return (minHourIndex...maxHourIndex).map { index -> IndexPath in IndexPath(item: index, section: 0) } } func frameForEvent(_ event: CalendarEvent) -> CGRect { let totalWidth = collectionViewContentSize.width - HourHeaderWidth let widthPerDay = totalWidth / DaysPerWeek var frame = CGRect.zero frame.origin.x = HourHeaderWidth + widthPerDay * CGFloat(event.day) frame.origin.y = DayHeaderHeight + HeightPerHour * CGFloat(event.startHour) frame.size.width = widthPerDay frame.size.height = CGFloat(event.durationInHours) * HeightPerHour frame = frame.insetBy(dx: HorizontalSpacing / 2.0, dy: 0) return frame } }
mit
bb5882ba3b080274bafc49093bcb57bd
37.876471
182
0.654259
5.139191
false
false
false
false
1000copy/fin
V2ex-Swift/AppDelegate.swift
1
5449
@UIApplicationMain class App: TJApp { var star : BigBrotherWatchingYou! override func onLoad(){ URLProtocol.registerClass(WebViewImageProtocol.self) let drawer = Drawer() self.window = TJWin(drawer) star = BigBrotherWatchingYou(drawer) HUDsetup() } } class Drawer : TJDrawer{ var centerNav : V2EXNavigationController! var home : HomeViewController! init(){ let h = HomeViewController() let c = V2EXNavigationController(rootViewController: h) let leftViewController = LeftViewController() let rightViewController = RightViewController() super.init(c, leftViewController, rightViewController) self.centerNav = c self.home = h } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // // WebViewImageProtocol.swift // V2ex-Swift // // Created by huangfeng on 16/10/25. // Copyright © 2016年 Fin. All rights reserved. // import UIKit import Kingfisher fileprivate let WebviewImageProtocolHandledKey = "WebviewImageProtocolHandledKey" class WebViewImageProtocol: URLProtocol ,URLSessionDataDelegate { var session: URLSession? var dataTask: URLSessionDataTask? var imageData: Data? override class func canInit(with request: URLRequest) -> Bool{ print( request.url) guard let pathExtension = request.url?.pathExtension else{ return false } if ["jpg","jpeg","png","gif"].contains(pathExtension.lowercased()) { if let tag = self.property(forKey: WebviewImageProtocolHandledKey, in: request) as? Bool , tag == true { return false } return true } return false } override class func canonicalRequest(for request: URLRequest) -> URLRequest{ return request } override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool { return super.requestIsCacheEquivalent(a, to: b) } override func startLoading() { let resource = ImageResource(downloadURL: self.request.url!) let data = try? Data(contentsOf:URL(fileURLWithPath: KingfisherManager.shared.cache.cachePath(forKey: resource.cacheKey))) if let data = data { //在磁盘上找到Kingfisher的缓存,则直接使用缓存 var mimeType = data.contentTypeForImageData() mimeType.append(";charset=UTF-8") let header = ["Content-Type": mimeType ,"Content-Length": String(data.count)] let response = HTTPURLResponse(url: self.request.url!, statusCode: 200, httpVersion: "1.1", headerFields: header)! self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed) self.client?.urlProtocol(self, didLoad: data) self.client?.urlProtocolDidFinishLoading(self) } else{ //没找到图片则下载 guard let newRequest = (self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else {return} WebViewImageProtocol.setProperty(true, forKey: WebviewImageProtocolHandledKey, in: newRequest) self.session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) self.dataTask = self.session?.dataTask(with:newRequest as URLRequest) self.dataTask?.resume() } } override func stopLoading() { self.dataTask?.cancel() self.dataTask = nil self.imageData = nil } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed) completionHandler(.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { self.client?.urlProtocol(self, didLoad: data) if self.imageData == nil { self.imageData = data } else{ self.imageData!.append(data) } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let error = error { self.client?.urlProtocol(self, didFailWithError: error) } else{ self.client?.urlProtocolDidFinishLoading(self) let resource = ImageResource(downloadURL: self.request.url!) guard let imageData = self.imageData else { return } //保存图片到Kingfisher guard let image = DefaultCacheSerializer.default.image(with: imageData, options: nil) else { return } KingfisherManager.shared.cache.store(image, original: imageData, forKey: resource.cacheKey, toDisk: true, completionHandler: nil) } } } fileprivate extension Data { func contentTypeForImageData() -> String { var c:UInt8 = 0 self.copyBytes(to: &c, count: MemoryLayout<UInt8>.size * 1) switch c { case 0xFF: return "image/jpeg"; case 0x89: return "image/png"; case 0x47: return "image/gif"; default: return "" } } } import UIKit import Fabric //import Crashlytics import DrawerController //import SVProgressHUD
mit
484584423d1ee378295320bd0a054fb8
38.313869
179
0.649647
4.834829
false
false
false
false
exyte/Macaw
Source/model/geom2d/Arc.swift
1
1553
import Foundation open class Arc: Locus { public let ellipse: Ellipse public let shift: Double public let extent: Double public init(ellipse: Ellipse, shift: Double = 0, extent: Double = 0) { self.ellipse = ellipse self.shift = shift self.extent = extent } override open func bounds() -> Rect { return Rect( x: ellipse.cx - ellipse.rx, y: ellipse.cy - ellipse.ry, w: ellipse.rx * 2.0, h: ellipse.ry * 2.0) } override open func toPath() -> Path { let rx = ellipse.rx let ry = ellipse.ry let cx = ellipse.cx let cy = ellipse.cy var delta = extent if shift == 0.0 && abs(extent - .pi * 2.0) < 0.00001 { delta = .pi * 2.0 - 0.001 } let theta1 = shift let theta2 = theta1 + delta let x1 = cx + rx * cos(theta1) let y1 = cy + ry * sin(theta1) let x2 = cx + rx * cos(theta2) let y2 = cy + ry * sin(theta2) let largeArcFlag = abs(delta) > .pi ? true : false let sweepFlag = delta > 0.0 ? true : false return PathBuilder(segment: PathSegment(type: .M, data: [x1, y1])).A(rx, ry, 0.0, largeArcFlag, sweepFlag, x2, y2).build() } override func equals<T>(other: T) -> Bool where T: Locus { guard let other = other as? Arc else { return false } return ellipse == other.ellipse && shift == other.shift && extent == other.extent } }
mit
33280cad28cdf363034eb15fcf0e884a
26.245614
130
0.526079
3.662736
false
false
false
false
larryhou/swift
LocateMe/LocateMe/SetupViewController.swift
1
3809
// // SetupViewController.swift // LocateMe // // Created by doudou on 8/16/14. // Copyright (c) 2014 larryhou. All rights reserved. // import Foundation import UIKit import CoreLocation @objc protocol SetupSettingReceiver { func setupSetting(setting: LocateSettingInfo) } class LocateSettingInfo: NSObject { let accuracy: CLLocationAccuracy let sliderValue: Float init(accuracy: CLLocationAccuracy, sliderValue: Float) { self.accuracy = accuracy self.sliderValue = sliderValue } override var description: String { return super.description + "{accuracy:\(accuracy), sliderValue:\(sliderValue)}" } } class SetupViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { struct AccuracyOption { var label: String var value: CLLocationAccuracy } struct InitialSetupValue { let selectedIndex: Int let sliderValue: Float } @IBOutlet weak var accuracyPicker: UIPickerView! @IBOutlet weak var slider: UISlider! @IBOutlet weak var label: UILabel! private var options: [AccuracyOption]! private var formater: NSNumberFormatter! private var selectedPickerIndex: Int! private var initial: InitialSetupValue! var setting: LocateSettingInfo { return LocateSettingInfo(accuracy: options[selectedPickerIndex].value, sliderValue: slider.value) } override func viewDidLoad() { options = [] options.append(AccuracyOption(label: localizeString("AccuracyBest"), value: kCLLocationAccuracyBest)) options.append(AccuracyOption(label: localizeString("Accuracy10"), value: kCLLocationAccuracyNearestTenMeters)) options.append(AccuracyOption(label: localizeString("Accuracy100"), value: kCLLocationAccuracyHundredMeters)) options.append(AccuracyOption(label: localizeString("Accuracy1000"), value: kCLLocationAccuracyKilometer)) options.append(AccuracyOption(label: localizeString("Accuracy3000"), value: kCLLocationAccuracyThreeKilometers)) formater = NSNumberFormatter() formater.minimumFractionDigits = 1 formater.minimumIntegerDigits = 1 initial = InitialSetupValue(selectedIndex: 2, sliderValue: slider.value) selectedPickerIndex = initial.selectedIndex } override func viewWillAppear(animated: Bool) { accuracyPicker.selectRow(selectedPickerIndex, inComponent: 0, animated: true) slider.value = setting.sliderValue sliderChangedValue(slider) } override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if segue.identifier == "SettingSegue" { if segue.destinationViewController is SetupSettingReceiver { var reciever: SetupSettingReceiver = segue.destinationViewController as SetupSettingReceiver reciever.setupSetting(setting) } } } @IBAction func reset(segue: UIStoryboardSegue) { accuracyPicker.selectRow(initial.selectedIndex, inComponent: 0, animated: true) slider.value = initial.sliderValue sliderChangedValue(slider) } @IBAction func sliderChangedValue(sender: UISlider) { label.text = formater.stringFromNumber(sender.value) } func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int { return 1 } func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int { return options.count } func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! { return options[row].label } func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { selectedPickerIndex = row } }
mit
a1b18ee4c1e7facd877d46ce547b6dc8
32.707965
120
0.711473
5.203552
false
false
false
false
to4iki/EitherSwift
EitherSwift/Either.swift
1
7329
// // Either.swift // EitherSwift // // Created by to4iki on 2/25/15. // Copyright (c) 2015 to4iki. All rights reserved. // /** Represents a value of one of two possible types (a disjoint union.) Instances of Either are either an instance of Left or Right. - Left: Left Value - Right: Right Value */ public enum Either<A, B>: EitherType { case Left(A) case Right(B) /** A left `Either` returning `value` This form is preferred to `Either.Left(Box(value))` because it does not require dealing with `Box()` - parameter value: result value - returns: Left */ public static func left(value: A) -> Either<A, B> { return Left(value) } /** A right `Either` returning `value` This form is preferred to `Either.Right(Box(value))` because it does not require dealing with `Box()` - parameter value: result value - returns: Right */ public static func right(value: B) -> Either<A, B> { return Right(value) } /// Projects this `Either` as a `Left`. public var left: LeftProjection<A, B> { return LeftProjection(self) } /// Projects this `Either` as a `Right`. public var right: RightProjection<A, B> { return RightProjection(self) } /// Returns `true` if this is a `Left`, `false` otherwise. public var isLeft: Bool { switch self { case .Left: return true case .Right: return false } } /// Returns `true` if this is a `Right`, `false` otherwise. public var isRight: Bool { switch self { case .Left: return false case .Right: return true } } /** Applies `fa` if this is a `Left` or `fb` if this is a `Right`. - parameter fa: the function to apply if this is a `Left` - parameter fb: the function to apply if this is a `Right` - returns: the results of applying the function */ public func fold<X>(fa: A -> X, _ fb: B -> X) -> X { switch self { case .Left(let l): return fa(l) case .Right(let r): return fb(r) } } /** Flip the left/right values in this disjunction. Alias for `~` - returns: the results of swap */ public func swap() -> Either<B, A> { switch self { case .Left(let l): return Either<B, A>.Right(l) case .Right(let r): return Either<B, A>.Left(r) } } /** Return the right value of this disjunction or the given default if left. like null Coalescing Operator. Alias for `??` - parameter or: the rawValue function to bind across `Left`. - returns: Right Value */ public func getOrElse(or: () -> B) -> B { return right.getOrElse(or) } /** Return this if it is a right, otherwise, return the given value. like null Coalescing Operator. Alias for `|||` - parameter or: the rawValue function to bind across `Left`. - returns: Either<A, B> */ public func orElse(or: () -> B) -> Either<A, B> { return fold({ _ in Either.right(or()) }, { _ in self }) } /** Return this if it is a right, otherwise, return the given value. like null Coalescing Operator. Alias for `|||` - parameter or: the either function to bind across `Left`. - returns: Either<A, B> */ public func orElse(or: () -> Either<A, B>) -> Either<A, B> { return fold({ _ in or() }, { _ in self }) } /** Maps `Right` values with `f`, and re-wraps `Left` values. - parameter f: the function to bind across `Right`. - returns: Either<A, X> */ public func map<X>(f: B -> X) -> Either<A, X> { return right.map(f) } /**. Returns the result of applying `f` to `Right` values, or re-wrapping `Left` values. Alias for `>>-` - parameter f: the function to bind across `Right`. - returns: Either<A, X> */ public func flatMap<X>(f: B -> Either<A, X>) -> Either<A, X> { return right.flatMap(f) } /** If the condition is satisfied, return the given `B` in `Right`, otherwise, return the given `A` in `Left`. - parameter test: predicate - parameter right: the either function to bind across `Right`. - parameter left: the either function to bind across `Left`. - returns: Either<A, B> */ public static func cond<A, B>(test: Bool, right: () -> B, left: () -> A) -> Either<A, B> { return test ? Either<A, B>.right(right()): Either<A, B>.left(left()) } } /** * Printable */ extension Either: CustomStringConvertible { public var description: String { switch self { case .Left(let l): return "Left: \(l)" case .Right(let r): return "Right: \(r)" } } } /** Equatable Equality for Either is defined by the equality of the contained types - parameter lhs: Left hand side - parameter rhs: right hand side - returns: equal */ public func == <A, B where A: Equatable, B: Equatable>(lhs: Either<A, B>, rhs: Either<A, B>) -> Bool { switch (lhs, rhs) { case let (.Right(l), .Right(r)): return l == r case let (.Left(l), .Left(r)): return l == r default: return false } } /** Equatable Inequality for Either is defined by the inequality of the contained types - parameter lhs: Left hand side - parameter rhs: right hand side - returns: inequal */ public func != <A, B where A: Equatable, B: Equatable>(lhs: Either<A, B>, rhs: Either<A, B>) -> Bool { return !(rhs == lhs) } /** Flip the left/right values in this disjunction. Alias for `swap` - parameter either: Either<A, B> - returns: the results of swap */ public prefix func ~ <A, B>(eithr: Either<A, B>) -> Either<B, A> { return eithr.swap() } /** Return the right value of this disjunction or the given default if left. Alias for `getOrElse` - parameter eithr: Either<A, B> - parameter or: the rawValue function to bind across `Left`. - returns: Right Value */ public func ?? <A, B>(eithr: Either<A, B>, or: B) -> B { return eithr.getOrElse { or } } /** Return this if it is a right, otherwise, return the given value. Alias for `orElse` - parameter eithr: Either<A, B> - parameter or: the rawValue function to bind across `Left`. - returns: Either<A, B> */ public func ||| <A, B>(eithr: Either<A, B>, or: B) -> Either<A, B> { return eithr.orElse { or } } /** Return this if it is a right, otherwise, return the given value. Alias for `orElse` - parameter eithr: Either<A, B> - parameter or: the either function to bind across `Left`. - returns: Either<A, B> */ public func ||| <A, B>(eithr: Either<A, B>, or: Either<A, B>) -> Either<A, B> { return eithr.orElse { or } } /** Returns the result of applying `f` to `Right` values, or re-wrapping `Left` values. Alias for `flatMap` - parameter either: Either<A, B> - parameter f: the function to bind across `Right`. - returns: Either<A, X> */ public func >>- <A, B, X>(either: Either<A, B>, f: B -> Either<A, X>) -> Either<A, X> { return either.flatMap(f) }
mit
3aa25f0a7d75a1ac3d6d966879f026f5
24.359862
103
0.577023
3.594409
false
false
false
false
sebreh/SquarePants
SquarePantsDemo/SquarePantsDemo/ViewController.swift
1
912
// // ViewController.swift // SquarePantsDemo // // Created by Sebastian Rehnby on 29/09/15. // Copyright © 2015 Sebastian Rehnby. All rights reserved. // import UIKit import SquarePants class ViewController: UIViewController { private lazy var view1: UIView = { let view = UIView() view.backgroundColor = .redColor() return view }() private lazy var label1: UILabel = { let view = UILabel() view.text = "This is some text" return view }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(view1) view.addSubview(label1) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) view1.sp_makeLayout { make in make.frame.equal(CGRectMake(0, 0, 40, 40)) make.width.equal(60) make.alpha.equal(0.4) }.apply() label1.sp_layout { $0.size.fitContent() } } }
mit
9298f35b033c64a70625ad537445e642
18.382979
59
0.638858
3.703252
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/ReaderCommentCell.swift
2
7261
import UIKit import WordPressShared import Gridicons @objc protocol ReaderCommentCellDelegate: WPRichContentViewDelegate { func cell(_ cell: ReaderCommentCell, didTapAuthor comment: Comment) func cell(_ cell: ReaderCommentCell, didTapLike comment: Comment) func cell(_ cell: ReaderCommentCell, didTapReply comment: Comment) } class ReaderCommentCell: UITableViewCell { struct Constants { // Because a stackview is managing layout we tweak text insets to fine tune things. // Insets: // Top 2: Just a bit of vertical padding so the text isn't too close to the label above. // Left -4: So the left edge of the text matches the left edge of the other views. // Bottom -16: Removes some of the padding normally added to the bottom of a textview. static let textViewInsets = UIEdgeInsets(top: 2, left: -4, bottom: -16, right: 0) static let buttonSize = CGSize(width: 20, height: 20) } var enableLoggedInFeatures = false @IBOutlet var avatarImageView: UIImageView! @IBOutlet var authorButton: UIButton! @IBOutlet var timeLabel: UILabel! @IBOutlet var textView: WPRichContentView! @IBOutlet var replyButton: UIButton! @IBOutlet var likeButton: UIButton! @IBOutlet var actionBar: UIStackView! @IBOutlet var leadingContentConstraint: NSLayoutConstraint! weak var delegate: ReaderCommentCellDelegate? { didSet { textView.delegate = delegate } } var comment: Comment? var showReply: Bool { get { if let comment = comment, let post = comment.post as? ReaderPost { return post.commentsOpen && enableLoggedInFeatures } return false } } override var indentationLevel: Int { didSet { updateLeadingContentConstraint() } } override var indentationWidth: CGFloat { didSet { updateLeadingContentConstraint() } } // MARK: - Lifecycle Methods override func awakeFromNib() { super.awakeFromNib() setupReplyButton() setupLikeButton() applyStyles() } // MARK: = Setup func applyStyles() { WPStyleGuide.applyReaderCardSiteButtonStyle(authorButton) WPStyleGuide.applyReaderCardBylineLabelStyle(timeLabel) authorButton.titleLabel?.lineBreakMode = .byTruncatingTail textView.textContainerInset = Constants.textViewInsets } func setupReplyButton() { let icon = Gridicon.iconOfType(.reply, withSize: Constants.buttonSize) let tintedIcon = icon.imageWithTintColor(WPStyleGuide.grey())?.rotate180Degrees() let highlightedIcon = icon.imageWithTintColor(WPStyleGuide.lightBlue())?.rotate180Degrees() replyButton.setImage(tintedIcon, for: .normal) replyButton.setImage(highlightedIcon, for: .highlighted) let title = NSLocalizedString("Reply", comment: "Verb. Title of the Reader comments screen reply button. Tapping the button sends a reply to a comment or post.") replyButton.setTitle(title, for: .normal) replyButton.setTitleColor(WPStyleGuide.grey(), for: .normal) } func setupLikeButton() { let size = Constants.buttonSize let tintedIcon = Gridicon.iconOfType(.starOutline, withSize: size).imageWithTintColor(WPStyleGuide.grey()) let highlightedIcon = Gridicon.iconOfType(.star, withSize: size).imageWithTintColor(WPStyleGuide.lightBlue()) let selectedIcon = Gridicon.iconOfType(.star, withSize: size).imageWithTintColor(WPStyleGuide.jazzyOrange()) likeButton.setImage(tintedIcon, for: .normal) likeButton.setImage(highlightedIcon, for: .highlighted) likeButton.setImage(selectedIcon, for: .selected) likeButton.setTitleColor(WPStyleGuide.grey(), for: .normal) } // MARK: - Configuration func configureCell(comment: Comment) { self.comment = comment configureAvatar() configureAuthorButton() configureTime() configureText() configureActionBar() } func configureAvatar() { guard let comment = comment else { return } let placeholder = UIImage(named: "gravatar") if let url = comment.avatarURLForDisplay() { avatarImageView.setImageWith(url, placeholderImage: placeholder) } else { avatarImageView.image = placeholder } } func configureAuthorButton() { guard let comment = comment else { return } authorButton.isEnabled = true authorButton.setTitle(comment.author, for: .normal) authorButton.setTitleColor(WPStyleGuide.lightBlue(), for: .highlighted) authorButton.setTitleColor(WPStyleGuide.greyDarken30(), for: .disabled) if comment.authorIsPostAuthor() { authorButton.setTitleColor(WPStyleGuide.jazzyOrange(), for: .normal) } else if comment.hasAuthorUrl() { authorButton.setTitleColor(WPStyleGuide.wordPressBlue(), for: .normal) } else { authorButton.isEnabled = false } } func configureTime() { guard let comment = comment else { return } timeLabel.text = (comment.dateForDisplay() as NSDate).mediumString() } func configureText() { guard let comment = comment else { return } textView.isPrivate = comment.isPrivateContent() // Use `content` vs `contentForDisplay`. Hierarchcial comments are already // correctly formatted during the sync process. textView.content = comment.content } func configureActionBar() { guard let comment = comment else { return } actionBar.isHidden = !enableLoggedInFeatures replyButton.isHidden = !showReply var title = NSLocalizedString("Like", comment: "Verb. Button title. Tap to like a commnet") let count = comment.numberOfLikes().intValue if count == 1 { title = "\(count) \(title)" } else if count > 1 { title = NSLocalizedString("Likes", comment: "Noun. Button title. Tap to like a comment.") title = "\(count) \(title)" } likeButton.setTitle(title, for: .normal) likeButton.isSelected = comment.isLiked } func updateLeadingContentConstraint() { leadingContentConstraint.constant = CGFloat(indentationLevel) * indentationWidth } func ensureTextViewLayout() { textView.updateLayoutForAttachments() } // MARK: - Actions @IBAction func handleAuthorTapped(sender: UIButton) { guard let comment = comment else { return } delegate?.cell(self, didTapAuthor: comment) } @IBAction func handleReplyTapped(sender: UIButton) { guard let comment = comment else { return } delegate?.cell(self, didTapReply: comment) } @IBAction func handleLikeTapped(sender: UIButton) { guard let comment = comment else { return } delegate?.cell(self, didTapLike: comment) } }
gpl-2.0
294820d2264e5980b014dfa99dd9feb3
29.128631
169
0.64633
5.052888
false
false
false
false
twocentstudios/tinykittenstv
tinykittenstv/VideosViewController.swift
1
11932
// // VideosViewController.swift // tinykittenstv // // Created by Christopher Trott on 4/4/17. // Copyright © 2017 twocentstudios. All rights reserved. // import UIKit import XCDYouTubeKit import AVFoundation import ReactiveSwift import ReactiveCocoa import Result final class VideosViewController: UIPageViewController { enum ViewData { case unloaded case loading case loaded([LiveVideoInfo]) case empty case failed(NSError) } let channelId: String let sessionConfig: SessionConfig let client: XCDYouTubeClient let viewData: Property<ViewData> let userPlayState = MutableProperty(UserPlayState.play) let fetchAction: Action<(), LiveVideosSearchResult, NSError> init(channelId: String, sessionConfig: SessionConfig, client: XCDYouTubeClient) { self.channelId = channelId self.sessionConfig = sessionConfig self.client = client fetchAction = Action { _ -> SignalProducer<LiveVideosSearchResult, NSError> in return Controller.fetchLiveVideos(channelId: channelId, config: sessionConfig) .start(on: QueueScheduler()) } let loadings = fetchAction.isExecuting.signal.filter({ $0 }).map({ _ in ViewData.loading }) let errors = fetchAction.errors.map { ViewData.failed($0) } let values = fetchAction.values.map { $0.liveVideos.count == 0 ? ViewData.empty : ViewData.loaded($0.liveVideos) } let merged = SignalProducer([loadings, errors, values]).flatten(.merge) self.viewData = ReactiveSwift.Property(initial: .unloaded, then: merged) // TODO: move signal outside this class NotificationCenter.default.reactive.notifications(forName: .UIApplicationWillEnterForeground) .observeValues { [weak fetchAction] _ in fetchAction?.apply(()).start() } super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) // Handle Airplay // TODO: investigate why this notification is never received. NotificationCenter.default.reactive.notifications(forName: .AVAudioSessionSilenceSecondaryAudioHint) .observeValues { [weak self] notification in guard let userInfo = notification.userInfo, let typeValue = userInfo[AVAudioSessionSilenceSecondaryAudioHintTypeKey] as? UInt, let type = AVAudioSessionSilenceSecondaryAudioHintType(rawValue: typeValue) else { return } let isMuted: Bool switch type { case .begin: isMuted = true case .end: isMuted = false } self?.currentVideoViewController()?.playerView.player?.isMuted = isMuted } self.delegate = self self.dataSource = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let backgroundView = UIImageView(image: UIImage(named: "LaunchImage")) self.view.addSubview(backgroundView) self.view.sendSubview(toBack: backgroundView) let playButtonTapGesture = UITapGestureRecognizer() playButtonTapGesture.allowedPressTypes = [NSNumber(value: UIPressType.playPause.rawValue as Int), NSNumber(value: UIPressType.select.rawValue as Int)]; self.view.addGestureRecognizer(playButtonTapGesture) viewData.producer .skipRepeats() .observe(on: UIScheduler()) .startWithValues { [weak self] (viewData: ViewData) in switch viewData { case .unloaded: break case .empty: let vc = InfoViewController(.normal("No streams are currently active.".l10())) self?.setViewControllers([vc], direction: .forward, animated: false, completion: nil) case .loading: let vc = InfoViewController(.normal("Loading...".l10())) self?.setViewControllers([vc], direction: .forward, animated: false, completion: nil) case .failed(let error): let vc = InfoViewController(.error(error.localizedDescription)) self?.setViewControllers([vc], direction: .forward, animated: false, completion: nil) case .loaded(let liveVideoInfos): guard let firstVideoInfo = liveVideoInfos.first else { return } guard let this = self else { return } let vc = VideoViewController(videoInfo: firstVideoInfo, client: this.client) this.setViewControllers([vc], direction: .forward, animated: false, completion: nil) vc.viewState.swap(.active) this.flashPageControl() } } playButtonTapGesture.reactive.stateChanged .filterMap({ (gesture: UITapGestureRecognizer) -> ()? in return gesture.state == .recognized ? () : nil }) .observeValues { [weak userPlayState] _ in guard let userPlayState = userPlayState else { return } userPlayState.value = userPlayState.value.toggle() } userPlayState.producer .observe(on: UIScheduler()) .startWithValues { [weak self] (userPlayState: UserPlayState) in if let currentVideoViewController = self?.currentVideoViewController() { currentVideoViewController.userPlayState.swap(userPlayState) } } if let pageControl = findPageControl() { pageControl.hidesForSinglePage = true pageControl.alpha = 0 } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) fetchAction.apply(()).start() } private func findPageControl() -> UIPageControl? { return self.view.subviews.first(where: { (pageControl: UIView) -> Bool in return pageControl is UIPageControl }) as? UIPageControl } private func flashPageControl() { guard let pageControl = self.findPageControl() else { return } pageControl.alpha = 0 UIView.animate(withDuration: 0.5, delay: 0, options: [], animations: { pageControl.alpha = 1 }) { _ in UIView.animate(withDuration: 0.5, delay: 4, options: [], animations: { pageControl.alpha = 0 }) } } private func currentVideoViewController() -> VideoViewController? { return viewControllers?.first as? VideoViewController } } extension VideosViewController { fileprivate func videoInfoAfter(_ videoInfo: LiveVideoInfo) -> LiveVideoInfo? { switch viewData.value { case .loaded(let infos): guard let index = videoInfoIndex(videoInfo) else { return nil } let nextIndex = index + 1 if infos.indices.contains(nextIndex) { return infos[nextIndex] } else { return nil } default: return nil } } fileprivate func videoInfoBefore(_ videoInfo: LiveVideoInfo) -> LiveVideoInfo? { switch viewData.value { case .loaded(let infos): guard let index = videoInfoIndex(videoInfo) else { return nil } let nextIndex = index - 1 if infos.indices.contains(nextIndex) { return infos[nextIndex] } else { return nil } default: return nil } } fileprivate func videoInfoIndex(_ videoInfo: LiveVideoInfo) -> Int? { switch viewData.value { case .loaded(let infos): guard let index = infos.index(where: { $0.id == videoInfo.id }) else { return nil } return index default: return nil } } fileprivate func videoInfoCount() -> Int { switch viewData.value { case .loaded(let infos): return infos.count default: return 0 } } } extension VideosViewController: UIPageViewControllerDelegate, UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let videoViewController = viewController as? VideoViewController else { return nil } let videoInfo = videoViewController.videoInfo guard let nextVideoInfo = videoInfoAfter(videoInfo) else { return nil } let newViewController = VideoViewController(videoInfo: nextVideoInfo, client: client) newViewController.viewState.swap(.inactive) newViewController.userPlayState.swap(userPlayState.value) return newViewController } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let videoViewController = viewController as? VideoViewController else { return nil } let videoInfo = videoViewController.videoInfo guard let previousVideoInfo = videoInfoBefore(videoInfo) else { return nil } let newViewController = VideoViewController(videoInfo: previousVideoInfo, client: client) newViewController.viewState.swap(.inactive) newViewController.userPlayState.swap(userPlayState.value) return newViewController } func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { guard let videoViewController = pendingViewControllers.first as? VideoViewController else { return } videoViewController.viewState.swap(.mayBecomeActive) videoViewController.userPlayState.swap(userPlayState.value) } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if let previousVideoViewController = previousViewControllers.first as? VideoViewController { previousVideoViewController.viewState.swap(.inactive) previousVideoViewController.userPlayState.swap(userPlayState.value) } if let currentVideoViewController = self.viewControllers?.first as? VideoViewController { currentVideoViewController.viewState.swap(.active) currentVideoViewController.userPlayState.swap(userPlayState.value) } } func presentationCount(for pageViewController: UIPageViewController) -> Int { return videoInfoCount() } func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let videoViewController = viewControllers?.first as? VideoViewController else { return 0 } guard let index = videoInfoIndex(videoViewController.videoInfo) else { return 0 } return index } } extension VideosViewController.ViewData: Equatable {} func ==(lhs: VideosViewController.ViewData, rhs: VideosViewController.ViewData) -> Bool { switch (lhs, rhs) { case (.loaded(let lhsVideos), .loaded(let rhsVideos)) where lhsVideos == rhsVideos: return true case (.failed(let lhsError), .failed(let rhsError)) where lhsError == rhsError: return true case (.unloaded, .unloaded): return true case (.empty, .empty): return true case (.loading, .loading): return true default: return false } }
mit
c853d2e82c883a627650ff632a3d127d
40.716783
190
0.635906
5.482996
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/General/SharedContainerUserDefaults.swift
1
2199
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxCocoa import RxSwift import ToolKit public final class SharedContainerUserDefaults: UserDefaults { // MARK: - Public Static public static let `default` = SharedContainerUserDefaults() // MARK: - Static static let name = String(describing: "group.rainydayapps.blockchain") // MARK: - Public Properties public let portfolioRelay = PublishSubject<Portfolio?>() // MARK: - Rx private var portfolioObservable: Observable<Portfolio?> { portfolioRelay .asObservable() } // MARK: - Setup private lazy var setup: Void = portfolioObservable .bindAndCatch(to: rx.rx_portfolio) .disposed(by: disposeBag) // MARK: - Types enum Keys: String { case portfolio case shouldSyncPortfolio } // MARK: - Private Properties private let disposeBag = DisposeBag() // MARK: - Init public convenience init() { self.init(suiteName: SharedContainerUserDefaults.name)! _ = setup } public var portfolioSyncEnabled: Observable<Bool> { rx.observe(Bool.self, Keys.shouldSyncPortfolio.rawValue) .map { value in value ?? false } } public var portfolio: Portfolio? { get { codable(Portfolio.self, forKey: Keys.portfolio.rawValue) } set { set(codable: newValue, forKey: Keys.portfolio.rawValue) } } public var shouldSyncPortfolio: Bool { get { bool(forKey: Keys.shouldSyncPortfolio.rawValue) } set { set(newValue, forKey: Keys.shouldSyncPortfolio.rawValue) } } public func reset() { shouldSyncPortfolio = false } } extension Reactive where Base: SharedContainerUserDefaults { public var portfolioSyncEnabled: Binder<Bool> { Binder(base) { container, payload in container.shouldSyncPortfolio = payload } } public var rx_portfolio: Binder<Portfolio?> { Binder(base) { container, payload in container.portfolio = payload } } }
lgpl-3.0
0fbd185e0868eb93014cd37793ffd7d7
22.382979
73
0.616015
4.788671
false
false
false
false
modocache/swift
test/ClangModules/sdk-bridging-header.swift
4
1378
// RUN: %target-swift-frontend -parse -verify %s -import-objc-header %S/Inputs/sdk-bridging-header.h // RUN: not %target-swift-frontend -parse %s -import-objc-header %S/Inputs/bad-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-FATAL %s // RUN: %target-swift-frontend -parse -verify %s -Xcc -include -Xcc %S/Inputs/sdk-bridging-header.h -import-objc-header %S/../Inputs/empty.swift // RUN: not %target-swift-frontend -parse %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s // RUN: not %target-swift-frontend -parse %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h -import-objc-header %S/../Inputs/empty.swift 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s // RUN: not %target-swift-frontend -parse %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h -import-objc-header %S/Inputs/sdk-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s // CHECK-FATAL: failed to import bridging header // CHECK-INCLUDE: error: 'this-header-does-not-exist.h' file not found // CHECK-INCLUDE: error: use of unresolved identifier 'MyPredicate' // REQUIRES: objc_interop import Foundation let `true` = MyPredicate.`true`() let not = MyPredicate.not() let and = MyPredicate.and([]) let or = MyPredicate.or([not, and]) _ = MyPredicate.foobar() // expected-error{{type 'MyPredicate' has no member 'foobar'}}
apache-2.0
c9a6fd5145d534bcede9129a8889955d
56.416667
196
0.723512
3.062222
false
false
false
false
StYaphet/firefox-ios
Client/Frontend/Settings/SettingsContentViewController.swift
6
6108
/* 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 Shared import SnapKit import UIKit import WebKit let DefaultTimeoutTimeInterval = 10.0 // Seconds. We'll want some telemetry on load times in the wild. private var TODOPageLoadErrorString = NSLocalizedString("Could not load page.", comment: "Error message that is shown in settings when there was a problem loading") /** * A controller that manages a single web view and provides a way for * the user to navigate back to Settings. */ class SettingsContentViewController: UIViewController, WKNavigationDelegate { let interstitialBackgroundColor: UIColor var settingsTitle: NSAttributedString? var url: URL! var timer: Timer? var isLoaded: Bool = false { didSet { if isLoaded { UIView.transition(from: interstitialView, to: settingsWebView, duration: 0.5, options: .transitionCrossDissolve, completion: { finished in self.interstitialView.removeFromSuperview() self.interstitialSpinnerView.stopAnimating() }) } } } fileprivate var isError: Bool = false { didSet { if isError { interstitialErrorView.isHidden = false UIView.transition(from: interstitialSpinnerView, to: interstitialErrorView, duration: 0.5, options: .transitionCrossDissolve, completion: { finished in self.interstitialSpinnerView.removeFromSuperview() self.interstitialSpinnerView.stopAnimating() }) } } } // The view shown while the content is loading in the background web view. fileprivate var interstitialView: UIView! fileprivate var interstitialSpinnerView: UIActivityIndicatorView! fileprivate var interstitialErrorView: UILabel! // The web view that displays content. var settingsWebView: WKWebView! fileprivate func startLoading(_ timeout: Double = DefaultTimeoutTimeInterval) { if self.isLoaded { return } if timeout > 0 { self.timer = Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(didTimeOut), userInfo: nil, repeats: false) } else { self.timer = nil } self.settingsWebView.load(PrivilegedRequest(url: url) as URLRequest) self.interstitialSpinnerView.startAnimating() } init(backgroundColor: UIColor = UIColor.Photon.White100, title: NSAttributedString? = nil) { interstitialBackgroundColor = backgroundColor settingsTitle = title super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // This background agrees with the web page background. // Keeping the background constant prevents a pop of mismatched color. view.backgroundColor = interstitialBackgroundColor self.settingsWebView = makeWebView() view.addSubview(settingsWebView) self.settingsWebView.snp.remakeConstraints { make in make.edges.equalTo(self.view) } // Destructuring let causes problems. let ret = makeInterstitialViews() self.interstitialView = ret.0 self.interstitialSpinnerView = ret.1 self.interstitialErrorView = ret.2 view.addSubview(interstitialView) self.interstitialView.snp.remakeConstraints { make in make.edges.equalTo(self.view) } startLoading() } func makeWebView() -> WKWebView { let config = TabManager.makeWebViewConfig(isPrivate: true, prefs: nil) config.preferences.javaScriptCanOpenWindowsAutomatically = false let webView = WKWebView( frame: CGRect(width: 1, height: 1), configuration: config ) webView.allowsLinkPreview = false webView.navigationDelegate = self // This is not shown full-screen, use mobile UA webView.customUserAgent = UserAgent.mobileUserAgent() return webView } fileprivate func makeInterstitialViews() -> (UIView, UIActivityIndicatorView, UILabel) { let view = UIView() // Keeping the background constant prevents a pop of mismatched color. view.backgroundColor = interstitialBackgroundColor let spinner = UIActivityIndicatorView(style: .gray) view.addSubview(spinner) let error = UILabel() if let _ = settingsTitle { error.text = TODOPageLoadErrorString error.textColor = UIColor.theme.tableView.errorText error.textAlignment = .center } error.isHidden = true view.addSubview(error) spinner.snp.makeConstraints { make in make.center.equalTo(view) return } error.snp.makeConstraints { make in make.center.equalTo(view) make.left.equalTo(view.snp.left).offset(20) make.right.equalTo(view.snp.right).offset(-20) make.height.equalTo(44) return } return (view, spinner, error) } @objc func didTimeOut() { self.timer = nil self.isError = true } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { didTimeOut() } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { didTimeOut() } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { self.timer?.invalidate() self.timer = nil self.isLoaded = true } }
mpl-2.0
6c1676faa6e7d31e2543e2e703c915d2
33.314607
164
0.63556
5.376761
false
false
false
false
ashleybrgr/surfPlay
surfPlay/surfPlay/ApiService.swift
1
3810
// // ApiService.swift // // Created by Ashley Berger on 2017-05-14. // // import Alamofire import SwiftyJSON class Retrier: RequestRetrier, RequestAdapter { private let maxRetries: UInt = 3 private let waitIncrement: Double = 1.0 static var isRefreshing = false func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { let waitTime = Double(request.retryCount) + waitIncrement if error._code == NSURLErrorTimedOut && request.retryCount < maxRetries { print("TIMEOUT \n retrying in \(waitTime) seconds ...") return completion(true, waitTime) // retry after x seconds } if let response = request.task?.response as? HTTPURLResponse, response.statusCode != nil && response.statusCode >= 500 || response.statusCode == 401, request.retryCount < maxRetries { if response.statusCode == 401 { print("token expired, reauthorizing...") // server.reloadAccount(callBack: { (result) in // if case .Success(_) = result { // let password = Server.hashedPass! // let userId = Server.id! // server.login(email: userId, password: password) { (result) in // switch result { // case .Success(_): // Retrier.isRefreshing = true // print("retrying request in \(waitTime) seconds ...") // return completion(true, waitTime) // retry after x seconds // // case .Error(_): // //Login failed after 3 attempts, stop retrying // return completion(false, 0.0) // } // } // } else { // return completion(false, 0.0) // } // }) } else { print("retrying request in \(waitTime) seconds ...") completion(true, waitTime) // retry after x seconds } } else { completion(false, 0.0) // don't retry } } func adapt(_ urlRequest: URLRequest) throws -> URLRequest { guard Retrier.isRefreshing else { return urlRequest } var urlRequest = urlRequest Retrier.isRefreshing = false if let token = ApiService.sharedInstance.headers["Authorization"] { print("adapting token to be", token) urlRequest.setValue(token, forHTTPHeaderField: "Authorization") } return urlRequest } } class ApiService { static let sharedInstance: ApiService = { let instance = ApiService() return instance }() let CONSUMER_KEY = "77f83b3e351543478787fa36a96d918b" let SECRET_KEY = "cb36d03092c34959b933854efe090563" let URL = "https://api.spotify.com/v1/" let apiTimeout = JSON(["error" : ["message":"Request Timeout"]]) var headers = [ "Content-Type": "application/json", "Accept": "application/json" ] func setAccessTokenHeader(token: String) { do { let tokenItem = KeychainService(service: KeychainConfiguration.serviceName, account: KeychainConfiguration.accountName, accessGroup: KeychainConfiguration.accessGroup) try tokenItem.saveAuth(token) } catch { print("Error updating keychain - \(error)") } self.headers["Authorization"] = "Bearer " + token } public enum Result<T> { case Success(T) case Error(Error) } func request(path: String, type: HTTPMethod, params: [String: Any], _ cb: @escaping (_ response: Result<JSON>) -> ()){ Alamofire.request(URL+path, method: type, parameters: params, encoding: URLEncoding.default, headers: headers).responseJSON { (response) in print(self.headers) switch(response.result) { case .success(let data): cb(Result.Success(JSON(data))) case .failure(let error): cb(Result.Error(error)) } } } func login() { } }
apache-2.0
a6b64520edff49b676cb318b2a086496
29.238095
173
0.625722
4.247492
false
false
false
false
neekon/ios
Neekon/Neekon/NewsViewController.swift
1
2369
// // FirstViewController.swift // Neekon // // Created by Eiman Zolfaghari on 1/9/15. // Copyright (c) 2015 Iranican Inc. All rights reserved. // import UIKit import Parse class NewsViewController: UITableViewController { var news : [NewsObject]? override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(NewsCell.self, forCellReuseIdentifier: "NewsCell") tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) tableView.allowsSelection = false let titleImage = UIImage(named: "navigation-top-bar-logo") let titleView = UIImageView(image: titleImage) titleView.frame = CGRectMake(0, 0, 150, 40) titleView.contentMode = UIViewContentMode.ScaleAspectFit self.navigationItem.titleView = titleView self.view.backgroundColor = UIColor.clearColor() tableView.separatorStyle = .None fetchNews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateWithNewsItems(newsItems: NSArray) { } func fetchNews() { NewsObject.fetchNewsObjects({ (newsObjects: [NewsObject]!, error: NSError!) -> Void in self.news = newsObjects self.tableView.reloadData() }) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let definiteNews = self.news { return definiteNews.count } else { return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as! NewsCell let newsObject = self.news![indexPath.row] cell.fill(newsObject.title, content: newsObject.content, imageUrl: newsObject.imageUrl) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let newsObject = self.news![indexPath.row] return NewsCell.getHeightGivenContent(newsObject.content, imageUrl: newsObject.imageUrl, width: view.frame.width - MARGIN * 2) } }
mit
9595f6a4115a077713c7c31c992b9ce9
31.902778
134
0.658084
4.956067
false
false
false
false
savelii/Swift-cfenv
Sources/CloudFoundryEnv/AppEnv.swift
1
10926
/** * Copyright IBM Corporation 2016 * * 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 SwiftyJSON public struct AppEnv { public let isLocal: Bool public let port: Int public let name: String? public let bind: String public let urls: [String] public let url: String public let app: JSON public let services: JSON /** * The vcap option property is ignored if not running locally. */ public init(options: JSON) throws { // NSProcessInfo.processInfo().environment returns [String : String] #if os(Linux) let environmentVars = ProcessInfo.processInfo().environment #else let environmentVars = ProcessInfo.processInfo.environment #endif let vcapApplication = environmentVars["VCAP_APPLICATION"] isLocal = (vcapApplication == nil) // Get app app = try AppEnv.parseEnvVariable(isLocal: isLocal, environmentVars: environmentVars, variableName: "VCAP_APPLICATION", varibleType: "application", options: options) // Get services services = try AppEnv.parseEnvVariable(isLocal: isLocal, environmentVars: environmentVars, variableName: "VCAP_SERVICES", varibleType: "services", options: options) // Get port port = try AppEnv.parsePort(environmentVars: environmentVars, app: app) // Get name name = AppEnv.parseName(app: app, options: options) // Get bind (IP address of the application instance) bind = app["host"].string ?? "0.0.0.0" // Get urls urls = AppEnv.parseURLs(isLocal: isLocal, app: app, port: port, options: options) url = urls[0] } /** * Returns an App object. */ public func getApp() -> App? { // Get limits let limits: App.Limits if let memory = app["limits"]["mem"].int, let disk = app["limits"]["disk"].int, let fds = app["limits"]["fds"].int { limits = App.Limits(memory: memory, disk: disk, fds: fds) } else { return nil } // Get uris let uris = JSONUtils.convertJSONArrayToStringArray(json: app, fieldName: "uris") // Create DateUtils instance let dateUtils = DateUtils() guard let name = app["application_name"].string, let id = app["application_id"].string, let version = app["version"].string, let instanceId = app["instance_id"].string, let instanceIndex = app["instance_index"].int, let port = app["port"].int, let startedAt = dateUtils.convertStringToDate(dateString: app["started_at"].string), let spaceId = app["space_id"].string else { return nil } let startedAtTs = startedAt.timeIntervalSince1970 // App instance should only be created if all required variables exist let appObj = App(id: id, name: name, uris: uris, version: version, instanceId: instanceId, instanceIndex: instanceIndex, limits: limits, port: port, spaceId: spaceId, startedAtTs: startedAtTs, startedAt: startedAt) return appObj } /** * Returns all services bound to the application in a dictionary. The key in * the dictionary is the name of the service, while the value is a Service * object that contains all the properties for the service. */ public func getServices() -> [String:Service] { var results: [String:Service] = [:] for (_, servs) in services { for service in servs.arrayValue { // as! [[String:AnyObject]] { // A service must have a name and a label if let name: String = service["name"].string, let label: String = service["label"].string { let tags = JSONUtils.convertJSONArrayToStringArray(json: service, fieldName: "tags") results[name] = Service(name: name, label: label, plan: service["plan"].string, tags: tags, credentials: service["credentials"]) } } } return results } /** * Returns a Service object with the properties for the specified Cloud Foundry * service. The spec parameter should be the name of the service * or a regex to look up the service. If there is no service that matches the * spec parameter, this method returns nil. */ public func getService(spec: String) -> Service? { let services = getServices() if let service = services[spec] { return service } do { #if os(Linux) let regex = try RegularExpression(pattern: spec, options: RegularExpression.Options.caseInsensitive) #else let regex = try NSRegularExpression(pattern: spec, options: NSRegularExpression.Options.caseInsensitive) #endif for (name, serv) in services { let numberOfMatches = regex.numberOfMatches(in: name, options: [], range: NSMakeRange(0, name.characters.count)) if numberOfMatches > 0 { return serv } } } catch let error as NSError { print("Error code: \(error.code)") } return nil } /** * Returns a URL generated from VCAP_SERVICES for the specified service or nil * if service is not found. The spec parameter should be the name of the * service or a regex to look up the service. * * The replacements parameter is a JSON object with the properties found in * Foundation's NSURLComponents class. */ public func getServiceURL(spec: String, replacements: JSON?) -> String? { var substitutions: JSON = replacements ?? [:] let service = getService(spec: spec) guard let credentials = service?.credentials else { return nil } guard let url: String = credentials[substitutions["url"].string ?? "url"].string ?? credentials["uri"].string else { return nil } substitutions.dictionaryObject?["url"] = nil guard let parsedURL = NSURLComponents(string: url) else { return nil } // Set replacements in a predefined order // Before, we were just iterating over the keys in the JSON object, // but unfortunately the order of the keys returned were different on // OS X and Linux, which resulted in different outcomes. if let user = substitutions["user"].string { parsedURL.user = user } if let password = substitutions["password"].string { parsedURL.password = password } if let port = substitutions["port"].number { parsedURL.port = port } if let host = substitutions["host"].string { parsedURL.host = host } if let scheme = substitutions["scheme"].string { parsedURL.scheme = scheme } if let query = substitutions["query"].string { parsedURL.query = query } if let queryItems = substitutions["queryItems"].array { var urlQueryItems: [URLQueryItem] = [] for queryItem in queryItems { if let name = queryItem["name"].string { let urlQueryItem = URLQueryItem(name: name, value: queryItem["value"].string) urlQueryItems.append(urlQueryItem) } } if urlQueryItems.count > 0 { parsedURL.queryItems = urlQueryItems } } // These are being ignored at the moment // if let fragment = substitutions["fragment"].string { // parsedURL.fragment = fragment // } // if let path = substitutions["path"].string { // parsedURL.path = path // } return parsedURL.string } /** * Returns a JSON object that contains the credentials for the specified * Cloud Foundry service. The spec parameter should be the name of the service * or a regex to look up the service. If there is no service that matches the * spec parameter, this method returns nil. In the case there is no credentials * property for the specified service, an empty JSON is returned. */ public func getServiceCreds(spec: String) -> JSON? { guard let service = getService(spec: spec) else { return nil } if let credentials = service.credentials { return credentials } else { return [:] } } /** * Static method for parsing VCAP_APPLICATION and VCAP_SERVICES. */ private static func parseEnvVariable(isLocal: Bool, environmentVars: [String:String], variableName: String, varibleType: String, options: JSON) throws -> JSON { if isLocal { let envVariable = options["vcap"][varibleType] if envVariable.null != nil { return [:] } return envVariable } else { if let json = JSONUtils.convertStringToJSON(text: environmentVars[variableName]) { return json } throw CloudFoundryEnvError.InvalidValue("Environment variable \(variableName) is not a valid JSON string!") } } /** * Static method for parsing the port number. */ private static func parsePort(environmentVars: [String:String], app: JSON) throws -> Int { let portString: String = environmentVars["PORT"] ?? environmentVars["CF_INSTANCE_PORT"] ?? environmentVars["VCAP_APP_PORT"] ?? "8090" // TODO: Are there any benefits in implementing logic similar to ports.getPort() (npm module)...? // if portString == nil { // if app["name"].string == nil { // portString = "8090" // } // //portString = "" + (ports.getPort(appEnv.name)); // portString = "8090" // } //let number: Int? = (portString != nil) ? Int(portString!) : nil if let number = Int(portString) { return number } else { throw CloudFoundryEnvError.InvalidValue("Invalid PORT value: \(portString)") } } /** * Static method for parsing the name for the application. */ private static func parseName(app: JSON, options: JSON) -> String? { let name: String? = options["name"].string ?? app["name"].string // TODO: Add logic for parsing manifest.yml to get name // https://github.com/behrang/YamlSwift // http://stackoverflow.com/questions/24097826/read-and-write-data-from-text-file return name } /** * Static method for parsing the URLs for the application. */ private static func parseURLs(isLocal: Bool, app: JSON, port: Int, options: JSON) -> [String] { var uris: [String] = JSONUtils.convertJSONArrayToStringArray(json: app, fieldName: "uris") if isLocal { uris = ["localhost:\(port)"] } else { if (uris.count == 0) { uris = ["localhost"] } } let scheme: String = options["protocol"].string ?? (isLocal ? "http" : "https") var urls: [String] = [] for uri in uris { urls.append("\(scheme)://\(uri)"); } return urls } }
apache-2.0
1bdc1c731394ee6089faf3b2569acad1
32.931677
124
0.653945
4.24146
false
false
false
false
Antondomashnev/Sourcery
SourceryRuntime/Sources/AccessLevel.swift
2
348
// // Created by Krzysztof Zablocki on 13/09/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation /// :nodoc: public enum AccessLevel: String { case `internal` = "internal" case `private` = "private" case `fileprivate` = "fileprivate" case `public` = "public" case `open` = "open" case none = "" }
mit
6865371151e9c31697abfda163a49ff9
20.75
49
0.632184
3.445545
false
false
false
false
andersblehr/JSONCache
JSONCacheTests/JSONCacheTests.swift
1
18526
// // JSONCacheTests.swift // JSONCacheTests // // Created by Anders Blehr on 13/03/2017. // Copyright © 2017 Anders Blehr. All rights reserved. // import XCTest @testable import JSONCache class JSONCacheTests: XCTestCase { var inMemory = true var bundle: Bundle! = nil var albums: [[String: Any]]! = nil var bands: [[String: Any]]! = nil var bandMembers: [[String: Any]]! = nil var musicians: [[String: Any]]! = nil override func setUp() { super.setUp() bundle = Bundle(for: type(of: self)) let filePath = bundle.path(forResource: "bands", ofType: "json") let fileData = try! Data(contentsOf: URL(fileURLWithPath: filePath!)) let jsonObject = try! JSONSerialization.jsonObject(with: fileData) as! [String: Any] bands = jsonObject["bands"] as? [[String: Any]] musicians = jsonObject["musicians"] as? [[String: Any]] bandMembers = jsonObject["band_members"] as? [[String: Any]] albums = jsonObject["albums"] as? [[String: Any]] JSONCache.casing = .snake_case JSONCache.dateFormat = .iso8601WithSeparators } override func tearDown() { super.tearDown() JSONCache.mainContext?.reset() } func testDateConversion() { let referenceTimeInterval = 966950880.0 let referenceDate = Date(timeIntervalSince1970: referenceTimeInterval) JSONCache.dateFormat = .iso8601WithSeparators XCTAssertEqual(Date(fromJSONValue: "2000-08-22T13:28:00Z").timeIntervalSince1970, referenceTimeInterval) XCTAssertEqual(referenceDate.toJSONValue() as! String, "2000-08-22T13:28:00Z") JSONCache.dateFormat = .iso8601WithoutSeparators XCTAssertEqual(Date(fromJSONValue: "20000822T132800Z").timeIntervalSince1970, referenceTimeInterval) XCTAssertEqual(referenceDate.toJSONValue() as! String, "20000822T132800Z") JSONCache.dateFormat = .timeIntervalSince1970 XCTAssertEqual(Date(fromJSONValue: referenceTimeInterval).timeIntervalSince1970, referenceTimeInterval) XCTAssertEqual(referenceDate.toJSONValue() as! TimeInterval, referenceTimeInterval) } func testStringCaseConversion() { XCTAssertEqual(JSONConverter.convert(.fromJSON, string: "snake_case_attribute"), "snakeCaseAttribute") XCTAssertEqual(JSONConverter.convert(.toJSON, string: "snake_case_attribute"), "snake_case_attribute") XCTAssertEqual(JSONConverter.convert(.fromJSON, string: "camelCaseAttribute"), "camelCaseAttribute") XCTAssertEqual(JSONConverter.convert(.toJSON, string: "camelCaseAttribute"), "camel_case_attribute") XCTAssertEqual(JSONConverter.convert(.fromJSON, string: "description", qualifier: "SnakeCase"), "snakeCaseDescription") XCTAssertEqual(JSONConverter.convert(.fromJSON, string: "camelCaseDescription"), "camelCaseDescription") XCTAssertEqual(JSONConverter.convert(.toJSON, string: "camelCaseDescription"), "description") XCTAssertEqual(JSONConverter.convert(.toJSON, string: "camelCaseDescription", qualifier: "CamelCase"), "description") XCTAssertEqual(JSONConverter.convert(.toJSON, string: "camelCaseDescription", qualifier: "Some"), "camel_case_description") } func testDictionaryCaseConversion() { let snake_case = bands.filter({ $0["name"] as! String == "Japan" })[0] let camelCase = JSONConverter.convert(.fromJSON, dictionary: snake_case, qualifier: "Band") let snake_case_roundtrip = JSONConverter.convert(.toJSON, dictionary: camelCase, qualifier: "Band") XCTAssertEqual(camelCase["bandDescription"] as! String, snake_case["description"] as! String) XCTAssertEqual(camelCase["bandDescription"] as! String, snake_case_roundtrip["description"] as! String) XCTAssertEqual(camelCase["otherNames"] as! String, snake_case["other_names"] as! String) XCTAssertEqual(camelCase["otherNames"] as! String, snake_case_roundtrip["other_names"] as! String) } func testJSONGenerationAsync() { struct BandInfo: JSONifiable { var name: String var bandDescription: String var formed: Int var disbanded: Int? var hiatus: Int? var otherNames: String? } let u2Dictionary = BandInfo(name: "U2", bandDescription: "Dublin boys", formed: 1976, disbanded: nil, hiatus: nil, otherNames: "Passengers").toJSONDictionary() XCTAssert(JSONSerialization.isValidJSONObject(u2Dictionary)) XCTAssertEqual(u2Dictionary["name"] as! String, "U2") XCTAssertEqual(u2Dictionary["description"] as! String, "Dublin boys") XCTAssertEqual(u2Dictionary["formed"] as! Int, 1976) XCTAssertEqual(u2Dictionary["other_names"] as! String, "Passengers") let jsonFromManagedObjectExpectation = self.expectation(description: "JSON dictionary from NSManagedObject") JSONCache.bootstrap(withModelName: "JSONCacheTests", inMemory: inMemory, bundle: bundle) { result in switch result { case .success: self.loadJSONTestData().await { result in switch result { case .success: switch JSONCache.fetchObject(ofType: "Album", withId: "Rain Tree Crow") { case .success(let rainTreeCrow): XCTAssertNotNil(rainTreeCrow) let rainTreeCrowDictionary = rainTreeCrow!.toJSONDictionary() XCTAssert(JSONSerialization.isValidJSONObject(rainTreeCrowDictionary)) XCTAssertEqual(rainTreeCrowDictionary["name"] as! String, "Rain Tree Crow") XCTAssertEqual(rainTreeCrowDictionary["band"] as! String, "Japan") XCTAssertEqual(rainTreeCrowDictionary["released"] as! String, "1991-04-08T00:00:00Z") XCTAssertEqual(rainTreeCrowDictionary["label"] as! String, "Virgin") XCTAssertEqual(rainTreeCrowDictionary["released_as"] as! String, "Rain Tree Crow") jsonFromManagedObjectExpectation.fulfill() case .failure(let error): XCTFail("Fetching 'Stranded' failed with error: \(error)") } case .failure(let error): XCTFail("Loading JSON failed with error: \(error)") } } case .failure(let error): XCTFail("Bootstrap failed with error: \(error)") } } self.waitForExpectations(timeout: 5.0) } func testJSONGenerationFuture() { struct BandInfo: JSONifiable { var name: String var bandDescription: String var formed: Int var disbanded: Int? var hiatus: Int? var otherNames: String? } let u2Dictionary = BandInfo(name: "U2", bandDescription: "Dublin boys", formed: 1976, disbanded: nil, hiatus: nil, otherNames: "Passengers").toJSONDictionary() XCTAssert(JSONSerialization.isValidJSONObject(u2Dictionary)) XCTAssertEqual(u2Dictionary["name"] as! String, "U2") XCTAssertEqual(u2Dictionary["description"] as! String, "Dublin boys") XCTAssertEqual(u2Dictionary["formed"] as! Int, 1976) XCTAssertEqual(u2Dictionary["other_names"] as! String, "Passengers") let expectation = self.expectation(description: "JSON dictionary from NSManagedObject") let promise: ResultPromise<Void, JSONCacheError> = JSONCache.bootstrap(withModelName: "JSONCacheTests", inMemory: inMemory, bundle: bundle) .thenAsync { self.loadJSONTestData() } .then { JSONCache.fetchObject(ofType: "Album", withId: "Rain Tree Crow") } .then { rainTreeCrow in XCTAssertNotNil(rainTreeCrow) let rainTreeCrowDictionary = rainTreeCrow!.toJSONDictionary() XCTAssert(JSONSerialization.isValidJSONObject(rainTreeCrowDictionary)) XCTAssertEqual(rainTreeCrowDictionary["name"] as! String, "Rain Tree Crow") XCTAssertEqual(rainTreeCrowDictionary["band"] as! String, "Japan") XCTAssertEqual(rainTreeCrowDictionary["released"] as! String, "1991-04-08T00:00:00Z") XCTAssertEqual(rainTreeCrowDictionary["label"] as! String, "Virgin") XCTAssertEqual(rainTreeCrowDictionary["released_as"] as! String, "Rain Tree Crow") return Result.success(()) } promise.await { result in switch result { case .success: expectation.fulfill() case .failure(_): XCTFail() } } self.waitForExpectations(timeout: 5.0) } func testJSONLoading() { let expectation = self.expectation(description: "JSON loading") JSONCache.bootstrap(withModelName: "JSONCacheTests", inMemory: inMemory, bundle: bundle) { result in switch result { case .success: self.loadJSONTestData().await { result in switch result { case .success: switch JSONCache.fetchObject(ofType: "Band", withId: "Roxy Music") { case .success(let roxyMusic): XCTAssertNotNil(roxyMusic) let roxyMusic = roxyMusic as! Band XCTAssertEqual(roxyMusic.formed, 1971) XCTAssertEqual(roxyMusic.members!.count, 7) XCTAssertEqual(roxyMusic.albums!.count, 10) expectation.fulfill() case .failure(let error): XCTFail("Fetching 'Roxy Music' failed with error: \(error)") } case .failure(let error): XCTFail("Loading JSON failed with error: \(error)") } } case .failure(let error): XCTFail("Bootstrap failed with error: \(error)") } } self.waitForExpectations(timeout: 5.0) } func testJSONMerging() { let expectation = self.expectation(description: "JSON merging") let promise: ResultPromise<Void, JSONCacheError> = JSONCache.bootstrap(withModelName: "JSONCacheTests", inMemory: inMemory, bundle: bundle) .thenAsync { self.loadJSONTestData() } .then { JSONCache.fetchObject(ofType: "Band", withId: "Japan") } .thenAsync { japan in XCTAssertNotNil(japan) let japan = japan as! Band XCTAssertEqual(japan.name!, "Japan") XCTAssertEqual(japan.albums!.count, 7) JSONCache.stageChanges(withDictionary: [ "name": "Assemblage", "band": "Japan", "released": "1981-09-01T00:00:00Z", "label": "Hansa" ], forEntityWithName: "Album") return JSONCache.applyChanges() } .then { JSONCache.fetchObject(ofType: "Album", withId: "Assemblage") } .then { assemblage in XCTAssertNotNil(assemblage) let assemblage = assemblage as! Album XCTAssertEqual(assemblage.name, "Assemblage") XCTAssertEqual(assemblage.band!.name, "Japan") return .success(()) } promise.await { result in switch result { case .success: expectation.fulfill() case .failure(_): XCTFail() } } self.waitForExpectations(timeout: 5.0) } func testFetchConvenienceMethods() { let fetchSingleObjectExpectation = self.expectation(description: "Fetch single object by id") let fetchMultipleObjectsExpectation = self.expectation(description: "Fetch multiple objects by id") JSONCache.bootstrap(withModelName: "JSONCacheTests", inMemory: inMemory, bundle: bundle) { result in switch result { case .success: self.loadJSONTestData().await { result in switch result { case .success: switch JSONCache.fetchObject(ofType: "Album", withId: "Stranded") { case .success(let stranded): let stranded = stranded as! Album XCTAssertEqual(stranded.name!, "Stranded") XCTAssertEqual(stranded.band!.name!, "Roxy Music") XCTAssertEqual(stranded.released! as Date, Date(fromJSONValue: "1973-11-01T00:00:00Z")) XCTAssertEqual(stranded.label!, "Island") fetchSingleObjectExpectation.fulfill() case .failure(let error): XCTFail("Fetching 'Stranded' failed with error: \(error)") } switch JSONCache.fetchObjects(ofType: "Musician", withIds: ["Bryan Ferry", "Brian Eno", "David Sylvian", "Mick Karn", "Phil Manzanera", "Steve Jansen"]) { case .success(let musicians): XCTAssert(musicians.filter({ ($0 as! Musician).name == "Brian Eno" }).count == 1) XCTAssert(musicians.filter({ ($0 as! Musician).name == "Bryan Ferry" }).count == 1) XCTAssert(musicians.filter({ ($0 as! Musician).name == "David Sylvian" }).count == 1) XCTAssert(musicians.filter({ ($0 as! Musician).name == "Mick Karn" }).count == 1) XCTAssert(musicians.filter({ ($0 as! Musician).name == "Phil Manzanera" }).count == 1) XCTAssert(musicians.filter({ ($0 as! Musician).name == "Steve Jansen" }).count == 1) fetchMultipleObjectsExpectation.fulfill() case .failure(let error): XCTFail("Fetching musicians failed with error: \(error)") } case .failure(let error): XCTFail("Loading JSON failed with error: \(error)") } } case .failure(let error): XCTFail("Bootstrap failed with error: \(error)") } } self.waitForExpectations(timeout: 5.0) } func testFailureScenarios() { let modelNotFoundExpectation = self.expectation(description: "Model file does not exist") JSONCache.bootstrap(withModelName: "NoModel", inMemory: inMemory, bundle: bundle) { result in switch result { case .success: XCTFail("Bootstrapping non-existent model succeeded. This should not happen.") case .failure(let error): switch error { case .modelNotFound: modelNotFoundExpectation.fulfill() JSONCache.bootstrap(withModelName: "JSONCacheTests", inMemory: self.inMemory, bundle: self.bundle) { result in switch result { case .success: let objectNotFoundExpectation = self.expectation(description: "Object does not exist") switch JSONCache.fetchObject(ofType: "Band", withId: "U2") { case .success(let band): XCTAssertNil(band) objectNotFoundExpectation.fulfill() case .failure(let error): XCTFail("Unexpected error: \(error)") } let noSuchEntityExpectation = self.expectation(description: "Entity does not exist") switch JSONCache.fetchObject(ofType: "Artist", withId: "Bryan Ferry") { case .success: XCTFail("Fetching object with non-existent entity succeeded. This should not happen.") case .failure(let error): switch error { case .noSuchEntity: noSuchEntityExpectation.fulfill() default: XCTFail("Unexpected error: \(error)") } } case .failure(let error): XCTFail("Unexpected error: \(error)") } } default: XCTFail("Unexpected error: \(error)") } } } self.waitForExpectations(timeout: 5.0) } // MARK: - Shared methods func loadJSONTestData() -> ResultPromise<Void, JSONCacheError> { JSONCache.stageChanges(withDictionaries: self.bands, forEntityWithName: "Band") JSONCache.stageChanges(withDictionaries: self.musicians, forEntityWithName: "Musician") JSONCache.stageChanges(withDictionaries: self.bandMembers, forEntityWithName: "BandMember") JSONCache.stageChanges(withDictionaries: self.albums, forEntityWithName: "Album") return JSONCache.applyChanges() } }
mit
1c2264c034454c6d2e873680ef2ce6ad
45.197007
178
0.550175
5.26428
false
true
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Vender/XLPagerTabStrip/ButtonBarView.swift
1
7931
// ButtonBarView.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public enum PagerScroll { case no case yes case scrollOnlyIfOutOfScreen } public enum SelectedBarAlignment { case left case center case right case progressive } open class ButtonBarView: UICollectionView { open lazy var selectedBar: UIView = { [unowned self] in let bar = UIView(frame: CGRect(x: 0, y: self.frame.size.height - CGFloat(self.selectedBarHeight), width: 0, height: CGFloat(self.selectedBarHeight))) bar.layer.zPosition = 9999 return bar }() internal var selectedBarHeight: CGFloat = 4 { didSet { self.updateSlectedBarYPosition() } } var selectedBarAlignment: SelectedBarAlignment = .center var selectedIndex = 0 required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addSubview(selectedBar) } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) addSubview(selectedBar) } open func moveTo(index: Int, animated: Bool, swipeDirection: SwipeDirection, pagerScroll: PagerScroll) { selectedIndex = index updateSelectedBarPosition(animated, swipeDirection: swipeDirection, pagerScroll: pagerScroll) } open func move(fromIndex: Int, toIndex: Int, progressPercentage: CGFloat,pagerScroll: PagerScroll) { selectedIndex = progressPercentage > 0.5 ? toIndex : fromIndex let fromFrame = layoutAttributesForItem(at: IndexPath(item: fromIndex, section: 0))!.frame let numberOfItems = dataSource!.collectionView(self, numberOfItemsInSection: 0) var toFrame: CGRect if toIndex < 0 || toIndex > numberOfItems - 1 { if toIndex < 0 { let cellAtts = layoutAttributesForItem(at: IndexPath(item: 0, section: 0)) toFrame = cellAtts!.frame.offsetBy(dx: -cellAtts!.frame.size.width, dy: 0) } else { let cellAtts = layoutAttributesForItem(at: IndexPath(item: (numberOfItems - 1), section: 0)) toFrame = cellAtts!.frame.offsetBy(dx: cellAtts!.frame.size.width, dy: 0) } } else { toFrame = layoutAttributesForItem(at: IndexPath(item: toIndex, section: 0))!.frame } var targetFrame = fromFrame targetFrame.size.height = selectedBar.frame.size.height targetFrame.size.width += (toFrame.size.width - fromFrame.size.width) * progressPercentage targetFrame.origin.x += (toFrame.origin.x - fromFrame.origin.x) * progressPercentage selectedBar.frame = CGRect(x: targetFrame.origin.x, y: selectedBar.frame.origin.y, width: targetFrame.size.width, height: selectedBar.frame.size.height) var targetContentOffset: CGFloat = 0.0 if contentSize.width > frame.size.width { let toContentOffset = contentOffsetForCell(withFrame: toFrame, andIndex: toIndex) let fromContentOffset = contentOffsetForCell(withFrame: fromFrame, andIndex: fromIndex) targetContentOffset = fromContentOffset + ((toContentOffset - fromContentOffset) * progressPercentage) } let animated = abs(contentOffset.x - targetContentOffset) > 30 || (fromIndex == toIndex) setContentOffset(CGPoint(x: targetContentOffset, y: 0), animated: animated) } open func updateSelectedBarPosition(_ animated: Bool, swipeDirection: SwipeDirection, pagerScroll: PagerScroll) -> Void { var selectedBarFrame = selectedBar.frame let selectedCellIndexPath = IndexPath(item: selectedIndex, section: 0) let attributes = layoutAttributesForItem(at: selectedCellIndexPath) let selectedCellFrame = attributes!.frame updateContentOffset(animated: animated, pagerScroll: pagerScroll, toFrame: selectedCellFrame, toIndex: (selectedCellIndexPath as NSIndexPath).row) selectedBarFrame.size.width = selectedCellFrame.size.width selectedBarFrame.origin.x = selectedCellFrame.origin.x if animated { UIView.animate(withDuration: 0.3, animations: { [weak self] in self?.selectedBar.frame = selectedBarFrame }) } else { selectedBar.frame = selectedBarFrame } } // MARK: - Helpers private func updateContentOffset(animated: Bool, pagerScroll: PagerScroll, toFrame: CGRect, toIndex: Int) -> Void { guard pagerScroll != .no || (pagerScroll != .scrollOnlyIfOutOfScreen && (toFrame.origin.x < contentOffset.x || toFrame.origin.x >= (contentOffset.x + frame.size.width - contentInset.left))) else { return } let targetContentOffset = contentSize.width > frame.size.width ? contentOffsetForCell(withFrame: toFrame, andIndex: toIndex) : 0 setContentOffset(CGPoint(x: targetContentOffset, y: 0), animated: animated) } private func contentOffsetForCell(withFrame cellFrame: CGRect, andIndex index: Int) -> CGFloat { let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset var alignmentOffset: CGFloat = 0.0 switch selectedBarAlignment { case .left: alignmentOffset = sectionInset.left case .right: alignmentOffset = frame.size.width - sectionInset.right - cellFrame.size.width case .center: alignmentOffset = (frame.size.width - cellFrame.size.width) * 0.5 case .progressive: let cellHalfWidth = cellFrame.size.width * 0.5 let leftAlignmentOffset = sectionInset.left + cellHalfWidth let rightAlignmentOffset = frame.size.width - sectionInset.right - cellHalfWidth let numberOfItems = dataSource!.collectionView(self, numberOfItemsInSection: 0) let progress = index / (numberOfItems - 1) alignmentOffset = leftAlignmentOffset + (rightAlignmentOffset - leftAlignmentOffset) * CGFloat(progress) - cellHalfWidth } var contentOffset = cellFrame.origin.x - alignmentOffset contentOffset = max(0, contentOffset) contentOffset = min(contentSize.width - frame.size.width, contentOffset) return contentOffset } private func updateSlectedBarYPosition() { var selectedBarFrame = selectedBar.frame selectedBarFrame.origin.y = frame.size.height - selectedBarHeight selectedBarFrame.size.height = selectedBarHeight selectedBar.frame = selectedBarFrame } }
mit
fd790506a6a4b1d664e8f01dc23da17f
44.58046
213
0.678603
4.892659
false
false
false
false
heylau/HLPageView
Classes/HLTitleView.swift
1
10297
// // HLTitleView.swift // HLPageView // // Created by heylau on 2017/3/16. // Copyright © 2017年 hey lau. All rights reserved. // import UIKit protocol HLTitleViewDelegate :class{ func titleView(_ titleView: HLTitleView,targetIndex :Int) } class HLTitleView: UIView { weak var delegate :HLTitleViewDelegate? var titles :[String] var style :HLPageStyle fileprivate var currentIndex = 0 fileprivate var targetIndex = 0 fileprivate lazy var titleLabels :[UILabel] = [UILabel]() fileprivate lazy var normalRGB :(CGFloat,CGFloat,CGFloat) = self.style.normalColor.getRGBValue() fileprivate lazy var selctedRGB :(CGFloat,CGFloat,CGFloat) = self.style.selectColor.getRGBValue() fileprivate lazy var deltaRGB :(CGFloat,CGFloat,CGFloat) = { let deltaR = self.selctedRGB.0 - self.normalRGB.0 let deltaG = self.selctedRGB.1 - self.normalRGB.1 let deltaB = self.selctedRGB.2 - self.normalRGB.2 return (deltaR,deltaG,deltaB) }() fileprivate lazy var bottomLine :UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor return bottomLine }() fileprivate lazy var coverView :UIView = { let coverView = UIView() coverView.backgroundColor = self.style.coverViewColor coverView.alpha = self.style.coverViewAlpha return coverView }() fileprivate lazy var scrollView :UIScrollView = { let scrollView = UIScrollView(frame:self.bounds) scrollView.showsHorizontalScrollIndicator = false; return scrollView; }() init(frame: CGRect,titles:[String],style:HLPageStyle) { self.titles = titles self.style = style super.init(frame: frame) self.setupUI(); scrollView.scrollsToTop = false; } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension HLTitleView { fileprivate func setupUI(){ addSubview(scrollView) setLabels() if style.isShowBottomLine { setupBottomLine() } if style.isShowCover { setupCoverView() } } private func setupBottomLine() { scrollView.addSubview(bottomLine) bottomLine.frame = titleLabels.first!.frame bottomLine.frame.size.height = style.bottomLineHeight bottomLine.frame.origin.y = style.titleHeight - style.bottomLineHeight } private func setupCoverView() { scrollView.insertSubview(coverView, at: 0) guard let firstLabel = titleLabels.first else{return} var coverW :CGFloat = firstLabel.frame.size.width let coverH :CGFloat = style.coverViewHeight var coverX :CGFloat = firstLabel.frame.origin.x let coverY :CGFloat = (scrollView.frame.height - style.coverViewHeight) * 0.5 if style.isSrollEnable { coverX -= style.converViewMargin coverW += style.converViewMargin * 2 }else{ coverW -= style.coverViewLrEdge * 2 coverX += style.coverViewLrEdge } coverView.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH) coverView.layer.cornerRadius = style.coverViewRadius coverView.layer.masksToBounds = true } private func setLabels(){ for (i,title) in titles.enumerated() { let titleLabel = UILabel() titleLabel.text = title titleLabel.tag = i titleLabel.textAlignment = .center titleLabel.textColor = i == 0 ? style.selectColor : style.normalColor titleLabel.font = style.titleFont scrollView.addSubview(titleLabel) let tapGes = UITapGestureRecognizer(target: self, action:#selector(titleTap(_ :))) titleLabel.addGestureRecognizer(tapGes) titleLabels.append(titleLabel) titleLabel.isUserInteractionEnabled = true } var labelW :CGFloat = bounds.width / CGFloat(titleLabels.count) let labelH :CGFloat = style.titleHeight var labelX :CGFloat = 0 let labelY :CGFloat = 0 for (i,titleLabel) in titleLabels.enumerated() { if style.isSrollEnable { labelW = (titleLabel.text! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:style.titleFont], context: nil).width labelX = i == 0 ? style.titleMargin * 0.5: titleLabels[i - 1].frame.maxX + style.titleMargin }else{ labelX = labelW * CGFloat(i) } titleLabel.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) print(titleLabel.frame) } if style.isSrollEnable { scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + style.titleMargin * 0.5, height: style.titleHeight) } if style.isScale { titleLabels.first?.transform = CGAffineTransform(scaleX:style.maxScale, y: style.maxScale) } } } extension HLTitleView{ func titleTap(_ tap :UITapGestureRecognizer){ guard let targetLabel = tap.view as? UILabel else { return } guard targetLabel.tag != currentIndex else { return } let sourceLabel = titleLabels[currentIndex] sourceLabel.textColor = style.normalColor targetLabel.textColor = style.selectColor currentIndex = targetLabel.tag adjustLabelPosition() delegate?.titleView(self, targetIndex: currentIndex) if style.isShowBottomLine { UIView.animate(withDuration: 0.25, animations: { self.bottomLine.frame.origin.x = targetLabel.frame.origin.x self.bottomLine.frame.size.width = targetLabel.frame.size.width })} if style.isScale { UIView.animate(withDuration: 0.25, animations: { sourceLabel.transform = CGAffineTransform.identity targetLabel.transform = CGAffineTransform(scaleX: self.style.maxScale, y: self.style.maxScale) }) } if style.isShowCover { UIView.animate(withDuration: 0.25, animations: { self.coverView.frame.origin.x = self.style.isSrollEnable ? targetLabel.frame.origin.x - self.style.converViewMargin :targetLabel.frame.origin.x + self.style.coverViewLrEdge self.coverView.frame.size.width = self.style.isSrollEnable ? (targetLabel.frame.size.width + self.style.converViewMargin * 2) : targetLabel.frame.width - self.style.coverViewLrEdge * 2 }) } } fileprivate func adjustLabelPosition() { guard style.isSrollEnable else { return } let targetLabel = titleLabels[currentIndex] var offset = targetLabel.center.x - scrollView.bounds.width * 0.5 if offset < 0 { offset = 0 } let maxOffsetX = scrollView.contentSize.width - scrollView.bounds.width if offset > maxOffsetX { offset = maxOffsetX } scrollView.setContentOffset(CGPoint(x:offset,y:0), animated: true) } } extension HLTitleView :HLContainViewDelegate{ func containViewDidEndScroll(_ containView: HLContainView, DidEndScroll index: Int) { currentIndex = index // titleLabels[currentIndex].textColor = style.normalColor // titleLabels[targetIndex].textColor = style.selectColor for (i,titleLabel) in titleLabels.enumerated() { if i == targetIndex { titleLabels[i].textColor = style.selectColor }else{ titleLabel.textColor = style.normalColor } } adjustLabelPosition() } func containView(_ containView: HLContainView, sourceIndex: Int, targetIndex: Int, progress: CGFloat) { if progress == 1 { self.targetIndex = targetIndex } let soucreLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] soucreLabel.textColor = UIColor(r: selctedRGB.0 - deltaRGB.0 * progress, g: selctedRGB.1 - deltaRGB.1 * progress, b: selctedRGB.2 - deltaRGB.2 * progress) targetLabel.textColor = UIColor(r: normalRGB.0 + deltaRGB.0 * progress, g: normalRGB.1 + deltaRGB.1 * progress, b: normalRGB.2 + deltaRGB.2 * progress) let deltaWidth = targetLabel.frame.width - soucreLabel.frame.width let deltaX = targetLabel.frame.origin.x - soucreLabel.frame.origin.x if style.isShowBottomLine { bottomLine.frame.size.width = deltaWidth * progress + soucreLabel.frame.width bottomLine.frame.origin.x = deltaX * progress + soucreLabel.frame.origin.x } if style.isScale { let deltaScale = style.maxScale - 1.0 soucreLabel.transform = CGAffineTransform(scaleX: style.maxScale - deltaScale * progress, y: style.maxScale - deltaScale * progress) targetLabel.transform = CGAffineTransform(scaleX: 1 + deltaScale * progress, y: 1 + deltaScale * progress) } if style.isShowCover { coverView.frame.origin.x = style.isSrollEnable ? (soucreLabel.frame.origin.x - style.converViewMargin + deltaX * progress) : (soucreLabel.frame.origin.x + style.coverViewLrEdge + deltaX * progress) coverView.frame.size.width = style.isSrollEnable ? (soucreLabel.frame.width + style.converViewMargin * 2 + deltaWidth * progress) : (soucreLabel.frame.width - style.coverViewLrEdge * 2 + deltaWidth * progress) } } }
apache-2.0
4253a28bcac7f17a190fc6b0a35dd5bf
34.133106
224
0.608024
4.830596
false
false
false
false
jamalping/XPUtil
XPUtil/UIKit/Device+Extensions.swift
1
6118
// // Device+Extensions.swift // XPUtilExample // // Created by xp on 15/07/15. // Copyright (c) 2015 xp. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit /// EZSwiftExtensions private let DeviceList = [ "iPod5,1": "iPod Touch 5",/* iPod 5 */ "iPod7,1": "iPod Touch 6",/* iPod 6 */ "iPhone3,1": "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4", /* iPhone 4 */ "iPhone4,1": "iPhone 4S", /* iPhone 4S */ "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5", /* iPhone 5 */ "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C", /* iPhone 5C */ "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S", /* iPhone 5S */ "iPhone7,2": "iPhone 6", /* iPhone 6 */ "iPhone7,1": "iPhone 6 Plus", /* iPhone 6 Plus */ "iPhone8,1": "iPhone 6S", /* iPhone 6S */ "iPhone8,2": "iPhone 6S Plus", /* iPhone 6S Plus */ "iPhone9,1": "iPhone 7", "iPhone9,3": "iPhone 7", /* iPhone 7 */ "iPhone9,2": "iPhone 7 Plus", "iPhone9,4": "iPhone 7 Plus", /* iPhone 7 Plus */ "iPhone8,4": "iPhone SE", /* iPhone SE */ "iPhone10,1": "iPhone 8", "iPhone10,4": "iPhone 8", /* iPhone 8 */ "iPhone10,2": "iPhone 8 Plus", "iPhone10,5": "iPhone 8 Plus", /* iPhone 8 Plus */ "iPhone10,3": "iPhone X", "iPhone10,6": "iPhone X", /* iPhone X */ "iPhone11,2": "iPhone XS", /* iPhone XS */ "iPhone11,4": "iPhone XS Max","iPhone11,6": "iPhone XS Max", /* iPhone XS Max*/ "iPhone11,8": "iPhone XR", /* iPhone XR */ "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2", /* iPad 2 */ "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3": "iPad 3", /* iPad 3 */ "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4", /* iPad 4 */ "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air", /* iPad Air */ "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2", /* iPad Air 2 */ "iPad2,5": "iPad Mini", "iPad2,6": "iPad Mini", "iPad2,7": "iPad Mini", /* iPad Mini */ "iPad4,4": "iPad Mini 2", "iPad4,5": "iPad Mini 2", "iPad4,6": "iPad Mini 2", /* iPad Mini 2 */ "iPad4,7": "iPad Mini 3", "iPad4,8": "iPad Mini 3", "iPad4,9": "iPad Mini 3", /* iPad Mini 3 */ "iPad5,1": "iPad Mini 4", "iPad5,2": "iPad Mini 4", /* iPad Mini 4 */ "iPad6,7": "iPad Pro", "iPad6,8": "iPad Pro", /* iPad Pro */ "AppleTV5,3": "AppleTV", /* AppleTV */ "x86_64": "Simulator", "i386": "Simulator" /* Simulator */ ] /// 设备名对应的case public enum DeviceModel: String { case iPodTouch5 = "iPod Touch 5" case iPodTouch6 = "iPod Touch 6" case iPhone4 = "iPhone 4" case iPhone4s = "iPhone 4s" case iPhone5 = "iPhone 5" case iPhone5c = "iPhone 5c" case iPhone5s = "iPhone 5s" case iPhone6 = "iPhone 6" case iPhone6Plus = "iPhone 6 Plus" case iPhone6s = "iPhone 6s" case iPhone6sPlus = "iPhone 6s Plus" case iPhone7 = "iPhone 7" case iPhone7Plus = "iPhone 7 Plus" case iPhoneSE = "iPhone SE" case iPhone8 = "iPhone 8" case iPhone8Plus = "iPhone 8 Plus" case iPhoneX = "iPhone X" case iPhoneXR = "iPhone XR" case iPhoneXS = "iPhone XS" case iPhoneXSMax = "iPhone XS Max" case iPad2 = "iPad 2" case iPad3 = "iPad 3" case iPad4 = "iPad 4" case iPadAir = "iPad Air" case iPadAir2 = "iPad Air 2" case iPadMini = "iPad Mini" case iPadMini2 = "iPad Mini 2" case iPadMini3 = "iPad Mini 3" case iPadMini4 = "iPad Mini 4" case iPadPro12inch = "iPad Pro (12.9 inch)" case iPadPro9inch = "iPad Pro (9.7 inch)" case AppleTV = "Apple TV" case Simulator = "Simulator" } public extension UIDevice { class func idForVendor() -> String? { return UIDevice.current.identifierForVendor?.uuidString } /// 系统名 class func systemName() -> String { return UIDevice.current.systemName } /// 系统版本 class func systemVersion() -> String { return UIDevice.current.systemVersion } /// 系统短版本号 class func systemFloatVersion() -> Float { return (systemVersion() as NSString).floatValue } /// 设备名称 class func deviceName() -> String { return UIDevice.current.name } /// 设备语言 class func deviceLanguage() -> String { return Bundle.main.preferredLocalizations[0] } /// 获取设备标识 class func deviceModelReadable() -> String { return DeviceList[deviceModel()] ?? deviceModel() } /// 获取设备标识 class func getDeviceModel() -> DeviceModel { return DeviceModel.init(rawValue: DeviceList[deviceModel()] ?? deviceName()) ?? DeviceModel.iPhone6 } /// 是否是iphone class func isPhone() -> Bool { return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone } /// 是否是ipad class func isPad() -> Bool { return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad } /// 获取设备的标示 class func deviceModel() -> String { var systemInfo = utsname() uname(&systemInfo) let machine = systemInfo.machine var identifier = "" let mirror = Mirror(reflecting: machine) for child in mirror.children { let value = child.value if let value = value as? Int8, value != 0 { identifier.append(String(UnicodeScalar(UInt8(value)))) } } return identifier } /// 当前版本号 class var CURRENT_VERSION: String { return "\(systemFloatVersion())" } class func isSystemVersionOver(_ requiredVersion: String) -> Bool { switch systemVersion().compare(requiredVersion, options: NSString.CompareOptions.numeric) { case .orderedSame, .orderedDescending: //println("iOS >= 8.0") return true case .orderedAscending: //println("iOS < 8.0") return false } } } #endif
mit
2424f66590b83e95b8dad79b4c112783
32.541899
107
0.569454
3.460519
false
false
false
false
googlearchive/abelana
iOS/Abelana_v2/UploadViewController.swift
1
3874
// // Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import MobileCoreServices import UIKit // // The upload view controller class, used for the upload photos flow. // class UploadViewController: MainViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet var imageView:UIImageView!=nil // The selected photo @IBOutlet var textField:UITextField!=nil // The photo description override func viewDidLoad() { super.viewDidLoad() let singleTap = UITapGestureRecognizer(target: self, action: Selector("tapDetected")) singleTap.numberOfTapsRequired = 1 imageView.userInteractionEnabled = true imageView.addGestureRecognizer(singleTap) if imageView.image == nil { selectImage() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // // Called when the user clicks on the 'cancel' button. // @IBAction func cancel() { self.navigationController!.popViewControllerAnimated(true) } // // Called when the user clicks on the 'upload' button. // Verifies the information provided by the user and uploads the photo. // @IBAction func upload(sender: AnyObject) { self.view.endEditing(true) if imageView.image != nil && !textField.text.isEmpty { showSpinner(true) abelanaClient.uploadPhoto(imageView.image!, description: textField.text, completionHandler: { (error, message) -> Void in self.hideSpinner() if error { self.showErrorAlert(message) } else { NSOperationQueue.mainQueue().addOperationWithBlock { self.navigationController! .pushViewController(Storyboard.photoStreamViewController()!, animated: true) } } }) } else { var message = "" if imageView.image == nil { message += localizedString("Please select an image!") } if textField.text.isEmpty { if message != "" { message += "\n" } message += localizedString("Please enter a description for the image.") } showErrorAlert(message) } } // // Called if the user taps on the selected image, to change it. // @IBAction func tapDetected() { selectImage() } // // Initiates the select image flow in iOS. // func selectImage() { if UIImagePickerController.isSourceTypeAvailable( UIImagePickerControllerSourceType.PhotoLibrary) { var imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary; imagePicker.mediaTypes = [String(kUTTypeImage)] imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) } } // // Called when the select image flow from iOS finishes. // func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { imageView.image = pickedImage imageView.backgroundColor = UIColor(white: 0.0, alpha: 0.0) } dismissViewControllerAnimated(true, completion: nil) } }
apache-2.0
3b605f99d7d97bb086efe0a881d4cf41
30.495935
90
0.687403
5.064052
false
false
false
false
SteveBarnegren/TweenKit
Example-iOS/Example/OnboardingExampleViewController.swift
1
15334
// // OnboardingExampleViewController.swift // Example // // Created by Steven Barnegren on 30/03/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import UIKit import TweenKit /* The basic structure here, is that we have a horizontally scrolling collection view that is transparent. The collectionview cells have a label at the top, showing the text for each slide. There are also a bunch of full screen views underneith the collectionview that play the animations for various slides. (rocketView, clockView etc.) We build a single tweenkit action (composed of smaller sub actions for each thing we want to animate), where the duration is 1s per page. We can then use an ActionScrubber instance, and drive the action using the offset of the scrollview, mapping each page swipe to 1s. */ class OnboardingExampleViewController: UIViewController { // MARK: - Properties fileprivate let cellTitles: [String] = [ "", "This is a rocket", "This is a clock", "Scrubbable animations", "Will make your onboarding rock" ] fileprivate var actionScrubber: ActionScrubber? fileprivate var hasAppeared = false fileprivate var showExclamation = false fileprivate var exclamationOriginY: CGFloat? fileprivate let backgroundColorView = { return BackgroundColorView() }() fileprivate let introView = { return IntroView() }() fileprivate let starsView = { return StarsView() }() fileprivate let rocketView = { return RocketView() }() fileprivate let clockView: ClockView = { let view = ClockView() view.isHidden = true return view }() fileprivate let tkAttributesView: TweenKitAttributesView = { let view = TweenKitAttributesView() return view }() fileprivate let exclamationLayer: CALayer = { let layer = CALayer() layer.backgroundColor = UIColor.white.cgColor return layer }() fileprivate let collectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout) collectionView.backgroundColor = UIColor.clear collectionView.isPagingEnabled = true return collectionView }() fileprivate let pageControl: UIPageControl = { let pageControl = UIPageControl(frame: .zero) return pageControl }() // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() // Collection view collectionView.registerCellFromNib(withTypeName: OnboardingCell.typeName) // Page Control pageControl.numberOfPages = cellTitles.count // Add Subviews view.addSubview(backgroundColorView) view.addSubview(starsView) view.addSubview(rocketView) view.addSubview(clockView) view.addSubview(collectionView) view.addSubview(tkAttributesView) view.addSubview(introView) view.layer.addSublayer(exclamationLayer) view.addSubview(pageControl) // Reload collectionView.dataSource = self collectionView.delegate = self collectionView.reloadData() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds rocketView.frame = view.bounds starsView.frame = view.bounds backgroundColorView.frame = view.bounds introView.frame = view.bounds // tkAttributesView let attrY = view.bounds.size.height * 0.5 tkAttributesView.frame = CGRect(x: 0, y: attrY, width: view.bounds.size.width, height: view.bounds.size.height - attrY) // Page Control pageControl.sizeToFit() pageControl.frame = CGRect(x: view.bounds.size.width/2 - pageControl.bounds.size.width/2, y: view.bounds.size.height - pageControl.bounds.size.height - 50, width: pageControl.bounds.size.width, height: pageControl.bounds.size.height) // Exclamation layer updateExclamationLayer() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !hasAppeared { actionScrubber = ActionScrubber(action: buildAction()) actionScrubber?.clampTValuesAboveOne = true } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) hasAppeared = true } // MARK: - Build Action fileprivate func buildAction() -> FiniteTimeAction { let rocketAction = InterpolationAction(from: 0.0, to: 1.0, duration: 2.0, easing: .linear) { [unowned self] in self.rocketView.setRocketAnimationPct(t: $0) } let starsAction = InterpolationAction(from: 0.0, to: 1.0, duration: 2.0, easing: .linear) { [unowned self] in self.starsView.update(t: $0) } let introAction = InterpolationAction(from: 0.0, to: 1.0, duration: 1.0, easing: .linear) { [unowned self] in self.introView.update(t: $0) } return ActionGroup(actions: [introAction, rocketAction, starsAction, makeClockAction(), makeTkAttributesAction(), makeBackgroundColorsAction()] ) } fileprivate func makeClockAction() -> FiniteTimeAction { // First page action (move clock on screen) let firstPageAction = InterpolationAction(from: 0.0, to: 1.0, duration: 1.0, easing: .linear) { [unowned self] in self.clockView.onScreenAmount = $0 } // Second page action (move up and make small) let secondPageChangeTime = InterpolationAction(from: 23.0, to: 24.0 + 4.0, duration: 1.0, easing: .linear) { [unowned self] in self.clockView.hours = $0 } let secondPageMoveClock = InterpolationAction(from: 1.0, to: 1.3, duration: 1.0, easing: .linear) { [unowned self] in self.clockView.onScreenAmount = $0 } let secondPageChangeSize = InterpolationAction(from: 1.0, to: 0.5, duration: 1.0, easing: .linear) { [unowned self] in self.clockView.size = $0 } let getClockPostion = RunBlockAction(handler: { [unowned self] in if self.exclamationOriginY == nil { self.exclamationOriginY = self.clockView.clockRect.origin.y } }) let secondPageAction = ActionSequence(actions: [ ActionGroup(actions: secondPageChangeTime, secondPageMoveClock, secondPageChangeSize), getClockPostion ]) // Third page action (move to bottom) let thirdPageFillWhite = InterpolationAction(from: 0.0, to: 1.0, duration: 1.0, easing: .linear) { [unowned self] in self.clockView.fillOpacity = $0 } let thirdPageMoveClock = InterpolationAction(from: { [unowned self] in self.clockView.onScreenAmount }, to: 0.55, duration: 1.0, easing: .linear) { [unowned self] in self.clockView.onScreenAmount = $0 self.updateExclamationLayer() } thirdPageMoveClock.onBecomeActive = { [unowned self] in self.showExclamation = true } thirdPageMoveClock.onBecomeInactive = { [unowned self] in self.showExclamation = false } let thirdPageAction = ActionGroup(actions: thirdPageFillWhite, thirdPageMoveClock) // Full action let fullAction = ActionSequence(actions: firstPageAction, secondPageAction, thirdPageAction) fullAction.onBecomeActive = { [unowned self] in self.clockView.isHidden = false } fullAction.onBecomeInactive = { [unowned self] in self.clockView.isHidden = true } // Return full action with start delay return ActionSequence(actions: DelayAction(duration: 1.0), fullAction) } fileprivate func makeTkAttributesAction() -> FiniteTimeAction { let action = InterpolationAction(from: 0.0, to: 1.0, duration: 2, easing: .linear) { [unowned self] in self.tkAttributesView.update(pct: $0) } let delay = DelayAction(duration: 2.0) return ActionSequence(actions: delay, action) } fileprivate func makeBackgroundColorsAction() -> FiniteTimeAction { let startColors = (UIColor.black, UIColor.black) let spaceColors = (UIColor(red: 0.004, green: 0.000, blue: 0.063, alpha: 1.00), UIColor(red: 0.031, green: 0.035, blue: 0.114, alpha: 1.00)) let clockColors = (UIColor(red: 0.114, green: 0.110, blue: 0.337, alpha: 1.00), UIColor(red: 0.114, green: 0.110, blue: 0.337, alpha: 1.00)) let littleClockColors = (UIColor(red: 0.004, green: 0.251, blue: 0.631, alpha: 1.00), UIColor(red: 0.298, green: 0.525, blue: 0.776, alpha: 1.00)) let exclamationColors = (UIColor(red: 0.149, green: 0.102, blue: 0.188, alpha: 1.00), UIColor(red: 0.149, green: 0.102, blue: 0.188, alpha: 1.00)) let colors: [(UIColor, UIColor)] = [ startColors, spaceColors, clockColors, littleClockColors, exclamationColors, ] var actions = [FiniteTimeAction]() for (startColors, endColors) in zip(colors, colors.dropFirst()) { let action = InterpolationAction(from: 0.0, to: 1.0, duration: 1.0, easing: .linear) { [unowned self] in let top = startColors.0.lerp(t: $0, end: endColors.0) let bottom = startColors.1.lerp(t: $0, end: endColors.1) self.backgroundColorView.setColors(top: top, bottom: bottom) } actions.append(action) } return ActionSequence(actions: actions) } // MARK: - Update ExclamationLayer fileprivate func updateExclamationLayer() { CATransaction.begin() CATransaction.setDisableActions(true) exclamationLayer.isHidden = true if showExclamation, let originY = exclamationOriginY { let bottomY = clockView.clockRect.origin.y - 30 if bottomY > originY { exclamationLayer.isHidden = false exclamationLayer.frame = CGRect(x: view.bounds.size.width/2 - clockView.clockRect.width/2, y: originY, width: clockView.clockRect.width, height: bottomY - originY) } } CATransaction.commit() } } extension OnboardingExampleViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset.x let pageOffset = offset / view.bounds.size.width actionScrubber?.update(elapsedTime: Double(pageOffset)) var currentPage = Int(pageOffset + 0.5) currentPage = max(currentPage, 0) currentPage = min(currentPage, cellTitles.count-1) pageControl.currentPage = currentPage } } extension OnboardingExampleViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return cellTitles.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OnboardingCell.typeName, for: indexPath) as! OnboardingCell cell.setTitle(cellTitles[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return view.bounds.size } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } } // MARK: - UITableView Register cells extension UICollectionView { func registerCellFromNib(withTypeName typeName: String) { let nib = UINib(nibName: typeName, bundle: nil) self.register(nib, forCellWithReuseIdentifier: typeName) } } // MARK: - Type Name Provider protocol TypeNameProvider { static var typeName: String {get} } extension TypeNameProvider { static var typeName: String { return String(describing: Self.self) } } extension NSObject: TypeNameProvider {}
mit
f4e1d0339cc21b00002618dc1c2275e9
36.397561
175
0.55449
5.314731
false
false
false
false
airbnb/lottie-ios
Sources/Private/Model/Assets/ImageAsset.swift
3
3235
// // ImageAsset.swift // lottie-swift // // Created by Brandon Withrow on 1/9/19. // import Foundation // MARK: - ImageAsset public final class ImageAsset: Asset { // MARK: Lifecycle required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ImageAsset.CodingKeys.self) name = try container.decode(String.self, forKey: .name) directory = try container.decode(String.self, forKey: .directory) width = try container.decode(Double.self, forKey: .width) height = try container.decode(Double.self, forKey: .height) try super.init(from: decoder) } required init(dictionary: [String: Any]) throws { name = try dictionary.value(for: CodingKeys.name) directory = try dictionary.value(for: CodingKeys.directory) width = try dictionary.value(for: CodingKeys.width) height = try dictionary.value(for: CodingKeys.height) try super.init(dictionary: dictionary) } // MARK: Public /// Image name public let name: String /// Image Directory public let directory: String /// Image Size public let width: Double public let height: Double override public func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(directory, forKey: .directory) try container.encode(width, forKey: .width) try container.encode(height, forKey: .height) } // MARK: Internal enum CodingKeys: String, CodingKey { case name = "p" case directory = "u" case width = "w" case height = "h" } } extension Data { // MARK: Lifecycle /// Initializes `Data` from an `ImageAsset`. /// /// Returns nil when the input is not recognized as valid Data URL. /// - parameter imageAsset: The image asset that contains Data URL. internal init?(imageAsset: ImageAsset) { self.init(dataString: imageAsset.name) } /// Initializes `Data` from a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) String. /// /// Returns nil when the input is not recognized as valid Data URL. /// - parameter dataString: The data string to parse. /// - parameter options: Options for the string parsing. Default value is `[]`. internal init?(dataString: String, options: DataURLReadOptions = []) { guard dataString.hasPrefix("data:"), let url = URL(string: dataString) else { return nil } // The code below is needed because Data(contentsOf:) floods logs // with messages since url doesn't have a host. This only fixes flooding logs // when data inside Data URL is base64 encoded. if let base64Range = dataString.range(of: ";base64,"), !options.contains(DataURLReadOptions.legacy) { let encodedString = String(dataString[base64Range.upperBound...]) self.init(base64Encoded: encodedString) } else { try? self.init(contentsOf: url) } } // MARK: Internal internal struct DataURLReadOptions: OptionSet { let rawValue: Int /// Will read Data URL using Data(contentsOf:) static let legacy = DataURLReadOptions(rawValue: 1 << 0) } }
apache-2.0
bb182b17f550d136e647c93bb5aa1ce3
27.883929
126
0.683771
4.04375
false
false
false
false
cocoascientist/Luna
Luna/SceneDelegate.swift
1
3282
// // SceneDelegate.swift // Luna // // Created by Andrew Shepard on 6/9/19. // Copyright © 2019 Andrew Shepard. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create a dummy URL Session // let configuration = URLSessionConfiguration.configurationWithProtocol(LocalURLProtocol.self) // let session = URLSession.init(configuration: configuration) // let provider = ContentProvider(session: session) let provider = ContentProvider(session: URLSession.shared) if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = DarkHostingController( rootView: ContentView(provider: provider) ) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } } // https://stackoverflow.com/a/57642382 private class DarkHostingController<Content>: UIHostingController<Content> where Content: View { @objc override dynamic open var preferredStatusBarStyle: UIStatusBarStyle { .lightContent } }
mit
5b8f6a5ba7e89fc513a24112b287fd47
42.171053
147
0.691557
5.387521
false
true
false
false
ryet231ere/DouYuSwift
douyu/douyu/Classes/Home/Controller/GameViewController.swift
1
4522
// // GameViewController.swift // douyu // // Created by 练锦波 on 2017/2/28. // Copyright © 2017年 练锦波. All rights reserved. // import UIKit private let kEdgeMargin : CGFloat = 10 private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3 private let kItemH : CGFloat = kItemW * 6 / 5 private let kHeaderViewH : CGFloat = 50 private let kGameViewH : CGFloat = 90 private let kGameCellID = "kGameCellID" private let kHeaderViewID = "kHeaderViewID" class GameViewController: BassViewController { // 懒加载 fileprivate lazy var gameVM : GameViewModel = GameViewModel() fileprivate lazy var collectionView : UICollectionView = {[unowned self] in let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin) layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) collectionView.autoresizingMask = [.flexibleWidth,.flexibleHeight] collectionView.dataSource = self collectionView.backgroundColor = UIColor.white return collectionView }() fileprivate lazy var topHeaderView : CollectionHeaderView = { let headerView = CollectionHeaderView.collectionHeaderView() headerView.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameViewH), width: kScreenW, height: kHeaderViewH) headerView.iconImageView.image = UIImage(named: "Img_orange") headerView.titleLabel.text = "常用" headerView.moreBtn.isHidden = true return headerView; }() fileprivate lazy var ganeView : RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } extension GameViewController{ override func setupUI() { contentView = collectionView view.addSubview(collectionView) // 添加顶部的headerview collectionView.addSubview(topHeaderView) // 将常用游戏的view添加到collectionview中 collectionView.addSubview(ganeView) // 设置collectionview的内边距 collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH + kGameViewH, left: 0, bottom: 0, right: 0) super.setupUI() } } extension GameViewController { fileprivate func loadData() { gameVM.loadAllGameData { self.collectionView.reloadData() self.ganeView.groups = Array(self.gameVM.games[0..<10]) self.loadDataFinisher() } } } extension GameViewController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameVM.games.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.baseModel = gameVM.games[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出headerView let herderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView herderView.titleLabel.text = "全部" herderView.iconImageView.image = UIImage(named: "Img_orange") herderView.moreBtn.isHidden = true return herderView } }
mit
74b8aeb347266aaf7653fdedf86bf1ff
36.058333
186
0.683382
5.49691
false
false
false
false
openHPI/xikolo-ios
Common/Data/Helper/AnnouncementHelper.swift
1
3126
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import BrightFutures import CoreData import Foundation import Stockpile public enum AnnouncementHelper { @discardableResult public static func syncAllAnnouncements() -> Future<SyncMultipleResult, XikoloError> { var query = MultipleResourcesQuery(type: Announcement.self) query.addFilter(forKey: "global", withValue: "true") return XikoloSyncEngine().synchronize(withFetchRequest: Announcement.fetchRequest(), withQuery: query) } @discardableResult public static func syncAnnouncements(for course: Course) -> Future<SyncMultipleResult, XikoloError> { let fetchRequest = Self.FetchRequest.announcements(forCourse: course) var query = MultipleResourcesQuery(type: Announcement.self) query.addFilter(forKey: "course", withValue: course.id) return XikoloSyncEngine().synchronize(withFetchRequest: fetchRequest, withQuery: query) } @discardableResult public static func markAllAsVisited() -> Future<Void, XikoloError> { guard UserProfileHelper.shared.isLoggedIn else { return Future(value: ()) } let promise = Promise<Void, XikoloError>() CoreDataHelper.persistentContainer.performBackgroundTask { context in let request = NSBatchUpdateRequest(entity: Announcement.entity()) request.resultType = .updatedObjectIDsResultType request.predicate = NSPredicate(format: "visited == %@", NSNumber(value: false)) request.propertiesToUpdate = [ "visited": true, "objectStateValue": ObjectState.modified.rawValue, ] let result = Result<[NSManagedObjectID], Error> { let updateResult = try context.execute(request) as? NSBatchUpdateResult return (updateResult?.result as? [NSManagedObjectID]) ?? [] }.mapError { error in return XikoloError.coreData(error) }.map { objectIDs in let changes = [NSUpdatedObjectsKey: objectIDs] NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [CoreDataHelper.viewContext]) } promise.complete(result) } return promise.future } @discardableResult public static func markAsVisited(_ item: Announcement) -> Future<Void, XikoloError> { guard UserProfileHelper.shared.isLoggedIn && !item.visited else { return Future(value: ()) } let promise = Promise<Void, XikoloError>() CoreDataHelper.persistentContainer.performBackgroundTask { context in guard let announcement = context.existingTypedObject(with: item.objectID) as? Announcement else { promise.failure(.missingResource(ofType: Announcement.self)) return } announcement.visited = true announcement.objectState = .modified promise.complete(context.saveWithResult()) } return promise.future } }
gpl-3.0
35125b6bc97c7f16e8f2a01a0f6626fd
38.556962
124
0.66176
5.29661
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Classes/Reusable/Extensions.swift
1
37159
// // Extensions.swift // byuSuite // // Created by Nathan Johnson on 4/14/17. // Copyright © 2017 Brigham Young University. All rights reserved. // import UIKit import SafariServices import MapKit //MARK: Basic data types extension Int { func toString() -> String { return String(self) } //Return an int equivalent to the first specified number of digits (ie. 123.firstXDigits(2) returns 12 func firstXDigits(_ numDigits: Int) -> Int? { if numDigits > 0 { var firstDigits = self while firstDigits >= (10 * numDigits) { firstDigits /= 10 } return firstDigits } else { return nil } } //Returns number of digits in Int number var digitCount: Int { get { return numberOfDigits(in: self) } } //Private recursive method for counting digits private func numberOfDigits(in number: Int) -> Int { if abs(number) < 10 { return 1 } else { return 1 + numberOfDigits(in: number / 10) } } } extension Double { func currency(numberStyle: NumberFormatter.Style = .currency) -> String { let formatter = NumberFormatter() formatter.locale = Locale(identifier: "en_US") formatter.numberStyle = numberStyle guard let currency = formatter.string(from: NSNumber(floatLiteral: self)) else { return "$0.00" } return currency } func toString() -> String { return String(self) } } extension Date { var isToday: Bool { return Calendar.current.isDateInToday(self) } static func dateWithoutTime() -> Date? { return Date().stripTime() } func stripTime() -> Date? { let components = NSCalendar.current.dateComponents([.day, .month, .year], from: self) return Calendar.current.date(from: components) } func isBetween(date1: Date, and date2: Date, inclusive: Bool = true) -> Bool { if inclusive { return date1.compare(self).rawValue * self.compare(date2).rawValue >= 0 } else { return date1.compare(self) == self.compare(date2) } } func laterDate(date: Date) -> Date { if self == date, self > date { return self } else { return date } } } extension Character { init(integer: Int) { if let unicodeScalar = UnicodeScalar(integer) { self.init(unicodeScalar) } else { self.init("") } } } extension Calendar { static func defaultCalendar(_ timeZone: TimeZone? = TimeZone(identifier: "America/Denver")) -> Calendar { var calendar = Calendar(identifier: .gregorian) calendar.timeZone = timeZone ?? calendar.timeZone return calendar } func endOfDay(for date: Date) -> Date? { return Calendar.current.date(bySettingHour: 23, minute: 59, second: 59, of: date) } func combine(date: Date, time: Date) -> Date? { let dateComponents = self.dateComponents([.year, .month, .day], from: date) let timeComponents = self.dateComponents([.hour, .minute, .second], from: time) let mergedComponents = DateComponents(calendar: self, timeZone: self.timeZone, year: dateComponents.year, month: dateComponents.month, day: dateComponents.day, hour: timeComponents.hour, minute: timeComponents.minute, second: timeComponents.second) return self.date(from: mergedComponents) } } extension String { init(unicodeValue: Int) { if let unicodeScalar = UnicodeScalar(unicodeValue) { self.init(unicodeScalar) } else { self.init() } } func captializedFirstLetter() -> String { return prefix(1).uppercased() } func stringWithFirstLetterCapitalized() -> String { return prefix(1).uppercased() + dropFirst() } func currency(numberStyle: NumberFormatter.Style = .currency) -> Double { let formatter = NumberFormatter() formatter.locale = Locale(identifier: "en_US") formatter.numberStyle = numberStyle guard let currency = formatter.number(from: self) else { return 0 } return currency.doubleValue } func asDouble() -> Double? { return Double(self) } func asBool() -> Bool? { return Bool(self) } func asInt() -> Int? { return Int(self) } func urlEncoded(characterSet: CharacterSet = .alphanumerics) -> String { return self.addingPercentEncoding(withAllowedCharacters: characterSet) ?? "" } func decodedHTMLEntities() -> String { let asciiMap = [ "&#32;": " ", //32 "&#33;": "!", "&#34;": "\"\"", "&quot;": "\"\"", "&#35;": "#", "&#36;": "$", "&#37;": "%", "&#38;": "&", //38 "&amp;": "&", "&#39;": "'", "&apos;": "'", "&#40;": "(", "&#41;": ")", "&#42;": "*", "&#43;": "+", "&#44;": ",", "&#45;": "-", "&#46;": ".", "&#47;": "/", "&#48;": "0", "&#49;": "1", "&#50;": "2", "&#51;": "3", "&#52;": "4", "&#53;": "5", "&#54;": "6", "&#55;": "7", "&#56;": "8", "&#57;": "9", "&#58;": ":", "&#59;": ";", "&#60;": "<", //60 "&lt;": "<", "&#61;": "=", "&#62;": ">", //62 "&gt;": ">", "&#63;": "?", "&#64;": "@", "&#65;": "A", "&#66;": "B", "&#67;": "C", "&#68;": "D", "&#69;": "E", "&#70;": "F", "&#71;": "G", "&#72;": "H", "&#73;": "I", "&#74;": "J", "&#75;": "K", "&#76;": "L", "&#77;": "M", "&#78;": "N", "&#79;": "O", "&#80;": "P", "&#81;": "Q", "&#82;": "R", "&#83;": "S", "&#84;": "T", "&#85;": "U", "&#86;": "V", "&#87;": "W", "&#88;": "X", "&#89;": "Y", "&#90;": "Z", "&#91;": "[", "&#92;": "\\", "&#93;": "]", "&#94;": "^", "&#95;": "_", "&#96;": "`", "&#97;": "a", "&#98;": "b", "&#99;": "c", "&#100;": "d", //100 "&#101;": "e", "&#102;": "f", "&#103;": "g", "&#104;": "h", "&#105;": "i", "&#106;": "j", "&#107;": "k", "&#108;": "l", "&#109;": "m", "&#110;": "n", "&#111;": "o", "&#112;": "p", "&#113;": "q", "&#114;": "r", "&#115;": "s", "&#116;": "t", "&#117;": "u", "&#118;": "v", "&#119;": "w", "&#120;": "x", "&#121;": "y", "&#122;": "z", "&#123;": "{", "&#124;": "|", "&#125;": "}", "&#126;": "~", "&#127;": " ", //127 "&#160;": " ", //160 "&nbsp;": " ", "&iexcl;": "¡", "&cent;": "¢", "&pound;": "£", "&curren;": "¤", "&yen;": "¥", "&brvbar;": "¦", "&sect;": "§", "&uml;": "¨", "&copy;": "©", "&ordf;": "ª", "&laquo;": "«", "&not;": "¬", "&shy;": "", "&reg;": "®", "&macr;": "¯", "&deg;": "°", "&plusmn;": "±", "&sup2;": "²", "&sup3;": "³", "&acute;": "´", "&micro;": "µ", "&para;": "¶", "&middot;": "·", "&cedil;": "¸", "&sup1;": "¹", "&ordm;": "º", "&raquo;": "»", "&frac14;": "¼", "&frac12;": "½", "&frac34;": "¾", "&iquest;": "¿", "&Agrave;": "À", "&Aacute;": "Á", "&Acirc;": "Â", "&Atilde;": "Ã", "&Auml;": "Ä", "&Aring;": "Å", "&AElig;": "Æ", "&Ccedil;": "Ç", "&Egrave;": "È", //200 "&Eacute;": "É", "&Ecirc;": "", "&Euml;": "Ë", "&Igrave;": "Ì", "&Iacute;": "Í", "&Icirc;": "Î", "&Iuml;": "Ï", "&ETH;": "Ð", "&Ntilde;": "Ñ", "&Ograve;": "Ò", "&Oacute;": "Ó", "&Ocirc;": "Ô", "&Otilde;": "Õ", "&Ouml;": "Ö", "&times;": "×", "&Oslash;": "Ø", "&Ugrave;": "Ù", "&Uacute;": "Ú", "&Ucirc;": "Û", "&Uuml;": "Ü", "&Yacute;": "Ý", "&THORN;": "Þ", "&szlig;": "ß", "&agrave;": "à", "&aacute;": "á", "&acirc;": "â", "&atilde;": "ã", "&auml;": "ä", "&aring;": "å", "&aelig;": "æ", "&ccedil;": "ç", "&egrave;": "è", "&eacute;": "é", "&ecirc;": "ê", "&euml;": "ë", "&igrave;": "ì", "&iacute;": "í", "&icirc;": "î", "&iuml;": "ï", "&eth;": "ð", "&ntilde;": "ñ", "&ograve;": "ò", "&oacute;": "ó", "&ocirc;": "ô", "&otilde;": "õ", "&ouml;": "ö", "&divide;": "÷", "&oslash;": "ø", "&ugrave;": "ù", "&uacute;": "ú", "&ucirc;": "û", "&uuml;": "ü", "&yacute;": "ý", "&thorn;": "þ", "&yuml;": "ÿ", //255 "&#8704;": "∀", // for all "&#8706;": "∂", // part "&#8707;": "∃", // exists "&#8709;": "∅", // empty "&#8711;": "∇", // nabla "&#8712;": "∈", // isin "&#8713;": "∉", // notin "&#8715;": "∋", // ni "&#8719;": "∏", // prod "&#8721;": "∑", // sum "&#8722;": "−", // minus "&#8727;": "∗", // lowast "&#8730;": "√", // square root "&#8733;": "∝", // proportional to "&#8734;": "∞", // infinity "&#8736;": "∠", // angle "&#8743;": "∧", // and "&#8744;": "∨", // or "&#8745;": "∩", // cap "&#8746;": "∪", // cup "&#8747;": "∫", // integral "&#8756;": "∴", // therefore "&#8764;": "∼", // similar to "&#8773;": "≅", // congruent to "&#8776;": "≈", // almost equal "&#8800;": "≠", // not equal "&#8801;": "≡", // equivalent "&#8804;": "≤", // less or equal "&#8805;": "≥", // greater or equal "&#8834;": "⊂", // subset of "&#8835;": "⊃", // superset of "&#8836;": "⊄", // not subset of "&#8838;": "⊆", // subset or equal "&#8839;": "⊇", // superset or equal "&#8853;": "⊕", // circled plus "&#8855;": "⊗", // circled times "&#8869;": "⊥", // perpendicular "&#8901;": "⋅", // dot operator "&#913;": "Α", // Alpha "&#914;": "Β", // Beta "&#915;": "Γ", // Gamma "&#916;": "Δ", // Delta "&#917;": "Ε", // Epsilon "&#918;": "Ζ", // Zeta "&#919;": "Η", // Eta "&#920;": "Θ", // Theta "&#921;": "Ι", // Iota "&#922;": "Κ", // Kappa "&#923;": "Λ", // Lambda "&#924;": "Μ", // Mu "&#925;": "Ν", // Nu "&#926;": "Ξ", // Xi "&#927;": "Ο", // Omicron "&#928;": "Π", // Pi "&#929;": "Ρ", // Rho "&#931;": "Σ", // Sigma "&#932;": "Τ", // Tau "&#933;": "Υ", // Upsilon "&#934;": "Φ", // Phi "&#935;": "Χ", // Chi "&#936;": "Ψ", // Psi "&#937;": "Ω", // Omega "&#945;": "α", // alpha "&#946;": "β", // beta "&#947;": "γ", // gamma "&#948;": "δ", // delta "&#949;": "ε", // epsilon "&#950;": "ζ", // zeta "&#951;": "η", // eta "&#952;": "θ", // theta "&#953;": "ι", // iota "&#954;": "κ", // kappa "&#955;": "λ", // lambda "&#956;": "μ", // mu "&#957;": "ν", // nu "&#958;": "ξ", // xi "&#959;": "ο", // omicron "&#960;": "π", // pi "&#961;": "ρ", // rho "&#962;": "ς", // sigmaf "&#963;": "σ", // sigma "&#964;": "τ", // tau "&#965;": "υ", // upsilon "&#966;": "φ", // phi "&#967;": "χ", // chi "&#968;": "ψ", // psi "&#969;": "ω", // omega "&#977;": "ϑ", // theta symbol "&#978;": "ϒ", // upsilon symbol "&#982;": "ϖ", // pi symbol "&#338;": "Œ", // capital ligature OE "&#339;": "œ", // small ligature oe "&#352;": "Š", // capital S with caron "&#353;": "š", // small S with caron "&#376;": "Ÿ", // capital Y with diaeres "&#402;": "ƒ", // f with hook "&#710;": "ˆ", // modifier letter circumflex accent "&#732;": "˜", // small tilde "&#8194;": " ", // en space "&#8195;": " ", // em space "&#8201;": " ", // thin space "&#8204;": "‌", // zero width non-joiner "&#8205;": "‍", // zero width joiner "&#8206;": "‎", // left-to-right mark "&#8207;": "", // right-to-left mark "&#8211;": "–", // en dash "&#8212;": "—", // em dash "&#8216;": "‘", // left single quotation mark "&#8217;": "’", // right single quotation mark "&#8218;": "‚", // single low-9 quotation mark "&#8220;": "“", // left double quotation mark "&#8221;": "”", // right double quotation mark "&#8222;": "„", // double low-9 quotation mark "&#8224;": "†", // dagger "&#8225;": "‡", // double dagger "&#8226;": "•", // bullet "&#8230;": "…", // horizontal ellipsis "&#8240;": "‰", // per mille "&#8242;": "′", // minutes "&#8243;": "″", // seconds "&#8249;": "‹", // single left angle quotation "&#8250;": "›", // single right angle quotation "&#8254;": "‾", // overline "&#8364;": "€", // euro "&#8482;": "™", // trademark "&#153;": "™", // trademark "&#8592;": "←", // left arrow "&#8593;": "↑", // up arrow "&#8594;": "→", // right arrow "&#8595;": "↓", // down arrow "&#8596;": "↔", // left right arrow "&#8629;": "↵", // carriage return arrow "&#8968;": "⌈", // left ceiling "&#8969;": "⌉", // right ceiling "&#8970;": "⌊", // left floor "&#8971;": "⌋", // right floor "&#9674;": "◊", // lozenge "&#9824;": "♠", // spade "&#9827;": "♣", // club "&#9829;": "♥", // heart "&#9830;": "♦", // diamond "&forall;": "∀", // for all "&part;": "∂", // part "&exist;": "∃", // exists "&empty;": "∅", // empty "&nabla;": "∇", // nabla "&isin;": "∈", // isin "&notin;": "∉", // notin "&ni;": "∋", // ni "&prod;": "∏", // prod "&sum;": "∑", // sum "&minus;": "−", // minus "&lowast;": "∗", // lowast "&radic;": "√", // square root "&prop;": "∝", // proportional to "&infin;": "∞", // infinity "&ang;": "∠", // angle "&and;": "∧", // and "&or;": "∨", // or "&cap;": "∩", // cap "&cup;": "∪", // cup "&int;": "∫", // integral "&there4;": "∴", // therefore "&sim;": "∼", // similar to "&cong;": "≅", // congruent to "&asymp;": "≈", // almost equal "&ne;": "≠", // not equal "&equiv;": "≡", // equivalent "&le;": "≤", // less or equal "&ge;": "≥", // greater or equal "&sub;": "⊂", // subset of "&sup;": "⊃", // superset of "&nsub;": "⊄", // not subset of "&sube;": "⊆", // subset or equal "&supe;": "⊇", // superset or equal "&oplus;": "⊕", // circled plus "&otimes;": "⊗", // circled times "&perp;": "⊥", // perpendicular "&sdot;": "⋅", // dot operator "&Alpha;": "Α", // Alpha "&Beta;": "Β", // Beta "&Gamma;": "Γ", // Gamma "&Delta;": "Δ", // Delta "&Epsilon;": "Ε", // Epsilon "&Zeta;": "Ζ", // Zeta "&Eta;": "Η", // Eta "&Theta;": "Θ", // Theta "&Iota;": "Ι", // Iota "&Kappa;": "Κ", // Kappa "&Lambda;": "Λ", // Lambda "&Mu;": "Μ", // Mu "&Nu;": "Ν", // Nu "&Xi;": "Ξ", // Xi "&Omicron;": "Ο", // Omicron "&Pi;": "Π", // Pi "&Rho;": "Ρ", // Rho "&Sigma;": "Σ", // Sigma "&Tau;": "Τ", // Tau "&Upsilon;": "Υ", // Upsilon "&Phi;": "Φ", // Phi "&Chi;": "Χ", // Chi "&Psi;": "Ψ", // Psi "&Omega;": "Ω", // Omega "&alpha;": "α", // alpha "&beta;": "β", // beta "&gamma;": "γ", // gamma "&delta;": "δ", // delta "&epsilon;": "ε", // epsilon "&zeta;": "ζ", // zeta "&eta;": "η", // eta "&theta;": "θ", // theta "&iota;": "ι", // iota "&kappa;": "κ", // kappa "&lambda;": "λ", // lambda "&mu;": "μ", // mu "&nu;": "ν", // nu "&xi;": "ξ", // xi "&omicron;": "ο", // omicron "&pi;": "π", // pi "&rho;": "ρ", // rho "&sigmaf;": "ς", // sigmaf "&sigma;": "σ", // sigma "&tau;": "τ", // tau "&upsilon;": "υ", // upsilon "&phi;": "φ", // phi "&chi;": "χ", // chi "&psi;": "ψ", // psi "&omega;": "ω", // omega "&thetasym;": "ϑ", // theta symbol "&upsih;": "ϒ", // upsilon symbol "&piv;": "ϖ", // pi symbol "&OElig;": "Œ", // capital ligature OE "&oelig;": "œ", // small ligature oe "&Scaron;": "Š", // capital S with caron "&scaron;": "š", // small S with caron "&Yuml;": "Ÿ", // capital Y with diaeres "&fnof;": "ƒ", // f with hook "&circ;": "ˆ", // modifier letter circumflex accent "&tilde;": "˜", // small tilde "&ensp;": " ", // en space "&emsp;": " ", // em space "&thinsp;": " ", // thin space "&zwnj;": "‌", // zero width non-joiner "&zwj;": "‍", // zero width joiner "&lrm;": "‎", // left-to-right mark "&rlm;": "‏", // right-to-left mark "&ndash;": "–", // en dash "&mdash;": "—", // em dash "&lsquo;": "‘", // left single quotation mark "&rsquo;": "’", // right single quotation mark "&sbquo;": "‚", // single low-9 quotation mark "&ldquo;": "“", // left double quotation mark "&rdquo;": "”", // right double quotation mark "&bdquo;": "„", // double low-9 quotation mark "&dagger;": "†", // dagger "&Dagger;": "‡", // double dagger "&bull;": "•", // bullet "&hellip;": "…", // horizontal ellipsis "&permil;": "‰", // per mille "&prime;": "′", // minutes "&Prime;": "″", // seconds "&lsaquo;": "‹", // single left angle quotation "&rsaquo;": "›", // single right angle quotation "&oline;": "‾", // overline "&euro;": "€", // euro "&trade;": "™", // trademark "&larr;": "←", // left arrow "&uarr;": "↑", // up arrow "&rarr;": "→", // right arrow "&darr;": "↓", // down arrow "&harr;": "↔", // left right arrow "&crarr;": "↵", // carriage return arrow "&lceil;": "⌈", // left ceiling "&rceil;": "⌉", // right ceiling "&lfloor;": "⌊", // left floor "&rfloor;": "⌋", // right floor "&loz;": "◊", // lozenge "&spades;": "♠", // spade "&clubs;": "♣", // club "&hearts;": "♥", // heart "&diams;": "♦", // diamond ] var temp = self.trimmingCharacters(in: NSCharacterSet.newlines) //ASCII standard says you can optionally have zero before any two digit codes: //http://www-ee.eng.hawaii.edu/~tep/EE160/Book/chap4/subsection2.1.1.1.html temp = temp.replacingOccurrences(of: "&#0", with: "&#") for ascii in asciiMap.keys { temp = temp.replacingOccurrences(of: ascii, with: asciiMap[ascii]!) } return temp } func stringByStrippingHTML(trimmingWhitespace: Bool) -> String { var temp = self.decodedHTMLEntities() let regex1 = try? NSRegularExpression(pattern: "<[^>]+>") temp = regex1?.stringByReplacingMatches(in: temp, range: NSMakeRange(0, temp.count), withTemplate: "") ?? temp let regex2 = try? NSRegularExpression(pattern: "\t+") temp = regex2?.stringByReplacingMatches(in: temp, range: NSMakeRange(0, temp.count), withTemplate: " ") ?? temp if trimmingWhitespace { temp = temp.trimmingCharacters(in: .whitespacesAndNewlines) } let regex3 = try? NSRegularExpression(pattern: " {2,}") temp = regex3?.stringByReplacingMatches(in: temp, range: NSMakeRange(0, temp.count), withTemplate: " ") ?? temp return temp } func stringByLinkifyingURLs() -> String { let pattern = "(?<!=\")\\b((http|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%%&amp;:/~\\+#]*[\\w\\-\\@?^=%%&amp;/~\\+#])?)" guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return self } return regex.stringByReplacingMatches(in: self, options: [], range: NSMakeRange(0, self.count), withTemplate: "<a href=\"$1\" class=\"linkified\">$1</a>") } func applyBYUTitleCapitalization() -> String { let wordsWithCapitalizationExceptions = ["and", "BYU", "BYUSA", "CAEDM", "CB", "CIO", "CITES", "CES", "CNA", "CTB", "DNA", "FLAS", "FM", "for", "ICLA", "ID", "KBYU", "LDS", "McDonald", "McKay", "MTC", "MPH", "N7BYU", "NMELRC", "of", "ORCA", "RB", "ROTC", "SAS", "SFH", "TEC", "the", "TV", "WSC", "YNews", "YSA"] var temp = self.trimmingCharacters(in: .whitespacesAndNewlines) temp = temp.capitalized for word in wordsWithCapitalizationExceptions { let regex = try? NSRegularExpression(pattern: "\\b\(word)\\b", options: .caseInsensitive) temp = regex?.stringByReplacingMatches(in: temp, range: NSMakeRange(0, temp.count), withTemplate: word) ?? temp } //Capitalize first letter in the string, even if it was changed to lowercase because of an exception word return temp.stringWithFirstLetterCapitalized() } } extension CLLocationCoordinate2D { func isWithinBounds(minLat: Double, maxLat: Double, minLong: Double, maxLong: Double) -> Bool { let (lat, long) = (Double(self.latitude), Double(self.longitude)) //Return a boolean indicating whether the coordinate's latitude and longitude are within the minimum and maximum points provided return lat >= minLat && lat <= maxLat && long >= minLong && long <= maxLong } } extension Array where Element: CampusBuilding2 { func sorted(using location: CLLocation) -> [CampusBuilding2] { return self.sorted { //Sort by distance from provided location return CLLocation(latitude: $0.coordinate.latitude, longitude: $0.coordinate.longitude).distance(from: location) < CLLocation(latitude: $1.coordinate.latitude, longitude: $1.coordinate.longitude).distance(from: location) } } func findBuilding(with acronym: String) -> CampusBuilding2? { //Some acronym arguments might have a hyphen in them (e.g., B-66 coming from Department Directory) return self.first { $0.acronym == acronym.replacingOccurrences(of: "-", with: "") } } func buildings(matching searchText: String) -> [CampusBuilding2] { return self.filter { $0.name?.range(of: searchText, options: .caseInsensitive) != nil || $0.acronym.range(of: searchText, options: .caseInsensitive) != nil } } } //MARK: NS (Advanced data types) extension DateFormatter { @objc static func defaultDateFormat(_ format: String) -> DateFormatter { let formatter = DateFormatter() formatter.locale = Locale(identifier: "US") formatter.dateFormat = format return formatter } func date(from string: String?) -> Date? { if let string = string { return self.date(from: string) } else { return nil } } func string(fromOptional date: Date?) -> String? { if let date = date { return self.string(from: date) } else { return nil } } } extension Array { mutating func filterAndRemove(where closure: (Element) -> Bool) -> [Element] { var filteredElements = [Element]() var rejectedElements = [Element]() for item in self { if closure(item) { filteredElements.append(item) } else { rejectedElements.append(item) } } self = rejectedElements return filteredElements } } extension Dictionary where Key == String, Value == Any { init(tuples: [(String, Any?)]) { self = Dictionary() for tuple in tuples { self[tuple.0] = tuple.1 } } } extension Dictionary { func keysAsArray() -> [Key] { return Array(self.keys) } } extension IndexPath { init(row: Int) { self.init(row: row, section: 0) } } extension MKMapView { func deselectSelectedAnnotation() { self.deselectAnnotation(self.selectedAnnotations.last, animated: true) } func dequeueDefaultReusablePin(pinId: String = "pin", annotation: MKAnnotation) -> MKPinAnnotationView { var pinView: MKPinAnnotationView if let reusablePinView = self.dequeueReusableAnnotationView(withIdentifier: pinId) as? MKPinAnnotationView { pinView = reusablePinView } else { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: pinId) } pinView.tintColor = .byuTint //Colors the detail disclosure button pinView.pinTintColor = .byuTint return pinView } func defaultBuildingAnnotationView(annotation: MKAnnotation, displayDetailDisclosureButton: Bool = true) -> MKAnnotationView? { //Only one annotation will not be a CampusBuilding for features using this (user location) guard let building = annotation as? CampusBuilding2 else { return nil } if let pinView = self.dequeueReusableAnnotationView(withIdentifier: "pin") as? MKPinAnnotationView { return pinView } else { return pinAnnotationView(displayDetailDisclosureButton: displayDetailDisclosureButton, forBuildingAnnotation: building, animatingDrop: false) } } func pinAnnotationView(displayDetailDisclosureButton: Bool, forBuildingAnnotation annotation: CampusBuilding2, animatingDrop: Bool) -> MKPinAnnotationView { let pinView = MKPinAnnotationView(annotation: annotation) pinView.canShowCallout = true pinView.animatesDrop = animatingDrop pinView.tintColor = .byuTint //Colors the detail disclosure button pinView.pinTintColor = .byuTint if displayDetailDisclosureButton { //Add detail button to callout pinView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } else { pinView.rightCalloutAccessoryView = nil } return pinView } func zoomToAnnotation(_ annotation: MKAnnotation, delta: Double = 0.003, animated: Bool = true) { self.setRegion(MKCoordinateRegion(center: annotation.coordinate, span: MKCoordinateSpan(latitudeDelta: delta, longitudeDelta: delta) ), animated: animated) } } extension MKPinAnnotationView { convenience init(annotation: MKAnnotation, id: String = "pin", pinTintColor: UIColor = UIColor.byuBlue, animatesDrop: Bool = false, canShowCallout: Bool = true, rightCalloutAccessoryView: UIButton? = nil) { self.init(annotation: annotation, reuseIdentifier: id) self.pinTintColor = pinTintColor self.animatesDrop = animatesDrop self.canShowCallout = rightCalloutAccessoryView != nil ? true : canShowCallout self.rightCalloutAccessoryView = rightCalloutAccessoryView } } extension NSLayoutConstraint { convenience init(item: Any, attr1: NSLayoutAttribute, relatedBy: NSLayoutRelation = .equal, toItem: Any? = nil, attr2: NSLayoutAttribute = .notAnAttribute, multiplier: CGFloat = 1, constant: CGFloat = 0) { self.init(item: item, attribute: attr1, relatedBy: relatedBy, toItem: toItem, attribute: attr2, multiplier: multiplier, constant: constant) } } extension NSLayoutDimension { func constraint(equalTo anchor: NSLayoutDimension, multiplier: CGFloat, priority: Float) -> NSLayoutConstraint { let constraintWithPriority: NSLayoutConstraint = constraint(equalTo: anchor, multiplier: multiplier) constraintWithPriority.priority = priority return constraintWithPriority } } extension NSAttributedString { convenience init(html: String) throws { if let data = html.data(using: .utf8) { try self.init(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) } else { self.init(string: html) } } } //MARK: UI extension UIApplication { static func open(url: URL) { if #available(iOS 10.0, *) { UIApplication.shared.open(url) } else { UIApplication.shared.openURL(url) } } } extension UICollectionView { func deselectSelectedItems() { if let indexPaths = self.indexPathsForSelectedItems { for indexPath in indexPaths { self.deselectItem(at: indexPath, animated: true) } } } func dequeueReusableCell(for indexPath: IndexPath, reuseIdentifier: String = "cell") -> UICollectionViewCell { return self.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) } } extension UIColor { convenience init(red: CGFloat, green: CGFloat, blue: CGFloat, opacity: CGFloat = 1) { self.init(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: opacity) } // this defines the global tint color for interactive elements - set to a lightish blue #1b5d9d static var byuTint: UIColor { return UIColor(red: 27, green: 93, blue: 157) } // background of the views -> white static var byuBackground: UIColor { return UIColor(red: 255, green: 255, blue: 255) } // the interactive tint color for the nav bars - set to a lighter blue than the typical tint color, at #8ec4ff static var byuNavigationBarTint: UIColor { return UIColor(red: 142, green: 196, blue: 255) } // top nav bar color -> Dark Blue - #315c8c static var byuNavigationBarBarTint: UIColor { return UIColor(red: 49, green: 92, blue: 140) } // these are the bottom "action" buttons, such as "add features, launch feature" - set to #eeeeee static var byuToolbarTint: UIColor { return UIColor(red: 0, green: 51, blue: 102) } static var byuToolbarBarTint: UIColor { return UIColor(red:238, green:238, blue:238) } // TODO: it doesn't display the correct color static var byuSearchBarTint: UIColor { return UIColor.byuNavigationBarTint } static var byuSearchBarBarTint: UIColor { return UIColor.byuNavigationBarBarTint } //this is actually the tint color //#1B5D9D static var byuSwitchSegmentHighlighted: UIColor { return UIColor(red: 27, green: 93, blue: 157) } //this is the text color static var byuSwitchSegment: UIColor { return UIColor(red: 0, green: 51, blue: 102) } static var byuSwitchOnTint: UIColor { return .green } static var byuTextFieldBackground: UIColor { return UIColor(red:250, green:250, blue:250) } static var byuTextFieldBorder: UIColor { return UIColor.byuDetailText } static var byuTableSeparatorDefault: UIColor { return UIColor(red:174, green:176, blue:177) } // the colors of the section headers static var byuTableSectionHeaderBackground: UIColor { return UIColor(red:238, green:238, blue:238) } //the color of the section header text static var byuTableSectionHeader: UIColor { return UIColor(red:120, green:120, blue:120) } static var byuText: UIColor { return UIColor.black } static var byuDetailText: UIColor { return UIColor(red: 189, green: 189, blue: 189) } static var byuBlue: UIColor { return .byuTint } static var byuRed: UIColor { return UIColor(red:184, green:95, blue:95) } static var byuGreen: UIColor { return UIColor(red:95, green:184, blue:95); } static var yTimeGreen: UIColor { return UIColor(red: 0, green: 170, blue: 0); } static var yTimeRed: UIColor { return UIColor(red: 170, green: 0, blue: 0); } @objc static var byuRedFaded: UIColor { return UIColor(red: 184, green: 95, blue: 95, opacity: 0.25) } @objc static var byuGreenFaded: UIColor { return UIColor(red: 95, green: 184, blue:95, opacity: 0.25) } static var transparent: UIColor { return UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) } } extension UIFont { static var byuTableViewCellTextLabel: UIFont { return UIFont.systemFont(ofSize: 17) } static var byuTableViewCellDetailTextLebl: UIFont { return UIFont.byuTableViewCellTextLabel } static var byuTableViewCellSubtitle: UIFont { return UIFont.systemFont(ofSize: 12) } static var byuTableViewHeader: UIFont { return UIFont.systemFont(ofSize: 14) } } extension UIImage { func reduceSize(maxDemension: CGFloat) -> UIImage? { if self.size.width < maxDemension && self.size.height < maxDemension { return self } let imgRatio = self.size.width > self.size.height ? self.size.height / self.size.width : self.size.width / self.size.height let newSize = self.size.width > self.size.height ? CGSize(width: maxDemension, height: maxDemension * imgRatio) : CGSize(width: maxDemension * imgRatio, height: maxDemension) //Do the resizing with the ImageContext UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } } extension UINavigationBar { func applyByuFormatting() { self.isTranslucent = false self.barTintColor = .byuNavigationBarBarTint self.tintColor = .byuNavigationBarTint self.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] } } extension UISegmentedControl { func applyByuFormatting() { self.tintColor = .byuSwitchSegmentHighlighted self.backgroundColor = .white } } extension UITabBar { func applyByuFormatting() { self.barTintColor = .byuToolbarBarTint self.tintColor = .byuTint } } extension UITableView { func deselectSelectedRow() { if let selectedIndex = self.indexPathForSelectedRow { self.deselectRow(at: selectedIndex, animated: true) } } func hideEmptyCells() { tableFooterView = UIView() } //This method will make the rows of a tableView cell automatically adjust to fit contents //NOTE: The number of lines on the cell's textLabel must be set to 0 for this to work. //This can be done programatically or from the storyboard @objc func variableHeightForRows() { self.estimatedRowHeight = 44.0 //Arbitrary value, set to default cell height self.rowHeight = UITableViewAutomaticDimension //Needed to resize cells to fit contents } func registerNib(nibName: String, forCellIdentifier cellId: String = "cell") { self.register(UINib(nibName: nibName, bundle: nil), forCellReuseIdentifier: cellId) } func dequeueReusableCell(for indexPath: IndexPath, identifier: String = "cell") -> UITableViewCell { return self.dequeueReusableCell(withIdentifier: identifier, for: indexPath) } func addDefaultRefreshControl(target: Any?, action: Selector) -> UIRefreshControl { let refreshControl = UIRefreshControl() refreshControl.attributedTitle = NSAttributedString(string: "Loading...") refreshControl.addTarget(target, action: action, for: .valueChanged) refreshControl.beginRefreshing() self.addSubview(refreshControl) return refreshControl } func peekSwipeOptions(onRight: Bool = true, indexPath: IndexPath, buttonOptions: [(String, UIColor)], afterDelay delay: Double = 0, duration: Double = 0.8, withCallback callback: (() -> Void)? = nil) { self.layoutIfNeeded() if let cell = self.cellForRow(at: indexPath) { self.isUserInteractionEnabled = false var buttons = [UIButton]() // Keep track of the total button widths so that the next button is placed next to the previous one var totalWidth: CGFloat = 0.0 for buttonOption in buttonOptions { let button = UIButton() button.backgroundColor = buttonOption.1 button.setTitle(buttonOption.0, for: .normal) button.setTitleColor(.white, for: .normal) button.sizeToFit() let width = button.frame.width + 30 let xOrigin = onRight ? cell.frame.width + totalWidth : -totalWidth - width button.frame = CGRect(x: xOrigin, y: 0, width: width, height: cell.frame.height) cell.contentView.addSubview(button) buttons.append(button) totalWidth += button.frame.width } UIView.animate(withDuration: duration, delay: delay, animations: { // For each view in the cell, move it by the combined widths of all buttons cell.subviews.forEach { $0.frame.origin.x += onRight ? -totalWidth : totalWidth } }, completion: { _ in UIView.animate(withDuration: duration, delay: 0.4, animations: { // For each view in the cell, move it by the combined widths of all buttons cell.subviews.forEach { $0.frame.origin.x += onRight ? totalWidth : -totalWidth } }, completion: { _ in // Remove buttons after we are done displaying the swipe options buttons.forEach { $0.removeFromSuperview() } self.isUserInteractionEnabled = true if let callback = callback { callback() } }) }) } } func scrollToTop(animated: Bool = false) { self.scrollToRow(at: IndexPath(row: 0), at: .top, animated: animated) } } extension UIView { func setGradientBackground(bottom: UIColor, top: UIColor) { let gradient = CAGradientLayer() gradient.colors = [top.cgColor, bottom.cgColor] gradient.locations = [0.0, 1.0] gradient.frame.size = self.frame.size gradient.frame.origin = CGPoint(x: 0.0, y: 0.0) self.layer.insertSublayer(gradient, at: 0) } } extension UIViewController { @objc func presentSafariViewController(urlString: String, delegate: SFSafariViewControllerDelegate? = nil, errorHandler: (() -> Void)? = nil) { if let url = URL(string: urlString) { let svc = SFSafariViewController(url: url) svc.delegate = delegate if #available(iOS 10.0, *) { svc.preferredBarTintColor = .byuNavigationBarBarTint svc.preferredControlTintColor = .white } self.present(svc, animated: true) } else { displayAlert(title: "Error loading URL", message: "There was an error loading this web page. If this error persists please provide feedback or contact the OIT service desk.", alertHandler: { (_) in if let errorHandler = errorHandler { errorHandler() } }) } } //This function is for convenience only. Sadly, we have fought for too long to try and make "popBack" the default alertHandler for the function below... to no avail. This will have to do. func displayAlert(error: ByuError? = nil, title: String = "Error", message: String? = nil) { displayAlert(error: error, title: title, message: message) { (_) in self.popBack() } } func displayAlert(error: ByuError? = nil, title: String = "Error", message: String? = nil, alertHandler: ((UIAlertAction?) -> Void)?) { guard let vc = self.navigationController?.visibleViewController, !vc.isKind(of: UIAlertController.self) else { return } let alert = UIAlertController(title: title, message: message ?? error?.readableMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: alertHandler)) present(alert, animated: true, completion: nil) } func displayLoadingView(message: String) -> LoadingView { return LoadingView.addAsSubview(to: view, withMessage: message) } func popBack() { navigationController?.popViewController(animated: true) } func showToast(message: String, type: ToastView.ToastType = .success, dismissDelay: TimeInterval = 3.5, completion: @escaping () -> () = {}) { ToastView.show(in: self.view, message: message, type: type, dismissDelay: dismissDelay, completion: completion) } }
apache-2.0
c5bb0c12e05499db63757c8dc337d276
28.776423
313
0.592573
2.978853
false
false
false
false
colbylwilliams/bugtrap
iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/JIRA/Domain/JiraIssueCreateMeta.swift
1
915
// // JiraIssueCreateMeta.swift // bugTrap // // Created by Colby L Williams on 1/26/15. // Copyright (c) 2015 bugTrap. All rights reserved. // import Foundation class JiraIssueCreateMeta : JsonSerializable { var projects = [JiraProject]() init() { } init (projects: [JiraProject]) { self.projects = projects } class func deserialize (json: JSON) -> JiraIssueCreateMeta? { let projects: [JiraProject] = JiraProject.deserializeAll(json["projects"]) return JiraIssueCreateMeta(projects: projects) } class func deserializeAll(json: JSON) -> [JiraIssueCreateMeta] { var items = [JiraIssueCreateMeta]() if let jsonArray = json.array { for item: JSON in jsonArray { if let si = deserialize(item) { items.append(si) } } } return items } func serialize () -> NSMutableDictionary { let dict = NSMutableDictionary() return dict } }
mit
f38890b7a1b42f652c14b6f0f9ebb0b7
16.283019
76
0.663388
3.426966
false
false
false
false
zakkhoyt/ColorPicKit
ColorPicKitExample/NibDefinable.swift
1
1904
// // NibDefinable.swift // // Created by Zakk Hoyt on 1/21/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit protocol NibDefinable { var nibName: String { get } func xibSetup() func loadViewFromXib() -> UIView } extension NibDefinable { var nibName : String { return String(describing: type(of: self)) } } /** Example class */ // import UIKit // // class MyView: UIView, NibDefinable { // // // // MARK: Begin NibDefinable // // @IBOutlet weak var contentView : UIView! // // override init(frame: CGRect) { // super.init(frame: frame) // xibSetup() // } // // required init?(coder aDecoder: NSCoder) { // super.init(coder: aDecoder) // xibSetup() // } // // func xibSetup() { // contentView = loadViewFromXib() // contentView.frame = bounds // contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // backgroundColor = UIColor.clear // addSubview(contentView) // } // // func loadViewFromXib() -> UIView { // let bundle = Bundle(for: type(of: self)) // let nib = UINib(nibName: nibName, bundle: bundle) // let view = nib.instantiate(withOwner: self, options: nil).first as! UIView // return view // } // // // // // MARK: Public variables // // // MARK: Private variables // // // MARK: Publilc methods // // // MARK: Private methods // // override func awakeFromNib() { // super.awakeFromNib() // } // // // override func prepareForInterfaceBuilder() { // super.prepareForInterfaceBuilder() // } // // }
mit
1cbf92073869f4cc22098302efa36d23
23.088608
88
0.502365
4.066239
false
false
false
false
pietrocaselani/Trakt-Swift
Trakt/TraktError.swift
1
716
public enum TraktError: Error, Hashable { case cantAuthenticate(message: String) case authenticateError(statusCode: Int, response: String?) case missingJSONValue(message: String) public var hashValue: Int { var hash = self.localizedDescription.hashValue switch self { case .cantAuthenticate(let message): hash ^= message.hashValue case .authenticateError(let statusCode, let response): if let responseHash = response?.hashValue { hash ^= responseHash } hash ^= statusCode.hashValue case .missingJSONValue(let message): hash ^= message.hashValue } return hash } public static func == (lhs: TraktError, rhs: TraktError) -> Bool { return lhs.hashValue == rhs.hashValue } }
unlicense
a7b6b15904e3de70d22edf706ecc5d8b
25.518519
67
0.72905
3.912568
false
false
false
false
adamhartford/SwiftR
SwiftR iOS Demo/ViewController.swift
1
5854
// // ViewController.swift // SwiftR iOS Demo // // Created by Adam Hartford on 4/16/15. // Copyright (c) 2015 Adam Hartford. All rights reserved. // import UIKit import SwiftR class ViewController: UIViewController { @IBOutlet weak var startButton: UIButton! var simpleHub: Hub! var complexHub: Hub! var hubConnection: SignalR! var persistentConnection: SignalR! override func viewDidLoad() { super.viewDidLoad() // Make sure myserver.com is mapped to 127.0.0.1 in /etc/hosts // Or change myserver.com to localhost or IP below // Hubs... hubConnection = SignalR("http://myserver.com:5000") hubConnection.useWKWebView = true hubConnection.transport = .serverSentEvents hubConnection.queryString = ["foo": "bar"] hubConnection.headers = ["X-MyHeader1": "Value1", "X-MyHeader2": "Value2"] // This only works with WKWebView on iOS >= 9 // Otherwise, use NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": "SwiftR iOS Demo App"]) hubConnection.customUserAgent = "SwiftR iOS Demo App" simpleHub = Hub("simpleHub") complexHub = Hub("complexHub") simpleHub.on("notifySimple") { args in let message = args![0] as! String let detail = args![1] as! String print("Message: \(message)\nDetail: \(detail)\n") } complexHub.on("notifyComplex") { args in let m: AnyObject = args![0] as AnyObject! print(m) } hubConnection.addHub(simpleHub) hubConnection.addHub(complexHub) // SignalR events hubConnection.starting = { [weak self] in print("Starting...") self?.startButton.isEnabled = false self?.startButton.setTitle("Connecting...", for: UIControlState()) } hubConnection.reconnecting = { [weak self] in print("Reconnecting...") self?.startButton.isEnabled = false self?.startButton.setTitle("Reconnecting...", for: UIControlState()) } hubConnection.connected = { [weak self] in print("Connected. Connection ID: \(String(describing: self!.hubConnection.connectionID))") self?.startButton.isEnabled = true self?.startButton.setTitle("Stop", for: UIControlState()) } hubConnection.reconnected = { [weak self] in print("Reconnected. Connection ID: \(String(describing: self!.hubConnection.connectionID))") self?.startButton.isEnabled = true self?.startButton.setTitle("Stop", for: UIControlState()) } hubConnection.disconnected = { [weak self] in print("Disconnected.") self?.startButton.isEnabled = true self?.startButton.setTitle("Start", for: UIControlState()) } hubConnection.connectionSlow = { print("Connection slow...") } hubConnection.error = { [weak self] error in print("Error: \(String(describing: error))") // Here's an example of how to automatically reconnect after a timeout. // // For example, on the device, if the app is in the background long enough // for the SignalR connection to time out, you'll get disconnected/error // notifications when the app becomes active again. if let source = error?["source"] as? String , source == "TimeoutException" { print("Connection timed out. Restarting...") self?.hubConnection.start() } } hubConnection.start() // Persistent connection... // Uncomment when using persitent connections on your SignalR server // persistentConnection = SignalR("http://myserver.com:5000/echo", connectionType: .persistent) // persistentConnection.received = { data in // print(data!) // } // persistentConnection.connect() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sendSimpleMessage(_ sender: AnyObject?) { do { try simpleHub.invoke("sendSimple", arguments: ["Simple Test", "This is a simple message"]) } catch { print(error) } // Or... // simpleHub.invoke("sendSimple", arguments: ["Simple Test", "This is a simple message"]) { (result, error) in // if let e = error { // print("Error: \(e)") // } else { // print("Done!") // if let r = result { // print("Result: \(r)") // } // } // } } @IBAction func sendComplexMessage(_ sender: AnyObject?) { let message = [ "messageId": 1, "message": "Complex Test", "detail": "This is a complex message", "items": ["foo", "bar", "baz"] ] as [String : Any] do { try complexHub.invoke("sendComplex", arguments: [message]) } catch { print(error) } } @IBAction func sendData(_ sender: AnyObject?) { persistentConnection.send("Persistent Connection Test") } @IBAction func startStop(_ sender: AnyObject?) { switch hubConnection.state { case .disconnected: hubConnection.start() case .connected: hubConnection.stop() default: break } } }
mit
c78b4536c03b18de55cff82807df84e5
32.83815
118
0.551759
4.948436
false
false
false
false
automationWisdri/WISData.JunZheng
WISData.JunZheng/Common/Extension/NSDate+WIS.swift
1
1124
// // NSDate+WIS.swift // WISData.JunZheng // // Created by Jingwei Wu on 17/01/2017. // Copyright © 2017 Wisdri. All rights reserved. // import Foundation extension NSDate { class var today: NSDate { get { return NSDate.init() } } class var yesterday: NSDate { get { return NSDate.init(timeIntervalSinceNow: -24*60*60.0) } } class var tomorrow: NSDate { get { return NSDate.init(timeIntervalSinceNow: +24*60*60.0) } } var noon: NSDate { get { let calendar = NSCalendar.currentCalendar() let todayDateComponents: NSDateComponents = NSDateComponents.init() todayDateComponents.hour = 12 todayDateComponents.minute = 0 todayDateComponents.second = 0 return calendar.dateByAddingComponents(todayDateComponents, toDate: self, options: .MatchStrictly)! } } var isNowAfternoonOrLater: Bool { get { let result = self.compare(self.noon) return result == NSComparisonResult.OrderedDescending ? true : false } } }
mit
7cfd7ff04b449e02e82678d2ccb83e3f
25.738095
111
0.610864
4.456349
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Availability/AvailabilityTitleView.swift
1
5582
// // Wire // Copyright (C) 2017 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 UIKit import WireDataModel import WireSyncEngine import WireCommonComponents /** * A title view subclass that displays the availability of the user. */ final class AvailabilityTitleView: TitleView, ZMUserObserver { /// The available options for this view. struct Options: OptionSet { let rawValue: Int /// Whether we allow the user to update the status by tapping this view. static let allowSettingStatus = Options(rawValue: 1 << 0) /// Whether to hide the action hint (down arrow) next to the status. static let hideActionHint = Options(rawValue: 1 << 1) /// Whether to display the user name instead of the availability. static let displayUserName = Options(rawValue: 1 << 2) /// Whether to use a large text font instead of the default small one. static let useLargeFont = Options(rawValue: 1 << 3) /// The default options for using the view in a title bar. static var header: Options = [.allowSettingStatus, .hideActionHint, .displayUserName, .useLargeFont] } // MARK: - Properties private let user: UserType private var observerToken: Any? private var options: Options private let feedbackGenerator = UIImpactFeedbackGenerator(style: .medium) // MARK: - Initialization /** * Creates a view for the specific user and options. * - parameter user: The user to display the availability of. * - parameter options: The options to display the availability. */ init(user: UserType, options: Options) { self.options = options self.user = user super.init() if let sharedSession = ZMUserSession.shared() { self.observerToken = UserChangeInfo.add(observer: self, for: user, in: sharedSession) } NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) updateConfiguration() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Configuration override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) guard previousTraitCollection?.userInterfaceStyle != traitCollection.userInterfaceStyle else { return } updateConfiguration() } /// Refreshes the content and appearance of the view. func updateConfiguration() { updateAppearance() updateContent() } /// Refreshes the content of the view, based on the user data and the options. private func updateContent() { typealias AvailabilityStatusStrings = L10n.Accessibility.AccountPage.AvailabilityStatus let availability = user.availability let fontStyle: FontSize = options.contains(.useLargeFont) ? .normal : .small let icon = AvailabilityStringBuilder.icon( for: availability, with: AvailabilityStringBuilder.color(for: availability), and: fontStyle) let isInteractive = options.contains(.allowSettingStatus) var title = "" if options.contains(.displayUserName) { title = user.name ?? "" accessibilityLabel = title } else if availability == .none && options.contains(.allowSettingStatus) { title = L10n.Localizable.Availability.Message.setStatus accessibilityLabel = title } else if availability != .none { title = availability.localizedName.localized accessibilityLabel = AvailabilityStatusStrings.description } let showInteractiveIcon = isInteractive && !options.contains(.hideActionHint) super.configure(icon: icon, title: title, interactive: isInteractive, showInteractiveIcon: showInteractiveIcon) accessibilityValue = availability != .none ? availability.localizedName : "" if options.contains(.allowSettingStatus) { accessibilityTraits = .button accessibilityHint = AvailabilityStatusStrings.hint } } /// Sets the titleFont and titleColor for the view. private func updateAppearance() { if options.contains(.useLargeFont) { titleFont = .headerSemiboldFont } else { titleFont = .headerRegularFont } titleColor = SemanticColors.Label.textDefault } // MARK: - Events @objc private func applicationDidBecomeActive() { updateConfiguration() } func userDidChange(_ changeInfo: UserChangeInfo) { guard changeInfo.availabilityChanged || changeInfo.nameChanged else { return } updateConfiguration() } }
gpl-3.0
04a1f0e9ca1fc18835b4a2efd6f84a56
34.329114
119
0.675743
5.221703
false
false
false
false
benlangmuir/swift
test/Constraints/if_expr.swift
20
3024
// RUN: %target-typecheck-verify-swift func useInt(_ x: Int) {} func useDouble(_ x: Double) {} class B { init() {} } class D1 : B { override init() { super.init() } } class D2 : B { override init() { super.init() } } func useB(_ x: B) {} func useD1(_ x: D1) {} func useD2(_ x: D2) {} var a = true ? 1 : 0 // should infer Int var b : Double = true ? 1 : 0 // should infer Double var c = true ? 1 : 0.0 // should infer Double var d = true ? 1.0 : 0 // should infer Double useInt(a) useDouble(b) useDouble(c) useDouble(d) var z = true ? a : b // expected-error{{result values in '? :' expression have mismatching types 'Int' and 'Double'}} var _ = a ? b : b // expected-error{{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} var e = true ? B() : B() // should infer B var f = true ? B() : D1() // should infer B var g = true ? D1() : B() // should infer B var h = true ? D1() : D1() // should infer D1 var i = true ? D1() : D2() // should infer B useB(e) useD1(e) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useB(f) useD1(f) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useB(g) useD1(g) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useB(h) useD1(h) useB(i) useD1(i) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}} useD2(i) // expected-error{{cannot convert value of type 'B' to expected argument type 'D2'}} var x = true ? 1 : 0 var y = 22 ? 1 : 0 // expected-error{{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} _ = x ? x : x // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} _ = true ? x : 1.2 // expected-error {{result values in '? :' expression have mismatching types 'Int' and 'Double'}} _ = (x: true) ? true : false // expected-error {{cannot convert value of type '(x: Bool)' to expected condition type 'Bool'}} _ = (x: 1) ? true : false // expected-error {{cannot convert value of type '(x: Int)' to expected condition type 'Bool'}} let ib: Bool! = false let eb: Bool? = .some(false) let conditional = ib ? "Broken" : "Heart" // should infer Bool! let conditional = eb ? "Broken" : "Heart" // expected-error {{value of optional type 'Bool?' must be unwrapped}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} // <rdar://problem/39586166> - crash when IfExpr has UnresolvedType in condition struct Delegate { var shellTasks: [ShellTask] } extension Array { subscript(safe safe: Int) -> Element? { get { } set { } } } struct ShellTask { var commandLine: [String] } let delegate = Delegate(shellTasks: []) _ = delegate.shellTasks[safe: 0]?.commandLine.compactMap({ $0.asString.hasPrefix("") ? $0 : nil }).count ?? 0 // expected-error@-1 {{value of type 'String' has no member 'asString'}}
apache-2.0
721418d89b18e0a9a7b3d3ae692af5cf
33.758621
125
0.644511
3.196617
false
false
false
false
wireapp/wire-ios-sync-engine
Source/Utility/Decodable+JSON.swift
1
2704
// // Wire // Copyright (C) 2020 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 Foundation extension Decodable { /// Initialize object from JSON Data /// /// - parameter jsonData: JSON data as raw bytes init?(_ jsonData: Data) { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in let container = try decoder.singleValueContainer() let rawDate = try container.decode(String.self) if let date = NSDate(transport: rawDate) { return date as Date } else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Expected date string to be ISO8601-formatted with fractional seconds") } }) do { self = try decoder.decode(Self.self, from: jsonData) } catch { Logging.network.debug("Failed to decode payload: \(error)") return nil } } } extension Decodable { /// Initialize object from a dictionary /// /// - parameter payload: Dictionary representing the object /// /// This only works for dictionaries which only contain type /// which can be represented as JSON. init?(_ payload: [String: Any]) { do { let jsonData = try JSONSerialization.data(withJSONObject: payload, options: .prettyPrinted) let decoder = JSONDecoder() self = try decoder.decode(Self.self, from: jsonData) } catch { Logging.network.debug("Failed to decode payload: \(error)") return nil } } } extension DateFormatter { static let iso8601Full: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" formatter.calendar = Calendar(identifier: .iso8601) formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.locale = Locale(identifier: "en_US_POSIX") return formatter }() }
gpl-3.0
3fc973e2997935193ab15b1c31d8d224
31.97561
144
0.628328
4.802842
false
false
false
false
Urinx/SomeCodes
Swift/swiftDemo/demo.1/demo.1/ViewController.swift
1
1094
// // ViewController.swift // demo.1 // // Created by Eular on 15-3-20. // Copyright (c) 2015年 Eular. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var num: UITextField @IBOutlet var qrcode: UIImageView override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) { num.resignFirstResponder() } @IBAction func confirmClick(sender: AnyObject) { num.resignFirstResponder() if let n = num.text.toInt() { if n % 2 == 0 { qrcode.image = UIImage(named: "IMG_0473.JPG") } else { qrcode.image = UIImage(named: "qrcode_for_gh_25b159f59282_430.jpg") } } } }
gpl-2.0
eb0022fbf75c24c0fab45957edf3e1e7
23.266667
83
0.578755
4.53112
false
false
false
false
frootloops/swift
test/SIL/Serialization/Inputs/def_generic_marker.swift
4
538
public protocol mmGeneratorType { associatedtype Element } public protocol mmSequenceType { associatedtype Generator : mmGeneratorType } public protocol mmCollectionType : mmSequenceType { mutating func extend< S : mmSequenceType where S.Generator.Element == Self.Generator.Element > (_ seq: S) } @_inlineable public func test< EC1 : mmCollectionType, EC2 : mmCollectionType where EC1.Generator.Element == EC2.Generator.Element > (_ lhs: EC1, _ rhs: EC2) -> EC1 { var lhs = lhs lhs.extend(rhs) return lhs }
apache-2.0
03e86910013d0ae6175fa4ef33ad3ff8
20.52
55
0.723048
3.842857
false
false
false
false
OlegKetrar/Tools
Sources/Tools/UIKit/Extensions/UIView+AutoLayout.swift
1
2585
// // UIView+AutoLayout.swift // ToolsUIKit // // Created by Oleg Ketrar on 12.01.18. // Copyright © 2018 Oleg Ketrar. All rights reserved. // import Foundation import UIKit extension UIView { @discardableResult public func addPinConstraint( toSubview subview: UIView, attribute: NSLayoutConstraint.Attribute, withSpacing spacing: CGFloat) -> NSLayoutConstraint { subview.translatesAutoresizingMaskIntoConstraints = false let constraint = NSLayoutConstraint( item: subview, attribute: attribute, relatedBy: .equal, toItem: self, attribute: attribute, multiplier: 1.0, constant: spacing) addConstraint(constraint) return constraint } @discardableResult public func addPinConstraints( toSubview subview: UIView, withSpacing spacing: CGFloat = 0.0) -> [NSLayoutConstraint] { return [ addPinConstraint(toSubview: subview, attribute: .left, withSpacing: spacing), addPinConstraint(toSubview: subview, attribute: .top, withSpacing: spacing), addPinConstraint(toSubview: subview, attribute: .right, withSpacing: -spacing), addPinConstraint(toSubview: subview, attribute: .bottom, withSpacing: -spacing) ] } public func addPinnedSubview(_ subview: UIView, withSpacing spacing: CGFloat = 0.0) { addSubview(subview) translatesAutoresizingMaskIntoConstraints = false addPinConstraints(toSubview: subview, withSpacing: spacing) } public func addPinnedSubview(_ subview: UIView, withInsets insets: UIEdgeInsets) { addSubview(subview) translatesAutoresizingMaskIntoConstraints = false subview.pinToSuperview(insets: insets) } @discardableResult public func pinToSuperview( attribute: NSLayoutConstraint.Attribute, spacing: CGFloat = 0) -> NSLayoutConstraint? { return superview?.addPinConstraint( toSubview: self, attribute: attribute, withSpacing: spacing) } @discardableResult public func pinToSuperview(insets: UIEdgeInsets) -> [NSLayoutConstraint] { return [ pinToSuperview(attribute: .left, spacing: insets.left), pinToSuperview(attribute: .top, spacing: insets.top), pinToSuperview(attribute: .right, spacing: -insets.right), pinToSuperview(attribute: .bottom, spacing: -insets.bottom) ] .compactMap { $0 } } }
mit
bf2af276fe1dd40f4754af1a03785b92
30.901235
91
0.651316
5.066667
false
false
false
false
Draveness/RbSwift
RbSwift/Hash/Hash+Enumeration.swift
1
2021
// // Hash+Enumeration.swift // RbSwift // // Created by draveness on 07/04/2017. // Copyright © 2017 draveness. All rights reserved. // import Foundation // MARK: - Enumeration public extension Hash { /// Calls block once for each key in hsh, passing the key-value pair as parameters. /// An alias to `Sequence#each(closure:)` method. /// /// let hash = ["a": 100, "b": 200] /// var result: [String: Int] = [:] /// hash.eachPair { /// result[$0] = $1 + 100 /// }) #=> ["a": 100, "b": 200] /// /// result #=> ["a": 200, "b": 300] /// /// - Parameter closure: An closure accepts key-value pair as parameters. /// - Returns: Self. @discardableResult func eachPair(closure: (Key, Value) -> Void) -> Hash<Key, Value> { return self.each(closure) } /// Calls block once for each key in hsh, passing the key as parameters. /// /// let hash = ["a": 100, "b": 200] /// var result: [String] = [] /// hash.eachKey { /// result.append($0) /// }) #=> ["a", "b"] /// /// result #=> ["a": 100, "b": 200] /// /// - Parameter closure: An closure accepts key as parameters. /// - Returns: Self. @discardableResult func eachKey(closure: (Key) -> Void) -> Hash<Key, Value> { self.keys.each(closure) return self } /// Calls block once for each key in hsh, passing the value as parameters. /// /// let hash = ["a": 100, "b": 200] /// var result: [Int] = [] /// hash.eachValue { /// result.append($0) /// }) #=> [100, 200] /// /// result #=> ["a": 100, "b": 200] /// /// - Parameter closure: An closure accepts value as parameters. /// - Returns: Self. @discardableResult func eachValue(closure: (Value) -> Void) -> Hash<Key, Value> { self.values.each(closure) return self } }
mit
81abf0b1bcca765b76cf46993f172ffc
29.606061
87
0.5
3.679417
false
false
false
false
reeichert/JRToolbar
TransitionAnimation/ViewController.swift
1
4594
// // ViewController.swift // TransitionAnimation // // Created by Joao Reichert on 06/04/16. // Copyright © 2016 Joao Reichert. All rights reserved. // import UIKit import SteviaLayout import JRMaterial import SnapKit class ViewController: UIViewController, JRMaterialSheetDelegate { let toolbar = UIView() let colorBase = JRColor.red.base //----- override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() // prepareToolbar() prepareMaterialSheet() } func prepareToolbar(){ let button = JRToolbar() self.view.addSubview(button) button.snp_makeConstraints { (make) in make.bottom.equalTo(-40) make.right.equalTo(-40) make.size.equalTo(50) } button.setNeedsLayout() button.layoutIfNeeded() print(button.frame) button.updateConstraints() button.layer.cornerRadius = button.frame.width/2 button.backgroundColor = colorBase button.toolbar = getToolbar() } func prepareMaterialSheet() { let button = JRMaterialSheet(frame: CGRectZero) button.delegate = self self.view.addSubview(button) button.snp_makeConstraints { (make) in make.bottom.equalTo(-16) make.right.equalTo(-16) make.size.equalTo(50) } button.data = [ JRMaterialSheetData( title: "Teste 1", icon: UIImage(named: "ic_message")!), JRMaterialSheetData( title: "Teste 2", icon: UIImage(named: "ic_message")!), JRMaterialSheetData( title: "Teste 3", icon: UIImage(named: "ic_message")!), JRMaterialSheetData( title: "Teste 4", icon: UIImage(named: "ic_message")!) ] button.setNeedsLayout() button.layoutIfNeeded() button.updateConstraints() button.backgroundColor = colorBase } func sheetDidSelected(data: JRMaterialSheetData, indexPath: NSIndexPath) { print(data.title) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getToolbar() -> UIView { //(0.0, 508.0, 320.0, 60.0) let tb = UIView(frame: CGRect(x: 0, y: 508.0, width: JRDevice.width, height: 60)) tb.backgroundColor = colorBase let im1 = UIButton(type: .System) let im2 = UIButton(type: .System) let im3 = UIButton(type: .System) let im4 = UIButton(type: .System) let im5 = UIButton(type: .System) im1.setBackgroundImage(UIImage(named: "ic_email"), forState: .Normal) im2.setBackgroundImage(UIImage(named: "ic_email"), forState: .Normal) im3.setBackgroundImage(UIImage(named: "ic_email"), forState: .Normal) im4.setBackgroundImage(UIImage(named: "ic_email"), forState: .Normal) im5.setBackgroundImage(UIImage(named: "ic_email"), forState: .Normal) // // im1.addTarget(self, action: #selector(tap), forControlEvents: .TouchUpInside) // im2.addTarget(self, action: #selector(tap), forControlEvents: .TouchUpInside) // im3.addTarget(self, action: #selector(tap), forControlEvents: .TouchUpInside) // im4.addTarget(self, action: #selector(tap), forControlEvents: .TouchUpInside) // im5.addTarget(self, action: #selector(tap), forControlEvents: .TouchUpInside) tb.addSubviews(im1,im2,im3,im4,im5) var padding = 16 let over = 65 im1.snp_makeConstraints { (make) in make.size.equalTo(24) make.left.equalTo(padding) make.centerY.equalTo(tb) } padding = padding + over im2.snp_makeConstraints { (make) in make.size.equalTo(24) make.left.equalTo(padding) make.centerY.equalTo(tb) } padding = padding + over im3.snp_makeConstraints { (make) in make.size.equalTo(24) make.left.equalTo(padding) make.centerY.equalTo(tb) } padding = padding + over im4.snp_makeConstraints { (make) in make.size.equalTo(24) make.left.equalTo(padding) make.centerY.equalTo(tb) } padding = padding + over im5.snp_makeConstraints { (make) in make.size.equalTo(24) make.left.equalTo(padding) make.centerY.equalTo(tb) } padding = padding + over return tb } }
mit
c90dde9df7a6fd3cd0e1480690190d0c
22.797927
83
0.604833
3.889077
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/VideoPlayerProxy.swift
1
3471
import Foundation import SwiftSignalKit import AVFoundation private final class VideoPlayerProxyContext { private let queue: Queue var updateVideoInHierarchy: ((Bool) -> Void)? var node: MediaPlayerView? { didSet { self.node?.takeFrameAndQueue = self.takeFrameAndQueue self.node?.state = state self.updateVideoInHierarchy?(node?.videoInHierarchy ?? false) self.node?.updateVideoInHierarchy = { [weak self] value in self?.updateVideoInHierarchy?(value) } } } var takeFrameAndQueue: (Queue, () -> MediaTrackFrameResult)? { didSet { self.node?.takeFrameAndQueue = self.takeFrameAndQueue } } var state: (timebase: CMTimebase, requestFrames: Bool, rotationAngle: Double, aspect: Double)? { didSet { self.node?.state = self.state } } init(queue: Queue) { self.queue = queue } deinit { assert(self.queue.isCurrent()) } } final class VideoPlayerProxy { var takeFrameAndQueue: (Queue, () -> MediaTrackFrameResult)? { didSet { let updatedTakeFrameAndQueue = self.takeFrameAndQueue self.withContext { context in context?.takeFrameAndQueue = updatedTakeFrameAndQueue } } } var state: (timebase: CMTimebase, requestFrames: Bool, rotationAngle: Double, aspect: Double)? { didSet { let updatedState = self.state self.withContext { context in context?.state = updatedState } } } private let queue: Queue private let contextQueue = Queue.mainQueue() private var contextRef: Unmanaged<VideoPlayerProxyContext>? var visibility: Bool = false var visibilityUpdated: ((Bool) -> Void)? init(queue: Queue) { self.queue = queue self.contextQueue.async { let context = VideoPlayerProxyContext(queue: self.contextQueue) context.updateVideoInHierarchy = { [weak self] value in queue.async { if let strongSelf = self { if strongSelf.visibility != value { strongSelf.visibility = value strongSelf.visibilityUpdated?(value) } } } } self.contextRef = Unmanaged.passRetained(context) } } deinit { let contextRef = self.contextRef self.contextQueue.async { if let contextRef = contextRef { let context = contextRef.takeUnretainedValue() context.state = nil contextRef.release() } } } private func withContext(_ f: @escaping (VideoPlayerProxyContext?) -> Void) { self.contextQueue.async { if let contextRef = self.contextRef { let context = contextRef.takeUnretainedValue() f(context) } else { f(nil) } } } func attachNodeAndRelease(_ nodeRef: Unmanaged<MediaPlayerView>) { self.withContext { context in if let context = context { context.node = nodeRef.takeUnretainedValue() } nodeRef.release() } } }
gpl-2.0
222ab68a0b7bb1b13ca3fdbd9b150cf9
28.666667
100
0.54624
5.149852
false
false
false
false
PlusR/AAMFeedback
src/Feedback/Context.swift
1
3406
import Foundation public struct Context { public static var alwaysUseMainBundle: Bool = false public init ( title: String? = nil, descriptionText: String? = nil, topics: [String]? = nil, topicsToSend: [String]? = nil, toRecipients: [String] = [], ccRecipients: [String] = [], bccRecipients: [String] = [], selectedTopicsIndex: Int = 0, descriptionPlaceHolder: String? = nil, topicsTitle: String? = nil, attention: String? = nil, tableHeaderAttention: String? = nil, tableHeaderTopics: String? = nil, tableHeaderBasicInfo: String? = nil, mailDidFinishWithError: String? = nil, buttonMail: String? = nil, note: String? = nil ) { self.title = title ?? Context.localized(key: "AAMFeedbackTitle") self.descriptionText = descriptionText let t = topics ?? [ Context.localized(key: "AAMFeedbackTopicsQuestion"), Context.localized(key: "AAMFeedbackTopicsRequest"), Context.localized(key: "AAMFeedbackTopicsBugReport"), Context.localized(key: "AAMFeedbackTopicsMedia"), Context.localized(key: "AAMFeedbackTopicsBusiness"), Context.localized(key: "AAMFeedbackTopicsOther"), ] self.topics = t self.topicsToSend = topicsToSend ?? t self.toRecipients = toRecipients self.ccRecipients = ccRecipients self.bccRecipients = bccRecipients self.selectedTopicsIndex = selectedTopicsIndex self.descriptionPlaceHolder = descriptionPlaceHolder ?? Context.localized(key: "AAMFeedbackDescriptionPlaceholder") self.topicsTitle = topicsTitle ?? Context.localized(key: "AAMFeedbackTopicsTitle") self.attention = attention self.tableHeaderAttention = tableHeaderAttention ?? Context.localized(key: "AAMFeedbackTableHeaderAttention") self.tableHeaderTopics = tableHeaderTopics self.tableHeaderBasicInfo = tableHeaderBasicInfo ?? Context.localized(key: "AAMFeedbackTableHeaderBasicInfo") self.mailDidFinishWithError = mailDidFinishWithError ?? Context.localized(key: "AAMFeedbackMailDidFinishWithError") self.buttonMail = buttonMail ?? Context.localized(key: "AAMFeedbackButtonMail") self.note = note } let title: String let descriptionText: String? let topics: [String] let topicsToSend: [String] let toRecipients: [String] let ccRecipients: [String] let bccRecipients: [String] let selectedTopicsIndex: Int let descriptionPlaceHolder: String let topicsTitle: String let attention: String? let tableHeaderAttention: String let tableHeaderTopics: String? let tableHeaderBasicInfo: String let mailDidFinishWithError: String let buttonMail: String let note: String? static func localized(key: String) -> String { NSLocalizedString(key, tableName: "AAMLocalizable", bundle: Context.bundle(), value: "", comment: "") } static func bundle() -> Bundle { if !alwaysUseMainBundle, let bundleURL = Bundle(for: FeedbackViewController.self).url(forResource: "AAMFeedback", withExtension: "bundle"), let bundle = Bundle(url: bundleURL) { return bundle } else { return Bundle.main } } }
bsd-3-clause
ed16ec7113ee0c7fb1ae0bf764c0253b
40.036145
126
0.659425
4.590296
false
false
false
false
opentok/opentok-ios-sdk-samples-swift
Custom-Audio-Driver/Custom-Audio-Driver/DefaultAudioDevice.swift
1
25103
// // DefaultAudioDevice.swift // 4.Custom-Audio-Driver // // Created by Roberto Perez Cubero on 21/09/2016. // Copyright © 2016 tokbox. All rights reserved. // import Foundation import OpenTok class DefaultAudioDevice: NSObject { #if targetEnvironment(simulator) static let kSampleRate: UInt16 = 44100 #else static let kSampleRate: UInt16 = 48000 #endif static let kOutputBus = AudioUnitElement(0) static let kInputBus = AudioUnitElement(1) static let kAudioDeviceHeadset = "AudioSessionManagerDevice_Headset" static let kAudioDeviceBluetooth = "AudioSessionManagerDevice_Bluetooth" static let kAudioDeviceSpeaker = "AudioSessionManagerDevice_Speaker" static let kToMicroSecond: Double = 1000000 static let kMaxPlayoutDelay: UInt8 = 150 var audioFormat = OTAudioFormat() let safetyQueue = DispatchQueue(label: "ot-audio-driver") var deviceAudioBus: OTAudioBus? func setAudioBus(_ audioBus: OTAudioBus?) -> Bool { deviceAudioBus = audioBus audioFormat = OTAudioFormat() audioFormat.sampleRate = DefaultAudioDevice.kSampleRate audioFormat.numChannels = 1 return true } var bufferList: UnsafeMutablePointer<AudioBufferList>? var bufferSize: UInt32 = 0 var bufferNumFrames: UInt32 = 0 var playoutAudioUnitPropertyLatency: Float64 = 0 var playoutDelayMeasurementCounter: UInt32 = 0 var recordingDelayMeasurementCounter: UInt32 = 0 var recordingDelay: UInt32 = 0 var recordingAudioUnitPropertyLatency: Float64 = 0 var playoutDelay: UInt32 = 0 var playing = false var playoutInitialized = false var recording = false var recordingInitialized = false var interruptedPlayback = false var isRecorderInterrupted = false var isPlayerInterrupted = false var isResetting = false var restartRetryCount = 0 fileprivate var recordingVoiceUnit: AudioUnit? fileprivate var playoutVoiceUnit: AudioUnit? fileprivate var previousAVAudioSessionCategory: AVAudioSession.Category? fileprivate var avAudioSessionMode: AVAudioSession.Mode? fileprivate var avAudioSessionPreffSampleRate = Double(0) fileprivate var avAudioSessionChannels = 0 fileprivate var isAudioSessionSetup = false var areListenerBlocksSetup = false var streamFormat = AudioStreamBasicDescription() override init() { audioFormat.sampleRate = DefaultAudioDevice.kSampleRate audioFormat.numChannels = 1 } deinit { tearDownAudio() removeObservers() } fileprivate func restartAudio() { safetyQueue.async { self.doRestartAudio(numberOfAttempts: 3) } } fileprivate func restartAudioAfterInterruption() { if isRecorderInterrupted { if startCapture() { isRecorderInterrupted = false restartRetryCount = 0 } else { restartRetryCount += 1 if restartRetryCount < 3 { safetyQueue.asyncAfter(deadline: DispatchTime.now(), execute: { [unowned self] in self.restartAudioAfterInterruption() }) } else { isRecorderInterrupted = false isPlayerInterrupted = false restartRetryCount = 0 print("ERROR[OpenTok]:Unable to acquire audio session") } } } if isPlayerInterrupted { isPlayerInterrupted = false let _ = startRendering() } } fileprivate func doRestartAudio(numberOfAttempts: Int) { if recording { let _ = stopCapture() disposeAudioUnit(audioUnit: &recordingVoiceUnit) let _ = startCapture() } if playing { let _ = self.stopRendering() disposeAudioUnit(audioUnit: &playoutVoiceUnit) let _ = self.startRendering() } isResetting = false } fileprivate func setupAudioUnit(withPlayout playout: Bool) -> Bool { if !isAudioSessionSetup { setupAudioSession() isAudioSessionSetup = true } let bytesPerSample = UInt32(MemoryLayout<Int16>.size) streamFormat.mFormatID = kAudioFormatLinearPCM streamFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked streamFormat.mBytesPerPacket = bytesPerSample streamFormat.mFramesPerPacket = 1 streamFormat.mBytesPerFrame = bytesPerSample streamFormat.mChannelsPerFrame = 1 streamFormat.mBitsPerChannel = 8 * bytesPerSample streamFormat.mSampleRate = Float64(DefaultAudioDevice.kSampleRate) var audioUnitDescription = AudioComponentDescription() audioUnitDescription.componentType = kAudioUnitType_Output audioUnitDescription.componentSubType = kAudioUnitSubType_VoiceProcessingIO audioUnitDescription.componentManufacturer = kAudioUnitManufacturer_Apple audioUnitDescription.componentFlags = 0 audioUnitDescription.componentFlagsMask = 0 let foundVpioUnitRef = AudioComponentFindNext(nil, &audioUnitDescription) let result: OSStatus = { if playout { return AudioComponentInstanceNew(foundVpioUnitRef!, &playoutVoiceUnit) } else { return AudioComponentInstanceNew(foundVpioUnitRef!, &recordingVoiceUnit) } }() if result != noErr { print("Error seting up audio unit") return false } var value: UInt32 = 1 if playout { AudioUnitSetProperty(playoutVoiceUnit!, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, DefaultAudioDevice.kOutputBus, &value, UInt32(MemoryLayout<UInt32>.size)) AudioUnitSetProperty(playoutVoiceUnit!, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, DefaultAudioDevice.kOutputBus, &streamFormat, UInt32(MemoryLayout<AudioStreamBasicDescription>.size)) // Disable Input on playout var enableInput = 0 AudioUnitSetProperty(playoutVoiceUnit!, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, DefaultAudioDevice.kInputBus, &enableInput, UInt32(MemoryLayout<UInt32>.size)) } else { AudioUnitSetProperty(recordingVoiceUnit!, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, DefaultAudioDevice.kInputBus, &value, UInt32(MemoryLayout<UInt32>.size)) AudioUnitSetProperty(recordingVoiceUnit!, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, DefaultAudioDevice.kInputBus, &streamFormat, UInt32(MemoryLayout<AudioStreamBasicDescription>.size)) // Disable Output on record var enableOutput = 0 AudioUnitSetProperty(recordingVoiceUnit!, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, DefaultAudioDevice.kOutputBus, &enableOutput, UInt32(MemoryLayout<UInt32>.size)) } if playout { setupPlayoutCallback() } else { setupRecordingCallback() } setBluetoothAsPreferredInputDevice() return true } fileprivate func setupPlayoutCallback() { let selfPointer = Unmanaged.passUnretained(self).toOpaque() var renderCallback = AURenderCallbackStruct(inputProc: renderCb, inputProcRefCon: selfPointer) AudioUnitSetProperty(playoutVoiceUnit!, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, DefaultAudioDevice.kOutputBus, &renderCallback, UInt32(MemoryLayout<AURenderCallbackStruct>.size)) } fileprivate func setupRecordingCallback() { let selfPointer = Unmanaged.passUnretained(self).toOpaque() var inputCallback = AURenderCallbackStruct(inputProc: recordCb, inputProcRefCon: selfPointer) AudioUnitSetProperty(recordingVoiceUnit!, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, DefaultAudioDevice.kInputBus, &inputCallback, UInt32(MemoryLayout<AURenderCallbackStruct>.size)) var value = 0 AudioUnitSetProperty(recordingVoiceUnit!, kAudioUnitProperty_ShouldAllocateBuffer, kAudioUnitScope_Output, DefaultAudioDevice.kInputBus, &value, UInt32(MemoryLayout<UInt32>.size)) } fileprivate func disposeAudioUnit(audioUnit: inout AudioUnit?) { if let unit = audioUnit { AudioUnitUninitialize(unit) AudioComponentInstanceDispose(unit) } audioUnit = nil } fileprivate func tearDownAudio() { print("Destoying audio units") disposeAudioUnit(audioUnit: &playoutVoiceUnit) disposeAudioUnit(audioUnit: &recordingVoiceUnit) freeupAudioBuffers() let session = AVAudioSession.sharedInstance() do { guard let previousAVAudioSessionCategory = previousAVAudioSessionCategory else { return } try session.setCategory(previousAVAudioSessionCategory, mode: .default) guard let avAudioSessionMode = avAudioSessionMode else { return } try session.setMode(avAudioSessionMode) try session.setPreferredSampleRate(avAudioSessionPreffSampleRate) try session.setPreferredInputNumberOfChannels(avAudioSessionChannels) isAudioSessionSetup = false } catch { print("Error reseting AVAudioSession") } } fileprivate func freeupAudioBuffers() { if var data = bufferList?.pointee, data.mBuffers.mData != nil { data.mBuffers.mData?.assumingMemoryBound(to: UInt16.self).deallocate() data.mBuffers.mData = nil } if let list = bufferList { list.deallocate() } bufferList = nil bufferNumFrames = 0 } } // MARK: - Audio Device Implementation extension DefaultAudioDevice: OTAudioDevice { func captureFormat() -> OTAudioFormat { return audioFormat } func renderFormat() -> OTAudioFormat { return audioFormat } func renderingIsAvailable() -> Bool { return true } func renderingIsInitialized() -> Bool { return playoutInitialized } func isRendering() -> Bool { return playing } func isCapturing() -> Bool { return recording } func estimatedRenderDelay() -> UInt16 { return UInt16(min(self.playoutDelay, UInt32(DefaultAudioDevice.kMaxPlayoutDelay))) } func estimatedCaptureDelay() -> UInt16 { return UInt16(self.recordingDelay) } func captureIsAvailable() -> Bool { return true } func captureIsInitialized() -> Bool { return recordingInitialized } func initializeRendering() -> Bool { if playing { return false } playoutInitialized = true return playoutInitialized } func startRendering() -> Bool { if playing { return true } playing = true if playoutVoiceUnit == nil { playing = setupAudioUnit(withPlayout: true) if !playing { return false } } let result = AudioOutputUnitStart(playoutVoiceUnit!) if result != noErr { print("Error creaing rendering unit") playing = false } return playing } func stopRendering() -> Bool { if !playing { return true } playing = false let result = AudioOutputUnitStop(playoutVoiceUnit!) if result != noErr { print("Error creaing playout unit") return false } if !recording && !isPlayerInterrupted && !isResetting { tearDownAudio() } return true } func initializeCapture() -> Bool { if recording { return false } recordingInitialized = true return recordingInitialized } func startCapture() -> Bool { if recording { return true } recording = true if recordingVoiceUnit == nil { recording = setupAudioUnit(withPlayout: false) if !recording { return false } } let result = AudioOutputUnitStart(recordingVoiceUnit!) if result != noErr { recording = false } return recording } func stopCapture() -> Bool { if !recording { return true } recording = false let result = AudioOutputUnitStop(recordingVoiceUnit!) if result != noErr { return false } freeupAudioBuffers() if !recording && !isRecorderInterrupted && !isResetting { tearDownAudio() } return true } } // MARK: - AVAudioSession extension DefaultAudioDevice { @objc func onInterruptionEvent(notification: Notification) { let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] safetyQueue.async { self.handleInterruptionEvent(type: type as? Int) } } fileprivate func handleInterruptionEvent(type: Int?) { guard let interruptionType = type else { return } switch UInt(interruptionType) { case AVAudioSession.InterruptionType.began.rawValue: if recording { isRecorderInterrupted = true let _ = stopCapture() } if playing { isPlayerInterrupted = true let _ = stopRendering() } case AVAudioSession.InterruptionType.ended.rawValue: configureAudioSessionWithDesiredAudioRoute(desiredAudioRoute: DefaultAudioDevice.kAudioDeviceBluetooth) restartAudioAfterInterruption() default: break } } @objc func onRouteChangeEvent(notification: Notification) { safetyQueue.async { self.handleRouteChangeEvent(notification: notification) } } @objc func appDidBecomeActive(notification: Notification) { safetyQueue.async { self.handleInterruptionEvent(type: Int(AVAudioSession.InterruptionType.ended.rawValue)) } } fileprivate func handleRouteChangeEvent(notification: Notification) { guard let reason = notification.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt else { return } if reason == AVAudioSession.RouteChangeReason.routeConfigurationChange.rawValue { return } if reason == AVAudioSession.RouteChangeReason.override.rawValue || reason == AVAudioSession.RouteChangeReason.categoryChange.rawValue { let oldRouteDesc = notification.userInfo?[AVAudioSessionRouteChangePreviousRouteKey] as! AVAudioSessionRouteDescription let outputs = oldRouteDesc.outputs var oldOutputDeviceName: String? = nil var currentOutputDeviceName: String? = nil if outputs.count > 0 { let portDesc = outputs[0] oldOutputDeviceName = portDesc.portName } if AVAudioSession.sharedInstance().currentRoute.outputs.count > 0 { currentOutputDeviceName = AVAudioSession.sharedInstance().currentRoute.outputs[0].portName } if oldOutputDeviceName == currentOutputDeviceName || currentOutputDeviceName == nil || oldOutputDeviceName == nil { return } restartAudio() } } fileprivate func setupListenerBlocks() { if areListenerBlocksSetup { return } let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(DefaultAudioDevice.onInterruptionEvent), name: AVAudioSession.interruptionNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(DefaultAudioDevice.onRouteChangeEvent(notification:)), name: AVAudioSession.routeChangeNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(DefaultAudioDevice.appDidBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: nil) areListenerBlocksSetup = true } fileprivate func removeObservers() { NotificationCenter.default.removeObserver(self) areListenerBlocksSetup = false } fileprivate func setupAudioSession() { let session = AVAudioSession.sharedInstance() previousAVAudioSessionCategory = session.category avAudioSessionMode = session.mode avAudioSessionPreffSampleRate = session.preferredSampleRate avAudioSessionChannels = session.inputNumberOfChannels do { try session.setPreferredSampleRate(Double(DefaultAudioDevice.kSampleRate)) try session.setPreferredIOBufferDuration(0.01) let audioOptions = AVAudioSession.CategoryOptions.mixWithOthers.rawValue | AVAudioSession.CategoryOptions.allowBluetooth.rawValue | AVAudioSession.CategoryOptions.defaultToSpeaker.rawValue try session.setCategory(AVAudioSession.Category.playAndRecord, mode: AVAudioSession.Mode.videoChat, options: AVAudioSession.CategoryOptions(rawValue: audioOptions)) setupListenerBlocks() try session.setActive(true) } catch let err as NSError { print("Error setting up audio session \(err)") } catch { print("Error setting up audio session") } } } // MARK: - Audio Route functions extension DefaultAudioDevice { fileprivate func setBluetoothAsPreferredInputDevice() { let btRoutes = [AVAudioSession.Port.bluetoothA2DP, AVAudioSession.Port.bluetoothLE, AVAudioSession.Port.bluetoothHFP] AVAudioSession.sharedInstance().availableInputs?.forEach({ el in if btRoutes.contains(el.portType) { do { try AVAudioSession.sharedInstance().setPreferredInput(el) } catch { print("Error setting BT as preferred input device") } } }) } fileprivate func configureAudioSessionWithDesiredAudioRoute(desiredAudioRoute: String) { let session = AVAudioSession.sharedInstance() if desiredAudioRoute == DefaultAudioDevice.kAudioDeviceBluetooth { setBluetoothAsPreferredInputDevice() } do { if desiredAudioRoute == DefaultAudioDevice.kAudioDeviceSpeaker { try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker) } else { try session.overrideOutputAudioPort(AVAudioSession.PortOverride.none) } } catch let err as NSError { print("Error setting audio route: \(err)") } } } // MARK: - Render and Record C Callbacks func renderCb(inRefCon:UnsafeMutableRawPointer, ioActionFlags:UnsafeMutablePointer<AudioUnitRenderActionFlags>, inTimeStamp:UnsafePointer<AudioTimeStamp>, inBusNumber:UInt32, inNumberFrames:UInt32, ioData:UnsafeMutablePointer<AudioBufferList>?) -> OSStatus { let audioDevice: DefaultAudioDevice = Unmanaged.fromOpaque(inRefCon).takeUnretainedValue() if !audioDevice.playing { return 0 } let _ = audioDevice.deviceAudioBus!.readRenderData((ioData?.pointee.mBuffers.mData)!, numberOfSamples: inNumberFrames) updatePlayoutDelay(withAudioDevice: audioDevice) return noErr } func recordCb(inRefCon:UnsafeMutableRawPointer, ioActionFlags:UnsafeMutablePointer<AudioUnitRenderActionFlags>, inTimeStamp:UnsafePointer<AudioTimeStamp>, inBusNumber:UInt32, inNumberFrames:UInt32, ioData:UnsafeMutablePointer<AudioBufferList>?) -> OSStatus { let audioDevice: DefaultAudioDevice = Unmanaged.fromOpaque(inRefCon).takeUnretainedValue() if audioDevice.bufferList == nil || inNumberFrames > audioDevice.bufferNumFrames { if audioDevice.bufferList != nil { audioDevice.bufferList!.pointee.mBuffers.mData? .assumingMemoryBound(to: UInt16.self).deallocate() audioDevice.bufferList?.deallocate() } audioDevice.bufferList = UnsafeMutablePointer<AudioBufferList>.allocate(capacity: 1) audioDevice.bufferList?.pointee.mNumberBuffers = 1 audioDevice.bufferList?.pointee.mBuffers.mNumberChannels = 1 audioDevice.bufferList?.pointee.mBuffers.mDataByteSize = inNumberFrames * UInt32(MemoryLayout<UInt16>.size) audioDevice.bufferList?.pointee.mBuffers.mData = UnsafeMutableRawPointer(UnsafeMutablePointer<UInt16>.allocate(capacity: Int(inNumberFrames))) audioDevice.bufferNumFrames = inNumberFrames audioDevice.bufferSize = (audioDevice.bufferList?.pointee.mBuffers.mDataByteSize)! } AudioUnitRender(audioDevice.recordingVoiceUnit!, ioActionFlags, inTimeStamp, 1, inNumberFrames, audioDevice.bufferList!) if audioDevice.recording { audioDevice.deviceAudioBus!.writeCaptureData((audioDevice.bufferList?.pointee.mBuffers.mData)!, numberOfSamples: inNumberFrames) } if audioDevice.bufferSize != audioDevice.bufferList?.pointee.mBuffers.mDataByteSize { audioDevice.bufferList?.pointee.mBuffers.mDataByteSize = audioDevice.bufferSize } updateRecordingDelay(withAudioDevice: audioDevice) return noErr } func updatePlayoutDelay(withAudioDevice audioDevice: DefaultAudioDevice) { audioDevice.playoutDelayMeasurementCounter += 1 if audioDevice.playoutDelayMeasurementCounter >= 100 { // Update HW and OS delay every second, unlikely to change audioDevice.playoutDelay = 0 let session = AVAudioSession.sharedInstance() // HW output latency let interval = session.outputLatency audioDevice.playoutDelay += UInt32(interval * DefaultAudioDevice.kToMicroSecond) // HW buffer duration let ioInterval = session.ioBufferDuration audioDevice.playoutDelay += UInt32(ioInterval * DefaultAudioDevice.kToMicroSecond) audioDevice.playoutDelay += UInt32(audioDevice.playoutAudioUnitPropertyLatency * DefaultAudioDevice.kToMicroSecond) // To ms if ( audioDevice.playoutDelay >= 500 ) { audioDevice.playoutDelay = (audioDevice.playoutDelay - 500) / 1000 } audioDevice.playoutDelayMeasurementCounter = 0 } } func updateRecordingDelay(withAudioDevice audioDevice: DefaultAudioDevice) { audioDevice.recordingDelayMeasurementCounter += 1 if audioDevice.recordingDelayMeasurementCounter >= 100 { audioDevice.recordingDelay = 0 let session = AVAudioSession.sharedInstance() let interval = session.inputLatency audioDevice.recordingDelay += UInt32(interval * DefaultAudioDevice.kToMicroSecond) let ioInterval = session.ioBufferDuration audioDevice.recordingDelay += UInt32(ioInterval * DefaultAudioDevice.kToMicroSecond) audioDevice.recordingDelay += UInt32(audioDevice.recordingAudioUnitPropertyLatency * DefaultAudioDevice.kToMicroSecond) audioDevice.recordingDelay = audioDevice.recordingDelay.advanced(by: -500) / 1000 audioDevice.recordingDelayMeasurementCounter = 0 } }
mit
51c67cca48a3890e71f393b48a2b16ee
36.465672
176
0.629551
5.591891
false
false
false
false
Antondomashnev/ADMozaicCollectionViewLayout
ADMozaikCollectionViewLayout/Public/ADMozaikLayout.swift
1
7236
// // ADMozaikLayout.swift // ADMozaikCollectionViewLayout // // Created by Anton Domashnev on 16/05/16. // Copyright © 2016 Anton Domashnev. All rights reserved. // import Foundation /// The `ADMozaikLayout` defines the custom `UICollectionViewFlowLayout` subclass open class ADMozaikLayout: UICollectionViewFlowLayout { /// Delegate for the layout. It's required open weak var delegate: ADMozaikLayoutDelegate! //*******************************// override open var minimumLineSpacing: CGFloat { willSet { fatalError("ADMozaikLayout doesn't support setting minimumLineSpacing directly for layout. Please use ADMozaikLayoutDelegate method to return geometry info") } } override open var minimumInteritemSpacing: CGFloat { willSet { fatalError("ADMozaikLayout doesn't support setting minimumInteritemSpacing directly for layout. Please use ADMozaikLayoutDelegate method to return geometry info") } } //*******************************// /// Layout geometries array for each section fileprivate var layoutGeometries: [ADMozaikLayoutSectionGeometry]? /// Array of `ADMozaikLayoutSectionMatrix` objects that represents layout for each section fileprivate var layoutMatrixes: [ADMozaikLayoutSectionMatrix]? /// Current layout cache to speed up calculations fileprivate var layoutCache: ADMozaikLayoutCache? /// Keeps information about current layout attributes fileprivate var layoutAttrbutes: ADMozaikLayoutAttributes? /// Keeps information about current layout bounds size fileprivate var currentLayoutBounds: CGSize = CGSize.zero //*******************************// /// Designated initializer for `ADMozaikLayout` /// /// - Parameter delegate: delegate/datasource for the layout public init(delegate: ADMozaikLayoutDelegate) { self.delegate = delegate super.init() } /// /// Initializer to create new instance of `ADMozaikLayout` from storyboard or xib /// /// - Parameter coder: encoded information about layout /// /// - Returns: newly created instance of `ADMozaikLayout` required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: - UICollectionViewLayout open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return self.currentLayoutBounds != newBounds.size } open override func invalidateLayout() { super.invalidateLayout() self.resetLayout() } open override func prepare() { guard let collectionView = self.collectionView else { fatalError("self.collectionView expected to be not nil when execute prepareLayout()") } guard self.delegate != nil else { fatalError("self.delegate expected to be not nil when execute prepareLayout()") } super.prepare() if self.isLayoutReady() { return } self.currentLayoutBounds = collectionView.bounds.size self.layoutCache = ADMozaikLayoutCache(collectionView: collectionView, mozaikLayoutDelegate: self.delegate) if self.layoutCache?.numberOfSections() == 0 { return } self.createSectionInformations() guard let layoutCache = self.layoutCache, let layoutMatrixes = self.layoutMatrixes, let layoutGeometries = self.layoutGeometries else { fatalError("layout is not prepared, because of internal setup error") } do { self.layoutAttrbutes = try ADMozaikLayoutAttributes(layoutCache: layoutCache, layoutMatrixes: layoutMatrixes, layoutGeometries: layoutGeometries) } catch let error { fatalError("Internal layout attributes error: \(error)") } } open override var collectionViewContentSize : CGSize { guard let collectionView = self.collectionView else { fatalError("self.collectionView expected to be not nil when execute collectionViewContentSize()") } guard let layoutGeometries = self.layoutGeometries else { return CGSize.zero } let numberOfSections = self.layoutCache!.numberOfSections() if numberOfSections == 0 { return CGSize.zero } let contentSize = super.collectionViewContentSize let delta = collectionView.bounds.height - collectionView.contentInset.top - collectionView.contentInset.bottom let layoutGeometriesContentHeight = layoutGeometries.reduce(0) { result, geometry in return result + geometry.contentHeight } return CGSize(width: contentSize.width, height: max(layoutGeometriesContentHeight, delta)); } open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return self.layoutAttrbutes?.layoutAttributesForItem(at: indexPath) } open override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return nil } open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return self.layoutAttrbutes?.layoutAttributesForElementsInRect(rect) } //MARK: - Helpers fileprivate func isLayoutReady() -> Bool { return self.layoutCache != nil && self.layoutGeometries != nil && self.layoutMatrixes != nil && self.layoutAttrbutes != nil } fileprivate func resetLayout() { self.layoutAttrbutes = nil self.layoutCache = nil self.layoutMatrixes = nil self.layoutGeometries = nil } fileprivate func createSectionInformations() { guard let cache = self.layoutCache, let delegate = self.delegate, let collectionView = self.collectionView else { fatalError("createLayoutGeometries internal parameters don't satisfy requirenments: cache: \(String(describing: self.layoutCache)), delegate: \(String(describing: self.delegate)), collectionView = \(String(describing: self.collectionView)))") } var buildingLayoutGeometries: [ADMozaikLayoutSectionGeometry] = [] var buildingLayoutMatrixes: [ADMozaikLayoutSectionMatrix] = [] for section in 0..<cache.numberOfSections() { let sectionGeometryInfo = delegate.collectonView(collectionView, mozaik: self, geometryInfoFor: section) let sectionGeometry = ADMozaikLayoutSectionGeometry(geometryInfo: sectionGeometryInfo) buildingLayoutGeometries.append(sectionGeometry) let sectionContentMode = delegate.collectonView(collectionView, mozaik: self, contentModeFor: section) let sectionMatrix = ADMozaikLayoutSectionMatrix(numberOfColumns: sectionGeometryInfo.columns.count, section: section, contentMode: sectionContentMode) buildingLayoutMatrixes.append(sectionMatrix) } self.layoutGeometries = buildingLayoutGeometries self.layoutMatrixes = buildingLayoutMatrixes } }
mit
bd8403c0ca7c38b6805696017706604f
41.309942
254
0.682654
5.335546
false
false
false
false
Telll/receiver
TelllClient/MovieCollectionViewCell.swift
3
752
// // MovieCollectionViewCell.swift // TelllClient // // Created by Fernando Oliveira on 28/11/15. // Copyright © 2015 FCO. All rights reserved. // import UIKit class MovieCollectionViewCell: UICollectionViewCell { @IBOutlet weak var image: UIImageView! @IBOutlet weak var title: UILabel! var movie : Movie = Movie(origJson: []) let noimage = UIImage(named: "noimage") func populate(movie : Movie) { title.text = movie.title if let url = movie.image { image.downloadedFrom(url: url, contentMode: .ScaleAspectFit) } } override func prepareForReuse() { super.prepareForReuse() image.image = noimage } }
agpl-3.0
a22cc2f82d384a01d243103529b670fc
25.821429
72
0.599201
4.391813
false
false
false
false
AlvinL33/TownHunt
TownHunt/DevScreenViewController.swift
2
5047
// // DevScreenViewController.swift // TownHunt // // Created by iD Student on 8/2/16. // Copyright © 2016 LeeTech. All rights reserved. // import UIKit import MapKit class DevScreenViewController: UIViewController { @IBOutlet weak var TestLabel: UILabel! @IBOutlet weak var menuOpenNavBarButton: UIBarButtonItem! let filePath = NSHomeDirectory() + "/Documents/" + "MITPack.txt" var values: [NSArray] = [] override func viewDidLoad() { super.viewDidLoad() menuOpenNavBarButton.target = self.revealViewController() menuOpenNavBarButton.action = #selector(SWRevealViewController.revealToggle(_:)) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func deleteFile(_ sender: AnyObject) { let text = "" do{ try text.write(toFile: filePath, atomically: false, encoding: String.Encoding.utf8) }catch{ } } @IBAction func addMITSamplePins(_ sender: AnyObject) { for pin in packPins{ let writeLine = "\(pin.title!),\(pin.hint),\(pin.codeword),\(pin.coordinate.latitude),\(pin.coordinate.longitude),\(pin.pointVal)" writeToFile(writeLine) } } @IBAction func downloadPinsFromServer(_ sender: AnyObject) { let url = URL(string: "http://alvinlee.london/getPins.php") let data = try? Data(contentsOf: url!) do {let object = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) if let dictionary = object as? [String: AnyObject] { readJSONObject(object: dictionary)} }catch{ print("Error reading JSON file") } } func readJSONObject(object: [String: AnyObject]) { guard let downPins = object[""] as? [[String: AnyObject]] else { return } for downPin in downPins { let title = downPin["Title"] as? String let hint = downPin["Hint"] as? String let codeword = downPin["Codeword"] as? String let cLong = downPin["CoordLongitude"] as? String let cLat = downPin["CoordLatitude"] as? String let pointVal = downPin["PointValue"] as? String let writeLine = "\(title!),\(hint!),\(codeword!),\(cLong!),\(cLat)!,\(pointVal!)" print(writeLine) } } func writeToFile(_ content: String) { let contentToAppend = content+"\n" //Check if file exists if let fileHandle = FileHandle(forWritingAtPath: filePath) { //Append to file fileHandle.seekToEndOfFile() fileHandle.write(contentToAppend.data(using: String.Encoding.utf8)!) } else { //Create new file do { try contentToAppend.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8) } catch { print("Error creating \(filePath)") } } } @IBAction func printsWhatsInFile(_ sender: AnyObject) { var stringFromFile: String do{ stringFromFile = try NSString(contentsOfFile: filePath, encoding: String.Encoding.utf8.rawValue) as String let packPinLocArrays = stringFromFile.characters.split(separator: "\n").map(String.init) print(packPinLocArrays) if packPinLocArrays.isEmpty == false{ for pinArray in packPinLocArrays{ print(pinArray) let pinDetails = pinArray.characters.split(separator: ",").map(String.init) } } } catch let error as NSError{ print(error.description) } } @IBAction func gameTimeTo10s(_ sender: Any) { } func deletePack(filePath: String) -> Bool { let fileManager = FileManager.default do { try fileManager.removeItem(atPath: filePath) return true } catch { print("Could not clear temp folder: \(error)") return false } } @IBAction func deleteAllPacksOnPhone(_ sender: Any) { let defaults = UserDefaults.standard var packsOnPhone = defaults.dictionary(forKey: "dictOfPacksOnPhone") for key in Array(packsOnPhone!.keys){ if self.deletePack(filePath: "\(packsOnPhone![key]!)"){ packsOnPhone?.removeValue(forKey: packsOnPhone![key] as! String) } } } /* // 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
51ffa1b30d64ab8942b1a2967c6fa27c
33.8
142
0.597899
4.702703
false
false
false
false
Melon-IT/base-view-controller-swift
MelonBaseViewController/MelonBaseViewController/MBFPageViewController.swift
1
8525
// // MTPPageViewController.m // MelonBaseViewController // // Created by Tomek Popis on 10/5/17. // Copyright (c) 2017 Melon. All rights reserved. // import UIKit open class MBFPageViewController: MBFBaseViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate { public var pageViewController: UIPageViewController? public weak var nextViewController: MBFContentPageViewController? public var currentViewController: MBFContentPageViewController? open func contentViewControllerIdentifierAt(index: Int) -> String { return "" } public var contentRect: CGRect = CGRect.zero public var navigationOrientation: UIPageViewController.NavigationOrientation = .horizontal public var currentPageIndex: Int = 0 public var isContinuousMode: Bool = false var rightDirection: Bool = false var leftDirection: Bool = false var nonDirection: Bool = false open var numberOfPages: Int { return 0 } var nextPageExist: Bool { return self.currentPageIndex + 1 < self.numberOfPages } var previousPageExist: Bool { return self.currentPageIndex - 1 >= 0 } open override var prefersStatusBarHidden: Bool { return true } override open func viewDidLoad() { super.viewDidLoad() self.pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: self.navigationOrientation, options: nil) if let startingViewController = self.storyboard?.instantiateViewController(withIdentifier: self.contentViewControllerIdentifierAt(index: 0)), let container = self.pageViewController { container.dataSource = self; container.delegate = self; for view in container.view.subviews { if view is UIScrollView { (view as! UIScrollView).delegate = self break } } self.currentPageIndex = 0 startingViewController.view.tag = self.currentPageIndex self.currentViewController = startingViewController as? MBFContentPageViewController self.currentViewController?.pageViewController = self; container.setViewControllers([startingViewController], direction: UIPageViewController.NavigationDirection.forward, animated: true, completion: nil) container.view.frame = self.contentRect self.addChild(container) self.view.addSubview(container.view) container.didMove(toParent: self) } } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { var resultViewController: UIViewController? self.currentViewController = viewController as? MBFContentPageViewController self.currentViewController?.pageViewController = self self.currentPageIndex = viewController.view.tag; if self.previousPageExist == true { let index = viewController.view.tag - 1 resultViewController = self.storyboard?.instantiateViewController(withIdentifier: self.contentViewControllerIdentifierAt(index: index)) resultViewController?.view.tag = index } else if self.isContinuousMode == true { let index = self.numberOfPages - 1; resultViewController = self.storyboard?.instantiateViewController(withIdentifier: self.contentViewControllerIdentifierAt(index: index)) resultViewController?.view.tag = index } return resultViewController } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { var resultViewController: UIViewController? self.currentViewController = viewController as? MBFContentPageViewController self.currentViewController?.pageViewController = self self.currentPageIndex = viewController.view.tag if self.nextPageExist == true { let index = viewController.view.tag + 1 resultViewController = self.storyboard?.instantiateViewController(withIdentifier: self.contentViewControllerIdentifierAt(index: index)) resultViewController?.view.tag = index; } else if(self.isContinuousMode == true) { let index = 0 resultViewController = self.storyboard?.instantiateViewController(withIdentifier: self.contentViewControllerIdentifierAt(index: index)) resultViewController?.view.tag = index } return resultViewController } public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { self.nextViewController = pendingViewControllers.last as? MBFContentPageViewController self.nextViewController?.pageViewController = self self.pageWillChange(fromViewController: self.currentViewController!, toViewcontroller: pendingViewControllers.last!) } public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { self.currentPageIndex = self.nextViewController!.view.tag; self.pageDidChange() } public func scrollViewDidScroll(_ scrollView: UIScrollView) { let refference: CGFloat = UIScreen.main.bounds.size.width let xOffset: CGFloat = scrollView.contentOffset.x var scrollDirection: ScrollDirectionType if refference - xOffset > 0.1 { self.rightDirection = true scrollDirection = .right } else if refference - xOffset < -0.1 { self.rightDirection = false scrollDirection = .left } else { if self.rightDirection == true { scrollDirection = .right } else { scrollDirection = .left } } let offsetOut: CGFloat = 1 - (abs(xOffset - refference))/refference let offsetOn: CGFloat = (abs(xOffset - refference))/refference self.currentViewController?.didScrollOutOfScreen(withOffset: offsetOut, andDirection: scrollDirection) self.currentViewController?.didScrollOnScreen(withOffset: offsetOn, andDirection: scrollDirection) } func moveToViewControllerAtIndex(_ index: Int, with direction:UIPageViewController.NavigationDirection) { self.currentPageIndex = index //self.nextPageIndex = index if let startingViewController = self.storyboard?.instantiateViewController(withIdentifier: self.contentViewControllerIdentifierAt(index: index)) { startingViewController.view.tag = self.currentPageIndex self.currentViewController = startingViewController as? MBFContentPageViewController self.currentViewController?.pageViewController = self self.pageViewController?.setViewControllers([startingViewController], direction: direction, animated: true, completion: nil) } } func pageWillChange(fromViewController: UIViewController, toViewcontroller: UIViewController) {} func pageDidChange() {} func setContentViewAt(index:Int) { //self.nextPageIndex = index if let startingViewController = self.storyboard?.instantiateViewController(withIdentifier: self.contentViewControllerIdentifierAt(index: index)) { startingViewController.view.tag = index self.currentViewController = startingViewController as? MBFContentPageViewController self.currentViewController?.pageViewController = self; self.pageViewController?.setViewControllers([startingViewController], direction: .forward, animated: true, completion: nil) } } }
mit
2b25477cb0e1cf2ecf845ef679a84f88
33.236948
195
0.661701
6.29616
false
false
false
false
RLovelett/langserver-swift
Sources/LanguageServerProtocol/Classes/ToolWorkspaceDelegate.swift
1
3680
// // ToolWorkspaceDelegate.swift // langserver-swift // // Created by Ryan Lovelett on 4/16/17. // // import Basic #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import os.log #endif import PackageGraph import Workspace class ToolWorkspaceDelegate: WorkspaceDelegate { func packageGraphWillLoad(currentGraph: PackageGraph, dependencies: AnySequence<ManagedDependency>, missingURLs: Set<String>) { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "ToolWorkspaceDelegate") os_log("The workspace is about to load the complete package graph.", log: log, type: .default) #endif } func fetchingWillBegin(repository: String) { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "ToolWorkspaceDelegate") os_log("The workspace has started fetching %{public}@", log: log, type: .default, repository) #endif } func fetchingDidFinish(repository: String, diagnostic: Diagnostic?) { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "ToolWorkspaceDelegate") os_log("The workspace has finished fetching %{public}@", log: log, type: .default, repository) #endif } func repositoryWillUpdate(_ repository: String) { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "ToolWorkspaceDelegate") os_log("The workspace has started updating %{public}@", log: log, type: .default, repository) #endif } func repositoryDidUpdate(_ repository: String) { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "ToolWorkspaceDelegate") os_log("The workspace has finished updating %{public}@", log: log, type: .default, repository) #endif } func cloning(repository: String) { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "ToolWorkspaceDelegate") os_log("The workspace has started cloning %{public}@", log: log, type: .default, repository) #endif } func checkingOut(repository: String, atReference: String, to path: AbsolutePath) { // FIXME: This is temporary output similar to old one, we will need to figure // out better reporting text. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "ToolWorkspaceDelegate") os_log("The workspace is checking out %{public}@", log: log, type: .default, repository) #endif } func removing(repository: String) { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "ToolWorkspaceDelegate") os_log("The workspace is removing %{public}@ because it is no longer needed.", log: log, type: .default, repository) #endif } func managedDependenciesDidUpdate(_ dependencies: AnySequence<ManagedDependency>) { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "ToolWorkspaceDelegate") os_log("Called when the managed dependencies are updated.", log: log, type: .default) #endif } }
apache-2.0
e64d18f3346e172df776fd75ad268752
43.878049
131
0.638859
3.931624
false
false
false
false
ChrisAU/Locution
Papyrus/Shaders/TileShader.swift
2
697
// // TileShader.swift // Papyrus // // Created by Chris Nevin on 25/02/2016. // Copyright © 2016 CJNevin. All rights reserved. // import UIKit import PapyrusCore struct TileShader : Shader { var fillColor: UIColor? var textColor: UIColor? var strokeColor: UIColor? var strokeWidth: CGFloat? init(tile: Character, points: Int, highlighted: Bool) { // Based on state of tile, render differently. if highlighted { fillColor = Color.Tile.Illuminated } else { fillColor = Color.Tile.Default } textColor = (points == 0 ? .gray : .black) strokeColor = Color.Tile.Border strokeWidth = 0.5 } }
mit
3d5697372de15fb5efb4b647ccea2352
23.857143
59
0.616379
4.023121
false
false
false
false
danielcwj16/ConnectedAlarmApp
Pods/JTAppleCalendar/Sources/UICollectionViewDelegates.swift
2
9965
// // UICollectionViewDelegates.swift // // Copyright (c) 2016-2017 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar) // // 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. // extension JTAppleCalendarView: UICollectionViewDelegate, UICollectionViewDataSource { /// Asks your data source object to provide a /// supplementary view to display in the collection view. public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard let validDate = monthInfoFromSection(indexPath.section), let delegate = calendarDelegate else { developerError(string: "Either date could not be generated or delegate was nil") assert(false, "Date could not be generated for section. This is a bug. Contact the developer") return UICollectionReusableView() } let headerView = delegate.calendar(self, headerViewForDateRange: validDate.range, at: indexPath) headerView.transform.a = semanticContentAttribute == .forceRightToLeft ? -1 : 1 return headerView } /// Asks your data source object for the cell that corresponds /// to the specified item in the collection view. public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let delegate = calendarDelegate else { developerError(string: "Cell was not of type JTAppleCell") return UICollectionViewCell() } restoreSelectionStateForCellAtIndexPath(indexPath) let cellState = cellStateFromIndexPath(indexPath) let configuredCell = delegate.calendar(self, cellForItemAt: cellState.date, cellState: cellState, indexPath: indexPath) configuredCell.transform.a = semanticContentAttribute == .forceRightToLeft ? -1 : 1 return configuredCell } /// Asks your data sourceobject for the number of sections in /// the collection view. The number of sections in collectionView. public func numberOfSections(in collectionView: UICollectionView) -> Int { return monthMap.count } /// Asks your data source object for the number of items in the /// specified section. The number of rows in section. public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if calendarViewLayout.cellCache.isEmpty {return 0} guard let count = calendarViewLayout.cellCache[section]?.count else { developerError(string: "cellCacheSection does not exist.") return 0 } return count } /// Asks the delegate if the specified item should be selected. /// true if the item should be selected or false if it should not. public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { if let delegate = calendarDelegate, let infoOfDateUserSelected = dateOwnerInfoFromPath(indexPath), let cell = collectionView.cellForItem(at: indexPath) as? JTAppleCell, cellWasNotDisabledOrHiddenByTheUser(cell) { let cellState = cellStateFromIndexPath(indexPath, withDateInfo: infoOfDateUserSelected) return delegate.calendar(self, shouldSelectDate: infoOfDateUserSelected.date, cell: cell, cellState: cellState) } return false } func cellWasNotDisabledOrHiddenByTheUser(_ cell: JTAppleCell) -> Bool { return cell.isHidden == false && cell.isUserInteractionEnabled == true } /// Tells the delegate that the item at the specified path was deselected. /// The collection view calls this method when the user successfully /// deselects an item in the collection view. /// It does not call this method when you programmatically deselect items. public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if let delegate = calendarDelegate, let dateInfoDeselectedByUser = dateOwnerInfoFromPath(indexPath) { // Update model deleteCellFromSelectedSetIfSelected(indexPath) let selectedCell = collectionView.cellForItem(at: indexPath) as? JTAppleCell var indexPathsToReload = isRangeSelectionUsed ? Set(validForwardAndBackwordSelectedIndexes(forIndexPath: indexPath)) : [] if selectedCell == nil { indexPathsToReload.insert(indexPath) } // Cell may be nil if user switches month sections // Although the cell may be nil, we still want to // return the cellstate let cellState = cellStateFromIndexPath(indexPath, withDateInfo: dateInfoDeselectedByUser, cell: selectedCell) let deselectedCell = deselectCounterPartCellIndexPath(indexPath, date: dateInfoDeselectedByUser.date, dateOwner: cellState.dateBelongsTo) if let unselectedCounterPartIndexPath = deselectedCell { deleteCellFromSelectedSetIfSelected(unselectedCounterPartIndexPath) indexPathsToReload.insert(unselectedCounterPartIndexPath) let counterPathsToReload = isRangeSelectionUsed ? Set(validForwardAndBackwordSelectedIndexes(forIndexPath: unselectedCounterPartIndexPath)) : [] indexPathsToReload.formUnion(counterPathsToReload) } if indexPathsToReload.count > 0 { self.batchReloadIndexPaths(Array(indexPathsToReload)) } delegate.calendar(self, didDeselectDate: dateInfoDeselectedByUser.date, cell: selectedCell, cellState: cellState) } } /// Asks the delegate if the specified item should be deselected. /// true if the item should be deselected or false if it should not. public func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool { if let delegate = calendarDelegate, let infoOfDateDeSelectedByUser = dateOwnerInfoFromPath(indexPath), let cell = collectionView.cellForItem(at: indexPath) as? JTAppleCell, cellWasNotDisabledOrHiddenByTheUser(cell) { let cellState = cellStateFromIndexPath(indexPath, withDateInfo: infoOfDateDeSelectedByUser) return delegate.calendar(self, shouldDeselectDate: infoOfDateDeSelectedByUser.date, cell: cell, cellState: cellState) } return false } /// Tells the delegate that the item at the specified index /// path was selected. The collection view calls this method when the /// user successfully selects an item in the collection view. /// It does not call this method when you programmatically /// set the selection. public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let delegate = calendarDelegate, let infoOfDateSelectedByUser = dateOwnerInfoFromPath(indexPath) else { return } // Update model addCellToSelectedSetIfUnselected(indexPath, date: infoOfDateSelectedByUser.date) let selectedCell = collectionView.cellForItem(at: indexPath) as? JTAppleCell // If cell has a counterpart cell, then select it as well let cellState = cellStateFromIndexPath(indexPath, withDateInfo: infoOfDateSelectedByUser, cell: selectedCell) // index paths to be reloaded should be index to the left and right of the selected index var pathsToReload = isRangeSelectionUsed ? Set(validForwardAndBackwordSelectedIndexes(forIndexPath: indexPath)) : [] if let selectedCounterPartIndexPath = selectCounterPartCellIndexPathIfExists(indexPath, date: infoOfDateSelectedByUser.date, dateOwner: cellState.dateBelongsTo) { pathsToReload.insert(selectedCounterPartIndexPath) let counterPathsToReload = isRangeSelectionUsed ? Set(validForwardAndBackwordSelectedIndexes(forIndexPath: selectedCounterPartIndexPath)) : [] pathsToReload.formUnion(counterPathsToReload) } if !pathsToReload.isEmpty { self.batchReloadIndexPaths(Array(pathsToReload)) } delegate.calendar(self, didSelectDate: infoOfDateSelectedByUser.date, cell: selectedCell, cellState: cellState) } public func sizeOfDecorationView(indexPath: IndexPath) -> CGRect { guard let size = calendarDelegate?.sizeOfDecorationView(indexPath: indexPath) else { return .zero } return size } }
mit
e2857c3a21d8f53fc22e2fdaeb870f86
56.601156
169
0.698244
5.548441
false
false
false
false
david-mcqueen/Pulser
Heart Rate Monitor - Audio/ViewControllers/CalculatorViewController.swift
1
3165
// // CalculatorViewController.swift // Pulser // // Created by DavidMcQueen on 28/05/2015. // Copyright (c) 2015 David McQueen. All rights reserved. // import Foundation class CalculatorViewController: UITableViewController, UserZonesDelegate { @IBOutlet weak var inputMaxBPM: UITextField! @IBOutlet weak var inputRestBPM: UITextField! @IBOutlet weak var btnCalculate: UIButton! var setUserSettings: UserSettings?; override func viewDidLoad() { super.viewDidLoad() } override func viewWillDisappear(animated: Bool) { } @IBAction func calculatePressed(sender: AnyObject) { let warningTitle = "Guidlines Only!"; let warningMessage = "Pulser provides these heart rate zones for guidance only. By continuing you indicate you accept the disclaimer detailed under the calculator information"; let alert = UIAlertController(title: warningTitle, message: warningMessage, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { action in //Don't do anything, as the user didn't accept. })) alert.addAction(UIAlertAction(title: "Continue", style: .Default, handler: { action in print("Did press OK") //TODO:- Save the user acceptance. Dont want to ask again self.calculateUserZones(); })); self.presentViewController(alert, animated: true, completion: nil) } func calculateUserZones(){ let zones = calculateHeartRateZones( (self.inputMaxBPM.text! as NSString).doubleValue, _restBPM: (self.inputRestBPM.text! as NSString).doubleValue ); setUserSettings?.UserZones = zones; //Finished with calculator, navigate to view the zones let zonesViewController = self.storyboard?.instantiateViewControllerWithIdentifier("EnterZonesViewController") as! EnterZonesViewController zonesViewController.userSettings = self.setUserSettings! zonesViewController.delegate = self; self.navigationController?.pushViewController(zonesViewController, animated: true); } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.row{ case 0: inputMaxBPM.becomeFirstResponder(); case 1: inputRestBPM.becomeFirstResponder(); default: break; } } func didUpdateUserZones(_newSettings: UserSettings) { setUserSettings = _newSettings; //Save the settings to NSUserDefaults saveUserSettings(setUserSettings!); self.navigationController?.popViewControllerAnimated(true); } override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView; header.textLabel!.textColor = redColour; } }
gpl-3.0
173b17b8f5bc43572fb194c07255949a
33.791209
184
0.667615
5.428816
false
false
false
false
mrdepth/EVEOnlineAPI
EVEAPI/EVEAPI/EVE.swift
1
4143
// // EVE.swift // EVEAPI // // Created by Artem Shimanski on 30.04.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import Foundation import Alamofire enum EVEError: Error { case invalidRequest(URLRequest) case internalError case network(error: Error) case objectSerialization(reason: String) case serialization(error: Error) case unauthorized(reason: String) case server(exceptionType: String, reason: String?) case notFound case forbidden case invalidFormat(Any.Type, Any) } extension Dictionary where Key == String { func rowset(name: String) -> [Any]? { guard let item = self["rowset"] else {return nil} let rowset: [String: Any]? if let array = item as? [Any] { rowset = array.first { ($0 as? [String: Any])?["name"] as? String == name } as? [String: Any] } else if let dic = item as? [String: Any], dic["name"] as? String == name { rowset = dic } else { rowset = nil } guard let rows = rowset?["row"] else {return []} if let rows = rows as? [Any] { return rows } else { return [rows] } } } public class EVE: SessionManager { let baseURL = "https://api.eveonline.com/" public init(token: OAuth2Token? = nil, clientID: String? = nil, secretKey: String? = nil, server: ESServer = .tranquility, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy, adapter: OAuth2Helper? = nil, retrier: OAuth2Retrier? = nil) { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders configuration.requestCachePolicy = cachePolicy super.init(configuration: configuration) if let token = token, let clientID = clientID, let secretKey = secretKey { self.adapter = adapter ?? OAuth2EVEAdapter(token: token) self.retrier = retrier ?? OAuth2Retrier(token: token, clientID: clientID, secretKey: secretKey) } } public class func initialize() { loadClassess() } } extension DataRequest { @discardableResult public func validateEVE() -> Self { var statusCode = IndexSet(200..<300) statusCode.insert(403) return validate(statusCode: statusCode).validate() {(request, response, data) -> ValidationResult in if response.statusCode == 403 { guard let data = data, let value = (try? XMLParser.xmlObject(data: data)) as? [String: Any], let error = ((value["eveapi"] as? [String:Any])?["error"] as? [String: Any])?["code"] as? Int, error == 224 else { return .failure(AFError.responseValidationFailed(reason: .unacceptableStatusCode(code: 403)))} return .failure(OAuth2Error.tokenExpired) } else { return .success } } } @discardableResult public func responseEVE<T: JSONCoding>(queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DataResponse<T>) -> Void) -> Self { let serializer = DataResponseSerializer<T> { (request, response, data, error) -> Result<T> in do { guard let data = data, let value = try XMLParser.xmlObject(data: data) as? [String: Any], let result = (value["eveapi"] as? [String: Any])?["result"] else {throw EVEError.objectSerialization(reason: "No XML Data")} return .success(try T(json: result)) } catch { return .failure(error) } } return response( queue: queue, responseSerializer: serializer, completionHandler: completionHandler ) } } public class OAuth2EVEAdapter: OAuth2Helper { override public func adapt(_ urlRequest: URLRequest) throws -> URLRequest { guard let url = urlRequest.url, var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else {throw EVEError.invalidRequest(urlRequest)} var queryItems = components.queryItems ?? [] let accessToken = URLQueryItem(name: "accessToken", value: token.accessToken) if let i = queryItems.index(where: {$0.name == "accessToken"}) { queryItems[i] = accessToken } else { queryItems.append(accessToken) } components.queryItems = queryItems var request = urlRequest request.url = components.url return request } }
mit
772d483b44d8ab42b8ccf2e1d33308a1
28.798561
249
0.689039
3.678508
false
false
false
false
janardhan1212/Virtual-Tourist
Virtual Tourist/MapViewController.swift
1
10447
// // MapViewController.swift // Virtual Tourist // // Created by Denis Ricard on 2016-10-22. // Copyright © 2016 Hexaedre. All rights reserved. // import UIKit import CoreData import MapKit class MapViewController: UIViewController, MKMapViewDelegate { // MARK: - Properties var managedContext: NSManagedObjectContext! let longPressRec = UILongPressGestureRecognizer() var restoringRegion = false var region: MKCoordinateRegion? var pin: Pin? var pins: [Pin] = [] var asyncFetchRequest: NSAsynchronousFetchRequest<Pin>! // MARK: - Outlets @IBOutlet weak var mapView: MKMapView! // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() // Configure the gesture recgnizer for long presses longPressRec.addTarget(self, action: #selector(MapViewController.userLongPressed)) longPressRec.allowableMovement = 25 longPressRec.minimumPressDuration = 1.0 longPressRec.numberOfTouchesRequired = 1 view!.addGestureRecognizer(longPressRec) // set the delegate mapView.delegate = self // Restore the saved state of the map view restoreMapRegion(animated: true) // check CoreData for all available Pins let pinFetch: NSFetchRequest<Pin> = Pin.fetchRequest() do { // execute the fetch request let pins = try managedContext.fetch(pinFetch) // validate that there are pins in Core Data if pins.isEmpty { // no pins in Core Data, display onboarding experience self.displayOnBoarding() return } // display the pins on the map self.pins = pins self.displayPinsOnMap(pins: pins) } catch let error as NSError { print("Fetch error: \(error), \(error.userInfo)") } } override func viewWillDisappear(_ animated: Bool) { // we're going to another view, let's save the current state saveMapRegion() } override func viewWillAppear(_ animated: Bool) { // Here we save the context for the following reason: // If the user pressed a pin and moved to the PhotosViewController // Photos might have been downloaded, deleted, etc. So we save here // to preserve the data when the user returns from that VC do { try managedContext.save() } catch let error as NSError { print("Could not save context \(error), \(error.userInfo)") } } // MARK: - Utilities // This is a utility function for the saveMapRegion method var filePath: String = { let manager = FileManager.default let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first! return url.appendingPathComponent("mapRegionArchive").path }() // MARK: - Map methods func saveMapRegion() { // Place the center and span of the map into a dictonary // Span is the width and the height of the map in degrees // It represents the zoom level of the map let dictionary = [ Const.latitudeKey : mapView.region.center.latitude, Const.longitudeKey: mapView.region.center.longitude, Const.latitudeDeltaKey : mapView.region.span.latitudeDelta, Const.longitudeDeltaKey : mapView.region.span.longitudeDelta ] // Archive the dictionary using filePath computed property NSKeyedArchiver.archiveRootObject(dictionary, toFile: filePath) } func restoreMapRegion(animated: Bool) { // prevent update to save region while we're restoring restoringRegion = true // if we can unarchive a dictionary, we will use it to set the map // back to its previous state (center and span) if let regionDictionary = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? [String:AnyObject] { let longitude = regionDictionary[Const.longitudeKey] as! CLLocationDegrees let latitude = regionDictionary[Const.latitudeKey] as! CLLocationDegrees let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let longitudeDelta = regionDictionary[Const.longitudeDeltaKey] as! CLLocationDegrees let latitudeDelta = regionDictionary[Const.latitudeDeltaKey] as! CLLocationDegrees let span = MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta) let savedRegion = MKCoordinateRegion(center: center, span: span) mapView.setRegion(savedRegion, animated: animated) } restoringRegion = false } // MARK: - Display methods func displayPinsOnMap(pins: [Pin]) { for pin in pins { var locationCoordinate = CLLocationCoordinate2D() locationCoordinate.latitude = pin.lat locationCoordinate.longitude = pin.lon let annotation = MKPointAnnotation() annotation.coordinate = locationCoordinate mapView.addAnnotation(annotation) } } func displayOnBoarding() { // TODO: An improvement would be to implement an onboarding experience } // MARK: - User action methods func userLongPressed(_ sender: AnyObject) { if longPressRec.state == UIGestureRecognizerState.began { // Get location of the longpress in mapView let location = sender.location(in: mapView) // Get the map coordinate from the point pressed on the map let locationCoordinate = mapView.convert(location, toCoordinateFrom: mapView) // create annotation let annotation = MKPointAnnotation() annotation.coordinate = locationCoordinate // now create the pin let pin = Pin(context: managedContext) pin.lat = locationCoordinate.latitude pin.lon = locationCoordinate.longitude // save the context do { try managedContext.save() } catch let error as NSError { print("Unresolved error: \(error), \(error.userInfo)") } // add annotation mapView.addAnnotation(annotation) } } // MARK: - Segue methods override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // pass the selected pin and the managedContext to the PhotosViewController let controller = segue.destination as! PhotosViewController controller.pin = pin controller.managedContext = managedContext controller.focusedRegion = region } func presentPhotosViewController(pin: Pin, coordinate: CLLocationCoordinate2D) { // first get the region to pass to PhotosViewController let center = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude) let lonDelta = mapView.region.span.longitudeDelta let latDelta = mapView.region.span.latitudeDelta / 3 let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta) region = MKCoordinateRegion(center: center, span: span) performSegue(withIdentifier: "PhotosView", sender: self) } // MARK: - MapView Delegates func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView if pinView != nil { pinView!.annotation = annotation } else { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView!.canShowCallout = false pinView!.pinTintColor = UIColor.black pinView!.animatesDrop = true } return pinView } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { // if we're in the process or restoring the map region, do not save // otherwise save the region since it changed if restoringRegion == false { saveMapRegion() } } // User selected a pin, transition to PhotosViewController func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { // first unselect the pin mapView.deselectAnnotation(view.annotation! , animated: true) guard view.annotation != nil else { return } let coordinate = view.annotation!.coordinate // check CoreData for corresponding Pin let pinFetch: NSFetchRequest<Pin> = Pin.fetchRequest() // we'll fetch the results with same latitude and longitude let precision = 0.0001 pinFetch.predicate = NSPredicate(format: "(%K BETWEEN {\(coordinate.latitude - precision), \(coordinate.latitude + precision) }) AND (%K BETWEEN {\(coordinate.longitude - precision), \(coordinate.longitude + precision) })", #keyPath(Pin.lat), #keyPath(Pin.lon)) do { let pins = try managedContext.fetch(pinFetch) if pins.count > 0 { if pins.count > 1 { // more than one possibility, so we refine the search? // TODO: - Resolve possibility of more than one matched pin // For now just use the first one self.pin = pins.first // print data to fine tune precision print("More than one pin returned from fetc: \(pins.count)") // present the photos view controller self.presentPhotosViewController(pin: self.pin!, coordinate: coordinate) } else { // there is only one match, so this is our pin self.pin = pins.first // present the photos view controller self.presentPhotosViewController(pin: self.pin!, coordinate: coordinate) } } else { // there are no pins returned from the fetch, something went wrong print("Could not find a matching pin for this latitude: \(coordinate.latitude) and longitude: \(coordinate.longitude)") } } catch let error as NSError { print("Fetch error: \(error), \(error.userInfo)") } } }
mit
4582f54c22d999fcb9759a28914d997a
34.410169
267
0.632874
5.351434
false
false
false
false
Rochester-Ting/DouyuTVDemo
RRDouyuTV/RRDouyuTV/Classes/Home(首页)/ViewController/RecommandVC.swift
1
7142
// // RecommandVC.swift // RRDouyuTV // // Created by 丁瑞瑞 on 13/10/16. // Copyright © 2016年 Rochester. All rights reserved. // import UIKit private let kItemMargin : CGFloat = 10 private let kItemWidth : CGFloat = (kScreenW - 3 * kItemMargin) / 2 private let kItemHeight : CGFloat = kItemWidth * 3 / 4 private let kItemBeatifulHeight : CGFloat = kItemWidth * 4 / 3 // cell的id private let kRecommandCellId = "recommadCell" private let kRecommandBeatifulCellId = "recommadBeatifulCell" private let kRecommandSectionHeadId = "recommadSectionId" // sectionHead的高度 private let kHeadViewH : CGFloat = 50 class RecommandVC: BaseViewController { var gameView : GameView? lazy var recommandVM : RecommandViewModel = RecommandViewModel() lazy var collectionView : UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemWidth, height: kItemHeight) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.scrollDirection = .vertical layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeadViewH) layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin) let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.contentInset = UIEdgeInsetsMake(kClycleH + kGameViewH, 0, kStatusBarH + kNavigationH + kTitleViewH + kTabBarH, 0) self.collectionView = collectionView; collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self // MARK:- 注册Normal cell collectionView.register(UINib(nibName: "RecommandNormalCell", bundle: nil), forCellWithReuseIdentifier: kRecommandCellId) // MARK:- 注册颜值cell collectionView.register(UINib(nibName: "RecommanBeautifulCell", bundle: nil), forCellWithReuseIdentifier: kRecommandBeatifulCellId) // MARK:- 注册headView collectionView.register(UINib(nibName: "RecommandHeadView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kRecommandSectionHeadId) return collectionView }() override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false // 设置背景颜色 setBackGroundColor() // 添加collectionView setUpUI() // 获取数据 GetNetwork() //添加轮播图 addCycleView() //推荐游戏 addGameView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension RecommandVC{ // MARK:- 设置背景颜色 public func setBackGroundColor(){ view.backgroundColor = UIColor.white } // MARK:- 设置collectionView public override func setUpUI(){ contentView = collectionView view.addSubview(collectionView) super.setUpUI() } } // MARK:- 实现collectionView的数据源方法 extension RecommandVC : UICollectionViewDataSource{ // 返回几组 func numberOfSections(in collectionView: UICollectionView) -> Int { return recommandVM.rGameModelArrs.count } // 返回每组有几个 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let num = recommandVM.rGameModelArrs[section] return num.anchors.count } // 返回cell func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1{ let cell : RecommanBeautifulCell = collectionView.dequeueReusableCell(withReuseIdentifier: kRecommandBeatifulCellId, for: indexPath) as! RecommanBeautifulCell cell.achor = recommandVM.rGameModelArrs[(indexPath as NSIndexPath).section].anchors[(indexPath as NSIndexPath).item] return cell }else{ let cell : RecommandNormalCell = collectionView.dequeueReusableCell(withReuseIdentifier: kRecommandCellId, for: indexPath) as! RecommandNormalCell cell.achor = recommandVM.rGameModelArrs[(indexPath as NSIndexPath).section].anchors[(indexPath as NSIndexPath).item] return cell } } // 返回collectionView的headView func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kRecommandSectionHeadId, for: indexPath) as! RecommandHeadView // headview.backgroundColor = UIColor.green headview.achorGame = recommandVM.rGameModelArrs[indexPath.section]; return headview } } // MARK:- 遵守UICollectionViewDelegateFlowLayout extension RecommandVC : UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemWidth, height: kItemBeatifulHeight) }else{ return CGSize(width: kItemWidth, height: kItemHeight) } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let isVertical = recommandVM.rGameModelArrs[indexPath.section].anchors[indexPath.item].isVertical isVertical == 0 ? pushVC() : presentVC() } func pushVC() { navigationController?.pushViewController(RoomNormalVC(), animated: true) } func presentVC(){ present(RoomBeatifulVC(), animated: true, completion: nil) } } // MARK:- 获取网络数据 extension RecommandVC{ func GetNetwork() { recommandVM.requestHomeData { self.collectionView.reloadData() var gameArrs = self.recommandVM.rGameModelArrs gameArrs.removeFirst() gameArrs.removeFirst() let gameModel : RGameModel = RGameModel() gameModel.icon_name = "home_more_btn" gameModel.tag_name = "更多" gameArrs.append(gameModel) self.gameView?.gameArrs = gameArrs // 去掉动画 self.stopAnimation() } } } // MARK:- 添加无限循环轮播图 extension RecommandVC{ func addCycleView(){ let cycleView = CycleView.cycleView() cycleView.frame = CGRect(x: 0, y: -(kClycleH + kGameViewH), width: kScreenW, height: kClycleH) collectionView.addSubview(cycleView) } } // MARK:- 添加GameView extension RecommandVC{ func addGameView(){ let gameView = GameView.gameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) self.gameView = gameView collectionView.addSubview(gameView) } }
mit
ad362fa58778814b3af2e3cbe0a9a97f
39.424419
193
0.692651
5.020217
false
false
false
false
TelerikAcademy/Mobile-Applications-with-iOS
demos/CustomViewsDemos/CustomViewsDemos/HttpRequester.swift
1
2563
// // HttpData.swift // DependencyInjectionDemos // // Created by Doncho Minkov on 3/24/17. // Copyright © 2017 Doncho Minkov. All rights reserved. // import Foundation enum HttpMethod: String { case get = "GET" case post = "POST" } class HttpRequester : HttpRequesterBase { var delegate: HttpRequesterDelegate? func send(withMethod method: HttpMethod, toUrl urlString: String, withBody body: Any?, andHeaders headers:Dictionary<String, String> = [:]){ let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = method.rawValue if(body != nil) { do { request.httpBody = try JSONSerialization.data(withJSONObject: body!, options: .prettyPrinted) } catch { // TODO: throw error } } headers.forEach() {request.setValue($0.value, forHTTPHeaderField: $0.key)} weak var weakSelf = self let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in if(error != nil){ // TODO: throw error } do { // let obj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) switch(method) { case .get: weakSelf?.delegate?.didCompleteGet(result: data!) case .post: weakSelf?.delegate?.didCompletePost(result: data!) } } catch { // TODO: throw error } } dataTask.resume() } func get(fromUrl urlString: String, withHeaders headers: Dictionary<String, String>?){ let newHeaders = headers ?? [:] self.send(withMethod: .get, toUrl: urlString, withBody: nil, andHeaders: newHeaders) } func post(toUrl urlString: String, withBody body: Any, andHeaders headers: Dictionary<String, String>?){ let newHeaders = headers ?? [:] self.send(withMethod: .post, toUrl: urlString, withBody: body, andHeaders: newHeaders) } func postJson(toUrl urlString: String, withBody body: Any, andHeaders headers: Dictionary<String, String>?){ var headersWithJson = headers ?? [:] headersWithJson["Content-Type"] = "application/json" self.send(withMethod: .post, toUrl: urlString, withBody: body, andHeaders: headersWithJson) } }
mit
6452171c8d69589aa069f17af9d3e19e
31.846154
112
0.566354
4.797753
false
false
false
false
shiguredo/sora-ios-sdk
Sora/Utilities.swift
1
3193
import Foundation import WebRTC /// :nodoc: public enum Utilities { fileprivate static let randomBaseString = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789" fileprivate static let randomBaseChars = randomBaseString.map { c in String(c) } public static func randomString(length: Int = 8) -> String { var chars: [String] = [] chars.reserveCapacity(length) for _ in 0 ..< length { let index = arc4random_uniform(UInt32(Utilities.randomBaseChars.count)) chars.append(randomBaseChars[Int(index)]) } return chars.joined() } public final class Stopwatch { private var timer: Timer! private var seconds: Int private var handler: (String) -> Void public init(handler: @escaping (String) -> Void) { seconds = 0 self.handler = handler timer = Timer(timeInterval: 1, repeats: true) { _ in let text = String(format: "%02d:%02d:%02d", arguments: [self.seconds / (60 * 60), self.seconds / 60, self.seconds % 60]) self.handler(text) self.seconds += 1 } } public func run() { seconds = 0 RunLoop.main.add(timer, forMode: RunLoop.Mode.common) timer.fire() } public func stop() { timer.invalidate() seconds = 0 } } } final class PairTable<T: Equatable, U: Equatable> { var name: String private var pairs: [(T, U)] init(name: String, pairs: [(T, U)]) { self.name = name self.pairs = pairs } func left(other: U) -> T? { let found = pairs.first { pair in other == pair.1 } return found.map { pair in pair.0 } } func right(other: T) -> U? { let found = pairs.first { pair in other == pair.0 } return found.map { pair in pair.1 } } } /// :nodoc: extension PairTable where T == String { func decode(from decoder: Decoder) throws -> U { let container = try decoder.singleValueContainer() let key = try container.decode(String.self) return try right(other: key).unwrap { throw DecodingError.dataCorruptedError(in: container, debugDescription: "\(self.name) cannot decode '\(key)'") } } func encode(_ value: U, to encoder: Encoder) throws { var container = encoder.singleValueContainer() if let key = left(other: value) { try container.encode(key) } else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "\(name) cannot encode \(value)")) } } } /// :nodoc: public extension Optional { func unwrap(ifNone: () throws -> Wrapped) rethrows -> Wrapped { switch self { case let .some(value): return value case .none: return try ifNone() } } }
apache-2.0
c043fa91ddd0b3d07e67d1e094811871
29.701923
135
0.533981
4.541963
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureNotificationPreferences/Sources/NotificationPreferences/NotificationPreferencesData/Clients/NotificationPreferencesClient.swift
1
1556
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import FeatureNotificationPreferencesDomain import NetworkKit public protocol NotificationPreferencesClientAPI { func fetchPreferences() -> AnyPublisher<NotificationInfoResponse, NetworkError> func update(_ preferences: UpdatedPreferences) -> AnyPublisher<Void, NetworkError> } public struct NotificationPreferencesClient: NotificationPreferencesClientAPI { // MARK: - Private Properties private enum Path { static let contactPreferences = ["users", "contact-preferences"] } private let networkAdapter: NetworkAdapterAPI private let requestBuilder: RequestBuilder // MARK: - Setup public init( networkAdapter: NetworkAdapterAPI, requestBuilder: RequestBuilder ) { self.networkAdapter = networkAdapter self.requestBuilder = requestBuilder } public func fetchPreferences() -> AnyPublisher<NotificationInfoResponse, NetworkError> { let request = requestBuilder.get( path: Path.contactPreferences, authenticated: true )! return networkAdapter .perform(request: request) } public func update(_ preferences: UpdatedPreferences) -> AnyPublisher<Void, NetworkError> { let request = requestBuilder.put( path: Path.contactPreferences, body: try? preferences.encode(), authenticated: true )! return networkAdapter.perform(request: request) } }
lgpl-3.0
ba348670be24b6679c5dd6b15278214f
29.490196
95
0.697749
5.738007
false
false
false
false